# Phase 10 Plan 1 — CRM Foundation: Leads, Activities, Reminders **Status:** ✅ COMPLETE **Phase:** 10 **Plan:** 01 **Wave:** 1 (Foundation) **Date Completed:** 2026-06-11 ## Objective Establish the CRM schema foundation for Phase 10 (CRM Pipeline & Activity Logging). Complete the `leads`, `activities`, and `reminders` tables in the database schema, establish pipeline stage enums, activity type definitions, and query layer patterns for lead management and activity logging. ## What Was Delivered ### Task 1: Schema Expansion ✓ **Tables Verified/Updated:** 1. **leads** table (already existed, added TypeScript types) - id (PK, nanoid) - name, email, phone, company - status (pipeline: contacted → qualified → proposal_sent → negotiating → won → lost) - last_contact_date, next_action, next_action_date - notes, created_at, updated_at - 12 columns total, all properly typed 2. **activities** table (already existed, added TypeScript types) - id (PK, nanoid) - lead_id (FK to leads, cascade delete) - type (call | email | meeting | note) - duration_minutes (optional, for calls/meetings) - notes (immutable) - activity_date, created_at - Timestamps with timezone support 3. **reminders** table (already existed, added TypeScript types) - id (PK, nanoid) - lead_id (FK to leads, cascade delete) - title, description - due_date (with timezone) - completed_at (nullable, immutable once set) - created_at **Relations Verified:** - leadsRelations: many quotes, many activities, many reminders - activitiesRelations: one lead - remindersRelations: one lead - quotesRelations: one lead (optional, nullable FK) **TypeScript Types Exported:** - `Lead`, `NewLead` - `Activity`, `NewActivity` - `Reminder`, `NewReminder` ### Task 2: Validators (Zod Schemas) ✓ **File:** `src/lib/lead-validators.ts` (51 lines) **Enums:** - `LEAD_STAGES`: ["contacted", "qualified", "proposal_sent", "negotiating", "won", "lost"] - `ACTIVITY_TYPES`: ["call", "email", "meeting", "note"] **Schemas:** 1. `createLeadSchema` — Admin lead creation with validation - name: required, max 100 chars - email, phone, company: optional - status: enum with default "contacted" - notes: optional, max 1000 chars 2. `updateLeadSchema` — Lead update (all fields optional) 3. `createActivitySchema` — Activity logging - lead_id: required - type: required, enum - activity_date: date or string - duration_minutes: optional number >= 0 - notes: required, max 1000 chars 4. `createReminderSchema` — Reminder creation - lead_id: required - title: required, max 200 chars - description: optional - due_date: date or string 5. `updateLeadStageSchema` — Pipeline stage change - lead_id: required - stage: required, enum **Type Exports:** - `CreateLeadInput`, `UpdateLeadInput` - `CreateActivityInput`, `CreateReminderInput` - `UpdateLeadStageInput` ### Task 3: Service Layer (Query Functions) ✓ **File:** `src/lib/lead-service.ts` (191 lines) **Query Functions:** **Lead Queries:** - `getAllLeads(limit?, offset?)` — Paginated all leads - `getLeadById(id)` — Single lead by ID - `getLeadsByStage(stage)` — Pipeline view by stage - `getLeadsNeedingFollowUp(daysAgo?)` — No recent contact - `searchLeads(query)` — Full-text search by name/email/company - `getQuotesByLeadId(leadId)` — Quotes for a lead **Lead Mutations:** - `updateLead(leadId, data)` — Update any lead fields - `updateLeadStage(leadId, stage)` — Change pipeline stage **Activity Operations:** - `getActivityLog(leadId)` — Reverse chronological activity history - `createActivity(data)` — Create activity + auto-update lead.last_contact_date - Atomic: sets lead.last_contact_date + updated_at on activity creation **Reminder Operations:** - `getUpcomingReminders(leadId)` — Incomplete reminders for lead - `getOverdueReminders()` — All overdue reminders (admin widget) - `createReminder(data)` — Create reminder with due date - `completeReminder(reminderId)` — Mark reminder done ### Task 4: Drizzle Migration ✓ **Status:** Schema already existed in database schema definition **Generated:** Migration tables already present; no new changes needed **Ready for:** Database deployment when Postgres is reachable ## Verification Checklist ✅ Schema compiles: `npm run build` passes with 0 TS errors ✅ Drizzle migration file: Schema ready (tables exist in schema.ts) ✅ Lead validators: All Zod schemas import cleanly ✅ Query layer: All functions exported and type-safe ✅ Relations: leads ↔ activities (cascade), leads ↔ reminders (cascade), quotes → leads (optional) ✅ TypeScript types: Lead, Activity, Reminder fully exported ✅ Data safety: No existing data at risk (schema-only changes) ## Technical Details **Files Created:** - `src/lib/lead-validators.ts` (51 lines) - `src/lib/lead-service.ts` (191 lines) **Files Modified:** - `src/db/schema.ts` (added Activity, NewActivity, Reminder, NewReminder type exports) **Code Quality:** - Full TypeScript type safety - Italian localization for validation messages - Immutable audit trail (activities/reminders) - Cascade delete for data integrity - Pagination support for scalability ## Security Considerations **Implemented:** - All lead operations require Auth.js session (no public API) - Activity dates validated server-side (no future backdating in future phases) - Cascade delete prevents orphaned activity/reminder records - Activity records are immutable (audit trail) **Deferred to Phase 10 Plan 2-3:** - Rate limiting on lead creation (MVP: assume honest admin) - Email/phone validation (accept unverified at lead stage, verify on win) ## Requirements Met ✅ CRM-01: Leads table with all required fields (name, email, phone, company, status, etc.) ✅ CRM-02: Activities table with immutable audit trail ✅ CRM-03: Reminders table with follow-up scheduling ✅ CRM-04: Pipeline stage enums and transitions ## Ready for Next Phase 10 Plan 2 (Lead CRUD UI) and Plan 3 (Activity Logging + Send Quote) can now: - Use the validators for form validation - Call the service layer for lead and activity operations - Render lead details, pipeline views, activity logs - Create reminders for follow-ups - Send quotes to leads via email (Phase 12) ## Progress - **Total Plans:** 8 - **Completed Plans:** 6 (Phase 7: 2, Phase 8: 1, Phase 9: 3) - **Progress:** 75% - **Current Phase:** 10/1 (Wave 1) ✅ Complete