# Plan: Website Signup Real-Time Pipeline

## Overview
When someone signs up on rateright.com.au, instantly:
1. Create/update lead in CRM
2. Alert via Slack + browser notification
3. Show speed-to-lead countdown on dashboard
4. Track time-to-first-contact metrics

**Goal:** < 5 second from form submit to sales rep notification

---

## Architecture

```
Website Form Submit
    ↓
POST /api/webhooks/website-signup (with API key)
    ↓
[1] Validate webhook key
[2] Smart dedupe (phone OR email OR company+name)
    ├── New lead → Create with score 70
    └── Existing → Boost +50, flag HOT, get history
[3] Generate AI insight (if re-engaged)
[4] Store in database
[5] Send Slack alert (URGENT formatting)
[6] Broadcast realtime event
[7] Return success
    ↓
Dashboard receives 'website_signup' event
    ↓
SpeedToLead modal appears with countdown
```

---

## Implementation Steps

### Step 1: Database Migration
**File:** `supabase/website-signup-migration.sql`

```sql
-- Add website signup tracking to leads
ALTER TABLE leads ADD COLUMN IF NOT EXISTS signup_source VARCHAR(50);
ALTER TABLE leads ADD COLUMN IF NOT EXISTS signup_at TIMESTAMPTZ;
ALTER TABLE leads ADD COLUMN IF NOT EXISTS first_contact_at TIMESTAMPTZ;
ALTER TABLE leads ADD COLUMN IF NOT EXISTS signup_message TEXT;

-- Speed-to-lead metrics table
CREATE TABLE IF NOT EXISTS speed_to_lead (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  lead_id UUID REFERENCES leads(id),
  signup_at TIMESTAMPTZ NOT NULL,
  first_contact_at TIMESTAMPTZ,
  first_response_at TIMESTAMPTZ,
  converted_at TIMESTAMPTZ,
  minutes_to_contact INTEGER,
  minutes_to_response INTEGER,
  contact_channel VARCHAR(20),
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_speed_to_lead_signup ON speed_to_lead(signup_at DESC);
```

### Step 2: Webhook Endpoint
**File:** `src/routes/webhooks.js`

Add `POST /api/webhooks/website-signup`:
- Validate `X-Webhook-Key` header
- Accept: `{ name, email, phone, company, message, source }`
- Smart dedupe logic:
  1. Try phone match (normalized)
  2. Try email match (lowercase)
  3. Try company + similar name (fuzzy)
- If new: create with score 70, source='website'
- If existing: boost score +50, flag `is_re_engaged=true`
- Call `generateReEngagedInsight()` if re-engaged
- Insert into `speed_to_lead` table
- Call `sendWebsiteSignupAlert()`
- Broadcast to Supabase realtime

### Step 3: Slack Alert Function
**File:** `src/services/slack.js`

Add `sendWebsiteSignupAlert(lead, isReEngaged, previousHistory)`:
- 🔴 Red alert for re-engaged (THEY'RE BACK!)
- 🟠 Orange alert for new signup
- Include:
  - Lead name, company, phone
  - "Signed up X seconds ago"
  - Previous history if re-engaged
  - Direct call link
  - "5 MIN WINDOW - 10x conversion rate"

### Step 4: AI Re-Engaged Insight
**File:** `src/services/ai.js`

Add `generateReEngagedInsight(lead, history)`:
- Analyzes why they might be back
- Looks at previous objections
- Suggests talking points
- Returns short insight string

### Step 5: Realtime Event Broadcasting
**File:** `admin/src/context/RealtimeContext.jsx`

Add `website_signup` event type:
- Listen for INSERT on leads where source='website'
- Emit with full lead data + timing
- Play alert sound (different tone)

### Step 6: SpeedToLead Component
**File:** `admin/src/components/SpeedToLead.jsx`

Fullscreen/modal alert showing:
- "NEW WEBSITE SIGNUP!"
- Lead name, company
- Live countdown: "Signed up 2m 34s ago"
- Conversion stat: "87% if called within 5 mins"
- Previous history (if re-engaged)
- AI insight
- Giant CALL NOW button
- Dismiss button (tracks declined)

### Step 7: Dashboard Integration
**File:** `admin/src/pages/Dashboard.jsx`

- Subscribe to `website_signup` events
- Show SpeedToLead modal when event fires
- Track time from signup to call made

### Step 8: Tracking & Metrics
**File:** `src/routes/dashboard.js`

Add to stats endpoint:
- Average time to first contact (today/week)
- Conversion rate by response time buckets
- Website signups today

---

## API Specification

### POST /api/webhooks/website-signup

**Headers:**
```
X-Webhook-Key: [configured key]
Content-Type: application/json
```

**Body:**
```json
{
  "name": "John Smith",
  "email": "john@company.com",
  "phone": "0412345678",
  "company": "Smith Construction",
  "message": "Looking for workers for my next project",
  "source": "homepage_form",
  "utm_source": "google",
  "utm_campaign": "contractors"
}
```

**Response (Success):**
```json
{
  "success": true,
  "lead_id": "uuid",
  "is_new": true,
  "is_re_engaged": false,
  "score": 70,
  "message": "Lead created, alerts sent"
}
```

**Response (Re-engaged):**
```json
{
  "success": true,
  "lead_id": "uuid",
  "is_new": false,
  "is_re_engaged": true,
  "previous_score": 45,
  "new_score": 95,
  "ai_insight": "Previously objected on price 3 months ago. Market rates have increased - good time to re-pitch.",
  "message": "Re-engaged lead updated, URGENT alerts sent"
}
```

---

## Files to Create/Modify

| File | Action |
|------|--------|
| `supabase/website-signup-migration.sql` | CREATE |
| `src/routes/webhooks.js` | ADD endpoint |
| `src/services/slack.js` | ADD `sendWebsiteSignupAlert()` |
| `src/services/ai.js` | ADD `generateReEngagedInsight()` |
| `admin/src/context/RealtimeContext.jsx` | ADD event listener |
| `admin/src/components/SpeedToLead.jsx` | CREATE |
| `admin/src/pages/Dashboard.jsx` | ADD modal trigger |
| `src/routes/dashboard.js` | ADD speed metrics |

---

## Verification Checklist

- [ ] Webhook endpoint responds to POST with valid key
- [ ] New signup creates lead with score 70
- [ ] Existing lead gets +50 boost and re-engaged flag
- [ ] Slack alert fires within 2 seconds
- [ ] Dashboard shows SpeedToLead modal
- [ ] Countdown timer works accurately
- [ ] CALL NOW button initiates call
- [ ] speed_to_lead table records timing
- [ ] Metrics show up in dashboard stats

---

## Configuration Required

Add to Railway environment:
```
WEBSITE_WEBHOOK_KEY=your-secure-key-here
```

Website form must POST to:
```
https://rateright-growth-production.up.railway.app/api/webhooks/website-signup
```

With header:
```
X-Webhook-Key: your-secure-key-here
```

---

## Progress

- [x] Step 1: Database migration (SQL created, pending user to run)
- [x] Step 2: Webhook endpoint (POST /api/webhooks/website-signup)
- [x] Step 3: Slack alert function (sendWebsiteSignupAlert)
- [x] Step 4: AI re-engaged insight (generateReEngagedInsight)
- [x] Step 5: Realtime event broadcasting (notifications channel)
- [x] Step 6: SpeedToLead component (fullscreen modal with countdown)
- [x] Step 7: Dashboard integration (SpeedToLead added to App.jsx)
- [x] Step 8: Tracking & metrics (speedToLead in dashboard stats)
