# Chatbot Onboarding — Production Deployment Plan

## Overview

```
User clicks ad → Landing page → Quiz (19 questions) → Email captured → Results → CTA
                                                                                  ↓
                                                              "Unlock My Personalized Plan"
                                                                                  ↓
                                                              Razorpay paywall → Payment → App deep link (auto-logged in)
```

**Razorpay link:** `https://program.quitsure.app/v3/eng/direct?link-source=chatbot-onboarding&program=3`

**India-only launch.** No exact pricing quoted by Quira — Razorpay page handles that with web-exclusive discount.

The chatbot needs to do 3 things at the end:
1. **Save the quiz data** (for analytics + remarketing)
2. **Redirect to Razorpay paywall** (same flow as V3 onboarding)
3. **After payment, user lands in app** (auto-logged in, program pre-assigned)

---

## 1. New DB Table — `tbl_ChatbotOnboarding`

Stores raw quiz data. One row per completed quiz. No PII in this table.

```sql
CREATE TABLE tbl_ChatbotOnboarding (
  id INT AUTO_INCREMENT PRIMARY KEY,
  iUserID INT NULL,                    -- linked after user creation, NULL if abandoned
  vSmokerStatus VARCHAR(20),           -- regular/vaper/occasional/quit_recent
  bIsVaper TINYINT DEFAULT 0,
  vAgeRange VARCHAR(10),               -- '15-24', '25-34', '35-50', '50+'
  vCoreValues TEXT,                    -- JSON array: ["family","health"]
  vYearsSmokingLabel VARCHAR(50),
  iCigsPerDay INT,
  vLikesAboutSmoking TEXT,             -- JSON array
  vDislikesAboutSmoking TEXT,          -- JSON array
  vTriggers TEXT,                      -- JSON array
  iFirstCigMinutes INT,
  vCurrency VARCHAR(10),
  decPricePerCig DECIMAL(10,2),
  decMonthlySavings DECIMAL(10,2),
  vDenialPatterns TEXT,                -- JSON array
  iDenialCount INT,
  iPastAttempts INT,
  vRelapseTriggers TEXT,               -- JSON array
  vMethodsTried TEXT,                  -- JSON array
  vDeeperWhys TEXT,                    -- JSON array
  vBiggestFear VARCHAR(50),
  vFutureVision TEXT,
  vCommitment VARCHAR(20),
  iReadiness INT,
  vSmokerType VARCHAR(20),            -- stress/social/habitual/emotional/reward/identity
  iSuccessProbability INT,
  vProgram VARCHAR(20),               -- six_day
  vQuitDate VARCHAR(50),
  vPersonalLetter TEXT,               -- LLM-generated letter (for email drip)
  vDeviceType VARCHAR(20),            -- detected from user agent
  vCountry VARCHAR(50),               -- detected from timezone
  vSource VARCHAR(500),               -- UTM params from ad
  dDateCreated DATETIME DEFAULT NOW(),
  bCompleted TINYINT DEFAULT 0,       -- 1 = reached CTA, 0 = abandoned
  INDEX idx_created (dDateCreated),
  INDEX idx_type (vSmokerType),
  INDEX idx_user (iUserID)
);
```

**PII (name + email)** stored separately in DB2:
```sql
-- In DB2 (PII database)
INSERT INTO tbl_UserInfo (iUserID, vEmail, vName) VALUES (?, ?, ?)
```

Same pattern as API 1 (sociallogin) — main data in QuitSure_Production, PII in DB2.

---

## 2. What `/api/complete` Does

When user clicks "Unlock My Personalized Plan":

```
/api/complete (Python endpoint)                Frontend (browser)
      ↓                                              ↓
  1. INSERT into tbl_ChatbotOnboarding          2. Redirect to Razorpay:
     (full quiz data, no PII)                      program.quitsure.app/v3/eng/direct
      ↓                                            ?link-source=chatbot-onboarding
  (runs async — doesn't block redirect)            &program=3
```

**Note:** Steps 1 and 2 happen in parallel. The `/api/complete` POST fires but doesn't wait for a response — the user is immediately redirected to Razorpay. The Razorpay page (V3 flow) handles user creation, payment, and app deep linking — same as it does for the existing V3 onboarding.

**Future enhancement:** Pass quiz data (smoker type, email, name) to the Razorpay page via URL params or session so the user doesn't have to re-enter anything. Requires BE team coordination.

---

## 3. User Creation & Payment Flow

**User creation is handled by the existing Razorpay/V3 flow** — same as current V3 onboarding. The chatbot just redirects to it.

The chatbot's `/api/complete` only saves quiz data to `tbl_ChatbotOnboarding`. It does NOT create users or process payments.

**link-source=chatbot-onboarding** in the Razorpay URL lets us track which users came from the chatbot funnel vs regular V3 onboarding.

**Future: Pre-fill Razorpay page with chatbot data**
If we can pass email/name/program to the Razorpay page (via URL params or session), users won't re-enter info. Requires BE team to support receiving these params on the V3 payment page.

---

## 4. Test vs Production Environments

|  | Test | Production |
|---|------|------------|
| **Chatbot URL** | `localhost:8080` or `test-tweb.quitsure.app` | `tweb.quitsure.app` |
| **Gemini API** | Same key (free tier fine for testing) | Same key or dedicated prod key |
| **DB writes** | Direct to test DB (we have write access) | Via PHP APIs (they handle multi-table writes) |
| **PHP API base** | `https://test-api.quitsure.app` (if exists) | `https://api.quitsure.app` |
| **Config** | `.env`: `ENV=test`, `DB_HOST=test-db...` | `.env`: `ENV=production`, `API_BASE=api...` |
| **Behavior** | Writes to `tbl_ChatbotOnboarding` in test DB. Skips PHP API calls. | Writes to chatbot table + calls PHP APIs to create real users. |

---

## 5. Client-Side Pixel Events

Fire to BOTH Google Analytics (gtag) and Meta Pixel (fbq). These track drop-offs — if user leaves, the next event never fires.

| Event Name | Trigger | Type |
|------------|---------|------|
| `quiz_start` | User clicks "Start My Assessment" | Engagement |
| `quiz_name_entered` | Completed Q1 (name) | Engagement |
| `quiz_smoker_status` | Completed Q2 (with value: regular/vaper/occasional) | Engagement |
| `quiz_values_selected` | Completed Q5 (values) | Engagement |
| `quiz_cost_revealed` | Saw the cost card (Reveal #1) | Engagement |
| `quiz_denial_revealed` | Saw denial patterns (Reveal #2) | Engagement |
| `quiz_methods_revealed` | Saw method comparison (Reveal #3) | Engagement |
| `quiz_type_teased` | Saw "you could be X or Y" type tease | Engagement |
| `quiz_email_captured` | Entered email | **Lead (Meta)** |
| `quiz_results_viewed` | Saw smoker type result | Engagement |
| `quiz_cta_clicked` | Clicked "Unlock My Personalized Plan" | **Conversion (Meta + Google)** |

**Implementation:** `gtag('event', ...)` and `fbq('track', ...)` at each milestone.

**Requirements:** GA4 Measurement ID + Meta Pixel ID from marketing team.

---

## 6. What BE Team Needs to Do (BLOCKERS)

**Status: Waiting on BE team. We cannot go to production until these are done.**

1. **CREATE 2 new tables** — `tbl_ChatbotClickstream` + `tbl_ChatbotOnboarding` (schemas in IMPLEMENTATION_SPEC.md). We have INSERT but not CREATE TABLE permission.
2. **CREATE `tbl_WebLoginDiscount` row** for `vLinkSource = 'chatbot-onboarding'` with 20% discount (SIGNUPOFFER) config. Currently no row exists.
3. **Verify email hash format** — confirm `SHA256(lowercase(trim(email)))` matches what Razorpay success page uses for `vHashedEmail`. Critical to avoid duplicate users.
4. **Confirm vEUserID generation** — Suresh provided PHP function. We need to replicate in Python. Need confirmation our implementation matches.
5. **OTP service for existing users** — when an email already exists in tbl_Users, we send OTP to verify identity. Need: email sending service details (Postmark? SendGrid?) and `tbl_Login` OTP flow confirmation.

**Already confirmed by BE team:**
- ACTIVE3DAYID for Program 3 = 1
- Email hash = SHA256(lowercase(trim(email))) ✅
- Existing user handling = UPDATE not duplicate ✅
- bVerified not used ✅
- tbl_UserAppActivity = just iUserId row ✅
- tbl_UserInfo needs vAPIToken (unhashed access token) ✅
- vOnBoardPlatform = web-chatbot-{os}-{browser} ✅
- bTransactSubscribed = 1 ✅
- tbl_UserProfile needs iPayMode=1, vPayCurrency='₹' ✅
- Step 6 updates: dProgramStartedOn=NOW(), vOnBoardLocation=null ✅

---

## 7. What Marketing Team Needs to Provide

1. **GA4 Measurement ID** (G-XXXXXXXXXX)
2. **Meta Pixel ID** (for fbq)
3. **UTM parameter format** — what params will ads use? (utm_source, utm_medium, utm_campaign, etc.)
4. **Privacy policy page URL** — needed for consent on email gate
5. **Deep link / app store URL format** — what URL does the CTA redirect to?

---

## 8. What Claude Builds

| Task | Dependencies | Estimated Time |
|------|-------------|----------------|
| Build `/api/complete` with DB write to `tbl_ChatbotOnboarding` | Test DB write access | 1 hr |
| Add pixel events (gtag + fbq) to frontend | GA4 ID + Meta Pixel ID | 1 hr |
| Add UTM param capture from ad URLs | None | 30 min |
| Privacy policy link + consent on email gate | Legal text / URL | 15 min |
| ~~Wire CTA to Razorpay~~ | ~~None~~ | ✅ Done |

---

## 9. Execution Order

| Step | Who | What | Blocked by |
|------|-----|------|------------|
| 1 | **Neel** | Share this plan with BE team + Ram | — |
| 2 | **BE team** | Create table + confirm API approach + share test credentials | Step 1 |
| 3 | **Marketing** | Share GA4 ID + Meta Pixel ID + UTM format | Step 1 |
| 4 | **Claude** | Build `/api/complete` + pixel events + UTM capture | Steps 2, 3 |
| 5 | **Neel + Claude** | Test full flow on test environment | Step 4 |
| 6 | **BE team** | Pull to production + DNS/server config | Step 5 |
| 7 | **Marketing** | Launch ads pointing to `tweb.quitsure.app/chatbot-onboarding` | Step 6 |

---

## 10. Post-Launch

| Task | Priority | Who |
|------|----------|-----|
| Monitor drop-off analytics (which questions lose people) | High | Neel |
| Email drip sequence (send personalized profile to captured emails) | Medium | Neel + Marketing |
| A/B test email gate position (early vs late) | Medium | Neel |
| Replace fabricated testimonials with real Play Store reviews | Medium | Neel |
| Multi-language support (Hindi, Spanish, French) | Low | Claude + BE |
| Session resume (pick up where you left off) | Low | Claude |
