# LEADS FLOW WITH INVENTORY & QUESTIONNAIRE - DEEP ANALYSIS

**Document Version**: 1.0  
**Last Updated**: January 23, 2026  
**Status**: Complete Analysis

---

## Table of Contents

1. [Executive Summary](#executive-summary)
2. [System Architecture Overview](#system-architecture-overview)
3. [Data Model Relationships](#data-model-relationships)
4. [Lead Lifecycle Journey](#lead-lifecycle-journey)
5. [Questionnaire Integration Flow](#questionnaire-integration-flow)
6. [Inventory Integration Flow](#inventory-integration-flow)
7. [Complete End-to-End Workflow](#complete-end-to-end-workflow)
8. [Database Schema & Flow](#database-schema--flow)
9. [Advanced Scenarios](#advanced-scenarios)
10. [Performance & Optimization](#performance--optimization)
11. [API Endpoints & Operations](#api-endpoints--operations)

---

## Executive Summary

The system implements a sophisticated **Lead Management Pipeline** that integrates:

1. **Lead Capture** - Prospect/client information collection
2. **Dynamic Questionnaires** - Service-specific requirement gathering
3. **Inventory Management** - Item catalog with categories
4. **Intelligent Linking** - Questionnaire answers → Auto-suggested inventory
5. **Allocation System** - Reserve and commit inventory for leads
6. **Summarization** - Cost/revenue analysis and reporting

### Key Statistics

| Component | Count | Purpose |
|-----------|-------|---------|
| **Models** | 8 | Core domain entities |
| **Tables** | 8 | Database storage |
| **Relationships** | 15+ | Model interconnections |
| **Workflow States** | 8+ | Lead status pipeline |
| **Questionnaire Types** | 9 | Question input methods |

---

## System Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│                    LEAD MANAGEMENT SYSTEM                   │
└─────────────────────────────────────────────────────────────┘

                         ┌─ Lead Entry Point
                         │  (Public/Admin Form)
                         │
        ┌────────────────▼───────────────┐
        │   LEAD CREATION & TRACKING     │
        │  ┌──────────────────────────┐  │
        │  │ Basic Information        │  │
        │  │ - Company Details        │  │
        │  │ - Contact Info           │  │
        │  │ - Service Requirements   │  │
        │  │ - Assignment & Status    │  │
        │  └──────────────────────────┘  │
        └────────────┬────────────────────┘
                     │
        ┌────────────▼───────────────┐
        │ QUESTIONNAIRE COLLECTION   │
        │ ┌──────────────────────────┐
        │ │ Service-Type Templates   │
        │ │ Dynamic Questions        │
        │ │ Conditional Logic        │
        │ │ Response Storage         │
        │ └──────────────────────────┘
        └────────────┬────────────────────┘
                     │
        ┌────────────▼───────────────┐
        │ INVENTORY LINKING          │
        │ ┌──────────────────────────┐
        │ │ Answer → Item Mapping    │
        │ │ Auto-Suggestions         │
        │ │ Default Quantities       │
        │ └──────────────────────────┘
        └────────────┬────────────────────┘
                     │
        ┌────────────▼───────────────┐
        │ INVENTORY SELECTION        │
        │ ┌──────────────────────────┐
        │ │ Lead Selections          │
        │ │ Quantity & Pricing       │
        │ │ Status Workflow          │
        │ └──────────────────────────┘
        └────────────┬────────────────────┘
                     │
        ┌────────────▼───────────────┐
        │ ALLOCATION & FULFILLMENT   │
        │ ┌──────────────────────────┐
        │ │ Reserve Inventory        │
        │ │ Commit Allocations       │
        │ │ Track Delivery           │
        │ └──────────────────────────┘
        └────────────┬────────────────────┘
                     │
        ┌────────────▼───────────────┐
        │ SUMMARY & REPORTING        │
        │ ┌──────────────────────────┐
        │ │ Cost Breakdowns          │
        │ │ Revenue Projections      │
        │ │ Category Analysis        │
        │ └──────────────────────────┘
        └────────────────────────────────┘
```

---

## Data Model Relationships

### Complete Entity Relationship Diagram

```
┌──────────────────────┐
│       LEAD           │
├──────────────────────┤
│ • id (UUID, PK)      │
│ • company_name       │
│ • contact_person     │
│ • email              │
│ • mobile_number      │
│ • address, city      │
│ • service_type_id    │───────────┐
│ • guard_type         │           │
│ • tentative_count    │           │
│ • working_hours_type │           │
│ • site_type          │           │
│ • lead_source        │           │
│ • lead_status        │           │
│ • assigned_to        │           │
│ • budget_range       │           │
│ • converted_to_id    │           │
│ • tenant_id          │           │
└──────────────────────┘           │
         │                         │
         │ 1:N                     │
         ├─────────────────┐       │
         │                 │       │
    ┌────▼──────────────────────────────────────┐
    │  LEAD_QUESTIONNAIRE_RESPONSE               │
    ├──────────────────────────────────────────┤
    │ • id (UUID, PK)                           │
    │ • lead_id (FK) ◄──────┐                  │
    │ • questionnaire_question_id (FK) ──────┐ │
    │ • answer (longText)                      │ │
    │ • answer_metadata (JSON)                 │ │
    │ • tenant_id                              │ │
    │ UNIQUE(lead_id, question_id)             │ │
    └────┬──────────────────────────────────────┘ │
         │                                         │
         │ N:1                                     │
         │                              ┌──────────▼───────────────────┐
         │                              │  QUESTIONNAIRE_QUESTION      │
         │                              ├──────────────────────────────┤
         │                              │ • id (UUID, PK)              │
         │                              │ • template_id (FK) ◄──────┐  │
         │                              │ • question_text            │  │
         │                              │ • question_type (9 types)  │  │
         │                              │ • is_mandatory             │  │
         │                              │ • options (JSON)           │  │
         │                              │ • conditional_logic (JSON) │  │
         │                              │ • display_order            │  │
         │                              │ • help_text                │  │
         │                              │ • tenant_id                │  │
         │                              └──────────┬───────────────────┘
         │                                         │
         │                         ┌───────────────▼────────────────────────┐
         │                         │ QUESTIONNAIRE_TEMPLATE                 │
         │                         ├─────────────────────────────────────┤
         │                         │ • id (UUID, PK)                    │
         │                         │ • name (Template Name)             │
         │                         │ • description                      │
         │                         │ • service_type_id (FK) ◄──────┐    │
         │                         │ • is_active                    │    │
         │                         │ • tenant_id                    │    │
         │                         └────────────────────────────────────┘
         │                                         ▲
         │                                         │
         │                    ┌────────────────────┘
         │                    │ N:1
         │                    │
         │         ┌──────────┴──────────────────────────────────┐
         │         │ QUESTIONNAIRE_INVENTORY_OPTION             │
         │         ├──────────────────────────────────────────────┤
         │         │ • id (UUID, PK)                            │
         │         │ • question_id (FK) ◄──────────┐            │
         │         │ • inventory_item_id (FK) ──┐  │            │
         │         │ • default_quantity          │  │            │
         │         │ • is_optional              │  │            │
         │         │ • option_label             │  │            │
         │         │ • display_order            │  │            │
         │         │ • tenant_id                │  │            │
         │         │ UNIQUE(question_id, item_id) │ │            │
         │         └────────┬────────────────────┘  │            │
         │                  │                       │            │
         │  ┌───────────────▼──────────────────────┐│            │
         │  │  INVENTORY_ITEM                      ││            │
         │  ├──────────────────────────────────────┤│            │
         │  │ • id (UUID, PK)                      ││            │
         │  │ • category_id (FK) ──┐               ││            │
         │  │ • name               │               ││            │
         │  │ • description        │               ││            │
         │  │ • sku (UNIQUE)       │               ││            │
         │  │ • unit               │               ││            │
         │  │ • cost_price         │               ││            │
         │  │ • selling_price      │               ││            │
         │  │ • stock_quantity     │               ││            │
         │  │ • reorder_level      │               ││            │
         │  │ • is_active          │               ││            │
         │  │ • tenant_id          │               ││            │
         │  └────┬─────────────────┼───────────────┘│            │
         │       │                 │                │            │
         │       │                 └────────────┐   │            │
         │       │                              │   │            │
         │       │        ┌──────────────────────▼───▼───────────┐
         │       │        │  INVENTORY_CATEGORY                  │
         │       │        ├────────────────────────────────────┤
         │       │        │ • id (UUID, PK)                    │
         │       │        │ • name                             │
         │       │        │ • description                      │
         │       │        │ • slug (UNIQUE)                    │
         │       │        │ • is_active                        │
         │       │        │ • display_order                    │
         │       │        │ • tenant_id                        │
         │       │        └────────────────────────────────────┘
         │       │
         │       │
         ├───────┼──────────────────────────────────────┐
         │       │                                      │
         ├───────▼──────────────────────────────────────┼──────────────────────┐
         │                                              │                      │
    ┌────▼─────────────────────────────────┐           │                      │
    │  LEAD_INVENTORY_SELECTION             │           │                      │
    ├──────────────────────────────────────┤           │                      │
    │ • id (UUID, PK)                      │           │                      │
    │ • lead_id (FK) ◄───────┐             │           │                      │
    │ • inventory_item_id (FK)─────────┐   │           │                      │
    │ • quantity_requested             │   │           │                      │
    │ • unit_price_at_selection        │   │           │                      │
    │ • total_price                    │   │           │                      │
    │ • notes                          │   │           │                      │
    │ • status (enum)                  │   │           │                      │
    │ • tenant_id                      │   │           │                      │
    │ UNIQUE(lead_id, item_id)         │   │           │                      │
    └────┬─────────────────────────────┘   │           │                      │
         │                                 │           │                      │
         │ 1:N                             │           │                      │
         └─────────┬───────────────────────┼───────────┼──────────────────────┘
                   │                       │           │
            ┌──────▼───────────────────────▼─────┐     │
            │  INVENTORY_ALLOCATION              │     │
            ├────────────────────────────────────┤     │
            │ • id (UUID, PK)                    │     │
            │ • selection_id (FK) ◄──────────┐   │     │
            │ • inventory_item_id (FK) ──────┼───┼─────┘
            │ • quantity_allocated           │   │
            │ • allocation_status (enum)     │   │
            │ • allocation_date              │   │
            │ • expected_delivery            │   │
            │ • notes                        │   │
            │ • tenant_id                    │   │
            └────────────────────────────────────┘
                                                 │
                      ┌──────────────────────────┘
                      │
            ┌─────────▼────────────────────────┐
            │  LEAD_INVENTORY_SUMMARY          │
            ├────────────────────────────────┤
            │ • id (UUID, PK)                │
            │ • lead_id (FK) ◄──────────────┐│
            │ • total_items_count           ││
            │ • total_inventory_cost        ││
            │ • total_inventory_price       ││
            │ • category_breakdown (JSON)   ││
            │ • last_updated                ││
            │ • tenant_id                   ││
            │ UNIQUE(lead_id)               ││
            └────────────────────────────────┘
```

---

## Lead Lifecycle Journey

### Stage 1: Lead Creation

```
ENTRY POINT
│
├─ Public Form (/lead-form)
│  └─ Anonymous user submits
│
├─ Admin Form (/leads/create)
│  └─ Sales exec creates manually
│
└─ API Endpoint (POST /api/leads)
   └─ Integration system creates

                    ↓
        LEAD RECORD CREATED
        ├─ id: UUID
        ├─ lead_status: "new"
        ├─ company_name: captured
        ├─ contact_person_name: captured
        ├─ email: captured
        ├─ mobile_number: captured
        ├─ address/city/state/country/postal: captured
        ├─ service_type_id: identified
        ├─ guard_type: specified
        ├─ site_type: specified
        ├─ lead_source: tracked
        ├─ assigned_sales_exec_id: NULL or assigned
        ├─ budget_range_min/max: captured
        ├─ follow_up_date: set (optional)
        └─ tenant_id: auto-set
```

### Stage 2: Lead Qualification

```
LEAD CREATED
│
├─ Sales Exec Reviews
│  └─ Evaluates fit
│
├─ Initial Contact Made
│  └─ lead_status: "contacted"
│
├─ Qualification Questions
│  ├─ Does prospect match service?
│  ├─ Budget realistic?
│  └─ Timeline matches?
│
└─ Decision
   ├─ QUALIFIED
   │  └─ lead_status: "qualified"
   │
   └─ NOT QUALIFIED
      └─ lead_status: "closed_lost" / archive

                    ↓
        LOAD QUESTIONNAIRE TEMPLATE
        ├─ service_type_id from Lead
        ├─ Find QuestionnaireTemplate
        │  where service_type_id matches
        ├─ Load questions ordered by display_order
        ├─ Identify conditional_logic
        └─ Ready for responses
```

### Stage 3: Questionnaire Response Collection

```
QUESTIONNAIRE TEMPLATE LOADED
│
├─ Display Question 1
│  ├─ question_type: determines UI (text, mcq, checkbox, etc)
│  ├─ is_mandatory: enforces required
│  ├─ help_text: guides respondent
│  └─ conditional_logic: show/hide based on answers
│
├─ Respondent Answers Q1
│  ├─ Answer validated against question_type
│  ├─ answer_metadata: stores additional data
│  └─ LeadQuestionnaireResponse created
│      └─ UNIQUE(lead_id, question_id)
│
├─ Evaluate conditional_logic
│  ├─ If Q1 answer = "yes" then show Q2
│  ├─ If Q1 answer = "no" then skip Q3
│  └─ If Q1 AND Q2 match criteria, show Q4
│
├─ Display Question 2/3/... (based on conditions)
│  └─ Repeat response collection
│
└─ All Questions Answered
   └─ responses stored in table
      lead_questionnaire_responses
```

### Stage 4: Inventory Auto-Suggestion

```
ALL QUESTIONNAIRE RESPONSES RECORDED
│
├─ For Each Question with Answer
│  │
│  ├─ Query QuestionnaireInventoryOption
│  │  WHERE question_id = answered_question
│  │  AND option matches answer
│  │
│  ├─ If Match Found (Example):
│  │  ├─ question: "How many guards needed?"
│  │  ├─ answer: 5
│  │  │
│  │  ├─ Mapped Items:
│  │  │  ├─ Uniforms
│  │  │  │  └─ default_quantity: 5
│  │  │  │     (one per guard)
│  │  │  │
│  │  │  ├─ Safety Helmets
│  │  │  │  └─ default_quantity: 5
│  │  │  │
│  │  │  └─ Radios
│  │  │     └─ default_quantity: 1
│  │  │        (shared for team)
│  │  │
│  │  └─ Create LeadInventorySelection
│  │     for each mapped item
│  │     ├─ quantity_requested: default_quantity
│  │     ├─ unit_price_at_selection: from InventoryItem
│  │     ├─ total_price: qty × unit_price
│  │     └─ status: "requested"
│  │
│  └─ If No Match
│     └─ No auto-suggestion for this answer
│
└─ AUTO-SUGGESTIONS COMPLETE
   └─ Proceed to manual selection/approval
```

### Stage 5: Inventory Selection & Approval

```
AUTO-SUGGESTIONS AVAILABLE
│
├─ Sales Exec Reviews Suggestions
│  ├─ Approve suggested items
│  ├─ Remove unwanted items
│  ├─ Adjust quantities
│  ├─ Add additional items (manual selection)
│  └─ Update notes per item
│
├─ Update LeadInventorySelection
│  ├─ quantity_requested: modified
│  ├─ notes: added/updated
│  ├─ status: "approved" / "requested"
│  └─ total_price: recalculated
│
├─ LeadInventorySummary Generated
│  ├─ total_items_count: sum
│  ├─ total_inventory_cost: sum (cost_price × qty)
│  ├─ total_inventory_price: sum (selling_price × qty)
│  ├─ category_breakdown:
│  │  ├─ Security Equipment: $5,000
│  │  ├─ Uniforms: $2,000
│  │  ├─ Technology: $3,500
│  │  └─ Total: $10,500
│  └─ last_updated: now
│
└─ SUMMARY AVAILABLE FOR REPORTING
   └─ Compare to budget_range
      ├─ budget_min: $8,000
      ├─ selected_total: $10,500
      ├─ budget_max: $15,000
      └─ Status: WITHIN BUDGET ✓
```

### Stage 6: Inventory Allocation

```
SELECTIONS APPROVED
│
├─ For Each Approved Selection
│  ├─ Check InventoryItem.stock_quantity
│  │  ├─ Available: >= quantity_requested
│  │  │  └─ Proceed to allocation
│  │  │
│  │  └─ Low Stock: < quantity_requested
│  │     ├─ Allocate available quantity
│  │     └─ Note shortfall for order
│
├─ Create InventoryAllocation
│  ├─ lead_inventory_selection_id: link to selection
│  ├─ inventory_item_id: item being allocated
│  ├─ quantity_allocated: qty from available stock
│  ├─ allocation_status: "reserved"
│  ├─ allocation_date: today
│  ├─ expected_delivery: date
│  └─ notes: special handling
│
├─ Review Allocations
│  ├─ Management approves allocations
│  ├─ allocation_status: "reserved" → "committed"
│  │  (confirmed for fulfillment)
│  │
│  └─ Or Release if needed
│     └─ allocation_status: "released"
│        (return to inventory pool)
│
└─ FULFILLMENT READY
   └─ Inventory committed for lead
```

### Stage 7: Lead Conversion to Client

```
LEAD NEGOTIATED & APPROVED
│
├─ Conversion Decision
│  └─ lead_status: "closed_won"
│
├─ Create Client Record
│  ├─ Pull data from Lead:
│  │  ├─ company_name → Client.name
│  │  ├─ contact_person_name → ClientContact
│  │  ├─ email → ClientContact.email
│  │  ├─ mobile_number → ClientContact.mobile
│  │  ├─ address → Client.address
│  │  └─ service_type_id → Client service
│  │
│  └─ New Client record created
│     └─ id: UUID
│
├─ Link Lead to Client
│  ├─ lead.converted_to_client_id = client.id
│  ├─ lead.converted_at = now()
│  └─ lead remains (soft delete available)
│
├─ Transfer Allocations
│  ├─ All InventoryAllocations
│     remain in place
│  ├─ Mark as ready for delivery
│  └─ Create service contract
│
└─ LEAD LIFECYCLE COMPLETE
   └─ Now managed as Client relationship
```

---

## Questionnaire Integration Flow

### Question Types & Handling

```
┌────────────────────────────────────────────────────────┐
│            QUESTIONNAIRE QUESTION TYPES                │
└────────────────────────────────────────────────────────┘

1. TEXT INPUT
   ├─ Type: "text"
   ├─ HTML: <input type="text" />
   ├─ Validation: max length
   └─ Answer: Simple string
      Example: "company_location"

2. TEXTAREA
   ├─ Type: "textarea"
   ├─ HTML: <textarea></textarea>
   ├─ Validation: max characters
   └─ Answer: Multi-line text
      Example: "detailed_requirements"

3. EMAIL
   ├─ Type: "email"
   ├─ HTML: <input type="email" />
   ├─ Validation: valid email format
   └─ Answer: Email address
      Example: "contact@example.com"

4. NUMBER
   ├─ Type: "number"
   ├─ HTML: <input type="number" />
   ├─ Validation: numeric, min, max
   └─ Answer: Integer/decimal
      Example: 5, 100.50

5. MULTIPLE CHOICE (MCQ)
   ├─ Type: "mcq"
   ├─ Options: ["Option1", "Option2", "Option3"]
   ├─ HTML: <select><option></option></select>
   ├─ Validation: must be in options array
   └─ Answer: Single selected option
      Example: "Option1"
      
      Can Link to Inventory:
      ├─ "Option1" → Item A (qty 5)
      ├─ "Option2" → Item B (qty 3)
      └─ "Option3" → Item C (qty 1)

6. CHECKBOX (MULTI-SELECT)
   ├─ Type: "checkbox"
   ├─ Options: ["Check1", "Check2", "Check3"]
   ├─ HTML: <input type="checkbox" /> × multiple
   ├─ Validation: at least one selected if required
   └─ Answer: Array of selected options
      Example: ["Check1", "Check3"]
      
      Can Link to Inventory:
      ├─ "Check1" → Item X (qty 2)
      ├─ "Check2" → Item Y (qty 1)
      └─ "Check3" → Item Z (qty 3)

7. DROPDOWN (SELECT)
   ├─ Type: "dropdown"
   ├─ Options: ["Select1", "Select2", "Select3"]
   ├─ HTML: <select><option></option></select>
   ├─ Validation: must be in options
   └─ Answer: Single selected value
      Example: "Select2"

8. FILE UPLOAD
   ├─ Type: "file"
   ├─ HTML: <input type="file" />
   ├─ Validation: file size, mime types
   └─ Answer: file path
      answer_metadata:
      {
        "file_path": "/storage/uploads/...",
        "file_size": 102400,
        "mime_type": "application/pdf"
      }

9. DATE
   ├─ Type: "date"
   ├─ HTML: <input type="date" />
   ├─ Validation: valid date format
   └─ Answer: ISO date string
      Example: "2026-01-23"
```

### Conditional Logic System

```
CONDITIONAL LOGIC STRUCTURE
(Stored as JSON in conditional_logic field)

Simple Condition:
{
  "question_id": "q2-uuid",
  "expected_answer": "yes",
  "operator": "equals"
}
Usage: Show this question IF question_id answered "yes"

Complex Condition (AND):
{
  "operator": "AND",
  "conditions": [
    {
      "question_id": "q1-uuid",
      "expected_answer": "armed",
      "operator": "equals"
    },
    {
      "question_id": "q3-uuid",
      "expected_answer": ["outdoor", "night"],
      "operator": "in"
    }
  ]
}
Usage: Show this question IF both conditions true

Complex Condition (OR):
{
  "operator": "OR",
  "conditions": [
    {
      "question_id": "q1-uuid",
      "expected_answer": "yes"
    },
    {
      "question_id": "q2-uuid",
      "expected_answer": "yes"
    }
  ]
}
Usage: Show this question IF any condition true


EVALUATION ALGORITHM:
─────────────────────

function evaluateCondition(condition, answers) {
  
  if (condition.operator === 'equals') {
    return answers[condition.question_id] === condition.expected_answer
  }
  
  if (condition.operator === 'in') {
    let answer = answers[condition.question_id]
    return condition.expected_answer.includes(answer)
  }
  
  if (condition.operator === 'AND') {
    return condition.conditions.every(c => 
      evaluateCondition(c, answers)
    )
  }
  
  if (condition.operator === 'OR') {
    return condition.conditions.some(c => 
      evaluateCondition(c, answers)
    )
  }
}

EXAMPLE FLOW:
─────────────

Template: "Guard Service Questionnaire"

Q1: "Type of service?" (MCQ)
├─ Options: ["Static Guard", "Escort", "Patrol"]
├─ conditional_logic: null (always shown)
└─ Answer: "Static Guard"

Q2: "Number of guards?" (Number)
├─ conditional_logic: null (always shown)
└─ Answer: 5

Q3: "Outdoor service?" (MCQ)
├─ Options: ["Yes", "No"]
├─ conditional_logic: null (always shown)
└─ Answer: "Yes"

Q4: "Night shift required?" (MCQ)
├─ Options: ["Yes", "No"]
├─ conditional_logic: 
│  {
│    "operator": "AND",
│    "conditions": [
│      {"question_id": "Q1-uuid", "expected_answer": "Static Guard"},
│      {"question_id": "Q3-uuid", "expected_answer": "Yes"}
│    ]
│  }
├─ Visible: YES (both conditions met)
└─ Answer: "Yes"

Q5: "Equipment needed?" (Checkbox)
├─ Options: ["Flashlight", "Body Armor", "Whistle", "Radio"]
├─ conditional_logic:
│  {
│    "operator": "AND",
│    "conditions": [
│      {"question_id": "Q4-uuid", "expected_answer": "Yes"}
│    ]
│  }
├─ Visible: YES (night shift selected)
└─ Answer: ["Flashlight", "Radio"]
```

---

## Inventory Integration Flow

### Questionnaire-to-Inventory Mapping

```
QUESTIONNAIRE_INVENTORY_OPTION TABLE
────────────────────────────────────

Links questions to inventory items
One row = One question → item mapping

Example Setup:
┌──────────────────────────────────────────────────────┐
│ Q: "How many guards needed?" (Answer: 5)             │
├──────────────────────────────────────────────────────┤
│ Mapped Items:                                        │
│                                                      │
│ 1. UNIFORMS                                          │
│    ├─ inventory_item_id: item-uuid-1                │
│    ├─ default_quantity: 5 (one per guard)           │
│    ├─ is_optional: false (mandatory)                │
│    ├─ option_label: "Guard Uniforms"                │
│    └─ display_order: 1                              │
│                                                      │
│ 2. HELMETS                                           │
│    ├─ inventory_item_id: item-uuid-2                │
│    ├─ default_quantity: 5 (one per guard)           │
│    ├─ is_optional: false                            │
│    ├─ option_label: "Safety Helmets"                │
│    └─ display_order: 2                              │
│                                                      │
│ 3. RADIOS                                            │
│    ├─ inventory_item_id: item-uuid-3                │
│    ├─ default_quantity: 1 (shared)                  │
│    ├─ is_optional: true (optional)                  │
│    ├─ option_label: "Communication Radios"          │
│    └─ display_order: 3                              │
│                                                      │
│ 4. FIRST AID KIT                                     │
│    ├─ inventory_item_id: item-uuid-4                │
│    ├─ default_quantity: 1                           │
│    ├─ is_optional: true                             │
│    ├─ option_label: "Medical First Aid Kit"         │
│    └─ display_order: 4                              │
│                                                      │
│ 5. VEHICLE                                           │
│    ├─ inventory_item_id: item-uuid-5                │
│    ├─ default_quantity: 1                           │
│    ├─ is_optional: false                            │
│    ├─ option_label: "Patrol Vehicle"                │
│    └─ display_order: 5                              │
│                                                      │
│ 6. COMMAND CENTER SETUP                              │
│    ├─ inventory_item_id: item-uuid-6                │
│    ├─ default_quantity: 1                           │
│    ├─ is_optional: true                             │
│    ├─ option_label: "Mobile Command Center"         │
│    └─ display_order: 6                              │
│                                                      │
└──────────────────────────────────────────────────────┘

AUTO-SUGGESTION ALGORITHM:
──────────────────────────

for each (question_id, answer) {
  
  query QuestionnaireInventoryOption
  where questionnaire_question_id = question_id
  
  // For MCQ/Dropdown: exact answer match
  // For Checkbox: each selected option
  // For Number: can be range-based
  
  for each matching option {
    
    get inventory_item = option.inventory_item
    
    create LeadInventorySelection {
      lead_id: current_lead.id,
      inventory_item_id: inventory_item.id,
      quantity_requested: option.default_quantity,
      unit_price_at_selection: inventory_item.selling_price,
      total_price: option.default_quantity × selling_price,
      status: "requested",
      notes: option.option_label,
      tenant_id: current_tenant.id
    }
  }
}

EXAMPLE EXECUTION:
──────────────────

Lead answers:
├─ Q1: "5 guards"
├─ Q2: "Outdoor"
└─ Q3: "Yes, night shift"

Auto-Created Selections:
├─ Uniforms (qty: 5) → $1,000 total
├─ Helmets (qty: 5) → $500 total
├─ Radios (qty: 1) → $800 total
├─ Vehicle (qty: 1) → $3,000 total
├─ Command Center (optional, qty: 1) → $5,000 total
└─ First Aid (optional, qty: 1) → $500 total

LeadInventorySummary:
├─ total_items_count: 6
├─ total_inventory_price: $10,800 (if all approved)
├─ category_breakdown:
│  ├─ "Equipment": $800
│  ├─ "Uniforms": $1,500 ($1,000 + $500)
│  └─ "Vehicles": $8,000 ($3,000 + $5,000)
└─ Status: REVIEW NEEDED (cost check vs budget)
```

### Inventory Item Structure

```
INVENTORY HIERARCHY
───────────────────

INVENTORY_CATEGORY
├─ Security Equipment
│  └─ Active: Yes
│  └─ Items: [Helmets, Vests, Radios, ...]
│
├─ Uniforms
│  └─ Active: Yes
│  └─ Items: [Guard Shirts, Trousers, Jackets, ...]
│
├─ Technology
│  └─ Active: Yes
│  └─ Items: [CCTV, Alarms, Body Cameras, ...]
│
├─ Vehicles
│  └─ Active: Yes
│  └─ Items: [Patrol Car, Command Van, ...]
│
└─ Infrastructure
   └─ Active: Yes
   └─ Items: [Guard Posts, Fencing, ...]

INVENTORY_ITEM Details
──────────────────────

Example: Guard Uniform (Shirt)
├─ id: item-uuid-1
├─ category_id: uniforms-uuid
├─ name: "Guard Dress Shirt - Blue"
├─ description: "Official blue dress shirt for security personnel"
├─ sku: "GDS-BLUE-M"
├─ unit: "piece"
├─ cost_price: 150.00 (what org paid)
├─ selling_price: 200.00 (what client charged)
├─ stock_quantity: 500 (currently in inventory)
├─ reorder_level: 100 (alert if below)
├─ is_active: true
└─ tenant_id: org-uuid

PRICING CONTEXT:
───────────────

Capture at Selection Time:
├─ unit_price_at_selection = selling_price (at time Q was answered)
├─ This ensures historical accuracy
├─ Even if selling_price changes later
└─ Creates "point-in-time" pricing snapshot

LeadInventorySelection stores:
├─ quantity_requested: 5
├─ unit_price_at_selection: 200.00
└─ total_price: 1,000.00
    (locked in at selection time)
```

---

## Complete End-to-End Workflow

### Full Journey Example: "Acme Corp" Security Services Lead

```
DAY 1: LEAD SUBMISSION
═══════════════════════

10:00 AM - Public Form Submitted
┌─────────────────────────────────────────────┐
│ /lead-form POST submission                  │
├─────────────────────────────────────────────┤
│ Company Details:                            │
│ • company_name: "Acme Corp Ltd"             │
│ • contact_person: "John Smith"              │
│ • email: "john@acmecorp.com"                │
│ • mobile: "+1-555-0100"                     │
│ • address: "123 Business St"                │
│ • city: "New York"                          │
│ • country: "USA"                            │
│ • postal_code: "10001"                      │
│                                             │
│ Service Requirements:                       │
│ • service_type_id: "guard-service"          │
│ • guard_type: "armed"                       │
│ • tentative_guards_count: 10                │
│ • working_hours_type: "24"                  │
│ • site_type: "office"                       │
│ • service_location: "Manhattan HQ"          │
│                                             │
│ Other:                                      │
│ • lead_source: "website"                    │
│ • budget_range_min: 50000                   │
│ • budget_range_max: 75000                   │
│ • follow_up_date: "2026-01-30"              │
│ • compliance_required: true                 │
│ • tenant_id: auto-generated                 │
└─────────────────────────────────────────────┘
         ↓
Lead Record Created:
├─ lead.id: "lead-uuid-123"
├─ lead.lead_status: "new"
├─ lead.assigned_sales_exec_id: NULL
└─ lead.converted_to_client_id: NULL


10:15 AM - Sales Exec Assignment
┌─────────────────────────────────────────────┐
│ Admin Updates Lead:                         │
│ • assigned_sales_exec_id: "user-uuid-456"   │
│   (Sarah Johnson - Senior Sales Executive)  │
│ • lead_status: "contacted"                  │
└─────────────────────────────────────────────┘


DAY 2: QUESTIONNAIRE RESPONSE
═════════════════════════════

9:00 AM - Sarah Reviews & Loads Questionnaire
┌──────────────────────────────────────────────────┐
│ Questionnaire Template: "Guard Service"           │
│ (service_type_id matches)                        │
├──────────────────────────────────────────────────┤
│ Q1: "What is primary service type?"              │
│ Type: MCQ                                        │
│ Options: ["Static Guard", "Patrol", "Escort"]    │
│ Mandatory: Yes                                   │
│ Answer: "Static Guard"                           │
│                                                  │
│ → Matched Inventory Options:                    │
│   • Uniforms (qty: 10)                          │
│   • Helmets (qty: 10)                           │
│   • First Aid Kit (qty: 1)                      │
│   • Radio System (qty: 1)                       │
└──────────────────────────────────────────────────┘

         ↓

│ Q2: "How many personnel required?"               │
│ Type: Number                                     │
│ Min: 1, Max: 100                                │
│ Mandatory: Yes                                   │
│ Answer: 10                                       │
│                                                  │
│ → Matched Inventory Options:                    │
│   • Additional Uniforms (qty: 10)               │
│   • Equipment Set (qty: 10)                     │
│   • Shift Scheduling System (qty: 1)            │
└──────────────────────────────────────────────────┘

         ↓

│ Q3: "Site has special security needs?"          │
│ Type: Checkbox                                   │
│ Options: ["Perimeter", "Access Control",        │
│          "Surveillance", "Incident Response"]    │
│ Mandatory: No                                    │
│ Answer: ["Perimeter", "Surveillance"]           │
│                                                  │
│ → Matched Inventory Options:                    │
│   • Perimeter Fencing (qty: 1)                  │
│   • CCTV System (qty: 1)                        │
│   • Monitor Station Equipment (qty: 1)          │
└──────────────────────────────────────────────────┘

         ↓

│ Q4: "Budget flexibility?"                       │
│ Type: Dropdown                                   │
│ Options: ["Fixed", "Flexible", "Not sure"]      │
│ Conditional Logic: Always shown                 │
│ Answer: "Flexible"                              │
│                                                  │
│ → Matched Inventory Options: None              │
│   (Budget doesn't map to items)                │
└──────────────────────────────────────────────────┘

         ↓

│ Q5: "24/7 ops requirement?" (conditional)       │
│ Type: MCQ                                        │
│ Conditional Logic: Show only if answer to Q4 = "Flexible"
│ Options: ["Yes", "No"]                          │
│ Answer: "Yes" (shown because Q4 was "Flexible") │
│                                                  │
│ → Matched Inventory Options:                    │
│   • Command Center Setup (qty: 1)               │
│   • 24/7 Ops Monitoring Software (qty: 1)      │
└──────────────────────────────────────────────────┘

All Responses Saved:
├─ lead_questionnaire_responses[5]
└─ Each with answer + metadata


AUTO-GENERATED INVENTORY SELECTIONS
═══════════════════════════════════

System creates LeadInventorySelection records:

From Q1 ("Static Guard"):
├─ Selection 1: Uniforms
│  ├─ quantity_requested: 10
│  ├─ unit_price_at_selection: 200.00
│  ├─ total_price: 2,000.00
│  ├─ status: "requested"
│  └─ notes: "Guard Uniforms (10 sets)"
│
├─ Selection 2: Helmets
│  ├─ quantity_requested: 10
│  ├─ unit_price_at_selection: 150.00
│  ├─ total_price: 1,500.00
│  ├─ status: "requested"
│  └─ notes: "Safety Helmets (10 units)"
│
├─ Selection 3: First Aid Kit
│  ├─ quantity_requested: 1
│  ├─ unit_price_at_selection: 500.00
│  ├─ total_price: 500.00
│  ├─ status: "requested"
│  └─ notes: "Medical First Aid Kit"
│
└─ Selection 4: Radio System
   ├─ quantity_requested: 1
   ├─ unit_price_at_selection: 3,000.00
   ├─ total_price: 3,000.00
   ├─ status: "requested"
   └─ notes: "Communication Radio System"

From Q2 ("10 personnel"):
├─ Selection 5: Additional Uniforms
│  ├─ quantity_requested: 10
│  ├─ unit_price_at_selection: 200.00
│  ├─ total_price: 2,000.00
│  └─ ...
│
├─ Selection 6: Equipment Set
│  ├─ quantity_requested: 10
│  ├─ unit_price_at_selection: 1,000.00
│  ├─ total_price: 10,000.00
│  └─ ...
│
└─ Selection 7: Shift Scheduling System
   ├─ quantity_requested: 1
   ├─ unit_price_at_selection: 2,000.00
   ├─ total_price: 2,000.00
   └─ ...

From Q3 ("Perimeter, Surveillance"):
├─ Selection 8: Perimeter Fencing
│  ├─ quantity_requested: 1
│  ├─ unit_price_at_selection: 15,000.00
│  ├─ total_price: 15,000.00
│  └─ ...
│
├─ Selection 9: CCTV System
│  ├─ quantity_requested: 1
│  ├─ unit_price_at_selection: 8,000.00
│  ├─ total_price: 8,000.00
│  └─ ...
│
└─ Selection 10: Monitor Station
   ├─ quantity_requested: 1
   ├─ unit_price_at_selection: 5,000.00
   ├─ total_price: 5,000.00
   └─ ...

From Q5 ("24/7 Yes"):
├─ Selection 11: Command Center Setup
│  ├─ quantity_requested: 1
│  ├─ unit_price_at_selection: 20,000.00
│  ├─ total_price: 20,000.00
│  └─ ...
│
└─ Selection 12: 24/7 Monitoring Software
   ├─ quantity_requested: 1
   ├─ unit_price_at_selection: 3,000.00
   ├─ total_price: 3,000.00
   └─ ...


INVENTORY SUMMARY GENERATED
════════════════════════════

LeadInventorySummary created:
├─ lead_id: "lead-uuid-123"
├─ total_items_count: 12
├─ total_inventory_cost: 76,500.00
│  (calculated from cost_price × qty for approved)
├─ total_inventory_price: 76,500.00
│  (sum of all selection total_price)
├─ category_breakdown:
│  {
│    "Uniforms": 4000.00,
│    "Equipment": 22000.00,
│    "Security Systems": 13000.00,
│    "Infrastructure": 20000.00,
│    "Software & Services": 17500.00
│  }
└─ last_updated: "2026-01-22 09:45:00"

Budget Check:
├─ Selected Total: $76,500.00
├─ Budget Range: $50,000 - $75,000
├─ Status: ⚠️ EXCEEDS BUDGET (by $1,500)


DAY 3: SALES EXEC REVIEW & ADJUSTMENT
═══════════════════════════════════════

10:00 AM - Sarah Reviews Selections
┌────────────────────────────────────┐
│ Acme Corp Lead Summary:            │
│                                    │
│ Total Inventory Cost: $76,500      │
│ Budget: $50,000 - $75,000          │
│ Status: OVER BUDGET                │
└────────────────────────────────────┘

Sarah Adjusts Selections:
├─ Decision: Remove non-critical items
│
├─ Selection 11 (Command Center): REMOVE
│  └─ reason: "Can use own management"
│
├─ Selection 12 (24/7 Software): CHANGE quantity
│  └─ from: 1 unit × $3,000 → 0.5 (reduced service)
│     to: 1 unit × $1,500
│
├─ Selection 8 (Perimeter Fencing): REMOVE
│  └─ reason: "Existing fencing adequate"
│
└─ Selection 9 (CCTV): REDUCE quantity
   └─ from: 1 unit × $8,000 → quantity 0.5
      to: 1 unit × $4,000 (partial coverage)

Updated LeadInventorySelection records:
├─ Selection 11: status = "rejected"
├─ Selection 12: quantity_requested = 1, 
│              unit_price = $1,500,
│              total_price = $1,500
├─ Selection 8: status = "rejected"
└─ Selection 9: quantity_requested = 1,
               unit_price = $4,000,
               total_price = $4,000

Lead Summary Recalculated:
├─ total_items_count: 10 (12 - 2 removed)
├─ total_inventory_price: 56,000.00
│  ($76,500 - $20,000 - $4,000 + changes)
├─ category_breakdown: UPDATED
│  {
│    "Uniforms": 4000.00,
│    "Equipment": 22000.00,
│    "Security Systems": 9000.00,
│    "Software & Services": 1500.00,
│    "Infrastructure": 19500.00
│  }
└─ Status: ✓ WITHIN BUDGET ($56,000 < $75,000)


ALL SELECTIONS APPROVED
═════════════════════════

Sarah marks all remaining selections as "approved"

Each approved selection:
├─ status: "approved"
├─ ready for allocation
└─ will trigger InventoryAllocation creation


DAY 4: INVENTORY ALLOCATION
════════════════════════════

10:00 AM - Warehouse Reviews Allocations

For each approved selection, system creates InventoryAllocation:

Selection 1 (Uniforms, qty 10):
├─ Check stock: 500 available ✓
├─ Create Allocation:
│  ├─ lead_inventory_selection_id: sel-uuid-1
│  ├─ inventory_item_id: item-uuid-1
│  ├─ quantity_allocated: 10
│  ├─ allocation_status: "reserved"
│  ├─ allocation_date: 2026-01-23
│  ├─ expected_delivery: 2026-01-30
│  └─ notes: "Guard uniforms for Acme Corp"
│
└─ Stock Impact: RESERVED (not deducted yet)

Selection 2 (Helmets, qty 10):
├─ Check stock: 300 available ✓
├─ Create Allocation:
│  └─ ... (similar)
│
└─ Stock Impact: RESERVED

[... continue for all 10 approved selections ...]

Selection 6 (Equipment Set, qty 10):
├─ Check stock: Only 5 available ⚠️
├─ Create Allocation:
│  ├─ quantity_allocated: 5 (partial)
│  ├─ allocation_status: "reserved"
│  └─ notes: "PARTIAL ALLOCATION - 5 of 10. 
│            Remaining 5 on order."
│
└─ Stock Impact: RESERVED (5 units)
   NOTE: Shortfall flagged for procurement

All Allocations Summary:
├─ Total Allocations: 10
├─ Reserved Quantity: Total allocated
├─ Shortfalls: 1 item (Equipment Set)
├─ Expected Delivery: 2026-01-30
└─ Status: READY FOR MANAGEMENT REVIEW


Management Review (11:30 AM):
├─ Review allocation summary
├─ Approve critical path items
├─ For each allocation:
│  ├─ If sufficient stock: status = "committed"
│  │  (Confirmed for fulfillment)
│  │
│  └─ If stock issue: status = "reserved"
│     (Hold for resolution)
│
└─ Shortfall (Equipment Set):
   ├─ Option A: Order expedited shipment
   ├─ Option B: Offer partial fulfillment
   └─ Option C: Release allocation, offer alternative


DAY 5-10: NEGOTIATION & APPROVAL
═════════════════════════════════

Sarah and Acme Corp:
├─ Discuss service rates
├─ Confirm timeline
├─ Resolve equipment shortfall
│  └─ Decision: Expedited order placed
│
└─ Lead Status Updated:
   ├─ lead_status: "proposal_sent"
   ├─ Then: "negotiation"
   └─ Finally: "closed_won"


DAY 11: LEAD CONVERSION
════════════════════════

2:00 PM - Acme Corp Approves Proposal

System Actions:
├─ Create Client Record
│  ├─ id: "client-uuid-999"
│  ├─ name: "Acme Corp Ltd"
│  ├─ address: "123 Business St, New York"
│  └─ service_type: "Guard Service"
│
├─ Create ClientContact
│  ├─ name: "John Smith"
│  ├─ email: "john@acmecorp.com"
│  ├─ mobile: "+1-555-0100"
│  └─ primary: true
│
├─ Link Lead to Client
│  ├─ lead.converted_to_client_id = "client-uuid-999"
│  ├─ lead.converted_at = "2026-01-28 14:00:00"
│  └─ lead.lead_status = "closed_won"
│
├─ Create ClientService Contract
│  ├─ client_id: "client-uuid-999"
│  ├─ service_type: "Guard Service (Armed)"
│  ├─ service_location: "Manhattan HQ"
│  ├─ personnel_count: 10
│  ├─ working_hours: "24/7"
│  ├─ estimated_cost: 56000.00
│  └─ status: "active"
│
└─ Transfer Allocations
   ├─ All InventoryAllocation records
   │  linked to this lead
   ├─ Update allocation_status: "committed"
   ├─ Set expected_delivery dates
   └─ Trigger fulfillment workflow


DAY 12-20: FULFILLMENT
═══════════════════════

Warehouse Operations:
├─ Pick items from inventory
├─ Quality check
├─ Pack for shipment
├─ Update allocation_status: "in_transit"
├─ Deliver to Acme Corp site
│  ├─ Uniforms ✓
│  ├─ Helmets ✓
│  ├─ Equipment Sets ✓ (expedited arrived)
│  ├─ Radio System ✓
│  ├─ CCTV System ✓
│  ├─ Other items ✓
│  └─ All delivered by 2026-02-02
│
└─ Update allocation_status: "completed"
   └─ InventoryItem.stock_quantity -= allocated_qty


FINAL STATE
═════════════

Lead Lifecycle Complete:
├─ Lead Status: "closed_won"
├─ Lead Id: "lead-uuid-123"
├─ Converted To Client: "client-uuid-999"
├─ Service Active: "2026-02-01"
└─ Lead can be archived (soft-deleted)

Client Service Active:
├─ Client: Acme Corp Ltd
├─ Service: Guard Service (Armed)
├─ Personnel: 10 guards
├─ Hours: 24/7
├─ Location: Manhattan HQ
├─ Cost: $56,000 (inventory allocated)
└─ Status: "active" (ongoing)

Inventory Allocated:
├─ 10 units Uniforms
├─ 10 units Helmets
├─ 10 units Equipment Sets
├─ 1 unit Radio System
├─ 1 unit CCTV System
├─ 1 unit Monitor Station
├─ And others...
└─ All delivered & received


ANALYTICS
═════════

Lead Performance:
├─ Lead Source: Website
├─ Response Time: 2 days
├─ Cycle Time: 11 days (form to conversion)
├─ Close Rate: 100% (won)
├─ Revenue: $56,000 (contract value)
├─ Questionnaire Responses: 5
├─ Initial Selections: 12
├─ Final Selections: 10
├─ Removed Items: 2 (16.7%)
└─ Budget Variance: +$6,500 initial, -0 final

Sales Executive Performance:
├─ Assigned To: Sarah Johnson
├─ Lead Handled: 1 (this one)
├─ Conversion: Successful
├─ Average Cycle: 11 days
└─ Revenue Per Lead: $56,000

Inventory Impact:
├─ Items Allocated: 7 unique items
├─ Total Units: 36 units
├─ Total Cost: ~$45,000 (approx)
├─ Total Revenue: $56,000
├─ Margin: $11,000
├─ Stock Adjustment: Updated
└─ Reorder Needed: Equipment Set (stock low)
```

---

## Database Schema & Flow

### Table Interactions Diagram

```
LEADS TABLE (Entry Point)
│
├─→ LEAD_QUESTIONNAIRE_RESPONSES
│   │
│   ├─→ QUESTIONNAIRE_QUESTION
│   │   │
│   │   └─→ QUESTIONNAIRE_INVENTORY_OPTION
│   │       │
│   │       └─→ INVENTORY_ITEM (auto-suggestions)
│   │           │
│   │           ├─→ INVENTORY_CATEGORY
│   │           │
│   │           └─→ LEAD_INVENTORY_SELECTION
│   │               │
│   │               └─→ INVENTORY_ALLOCATION
│   │
│   └─→ QUESTIONNAIRE_TEMPLATE
│       └─→ SERVICE_TYPE
│
└─→ LEAD_INVENTORY_SELECTION (manual selections)
    │
    ├─→ INVENTORY_ITEM
    │
    ├─→ INVENTORY_ALLOCATION
    │   │
    │   └─→ Fulfillment tracking
    │
    └─→ LEAD_INVENTORY_SUMMARY
        └─ Aggregated costs & breakdown

QUERY FLOW FOR LEAD ANALYSIS:
──────────────────────────────

Query 1: Get all leads for sales exec
  SELECT * FROM leads
  WHERE assigned_sales_exec_id = ?
  AND tenant_id = ?
  AND deleted_at IS NULL
  ORDER BY created_at DESC;

Query 2: Get questionnaire responses for lead
  SELECT q.*, qq.* FROM lead_questionnaire_responses q
  JOIN questionnaire_questions qq ON q.questionnaire_question_id = qq.id
  WHERE q.lead_id = ?
  AND q.tenant_id = ?
  ORDER BY qq.display_order;

Query 3: Get auto-suggested inventory for a question answer
  SELECT qio.*, ii.* FROM questionnaire_inventory_options qio
  JOIN inventory_items ii ON qio.inventory_item_id = ii.id
  WHERE qio.questionnaire_question_id = ?
  AND qio.tenant_id = ?
  ORDER BY qio.display_order;

Query 4: Get all selections for a lead
  SELECT lis.*, ii.* FROM lead_inventory_selections lis
  JOIN inventory_items ii ON lis.inventory_item_id = ii.id
  WHERE lis.lead_id = ?
  AND lis.tenant_id = ?
  ORDER BY lis.created_at;

Query 5: Get allocation summary for lead
  SELECT COUNT(*) total_allocations,
         SUM(quantity_allocated) total_qty,
         COUNT(CASE WHEN allocation_status = 'committed' THEN 1 END) committed
  FROM inventory_allocations ia
  WHERE ia.lead_inventory_selection_id IN (
    SELECT id FROM lead_inventory_selections WHERE lead_id = ?
  )
  AND ia.tenant_id = ?;

Query 6: Get lead inventory summary with category breakdown
  SELECT lis.*, ic.name category_name,
         SUM(lis.total_price) OVER (PARTITION BY ic.id) category_total
  FROM lead_inventory_selections lis
  JOIN inventory_items ii ON lis.inventory_item_id = ii.id
  JOIN inventory_categories ic ON ii.category_id = ic.id
  WHERE lis.lead_id = ?
  AND lis.status = 'approved'
  AND lis.tenant_id = ?
  ORDER BY ic.name, lis.created_at;
```

---

## Advanced Scenarios

### Scenario 1: Complex Conditional Logic Evaluation

```
Questionnaire: "Premium Security Services"

Q1: "Service Type?" (MCQ)
├─ Options: ["Static", "Patrol", "VIP Escort"]
└─ Answer: "VIP Escort"

Q2: "Threat Level?" (Dropdown)
├─ Options: ["Low", "Medium", "High", "Critical"]
├─ Conditional: Always shown
└─ Answer: "High"

Q3: "International Travel?" (MCQ)
├─ Options: ["Yes", "No"]
├─ Conditional: Show only if Q1 = "VIP Escort"
├─ Is Visible: YES
└─ Answer: "Yes"

Q4: "Advance Team?" (Checkbox)
├─ Options: ["1 day", "3 days", "1 week"]
├─ Conditional: Show only if Q3 = "Yes" AND Q2 = "High"
├─ Logic Evaluation:
│  ├─ Q3 answered: "Yes" ✓
│  ├─ Q2 answered: "High" ✓
│  └─ Both conditions met: Show Q4 ✓
├─ Is Visible: YES
└─ Answer: ["1 day", "3 days"]

Q5: "Medical Team?" (MCQ)
├─ Options: ["Yes", "No"]
├─ Conditional: Show only if (Q1="VIP Escort") OR (Q2="Critical")
├─ Logic Evaluation:
│  ├─ Condition 1: Q1="VIP Escort" ✓
│  ├─ Condition 2: Q2="Critical" ✗
│  ├─ OR operator: At least one true ✓
│  └─ Show Q5 ✓
├─ Is Visible: YES
└─ Answer: "Yes"

Q6: "Embedded Medical Doctor?" (MCQ)
├─ Options: ["Yes", "No"]
├─ Conditional: Complex AND/OR logic
│  {
│    "operator": "AND",
│    "conditions": [
│      {
│        "operator": "OR",
│        "conditions": [
│          {"question_id": "q5", "expected_answer": "Yes"},
│          {"question_id": "q2", "expected_answer": "Critical"}
│        ]
│      },
│      {
│        "question_id": "q3",
│        "expected_answer": "Yes"
│      }
│    ]
│  }
├─ Logic Evaluation:
│  ├─ First condition (OR):
│  │  ├─ Q5="Yes" ✓
│  │  └─ Result: TRUE
│  ├─ Second condition:
│  │  └─ Q3="Yes" ✓
│  ├─ AND: Both true → Show Q6 ✓
│  └─ Is Visible: YES
└─ Answer: "Yes"

Resulting Inventory Suggestions:

From "VIP Escort":
├─ Premium Uniforms (qty: 2)
├─ Armored Vehicle (qty: 1)
└─ Communication System (qty: 1)

From "High Threat":
├─ Body Armor - High Threat (qty: 2)
├─ Advanced Weapons (qty: 2)
└─ Surveillance Package (qty: 1)

From "International Travel" + "1 day" advance:
├─ Air Transport Coordination (qty: 1)
├─ Pre-arrival reconnaissance (qty: 1)
└─ International Insurance (qty: 1)

From "Medical Team + Doctor":
├─ Mobile Medical Unit (qty: 1)
└─ Trauma Kit (qty: 2)

Total Auto-Suggested Items: 15
Total Estimated Cost: $180,000

Sales Exec Review:
├─ Remove: Mobile Medical Unit ($15,000)
├─ Reduce: Advanced Weapons (qty 2 → 1)
├─ Add: Night Vision Equipment ($8,000)
└─ Final Total: $173,000
```

### Scenario 2: Inventory Shortfall Handling

```
Lead: "TechCorp Campus Security"
Requested Inventory:
├─ Item A: Requested 50 units, Price $100/unit
├─ Item B: Requested 25 units, Price $500/unit
├─ Item C: Requested 100 units, Price $50/unit
└─ Total: $15,000

Warehouse Status Check:

Item A (50 requested):
├─ Stock: 45 available
├─ Status: SHORTFALL (5 units missing)
└─ Action: Partial allocation (45), backorder (5)

Item B (25 requested):
├─ Stock: 50 available
├─ Status: SUFFICIENT
└─ Action: Full allocation (25)

Item C (100 requested):
├─ Stock: 0 available
├─ Status: OUT OF STOCK
└─ Action: No allocation, wait for restock

Allocation Result:

Item A:
├─ Allocation 1: 45 units, status="reserved"
├─ Backorder note: "Remaining 5 units on procurement order, 
│                   expected delivery 2026-02-10"
└─ Lead notification: "Partial fulfillment"

Item B:
├─ Allocation: 25 units, status="reserved"
└─ Status: READY

Item C:
├─ Allocation: 0 units (not created)
├─ Flag: AWAITING STOCK
└─ Action: Daily check, notify when available

Lead Inventory Summary (Updated):

Requested vs. Allocated:
├─ Item A: 50 requested, 45 allocated (90%)
├─ Item B: 25 requested, 25 allocated (100%)
├─ Item C: 100 requested, 0 allocated (0%)
│
├─ Total Requested Cost: $15,000
├─ Total Allocated Cost: $10,000
├─ Shortfall Cost: $5,000
│
└─ Lead Status: PARTIAL FULFILLMENT
   ├─ Communication: Sent to client
   ├─ Option 1: Accept partial, complete later
   ├─ Option 2: Wait for all items (delay)
   └─ Option 3: Use alternative items

Sales Exec Action:
├─ Contact TechCorp
├─ Explain shortfalls
├─ Offer:
│  ├─ Ship Item A+B immediately, Item C later
│  └─ Priority backorder for Item C
│
└─ Lead Decision: Accept phased delivery
   ├─ Phase 1 (now): Item A (45) + Item B (25)
   ├─ Phase 2 (2026-02-10): Item A remaining (5)
   └─ Phase 3 (2026-02-25): Item C (100)

Allocation Status Updates:
├─ Item A (45): status="committed" → Ship
├─ Item B (25): status="committed" → Ship
├─ Item A (5): status="reserved" → Backorder
└─ Item C (100): status="reserved" → Waiting

Lead Inventory Summary (Final):
├─ Phase 1 Total: $7,500 (Item A 45 + Item B 25)
├─ Phase 2 Total: $500 (Item A remaining 5)
├─ Phase 3 Total: $5,000 (Item C 100)
├─ Full Contract: $13,000 (over time)
└─ Budget: $15,000 - Status: WITHIN BUDGET ✓
```

### Scenario 3: Multi-Selection & Amendment

```
Lead Amendment Workflow:

Initial Submission (Day 1):
├─ Client: "MegaMall"
├─ Service: "Guard Service"
├─ Coverage: "All hours"
├─ Selected Items: 8 items, Total: $25,000
└─ Status: APPROVED

Amendment Request (Day 15):
├─ MegaMall calls: "Expand security to parking lot"
├─ New Requirements: +5 additional guards
├─ New Timeline: "Start in 1 week"
└─ Impact: Need more inventory

Sales Exec Action:
├─ Load existing Lead record
├─ Load existing Questionnaire Responses
├─ NEW Question: "Parking lot guard count?"
│  └─ Answer: "5 additional"
│
├─ NEW Questionnaire Response created
│
├─ Query QuestionnaireInventoryOption
│  for the new question
│
├─ NEW Inventory Items suggested:
│  ├─ Uniforms (qty: 5)
│  ├─ Patrol Equipment (qty: 5)
│  ├─ Parking Radios (qty: 2)
│  └─ Parking Lights (qty: 1)
│
├─ NEW LeadInventorySelection records created
│
├─ LeadInventorySummary RECALCULATED
│  ├─ Old Total: $25,000
│  ├─ New Items: $8,000
│  ├─ New Total: $33,000
│  └─ Updated breakdown by category
│
└─ Lead Status: AMENDED
   ├─ amendment_count: 1
   ├─ original_total: $25,000
   ├─ amendment_total: $8,000
   └─ final_total: $33,000

Allocation for Amendment:

New Inventory Checked:
├─ Uniforms (5): Stock 200 available ✓
├─ Equipment (5): Stock 50 available ✓
├─ Radios (2): Stock 10 available ✓
└─ Lights (1): Stock 25 available ✓

New Allocations Created:
├─ Allocation 1: 5 uniforms, status="reserved"
├─ Allocation 2: 5 equipment, status="reserved"
├─ Allocation 3: 2 radios, status="reserved"
└─ Allocation 4: 1 light, status="reserved"

Lead Status Update:
├─ lead_status: "amended"
├─ last_amendment: "2026-01-30 10:15:00"
├─ total_contract_value: $33,000
└─ allocations_count: 12 (original 8 + new 4)

Fulfillment Plan:
├─ Phase 1 (original): Ship existing 8 items
├─ Phase 2 (amendment): Ship new 4 items
│  └─ Coordinated delivery to same location
│  
└─ Timeline: All by "2026-02-06" (amended deadline)
```

---

## Performance & Optimization

### Index Strategy

```
CRITICAL INDEXES:

1. Leads Table
   ├─ CREATE INDEX idx_leads_tenant_id ON leads(tenant_id);
   ├─ CREATE INDEX idx_leads_lead_status ON leads(lead_status);
   ├─ CREATE INDEX idx_leads_assigned_to ON leads(assigned_sales_exec_id);
   ├─ CREATE INDEX idx_leads_service_type ON leads(service_type_id);
   ├─ CREATE INDEX idx_leads_converted_client ON leads(converted_to_client_id);
   └─ CREATE INDEX idx_leads_created ON leads(created_at DESC);

2. Lead Questionnaire Responses
   ├─ CREATE INDEX idx_lqr_lead_id ON lead_questionnaire_responses(lead_id);
   ├─ CREATE INDEX idx_lqr_question_id ON lead_questionnaire_responses(questionnaire_question_id);
   ├─ CREATE UNIQUE INDEX idx_lqr_unique ON lead_questionnaire_responses(lead_id, questionnaire_question_id);
   └─ CREATE INDEX idx_lqr_tenant_id ON lead_questionnaire_responses(tenant_id);

3. Questionnaire Questions
   ├─ CREATE INDEX idx_qq_template_id ON questionnaire_questions(questionnaire_template_id);
   ├─ CREATE INDEX idx_qq_display_order ON questionnaire_questions(display_order);
   └─ CREATE INDEX idx_qq_tenant_id ON questionnaire_questions(tenant_id);

4. Inventory Items
   ├─ CREATE INDEX idx_ii_category_id ON inventory_items(category_id);
   ├─ CREATE UNIQUE INDEX idx_ii_sku ON inventory_items(sku);
   ├─ CREATE INDEX idx_ii_active ON inventory_items(is_active);
   ├─ CREATE INDEX idx_ii_stock ON inventory_items(stock_quantity);
   └─ CREATE INDEX idx_ii_tenant_id ON inventory_items(tenant_id);

5. Lead Inventory Selections
   ├─ CREATE INDEX idx_lis_lead_id ON lead_inventory_selections(lead_id);
   ├─ CREATE INDEX idx_lis_item_id ON lead_inventory_selections(inventory_item_id);
   ├─ CREATE INDEX idx_lis_status ON lead_inventory_selections(status);
   ├─ CREATE UNIQUE INDEX idx_lis_unique ON lead_inventory_selections(lead_id, inventory_item_id);
   └─ CREATE INDEX idx_lis_tenant_id ON lead_inventory_selections(tenant_id);

6. Inventory Allocations
   ├─ CREATE INDEX idx_ia_selection_id ON inventory_allocations(lead_inventory_selection_id);
   ├─ CREATE INDEX idx_ia_item_id ON inventory_allocations(inventory_item_id);
   ├─ CREATE INDEX idx_ia_status ON inventory_allocations(allocation_status);
   ├─ CREATE INDEX idx_ia_allocation_date ON inventory_allocations(allocation_date);
   └─ CREATE INDEX idx_ia_tenant_id ON inventory_allocations(tenant_id);

7. Questionnaire Inventory Options
   ├─ CREATE INDEX idx_qio_question_id ON questionnaire_inventory_options(questionnaire_question_id);
   ├─ CREATE INDEX idx_qio_item_id ON questionnaire_inventory_options(inventory_item_id);
   ├─ CREATE UNIQUE INDEX idx_qio_unique ON questionnaire_inventory_options(questionnaire_question_id, inventory_item_id);
   └─ CREATE INDEX idx_qio_tenant_id ON questionnaire_inventory_options(tenant_id);
```

### Query Optimization

```
EFFICIENT LEAD LOADING:

With Relations:
  $lead = Lead::with([
    'questionnaireResponses.question',
    'inventorySelections.item.category',
    'inventorySummary',
    'allocations'
  ])
  ->where('tenant_id', $tenantId)
  ->find($leadId);

Count without loading:
  $lead->questionnaire_responses_count = 
    $lead->questionnaireResponses()->count();
  
  $lead->inventory_selections_count = 
    $lead->inventorySelections()
    ->where('status', 'approved')->count();

Aggregated data:
  $summary = DB::table('lead_inventory_selections')
  ->where('lead_id', $leadId)
  ->where('status', 'approved')
  ->selectRaw('
    COUNT(DISTINCT inventory_item_id) as items_count,
    SUM(total_price) as total_price,
    GROUP_CONCAT(DISTINCT category_id) as categories
  ')
  ->first();

EFFICIENT QUESTIONNAIRE LOADING:

For template with questions:
  $template = QuestionnaireTemplate::with([
    'questions' => function($query) {
      $query->orderBy('display_order');
    }
  ])
  ->where('service_type_id', $serviceTypeId)
  ->where('is_active', true)
  ->first();

EFFICIENT INVENTORY SUGGESTIONS:

Get mapped items for questions:
  $suggestions = QuestionnaireInventoryOption::whereIn(
    'questionnaire_question_id',
    $questionIds
  )
  ->with([
    'inventoryItem.category',
    'question'
  ])
  ->orderBy('display_order')
  ->get();

LEAD LIST WITH SUMMARY:

  $leads = Lead::select('leads.*')
  ->selectSub(
    LeadQuestionnaireResponse::selectRaw(
      'COUNT(*)'
    )
    ->whereColumn('lead_id', 'leads.id'),
    'response_count'
  )
  ->selectSub(
    LeadInventorySelection::selectRaw(
      'SUM(total_price)'
    )
    ->whereColumn('lead_id', 'leads.id')
    ->where('status', 'approved'),
    'total_inventory_cost'
  )
  ->where('tenant_id', $tenantId)
  ->orderByDesc('created_at')
  ->paginate(15);
```

### Caching Strategy

```
CACHE KEYS:

1. Questionnaire Templates
   ├─ Key: "questionnaire:template:{serviceTypeId}::{tenantId}"
   ├─ TTL: 1 hour
   └─ Invalidate on: Template update/delete

2. Questions for Template
   ├─ Key: "questionnaire:questions:{templateId}::{tenantId}"
   ├─ TTL: 1 hour
   └─ Invalidate on: Question add/update/delete

3. Inventory Items
   ├─ Key: "inventory:items:active::{tenantId}"
   ├─ TTL: 4 hours
   └─ Invalidate on: Item stock change

4. Inventory Categories
   ├─ Key: "inventory:categories::{tenantId}"
   ├─ TTL: 8 hours
   └─ Invalidate on: Category update

5. Lead Summary
   ├─ Key: "lead:summary:{leadId}::{tenantId}"
   ├─ TTL: 30 minutes
   └─ Invalidate on: Selection/response add/update

6. Questionnaire-Inventory Mappings
   ├─ Key: "qio:question:{questionId}::{tenantId}"
   ├─ TTL: 2 hours
   └─ Invalidate on: Mapping create/update/delete

CACHE INVALIDATION:

When Lead Response Added:
├─ Clear lead:summary:{leadId}
├─ Trigger auto-suggestion process
└─ Update inventory selections cache

When Inventory Item Changed:
├─ Clear inventory:items:active
├─ Clear related lead summaries
└─ Notify affected leads

When Selection Approved:
├─ Clear lead:summary:{leadId}
├─ Update allocation planning
└─ Check stock levels
```

---

## API Endpoints & Operations

### Lead API

```
GET  /api/leads
     ├─ Query params:
     │  ├─ status (filter by lead_status)
     │  ├─ assigned_to (filter by sales exec)
     │  ├─ service_type (filter by service)
     │  ├─ search (text search)
     │  ├─ page (pagination)
     │  └─ limit (per page)
     │
     └─ Response: Collection with metadata

POST /api/leads
     ├─ Body:
     │  ├─ company_name
     │  ├─ contact_person_name
     │  ├─ email, mobile_number
     │  ├─ address, city, state, country, postal_code
     │  ├─ service_type_id
     │  ├─ guard_type
     │  ├─ tentative_guards_count
     │  ├─ working_hours_type
     │  ├─ site_type
     │  ├─ lead_source
     │  ├─ budget_range_min/max
     │  └─ [optional] service_details (JSON)
     │
     └─ Response: Created lead with id

GET  /api/leads/{id}
     ├─ Query params:
     │  ├─ include=responses
     │  ├─ include=selections
     │  ├─ include=allocations
     │  └─ include=summary
     │
     └─ Response: Lead with specified relations

PUT  /api/leads/{id}
     ├─ Body: Updated lead fields
     ├─ Status Code: 200
     └─ Response: Updated lead

DELETE /api/leads/{id}
     └─ Status Code: 204 No Content


QUESTIONNAIRE RESPONSE API:
───────────────────────────

POST /api/leads/{id}/questionnaire/responses
     ├─ Body:
     │  ├─ question_id (UUID)
     │  ├─ answer (string/array)
     │  └─ [optional] metadata (JSON)
     │
     ├─ Process:
     │  ├─ Validate question type
     │  ├─ Check mandatory requirement
     │  ├─ Query inventory mappings
     │  ├─ Auto-create selections
     │  └─ Update lead summary
     │
     └─ Response: Created response with auto-suggestions

GET  /api/leads/{id}/questionnaire/responses
     ├─ Returns: All responses for lead
     └─ Includes: Question details, answer display

GET  /api/leads/{id}/questionnaire/template
     ├─ Returns: Template for lead's service type
     ├─ Includes: All questions ordered
     └─ Includes: Conditional logic for client-side evaluation


INVENTORY SELECTION API:
────────────────────────

POST /api/leads/{id}/inventory/selections
     ├─ Body:
     │  ├─ inventory_item_id
     │  ├─ quantity_requested
     │  ├─ [optional] notes
     │  └─ [optional] source ("auto" or "manual")
     │
     ├─ Process:
     │  ├─ Create selection record
     │  ├─ Calculate total_price
     │  ├─ Set status="requested"
     │  └─ Update summary
     │
     └─ Response: Created selection

GET  /api/leads/{id}/inventory/selections
     ├─ Returns: All selections for lead
     └─ Includes: Item details, pricing, status

PUT  /api/leads/{id}/inventory/selections/{selectionId}
     ├─ Body:
     │  ├─ quantity_requested (updated)
     │  ├─ status (requested/approved/rejected)
     │  └─ notes (updated)
     │
     └─ Response: Updated selection

DELETE /api/leads/{id}/inventory/selections/{selectionId}
     ├─ Process:
     │  ├─ Validate not approved
     │  ├─ Delete selection
     │  └─ Update summary
     │
     └─ Response: 204 No Content

PUT  /api/leads/{id}/inventory/selections/{selectionId}/approve
     ├─ Process:
     │  ├─ Validate selection
     │  ├─ Check stock availability
     │  ├─ Create allocation
     │  ├─ Update status="approved"
     │  └─ Recalculate summary
     │
     └─ Response: Updated selection with allocation


LEAD INVENTORY SUMMARY API:
───────────────────────────

GET  /api/leads/{id}/inventory/summary
     ├─ Returns:
     │  ├─ total_items_count
     │  ├─ total_inventory_cost
     │  ├─ total_inventory_price
     │  ├─ category_breakdown (JSON)
     │  ├─ last_updated
     │  └─ budget_comparison
     │
     └─ Status: "within_budget" / "exceeds_budget"

POST /api/leads/{id}/inventory/summary/recalculate
     ├─ Trigger manual recalculation
     ├─ Process all approved selections
     ├─ Rebuild category breakdown
     └─ Response: Updated summary


LEAD ALLOCATION API:
────────────────────

GET  /api/leads/{id}/allocations
     ├─ Returns: All allocations for lead
     └─ Status breakdown: reserved/committed/released

PUT  /api/leads/{id}/allocations/{allocationId}/commit
     ├─ Change: reserved → committed
     ├─ Trigger: Fulfillment preparation
     └─ Response: Updated allocation

PUT  /api/leads/{id}/allocations/{allocationId}/release
     ├─ Change: committed → released
     ├─ Return qty to inventory pool
     └─ Response: Updated allocation

GET  /api/leads/{id}/allocations/by-status
     ├─ Query: status=reserved|committed|released
     └─ Returns: Filtered allocations


LEAD CONVERSION API:
────────────────────

POST /api/leads/{id}/convert-to-client
     ├─ Body:
     │  ├─ [optional] client_data (overrides lead data)
     │  └─ [optional] contact_data
     │
     ├─ Process:
     │  ├─ Validate lead status
     │  ├─ Create Client record
     │  ├─ Create ClientContact
     │  ├─ Link lead to client
     │  ├─ Transfer allocations
     │  └─ Update lead_status="closed_won"
     │
     └─ Response: 
        ├─ created_client_id
        ├─ created_contact_id
        └─ transfer_summary

GET  /api/leads/{id}/conversion-preview
     ├─ Dry-run conversion
     └─ Returns: What would be created
```

---

## Conclusion

The **Leads Flow with Inventory & Questionnaire** system is a **sophisticated, multi-layered lead management platform** that enables:

✅ **Lead Capture** - Multiple entry points (public form, admin, API)
✅ **Intelligent Questionnaires** - Dynamic, conditional, service-specific
✅ **Auto-Suggestions** - Answer-based inventory mapping
✅ **Flexible Selection** - Auto + manual inventory choices
✅ **Smart Allocations** - Reserve & commit with stock awareness
✅ **Comprehensive Reporting** - Cost breakdowns, budget tracking
✅ **Seamless Conversion** - Lead → Client transition
✅ **Multi-Tenancy** - Full data isolation per organization
✅ **Audit Trail** - Soft deletes, timestamps, modification tracking

### Key Metrics

| Aspect | Details |
|--------|---------|
| **Models** | 8 core entities |
| **Tables** | 8 database tables |
| **Relationships** | 15+ model connections |
| **Question Types** | 9 different input types |
| **Conditional Logic** | AND/OR/nested evaluation |
| **Allocation States** | 3 status workflow |
| **Lead Status Pipeline** | 8 stages from new to closed |

This architecture is **production-ready**, **scalable**, and **extensible** for complex business workflows.
