# Leads and Sales Pipeline

**Task 013 — implemented**

## Overview

Leads represent potential business interest; **Opportunities** track deals through the sales pipeline; **Tasks** drive follow-up actions. AI classification **does not auto-create leads** — conversion is explicit via API or inbox UI.

## Lead sources

| Source | Description |
|--------|-------------|
| `inbox` | Converted from classified `EmailReply` |
| `campaign` / `campaign_reply` | Campaign-related capture |
| `import` | Market import |
| `manual` | BD creates via `/leads/new` |
| `website`, `referral`, `other` | Other channels |

## Classification → Lead mapping

Rules: `src/lib/lead-rules.ts` — `mapClassificationToLead()`

| Intent | Create lead? | Status | Temperature | Priority | Opportunity stage | Task |
|--------|--------------|--------|-------------|----------|-------------------|------|
| `proposal_request` | yes | qualified | hot | very_high | proposal | send_proposal |
| `meeting_request` | yes | qualified | hot | very_high | meeting | schedule_meeting |
| `interested` | yes | qualified | warm | high | interested | call |
| `more_info_request` | yes | contacted | warm | high | contacted | send_more_info |
| `not_interested`, `wrong_contact`, `spam`, `auto_reply`, `out_of_office` | no | — | — | — | — | — |
| `unknown` | no (manual/force) | — | — | — | — | — |

Use `POST /api/leads/from-email-reply` with `{ "force": true }` to override non-lead-worthy classification.

## Email reply conversion flow

1. Classify reply (Task 012).
2. User clicks **تحويل إلى Lead** on inbox detail or calls API.
3. Service checks duplicate `emailReplyId` on `leads`.
4. Creates **Lead** + **Opportunity** (stage from mapping) + **Task** (from recommended action).
5. Sets `EmailReply.status` → `linked_to_lead`.
6. Logs activities: `lead_created`, `stage_changed`.

Service: `src/server/services/lead.service.ts` — `convertEmailReplyToLead()`

## Lead fields (model)

- Links: `companyId`, `personId`, `campaignId`, `emailReplyId`, `aiClassificationId`
- Qualification: `status`, `temperature`, `priority`, `leadScore`, `serviceInterest`, `notes`
- `assignedTo` (User)

Unique sparse index on `emailReplyId` prevents duplicate inbox leads.

## Opportunity stages & probability

| Stage | Default probability % |
|-------|----------------------|
| new_lead | 10 |
| contacted | 20 |
| interested | 35 |
| meeting | 50 |
| proposal | 65 |
| negotiation | 80 |
| won | 100 |
| lost | 0 |
| postponed | 25 |

`moveOpportunityStage()` recalculates probability and logs `stage_changed` activity.

## Task generation

Created on email conversion or via `createFollowUpTaskForLead()`. Linked with `relatedEntityType: "lead"`.

## APIs

See [03-api-specification.md](./03-api-specification.md) — `/api/leads`, `/api/opportunities`, `/api/tasks`.

## UI

| Route | Purpose |
|-------|---------|
| `/leads` | List, filters, manual create link |
| `/leads/new` | Manual lead form |
| `/leads/[id]` | Detail, status, create opportunity |
| `/pipeline` | Kanban by stage (dropdown move) |
| `/opportunities/[id]` | Detail, move stage, won/lost |
| `/tasks` | Open tasks, complete |
| Inbox detail | **تحويل إلى Lead** on AI panel |
| Company profile | **إنشاء Lead** / **إنشاء مهمة** quick actions (`entity-quick-actions.tsx`) |
| Person profile | Same quick actions with `personId` / `companyId` prefill |

Quick lead create uses `POST /api/leads` with `source: "import"`, `companyId`/`personId`, `serviceInterest`, `notes`, `priority`. Task create uses `POST /api/tasks` with `relatedEntityType` `company` or `person`, `dueDate`, `priority`.

## Dashboard metrics (Task 014)

Exposed on `GET /api/dashboard` under `leads`, `opportunities`, `tasks`, and `pipelineSummary`:

- Lead counts by status and temperature
- Open/won/lost opportunities; `estimatedPipelineValue` and `weightedPipelineValue` (value × probability)
- `opportunitiesByStage` for pipeline chart
- Task counts: open, overdue, due today, completed

## Deferred

- n8n webhooks on lead create (Task 019)
- Drag-and-drop pipeline (optional future)

## Related docs

- [08-ai-classification.md](./08-ai-classification.md)
- [05-email-system.md](./05-email-system.md)
- [02-database-schema.md](./02-database-schema.md)
