Skip to content

Instantly share code, notes, and snippets.

@hmseeb
Created March 14, 2026 01:00
Show Gist options
  • Select an option

  • Save hmseeb/269d4dc109be3fd0b0b3b224b4866dc8 to your computer and use it in GitHub Desktop.

Select an option

Save hmseeb/269d4dc109be3fd0b0b3b224b4866dc8 to your computer and use it in GitHub Desktop.
LeadrWizard v1.0 — Application Flow (Mermaid Diagrams)

LeadrWizard — Application Flow

AI-powered autonomous onboarding agent. Agencies self-serve via Stripe, their clients get onboarded automatically through multi-channel conversations (SMS, voice, email, web widget).

1. Agency Signup Flow

sequenceDiagram
    participant Agency as Agency Admin
    participant Checkout as /api/signup/checkout
    participant Stripe
    participant Webhook as /api/webhooks/stripe
    participant DB as Supabase (PostgreSQL)
    participant Email as Supabase Auth

    Agency->>Checkout: POST {planSlug, email, orgName}
    Checkout->>Stripe: createSignupCheckoutSession()
    Stripe-->>Agency: Redirect to Stripe Checkout
    Agency->>Stripe: Completes payment
    Stripe->>Webhook: checkout.session.completed (signed)
    Webhook->>Webhook: constructEvent() — verify signature
    Webhook->>Webhook: Idempotency check (processed_webhook_events)
    Webhook->>DB: supabase.rpc('provision_org') — atomic
    Note over DB: Creates org + org_subscription<br/>in single transaction
    Webhook->>Email: inviteUserByEmail(adminEmail)
    Email-->>Agency: Welcome email with password link
    Webhook->>DB: INSERT org_members (owner role)
    Agency->>Agency: Sets password, logs in
    Agency->>Agency: Sees Setup Wizard on dashboard
Loading

2. Admin Setup Flow

flowchart TD
    A[Admin logs in] --> B{Setup Wizard visible?}
    B -->|No services or packages| C[Setup Wizard]
    B -->|Has services + packages| D[Normal Dashboard]

    C --> E[Step 1: Add Services]
    C --> F[Step 2: Configure Package]
    C --> G[Step 3: Set Up Integrations]

    E --> E1[Create service definitions]
    E1 --> E2[Define required_data_fields]
    E2 --> E3[Define setup_steps]

    F --> F1[Create package]
    F1 --> F2[Assign services]
    F2 --> F3[Set pricing]

    G --> G1[Enter Twilio SID + Auth Token]
    G1 --> G2[Enter GHL API Key]
    G2 --> G3[Provision Twilio Phone Number]
    G3 --> G4[Credentials encrypted with AES-256-GCM]

    E3 --> D
    F3 --> D
    G4 --> D

    D --> D1[Live KPI Cards — realtime]
    D --> D2[Recent Escalations — realtime]
    D --> D3[Sessions List — realtime]
Loading

3. Client Onboarding Flow (End-to-End)

sequenceDiagram
    participant Payment as Payment System
    participant PayHook as /api/webhooks/payment
    participant DB as Supabase
    participant Cron as /api/cron/outreach
    participant Twilio
    participant Client
    participant Widget as Embeddable Widget
    participant API as /api/widget/*
    participant Tasks as /api/cron/task-processor

    Payment->>PayHook: Payment completed (HMAC signed)
    PayHook->>PayHook: Verify signature + idempotency
    PayHook->>DB: supabase.rpc('provision_client') — atomic
    Note over DB: Creates client + client_package +<br/>client_services + onboarding_session<br/>in single transaction
    PayHook->>DB: Queue outreach messages

    Cron->>DB: Fetch pending outreach
    Cron->>Cron: getOrgCredentials() — decrypt per-org creds
    Cron->>Twilio: sendSMS(orgCreds.twilio) — org's dedicated number
    Twilio-->>Client: "Hi! Let's get you set up. Click here →"

    Client->>Widget: Opens widget link (sessionId in URL)
    Widget->>Widget: validateOrigin(allowedOrigins)
    Widget->>API: GET /api/widget/session/{sessionId}
    API-->>Widget: {session, client, services, currentQuestion, voiceConfig}
    Widget->>Widget: Render step-by-step form + progress bar

    loop Each required field
        alt Form Mode
            Client->>Widget: Fills form field, clicks Submit
        else Voice Mode (ElevenLabs)
            Client->>Widget: Speaks answer via microphone
            Widget->>Widget: VoiceBot processes via WebSocket
        end
        Widget->>API: POST /api/widget/response (with retry 3x)
        API->>DB: INSERT session_response + interaction_log
        API->>API: Check if all fields complete
        API-->>Widget: {nextQuestion} or {action: "complete"}
    end

    Widget->>Widget: Show completion screen + next steps

    Tasks->>DB: Fetch pending service_tasks
    Tasks->>Tasks: getOrgCredentials() — per-org isolation
    Tasks->>Tasks: Execute: A2P, GMB, Website, GHL sync
    Note over Tasks: Failed 5x? → Dead Letter Queue
Loading

4. Per-Org Credential Isolation

flowchart LR
    subgraph "Org A"
        A1[Twilio SID: xxx] --> A2[encrypt AES-256-GCM]
        A2 --> A3[twilio_account_sid_encrypted]
        A4[GHL Key: yyy] --> A5[encrypt]
        A5 --> A6[ghl_api_key_encrypted]
    end

    subgraph "Org B"
        B1[Twilio SID: zzz] --> B2[encrypt AES-256-GCM]
        B2 --> B3[twilio_account_sid_encrypted]
        B4[GHL Key: www] --> B5[encrypt]
        B5 --> B6[ghl_api_key_encrypted]
    end

    subgraph "Outreach Processor"
        OP[Process outreach item] --> OC[getOrgCredentials org_id]
        OC --> DC[decrypt per-org creds]
        DC --> SMS[sendSMS with orgCreds.twilio]
        DC --> GHL[sendEmail with orgCreds.ghl]
    end

    A3 -.->|Org A outreach| OC
    B3 -.->|Org B outreach| OC
Loading

5. Error Handling & Observability

flowchart TD
    subgraph "Request Pipeline"
        R[Incoming Request] --> MW[Middleware]
        MW --> MW1[Rate Limit Check — Upstash Redis]
        MW1 -->|Over limit| R429[429 Too Many Requests]
        MW1 -->|Under limit| MW2[Inject x-correlation-id]
        MW2 --> RH[Route Handler]
        RH --> LOG[pino logger — structured JSON]
        LOG --> LOG1["{ correlation_id, org_id, session_id, route }"]
    end

    subgraph "Error Path"
        RH -->|Error| CATCH[catch block]
        CATCH --> PINO[log.error — err, org_id, session_id]
        CATCH --> SENTRY[Sentry.captureException]
        SENTRY --> TAGS["Tags: correlation_id, org_id, session_id"]
    end

    subgraph "Task Failure Path"
        TF[Service task fails] --> TC{Attempt count?}
        TC -->|< 5| RETRY[Exponential backoff — retry]
        TC -->|>= 5| DLQ[Move to Dead Letter Queue]
        DLQ --> ESC[Create escalation]
        ESC --> ADMIN[Admin DLQ page — retry/dismiss]
    end

    subgraph "Realtime Dashboard"
        DB[(PostgreSQL)] -->|Postgres Changes| SUB[Supabase Realtime]
        SUB -->|filter: org_id=eq.uuid| HOOK[useRealtimeTable hook]
        HOOK --> KPI[Live KPI Cards]
        HOOK --> SESS[Live Sessions List]
        HOOK --> ESCL[Live Escalations List]
    end
Loading

6. System Architecture

flowchart TB
    subgraph "Frontend"
        ADMIN[Admin Dashboard<br/>Next.js 15 App Router]
        WIDGET[Embeddable Widget<br/>Vite IIFE Bundle]
    end

    subgraph "API Layer"
        WH_STRIPE[/api/webhooks/stripe]
        WH_PAY[/api/webhooks/payment]
        W_SESSION[/api/widget/session]
        W_RESPONSE[/api/widget/response]
        SIGNUP[/api/signup/checkout]
        CRON_OUT[/api/cron/outreach]
        CRON_TASK[/api/cron/task-processor]
    end

    subgraph "Shared Package"
        BILLING[Stripe Adapter]
        COMMS[Twilio SMS · GHL Email · Vapi Voice]
        AUTO[Task Processor · Escalation · Website Builder]
        CRYPTO[AES-256-GCM Encryption]
        LOGGER[pino Logger · Rate Limiter]
        TENANT[Org Manager · Credential Resolver]
    end

    subgraph "Infrastructure"
        SUPA[(Supabase PostgreSQL<br/>+ RLS + Realtime)]
        STRIPE_SVC[Stripe]
        TWILIO_SVC[Twilio]
        GHL_SVC[GoHighLevel]
        ELEVEN[ElevenLabs]
        UPSTASH[Upstash Redis]
        SENTRY_SVC[Sentry]
    end

    ADMIN --> W_SESSION & W_RESPONSE & WH_STRIPE & SIGNUP
    WIDGET --> W_SESSION & W_RESPONSE
    WIDGET -.->|WebSocket| ELEVEN

    WH_STRIPE --> BILLING --> STRIPE_SVC
    WH_PAY --> AUTO
    CRON_OUT --> COMMS
    CRON_TASK --> AUTO
    COMMS --> TWILIO_SVC & GHL_SVC
    AUTO --> SUPA
    TENANT --> CRYPTO --> SUPA
    LOGGER --> UPSTASH & SENTRY_SVC

    W_SESSION & W_RESPONSE --> SUPA
    SIGNUP --> BILLING
Loading

Tech Stack

Layer Technology
Admin App Next.js 15 (App Router, RSC, Server Actions)
Widget Vite + React (IIFE bundle, Shadow DOM)
Database Supabase PostgreSQL + RLS + Realtime
Auth Supabase Auth (inviteUserByEmail, middleware)
Payments Stripe SDK v20.4.1
SMS Twilio REST API
Voice ElevenLabs WebSocket
CRM GoHighLevel API
Rate Limiting Upstash Redis (sliding window)
Logging pino (structured JSON)
Error Tracking Sentry (@sentry/nextjs)
Encryption AES-256-GCM (Node.js crypto)
Monorepo Turborepo + pnpm

Generated from LeadrWizard v1.0 milestone audit — 28/28 requirements, 8 phases, 26 plans.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment