# Booking Flow Integration - Lead to Dashboard

## 🔄 Complete Pipeline: Web Form → Dashboard

### End-to-End Workflow

```
[Website Contact Form]
         ↓
[Calendly / Typeform Embed]
         ↓
[Webhook → n8n]
         ↓
[n8n Processing]
    ↙         ↘
[CRM Update]  [Dashboard Card]
         ↓
[Stripe Proposal]
         ↓
[Payment → Metabase MRR]
         ↓
[Project Creation]
         ↓
[Ongoing Tracking]
```

---

## Step 1: Contact Form Configuration

### Astro Contact Form
```html
<!-- src/components/ContactForm.astro -->
<form 
    action="https://startuplx.typeform.com/to/main" 
    method="POST"
    class="max-w-md mx-auto"
>
    <input 
        type="text" 
        name="name" 
        placeholder="Your Name" 
        required
        class="w-full mb-4 p-3 border rounded-lg"
    />
    <input 
        type="email" 
        name="email" 
        placeholder="Your Email" 
        required
        class="w-full mb-4 p-3 border rounded-lg"
    />
    <textarea 
        name="project_details" 
        placeholder="Tell me about your project..." 
        class="w-full mb-4 p-3 border rounded-lg h-32"
    ></textarea>
    <button 
        type="submit"
        class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-semibold"
    >
        Book Free System Audit
    </button>
</form>
```

### Typeform Webhook Setup
1. Go to Typeform Admin → Webhooks
2. Add webhook: `http://your-server:3000/webhook/typeform`
3. Select events: "New Entry"
4. Test webhook connection

---

## Step 2: n8n Workflow Configuration

### Main Lead Processing Flow
```yaml
# n8n Workflow: Lead → Dashboard

Triggers:
  - Webhook: /webhook/typeform (new form entry)
  - Schedule: Every 5 minutes (catchup)

Actions:
  1. Set Headers
  2. Parse JSON
  3. IF: Score ≥ 50 (qualification)
      ├─ Yes → CRM: Create Lead
      │        → Slack: New Qualified Lead
      │        → Email: Auto-responder
      │        → Dashboard: Increment lead count
      └─ No → Email: Out of scope
               → CRM: Status = "unqualified"

4. Set Variable: lead_score
5. IF: Score ≥ 80 (hot lead)
      ├─ Yes → CRM: Priority = "High"
      │        → Slack: 🔥 HOT LEAD
      │        → SMS: Notify founder
      └─ No → Continue

6. Dashboard Update (PostgreSQL)
   Table: dashboard_metrics
   Query: UPDATE MRR POTENTIAL
```

### n8n Nodes Configuration

#### Node 1: Webhook Trigger
```
Type: Webhook
Path: /webhook/typeform
Response Mode: Response Node
Response Code: 200
Response Data: {"status": "received"}
```

#### Node 2: Set Variable
```
Name: Calculate Lead Score
Values:
  - name: lead_score
    value: "{{$json.budget / 1000 + $json.urgency}}"
```

#### Node 3: CRM Create Lead (Postgres)
```sql
INSERT INTO leads (
    name, email, company, budget, source, 
    status, created_at, lead_score
) VALUES (
    '{{$json.name}}',
    '{{$json.email}}', 
    '{{$json.company}}',
    {{$json.budget}},
    'website',
    'new',
    NOW(),
    {{$node["Set Variable"].json.lead_score}}
) RETURNING id;
```

#### Node 4: Dashboard Update
```sql
-- Insert lead count for funnel tracking
INSERT INTO dashboard_metrics (metric, value, date)
VALUES ('leads_today', 1, CURRENT_DATE)
ON CONFLICT (metric, date) 
DO UPDATE SET value = dashboard_metrics.value + 1;
```

#### Node 5: Email Auto-responder
```
Template: welcome-to-startuplx
Variables:
  - name: {{$json.name}}
  - company: {{$json.company}}
  - booking_url: https://calendly.com/startuplx/15min
```

---

## Step 3: Stripe Integration

### Payment Webhook Flow
```yaml
# n8n Workflow: Payment → Dashboard

Triggers:
  - Stripe Webhook: invoice.payment_succeeded
  - Stripe Webhook: customer.subscription.created

Actions:
  1. Get Invoice Details
  2. Find Related Client
  3. Update Subscription Status
  4. Update MRR in Dashboard
  5. Create Project Record
  6. Send Confirmation Email
```

### Stripe Webhook Node
```
Event Types:
  - invoice.payment_succeeded
  - customer.subscription.created
  - customer.subscription.updated
  - customer.subscription.deleted

Webhook URL: https://your-server.com/webhook/stripe
Secret: whsec_... (from Stripe Dashboard)
```

### Payment Processing Query
```sql
-- Update MRR after payment
INSERT INTO mrr_tracking (date, amount, source)
VALUES (
    CURRENT_DATE,
    {{$json.data.amount_paid}},
    'outreach-project'
) ON CONFLICT (date, source) 
DO UPDATE SET amount = EXCLUDED.amount;
```

---

## Step 4: Metabase Dashboard Connection

### Required Database Views

```sql
-- Revenue Dashboard View
CREATE OR REPLACE VIEW revenue_dashboard AS
SELECT 
    (SELECT COALESCE(SUM(amount), 0) FROM stripe_transactions 
     WHERE status = 'paid' AND created_at >= DATE_TRUNC('month', CURRENT_DATE)) / 100.0 as mrr,
    (SELECT COALESCE(SUM(budget), 0) FROM deals 
     WHERE probability * estimated_value >= 1000 AND stage = 'proposal') / 1000.0 as pipeline,
    (SELECT COUNT(*) FROM leads WHERE created_at >= CURRENT_DATE) as new_leads_today,
    (SELECT COUNT(*) FROM projects WHERE status = 'active') as active_projects;
```

### KPI Update Triggers

```sql
-- Auto-increment lead count
CREATE OR REPLACE FUNCTION update_lead_count()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO dashboard_metrics (metric, value, date)
    VALUES ('leads_today', 1, CURRENT_DATE)
    ON CONFLICT (metric, date) 
    DO UPDATE SET value = dashboard_metrics.value + 1;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER lead_count_trigger
AFTER INSERT ON leads
FOR EACH ROW EXECUTE FUNCTION update_lead_count();
```

---

## Step 5: Testing the Full Flow

### Test Sequence

1. **Visit website** → Fill out contact form
2. **Check**: Lead appears in CRM table
3. **Check**: Lead count increments in dashboard
4. **Check**: Auto-response email sent
5. **Test**: Book call in Calendly
6. **Test**: Process test payment in Stripe
7. **Check**: Payment appears in dashboard
8. **Check**: Project created in system

### Verification Commands
```bash
# Check webhook reception
docker-compose logs n8n | grep "webhook"

# Check database entries
docker-compose exec postgres psql -U postgres -d startuplx -c "SELECT * FROM leads ORDER BY created_at DESC LIMIT 5;"

# Check metabase connection
docker-compose exec postgres pg_isready -h postgres -p 5432

# Check form submission
curl -X POST http://localhost:5678/webhook/typeform -d '{"name":"Test User","email":"test@test.com"}'
```

---

## 🔗 Integration Links

- **Website:** Available on live VPS
- **Form:** Embedded in `/contact` page  
- **Booking:** Integrated Calendly widget
- **CRM:** PostgreSQL leads table
- **Payment:** Stripe webhooks
- **Dashboard:** Metabase live at `/dashboard`
- **Automation:** n8n workflow active

---

## ✅ Ready for Live Testing

All components configured for end-to-end flow:
1. Lead captures from website
2. Qualification happens in n8n
3. Dashboard updates in real-time
4. Payments trigger further automation
5. System learns and optimizes

**Next:** Deploy to VPS and test live flow!