# LeadPilot — Core User Journeys (16 Scenarios)

**Document Version:** 1.0.0 (Phase 1 Scope Lock)  
**Status:** Approved  

---

## Journey Index

1. [First-Time Onboarding](#journey-1-first-time-onboarding)
2. [Manual Lead Creation](#journey-2-manual-lead-creation)
3. [Website Form Lead Capture](#journey-3-website-form-lead-capture)
4. [REST API Lead Capture](#journey-4-rest-api-lead-capture)
5. [Inbound Webhook Lead Capture](#journey-5-inbound-webhook-lead-capture)
6. [CSV Bulk Lead Import](#journey-6-csv-bulk-lead-import)
7. [AI Lead Qualification & Scoring](#journey-7-ai-lead-qualification--scoring)
8. [Lead First Response & Templated Outreach](#journey-8-lead-first-response--templated-outreach)
9. [One-Time Follow-up Scheduling](#journey-9-one-time-follow-up-scheduling)
10. [Automated Follow-up Sequence Execution](#journey-10-automated-follow-up-sequence-execution)
11. [Pipeline Progression (Kanban / List)](#journey-11-pipeline-progression-kanban--list)
12. [Marking a Lead as Won](#journey-12-marking-a-lead-as-won)
13. [Marking a Lead as Lost (Lost Reason Protocol)](#journey-13-marking-a-lead-as-lost-lost-reason-protocol)
14. ["No Lead Left Behind" Attention Hub Triage](#journey-14-no-lead-left-behind-attention-hub-triage)
15. [Lead Assignment & Reassignment](#journey-15-lead-assignment--reassignment)
16. [Lead Recovery & Revenue Attribution](#journey-16-lead-recovery--revenue-attribution)

---

### Journey 1: First-Time Onboarding
* **Goal:** A new customer sets up their business workspace and captures their first lead in under 5 minutes.
* **Trigger:** User completes registration / email verification.
* **Steps:**
  1. User enters Workspace Name (e.g. "Apex Digital Studio") and selects Primary Business Currency & Timezone.
  2. Wizard displays instant Lead Capture URL and code snippet for website.
  3. User clicks "Add Sample Lead" or enters their first real enquiry.
  4. LeadPilot immediately runs qualification and opens the Lead Detail view with recommended next action.
* **System Response:** Workspace initialized, default pipeline stages seeded, sample follow-up sequence enabled, demo lead qualified.
* **Success State:** User reaches the active inbox with 1 qualified lead and sees "Next Step: Send Intro Template".
* **Failure State:** Incomplete setup redirects back to the missing configuration step with inline validation errors.
* **Edge Cases:** User skips sample lead; system opens clean empty state with prominent "Copy Capture URL" button.

---

### Journey 2: Manual Lead Creation
* **Goal:** A sales rep quickly logs an inbound phone call or walk-in enquiry.
* **Trigger:** Rep clicks `+ New Lead` (or presses shortcut `N`).
* **Steps:**
  1. Modal opens with focused input fields: First Name, Last Name, Email, Phone, Company, Estimated Value, and Inquiry Notes.
  2. Rep fills in mandatory fields (Name + at least Email OR Phone) and submits.
* **System Response:** Validates data, performs instant deduplication check, inserts lead record, queues AI qualification job, and navigates to Lead Detail or refreshes table.
* **Success State:** Lead created with `stage = 'new'`, `status = 'active'`, activity log entry recorded.
* **Failure State:** Submission fails with highlighted field errors if neither email nor phone is provided.
* **Edge Cases:** Email matches an existing lead in the workspace; system displays "Possible Duplicate Detected" alert with a link to merge or view existing record.

---

### Journey 3: Website Form Lead Capture
* **Goal:** A prospective customer submits an inquiry on the client's public website.
* **Trigger:** Public user submits an HTML form targeting `/api/v1/capture/form/{workspace_uuid}`.
* **Steps:**
  1. Form POSTs payload (name, email, phone, message, honeypot field).
  2. Backend inspects CORS, verifies honeypot is empty, validates email/phone format.
  3. System creates lead record with source `Website Form` and metadata (referrer URL, IP, user-agent).
* **System Response:** Returns JSON `{ success: true, message: "Enquiry received" }` (or redirects to configured thank-you URL). Dispatches email/in-app alert to workspace team. Dispatches async AI qualification job.
* **Success State:** Lead appears at the top of the workspace inbox in $< 1\text{ second}$.
* **Failure State:** Honeypot triggered or rate limit exceeded; returns HTTP 422/429 without database insertion.
* **Edge Cases:** Incomplete payload (e.g. only name); system creates lead with available data and tags `Incomplete Data`.

---

### Journey 4: REST API Lead Capture
* **Goal:** Third-party system (custom portal, mobile app) pushes leads via authenticated API.
* **Trigger:** External server sends `POST /api/v1/leads` with `Bearer <api_token>`.
* **Steps:**
  1. Request arrives with JSON payload including `first_name`, `email`, `phone`, `value`, `source`, `tags`, and `custom_notes`.
  2. System verifies SHA-256 hashed API token and tenant authorization.
  3. System parses payload, checks idempotency key (if provided), and saves lead.
* **System Response:** Returns HTTP 201 Created with JSON representation of the new lead entity and assigned ID.
* **Success State:** Lead inserted cleanly into the matching workspace; webhooks/AI queued.
* **Failure State:** Invalid or expired API token returns HTTP 401 Unauthorized. Validation error returns HTTP 422 Unprocessable Entity.
* **Edge Cases:** Client sends the same request twice with matching `Idempotency-Key` within 24 hours; system returns original HTTP 201 response without creating a duplicate record.

---

### Journey 5: Inbound Webhook Lead Capture
* **Goal:** Ingest leads from external forms (Typeform, Webflow, Jotform) via flexible payload mapping.
* **Trigger:** Webhook POST received at `/api/v1/webhooks/inbound/{webhook_uuid}`.
* **Steps:**
  1. System receives raw nested JSON payload.
  2. Webhook mapper translates foreign keys (e.g. `answers[0].text` or `client_email`) according to the workspace's configured mapping schema.
  3. Lead record is populated and stored with source `Webhook: <Source Name>`.
* **System Response:** Returns HTTP 200 OK immediately. Dispatches background worker for mapping & ingestion.
* **Success State:** Lead created with all mapped fields correctly mapped into lead profile.
* **Failure State:** Unparseable JSON or corrupted payload logged in Webhook Ingest Log with status `Failed` and raw payload preserved for debugging.
* **Edge Cases:** Webhook source changes payload structure; lead is created with raw data stored in notes and marked `Unmapped Fields`.

---

### Journey 6: CSV Bulk Lead Import
* **Goal:** User imports a historical list of 250 leads from a spreadsheet.
* **Trigger:** User navigates to Settings -> Import and uploads a `.csv` file.
* **Steps:**
  1. User uploads CSV; system displays first 3 rows for preview.
  2. User maps CSV headers (e.g. "Full Name", "E-mail Address", "Budget") to LeadPilot fields.
  3. User selects duplicate resolution policy (`Skip Duplicates`, `Update Existing`, or `Import as Separate`).
  4. User clicks "Start Import".
* **System Response:** File dispatched to background queue. Progress bar displays percentage complete.
* **Success State:** All valid rows imported; completion summary displayed (e.g., "242 leads imported, 8 skipped due to invalid email").
* **Failure State:** Corrupted CSV or missing delimiter detected; import aborted with line-specific error report.
* **Edge Cases:** File contains 5,000+ rows; system chunks import in batches of 250 to ensure memory limits and DB timeouts are never breached.

---

### Journey 7: AI Lead Qualification & Scoring
* **Goal:** System automatically determines lead quality, buying intent, and urgency upon ingestion.
* **Trigger:** Async event `LeadCreated` fires.
* **Steps:**
  1. AI Worker constructs prompt with lead inquiry text, budget, company info, and workspace business profile.
  2. Request dispatched to LLM provider with strict JSON output schema.
  3. Worker receives and validates structured output: `score` (0-100), `temperature` (`HOT`/`WARM`/`COLD`), `intent`, `urgency` (`LOW`/`MED`/`HIGH`), `fit_summary`, `reason`, `recommended_action`.
  4. System updates lead record and inserts `ai_intelligence` record.
* **System Response:** UI updates dynamically via Alpine.js polling/live-update showing badge (e.g. `HOT 92/100`) and recommended action chip.
* **Success State:** Lead is prioritized in the inbox with clear rationale (e.g. "High Intent: Explicit $15k budget, urgent 2-week timeline").
* **Failure State (AI Down/Throttled):** Worker falls back to rule-based heuristic (checks for presence of budget keywords, business email domains) and flags `ai_status = 'fallback_rules'`. Lead ingestion is NEVER blocked.
* **Edge Cases:** Inquiry is in a non-English language; prompt specifies translation of intent summary to workspace default language while preserving raw text.

---

### Journey 8: Lead First Response & Templated Outreach
* **Goal:** Sales rep reviews a new lead and sends a customized introductory email/message.
* **Trigger:** Rep opens Lead Detail from the "Needs Attention" queue.
* **Steps:**
  1. Rep reads AI intelligence card and inquiry context.
  2. Rep clicks "Use Template" and selects "Agency Discovery Intro".
  3. Modal generates message with merged tags (`Hello Rajesh...`).
  4. Rep copies message to email/WhatsApp or dispatches it and clicks "Mark Contacted".
* **System Response:** Pipeline stage advances from `New` to `Contacted`. First response time metric is computed and locked. Sequence timer begins.
* **Success State:** Lead removed from "Needs Response" queue; activity recorded: "Contacted via Discovery Intro template".
* **Failure State:** Rep tries to mark contacted without selecting an outreach method; system prompts for quick touchpoint logging.
* **Edge Cases:** Rep responds in under 3 minutes; system records record response time in dashboard telemetry.

---

### Journey 9: One-Time Follow-up Scheduling
* **Goal:** Rep agrees on a specific callback date/time with a prospective client.
* **Trigger:** Rep clicks "Schedule Follow-up" in the Lead Detail view.
* **Steps:**
  1. Rep selects Date, Time, and enters a brief reminder note ("Call back after they review proposal with partner").
  2. Rep selects priority flag (`Normal` or `High`).
  3. Rep clicks "Save Follow-up".
* **System Response:** Inserts `follow_ups` record with status `scheduled`. Updates lead `next_follow_up_at` timestamp.
* **Success State:** Follow-up badge appears on the lead card; notification job scheduled for the designated timestamp.
* **Failure State:** Setting a timestamp in the past displays an immediate validation warning.
* **Edge Cases:** Existing scheduled follow-up is already active; system prompts to reschedule or complete the prior one.

---

### Journey 10: Automated Follow-up Sequence Execution
* **Goal:** Keep non-responsive leads engaged across a 7-day window without manual tracking.
* **Trigger:** Lead stage changes to `Contacted` or user manually attaches "Default Agency Follow-up Sequence".
* **Steps:**
  1. System schedules Sequence Step 1 (Day 1 Nudge).
  2. When timestamp expires, LeadPilot surfaces an attention item: "Follow-up Due: Day 1 Nudge for Alex".
  3. Rep executes nudge and clicks "Done" (or automated step dispatches).
  4. System schedules Step 2 (Day 3 Value Add) and Step 3 (Day 7 Break-up).
* **System Response:** Each step creates an audit trail entry. If lead replies or status changes to `Won`/`Lost`, sequence status instantly switches to `Paused` / `Completed`.
* **Success State:** Lead either re-engages and books a call or completes sequence without slipping through the cracks unnoticed.
* **Failure State:** Lead marked Lost while sequence is active; system guarantees no further sequence notifications are generated.
* **Edge Cases:** User manually snoozes a sequence step; subsequent steps shift their target dates accordingly.

---

### Journey 11: Pipeline Progression (Kanban / List)
* **Goal:** Move a lead across sales stages as conversations mature.
* **Trigger:** Rep drags lead card from `Contacted` to `Proposal` on the Kanban board (or changes stage dropdown).
* **Steps:**
  1. Card is dropped into the `Proposal` column.
  2. System prompts for estimated deal value if currently empty.
  3. Rep enters deal value ($5,000) and confirms.
* **System Response:** Updates `pipeline_stage = 'proposal'`, updates column financial aggregates, logs activity "Stage changed from Contacted to Proposal by Ananya".
* **Success State:** Board UI updates smoothly; deal value is added to the active proposal pipeline total.
* **Failure State:** Network disconnect during drag-and-drop triggers an error toast and reverts the card to its original position.
* **Edge Cases:** Dragging backwards (e.g. `Proposal` back to `Qualified`); permitted with activity log recording regression.

---

### Journey 12: Marking a Lead as Won
* **Goal:** Close a successful deal, record revenue, and celebrate the win.
* **Trigger:** Rep drops lead into `Won` stage or clicks "Mark as Won" in Lead Detail.
* **Steps:**
  1. Modal opens confirming Final Closed Deal Value and optional victory notes.
  2. Rep submits modal.
* **System Response:** Sets `status = 'won'`, `pipeline_stage = 'won'`, `won_at = NOW()`. Cancels all pending follow-ups and sequences. Updates dashboard Won Revenue metrics.
* **Success State:** Lead displays green `WON` banner; celebratory visual micro-state in UI; revenue counted in monthly metrics.
* **Failure State:** Missing deal value prompts user to provide an estimate ($0 allowed if explicitly confirmed).
* **Edge Cases:** Lead was previously marked Lost and is now resurrected as Won; system logs "Resurrected & Won" and recalculates conversion metrics.

---

### Journey 13: Marking a Lead as Lost (Lost Reason Protocol)
* **Goal:** Close an unsuccessful deal with structured data to learn why deals are lost.
* **Trigger:** Rep drags card to `Lost` dropzone or clicks "Mark as Lost".
* **Steps:**
  1. Mandatory Lost Reason Modal opens.
  2. Rep selects reason from standard dropdown: `Price`, `Competitor`, `No Response`, `Not Qualified`, `Timing`, `Requirement Changed`, `Other`.
  3. Rep enters optional contextual notes ("Chose local vendor who offered 20% discount").
  4. Rep clicks "Confirm Lost".
* **System Response:** Sets `status = 'lost'`, `pipeline_stage = 'lost'`, `lost_reason`, `lost_at = NOW()`. Cancels active follow-up sequences. Removes lead from active attention queues.
* **Success State:** Lead moved to Lost archive; reason aggregated in Lost Analytics breakdown.
* **Failure State:** Attempting to bypass modal prevents status mutation (reason is strictly required).
* **Edge Cases:** Prospect marked Lost due to "Timing" contacts back 3 months later; inbound message transitions status back to `Active` with note "Re-engaged prospect".

---

### Journey 14: "No Lead Left Behind" Attention Hub Triage
* **Goal:** Rep or business owner spends 5 minutes clearing all urgent and neglected leads.
* **Trigger:** User logs in and clicks the prominent "Needs Attention" badge on the sidebar.
* **Steps:**
  1. Hub displays categorized attention cards:
     * *Response Overdue:* 2 new leads uncontacted for $> 2$ hours.
     * *Follow-up Overdue:* 4 scheduled follow-ups past their due timestamp.
     * *Stale Proposal:* 1 proposal with zero activity for 6 days.
  2. User processes Card 1: clicks "Quick Template", copies message, marks "Contacted" -> Card disappears.
  3. User processes Card 2: clicks "Reschedule" -> selects tomorrow -> Card disappears.
* **System Response:** Dynamic counter decreases as items are resolved; updates "Leads Cleared Today" badge.
* **Success State:** Hub reaches zero items; displays "Inbox Zero: All leads are attended to!".
* **Failure State:** Action fails due to permission change; shows friendly warning and refreshes card state.
* **Edge Cases:** New urgent hot lead arrives while user is on screen; real-time event adds card to top of list with subtle highlight.

---

### Journey 15: Lead Assignment & Reassignment
* **Goal:** Manager reassigns uncontacted leads from an absent team member to an active rep.
* **Trigger:** Manager notices uncontacted leads assigned to "Sarah (On Leave)".
* **Steps:**
  1. Manager selects leads via bulk checkboxes in the Lead Table.
  2. Manager clicks "Assign To" -> selects "Alex".
  3. Manager clicks "Apply".
* **System Response:** Updates `assigned_user_id = Alex.id` on selected records. Logs reassignment activity on each lead. Sends in-app/email notification to Alex.
* **Success State:** Leads appear in Alex's "My Leads" filter and personal attention queue.
* **Failure State:** Selected user does not have permission in workspace; reassignment rejected.
* **Edge Cases:** Assigning to "Unassigned"; removes user link and places lead in the team-wide triage pool.

---

### Journey 16: Lead Recovery & Revenue Attribution
* **Goal:** A neglected or stalled deal is rescued and closed, proving LeadPilot's commercial ROI.
* **Trigger:** Lead has been neglected in "Stale Proposal" for 7 days.
* **Steps:**
  1. LeadPilot surfaces the lead with alert: *"Stale Proposal: Marcus hasn't heard from you in 7 days. Recommended Action: Send Stall Breaker Template."*
  2. Rep clicks 1-click action: "Send Stall Breaker Template".
  3. Prospect responds 4 hours later: "Sorry for the delay, let's proceed!".
  4. Rep moves lead to `Won` ($8,500).
* **System Response:** System verifies conditions: Lead was in `needs_attention` state $\ge 48\text{h}$, attention action was triggered, lead transitioned to `Won`. System tags lead as `is_recovered = true` and attributes $8,500 to "Recovered Revenue".
* **Success State:** Dashboard KPI "Leads Recovered" increments by 1; "Recovered Revenue" increases by $8,500.
* **Failure State:** Normal deals closed on regular schedules are NOT tagged as recovered (prevents false metric inflation).
* **Edge Cases:** Lead was touched manually outside LeadPilot before recovery action; system checks timestamp proximity to prevent false attribution.
