# Leads Follow-Up Tracker

Web version of the Esferasoft **Leads Follow-Up Tracker** panel (Google Sheet canvas).

- **Frontend:** React (Vite)
- **Backend:** FastAPI
- **Database:** PostgreSQL

## Features

- KPI cards: Total, Due Today, Overdue, In Progress, Completed, Call Scheduled
- **7-Stage Matrix** with FU 1–7 (Day 1 / 3 / 7 / 10 / 14 / 21 / 30)
- **Action Queue** for due & overdue touchpoints
- **Stages Pipeline** board view
- Search, stage/status filters, add/edit/delete leads
- Toggle follow-up Done ↔ Pending
- **Voice agent** (mic): speak commands → Whisper STT → OpenAI tools → send + mark FU Done
- **Gmail API + OAuth** (multi-account): connect many send-from mailboxes; SMTP kept as fallback
- **Inbox automation**: poll Gmail → hard spam/negative filters → **OpenAI** interest detect → auto-create **Positive lead**
- Seeded with the Blair S / Velurax sample lead from the sheet

## Quick start (Docker)

```bash
docker compose up --build
```

- App: http://localhost:5173  
- API docs: http://localhost:8000/docs  

## Local development

### 1. Database

**PostgreSQL (recommended):**

```bash
docker compose up db -d
# DATABASE_URL=postgresql+psycopg://marketing:marketing@localhost:5432/leads_tracker
```

**SQLite (quick local demo without Docker):**

```bash
# in backend/.env
DATABASE_URL=sqlite:///./leads.db
```

### 2. Backend

Requires [uv](https://docs.astral.sh/uv/). The pinned Python version (3.12) is
declared in `backend/.python-version` and fetched automatically by uv.

```bash
cd backend
cp .env.example .env
uv sync                     # creates .venv and installs locked deps
uv run uvicorn app.main:app --reload --port 8000
```

### 3. Frontend

```bash
cd frontend
npm install
npm run dev
```

Open http://localhost:5173

## Tests

Tests live in `backend/tests/`. They use a throwaway SQLite database and a fake
OpenAI client, so they never touch your real database, send email, or cost money.

```bash
cd backend
uv run pytest                     # fast offline suite
RUN_LIVE_OPENAI=1 uv run pytest -m live -s   # real OpenAI: speed + accuracy (~1 cent)
```

## API overview

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/stats` | Dashboard KPI counts |
| GET | `/api/leads` | List leads (`q`, `stage`, `status`) |
| POST | `/api/leads` | Create lead (+ auto FU 1–7 dates) |
| PATCH | `/api/leads/{id}` | Update lead |
| DELETE | `/api/leads/{id}` | Delete lead |
| PATCH | `/api/leads/{id}/follow-ups/{n}` | Update FU status/date |
| POST | `/api/leads/{id}/follow-ups/{n}/send` | Send FU email via Gmail/SMTP (+ mark Done) |
| GET | `/api/action-queue` | Due / overdue items |
| GET | `/api/meta` | Stages + FU schedule |
| POST | `/api/agent/transcribe` | Whisper STT (multipart audio) |
| POST | `/api/agent/plan` | Dry-run agent plan from transcript |
| POST | `/api/agent/execute` | Execute confirmed actions / transcript |
| GET | `/api/agent/email-logs` | Recent outbound email log |
| GET | `/api/gmail/status` | OAuth config + connected accounts |
| GET | `/api/gmail/auth/start` | Begin Google OAuth (returns consent URL) |
| GET | `/api/gmail/auth/callback` | OAuth redirect target |
| POST | `/api/gmail/accounts/{email}/default` | Set default send account |
| DELETE | `/api/gmail/accounts/{email}` | Disconnect mailbox |
| GET | `/api/inbound-mail/rules` | Inbox automation keyword rules |
| PUT | `/api/inbound-mail/rules` | Update enable + keyword lists |
| GET | `/api/inbound-mail/status` | Last poll + accounts missing readonly |
| POST | `/api/inbound-mail/run` | Run inbox poll now |
| GET | `/api/inbound-mail/events` | Recent inbound processing log |

## Gmail API + OAuth (recommended for many accounts)

One Google Cloud OAuth client can authorize **many** Gmail send-from accounts. Each mailbox is connected once; refresh tokens are stored in `gmail_accounts`. Sends route by the lead’s **Our Email** (or the default connected account).

1. In [Google Cloud Console](https://console.cloud.google.com/):
   - Enable **Gmail API**
   - Create an OAuth client of type **Web application**
   - Add authorized redirect URI: `http://localhost:8000/api/gmail/auth/callback` (or your API URL)
2. Put credentials in `backend/.env`:
   - `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`
   - `GOOGLE_REDIRECT_URI=http://localhost:8000/api/gmail/auth/callback`
   - `FRONTEND_URL=http://localhost:5173`
   - `EMAIL_PROVIDER=auto` (Gmail when connected, else SMTP)
3. Restart the API, open the app → **Gmail** in the top bar → **Connect Gmail account**.
4. Repeat Connect for each send-from mailbox. Match lead **Our Email** to those addresses.

App verification: while the OAuth app is in **Testing**, only listed test users can connect.

**Inbox automation** needs `gmail.readonly` in addition to send. After upgrading, open **Gmail → Connect / reconnect** for each mailbox so Google grants the new scope.

### Inbox → Positive leads

1. Connect/reconnect Gmail (readonly scope).
2. Open **Gmail** panel → **Inbox automation**.
3. Paste **Filter** / **Positive** / **Negative** keywords (one per line). Empty filter = all new inbox mail.
4. Enable polling (default every 120s) or click **Run now**.
5. Interested / positive replies create a lead at stage **Positive lead** (deduped by client email). Negatives are logged only.

Classification: filter gate → pipe-tracking spam / negative keywords → **OpenAI** (`INBOUND_MAIL_AI_ENABLED`, needs `OPENAI_API_KEY`) decides positive vs not → if AI is off, positive keywords are used as fallback.

## Voice agent + email

1. Set secrets in `backend/.env` (see `.env.example`):
   - `OPENAI_API_KEY` — Whisper + tool-calling (`OPENAI_MODEL=gpt-5-nano` by default for low cost)
   - Gmail OAuth (above) **and/or** `SMTP_*` as fallback
2. Restart the API.
3. In the app top bar, click **Voice**, speak (e.g. “Send the follow-up email to Alex Rivera”), review the plan, then **Confirm & run**.
4. On success the follow-up is emailed and marked **Done** in the matrix / Action Queue.

Without keys, the mic UI still loads but plan/transcribe return a clear configuration error.

## Follow-up schedule

| FU | Day | Offset from date added |
|----|-----|------------------------|
| 1 | Day 1 | +0 |
| 2 | Day 3 | +2 |
| 3 | Day 7 | +6 |
| 4 | Day 10 | +9 |
| 5 | Day 14 | +13 |
| 6 | Day 21 | +20 |
| 7 | Day 30 | +29 |
