---
# System prepended metadata

title: Create Opportunity from Email - Flow Diagram

---

# Create Opportunity from Email - Flow Diagram

## Overview

This Screen Flow enables sales users to create Opportunities directly from customer email content using **Gemini AI** for intelligent data extraction.

---

## Simplified Decision Logic Flow

```mermaid
flowchart TD
    A[Screen 1: Email Input] --> B[Apex: Parse Email with Gemini]
    B --> C{Success?}
    C -->|No| E[Show Error Message]
    E -->|Try Again| A
    C -->|Yes| D[Apex: Search Account/Contact]
    
    D --> F{Account Found?}
    F -->|Yes| G{Contact Found?}
    F -->|No| H{Lead Found?}
    
    G -->|Yes| I[Screen 2: Review Data]
    G -->|No| J[Warning: No Contact]
    J --> K[Redirect to Create Contact with pre-filled data]
    
    H -->|Yes| L[Screen: Convert Lead?]
    L -->|Convert| M[Apex: Convert Lead to Account+Contact]
    M --> I
    L -->|Skip| N[Redirect to Create Account with pre-filled data]
    
    H -->|No| N
    
    I --> O{Pricebook Exists?}
    O -->|No| P[Apex: Auto-Create Pricebook]
    O -->|Yes| Q[Apex: Match Products]
    P --> Q
    
    Q --> R[Screen 3: Product Selection]
    R --> S[Apex: Create Opportunity]
    S --> T{Success?}
    T -->|Yes| U[Screen 4: Confirmation]
    T -->|No| V[Show Error and Retry]
    V -->|Retry| R
```

---

## Pricebook Decision Subflow

```mermaid
flowchart TD
    A[Account/Contact Found] --> B[Action_GetAccountPricebooks]
    B --> C{Pricebook Count?}
    C -->|0| D[Screen_CreatePricebook]
    C -->|1| E[Use existing pricebook]
    C -->|2+| F[Screen_SelectPricebook]
    D --> G[Action_CreatePricebook]
    G --> H[Product Matching]
    F --> I[Assign_SelectedPricebook]
    I --> H
    E --> J[Assign_SinglePricebook]
    J --> H
```

---

## Lead Conversion Subflow

```mermaid
flowchart TD
    L[Lead Found] --> M[Screen_ConvertLead]
    M --> N[User converts Lead externally]
    N --> O[Action_GetConvertedLeadInfo]
    O --> P{Converted?}
    P -->|Yes| Q[Assign_ConvertedAccount]
    Q --> R[Continue to Pricebook Selection]
    P -->|No| S[Screen_LeadNotConverted]
    S -->|Try Again| M
```

---

## Complete Technical Flow Diagram

```mermaid
flowchart TD
    subgraph START["🚀 START"]
        S([Start])
    end

    subgraph PHASE1["📧 Phase 1: Email Input & AI Parsing"]
        Screen_EmailInput["📧 Screen: Email Input<br/>• Email Content (required)<br/>• Sender Email (optional)<br/>• Sender Name (optional)"]
        Action_ParseEmail["🤖 Action: Parse Email with Gemini AI<br/>(GeminiFlowAction)"]
        Decision_ParseSuccess{"Parse Successful?"}
        Screen_ParseError["❌ Screen: Parse Error<br/>Show error message"]
    end

    subgraph PHASE2["🔍 Phase 2: Data Extraction & Search"]
        Action_SearchAccountContact["🔍 Action: Search Account/Contact<br/>(AccountContactSearchFlowAction)"]
        Action_GetPricebook["📚 Action: Get Account Pricebook<br/>(PricebookFlowAction)"]
        Action_ConvertProductsToTable["📋 Action: Convert Products to Table<br/>(ProductTableFlowAction)"]
        Screen_ReviewData["📋 Screen: Review Extracted Data<br/>• Contact Info<br/>• SF Records<br/>• Products Table<br/>• Opportunity Name<br/>• Notes"]
    end

    subgraph PHASE3["👤 Phase 3: Account/Lead Resolution"]
        Decision_AccountFound{"Account Found?"}
        Decision_LeadFound{"Lead Found?"}
        Screen_NoRecordsFound["⚠️ Screen: No Records Found<br/>Create Account first"]
        Screen_ConvertLead["🔄 Screen: Convert Lead<br/>Link to Lead record"]
        Action_GetConvertedLeadInfo["🔄 Action: Get Converted Lead Info<br/>(GetConvertedLeadInfo)"]
        Decision_LeadConverted{"Lead Converted?"}
        Screen_LeadNotConverted["⚠️ Screen: Lead Not Converted<br/>Try again"]
        Assign_AccountFromSearch["📝 Assign: Account From Search"]
        Assign_ConvertedAccount["📝 Assign: Converted Account"]
    end

    subgraph PHASE4["💰 Phase 4: Pricebook Selection"]
        Action_GetAccountPricebooks["📚 Action: Get Account Pricebooks<br/>(GetAccountPricebooksAction)"]
        Decision_PricebookCount{"How Many Pricebooks?"}
        Screen_CreatePricebook["📗 Screen: Create Pricebook<br/>Enter new pricebook name"]
        Screen_SelectPricebook["📚 Screen: Select Pricebook<br/>Choose from multiple"]
        Action_CreatePricebook["📗 Action: Create Pricebook<br/>(CreatePricebookAction)"]
        Assign_SinglePricebook["📝 Assign: Single Pricebook"]
        Assign_SelectedPricebook["📝 Assign: Selected Pricebook"]
        Assign_CreatedPricebook["📝 Assign: Created Pricebook"]
    end

    subgraph PHASE5["📦 Phase 5: Product Selection"]
        Action_MatchProducts["🎯 Action: Match Products<br/>(ProductMatchFlowAction)"]
        Screen_ProductSelection["📦 Screen: Product Selection<br/>(c:productSelectionFlow LWC)"]
    end

    subgraph PHASE6["✅ Phase 6: Opportunity Creation"]
        Action_CreateOpportunity["✨ Action: Create Opportunity<br/>(CreateOpportunityFlowAction)"]
        Decision_CreateSuccess{"Opportunity Created?"}
        Screen_Success["✅ Screen: Success<br/>Link to Opportunity"]
        Screen_CreateError["❌ Screen: Create Error"]
    end

    subgraph ERROR["⚠️ Error Handling"]
        Screen_Error["❌ Screen: Error<br/>Show fault message"]
    end

    %% Main Flow Connections
    S --> Screen_EmailInput
    Screen_EmailInput --> Action_ParseEmail
    Action_ParseEmail --> Decision_ParseSuccess
    Action_ParseEmail -.->|Fault| Screen_Error
    
    Decision_ParseSuccess -->|Success| Action_SearchAccountContact
    Decision_ParseSuccess -->|Parse Failed| Screen_ParseError
    Screen_ParseError -->|Try Again| Screen_EmailInput
    
    Action_SearchAccountContact --> Action_GetPricebook
    Action_SearchAccountContact -.->|Fault| Screen_Error
    Action_GetPricebook --> Action_ConvertProductsToTable
    Action_GetPricebook -.->|Fault| Screen_Error
    Action_ConvertProductsToTable --> Screen_ReviewData
    Action_ConvertProductsToTable -.->|Fault| Screen_Error
    
    Screen_ReviewData --> Decision_AccountFound
    
    Decision_AccountFound -->|Account Found| Assign_AccountFromSearch
    Decision_AccountFound -->|No Account| Decision_LeadFound
    
    Decision_LeadFound -->|Lead Found| Screen_ConvertLead
    Decision_LeadFound -->|No Lead| Screen_NoRecordsFound
    
    Screen_ConvertLead --> Action_GetConvertedLeadInfo
    Action_GetConvertedLeadInfo --> Decision_LeadConverted
    Action_GetConvertedLeadInfo -.->|Fault| Screen_Error
    
    Decision_LeadConverted -->|Lead Converted| Assign_ConvertedAccount
    Decision_LeadConverted -->|Not Converted| Screen_LeadNotConverted
    Screen_LeadNotConverted -->|Try Again| Screen_ConvertLead
    
    Assign_AccountFromSearch --> Action_GetAccountPricebooks
    Assign_ConvertedAccount --> Action_GetAccountPricebooks
    Action_GetAccountPricebooks -.->|Fault| Screen_Error
    
    Action_GetAccountPricebooks --> Decision_PricebookCount
    
    Decision_PricebookCount -->|No Pricebook| Screen_CreatePricebook
    Decision_PricebookCount -->|One Pricebook| Assign_SinglePricebook
    Decision_PricebookCount -->|Multiple Pricebooks| Screen_SelectPricebook
    
    Screen_CreatePricebook --> Action_CreatePricebook
    Action_CreatePricebook --> Assign_CreatedPricebook
    Action_CreatePricebook -.->|Fault| Screen_Error
    Screen_SelectPricebook --> Assign_SelectedPricebook
    
    Assign_SinglePricebook --> Action_MatchProducts
    Assign_SelectedPricebook --> Action_MatchProducts
    Assign_CreatedPricebook --> Action_MatchProducts
    
    Action_MatchProducts --> Screen_ProductSelection
    Action_MatchProducts -.->|Fault| Screen_Error
    
    Screen_ProductSelection --> Action_CreateOpportunity
    Action_CreateOpportunity --> Decision_CreateSuccess
    Action_CreateOpportunity -.->|Fault| Screen_Error
    
    Decision_CreateSuccess -->|Success| Screen_Success
    Decision_CreateSuccess -->|Create Failed| Screen_CreateError
```

---

## Flow Elements Summary

### Screens (12 total)
| Screen | Purpose |
|--------|---------|
| `Screen_EmailInput` | Enter email content and sender info |
| `Screen_ReviewData` | Review AI-extracted data before proceeding |
| `Screen_ConvertLead` | Instructions to convert Lead via standard UI |
| `Screen_NoRecordsFound` | No Account/Contact/Lead found - redirect to create |
| `Screen_LeadNotConverted` | Lead conversion not completed - retry |
| `Screen_CreatePricebook` | Create new Pricebook for Account |
| `Screen_SelectPricebook` | Select from multiple Pricebooks |
| `Screen_ProductSelection` | LWC component for product selection |
| `Screen_Success` | Opportunity created successfully |
| `Screen_ParseError` | Email parsing failed |
| `Screen_CreateError` | Opportunity creation failed |
| `Screen_Error` | Generic fault error handler |

### Apex Actions (10 total)
| Action | Apex Class | Purpose |
|--------|------------|---------|
| `Action_ParseEmail` | `GeminiFlowAction` | Parse email with Gemini AI |
| `Action_SearchAccountContact` | `AccountContactSearchFlowAction` | Find Account/Contact/Lead |
| `Action_GetPricebook` | `PricebookFlowAction` | Get Account's linked Pricebook |
| `Action_GetAccountPricebooks` | `GetAccountPricebooksAction` | List all Account Pricebooks |
| `Action_CreatePricebook` | `CreatePricebookAction` | Create new Pricebook |
| `Action_ConvertProductsToTable` | `ProductTableFlowAction` | Generate HTML table for display |
| `Action_GetConvertedLeadInfo` | `GetConvertedLeadInfo` | Check Lead conversion status |
| `Action_MatchProducts` | `ProductMatchFlowAction` | Match products to specs from Pricebook |
| `Action_CreateOpportunity` | `CreateOpportunityFlowAction` | Create Opportunity + Line Items |

### Decisions (7 total)
| Decision | Condition | Outcomes |
|----------|-----------|----------|
| `Decision_ParseSuccess` | `Action_ParseEmail.success == true` | Success → Search / Failed → Error |
| `Decision_AccountFound` | `Action_SearchAccountContact.accountFound == true` | Found → Assign / Not Found → Check Lead |
| `Decision_LeadFound` | `Action_SearchAccountContact.leadFound == true` | Found → Convert / Not Found → No Records |
| `Decision_LeadConverted` | `Action_GetConvertedLeadInfo.isConverted == true` | Converted → Proceed / Not → Retry |
| `Decision_PricebookCount` | `Action_GetAccountPricebooks.pricebookCount` | 0 → Create / 1 → Use / 2+ → Select |
| `Decision_CreateSuccess` | `Action_CreateOpportunity.success == true` | Success → Done / Failed → Error |

### Variables (5 total)
| Variable | Type | Purpose |
|----------|------|---------|
| `varAccountId` | String | Selected/Converted Account ID |
| `varContactId` | String | Selected/Converted Contact ID |
| `varOpportunityId` | String (Output) | Created Opportunity ID |
| `varSelectedProductsJson` | String | Products JSON from LWC |
| `varSelectedPricebookId` | String | Selected Pricebook ID |

---

## Data Flow Sequence

```mermaid
sequenceDiagram
    participant User
    participant Flow
    participant GeminiAI as Gemini AI
    participant Salesforce as Salesforce DB
    participant LWC as Product LWC

    User->>Flow: Paste Email Content
    Flow->>GeminiAI: Parse Email
    GeminiAI-->>Flow: Contact, Company, Products JSON
    
    Flow->>Salesforce: Search Account/Contact/Lead
    Salesforce-->>Flow: Matching Records
    
    Flow->>Salesforce: Get Pricebook
    Salesforce-->>Flow: Pricebook Info
    
    Flow->>User: Review Extracted Data
    
    alt Account Found
        Flow->>Flow: Assign Account/Contact
    else Lead Found
        User->>Salesforce: Convert Lead (external)
        Flow->>Salesforce: Get Converted Info
        Salesforce-->>Flow: Account/Contact IDs
    else No Records
        Flow->>User: Show "No Records" - Exit
    end
    
    Flow->>Salesforce: Get Account Pricebooks
    Salesforce-->>Flow: Pricebook List
    
    alt No Pricebook
        User->>Flow: Enter Pricebook Name
        Flow->>Salesforce: Create Pricebook
    else One Pricebook
        Flow->>Flow: Auto-assign Pricebook
    else Multiple Pricebooks
        User->>Flow: Select Pricebook
    end
    
    Flow->>Salesforce: Match Products
    Salesforce-->>Flow: Matched Products
    
    Flow->>LWC: Display Products
    User->>LWC: Select Products & Quantities
    LWC-->>Flow: Selected Products JSON
    
    Flow->>Salesforce: Create Opportunity + Line Items
    Salesforce-->>Flow: Opportunity ID
    
    Flow->>User: Success! View Opportunity
```

---

## LWC Component

The flow uses a custom LWC component [c:productSelectionFlow](file:///home/user/Documents/Salesforce%20Test/opportunity-agent/opportunity-agent/force-app/main/default/lwc/productSelectionFlow) on the Product Selection screen:

**Inputs:**
| Parameter | Source | Description |
|-----------|--------|-------------|
| `productsJson` | `Action_ParseEmail.productsJson` | Products extracted from email |
| `pricebookId` | `varSelectedPricebookId` | Selected pricebook ID |
| `accountId` | `varAccountId` | Account ID |

**Outputs:**
| Parameter | Target | Description |
|-----------|--------|-------------|
| `selectedProductsJson` | `varSelectedProductsJson` | User-selected products with quantities |

---

## Error Handling

All Apex actions have **fault connectors** that route to `Screen_Error`, displaying the `$Flow.FaultMessage` to the user.

| Error Screen | Trigger | Recovery |
|--------------|---------|----------|
| `Screen_ParseError` | Gemini AI parsing fails | Try Again → Email Input |
| `Screen_CreateError` | Opportunity creation fails | Go Back → Review |
| `Screen_Error` | Any Apex action fault | Display fault message |
| `Screen_NoRecordsFound` | No Account/Lead found | Exit flow |
| `Screen_LeadNotConverted` | Lead not yet converted | Try Again → Convert Lead |
