# Territory Manager Lead Management System - Development Guide

## Overview

This guide documents the Territory Manager Lead Management system scaffolding and provides guidance for completing the implementation.

## Current Status: SCAFFOLDED

The lead management system has been scaffolded with basic structure but is **not fully functional**. This was intentionally left as a skeleton to be completed at a future date.

## What's Been Implemented

### 1. Database Schema (COMPLETE)
- **Location**: `/supabase/migrations/20250109_territory_manager_schema.sql`
- **Table**: `leads`
- **Fields**:
  - `id` (UUID, primary key)
  - `territory_manager_id` (UUID, references territory_managers)
  - `event_name` (VARCHAR(255))
  - `organizer_contact` (JSONB) - Contact information
  - `event_details` (JSONB) - Event details like date, type, etc.
  - `status` (VARCHAR(20)) - cold, contacted, confirmed, converted, dead
  - `notes` (TEXT[]) - Array of notes
  - `follow_up_date` (TIMESTAMP)
  - `created_at`, `updated_at` (TIMESTAMP)

### 2. Sample Data (COMPLETE)
- **Location**: `/supabase/migrations/20250109_add_sample_territories.sql`
- **Sample leads**: 4 leads with different statuses and realistic data
- **Sample territory managers**: 3 TMs with assigned territories

### 3. UI Components (SCAFFOLDED)
- **Location**: `/src/pages/territory-manager/leads/`
- **Files**:
  - `index.astro` - Lead listing page with filters and stats
  - `new.astro` - New lead creation form
  - `DEVELOPMENT_GUIDE.md` - This file

### 4. API Router Integration (SCAFFOLDED)
- **Location**: `/src/lib/territory-manager-router.ts`
- **Methods**:
  - `loadLeads()` - Load leads for current territory manager
  - `createLead()` - Create new lead
  - `updateLead()` - Update existing lead
  - `deleteLead()` - Delete lead

## What Needs to be Completed

### 1. API Endpoints (MISSING)
Create the following API endpoints:

```
/src/pages/api/territory-manager/leads/
├── index.ts        # GET: List leads, POST: Create lead
├── [id].ts         # GET: Get lead, PUT: Update lead, DELETE: Delete lead
└── stats.ts        # GET: Lead statistics
```

### 2. Frontend Functionality (PARTIALLY IMPLEMENTED)
- **Lead Creation**: Form exists but doesn't submit to API
- **Lead Editing**: No edit page exists
- **Lead Viewing**: No detailed view modal/page
- **Filters**: UI exists but filtering logic not implemented
- **Search**: UI exists but search not implemented
- **Stats**: Basic stats calculation implemented

### 3. Real-time Updates (MISSING)
- Supabase real-time subscriptions for live updates
- Auto-refresh when leads are updated

### 4. Lead Status Management (MISSING)
- Status change workflow
- Follow-up date automation
- Note adding functionality

## Technical Implementation Details

### Database Structure
```sql
-- Lead organizer_contact JSONB structure
{
  "name": "John Doe",
  "email": "john@example.com",
  "phone": "+1-555-0123",
  "title": "Event Coordinator",
  "organization": "ABC Events"
}

-- Lead event_details JSONB structure
{
  "event_type": "Wedding",
  "event_date": "2025-08-15",
  "venue": "Downtown Hotel",
  "expected_attendance": 150,
  "budget_range": "$5,000-$10,000",
  "description": "Elegant wedding reception"
}
```

### API Client Integration
The Territory Manager API client (`territory-manager-api.ts`) needs these methods:
- `getLeads(territoryManagerId: string): Promise<Lead[]>`
- `createLead(data: LeadFormData): Promise<Lead>`
- `updateLead(id: string, data: Partial<Lead>): Promise<Lead>`
- `deleteLead(id: string): Promise<void>`

### Frontend State Management
- Use Supabase real-time subscriptions for live updates
- Implement optimistic UI updates
- Add loading states and error handling

## Security Considerations

### Row Level Security (RLS)
Already implemented in schema:
- Territory managers can only see their own leads
- Admin can see all leads
- Proper filtering by territory_manager_id

### Validation
- Client-side validation exists in forms
- Server-side validation needed in API endpoints
- Sanitize all JSONB inputs

## Testing Data

Sample leads are available in the database:
- Wedding lead (confirmed status)
- Music festival lead (contacted status)
- Charity gala lead (cold status)
- Corporate conference lead (converted status)

## Future Enhancements

When completing this system, consider:

1. **Lead Scoring**: Implement scoring based on event size, budget, etc.
2. **Email Integration**: Send follow-up emails automatically
3. **Calendar Integration**: Sync follow-up dates with calendar
4. **Lead Import**: Bulk import leads from CSV/Excel
5. **Analytics**: Advanced reporting and conversion tracking
6. **Mobile Optimization**: Ensure mobile-friendly lead management

## Development Priority

1. **High Priority**: Complete API endpoints and basic CRUD operations
2. **Medium Priority**: Add real-time updates and advanced filtering
3. **Low Priority**: Add advanced features like lead scoring and analytics

## Files to Modify

When completing implementation:
- `/src/lib/territory-manager-api.ts` - Add lead management methods
- `/src/pages/api/territory-manager/leads/` - Create API endpoints
- `/src/pages/territory-manager/leads/index.astro` - Complete functionality
- `/src/pages/territory-manager/leads/new.astro` - Connect to API
- Create `/src/pages/territory-manager/leads/[id]/edit.astro` - Edit page
- Create `/src/pages/territory-manager/leads/[id]/view.astro` - View page

## Commission Integration

Remember to integrate with the commission system:
- When a lead is converted, create a commission record
- Track commission rate (currently $0.10 per ticket)
- Link converted leads to actual events for payout calculation

---

**Note**: This is a scaffolded system. All UI components and database schema are ready, but the API layer and complete functionality need to be implemented.