# RateRight Message Sequencing System

Automated SMS sequences based on lead stage. Runs every 60 seconds.

---

## How It Works

### Flow
```
Lead Stage Changes → Auto-Enrolled in Sequence → Steps Sent at Intervals → Sequence Completes
```

### Key Logic (sequenceProcessor.js)

1. **Find Due Enrollments:** `next_step_at <= NOW` and `status = 'active'`
2. **For Each Enrollment:**
   - Get current step from sequence
   - If SMS: personalize message, send via Twilio, log to communications
   - If call_reminder: create callback for manual follow-up
   - Increment `current_step`
   - Calculate `next_step_at` with randomization
   - If no more steps: mark `completed`

### Business Hours Protection
- Only sends **8am-6pm AEST**, **Monday-Friday**
- Messages due outside hours get rescheduled to next business day 8am
- Weekends are automatically skipped

### Send Windows (Tradie-Optimized)
| Window | Time (AEST) | Why |
|--------|-------------|-----|
| `morning` | 6:00-7:30am | Before site starts |
| `lunch` | 12:00-1:00pm | Lunch break |
| `knockoff` | 3:00-6:00pm | After work |
| `any` | 8:00am-6:00pm | General business |

### Randomization (Human-Like)
- **Delay Range:** `delay_days_min` to `delay_days_max` (random day in range)
- **Time Within Window:** Random hour + random minute
- Prevents robotic "exactly 24 hours" pattern

---

## Personalization Variables

| Variable | Replaced With |
|----------|---------------|
| `{first_name}` | Lead's first name or "there" |
| `{name}` | Full name |
| `{trade}` | Lead's trade/industry |
| `{company}` | Company name |
| `{sender_name}` | "Rocky" (default sender) |

---

## Worker Sequences (7 Stages)

### 1. Worker Intro (`not_signed_up`)
**Goal:** Get worker to sign up

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 0 | knockoff | Hey {first_name}, Rocky from RateRight. We connect tradies with work - only 9.9% when you get paid. Check us out: rateright.com.au/signup |
| 2 | Day 2-4 | morning | Hey {first_name}, still looking for {trade} work? We've got jobs coming through in your area. |
| 3 | Day 5-8 | knockoff | Last one from me {first_name}. If you're sorted, no dramas. We're here when you need work: rateright.com.au/signup |

---

### 2. Worker Complete Profile (`signed_up`)
**Goal:** Complete their profile

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 1-2 | morning | Hey {first_name}, saw you signed up - legend! Just need to finish your profile to start seeing jobs. Takes 2 mins. |
| 2 | Day 4-6 | knockoff | Hey {first_name}, your profile's almost done. Once complete you'll see {trade} jobs in your area straight away. |

---

### 3. Worker Connect Stripe (`profile_complete`)
**Goal:** Set up payments

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 1-2 | lunch | Hey {first_name}, profile's looking good! Last step - connect Stripe so you can get paid. Only takes a minute. |
| 2 | Day 4-5 | knockoff | Hey {first_name}, quick reminder - connect your Stripe and you're ready to start earning. No fees until you get paid. |

---

### 4. Worker Get Job Ready (`stripe_ready`)
**Goal:** Upload docs (white card, etc.)

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 1-2 | morning | Hey {first_name}, you're almost job-ready! Just need your white card and a few docs. Then you can start applying. |
| 2 | Day 3-5 | knockoff | Hey {first_name}, upload your docs and you'll be first in line for {trade} jobs. Heaps coming through. |

---

### 5. Worker Start Applying (`job_ready`)
**Goal:** Apply for first job

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 1-2 | morning | Hey {first_name}, you're job-ready! Check the app - there's {trade} work available now. Apply and we'll connect you. |
| 2 | Day 4-6 | knockoff | Hey {first_name}, seen any jobs you like? Apply for a few and we'll get you working. |

---

### 6. Worker Check-In (`working`)
**Goal:** Check satisfaction

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 3-5 | lunch | Hey {first_name}, how's the job going? Let us know if you need anything. And if you know other tradies looking for work, send them our way! |

---

### 7. Worker Referral Ask (`proven`)
**Goal:** Get referrals from proven workers

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 2-3 | knockoff | Hey {first_name}, legend work on that last job! Know any other {trade}s looking for work? We're always after good blokes. |
| 2 | Day 7-10 | morning | Hey {first_name}, just checking - any mates need work? Send them to rateright.com.au/signup and we'll look after them. |

---

## Contractor Sequences (5 Stages)

### 1. Contractor Intro (`not_signed_up`)
**Goal:** Get contractor to sign up

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 0 | knockoff | Hey {first_name}, Rocky from RateRight. We supply quality tradies to builders - FREE to use. Worth a look: rateright.com.au/signup |
| 2 | Day 2-4 | morning | Hey {first_name}, need any crew for upcoming jobs? We've got good {trade}s ready to go. |
| 3 | Day 5-8 | knockoff | Last check-in {first_name}. If you're all staffed up, no dramas. We're here when you need crew: rateright.com.au/signup |

---

### 2. Contractor Complete Profile (`signed_up`)
**Goal:** Complete company profile

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 1-2 | morning | Hey {first_name}, saw you signed up - good stuff! Finish your company profile and you can start posting jobs. |
| 2 | Day 4-6 | knockoff | Hey {first_name}, your profile's almost done. Complete it and you'll have access to quality {trade}s straight away. |

---

### 3. Contractor Post Job (`profile_complete`)
**Goal:** Post first job

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 1-2 | lunch | Hey {first_name}, profile's done! Ready to find crew? Post your first job and we'll match you with quality tradies. |
| 2 | Day 4-5 | knockoff | Hey {first_name}, got any jobs coming up? Post them and we'll send you the right blokes. Free to post. |

---

### 4. Contractor Satisfaction (`hired`)
**Goal:** Check if hire worked out

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 2-3 | knockoff | Hey {first_name}, how'd that hire go? Let us know if the tradie worked out. And if you need more crew, we've got plenty. |

---

### 5. Contractor Referral Ask (`active`)
**Goal:** Get referrals

| Step | Timing | Window | Message |
|------|--------|--------|---------|
| 1 | Day 3-5 | morning | Hey {first_name}, glad the crew's working out! Know any other builders who need tradies? Send them our way. |
| 2 | Day 10-14 | knockoff | Hey {first_name}, any builder mates struggling to find good crew? We're always looking after contractors who refer others. |

---

## API Endpoints

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/api/sequences` | GET | List all active sequences |
| `/api/sequences/:id` | GET | Get sequence with steps |
| `/api/sequences/:id/enroll` | POST | Enroll lead(s) in sequence |
| `/api/sequences/:id/unenroll` | POST | Remove lead from sequence |
| `/api/sequences/enrollments/active` | GET | Get active enrollments |
| `/api/sequences/enrollments/lead/:id` | GET | Get enrollments for a lead |
| `/api/sequences/enrollments/:id/pause` | POST | Pause enrollment |
| `/api/sequences/enrollments/:id/resume` | POST | Resume enrollment |
| `/api/sequences/enrollments/:id/skip` | POST | Skip to next step |
| `/api/sequences/enrollments/:id/send-now` | POST | Send current step immediately |
| `/api/sequences/lead/:id/opt-out` | POST | Toggle opt-out for lead |

---

## Auto-Stop Conditions

Sequences automatically stop when:
- Lead status becomes `converted`, `opted_out`, or `archived`
- Lead replies (manual review triggered)
- Sequence is disabled
- All steps completed

---

## Database Tables

### `sequences`
- id, name, description, channel (sms/email)
- stage, lead_type (worker/contractor)
- trigger_type (stage_change/manual)
- is_active

### `sequence_steps`
- sequence_id, step_order, name
- action_type (sms/call_reminder/wait)
- delay_days_min, delay_days_max
- send_window (morning/lunch/knockoff/any)
- message_template

### `sequence_enrollments`
- sequence_id, lead_id
- current_step (0-indexed)
- status (active/paused/completed)
- next_step_at, enrolled_at, completed_at
- pause_reason

---

## Files

| File | Purpose |
|------|---------|
| `src/jobs/sequenceProcessor.js` | Main processor (runs every 60s) |
| `src/routes/sequences.js` | API endpoints |
| `supabase/migrations/20260119115515_seed_stage_sequences_v2.sql` | Sequence definitions |
