# Actionable Sales Playbook - Plan

## Problem
Current Sales Playbook/Strategy shows general advice but requires mental translation to action. Reps still have to figure out who to contact and what to say.

## Solution
Show top 3 leads with AI-generated personalized messages ready to send in one tap. Add bulk personalized outreach for leads in same funnel stage.

---

## Feature Overview

### 1. Today's Plays (Top 3 Leads + AI Messages)

**What the user sees:**
```
+------------------------------------------+
| TODAY'S PLAYS                            |
+------------------------------------------+
| #1 Tony's Formwork (Hot, 3 days silent)  |
| ├─ "Hey Tony, just checking in on..."    | [Send]
| ├─ "Quick one - still looking at..."     | [Send]
| └─ "Saw formwork prices jumped, wanted..."| [Send]
+------------------------------------------+
| #2 Sarah's Electrical (Warm, callback)   |
| ├─ "Hi Sarah, as promised calling..."    | [Send]
| ├─ "Following up on the quote..."        | [Send]
| └─ "Any questions I can help with?"      | [Send]
+------------------------------------------+
| #3 Mike's Plumbing (Hot, buying signal)  |
| ├─ "Mike, saw you were ready to..."      | [Send]
| ...                                       |
+------------------------------------------+
```

**How it works:**
1. Fetch top 3 leads from call list ranker (already exists)
2. For each lead, generate 3 personalized SMS options via GPT
3. Each message is a different angle:
   - **Follow-up**: Reference last conversation
   - **Value prop**: Highlight benefit relevant to their trade
   - **Urgency/Timing**: Create reason to act now
4. One-tap send button next to each message
5. After sending, card updates to show "Sent ✓" and next lead loads

### 2. Bulk Personalized Outreach

**What the user sees:**
```
+------------------------------------------+
| BULK ACTION                              |
| 12 warm leads not contacted in 7+ days   |
| [Preview All] [Send All Personalized]    |
+------------------------------------------+
```

**Preview modal:**
```
+------------------------------------------+
| PREVIEW: 12 Personalized Messages        |
+------------------------------------------+
| ☑ Tony's Formwork                        |
|   "Hey Tony, been a week since..."       |
| ☑ Sarah's Electrical                     |
|   "Hi Sarah, checking back on..."        |
| ☑ Mike's Plumbing                        |
|   "Mike, still interested in..."         |
| ... 9 more                               |
+------------------------------------------+
| [ ] Select All  [Send 12 Messages]       |
+------------------------------------------+
```

**How it works:**
1. Query leads by criteria:
   - Same funnel stage (e.g., all "warm" leads)
   - Last contact > X days ago (configurable: 3, 7, 14 days)
   - Not contacted today
2. Generate personalized message for each (batch GPT call)
3. Preview modal shows all messages with checkboxes
4. User can edit individual messages before send
5. Send with rate limiting (1 per second to avoid Twilio issues)

---

## Database Schema

```sql
-- Track playbook message generations and sends
CREATE TABLE IF NOT EXISTS playbook_messages (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES auth.users(id),
  lead_id UUID REFERENCES leads(id),
  message_text TEXT NOT NULL,
  message_angle VARCHAR(50), -- 'follow_up', 'value_prop', 'urgency'
  was_sent BOOLEAN DEFAULT FALSE,
  sent_at TIMESTAMPTZ,
  generated_at TIMESTAMPTZ DEFAULT NOW(),
  batch_id UUID, -- Groups bulk sends together
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Index for finding recent generations (cache check)
CREATE INDEX idx_playbook_messages_lead_recent
ON playbook_messages(lead_id, generated_at DESC);

-- Index for batch tracking
CREATE INDEX idx_playbook_messages_batch
ON playbook_messages(batch_id) WHERE batch_id IS NOT NULL;
```

---

## API Endpoints

### GET /api/playbook/today
Returns top 3 leads with 3 AI-generated messages each.

**Response:**
```json
{
  "leads": [
    {
      "id": "uuid",
      "name": "Tony's Formwork",
      "trade": "Formwork",
      "status": "hot",
      "daysSinceContact": 3,
      "priorityReason": "Hot lead going cold",
      "messages": [
        { "id": "msg-uuid", "text": "Hey Tony...", "angle": "follow_up" },
        { "id": "msg-uuid", "text": "Quick one...", "angle": "value_prop" },
        { "id": "msg-uuid", "text": "Saw formwork...", "angle": "urgency" }
      ]
    },
    // ... 2 more leads
  ],
  "generatedAt": "2026-01-18T10:00:00Z",
  "cacheExpiresAt": "2026-01-18T14:00:00Z"
}
```

### POST /api/playbook/send
Send a single playbook message.

**Body:**
```json
{
  "leadId": "uuid",
  "messageId": "msg-uuid"  // or "messageText" for edited
}
```

### GET /api/playbook/bulk-preview
Get leads matching bulk criteria with generated messages.

**Query params:**
- `status`: warm, hot, cool (default: warm)
- `daysSinceContact`: 3, 7, 14 (default: 7)
- `limit`: max leads (default: 20, max: 50)

**Response:**
```json
{
  "leads": [
    {
      "id": "uuid",
      "name": "Tony's Formwork",
      "message": "Hey Tony, been a week since...",
      "lastContactDays": 8
    }
    // ... more leads
  ],
  "totalMatching": 12,
  "batchId": "uuid"
}
```

### POST /api/playbook/bulk-send
Send bulk personalized messages.

**Body:**
```json
{
  "batchId": "uuid",
  "leadIds": ["uuid1", "uuid2", ...],  // Selected leads
  "edits": {  // Optional message overrides
    "uuid1": "Custom message for this lead"
  }
}
```

---

## AI Prompt Design

### Individual Lead Messages
```
Generate 3 SMS messages for a sales rep to send to a lead.

LEAD CONTEXT:
- Name: {first_name} ({company_name})
- Trade: {trade}
- Status: {status} lead
- Days since last contact: {days}
- Last message from us: "{last_outbound}"
- Last message from them: "{last_inbound}"
- Notes: {notes}
- Objections raised: {objections}

RULES:
1. Under 160 characters each
2. Natural Australian tone (mate, cheers, no worries)
3. NO spam phrases (limited time, act now, don't miss out)
4. Reference specific context when possible
5. Each message takes a different approach:
   - Message 1 (follow_up): Reference previous conversation
   - Message 2 (value_prop): Highlight benefit for their trade
   - Message 3 (urgency): Create legitimate reason to respond

OUTPUT FORMAT (JSON):
[
  {"angle": "follow_up", "text": "..."},
  {"angle": "value_prop", "text": "..."},
  {"angle": "urgency", "text": "..."}
]
```

### Bulk Messages (Batch)
```
Generate personalized SMS messages for multiple leads. Each should feel individual, not templated.

LEADS:
{leads_json}

RULES:
- Under 160 chars each
- Vary the opening (don't start every message the same way)
- Reference their specific trade/context
- Australian casual tone

OUTPUT: Array matching input order with personalized message for each.
```

---

## Frontend Components

### TodaysPlays.jsx
Main component showing top 3 leads with message options.

```jsx
// Structure
<TodaysPlays>
  <PlayHeader title="Today's Plays" subtitle="Your top 3 leads with ready-to-send messages" />

  {leads.map(lead => (
    <PlayCard key={lead.id}>
      <LeadInfo name={lead.name} status={lead.status} reason={lead.priorityReason} />
      <MessageOptions>
        {lead.messages.map(msg => (
          <MessageOption
            key={msg.id}
            text={msg.text}
            onSend={() => handleSend(lead.id, msg.id)}
            onEdit={() => openEditor(lead.id, msg)}
          />
        ))}
      </MessageOptions>
      <QuickActions>
        <CallButton leadId={lead.id} />
        <SkipButton onSkip={() => skipLead(lead.id)} />
      </QuickActions>
    </PlayCard>
  ))}

  <BulkActionCard
    count={bulkCount}
    criteria={bulkCriteria}
    onPreview={() => openBulkModal()}
  />
</TodaysPlays>
```

### BulkSendModal.jsx
Preview and send bulk personalized messages.

```jsx
<BulkSendModal>
  <Header>
    <Title>Send to {selectedCount} leads</Title>
    <Filters>
      <StatusFilter value={status} onChange={setStatus} />
      <DaysFilter value={days} onChange={setDays} />
    </Filters>
  </Header>

  <MessageList>
    {leads.map(lead => (
      <BulkMessageRow key={lead.id}>
        <Checkbox checked={selected[lead.id]} onChange={toggle} />
        <LeadName>{lead.name}</LeadName>
        <MessagePreview
          text={edits[lead.id] || lead.message}
          onEdit={() => openEditor(lead.id)}
        />
      </BulkMessageRow>
    ))}
  </MessageList>

  <Footer>
    <SelectAll />
    <SendButton onClick={handleBulkSend} disabled={selectedCount === 0}>
      Send {selectedCount} Messages
    </SendButton>
  </Footer>
</BulkSendModal>
```

---

## Safeguards

### Cost Control
- Cache generated messages for 4 hours per lead
- Use GPT-4o-mini (cheaper, fast enough for SMS)
- Batch bulk generation in single API call (up to 20 leads)
- Max 3 regenerations per lead per day

### Spam Prevention
- Max 20 bulk messages per day per user
- Require preview before bulk send
- Don't include leads contacted in last 24 hours
- Run all messages through compliance checker

### Quality Control
- Messages checked against brand guidelines
- Flag any message with banned phrases
- User can edit before sending
- Track which message angles get best response rates

---

## Learning Integration

Track which message angles work best:
- Log message angle with each send
- When lead replies, attribute to message angle
- Over time, prioritize angles with higher response rates
- Per-trade optimization (electricians respond to X, plumbers to Y)

---

## UI Location

**Option A:** Replace current Strategy Modal content
- Pros: Already exists, users know where to find it
- Cons: Loses the "wisdom" aspect

**Option B:** New "Plays" tab in bottom nav
- Pros: Prime real estate, clear purpose
- Cons: Another nav item

**Option C:** Top section of Dashboard
- Pros: First thing they see
- Cons: Dashboard already busy

**Recommended:** Option A - Enhance Strategy Modal
- Keep the AI wisdom greeting at top
- Add "Today's Plays" as the main content
- Bulk action at bottom

---

## Implementation Order

1. [x] Database: playbook_messages table ✅
2. [x] Backend: GET /api/playbook/today (top 3 + AI messages) ✅
3. [x] Backend: POST /api/playbook/send (single send) ✅
4. [x] Frontend: TodaysPlays component ✅
5. [x] Integrate into Strategy Modal ✅
6. [x] Backend: GET /api/playbook/bulk-preview ✅
7. [x] Backend: POST /api/playbook/bulk-send ✅
8. [x] Frontend: BulkSendModal ✅
9. [ ] Safeguards: rate limits, compliance check (basic version included)
10. [ ] Learning: track message angle effectiveness (future enhancement)

---

## Success Metrics

- Messages sent via playbook per day
- Response rate on playbook messages vs manual
- Time from opening app to first message sent
- Bulk send usage (how many, how often)
- Which message angles perform best

---

## Estimated Effort

| Phase | Effort |
|-------|--------|
| Database + Backend (individual) | 1 day |
| Frontend (Today's Plays) | 1 day |
| Backend (bulk) | 1 day |
| Frontend (Bulk Modal) | 0.5 day |
| Safeguards + Polish | 0.5 day |
| **Total** | **4 days** |

---

*Created: Jan 18, 2026*
