openapi: 3.1.0 info: title: Anjuman e Saifee Coordination API version: 1.0.0 description: >- API-first contract for the WhatsApp coordination portal, agent tools, admin dashboard, transcript parser, and task workflows. For which account/department role may call each admin route (the role × page matrix and access tiers), see docs/access-control.md — it is the canonical source; per-path prose here summarizes it. servers: - url: /api security: - whatsappPhone: [] - portalSession: [] - adminKey: [] tags: - name: auth - name: conversations - name: departments - name: tasks - name: transcripts - name: users - name: cron - name: email - name: accommodations - name: triage - name: lost-found paths: /lost-found: post: tags: [lost-found] summary: Record a lost or found item report description: >- WhatsApp-agent intake identified by x-whatsapp-from. Reporter identity is enriched from registration data when available. Lost reports automatically enter the escalation pipeline tagged to the Lost and Found department; found reports are recorded only. security: [{ whatsappPhone: [] }] requestBody: required: true content: application/json: schema: type: object required: [report_type, item_name] additionalProperties: false properties: report_type: { type: string, enum: [lost, found] } item_name: { type: string, minLength: 2, maxLength: 160 } description: { type: [string, "null"], maxLength: 2000 } category: { type: [string, "null"], maxLength: 120 } color: { type: [string, "null"], maxLength: 120 } brand: { type: [string, "null"], maxLength: 120 } location: { type: [string, "null"], maxLength: 500 } occurred_at: { type: [string, "null"], format: date-time } reporter_name: { type: [string, "null"], maxLength: 200 } reporter_its: { type: [string, "null"], maxLength: 40 } responses: "201": { description: Report recorded, with escalation status and help-desk guidance. } "400": { $ref: "#/components/responses/BadRequest" } "500": { $ref: "#/components/responses/ServerError" } /admin/lost-found: get: tags: [lost-found, admin] summary: List all lost and found reports description: >- Any portal member. Returns item details, escalation state, resolver info, and reporter name/phone/ITS. security: [{ portalSession: [] }] responses: "200": { description: "{ reports: LostFoundReport[] }." } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [lost-found, admin] summary: Manually add a lost or found item description: >- Any portal member can add items. Source is recorded as 'manual'. security: [{ portalSession: [] }] requestBody: required: true content: application/json: schema: type: object required: [report_type, item_name] properties: report_type: { type: string, enum: [lost, found] } item_name: { type: string, minLength: 2, maxLength: 160 } description: { type: string, maxLength: 2000 } category: { type: string, maxLength: 120 } color: { type: string, maxLength: 120 } brand: { type: string, maxLength: 120 } location: { type: string, maxLength: 500 } reporter_name: { type: string, maxLength: 200 } reporter_its: { type: string, maxLength: 40 } responses: "201": { description: "{ report: { id, report_type, created_at } }." } "400": { description: "Validation error." } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /admin/lost-found/{id}: put: tags: [lost-found, admin] summary: Edit a lost/found item description: Any portal member can edit item details. security: [{ portalSession: [] }] parameters: - name: id in: path required: true schema: { type: string, format: uuid } requestBody: required: true content: application/json: schema: type: object properties: item_name: { type: string, minLength: 2, maxLength: 160 } description: { type: string, maxLength: 2000 } category: { type: string, maxLength: 120 } color: { type: string, maxLength: 120 } brand: { type: string, maxLength: 120 } location: { type: string, maxLength: 500 } reporter_name: { type: string, maxLength: 200 } reporter_its: { type: string, maxLength: 40 } responses: "200": { description: "{ ok: true }." } "400": { description: "Validation error." } "404": { description: "Report not found." } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } delete: tags: [lost-found, admin] summary: Remove a lost/found item description: Any portal member can delete items. security: [{ portalSession: [] }] parameters: - name: id in: path required: true schema: { type: string, format: uuid } responses: "200": { description: "{ ok: true }." } "404": { description: "Report not found." } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /admin/lost-found/{id}/resolve: patch: tags: [lost-found, admin] summary: Mark an item as resolved (found/returned) description: >- Any portal member. Records who closed it (user_id + display_name), when, and optional notes. Shows in the Resolved history tab. security: [{ portalSession: [] }] parameters: - name: id in: path required: true schema: { type: string, format: uuid } requestBody: content: application/json: schema: type: object properties: notes: { type: string, maxLength: 2000 } responses: "200": { description: "{ ok: true }." } "404": { description: "Report not found or already resolved." } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /admin/auth: post: tags: [auth] summary: Log in to the admin portal. description: >- Verifies credentials and sets a `portal_session` httpOnly cookie (HMAC-SHA256-signed, SameSite=Lax, Secure in production, 7-day TTL). Returns `{ user }` in the response body — no token. The cookie is used by all subsequent admin API requests. 401 if credentials are invalid; 403 if the user lacks portal access (i.e. a visitor — any non-visitor user may sign in, with or without a department). The email lookup is case-insensitive. security: [] requestBody: required: true content: application/json: schema: type: object required: [email, password] properties: email: { type: string, format: email } password: { type: string } responses: "200": description: Authenticated user profile. Sets `portal_session` cookie. content: application/json: schema: type: object required: [user] properties: user: { type: object } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /admin/auth/logout: post: tags: [auth] summary: Log out of the admin portal. description: >- Clears the `portal_session` cookie. Public route — no session required. Clients should also clear any locally cached user state (e.g. localStorage admin_user). security: [] responses: "200": description: Session cookie cleared. content: application/json: schema: type: object required: [ok] properties: ok: { type: boolean } /auth/forgot-password: post: tags: [auth, email] summary: Request a password reset email. description: > Emails a reset link to any active user who can sign in to the portal — any non-visitor user (role "committee" or "admin"), including those not yet assigned to a department. Visitors (the public/mumineen) are excluded. The email lookup is case-insensitive. Always returns a generic 200 response so user existence is not leaked. security: [] requestBody: required: true content: application/json: schema: type: object required: [email] properties: email: { type: string, format: email } responses: "200": description: Generic reset response. content: application/json: schema: type: object required: [ok] properties: ok: { type: boolean } /auth/reset-password: post: tags: [auth] summary: Set a password from a reset or welcome setup link. description: > Stores the new password, clears the reset token, and returns a portal session so the caller can be logged in immediately. Accepts any active non-visitor portal user (with or without a department) — this is also the path the welcome "set password" link uses for new members. security: [] requestBody: required: true content: application/json: schema: type: object required: [token, password] properties: token: { type: string } password: { type: string, minLength: 8 } responses: "200": description: Password updated and session created. content: application/json: schema: { $ref: "#/components/schemas/AuthSessionResponse" } "400": { $ref: "#/components/responses/BadRequest" } "500": { $ref: "#/components/responses/ServerError" } /admin/users: get: tags: [users] summary: List portal users. security: [{ portalSession: [] }, { adminKey: [] }] parameters: - name: department_id in: query schema: { type: string, format: uuid } description: Optional department filter; returned users include membership metadata for that department. responses: "200": description: Users. content: application/json: schema: type: array items: { $ref: "#/components/schemas/User" } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [users] summary: Create a portal user. description: >- Any portal user (committee or admin) may create users. Only admin/leadership may create a user holding the Admin/Leadership account role (role=admin or global_role=leadership_admin) — otherwise 403. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/CreateUserRequest" } responses: "201": { description: Created user. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /admin/users/{id}: get: tags: [users] summary: Get one user. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: User detail. } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } put: tags: [users] summary: Update one user. description: >- Any portal user (committee or admin) may edit users. Only admin/leadership may grant, change, or modify the Admin/Leadership account role — a non-admin caller that tries to promote a user to admin/leadership, or to edit a user who already holds it, gets 403. DELETE on this path remains admin/leadership only. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/UpdateUserRequest" } responses: "200": { description: Updated user. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /admin/users/{id}/departments: get: tags: [users, departments] summary: List a user's department memberships. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: Department memberships. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [users, departments] summary: Add a department membership. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/DepartmentMembershipRequest" } responses: "201": description: >- Created membership. When the request set `send_welcome: true`, the body also includes a `welcome_notification` (WelcomeNotification) describing the email/WhatsApp outcome. content: application/json: schema: type: object properties: welcome_notification: { $ref: "#/components/schemas/WelcomeNotification" } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "409": { description: User already in this department. } "500": { $ref: "#/components/responses/ServerError" } /admin/users/{id}/welcome: post: tags: [users] summary: (Re)send the onboarding welcome to an existing user. description: >- Sends the welcome email + `committee_platform_access_created` WhatsApp template with a fresh password-setup link, without touching department memberships. Always (re)sends — it forces past the once-per-user guard, so an admin can re-issue a welcome on request. A department is resolved from the user's memberships when not supplied; the user must belong to at least one department. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: false content: application/json: schema: type: object properties: department_id: { type: string, format: uuid } responses: "200": description: Welcome attempted. content: application/json: schema: type: object properties: welcome_notification: { $ref: "#/components/schemas/WelcomeNotification" } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "404": { description: User not found. } "500": { $ref: "#/components/responses/ServerError" } /admin/users/{id}/departments/{membershipId}: put: tags: [users, departments] summary: Update or deactivate a department membership. description: Supports department role, active status, and per-membership contact_for_issues notification flag. security: [{ portalSession: [] }, { adminKey: [] }] parameters: - { $ref: "#/components/parameters/Id" } - name: membershipId in: path required: true schema: { type: string, format: uuid } responses: "200": { description: Updated membership. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /admin/conversations: get: tags: [conversations] summary: List Lead Inbox conversations with messages and tool calls. description: Returns recent conversations sorted by `last_message_at`; message and tool-call arrays are capped to latest activity and ordered chronologically within each conversation. security: [{ portalSession: [] }, { adminKey: [] }] parameters: - name: phone in: query schema: { type: string } description: Restrict to a single conversation by E.164 phone. - name: limit in: query schema: { type: integer, default: 75, maximum: 200 } - name: scope in: query schema: { type: string, enum: [main, niyaz], default: main } description: >- Inbox split by the number a conversation is on (conversation_sessions.phone_number_id). main = exclude the niyaz RSVP/broadcast number; niyaz = only it. NOTE: this split applies to the Conversations list only. Escalations (pending + resolved) are cross-cutting and are returned regardless of number under scope=main, so a ticket that arrived on the broadcast number is never hidden from the main Escalations tab. scope=niyaz still narrows escalations to the niyaz number. - name: includeResolved in: query schema: { type: string, enum: ["1"] } description: >- When "1", also load resolved escalations (escalation_status=resolved) for the Escalations tab, bounded to the most-recent `resolvedLimit`. Resolved escalations linked to an issue are ALWAYS returned regardless of this flag so issue "View" links resolve. Pending escalations are always returned. - name: resolvedLimit in: query schema: { type: integer, default: 50, maximum: 500 } description: Page size for resolved escalations when includeResolved=1 (used for "load more"). responses: "200": description: >- Conversations with handling mode, messages, and tool calls. Body also includes `resolved_has_more` (boolean) — true when more resolved escalations exist beyond `resolvedLimit` — and `accounts`: an array of WABA numbers (`{ phoneNumberId, label, displayNumber, isPrimary }`) the UI uses to attribute each message to the number it went to/from. Each conversation carries `escalation_status` (none|pending|resolved), the canonical open/resolved lifecycle field; each message carries `phone_number_id` (NULL = primary account) identifying which WABA number it used. "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/conversations/religious-export: get: tags: [conversations] summary: Export religious / Lisan chats as a mobile-readable HTML transcript. description: >- Downloads a self-contained HTML chat transcript (WhatsApp-style bubbles + tool badges) of every conversation where the bot used a religious tool (`answer_religious_questions` or `get_lisan_word_meaning`), optionally bounded by a date range. Admin/leadership only. Contains PII (phone numbers, message bodies) — guarded by admin auth. security: [{ portalSession: [] }, { adminKey: [] }] parameters: - name: from in: query schema: { type: string, format: date } description: Inclusive start date (YYYY-MM-DD). Omit for all-time. - name: to in: query schema: { type: string, format: date } description: Inclusive end date (YYYY-MM-DD). Omit for all-time. responses: "200": description: An HTML file attachment (`Content-Disposition: attachment`). content: text/html: { schema: { type: string } } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/conversations/stream: get: tags: [conversations] summary: Server-Sent Events stream of inbox activity for live updates. description: >- EventSource endpoint. Emits a `changed` event when conversation activity changes so the Lead Inbox refetches without polling. Authenticated via the `portal_session` cookie (sent automatically by the browser). security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: "text/event-stream of ready/changed/ping events." } "401": { $ref: "#/components/responses/Unauthorized" } /admin/conversations/{phoneE164}/profile: get: tags: [conversations] summary: Sender registration profile for the inbox User Profile panel (PII stripped). description: > Internal-only. Returns the sender's roster/registration profile with PII removed (age, phone, email, and ITS are never included) plus their committee department assignments. The full profile (with age) powers the agent's Sender Context. security: [{ adminKey: [] }] parameters: - name: phoneE164 in: path required: true schema: { type: string } responses: "200": description: Profile (null when the sender isn't a registered roster member) and departments. content: application/json: schema: type: object properties: profile: nullable: true type: object description: PublicSenderProfile — registration fields with age and contacts stripped. global_role: { type: string, nullable: true } departments: type: array items: type: object properties: name: { type: string } role: { type: string } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/conversations/{phoneE164}/mode: put: tags: [conversations] summary: Switch a conversation between AI and manual handling. security: [{ portalSession: [] }, { adminKey: [] }] parameters: - name: phoneE164 in: path required: true schema: { type: string } requestBody: required: true content: application/json: schema: type: object required: [mode] properties: mode: { type: string, enum: [ai, manual] } user_id: { type: string, format: uuid, description: Admin making the change. } responses: "200": { description: Updated handling mode. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /admin/conversations/{phoneE164}/messages: post: tags: [conversations] summary: Send a manual WhatsApp reply for a conversation. description: >- Requires the conversation to be in manual handling mode. For an in-app agent chat conversation (latest inbound has raw_payload.channel "in_app") the reply is recorded into the member's chat instead of sent via WhatsApp, and image attachments are rejected (400). security: [{ portalSession: [] }, { adminKey: [] }] parameters: - name: phoneE164 in: path required: true schema: { type: string } requestBody: required: true content: application/json: schema: type: object required: [body] properties: body: { type: string, maxLength: 4096 } responses: "200": { description: Reply sent; returns the WhatsApp message id. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /admin/conversations/{phoneE164}/escalation: put: tags: [conversations] summary: De-escalate or set the escalation status of a conversation. description: Used by the Lead Inbox De-escalate button. security: [{ portalSession: [] }, { adminKey: [] }] parameters: - name: phoneE164 in: path required: true schema: { type: string } requestBody: required: true content: application/json: schema: type: object required: [status] properties: status: { type: string, enum: [resolved, pending, none] } responses: "200": { description: Updated escalation status. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /escalations: post: tags: [conversations] summary: Escalate the caller's conversation to the human support team. description: >- Called by the agent's move_to_escalation tool. Identified by the x-whatsapp-from header. Non-emergency escalations are declined until a minimum number of inbound messages exist (deterministic last-resort gate). Emergencies and the `religious_followup` category bypass that gate (a deen/Waaz question the reflections can't answer is often the first message); the agent then replies with a fixed Waaz-scoped acknowledgment. Escalation ≠ issue: the escalation always notifies the on-call team, but a tracked issue + workspace task is created ONLY when `requires_department_coordination` is true (an actionable problem a department must coordinate to fix — not an individual request/question/hand-off). Issue creation is idempotent per conversation: a re-escalation reuses the conversation's existing open issue (`deduplicated: true`) instead of creating a duplicate. No cross-conversation topical auto-linking (that is suggestion-only / a planned Trigger B). security: [{ whatsappPhone: [] }] requestBody: required: true content: application/json: schema: type: object required: [reason, priority, category] properties: reason: { type: string } title: { type: string, description: "AI-generated issue title" } description: { type: string, description: "AI-generated issue description" } priority: { type: string, enum: [normal, urgent] } category: type: string enum: [emergency, accommodation, transport, registration, schedule, facilities, complaint, religious_followup, other] department: { type: string, description: "Department name to assign the issue to" } requires_department_coordination: { type: boolean, description: "When true, create a tracked issue + task for department coordination. When false/absent, escalation-only (on-call follow-up, no issue)." } source: { type: string, enum: [ai, rule, manual] } responses: "200": description: "Escalated (with new or deduplicated issue), or declined by the last-resort guardrail." content: application/json: schema: type: object properties: status: { type: string, enum: [escalated, declined] } priority: { type: string } category: { type: string } issue_id: { type: string, nullable: true, description: "The created/reused issue id, or null when the escalation created no issue (escalation-only)." } deduplicated: { type: boolean, description: "True if the conversation's existing open issue was reused instead of creating a new one." } message: { type: string } "400": { $ref: "#/components/responses/BadRequest" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /issues: post: tags: [tasks] summary: Log an external issue reported by a visitor (create_issue tool). description: >- Creates an `item_type='issue'`, `origin='external'` task linked to the reporting guest. When a department is supplied, active department members marked `contact_for_issues` receive assignment email and WhatsApp template notifications. Identified by the x-whatsapp-from header. security: [{ whatsappPhone: [] }] requestBody: required: true content: application/json: schema: type: object required: [title] properties: title: { type: string } description: { type: string } priority: { type: string, enum: [low, medium, high] } department: { type: string } responses: "201": { description: Created issue. } "400": { $ref: "#/components/responses/BadRequest" } "500": { $ref: "#/components/responses/ServerError" } /admin/ruling-flags: get: tags: [conversations] summary: Flagged personal religious-ruling (fatwa) questions — awareness only, not escalations. description: >- Counts + recent personal fiqh / halal-haram questions the assistant refused (redirecting to the Aamil Saheb) and quietly flagged via the deterministic ruling guard. NOT escalations — no one is paged. Phone is masked to the last 4 digits. Admin/leadership or a religious monitor. parameters: - in: query name: from required: false schema: { type: string, format: date } description: Floor flags by date (YYYY-MM-DD), e.g. "Since Ashara", to exclude pre-event test flags. security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: "{ total, unreviewed, recent[] } of flagged ruling questions." } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/religious/metrics: get: tags: [conversations] summary: Religious-dashboard metrics (waaz/Lisan tool usage, missing words, ruling flags). description: >- Aggregated counts from tool_audit_logs over a window (?from/?to YYYY-MM-DD, default 30 days): total calls, unique members, waaz questions, Lisan lookups + status split, top words, open missing-word requests, unreviewed ruling flags. Admin/leadership or a religious monitor. security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: "{ summary, top_words[] }." } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/religious/conversations: get: tags: [conversations] summary: Religious chats ACTIVE in the last N hours (by religious tool-call recency). description: >- Threads (newest religious-activity first) for the Waaz Talaqqi Inbox. Membership is scoped by religious tool-CALL recency, NOT message activity, so a chat whose religious tool-call aged past the window no longer appears even if it got a logistics/template message today. A Manual-mode chat with a recent handoff (within the window) is kept. The general Conversations inbox keeps its all-time religious filter as the archive. Religious monitor / admin. parameters: - in: query name: windowHours schema: { type: integer, enum: [24, 48, 168], default: 48 } description: Lookback window for religious tool-call recency. Invalid values fall back to 48. security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: "{ conversations[], window_hours } each conversation with messages, in_window, handling_mode." } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/religious/mode: put: tags: [conversations] summary: Flip a religious chat between AI-handled and Manual (Waaz Talaqqi Chats tab). description: >- Sets conversation_sessions.handling_mode. Gated for religious monitors (the Inbox's /conversations/{phone}/mode is canAccessInbox, which monitors lack). Flipping to Manual takes the member off the AI for all replies (logistics included), same as the Inbox toggle; updates only handling_mode + attribution, never current_intent/state. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: { type: object, required: [phone, mode], properties: { phone: { type: string }, mode: { type: string, enum: [ai, manual] } } } responses: "200": { description: "{ phone_e164, handling_mode, handling_mode_at }." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "404": { description: Conversation not found. } "500": { $ref: "#/components/responses/ServerError" } /admin/religious/word-requests: get: tags: [conversations] summary: Missing-word queue (words asked for that aren't in the dictionary). description: ?status=open|added|dismissed|all (default open), most-asked first. Religious monitor / admin. security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: "{ requests[] }." } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } patch: tags: [conversations] summary: Resolve a missing-word request (mark added / dismissed). security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [id, status] properties: id: { type: string, format: uuid } status: { type: string, enum: [open, added, dismissed] } responses: "200": { description: Updated. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /agent-chat: get: tags: [conversations] summary: Read the caller's own in-app agent chat conversation. description: >- Portal tier (any signed-in portal user). The thread is always the session user's own (keyed on their whatsapp_users.phone_e164 — the client never supplies a phone). Primary-inbox rows only; template notifications and broadcasts are hidden. Oldest first, newest 200. Session-only: the admin key has no phone of its own. security: [{ portalSession: [] }] parameters: - name: after in: query required: false description: ISO timestamp; return only messages at/after it (polling). Client dedupes by id. schema: { type: string, format: date-time } responses: "200": description: The conversation. content: application/json: schema: type: object properties: handling_mode: { type: string, enum: [ai, manual] } messages: type: array items: type: object properties: id: { type: string, format: uuid } direction: { type: string, enum: [inbound, outbound] } from: { type: string, enum: [you, agent, team] } body: { type: string } created_at: { type: string, format: date-time } "400": { description: Bad after cursor, or the account has no phone number. } "401": { $ref: "#/components/responses/Unauthorized" } "403": { description: Not a portal user. } "500": { $ref: "#/components/responses/ServerError" } post: tags: [conversations] summary: Send a message to the AI agent as the caller (in-app agent chat). description: >- Records the message (raw_payload.channel "in_app") and runs the same text pipeline the WhatsApp webhook used: head-count reply, manual-mode pause, registration gate, coalesced agent run. Side effects are real (escalations email the on-call team). The agent's reply is recorded a few seconds later — poll GET ?after=. visitor_mode true handles the message as a visitor (narrows tools/permissions only). security: [{ portalSession: [] }] requestBody: required: true content: application/json: schema: type: object required: [text] properties: text: { type: string, minLength: 1, maxLength: 4096 } visitor_mode: { type: boolean, default: false } responses: "201": { description: "{ sent: true, id } — the inbound message row id." } "400": { description: Empty/too-long message, or the account has no phone number. } "401": { $ref: "#/components/responses/Unauthorized" } "403": { description: Not a portal user. } "500": { $ref: "#/components/responses/ServerError" } /admin/religious/reply: post: tags: [conversations] summary: Send a WhatsApp reply to a member from the religious dashboard. description: >- Free-form text, delivered ONLY inside WhatsApp's 24-hour window (else 422 out_of_window). For an in-app agent chat conversation the reply is recorded into the member's chat (no WhatsApp send, no 24-hour window). State-preserving — updates only last_message_at; never resets the member's conversation intent/state or handling_mode, so an in-progress logistics flow is untouched. Religious monitor / admin. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [phone, text] properties: phone: { type: string } text: { type: string, maxLength: 4096 } responses: "200": { description: "{ sent, whatsapp_message_id }." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "422": { description: Member is outside the 24-hour window (out_of_window true). } "500": { $ref: "#/components/responses/ServerError" } /admin/religious/monitors: get: tags: [conversations, users] summary: List religious monitors. Religious monitor / admin. security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: "{ members[] }." } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [conversations, users] summary: Add a religious monitor (admin/leadership only). security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: { type: object, required: [user_id], properties: { user_id: { type: string, format: uuid } } } responses: "201": { description: Added. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "409": { description: User is already a monitor. } "500": { $ref: "#/components/responses/ServerError" } /admin/religious/monitors/{id}: delete: tags: [conversations, users] summary: Remove a religious monitor (admin/leadership only). security: [{ portalSession: [] }, { adminKey: [] }] parameters: - in: path name: id required: true schema: { type: string, format: uuid } responses: "200": { description: Removed. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/escalation-support: get: tags: [conversations, users] summary: List escalation/support team members with on-call hours. security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: Support members with user info and on-call hours. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [conversations, users] summary: Add an existing user to the support team. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [user_id] properties: user_id: { type: string, format: uuid } responses: "201": { description: Created support member. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "409": { description: User is already on the support team. } "500": { $ref: "#/components/responses/ServerError" } /admin/escalation-support/{id}: delete: tags: [conversations, users] summary: Remove a support team member (cascades their on-call hours). security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: Removed. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } put: tags: [conversations, users] summary: Replace a member's weekly on-call hours (America/Chicago). security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: type: object required: [hours] properties: hours: type: array items: type: object required: [day_of_week, start_time, end_time] properties: day_of_week: { type: integer, minimum: 0, maximum: 6 } start_time: { type: string, example: "09:00" } end_time: { type: string, example: "17:00" } responses: "200": { description: On-call hours replaced. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /knowledge: get: tags: [conversations] summary: List uploaded FAQ/guide documents. security: [{ portalSession: [] }, { adminKey: [] }] parameters: - name: store in: query required: false schema: { type: string, enum: [logistics, religious] } description: Filter by destination store. Omit for all. responses: "200": { description: Documents with status and chunk counts. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [conversations] summary: Upload a CSV/Excel/Word/PDF document and index it. description: Admin/leadership or department PM/HOD. Extracted text is chunked, embedded, and stored for the agent — into site_content (store=logistics, default) or religious_content (store=religious, not department-scoped). security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: multipart/form-data: schema: type: object required: [file] properties: file: { type: string, format: binary } title: { type: string } department_id: { type: string, format: uuid } store: { type: string, enum: [logistics, religious], default: logistics } responses: "201": { description: Indexed document with chunk count. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "422": { description: No extractable text (e.g. scanned PDF). } "500": { $ref: "#/components/responses/ServerError" } /knowledge/{id}: get: tags: [conversations] summary: Get a document's indexed chunk content for review. description: >- Returns the actual chunks embedded for this document (from site_content for logistics uploads, religious_content for religious uploads) so admins can review whether the indexed content is still relevant before deleting/re-uploading. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: "{ id, title, store, status, chunks: [{ section, content }] }." } "401": { $ref: "#/components/responses/Unauthorized" } "404": { description: Document not found. } "500": { $ref: "#/components/responses/ServerError" } delete: tags: [conversations] summary: Delete a document and remove its vectors from its store. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: Deleted. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/lisan-words: get: tags: [conversations] summary: Count, CSV export, or a searchable page of the Lisan ud Dawat dictionary. description: "Default returns { count }. With ?format=csv, streams the dictionary as a re-importable CSV. With ?list=1, returns a paginated, searchable page { rows[], total, page, pageSize } for the admin Dictionary browser (?q=, ?field=word|meaning|all, ?page=, ?pageSize=). DB is the source of truth." security: [{ portalSession: [] }, { adminKey: [] }] parameters: - in: query name: format required: false schema: { type: string, enum: [csv] } description: When "csv", download the full dictionary instead of the count. - in: query name: list required: false schema: { type: string, enum: ["1"] } description: When "1", return a searchable page of rows (with ids) instead of the count. - in: query name: q required: false schema: { type: string } description: Substring search term (used with list=1). - in: query name: field required: false schema: { type: string, enum: [word, meaning, all], default: all } description: Which columns the search term matches (word = transliteration/lisan). - in: query name: page required: false schema: { type: integer, default: 1 } - in: query name: pageSize required: false schema: { type: integer, default: 25, maximum: 100 } responses: "200": { description: "{ count }, a text/csv attachment (format=csv), or { rows[], total, page, pageSize } (list=1)." } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } put: tags: [conversations] summary: Add (or update) ONE Lisan word without re-uploading the whole CSV. description: "Day-to-day path for filling a dictionary gap. Computes the match columns (norm/skeleton/forms) like the bulk import; deduped on the normalized word. If the word already exists and confirm is not set, returns 409 { status: 'exists', existing } WITHOUT writing, so the UI can warn before overwriting. With confirm:true it overwrites in place. Powers get_lisan_word_meaning." security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object properties: transliteration: { type: string } lisan: { type: string } meaning: { type: string } example: { type: string } confirm: { type: boolean, default: false, description: Authorise overwriting an existing entry with the same normalized word. } description: At least one of transliteration or lisan is required. responses: "200": { description: "Existing word updated (confirm:true): { status: 'updated', entry, count }." } "201": { description: "New word added: { status: 'added', entry, count }." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "409": { description: "Word already exists and confirm was not set: { status: 'exists', existing }." } "422": { description: Word has no transliteration or lisan text. } "500": { $ref: "#/components/responses/ServerError" } patch: tags: [conversations] summary: Edit ONE existing Lisan word by id (fix a wrong spelling / meaning). description: "Recomputes all match columns via prepareLisanRow so the edited row stays searchable like an imported one." security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [id] properties: id: { type: integer } transliteration: { type: string } lisan: { type: string } meaning: { type: string } example: { type: string } responses: "200": { description: "{ status: 'updated', entry }." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "422": { description: Word has no transliteration or lisan text. } "500": { $ref: "#/components/responses/ServerError" } delete: tags: [conversations] summary: Delete ONE Lisan word by id (?id=123). security: [{ portalSession: [] }, { adminKey: [] }] parameters: - in: query name: id required: true schema: { type: integer } responses: "200": { description: "{ status: 'deleted', count }." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [conversations] summary: Upload the dictionary CSV (full replace) into the lisan_words exact-lookup table. description: "Columns by header: transliteration/word, lisan, meaning, example. Powers get_lisan_word_meaning." security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: multipart/form-data: schema: type: object required: [file] properties: file: { type: string, format: binary } responses: "201": { description: Imported with word count. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "422": { description: CSV missing data rows or required columns. } "500": { $ref: "#/components/responses/ServerError" } /admin/religious-topics: get: tags: [conversations] summary: List religious content topic blocks (Vaaz Talaqi, Iqtibasaat, Lisan word meanings). security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: Topics with content + entry/chunk counts. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [conversations] summary: Create a new (empty) religious topic block. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [title] properties: title: { type: string } responses: "201": { description: "Created topic { id, slug }." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/religious-topics/{id}: put: tags: [conversations] summary: Save a religious topic block and re-index it into religious_content. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: type: object properties: content: { type: string } updated_by: { type: string } responses: "200": { description: Saved with chunk count. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } delete: tags: [conversations] summary: Delete a religious topic block and its vectors. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: Deleted. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/profile: put: tags: [users] summary: Update the signed-in user's own display name and/or password. description: Changing the password requires the correct current password. Identified by the user id in the body. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [id] properties: id: { type: string, format: uuid } display_name: { type: string } current_password: { type: string } new_password: { type: string, minLength: 8 } responses: "200": { description: Updated profile. } "400": { $ref: "#/components/responses/BadRequest" } "401": { description: Unauthorized or current password incorrect. } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /admin/scrape: post: tags: [conversations] summary: Manually re-scrape and re-embed the official site content. description: Same work as the daily cron, triggered from the Prompt page, gated by the admin key. security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": { description: Scrape stats (pages, chunks embedded/stored). } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /admin/analytics: get: tags: [conversations, tasks] summary: Leadership task and conversation analytics (rolling 30-day window). security: [{ portalSession: [] }, { adminKey: [] }] parameters: - name: department_id in: query schema: { type: string } description: Filter task metrics to one department, or `all`. responses: "200": { description: Task and conversation analytics. } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /users/me: get: tags: [users] summary: Resolve the current WhatsApp caller context. security: [{ whatsappPhone: [] }] responses: "200": description: Caller context. content: application/json: schema: { $ref: "#/components/schemas/CallerContext" } "401": { $ref: "#/components/responses/Unauthorized" } /users/resolve: get: tags: [users] summary: Resolve a transcript alias to a user. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: - name: alias in: query required: true schema: { type: string } responses: "200": { description: Matching user, if any. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /users/bulk-create: post: tags: [users, departments] summary: Bulk-create users detected from a transcript. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/BulkCreateUsersRequest" } responses: "201": { description: Created or updated users and memberships. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /departments: get: tags: [departments] summary: List departments visible to the caller. description: Committee/admin and portal callers see the full directory; other authenticated callers remain scoped to their memberships. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] responses: "200": description: Departments. content: application/json: schema: type: array items: { $ref: "#/components/schemas/Department" } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [departments] summary: Create a department. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [name] properties: name: { type: string } description: { type: [string, "null"] } responses: "201": { description: Created department. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "409": { description: Department already exists. } "500": { $ref: "#/components/responses/ServerError" } /departments/{id}: put: tags: [departments] summary: Update a department. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: type: object properties: description: { type: [string, "null"] } responses: "200": { description: Updated department. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } delete: tags: [departments] summary: Remove an unused department. description: Blocked if the department has members, tasks, or milestones. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: Deleted department. } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "409": { description: Department is still in use. } "500": { $ref: "#/components/responses/ServerError" } /departments/{id}/tasks: get: tags: [departments, tasks] summary: List tasks in one department. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: - { $ref: "#/components/parameters/Id" } - { $ref: "#/components/parameters/StatusFilter" } - { $ref: "#/components/parameters/PriorityFilter" } responses: "200": { description: Tasks. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /departments/{id}/members: get: tags: [departments, tasks] summary: List active department members eligible for ticket assignment. description: Returns PII-minimal assignment fields only. Caller must have access to the department. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": description: Active department members. content: application/json: schema: type: array items: { $ref: "#/components/schemas/DepartmentAssignmentMember" } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /departments/{id}/summary: get: tags: [departments, tasks] summary: Get task counts for one department. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: Department summary. } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /departments/{id}/prompt-config: get: tags: [departments, transcripts] summary: Get transcript parser prompt configuration for a department. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": description: Prompt configuration. content: application/json: schema: { $ref: "#/components/schemas/DepartmentPromptConfig" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } put: tags: [departments, transcripts] summary: Save transcript parser prompt configuration for a department. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: type: object required: [flexible_prompt] properties: flexible_prompt: { type: string, maxLength: 4000 } responses: "200": { description: Saved prompt configuration. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /departments/summary/all: get: tags: [departments, tasks] summary: Get all department summaries and top blockers. security: [{ adminKey: [] }, { whatsappPhone: [] }] parameters: - name: filter in: query schema: { type: string, enum: [all, blocked, overdue, on_track], default: all } responses: "200": description: Department summaries. content: application/json: schema: type: array items: { $ref: "#/components/schemas/DepartmentSummary" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /tasks: get: tags: [tasks] summary: List tasks scoped to the caller. description: Members see assigned tasks only. PM/HOD users see tasks in their active departments. Leadership/admin sees all tasks. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: - { $ref: "#/components/parameters/StatusFilter" } - { $ref: "#/components/parameters/PriorityFilter" } - name: department_id in: query schema: { type: string, format: uuid } - name: assignee_id in: query schema: { type: string, format: uuid } - name: include_archived in: query schema: { type: boolean, default: false } responses: "200": description: Tasks. content: application/json: schema: type: array items: { $ref: "#/components/schemas/Task" } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [tasks] summary: Create a task. description: Creating an issue with a department notifies active department members marked contact_for_issues. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/CreateTaskRequest" } responses: "201": { description: Created task. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /tasks/kanban: get: tags: [tasks] summary: List tasks grouped for the kanban board. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: - { $ref: "#/components/parameters/PriorityFilter" } - name: department_id in: query schema: { type: string, format: uuid } - name: assignee_id in: query schema: { type: string, format: uuid } - name: include_complete in: query schema: { type: boolean, default: false } responses: "200": description: Board grouped by status. content: application/json: schema: { $ref: "#/components/schemas/KanbanBoard" } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /tasks/{id}: get: tags: [tasks] summary: Get one task. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": { description: Task detail. } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } put: tags: [tasks] summary: Update one task. description: Moving an issue to a department notifies active department members marked contact_for_issues. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/UpdateTaskRequest" } responses: "200": { description: Updated task. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /transcripts/upload: post: tags: [transcripts] summary: Upload and parse a WhatsApp or meeting transcript. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] requestBody: required: true content: multipart/form-data: schema: type: object required: [file] properties: file: { type: string, format: binary } department_id: type: string format: uuid description: Backward-compatible single department/primary department. department_ids: type: array items: { type: string, format: uuid } description: Departments to include in parser context. Multipart clients may send this as JSON. transcript_type: { type: string, enum: [whatsapp, meeting] } responses: "201": description: Parsed transcript upload with reviewable create/update proposals. content: application/json: schema: { $ref: "#/components/schemas/ParsedTranscript" } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /transcripts/{id}/events: get: tags: [transcripts] summary: List parsed events for an upload. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] responses: "200": description: Conversation events enriched with review action and existing-match metadata. content: application/json: schema: type: array items: { $ref: "#/components/schemas/ConversationEvent" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /transcripts/{id}/apply: post: tags: [transcripts, tasks] summary: Apply selected parsed events as tasks. security: [{ whatsappPhone: [] }, { portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: type: object properties: event_ids: type: array items: { type: string, format: uuid } selected_events: type: array items: { $ref: "#/components/schemas/ApplyTranscriptEvent" } responses: "200": { description: Apply results. } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /cron/scrape: get: tags: [cron] summary: Run site scrape cron. security: [{ cronSecret: [] }] responses: "200": { description: Scrape result. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [cron] summary: Run site scrape cron. security: [{ cronSecret: [] }] responses: "200": { description: Scrape result. } "401": { $ref: "#/components/responses/Unauthorized" } "500": { $ref: "#/components/responses/ServerError" } /relay-updates: get: tags: [conversations] summary: Public relay-center updates feed (CORS, cached). description: >- Returns all published relay updates newest-first. Served with `Access-Control-Allow-Origin: *` and `Cache-Control: public, s-maxage=60, stale-while-revalidate=300`. No authentication required. security: [] responses: "200": description: Published updates, newest first. content: application/json: schema: type: array items: { $ref: "#/components/schemas/RelayUpdate" } "500": { $ref: "#/components/responses/ServerError" } /admin/relay-updates: get: tags: [conversations] summary: List all relay updates (published and unpublished). security: [{ portalSession: [] }, { adminKey: [] }] responses: "200": description: All relay updates, newest first. content: application/json: schema: type: object required: [updates] properties: updates: type: array items: { $ref: "#/components/schemas/RelayUpdate" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } post: tags: [conversations] summary: Create a relay update and re-index published updates. description: Admin/leadership only. On success, re-indexes all published updates into site_content under `updates://relay`. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/RelayUpdateWriteRequest" } responses: "200": description: Created update. content: application/json: schema: type: object required: [ok] properties: ok: { type: boolean } # Absent (not null) in the unlikely case the insert returns no row. id: { type: string, format: uuid, nullable: true } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /admin/relay-updates/{id}: put: tags: [conversations] summary: Update a relay update and re-index published updates. description: Admin/leadership only. On success, re-indexes all published updates into site_content under `updates://relay`. security: [{ portalSession: [] }, { adminKey: [] }] parameters: [{ $ref: "#/components/parameters/Id" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/RelayUpdateWriteRequest" } responses: "200": description: Updated update. content: application/json: schema: type: object required: [ok, id] properties: ok: { type: boolean } id: { type: string, format: uuid } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /admin/mumineen/registration: post: summary: Committee registration action for a family description: > Unregister a family, or mark the whole family as not attending. Requires a portal caller with Mumineen access (canAccessMumineen). Registration is two-state: `not_started` (pending) and `submitted` (registered). `unregister` resets the family to `not_started`, erases all submitted registration details (accommodation, transport, travel), clears every member's `not_attending` flag, and deletes the family's per-mumin Niyaz RSVP rows. `not_attending` sets the family's status to `submitted`, flags every active roster member `not_attending=true`, and reseeds the family's Niyaz RSVP to attending=false; it is rejected with 409 if the family is already `submitted`. requestBody: required: true content: application/json: schema: type: object required: [hof_its, action] properties: hof_its: type: string description: Head-of-family ITS identifying the family. action: type: string enum: [unregister, not_attending] responses: "200": description: Updated. content: application/json: schema: type: object properties: ok: type: boolean hof_its: type: string status: type: string "400": description: Missing hof_its or invalid action. "401": description: Caller not authenticated. "403": description: Caller lacks Mumineen access. "404": description: Family not found. "409": description: Family already registered (action=not_attending). /admin/mumineen/roster-status: post: summary: Activate or deactivate a family (and all its members) on the roster description: > Flip a whole family's `roster_active` flag on or off. Activating re-adds the family and every member sharing its `hof_its` to the active roster; deactivating removes them (they stop appearing in normal roster reads, searches, and counts). This is the UI counterpart to the bulk roster import's soft-deactivation, so it is gated to the same tier: admin/leadership plus IT (`canImportMumineen`). Looks the family up regardless of its current `roster_active` state (so deactivated families can be found and re-activated). Only `roster_active` is touched — the schema has no family head-linkage columns, and `mumineen.is_head` is independent of roster membership. security: [{ portalSession: [] }, { adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [hof_its, active] properties: hof_its: type: string description: Head-of-family ITS identifying the family. active: type: boolean description: Target roster membership state for the family and all its members. responses: "200": description: Updated. Returns the family's members with their refreshed roster_active. content: application/json: schema: type: object required: [ok, hof_its, active, members] properties: ok: { type: boolean } hof_its: { type: string } active: { type: boolean } members: type: array items: type: object properties: its: { type: string } full_name: { type: string, nullable: true } is_head: { type: boolean } roster_active: { type: boolean } "400": description: Missing/invalid hof_its or active. "401": description: Caller not authenticated. "403": description: Caller lacks roster-management access (canImportMumineen). "404": description: Family not found. /register: get: tags: [registration] summary: Load a family's registration data by ITS number. description: Public. Accepts any family member's ITS number. Returns locked status when already submitted/confirmed, or full roster data when pending. parameters: - in: query name: hof required: true schema: { type: string } description: ITS number of any family member. responses: "200": description: Pending family data or locked status. content: application/json: schema: oneOf: - type: object required: [locked, status] properties: locked: { type: boolean, enum: [true] } status: { type: string, enum: [submitted, confirmed] } - type: object required: [family, members, departments, is_local] properties: family: { type: object } members: { type: array, items: { type: object } } departments: { type: array, items: { type: object } } is_local: { type: boolean } "400": { $ref: "#/components/responses/BadRequest" } "404": { $ref: "#/components/responses/NotFound" } post: tags: [registration] summary: Submit or edit a family registration. description: > Public. First submission sets status to submitted. Subsequent edits require a valid edit_token from /register/otp/verify. Accommodation and transport are required for mehman families EXCEPT when every member is marked not-attending — such a family isn't coming, so those fields are neither required nor stored (any previously entered values are cleared). Local families never provide accommodation/transport. requestBody: required: true content: application/json: schema: type: object required: [hof_its, members] properties: hof_its: { type: string } submitted_by_its: { type: string, nullable: true } edit_token: { type: string, format: uuid, description: Required for editing an already-submitted registration. Obtained from /register/otp/verify. } members: { type: array, items: { type: object } } accommodation: { type: object } transport: { type: object } responses: "200": description: Registration saved. content: application/json: schema: type: object required: [ok, members_updated] properties: ok: { type: boolean } members_updated: { type: integer } edited: { type: boolean } "400": { $ref: "#/components/responses/BadRequest" } "404": { $ref: "#/components/responses/NotFound" } "409": description: Registration already submitted and no valid edit_token provided, or edit_token expired. content: application/json: schema: type: object required: [error, locked] properties: error: { type: string } locked: { type: boolean } "500": { $ref: "#/components/responses/ServerError" } /register/otp: post: tags: [registration] summary: Request an OTP to edit a submitted registration. description: Public. Sends a 6-digit code to the head of family's email (or eldest attending member if HOF is not in the roster). Rate-limited to one request per 2 minutes per family. requestBody: required: true content: application/json: schema: type: object required: [its] properties: its: { type: string, description: ITS number of any family member. } responses: "200": description: OTP sent. content: application/json: schema: type: object required: [masked_email] properties: masked_email: { type: string, description: Partially masked recipient email for display (e.g. mu***@gmail.com). } "400": { $ref: "#/components/responses/BadRequest" } "404": { $ref: "#/components/responses/NotFound" } "422": description: No email found for this family. content: application/json: schema: { $ref: "#/components/schemas/Error" } "429": description: Rate limit exceeded. Try again in 2 minutes. content: application/json: schema: { $ref: "#/components/schemas/Error" } "500": { $ref: "#/components/responses/ServerError" } /register/otp/verify: post: tags: [registration] summary: Verify OTP and obtain an edit token. description: Public. Validates the 6-digit OTP. On success returns an edit_token (valid 30 min) plus prefilled family data for the edit form. requestBody: required: true content: application/json: schema: type: object required: [its, otp] properties: its: { type: string } otp: { type: string, pattern: '^\d{6}$' } responses: "200": description: OTP verified. Edit token issued. content: application/json: schema: type: object required: [edit_token, family, members, departments, is_local] properties: edit_token: { type: string, format: uuid } family: { type: object } members: { type: array, items: { type: object } } departments: { type: array, items: { type: object } } is_local: { type: boolean } "400": { $ref: "#/components/responses/BadRequest" } "401": description: Invalid or expired OTP. content: application/json: schema: { $ref: "#/components/schemas/Error" } "404": { $ref: "#/components/responses/NotFound" } "500": { $ref: "#/components/responses/ServerError" } /api/rsvp/meals: get: tags: [rsvp] summary: Get the caller's family Niyaz RSVP, organised per day description: >- Self-scoped via x-whatsapp-from. Returns the family RSVP grouped per DAY (one row per Gregorian day, today→Ashura — past days filtered out, America/Chicago), each with a single attending count for lunch and for dinner. The day `title` comes from the day-level niyaz_event_config (matching the admin "Niyaz days" view), NOT the per-meal instance title (which differs on dinners due to the hijri night-shift). Phone→family resolution checks mumin_phone_links first, then falls back to the member's own mumineen.whatsapp_e164, so roster-seeded numbers without a registration link still resolve. For genuinely unlinked phones, returns status=unregistered with any existing (future) unregistered_rsvps rows plus a per-day events array (date/dateLabel/title + which meals served) so the agent maps day references to real dates. Used by the get_family_meal_rsvps agent tool. responses: "200": { description: "status=ok: days [{ date, dateLabel, title, hijriDate, lunch, dinner, closed, closedAt, closedLabel }] where lunch/dinner are each { attending, total } or null when that meal isn't served (Pehli Raat/Ashura are dinner-only); dateLabel e.g. 'Mon, Jun 15' has the weekday pre-computed for the agent's read-back; closed=true (with closedAt/closedLabel) means the day's RSVP cutoff has passed and it can no longer be changed. Plus familyMembers [{name, isAdult, isHead, notAttending}]. Or status=unregistered with rsvps + per-day events [{ date, dateLabel, title, lunch:boolean, dinner:boolean, closed, closedAt, closedLabel }] for unlinked phones." } "400": { $ref: "#/components/responses/BadRequest" } post: tags: [rsvp] summary: Update the caller's family Niyaz RSVP description: >- Self-scoped via x-whatsapp-from. Attendance is pre-set from arrival dates; this records changes (mostly "not coming on day X"). Each entry marks the family attending or not for specific dates (or all days), optionally narrowed to one meal; the change cascades to the whole family. An entry applies globally ONLY when all=true is set explicitly — an entry with no dates/titles and no all=true matches nothing and is ignored, so a single-day change can never accidentally overwrite every day. Per-day RSVP cutoff: a day whose niyaz_event_config rsvp_end_at has passed is locked — changes to it are NOT applied (for every source, no bypass) and are returned in a blocked array. Used by set_family_meal_rsvps. requestBody: required: true content: application/json: schema: type: object required: [entries] properties: entries: type: array minItems: 1 maxItems: 60 items: type: object required: [attending] properties: attending: { type: boolean } dates: { type: array, items: { type: string, format: date }, description: "Preferred selector — the day row's `date` copied verbatim from the per-day response. Pair with meal; (date, meal) is exactly one jaman, so no hijri night-shift guessing. Omit (or all=true) for every day." } titles: { type: array, items: { type: string }, description: "Legacy/fallback selector — event titles (e.g. 'Pehli Raat'). Server resolves title (+meal) to a date. Prefer dates+meal copied from the day row. Pair with meal to disambiguate a title shared by a lunch and a dinner." } meal: { type: string, enum: [lunch, dinner] } all: { type: boolean, description: "Set true to apply to every day (required for any global change). An entry with no dates/titles and all!=true targets nothing and is skipped." } total: { type: integer, description: "Bare head count with no adult/kid split (e.g. 'change to 5'). Fills that many attendees head→adults→kids, capped at the registered family size. Preferred over adults/kids when the caller doesn't state a split. For unregistered callers it records the head count (as adults)." } adults: { type: integer, description: "Number of adults attending — use only with an explicit adult/kid split. For registered families, triggers partial attendance (head of family kept first); capped at the family's adult count. For unregistered callers, records head count." } kids: { type: integer, description: "Number of kids attending — use only with an explicit split. For registered families, triggers partial attendance; capped at the family's kid count." } its_number: { type: string, description: "Unregistered callers only — optional ITS for family matching." } responses: "200": { description: "Updated row count + the refreshed per-day days array (same shape as GET, today→Ashura). When the requested counts exceeded the family size, also returns clamped {requestedAdults, requestedKids, requestedTotal, maxAdults, maxKids, maxTotal, message} so the agent tells the user the count was capped and extras must register separately. requestedTotal/maxTotal carry the single-number (head-count) case; adults/kids the split case. When one or more targeted days were past their RSVP cutoff, returns blocked [{date, title, endAt, endLabel}] for the days that were NOT changed so the agent tells the user RSVP has closed for them. (Or status=unregistered_recorded for unlinked phones — upserts into unregistered_rsvps.)" } "400": { $ref: "#/components/responses/BadRequest" } /api/parking/my-passes: get: tags: [rsvp] summary: Get the caller's own family's parking pass(es) description: >- Strictly self-scoped via x-whatsapp-from — resolves the caller's phone to their family (mumin_phone_links, falling back to the member's own whatsapp_e164) and returns ONLY that family's allocated parking passes. No ITS or family identifier is accepted from the request, so a caller can never query another person's pass. Each pass carries lot_name, color, the per-color entry guidance (entry; plus purpose for gold=wheelchair support and green=khidmat-guzaar early access), general_access (southbound Route 83 / Kingery Hwy) and rideshare_dropoff (Wat Buddha Damma Meditation Center). status=ok with passes; status=no_passes when the family has none; status=unregistered when the number isn't linked (the agent then asks if they need a pass and escalates to Transport). The DB has no "collected" flag, so collection status is asked of the user, not returned. Used by the get_family_parking_passes agent tool. responses: "200": { description: "{ status: ok|no_passes|unregistered, head_name, general_access, rideshare_dropoff, passes: [{ lot_name, color, purpose, entry }] }." } "400": { $ref: "#/components/responses/BadRequest" } "500": { description: "Pass lookup failed." } /api/admin/niyaz/instances: get: tags: [admin] summary: List Niyaz events with attendance tallies description: >- Admin/leadership (portal). Returns all events ordered by date, each with per-event attendance tallies (yes/no by adult/kid/family, thaal count, unregistered adults/kids). Thaal count includes both registered and unregistered attendees. Each item also carries the manually-entered thaal_wardi_count (thaals ordered) and actual_count (thaals served), or null. parameters: - name: mode in: query schema: { type: string, enum: [max, min], default: max } description: >- max = arrival-date defaults (all registered assumed attending); min = only whatsapp/admin-confirmed RSVPs. responses: "200": { description: "{ instances: EventTally[] }." } "403": { $ref: "#/components/responses/Forbidden" } post: tags: [admin] summary: Create a Niyaz event description: Admin/leadership (portal). Creates a new event (day + meal + serving type). requestBody: required: true content: application/json: schema: type: object required: [title] properties: title: { type: string } event_date: { type: string, format: date } hijri_date: { type: string } meal: { type: string, enum: [lunch, dinner] } serving_type: { type: string, enum: [thaal, packet] } description: { type: string } thaal_wardi_count: { type: integer, minimum: 0, nullable: true, description: "Thaals ordered (the wardi). Negative/non-numeric → null." } actual_count: { type: integer, minimum: 0, nullable: true, description: "Thaals actually served on the day. Negative/non-numeric → null." } responses: "201": { description: "{ instance: { id } }." } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/niyaz/instances/{id}: patch: tags: [admin] summary: Edit a Niyaz event description: >- Admin/leadership (portal). Partial patch of an event's day / meal / serving type / details and the manually-entered thaal_wardi_count & actual_count — only provided fields are written. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } requestBody: required: true content: application/json: schema: type: object properties: title: { type: string } event_date: { type: string, format: date } hijri_date: { type: string } meal: { type: string, enum: [lunch, dinner] } serving_type: { type: string, enum: [thaal, packet] } description: { type: string } thaal_wardi_count: { type: integer, minimum: 0, nullable: true, description: "Thaals ordered. Negative/non-numeric/empty → null." } actual_count: { type: integer, minimum: 0, nullable: true, description: "Thaals served. Negative/non-numeric/empty → null." } responses: "200": { description: "{ instance: { id, title, event_date, hijri_date, meal, serving_type, description, thaal_wardi_count, actual_count, updated_at } }." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } /api/admin/niyaz/days: get: tags: [admin] summary: List Niyaz days (day-level RSVP config) description: >- Admin (portal). The configured Niyaz days from niyaz_event_config (prefilled 1st–10th Moharram), each with a representative registration instance id for that date (used to preview/send the RSVP broadcast). Ordered by date. responses: "200": { description: "{ days: [{ date, title, lunch_menu, dinner_menu, rsvp_end_time, has_lunch, has_dinner, template_code, instance_id }] }." } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/niyaz/days/{date}: get: tags: [admin] summary: Day-level Niyaz config by date description: Admin (portal). The niyaz_event_config row for a date (null if not configured yet). parameters: - { name: date, in: path, required: true, schema: { type: string, format: date } } responses: "200": { description: "{ date, config }." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } put: tags: [admin] summary: Upsert day-level Niyaz config by date description: Admin/leadership (portal). Partial patch — only provided fields are written. parameters: - { name: date, in: path, required: true, schema: { type: string, format: date } } requestBody: required: true content: application/json: schema: type: object properties: rsvp_event_title: { type: string, nullable: true } lunch_menu: { type: string, nullable: true } dinner_menu: { type: string, nullable: true } rsvp_end_time: { type: string, nullable: true, description: "Legacy free-text label (display fallback)." } rsvp_end_at: { type: string, format: date-time, nullable: true, description: "RSVP cutoff instant. Interactive responses after this are rejected with a 'registration has ended' reply; {{rsvp_end_time}} renders this in Chicago time." } has_lunch: { type: boolean } has_dinner: { type: boolean } template_code: { type: string, nullable: true } confirmation_template_code: { type: string, nullable: true, description: "Template sent back to a family after they respond (e.g. ashara_relay_double_rsvp_confirmation)." } confirmation_variable_bindings: { type: object, nullable: true, description: "Flat token→binding map for the confirmation template." } confirmation_buttons: { type: array, nullable: true, items: { type: object }, description: "Per-recipient button spec for the confirmation template." } responses: "200": { description: "{ date, config }." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/niyaz/instances/{id}/config: get: tags: [admin] summary: Day-level Niyaz event config (by instance) description: >- Admin/leadership (portal). The day-level config (keyed by the instance's event_date) holding the template-facing fields the RSVP broadcast needs: rsvp_event_title, lunch/dinner menus, rsvp_end_time, which meals are offered, and the template to send. The per-meal rsvp_registration_instance rows remain the RSVP/tally source of truth. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ date, config }. config is null if not configured yet." } "403": { $ref: "#/components/responses/Forbidden" } put: tags: [admin] summary: Upsert day-level Niyaz event config description: Admin/leadership (portal). Partial patch — only provided fields are written. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } requestBody: required: true content: application/json: schema: type: object properties: rsvp_event_title: { type: string, nullable: true } lunch_menu: { type: string, nullable: true } dinner_menu: { type: string, nullable: true } rsvp_end_time: { type: string, nullable: true } has_lunch: { type: boolean } has_dinner: { type: boolean } template_code: { type: string, nullable: true } responses: "200": { description: "{ date, config }." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/niyaz/instances/{id}/responses: get: tags: [admin] summary: Recorded Niyaz RSVP responses for an event description: >- Admin/leadership (portal). Returns the event's instance meta (title, event_date, hijri_date, meal, serving_type, thaal_wardi_count, actual_count), a mode-aware Yes/No `tally`, a mode-independent `breakdown` of the eligible-to-RSVP population grouped into local/mehman/guest (per-group eligible + confirmation-based Yes/No with adults/kids + responded/not-responded + response rate, from the `niyaz_event_breakdown` DB aggregate; guests are sentinel-ITS yes-only and excluded from the member total), the per-mumin niyaz_rsvp rows (name, attending, source, `is_adult`, `local_mehman`), unregistered RSVPs, and family head-counts. Both `tally` and `breakdown` are sourced from DB aggregates (the same numbers as the days overview), NOT by counting the returned rows, so they are correct even when the event has more than 1000 responses. The `responses` and `unregistered` lists are paged server-side (fetchAllRows) to return the full event past PostgREST's 1000-row db-max-rows cap, sorted most-recent first. `crossMeal` lists the mumineen attending THIS meal but NOT the day's other meal (e.g. yes-lunch/no-dinner), from the `niyaz_event_cross_meal` RPC (paged; mode-aware via the same Min/Max confirmed-only rule); it is `null` when the day has no sibling meal. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } - { name: mode, in: query, schema: { type: string, enum: [min, max], default: min }, description: "min = whatsapp/admin-confirmed only; max = includes arrival-date defaults. Drives the tally, breakdown, and crossMeal." } responses: "200": { description: "JSON { instance, tally: { mode, yes, no, ... }, breakdown: { local, mehman, guest, total }, responses, unregistered, headcounts, crossMeal: { otherMeal, members: [{ mumin_id, its, full_name, is_adult, local_mehman, hof_its, whatsapp }] } | null }." } "404": { description: Niyaz event not found. } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/niyaz/instances/{id}/families: get: tags: [admin] summary: Per-family RSVP grid for an event (the admin "By Family" view) description: >- Admin/leadership (portal). One row per roster-active family from the `niyaz_event_family_grid` DB aggregate: `family_id`, `hof_its`, `hof_name` (the family's acting head — the `is_head` member, else the eldest member, matching the mumin-lookup "Acting head"; falls back to the ITS string only if no roster member exists), `responded` (any whatsapp/admin row for the family this event), `attending` (attending real members, guests excluded), `guests` (attending sentinel-ITS placeholders), and `responded_at` / `responded_by` from the latest confirmed row. Derived from niyaz_rsvp (not the often-empty niyaz_family_headcount). PAGED server-side (fetchAllRows), so all ~1k families are returned past PostgREST's 1000-row db-max-rows cap. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "JSON { families: [{ family_id, hof_its, hof_name, responded, attending, guests, responded_at, responded_by }] }." } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /api/admin/niyaz/instances/{id}/individuals: get: tags: [admin] summary: Per-member RSVP grid for an event (the admin "By Individual" view) description: >- Admin/leadership (portal). One row per eligible-to-RSVP member from the `niyaz_event_individual_grid` DB aggregate — the per-person parallel of the By Family grid. Eligible population is identical to `niyaz_event_breakdown` (roster-active, not_attending=false, active family, local OR submitted-mehman), LEFT-joined to niyaz_rsvp so members who never replied still appear with `responded=false` and null rsvp fields ("No response"). Each row: `mumin_id`, `its`, `full_name`, `is_adult`, `local_mehman`, `hof_its`, `whatsapp` (own whatsapp_e164 else primary mumin_phone_links, for the CSV export), `attending`, `source`, `responded_by`, `updated_at`, `responded`. So the "No response" count ties out to the Breakdown panel's "Not responded" total. PAGED server-side (fetchAllRows, stable order by mumin_id) past PostgREST's 1000-row db-max-rows cap. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "JSON { individuals: [{ mumin_id, its, full_name, is_adult, local_mehman, hof_its, whatsapp, attending, source, responded_by, updated_at, responded }] }." } "403": { $ref: "#/components/responses/Forbidden" } "500": { $ref: "#/components/responses/ServerError" } /api/admin/niyaz/instances/{id}/broadcast: get: tags: [admin] summary: Preview (or export) the audience for a Niyaz RSVP send description: >- Admin (portal). Returns the recipient count, any unresolved ITS, and a sample list (name / ITS / masked phone, first 100) for the chosen audience/level/filter so the composer can preview who will receive the broadcast. With `format=csv` it instead streams the FULL resolved audience (every matched recipient, UNMASKED phone numbers) as a CSV download — that branch is gated to admin/leadership. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } - { name: audience, in: query, required: true, schema: { type: string, enum: [specific_its, all_mumineen, all_hof, all_adults, all_adults_hof] }, description: "all_adults_hof = all adults of one family; pass its=. only_non_responders is family-level. all_adults & all_hof apply a conditional registration filter: locals are included regardless of registration, mehman only when their family registration is submitted (both attending) — this ignores require_registered." } - { name: level, in: query, schema: { type: string, enum: [ind, fam] } } - { name: only_non_responders, in: query, schema: { type: boolean } } - { name: require_registered, in: query, schema: { type: boolean, default: true }, description: "Governs all_mumineen only: false drops the submitted-registration filter, targeting every roster-active, not-attending=false family. all_adults/all_hof ignore this and use the local-vs-mehman rule instead." } - { name: its, in: query, schema: { type: string }, description: Comma/space-separated ITS for the test audience. } - { name: format, in: query, schema: { type: string, enum: [csv] }, description: "csv = download the full resolved audience (Name, ITS, HOF ITS, Jamaat, City, Gender, Local/Mehman, WhatsApp) instead of the masked JSON preview. Admin/leadership only." } responses: "200": { description: "JSON { count, unresolved_its, sample: [{ name, its, phone_masked }] }, or a text/csv attachment when format=csv." } "403": { $ref: "#/components/responses/Forbidden" } post: tags: [admin] summary: Send a Niyaz RSVP template (quick-reply or custom Flow/quick-reply buttons) description: >- Admin/leadership (portal). Sends an approved template to the chosen audience for the event's date via the broadcast queue. Body variables auto-bind to person fields, family_members, or the day's event-config values (rsvp_event_title / lunch_menu / dinner_menu / rsvp_end_time). When `buttons` is supplied (ashara_relay_double_rsvp), each button's payload templates are resolved per recipient — {{hof_its}}, {{RegistrationInstanceId}} (the day's numeric niyaz_event_config.day_id), {{EligibleFamilyCount}} — replacing the legacy niyaz|level|scope|date quick-reply buttons. Single-meal days (ashara_relay_single_rsvp) use a Flow that returns one `attending_count` (prefilled from {{EligibleFamilyCount}}); the webhook maps it to whichever meal the day serves (has_lunch/has_dinner). hof_its + day_id are decoded from the flow_token (rsvp::) so it works even if the Flow body omits them. For audience=csv_upload, pass `csv` (raw CSV text in the audience-export format); audience resolution is skipped and each row is matched back to the roster by its WhatsApp number so recipients carry the same computed fields (family_id, mumin_id, hof_its, eligible_family_count) a resolved audience would — so the per-recipient buttons still personalize. CSV upload is POST-only (the file isn't a query param), so the GET preview/export does not accept it. Phase 1: inbound Flow/button responses are captured raw by the webhook; decoding into RSVPs is phase 2. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } requestBody: required: true content: application/json: schema: type: object required: [audience, level, template_code] properties: audience: { type: string, enum: [specific_its, all_mumineen, all_hof, all_adults, all_adults_hof, csv_upload], description: "all_adults & all_hof apply a conditional registration filter: locals included regardless of registration, mehman only when family registration is submitted (both attending)." } csv: { type: string, description: "Raw CSV text in the audience-export format (audience=csv_upload). A WhatsApp column is required; Name/ITS/HOF ITS/etc. personalize." } its: { type: array, items: { type: string }, description: "ITS list for specific_its; the single HOF ITS for all_adults_hof." } only_non_responders: { type: boolean, description: "Family-level: excludes a family once any member has a whatsapp/admin RSVP for the day." } require_registered: { type: boolean, default: true, description: "Governs all_mumineen only: false targets every roster-active, not-attending=false family. all_adults/all_hof use the local-vs-mehman rule instead." } level: { type: string, enum: [ind, fam] } template_code: { type: string } mode: { type: string, enum: [buttons, headcount], description: "buttons = quick-reply RSVP; headcount = free-text family head count (logs a prompt for the numeric reply). Ignored when `buttons` is supplied." } registration_message: { type: string, description: "Head-count mode: {{registration_message}} (auto-generated if omitted)." } example_response: { type: string, description: "Head-count mode: {{example_response}} (default 4)." } buttons: type: array description: "Custom per-recipient button payloads (Flow + quick-reply). Replaces the legacy niyaz buttons." items: oneOf: - type: object required: [type, index, flow_token] properties: type: { type: string, enum: [flow] } index: { type: integer } flow_token: { type: string, description: "Templated, e.g. rsvp:{{Person.Id}}:{{RegistrationInstanceId}}." } flow_action_data: { type: object, additionalProperties: { type: string }, description: "Templated values; integer-looking values are coerced to numbers." } - type: object required: [type, index, payload] properties: type: { type: string, enum: [quick_reply] } index: { type: integer } payload: { type: string, description: "Templated, e.g. rsvp:{{hof_its}}:{{RegistrationInstanceId}}:not-attending." } variable_bindings: type: object description: "Explicit per-variable bindings (override the auto-bound defaults). Each body token (and optional header) binds to a static value or a per-recipient roster field." properties: body: type: object additionalProperties: oneOf: - { type: object, required: [kind, value], properties: { kind: { type: string, enum: [static] }, value: { type: string } } } - { type: object, required: [kind, field], properties: { kind: { type: string, enum: [field] }, field: { type: string } } } header: oneOf: - { type: object, required: [kind, value], properties: { kind: { type: string, enum: [static] }, value: { type: string } } } - { type: object, required: [kind, field], properties: { kind: { type: string, enum: [field] }, field: { type: string } } } responses: "200": { description: "{ status: started, broadcastId, total, … }." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } /api/feedback-survey/{token}: get: tags: [feedback] summary: Load a targeted survey for a recipient token (public) description: >- Token-scoped, no auth. The opaque per-recipient token maps to exactly one (mumin, form). Returns the form's sections/questions snapshot + the responder's FIRST NAME only (shown as "Submitting as — is this you?"). Marks the recipient 'opened'. 404 for an unknown token. parameters: - { name: token, in: path, required: true, schema: { type: string } } responses: "200": { description: "{ status: ok|closed, firstName, formTitle, alreadyCompleted, sections: [{ section_id, title, questions: [{ form_question_id, question_id, area, snapshot }] }] }." } "404": { description: "Unknown token (status=not_found)." } post: tags: [feedback] summary: Submit a targeted survey response (public) description: >- Token-scoped, no auth. Records answers (one row per question), each scored 1-5 (`sentiment_1_5`) and routed to the area's department; negative answers carry a `reason`. Idempotent — re-submitting replaces this recipient's prior answers and marks them 'completed'. parameters: - { name: token, in: path, required: true, schema: { type: string } } requestBody: required: true content: application/json: schema: type: object required: [answers] properties: answers: type: array minItems: 1 maxItems: 200 items: type: object required: [question_id, value] properties: question_id: { type: string, format: uuid } value: { type: string, nullable: true } reason: { type: string, nullable: true } responses: "200": { description: "{ status: ok, recorded: }." } "400": { description: "Invalid body or invalid/expired token." } "404": { description: "Malformed token." } /api/quiz/{token}: get: tags: [quiz] summary: Load the Ashara knowledge quiz (public) description: >- Public, no auth. `{token}` is EITHER the quiz's shared share_token (the link everyone gets) OR a per-recipient test-link token. Returns the bilingual quiz (English + Lisan ud Dawat). For the shared link the response sets `requires_identity: true` (the page then collects ITS + name) and the quiz must be open. A completed test-link recipient gets their saved score. 404 for an unknown/closed token. parameters: - { name: token, in: path, required: true, schema: { type: string } } responses: "200": { description: "{ status: ok, title_en, title_ld, first_name, questions: [...], requires_identity? } | { status: completed, first_name, score, total }." } "404": { description: "Unknown/closed token (status=not_found)." } post: tags: [quiz] summary: Submit + grade a quiz attempt (public) description: >- Public, no auth. Two body shapes: (1) shared-link self-identified — includes its_number (8 digits) + name + timing; one attempt per (quiz, ITS), idempotent. (2) test-link — answers only. Grading is server-side against correctIndex; the stored score is authoritative. ITS is PII — stored, never logged. parameters: - { name: token, in: path, required: true, schema: { type: string } } requestBody: required: true content: application/json: schema: oneOf: - type: object required: [its_number, name, duration_seconds, time_taken_seconds, answers] properties: its_number: { type: string, pattern: '^\d{8}$' } name: { type: string, minLength: 1, maxLength: 80 } duration_seconds: { type: integer, minimum: 0, maximum: 36000 } time_taken_seconds: { type: integer, minimum: 0, maximum: 86400 } answers: { $ref: "#/components/schemas/QuizAnswers" } - type: object required: [answers] properties: answers: { $ref: "#/components/schemas/QuizAnswers" } responses: "200": { description: "{ status: completed, score, total, answers: [{ question_id, chosen_index, correct_index, is_correct }] }." } "400": { description: "Invalid body, bad ITS, closed quiz, or invalid token." } "404": { description: "Malformed token." } /api/admin/quiz/results: get: tags: [admin] summary: Quiz leaderboard + summary (admin-only) description: >- Religious-monitor/admin only (requirePortalCaller · canMonitorReligiousChats). Completed, non-test attempts ranked by score, then fastest time, then earliest finish. ITS is included for admin display only. Participants never see this. responses: "200": { description: "{ rows: [{ name, its_number, score, total, time_taken_seconds, completed_at }], summary: { sent, completed, avg_score, total } }." } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/quiz/share: get: tags: [admin] summary: Shared quiz link + open state (admin-only) description: Religious-monitor/admin only. Returns the shared public link and whether the quiz is open. responses: "200": { description: "{ status: ok, share_token, is_open, link }." } "403": { $ref: "#/components/responses/Forbidden" } post: tags: [admin] summary: Open or close the quiz (admin-only) description: Religious-monitor/admin only. Sets is_open; closing makes the shared link stop accepting attempts. requestBody: required: true content: application/json: schema: { type: object, required: [is_open], properties: { is_open: { type: boolean } } } responses: "200": { description: "{ status: ok, share_token, is_open, link }." } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/quiz/test-link: post: tags: [admin] summary: Mint a quiz test link (admin-only) description: >- Religious-monitor/admin only. Creates an is_test recipient (excluded from the leaderboard) and returns a link to preview the live quiz end-to-end. requestBody: required: false content: application/json: schema: { type: object, properties: { display_name: { type: string } } } responses: "200": { description: "{ status: ok, token, link }." } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/surveys/databank: get: tags: [admin] summary: Survey databank (sections + questions) and target groups description: Admin/leadership only (requirePortalCaller · isAdminOrLeadership). Powers the survey console. responses: "200": { description: "{ sections: [{ ..., questions: [...] }], groups: [...] }." } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/surveys/sections: post: tags: [admin] summary: Add a databank section description: >- Admin/leadership only. Body { title, area (one of the 7 feedback areas), description?, is_general? }. The slug `key` is derived from the title (made unique automatically). New sections sort to the end of the databank. responses: "201": { description: "{ section } (with empty questions)." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/surveys/sections/{id}: patch: tags: [admin] summary: Edit a databank section (name / area / general flag) description: Admin/leadership only. Updates any of { title, area, description, is_general }. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ section }." } "400": { $ref: "#/components/responses/BadRequest" } "404": { description: "Section not found." } delete: tags: [admin] summary: Delete a databank section (soft-delete, cascades to its questions) description: >- Admin/leadership only. Sets active=false on the section and all its questions — they leave the databank and compose picker. Already-composed forms keep working off their snapshots. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ ok: true }." } "404": { description: "Section not found." } /api/admin/surveys/questions: post: tags: [admin] summary: Add a question to a section (databank grows during the event) description: >- Admin/leadership only. Body { section_id, text, type, options?, negative_values?, polarity?, is_general?, collect_comment?, comment_threshold?, required?, scored? }. `scored:false` marks an informational/cross-tab question (no 1–5 sentiment). `collect_comment` toggles the "why?" box; `comment_threshold` (scale questions) is the rating ≤ which an answer opens it; `required` makes the question mandatory on the public form (client + server enforced). responses: "201": { description: "Created question." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/surveys/questions/reorder: post: tags: [admin] summary: Reorder questions within a section description: >- Admin/leadership only. Body { section_id, ordered_ids: [...] } rewrites each question's sort_order to its position in the list. All ids must be active questions in that section. Order is cosmetic (databank + compose listing); it never touches composed-form snapshots. responses: "200": { description: "{ ok: true }." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/surveys/questions/{id}: patch: tags: [admin] summary: Edit a databank question description: >- Admin/leadership only. Updates any of { text, type, options, negative_values, polarity, is_general, collect_comment, comment_threshold, required, scored }. Edits affect FUTURE forms only — existing forms snapshot the question, so already-sent surveys are unchanged. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ question }." } "400": { $ref: "#/components/responses/BadRequest" } "404": { description: "Question not found." } delete: tags: [admin] summary: Retire a databank question (soft-delete) description: >- Admin/leadership only. Sets active=false — the question leaves the databank and compose picker, but existing forms (which snapshot question text) and past answers/exposures stay. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ status: retired }." } "404": { description: "Question not found." } /api/admin/surveys/groups: get: tags: [admin] summary: List target groups responses: "200": { description: "{ groups: [...] }." } "403": { $ref: "#/components/responses/Forbidden" } post: tags: [admin] summary: Create a target group from an audience RuleGroup description: Admin/leadership only. Body { name, description?, rules (RuleGroup), area_focus? }. Validates rules; returns a live reachable count. responses: "201": { description: "{ group, reachable }." } "400": { $ref: "#/components/responses/BadRequest" } "409": { description: "Duplicate group name." } /api/admin/surveys/forms: get: tags: [admin] summary: List forms with recipient/response counts responses: "200": { description: "{ forms: [{ id, title, group_name, status, recipient_count, completed_count, ... }] }." } "403": { $ref: "#/components/responses/Forbidden" } post: tags: [admin] summary: Create a form and compose its questions description: >- Admin/leadership only. Body { title, tags?, sample_size?, public_title?, census?, template_phrase?, question_ids[] } plus EXACTLY ONE target: `group_id` (a saved survey_group) OR `rules` (an inline audience-filter RuleGroup, supporting mixed AND/OR and NOT groups for exclusions like "attending AND NOT rahat") OR `sample_plan` (stratified). `census:true` (pair with `rules`, e.g. everyone) sends to the whole eligible audience with no sampling. `tags` are free-form labels to tell same-titled forms apart. Snapshots each question for stability; the custom filter is validated against the field catalog before saving. responses: "201": { description: "{ form_id, question_count }." } "400": { $ref: "#/components/responses/BadRequest" } /api/admin/surveys/forms/{id}/preview: post: tags: [admin] summary: Dry-run the sample (no writes) description: >- Admin/leadership only. Body { freeWindowOnly?, excludeAlreadySent? }. Returns the sampling funnel (candidates/excludedUnregistered/excludedToday/excludedExhausted/excludedNonResponder/ excludedAlreadySent/fresh/reused/chosen) + first-name preview. Candidates are always registration-submitted households; excludeAlreadySent drops anyone already sent any survey this event (cross-form de-overlap). parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ funnel, sample_names }." } "404": { description: "Form not found." } /api/admin/surveys/forms/{id}/send: post: tags: [admin] summary: Commit the sample and (optionally) dispatch the WhatsApp template description: >- Admin/leadership only. Body { template?, freeWindowOnly?, excludeAlreadySent? }. Creates per-recipient tokens + writes (mumin, question) exposures (once-per-event). Dispatches via WhatsApp when a template is selected (or SURVEY_SEND_ENABLED + SURVEY_WA_TEMPLATE are set); otherwise returns the per-recipient links for manual sending. excludeAlreadySent drops anyone already sent any survey this event. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ formId, funnel, recipients: [{ phone, token, link, name }], sent, sendError? }." } "400": { description: "Not sendable (no group/questions/eligible recipients, or already sent)." } /api/admin/surveys/forms/{id}: patch: tags: [admin] summary: Edit a form (sample size / title / tags) description: >- Admin/leadership only. Body { sample_size?, title?, tags? }. Updates the form's editable fields; sample_size sets how many mumineen the next Preview/Commit & send will sample. Does not touch already-committed recipients. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ form }." } "400": { $ref: "#/components/responses/BadRequest" } "404": { description: "Form not found." } delete: tags: [admin] summary: Delete a form description: >- Admin/leadership only. Removes the form and cascades its composed questions, recipients, and answers. Also deletes the form's (mumin, question) exposures so its questions become askable again (a full undo). Cannot be undone. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ status: deleted }." } "404": { description: "Form not found." } /api/admin/surveys/forms/{id}/questions: get: tags: [admin] summary: The form's composed questions (snapshots), in order description: Admin/leadership only. Powers the per-form "Questions" review/edit panel. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ form, questions: [{ id, question_id, section_id, area, snapshot, sort_order }] }." } "404": { description: "Form not found." } /api/admin/surveys/forms/{id}/questions/{fqId}: patch: tags: [admin] summary: Edit one composed question on a form (its snapshot) description: >- Admin/leadership only. Body { text?, options?, negative_values?, polarity?, comment_threshold?, collect_comment?, required? } merged into this form's snapshot. Applies ONLY to this form (the databank is untouched). Blocked once the form is sent. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } - { name: fqId, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ snapshot }." } "400": { description: "Invalid body, or form already sent." } "404": { description: "Question not found on this form." } delete: tags: [admin] summary: Remove one question from a form description: Admin/leadership only. Drops the composed question from this form. Blocked once the form is sent. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } - { name: fqId, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ ok: true }." } "400": { description: "Form already sent." } /api/admin/surveys/mumin: get: tags: [admin] summary: One mumin's personal + registration details (popup) description: Admin/leadership only. By `?its=`, returns roster + family fields shown in the "view details" popup off a sampled record. parameters: - { name: its, in: query, required: true, schema: { type: string } } responses: "200": { description: "{ mumin: {...}, family: {...}|null }." } "404": { description: "ITS not in the active roster." } /api/admin/surveys/responses: get: tags: [admin] summary: Individual mumin survey-feedback lookup description: >- Admin/leadership only. `?q=` returns up to 20 candidate matches to pick from; `?its=` returns that person's full survey history — every answer with its question text, form and section, their 1-5 sentiment and any reason — plus per-section sentiment, an overall sentiment, and the forms they were sent. parameters: - { name: q, in: query, required: false, schema: { type: string } } - { name: its, in: query, required: false, schema: { type: string } } responses: "200": { description: "{ matches: [{its,name}] } for q, or { mumin, overall_sentiment, answered, forms_received, sections, answers } for its." } "400": { description: "Neither its nor q provided." } "404": { description: "ITS not found in the active roster." } /api/admin/surveys/forms/{id}/test-batch: post: tags: [admin] summary: Send to manually-selected individuals (test, or real attributed send) description: >- Admin/leadership only. Body { its: string[], deliver?, real? }. Creates a recipient per ITS and returns each one's link; deliver:true also sends it to their WhatsApp. `real:false` (default) → is_test recipient (no exposures, excluded from results) for in-team testing. `real:true` → genuine, attributed recipient COUNTED in analytics — the "send manually, individually" path for forms with no roster-derived audience (e.g. special-care seating feedback). Used by the "Test to people" picker + its "real send" toggle. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ recipients: [{ its, name, phone, link?, delivered?, error? }] }." } "400": { description: "Invalid body or no composed questions." } "404": { description: "Form not found." } /api/admin/surveys/forms/{id}/test-link: post: tags: [admin] summary: Mint a self-test link for a form (optionally to a specific person) description: >- Admin/leadership only. Creates an is_test recipient (no question exposures written, excluded from results) and returns its tokenized form link. Body { its? } targets a specific person (form greets them by name, response attributable; returns their name + phone). Body { its, deliver:true } also sends the link to THAT person's WhatsApp when SURVEY_SEND_ENABLED + SURVEY_WA_TEMPLATE are set (otherwise delivery.error explains and you copy the link). parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } requestBody: required: false content: application/json: schema: type: object properties: its: { type: string, description: "Target a specific person by ITS." } deliver: { type: boolean, description: "Also send the link to that person's WhatsApp." } responses: "200": { description: "{ link, token, name, phone, delivery: { delivered, error? } | null }." } "400": { description: "Form has no composed questions, or ITS not in the active roster." } "404": { description: "Form not found." } /api/admin/surveys/forms/{id}/results: get: tags: [admin] summary: Per-section 1-5 sentiment, response rate, breakdowns, comments parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "{ form, response: { sent, completed, rate }, sections: [{ title, sentiment, responses }], questions: [{ text, sentiment, breakdown, comments }] }." } "404": { description: "Form not found." } /api/admin/surveys/analytics: post: tags: [admin] summary: Cross-form feedback analytics (fully filterable) description: >- Admin/leadership only. Read-only (POST carries the filter object). Body { formIds?, areas?, sectionIds?, includeTest?, gender?, ageMin?, ageMax?, localMehman?, rahatOnly?, jamaats?, categories?, drillScore? }. Every aggregate reflects the active filters. When `drillScore` (1-5) is set, also returns `responses` — the individual answers at that sentiment score (name, ITS, question, answer, reason) for the "who responded" side pane. Returns overview (sent, responded [distinct people], response_rate, avg_sentiment, comment_count), by section/area/question, by-attribute breakdowns (local/mehman, gender, age, rahat, jamaat), the comment list, and the filter-option universe. responses: "200": { description: "{ forms, options, overview, distribution, by_section, by_area, by_question, by_attribute, comments }." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/surveys/analytics/ai: post: tags: [admin] summary: AI qualitative analysis of feedback comments description: >- Admin/leadership only. Body { comments: [{ text, area? }], scope? }. Sends only the comment TEXT (no PII) to the LLM (via getAIClient / AI_MODEL) and returns structured analysis: overall_sentiment, sentiment_score_1_5, summary, themes, ranked improvements, positives, and per_comment (one "g"|"f"|"n" label per input comment, in order — lets the UI sort free-text comments into Good/Fair/Negative). responses: "200": { description: "{ analysis, analyzed }." } "400": { $ref: "#/components/responses/BadRequest" } "403": { $ref: "#/components/responses/Forbidden" } "502": { description: "AI call failed or returned unparseable output." } /api/feedback: post: tags: [feedback] summary: Submit experience feedback description: Append-only, self-scoped via x-whatsapp-from. One call may carry several areas; each is tagged to its owning department. Used by the submit_feedback agent tool. requestBody: required: true content: application/json: schema: type: object required: [entries] properties: entries: type: array minItems: 1 maxItems: 10 items: type: object required: [area] properties: area: { type: string, enum: [mawaid, flow, parking_transport, audio_video, accommodation, seating, general] } sentiment: { type: string, enum: [positive, neutral, negative] } rating: { type: integer, minimum: 1, maximum: 5 } comment: { type: string, maxLength: 2000 } responses: "200": { description: Recorded count. } "400": { $ref: "#/components/responses/BadRequest" } /api/admin/templates: get: tags: [admin, templates] summary: Approved templates (with friendly-name + active annotations) + selectable test users description: >- Admin/leadership only (requireAdminLeadership — admin key + DB-verified role via x-portal-user-id). Returns the FULL catalog (active + inactive); each template carries friendlyName (string|null) and isActive (boolean) merged from whatsapp_template_settings. The console filters its dropdowns to isActive and drives the cleanup popup from the full list. No phone numbers returned. Spans ALL configured WhatsApp accounts: each template is tagged with accountLabel (string), wabaId (string|null), and phoneNumberId (string) of the account/WABA that owns it, and its friendlyName/isActive are scoped to that WABA. responses: "200": { description: "templates[] (each + friendlyName, isActive, accountLabel, wabaId, phoneNumberId) + selectable_users[] (id + name only)." } "401": { $ref: "#/components/responses/Unauthorized" } /api/admin/templates/settings: put: tags: [admin, templates] summary: Set a template's friendly name and/or active flag description: >- Admin/leadership only. Upserts whatsapp_template_settings for one Meta template, scoped to a WABA. Inactive templates are hidden from the console's Template dropdowns. Pass waba_id to annotate a non-primary account's template; omit it for the primary account. An unknown waba_id returns 400. requestBody: required: true content: application/json: schema: type: object required: [template_name] properties: template_name: { type: string } waba_id: { type: string, description: "WABA that owns the template; omit for the primary account." } friendly_name: { type: string, nullable: true, maxLength: 120 } is_active: { type: boolean } responses: "200": { description: "{ template_name, friendlyName, isActive }." } "400": { description: "Invalid body (no fields to update)." } "401": { $ref: "#/components/responses/Unauthorized" } /api/admin/templates/segments: get: tags: [admin, templates] summary: Niyaz reach segment sizes (free vs paid split) description: >- Admin/leadership only. Sizes of the three reach segments for the console header, each split into in_window (messaged within the free customer-service window — answerable for free) vs out_window (needs a template — counts against the daily cap). The optional `hours` query param overrides the free-window size (any positive value; falls back to the configured WHATSAPP_WINDOW_HOURS, default 24); the resolved value is echoed back as window_hours so the console can label the split. Counts only; no PII. parameters: - { name: hours, in: query, required: false, schema: { type: number, minimum: 1 }, description: "Override the free-window size in hours (any positive value)." } responses: "200": { description: "{ segments: [{ key, label, total, in_window, out_window }], window_hours }." } "401": { $ref: "#/components/responses/Unauthorized" } /api/admin/templates/preview: post: tags: [admin, templates] summary: Preview an audience (free/paid counts + cost) description: Admin/leadership only. Counts by default; with include_recipients a capped, paginated recipient sample. For audience_key=custom pass rules; for csv_upload pass csv (raw CSV text in the audience-export/failures-export format) and the response includes csv_stats (parsed/skipped/duplicates/corrupted). requestBody: required: true content: application/json: schema: type: object required: [audience_key] properties: audience_key: { type: string, enum: [selected_users, chicago_committee, arrived_hof, registered_hof, all_members, segment_all_users, segment_hof, segment_hof_unresponded, custom, csv_upload] } selected_user_ids: { type: array, items: { type: string, format: uuid } } rules: { type: object, description: react-querybuilder rule tree (audience_key=custom) } csv: { type: string, description: Raw CSV text in the audience-export format (audience_key=csv_upload) } window: { type: string, enum: [all, in_window, out_window], default: all, description: "Restrict the audience to one side of the customer-service window — in_window (free) or out_window (paid, needs a template). Counts/cost reflect the filtered subset." } window_hours: { type: number, minimum: 1, description: "Override the free-window size in hours, any positive value (defaults to WHATSAPP_WINDOW_HOURS, 24)." } include_recipients: { type: boolean } limit: { type: integer, minimum: 1, maximum: 200 } offset: { type: integer, minimum: 0 } responses: "200": { description: "{ total, in_window, out_window, est_cost_usd, funnel?, csv_stats?, recipients? }." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } /api/admin/whatsapp/accounts: get: tags: [admin, templates] summary: List configured WhatsApp sending numbers description: Admin/leadership only. Returns the configured WhatsApp accounts for the send console's "Send from" picker. No secrets — only the non-PII routing id and display labels. responses: "200": description: "{ accounts: [{ label, name, displayName, displayNumber, phoneNumberId }] }" "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/whatsapp/send: post: tags: [admin, templates] summary: Send a free-text or template message to one recipient description: Admin/leadership only. Resolves an ITS or phone to a destination number and sends a free-text (kind=text) or template (kind=template) message. Free-text sends from phone_number_id when provided (else primary); template sends from the account whose WABA owns the template. requestBody: required: true content: application/json: schema: type: object required: [kind] properties: its: { type: string, description: "ITS code (resolved to the roster member's WhatsApp number). One of its/phone required." } phone: { type: string, description: "E.164 phone number. One of its/phone required." } kind: { type: string, enum: [text, template] } text: { type: string, description: "Free-text body (kind=text)." } phone_number_id: { type: string, description: "Account/number to send a free-text message from (kind=text); defaults to primary." } template: { type: object, description: "Template payload (kind=template): name, language, bodyParams, optional header/url-button params." } responses: "200": { description: "{ ok, to, name, kind, template? }" } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/templates/send: post: tags: [admin, templates] summary: Start a manual template or free-text broadcast description: Admin/leadership only. Creates a broadcast, enqueues recipients, then drains inline until the queue is empty (bounded); the minute cron is a backstop. Manual — no auto-scheduling. message_kind=template (default) sends an approved template (template_code required; variables bound via variable_bindings). message_kind=text sends a plain free-text message (text + phone_number_id required); free-text only delivers inside the recipient's 24h window, so the audience is forced to in_window. For audience_key=custom pass rules; for csv_upload pass csv (raw CSV text in the audience-export/failures-export format). requestBody: required: true content: application/json: schema: type: object required: [audience_key] properties: message_kind: { type: string, enum: [template, text], default: template, description: "template = approved template send; text = plain free-text send." } template_code: { type: string, description: "Required when message_kind=template." } template_language: { type: string } text: { type: string, description: "Free-text body; required when message_kind=text." } phone_number_id: { type: string, description: "WhatsApp account/number to send from. Required for free-text; for templates it is validated against the template's owning WABA." } audience_key: { type: string, enum: [selected_users, chicago_committee, arrived_hof, registered_hof, all_members, segment_all_users, segment_hof, segment_hof_unresponded, custom, csv_upload] } selected_user_ids: { type: array, items: { type: string, format: uuid } } rules: { type: object, description: react-querybuilder rule tree (audience_key=custom) } csv: { type: string, description: Raw CSV text in the audience-export format (audience_key=csv_upload) } window: { type: string, enum: [all, in_window, out_window], default: all, description: "Restrict the audience to one side of the customer-service window — in_window (free) or out_window (paid). Ignored for free-text (forced in_window)." } window_hours: { type: number, minimum: 1, description: "Override the free-window size in hours, any positive value (defaults to WHATSAPP_WINDOW_HOURS, 24)." } variable_bindings: { type: object, description: Per-variable static value or roster-field mapping (template sends only) } responses: "200": { description: "status=started + broadcastId + counts." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } /api/admin/templates/audience-export: post: tags: [admin, templates] summary: Export the full resolved audience as a CSV download description: Admin/leadership only. Returns every matched recipient (Name, ITS, HOF ITS, Jamaat, City, Gender, Local/Mehman, WhatsApp, free/paid Window) as a UTF-8 CSV — the uncapped form of the preview list. For audience_key=custom pass rules; for csv_upload pass csv (raw CSV text) and the export is the resolved audience — deduped by number, roster-enriched by phone, and free/paid-labelled. requestBody: required: true content: application/json: schema: type: object required: [audience_key] properties: audience_key: { type: string, enum: [selected_users, chicago_committee, arrived_hof, registered_hof, all_members, segment_all_users, segment_hof, segment_hof_unresponded, custom, csv_upload] } selected_user_ids: { type: array, items: { type: string, format: uuid } } rules: { type: object, description: react-querybuilder rule tree (audience_key=custom) } csv: { type: string, description: Raw CSV text in the audience-export format (audience_key=csv_upload) } window: { type: string, enum: [all, in_window, out_window], default: all, description: "Restrict the export to one side of the customer-service window — in_window (free) or out_window (paid)." } window_hours: { type: number, minimum: 1, description: "Override the free-window size in hours, any positive value (defaults to WHATSAPP_WINDOW_HOURS, 24)." } responses: "200": { description: "text/csv attachment of the resolved audience." } "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } /api/admin/templates/drain: post: tags: [admin, templates] summary: Manually drain pending broadcast recipients ("Send pending") description: Admin/leadership only. Runs a bounded drain loop until the queue is empty. Triggers real sends — same gating as /send. Used by the console to unstick broadcasts when the minute cron isn't firing. responses: "200": { description: "{ ok, processed, batches }." } "401": { $ref: "#/components/responses/Unauthorized" } "500": { description: Drain failed. } /api/admin/templates/broadcasts: get: tags: [admin, templates] summary: Broadcast send log with metrics description: Admin/leadership only. Optionally filter by audience_key (e.g. niyaz_rsvp for the Niyaz RSVP sends). count_sent / count_failed are delivery-aware: bumped at send time, then kept in sync as Meta's async delivery-status webhooks report messages undeliverable (so they match the per-recipient rollup, not just send-time outcomes). parameters: - { name: audience_key, in: query, required: false, schema: { type: string }, description: "Filter to broadcasts with this audience_key (e.g. niyaz_rsvp)." } responses: "200": { description: "broadcasts[] (most recent first)." } "401": { $ref: "#/components/responses/Unauthorized" } /api/admin/templates/broadcasts/{id}: get: tags: [admin, templates] summary: One broadcast + delivery-status rollup + grouped failure reasons description: Admin/leadership only. Aggregate status counts and a grouped failure-reason breakdown only — no phone numbers (use /failures or /recipients for per-recipient lists). The returned broadcast object carries how the audience was defined — audience_key, audience_rules, variable_bindings, and the audience toggles window_filter / window_hours / selected_user_ids (null on broadcasts created before these were recorded). Failure reasons group by Meta's captured error code/title when available, otherwise the free/paid 24h-window fallback label. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } responses: "200": { description: "broadcast (incl. audience_rules/variable_bindings/window_filter/window_hours/selected_user_ids) + status_counts + failure_reasons (reason → count)." } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } /api/admin/templates/broadcasts/{id}/recipients: get: tags: [admin, templates] summary: Full recipient list for a broadcast — every status (JSON or CSV) description: Admin/leadership only. Returns the entire audience the broadcast sent to (sent/failed/skipped/queued/delivered/read/replied), each with phone, best-effort identity (name/ITS resolved by phone), send status, window flag, sent_at, and a detail field (failure reason for failed rows, skip reason for skipped). Paged server-side, so the full audience is returned even past PostgREST's 1000-row response cap. Exposes PII to authorized staff (same level as /failures); never shown to visitors. ?format=csv returns a download. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } - { name: format, in: query, required: false, schema: { type: string, enum: [csv] } } responses: "200": { description: "{ recipients[] } (JSON) or a text/csv attachment." } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } /api/admin/templates/broadcasts/{id}/failures: get: tags: [admin, templates] summary: Per-recipient failure list for a broadcast (JSON or CSV) description: Admin/leadership only. Returns each failed recipient with phone, best-effort identity (name/ITS resolved by phone), window flag, and failure reason. The reason is Meta's captured error code/title (e.g. "131026: Undeliverable …") when the delivery-status webhook supplied one, otherwise a free/paid 24h-window fallback label. Paged server-side, so all failures are returned even past PostgREST's 1000-row response cap. Exposes PII to authorized staff (same level as the audience CSV export); never shown to visitors. ?format=csv returns a download. parameters: - { name: id, in: path, required: true, schema: { type: string, format: uuid } } - { name: format, in: query, required: false, schema: { type: string, enum: [csv] } } responses: "200": { description: "{ failures[] } (JSON) or a text/csv attachment." } "401": { $ref: "#/components/responses/Unauthorized" } "404": { $ref: "#/components/responses/NotFound" } /api/admin/whatsapp/undeliverable: get: tags: [admin, templates] summary: List auto-suppressed undeliverable numbers description: Admin/leadership only. Numbers auto-suppressed because Meta reported them as not-on-WhatsApp / can't-receive (error 131026) past the failure threshold, so they're skipped on every broadcast. Each row carries phone, best-effort identity (name/ITS by phone), fail_count, last error code, and timestamps. Exposes PII to authorized staff (same level as the failures export); never shown to visitors. responses: "200": { description: "{ numbers[] } (newest failure first)." } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } delete: tags: [admin, templates] summary: Un-flag an undeliverable number description: Admin/leadership only. Clears suppression for one number and resets its failure counter so it's eligible for sends again (e.g. a mistyped number that's since been corrected). It would take a fresh run of failures to re-suppress. parameters: - { name: phone, in: query, required: true, schema: { type: string }, description: "The number to un-flag (any format; normalized server-side)." } responses: "200": { description: "{ cleared: true, phone }." } "400": { description: "phone is required." } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/Forbidden" } "404": { description: "Number is not on the suppression list." } /api/admin/prompts/{key}: get: tags: [admin] summary: Read a system prompt by key description: Admin/leadership. Returns the prompt text (DB override or code default), whether it's been customized, and the default text. parameters: - { name: key, in: path, required: true, schema: { type: string }, description: "Prompt key, e.g. agent_system, conversation_quality." } responses: "200": { description: "{ prompt_key, prompt_text, is_default, default_text, updated_by, updated_at }." } "403": { $ref: "#/components/responses/Forbidden" } put: tags: [admin] summary: Save/override a system prompt description: Admin/leadership. Upserts the prompt text for the given key. parameters: - { name: key, in: path, required: true, schema: { type: string } } requestBody: required: true content: application/json: schema: type: object properties: prompt_text: { type: string, maxLength: 10000 } responses: "200": { description: "{ prompt_key, prompt_text, updated_at }." } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/prompts/rules: get: tags: [admin] summary: Always-on rule blocks description: >- Admin/leadership. Returns all always-on rules appended to every agent system prompt, each with its current text (DB override or code default), default_text, and is_default flag. responses: "200": { description: "{ rules: [{ name, label, text, default_text, is_default, updated_by, updated_at }], dynamic: string[] }." } "403": { $ref: "#/components/responses/Forbidden" } put: tags: [admin] summary: Save/override one always-on rule description: >- Admin/leadership. Upserts a rule override into system_prompts (key = rule_{name}). Empty text or text matching the default resets the rule (deletes the override). requestBody: required: true content: application/json: schema: type: object required: [name] properties: name: { type: string, description: "Rule name, e.g. ESCALATION_POLICY." } text: { type: string, maxLength: 15000 } responses: "200": { description: "{ name, text, is_default }." } "403": { $ref: "#/components/responses/Forbidden" } /api/admin/department-contacts: get: tags: [admin, escalation] summary: List department contacts (reference rows + member users) description: > Admin-portal gated (canAccessPortal). Returns a merged list of `kind: "reference"` (freestanding department_contacts rows) and `kind: "member"` (whatsapp_users flagged as department issue contacts via department_members.contact_for_issues). Optional ?department_id filter. parameters: - { name: department_id, in: query, required: false, schema: { type: string, format: uuid } } responses: "200": { description: "{ contacts[] } — each item has a `kind` of reference|member." } "401": { $ref: "#/components/responses/Unauthorized" } post: tags: [admin, escalation] summary: Add a department contact (reference, existing user, or new user) description: > Admin-portal gated (canAccessPortal). `mode` selects the behavior: `reference` (default) inserts a freestanding department_contacts row; `existing_user` flags an existing department member as an issue contact (sets contact_for_issues=true on a membership that already exists; 400 if the user isn't a member — adding a user to a department and their role is managed on the Departments page); `new_user` creates a portal user (role committee / global_role member, reusing any existing user with the same phone) and a contact membership. Returns `{ contact }`. requestBody: required: true content: application/json: schema: oneOf: - { type: object, required: [department_id, name], properties: { mode: { type: string, enum: [reference] }, department_id: { type: string, format: uuid }, name: { type: string }, role: { type: string, nullable: true }, phone_e164: { type: string, nullable: true }, email: { type: string, format: email, nullable: true }, notes: { type: string, nullable: true }, display_order: { type: integer } } } - { type: object, required: [mode, department_id, user_id], properties: { mode: { type: string, enum: [existing_user] }, department_id: { type: string, format: uuid }, user_id: { type: string, format: uuid } } } - { type: object, required: [mode, department_id, name, phone_e164], properties: { mode: { type: string, enum: [new_user] }, department_id: { type: string, format: uuid }, name: { type: string }, phone_e164: { type: string }, email: { type: string, format: email, nullable: true }, dept_role: { type: string, enum: [member, pm, hod] }, send_welcome: { type: boolean } } } responses: "201": { description: "{ contact } — kind reference|member." } "400": { description: Invalid input. } "401": { $ref: "#/components/responses/Unauthorized" } /api/admin/department-digest: get: tags: [admin, digest] summary: Stored department + all-up daily briefings description: Admin-portal gated (requireAdminKey). Defaults to the most recent day with summaries. parameters: - { name: date, in: query, required: false, schema: { type: string, format: date } } responses: "200": { description: "{ date, summaries[] }." } "401": { $ref: "#/components/responses/Unauthorized" } /api/cron/department-digest: get: tags: [cron] summary: Department digest runner (manual/admin trigger) description: Aggregate→AI briefing→store→distribute (email + free in-window WhatsApp). Auth via CRON_SECRET bearer or admin key. Optional ?date= override. responses: "200": { description: Run result. } "401": { $ref: "#/components/responses/Unauthorized" } /api/cron/broadcast-drain: get: tags: [cron] summary: Drain queued template-broadcast recipients (throttled batch) description: Runs every minute. Auth via CRON_SECRET bearer or admin key. responses: "200": { description: "{ processed, broadcastsTouched }." } "401": { $ref: "#/components/responses/Unauthorized" } components: securitySchemes: whatsappPhone: type: apiKey in: header name: x-whatsapp-from description: E.164 phone number used by the WhatsApp agent and scoped user APIs. adminKey: type: apiKey in: header name: x-admin-key description: Server-to-server auth for agent tools and cron jobs. Never sent by browser clients. portalSession: type: apiKey in: cookie name: portal_session description: HMAC-SHA256-signed httpOnly session cookie set by POST /api/admin/auth. Carries { user_id, exp }. Used by all browser-facing admin routes. cronSecret: type: http scheme: bearer description: Cron bearer token derived from CRON_SECRET. parameters: Id: name: id in: path required: true schema: { type: string, format: uuid } StatusFilter: name: status in: query schema: { type: string, enum: [open, in_progress, blocked, complete, all], default: all } PriorityFilter: name: priority in: query schema: { type: string, enum: [low, medium, high, all], default: all } responses: BadRequest: description: Invalid request. content: application/json: schema: { $ref: "#/components/schemas/Error" } Unauthorized: description: Missing or invalid authentication. content: application/json: schema: { $ref: "#/components/schemas/Error" } Forbidden: description: Caller lacks permission. content: application/json: schema: { $ref: "#/components/schemas/Error" } NotFound: description: Resource not found. content: application/json: schema: { $ref: "#/components/schemas/Error" } ServerError: description: Server error. content: application/json: schema: { $ref: "#/components/schemas/Error" } schemas: Error: type: object required: [error] properties: error: { type: string } QuizAnswers: type: array minItems: 1 maxItems: 100 items: type: object required: [question_id, chosen_index] properties: question_id: { type: string } chosen_index: { type: integer, nullable: true, minimum: 0, maximum: 9 } TaskStatus: type: string enum: [open, in_progress, blocked, complete] TaskPriority: type: string enum: [low, medium, high] Department: type: object required: [id, name] properties: id: { type: string, format: uuid } name: { type: string } description: { type: [string, "null"] } created_at: { type: string, format: date-time } DepartmentAssignmentMember: type: object required: [id, display_name, department_role] properties: id: { type: string, format: uuid } display_name: { type: [string, "null"] } department_role: { type: string, enum: [hod, pm, member] } User: type: object required: [id, phone_e164, role, global_role, status] properties: id: { type: string, format: uuid } display_name: { type: [string, "null"] } phone_e164: { type: string } email: { type: [string, "null"], format: email } role: { type: string, enum: [visitor, committee, admin] } global_role: { type: string, enum: [member, pm, hod, leadership_admin] } status: { type: string } transcript_aliases: type: array items: { type: string } email_digest: { type: boolean } department_membership_id: { type: [string, "null"], format: uuid } department_role: { type: [string, "null"], enum: [hod, pm, member, null] } contact_for_issues: { type: boolean } AuthSessionResponse: type: object required: [ok, token, user] properties: ok: { type: boolean } token: { type: string } user: type: object required: [id, is_support, is_manager, is_it] properties: id: { type: string, format: uuid } display_name: { type: [string, "null"] } email: { type: [string, "null"], format: email } role: { type: [string, "null"], enum: [visitor, committee, admin, null] } global_role: { type: [string, "null"], enum: [member, pm, hod, leadership_admin, null] } is_support: { type: boolean } is_manager: { type: boolean } is_it: { type: boolean } CallerContext: type: object required: [user_id, global_role, can_read_all, can_write_all, departments] properties: user_id: { type: string } display_name: { type: [string, "null"] } global_role: { type: string, enum: [member, pm, hod, leadership_admin] } can_read_all: { type: boolean } can_write_all: { type: boolean } departments: type: array items: type: object required: [department_id, department_name, dept_role] properties: department_id: { type: string, format: uuid } department_name: { type: string } dept_role: { type: string, enum: [hod, pm, member] } Task: type: object required: [id, title, status, priority, source, archived, created_at, updated_at] properties: id: { type: string, format: uuid } title: { type: string } description: { type: [string, "null"] } department_id: { type: [string, "null"], format: uuid } status: { $ref: "#/components/schemas/TaskStatus" } priority: { $ref: "#/components/schemas/TaskPriority" } archived: { type: boolean } assigned_to: { type: [string, "null"], format: uuid } created_by: { type: [string, "null"], format: uuid } source: { type: string, enum: [transcript, whatsapp_agent, manual] } due_date: { type: [string, "null"], format: date } created_at: { type: string, format: date-time } updated_at: { type: string, format: date-time } CreateTaskRequest: type: object required: [title] properties: title: { type: string } department_id: { type: string, format: uuid } department_name: { type: string } description: { type: [string, "null"] } assigned_to: { type: [string, "null"], format: uuid } assigned_to_alias: { type: string } due_date: { type: [string, "null"], format: date } priority: { $ref: "#/components/schemas/TaskPriority" } source: { type: string, enum: [transcript, whatsapp_agent, manual] } UpdateTaskRequest: type: object properties: title: { type: string } description: { type: [string, "null"] } status: { $ref: "#/components/schemas/TaskStatus" } priority: { $ref: "#/components/schemas/TaskPriority" } department_id: { type: [string, "null"], format: uuid } assigned_to: { type: [string, "null"], format: uuid } assigned_to_alias: { type: string } due_date: { type: [string, "null"], format: date } archived: { type: boolean } KanbanBoard: type: object required: [open, in_progress, blocked, complete] properties: open: type: array items: { $ref: "#/components/schemas/Task" } in_progress: type: array items: { $ref: "#/components/schemas/Task" } blocked: type: array items: { $ref: "#/components/schemas/Task" } complete: type: array items: { $ref: "#/components/schemas/Task" } DepartmentSummary: type: object required: [department_name, department_id, open, in_progress, blocked, complete, total, overdue, top_blockers] properties: department_name: { type: string } department_id: { type: string, format: uuid } open: { type: integer } in_progress: { type: integer } blocked: { type: integer } complete: { type: integer } total: { type: integer } overdue: { type: integer } top_blockers: type: array items: { $ref: "#/components/schemas/Task" } ConversationUpload: type: object properties: id: { type: string, format: uuid } department_id: { type: string, format: uuid } filename: { type: [string, "null"] } group_name: { type: [string, "null"] } parsed_at: { type: [string, "null"], format: date-time } last_message_at: { type: [string, "null"], format: date-time } parsed_new_members: type: array items: { $ref: "#/components/schemas/ParsedNewMember" } ConversationEvent: type: object properties: id: { type: string, format: uuid } upload_id: { type: string, format: uuid } department_id: { type: string, format: uuid } event_type: type: string enum: [task_created, task_updated, task_completed, milestone_created, milestone_updated, issue_created, issue_updated, issue_resolved, decision, info] item_type: { type: string, enum: [task, issue, milestone] } task_id: { type: [string, "null"], format: uuid } milestone_id: { type: [string, "null"], format: uuid } review_action: { type: string, enum: [create, update] } review_kind: { type: string, enum: [task, issue, milestone] } target_id: { type: [string, "null"], format: uuid } target_title: { type: [string, "null"] } target_status: { type: [string, "null"] } review_label: { type: string } sender_alias: { type: [string, "null"] } message_text: { type: [string, "null"] } message_timestamp: { type: [string, "null"], format: date-time } ai_summary: { type: [string, "null"] } task_title: { type: [string, "null"] } milestone_title: { type: [string, "null"] } assigned_to_alias: { type: [string, "null"] } assigned_to_user_id: { type: [string, "null"], format: uuid } priority: { $ref: "#/components/schemas/TaskPriority" } confidence: { type: [number, "null"] } percent_complete: { type: [integer, "null"] } budget: { type: [number, "null"] } notes: { type: [string, "null"] } description: { type: [string, "null"] } suggested_status: { $ref: "#/components/schemas/TaskStatus" } due_date: { type: [string, "null"], format: date } source: { type: [string, "null"], enum: [call_transcript, whatsapp_agent, manual, transcript] } raw_function_event: { type: [object, "null"] } suggested_changes: { type: [object, "null"] } applied: { type: boolean } ParsedTranscript: type: object required: [events] properties: group_name: { type: [string, "null"] } last_message_at: { type: [string, "null"], format: date-time } departments: type: array items: { $ref: "#/components/schemas/Department" } existing_items: type: array items: { type: object } events: type: array items: { $ref: "#/components/schemas/ConversationEvent" } function_calls_saved: { type: integer } flexible_prompt: { type: string } transcript_type: { type: string, enum: [whatsapp, meeting] } ParsedNewMember: type: object required: [alias, context] properties: alias: { type: string } context: { type: string } DepartmentPromptConfig: type: object required: [fixed_prompt_locked, flexible_prompt] properties: fixed_prompt_locked: { type: boolean } flexible_prompt: { type: string } updated_at: { type: [string, "null"], format: date-time } ApplyTranscriptEvent: type: object required: [event_id] properties: event_id: { type: string, format: uuid } title: { type: string } description: { type: [string, "null"] } status: { $ref: "#/components/schemas/TaskStatus" } priority: { $ref: "#/components/schemas/TaskPriority" } due_date: { type: [string, "null"], format: date } budget: { type: [number, "null"] } percent_complete: { type: [number, "null"] } notes: { type: [string, "null"] } milestone_id: { type: [string, "null"], format: uuid } assigned_to_alias: { type: string } assigned_to_user_id: { type: [string, "null"], format: uuid } CreateUserRequest: type: object required: [display_name, phone_e164] properties: display_name: { type: string } phone_e164: { type: string } email: { type: [string, "null"], format: email } global_role: { type: string, enum: [member, pm, hod, leadership_admin] } UpdateUserRequest: type: object properties: display_name: { type: string } email: { type: [string, "null"], format: email } global_role: { type: string, enum: [member, pm, hod, leadership_admin] } status: { type: string } DepartmentMembershipRequest: type: object required: [department_id, dept_role] properties: department_id: { type: string, format: uuid } dept_role: { type: string, enum: [hod, pm, member] } is_active: { type: boolean } contact_for_issues: { type: boolean } send_welcome: type: boolean description: >- When true, issue a password setup link and send the new-user welcome notification (email + the `committee_platform_access_created` WhatsApp template). Welcomes each user only once: an already-welcomed user (non-null `welcomed_at`) returns `already_welcomed: true` and nothing is sent. When set, the response includes a `welcome_notification` object (see WelcomeNotification). WelcomeNotification: type: object description: >- Outcome of an onboarding welcome attempt. `already_welcomed` is true when the user had already been welcomed and the automatic path therefore sent nothing (the manual /welcome action forces a re-send and never short-circuits). properties: email: { type: string, enum: [sent, skipped, failed] } whatsapp: { type: string, enum: [sent, skipped, failed] } already_welcomed: { type: boolean } set_password_url: { type: string } errors: type: array items: { type: string } BulkCreateUsersRequest: type: object required: [members] properties: members: type: array items: type: object required: [display_name, phone_e164, department_id, dept_role] properties: display_name: { type: string } phone_e164: { type: string } email: { type: [string, "null"], format: email } department_id: { type: string, format: uuid } dept_role: { type: string, enum: [hod, pm, member] } transcript_aliases: type: array items: { type: string } RelayUpdate: type: object required: [id, date, title, body, category, published] properties: id: { type: string, format: uuid } date: { type: string, format: date } title: { type: string, maxLength: 200 } body: { type: string, maxLength: 1000 } category: { type: string, enum: [urgent, schedule, travel, advisory] } link: { type: [string, "null"], maxLength: 500, description: Optional CTA URL (http/https). } cta: { type: [string, "null"], maxLength: 80, description: Optional CTA label; requires link. } published: { type: boolean } created_at: { type: string, format: date-time } updated_at: { type: string, format: date-time } RelayUpdateWriteRequest: type: object required: [user_id, date, title, body, category] properties: user_id: { type: string, format: uuid, description: Acting admin user id; server verifies admin/leadership role. } date: { type: string, format: date } title: { type: string, maxLength: 200 } body: { type: string, maxLength: 1000 } category: { type: string, enum: [urgent, schedule, travel, advisory] } link: { type: string, maxLength: 500, description: Optional CTA URL (http/https). } cta: { type: string, maxLength: 80, description: Optional CTA label; requires link. } published: { type: boolean, default: true } # --- Accommodations Module --- /admin/accommodations/hosts: get: tags: [accommodations] summary: List host rollups with capacity and demographics. security: [{ adminKey: [] }] responses: 200: description: Array of host rollup rows. content: application/json: schema: type: object properties: hosts: { type: array, items: { $ref: '#/components/schemas/AccommodationHost' } } post: tags: [accommodations] summary: Upload host spreadsheet (XLSX). security: [{ adminKey: [] }] requestBody: required: true content: multipart/form-data: schema: type: object properties: file: { type: string, format: binary } responses: 201: description: Import result. content: application/json: schema: type: object properties: rows: { type: integer } hostsUpserted: { type: integer } importId: { type: string, format: uuid } patch: tags: [accommodations] summary: Toggle include_family_friends for a host. security: [{ adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [hostId, include_family_friends] properties: hostId: { type: string, format: uuid } include_family_friends: { type: boolean } responses: 200: description: Success. /admin/accommodations/guests: get: tags: [accommodations] summary: List awaiting-utaro guest families with demographics. security: [{ adminKey: [] }] responses: 200: description: Array of guest rollup rows. content: application/json: schema: type: object properties: guests: { type: array, items: { $ref: '#/components/schemas/AccommodationGuest' } } /admin/accommodations/matches: get: tags: [accommodations] summary: List matches or generate suggestions (?action=suggest). security: [{ adminKey: [] }] parameters: - name: action in: query schema: { type: string, enum: [suggest] } responses: 200: description: Matches list or suggestions array. post: tags: [accommodations] summary: Create a pending match. security: [{ adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [guestFamilyId, hostId, guestMemberCount] properties: guestFamilyId: { type: string, format: uuid } hostId: { type: string, format: uuid } guestMemberCount: { type: integer } notes: { type: string } responses: 201: description: Created match ID. content: application/json: schema: type: object properties: matchId: { type: string, format: uuid } patch: tags: [accommodations] summary: Confirm, reject, or cancel a match. security: [{ adminKey: [] }] requestBody: required: true content: application/json: schema: type: object required: [matchId, action] properties: matchId: { type: string, format: uuid } action: { type: string, enum: [confirm, reject, cancel] } confirmedBy: { type: string } responses: 200: description: Action completed. # ── Issues ──────────────────────────────────────────────────── /admin/issues: get: tags: [issues] summary: List issues with optional filters. parameters: - { name: status, in: query, description: "active = open + in_progress; all/omitted = every status", schema: { type: string, enum: [active, open, in_progress, resolved, all] } } - { name: department_id, in: query, schema: { type: string, format: uuid } } - { name: priority, in: query, schema: { type: string, enum: [low, medium, high, all] } } - { name: search, in: query, schema: { type: string } } responses: 200: description: List of issues with escalation counts. post: tags: [issues] summary: Create a new issue. requestBody: required: true content: application/json: schema: type: object required: [title] properties: title: { type: string } description: { type: string } priority: { type: string, enum: [low, medium, high] } department_id: { type: string, format: uuid } assigned_to: { type: string, format: uuid } responses: 201: description: Created issue. /admin/issues/{issueId}: get: tags: [issues] summary: Issue detail with linked escalations and activity log. description: >- Each linked escalation carries a per-link episode lifecycle: `link_status` (open|resolved) and `link_resolved_at`, plus the conversation's `escalation_status`/`escalation_stage`. Resolved-ness and `breaching` are computed from `link_status` (this conversation's episode in THIS issue) — not the conversation's current state, which may have moved on to another issue. Resolving a conversation resolves its open link(s); when all of an issue's links are resolved the issue auto-closes (and auto-reopens if a fresh link is added). responses: 200: description: Issue detail. put: tags: [issues] summary: Update issue fields. responses: 200: description: Updated issue. delete: tags: [issues] summary: Delete an issue (cascade removes links). responses: 200: description: Deleted. /admin/issues/{issueId}/link: post: tags: [issues] summary: Link an escalation to this issue. requestBody: required: true content: application/json: schema: type: object required: [phone_e164] properties: phone_e164: { type: string } responses: 200: description: Linked. delete: tags: [issues] summary: Unlink an escalation from this issue. responses: 200: description: Unlinked. /admin/issues/{issueId}/resolve: post: tags: [issues] summary: Close issue — optionally notify linked conversations and resolve escalations. requestBody: content: application/json: schema: type: object properties: message: type: string maxLength: 4096 description: WhatsApp message sent to all linked conversations (recorded into the member's chat for in-app conversations). Omit to skip. resolve_escalations: type: boolean default: true description: Resolve linked escalations and switch conversations back to AI handling. close_issue: type: boolean default: true description: Set issue status to resolved. responses: 200: description: Issue closed with counts. content: application/json: schema: type: object properties: issue: type: object properties: id: { type: string } issue_number: { type: integer } status: { type: string } conversations_resolved: { type: integer } messages_sent: { type: integer } messages_failed: { type: integer } failed_phones: type: array items: { type: string } description: Present only when messages_failed > 0. 409: description: Issue is already resolved. /admin/issues/suggestions: get: tags: [issues] summary: AI grouping suggestions — analyze ungrouped escalations for clusters + matches. description: >- On-demand endpoint that fetches ungrouped escalations and open issues, sends them to the AI model for cluster detection, and returns suggested groupings. No caching. responses: 200: description: Grouping suggestions. content: application/json: schema: type: object properties: new_clusters: type: array description: Clusters of 2+ escalations that should be grouped into new issues. existing_issue_matches: type: array description: Ungrouped escalations matching existing open issues. meta: type: object properties: ungrouped_count: { type: integer } analyzed_at: { type: string, format: date-time } 500: description: AI analysis failed. /admin/issues/suggestions/apply: post: tags: [issues] summary: Create issue from AI suggestion and bulk-link escalations. requestBody: required: true content: application/json: schema: type: object required: [title, session_ids] properties: title: { type: string, minLength: 1, maxLength: 500 } description: { type: string, maxLength: 5000 } priority: { type: string, enum: [low, medium, high] } department_id: { type: string, format: uuid } assigned_to: { type: string, format: uuid } session_ids: type: array items: { type: string } minItems: 1 responses: 201: description: Issue created and escalations linked. content: application/json: schema: type: object properties: issue: type: object properties: id: { type: string } issue_number: { type: integer } title: { type: string } status: { type: string } linked_count: { type: integer } 400: description: Invalid request body. /admin/issues/{issueId}/link-bulk: post: tags: [issues] summary: Bulk-link multiple escalations to an existing issue. parameters: - name: issueId in: path required: true schema: { type: string, format: uuid } requestBody: required: true content: application/json: schema: type: object required: [session_ids] properties: session_ids: type: array items: { type: string } minItems: 1 responses: 200: description: Escalations linked. content: application/json: schema: type: object properties: linked_count: { type: integer } skipped_count: { type: integer } 404: description: Issue not found. /admin/escalations/stats: get: tags: [escalations] summary: KPI stats for inbox header (open, pending, breaching, avg pickup, resolved today). responses: 200: description: SLA stats. /admin/escalations/{phoneE164}/suggestions: get: tags: [escalations] summary: AI-generated suggestions for an escalation (matching issues + resolution history). description: >- On-demand endpoint called when a support member views an escalation. Uses AI to match the escalation reason/category against open issues and summarize how similar past escalations were resolved. Results are cached in-memory for 3 minutes. security: [{ portalSession: [] }] parameters: - name: phoneE164 in: path required: true schema: { type: string } responses: 200: description: Suggestions with matching issues and resolution history. content: application/json: schema: type: object properties: matching_issues: type: array items: type: object properties: id: { type: string, format: uuid } issue_number: { type: integer } title: { type: string } status: { type: string, enum: [open, in_progress] } priority: { type: string, enum: [low, medium, high] } department_name: { type: string, nullable: true } relevance_reason: { type: string } resolution_history: type: object nullable: true properties: summary: { type: string } past_count: { type: integer } 401: { $ref: "#/components/responses/Unauthorized" } 500: { $ref: "#/components/responses/ServerError" } /api/admin/parking/proximity: get: summary: Audit parking passes for proximity violations description: | Returns all families whose passes violate proximity rules (anchor lot + wrong overflow). Proximity rules: Gold/White anchor → overflow Red (fallback Blue); Blue anchor → overflow Blue. Requires canManageParking. tags: [Parking] security: [{ portalSession: [] }] responses: 200: description: Audit result with per-family issues and planned fix targets. content: application/json: schema: type: object properties: issues: type: array items: type: object properties: family_id: { type: string, format: uuid } hof_its: { type: string } head_name: { type: string } anchor_color: { type: string } anchor_lot_name: { type: string } passes_to_revoke: type: array items: type: object properties: id: { type: string, format: uuid } lot_name: { type: string } lot_color: { type: string, nullable: true } overflow_lot: type: object nullable: true properties: id: { type: string, format: uuid } name: { type: string } color: { type: string, nullable: true } using_fallback: { type: boolean } over_capacity: { type: boolean } total_families: { type: integer } total_to_revoke: { type: integer } 401: { $ref: "#/components/responses/Unauthorized" } 500: { $ref: "#/components/responses/ServerError" } post: summary: Fix all parking pass proximity violations description: | Revokes all misallocated passes and inserts replacements in the correct overflow lot. Processes families sequentially; tracks running lot counts to respect capacity. Capacity is soft — if both primary and fallback lots are full the fix proceeds with a warning. Requires canManageParking. tags: [Parking] security: [{ portalSession: [] }] responses: 200: description: Fix summary. content: application/json: schema: type: object properties: ok: { type: boolean } revoked: { type: integer } assigned: { type: integer } skipped: { type: integer } fallbacks_used: { type: integer } 401: { $ref: "#/components/responses/Unauthorized" } 500: { $ref: "#/components/responses/ServerError" } /api/admin/parking/print: get: summary: Get passes for the print layout (by lot, by household, or all) description: | Returns parking passes with the family head's name and phone number for the /admin/parking/print page (2-per-page printable layout). Scope is controlled by query params: - lot_id — passes for one lot, sorted alphabetically by head name. - hof_its — passes for one household, sorted by lot name; response includes a `household` object. Used by the per-row "Show passes" action. - neither — all passes across every lot, sorted by ITS number. unprinted_only defaults to true (only passes with printed_at IS NULL). tags: [Parking] security: [{ portalSession: [] }] parameters: - name: lot_id in: query required: false schema: { type: string, format: uuid } - name: hof_its in: query required: false description: Restrict to a single household's passes (mutually exclusive with lot_id). schema: { type: string } - name: unprinted_only in: query required: false description: "1 (default) returns only unprinted passes; 0 returns all." schema: { type: string, enum: ["0", "1"] } responses: 200: description: Pass list (optionally scoped to a lot or household). content: application/json: schema: type: object properties: lot: type: object nullable: true properties: id: { type: string, format: uuid } name: { type: string } color: { type: string, nullable: true } household: type: object nullable: true properties: hof_its: { type: string } head_name: { type: string } passes: type: array items: type: object properties: id: { type: string, format: uuid } hof_its: { type: string } head_name: { type: string } phone: { type: string, nullable: true } lot_name: { type: string } lot_color: { type: string, nullable: true } printed_at: { type: string, format: date-time, nullable: true } total_passes: { type: integer } unprinted_count: { type: integer } 400: { $ref: "#/components/responses/BadRequest" } 401: { $ref: "#/components/responses/Unauthorized" } 404: { $ref: "#/components/responses/NotFound" } 500: { $ref: "#/components/responses/ServerError" }