# LeoCRM API Documentation

> Auto-generated from FastAPI route enumeration. **295 endpoints** across **30 tag groups**.

## Overview

LeoCRM exposes a RESTful API under `/api/v1/`. All endpoints (except `/api/v1/health` and `/api/v1/auth/login`) require authentication via session cookie.

- **Swagger UI**: `/docs`
- **ReDoc**: `/redoc`
- **OpenAPI JSON**: `/openapi.json`

### Authentication

1. Call `POST /api/v1/auth/login` with `{email, password}` → receives session cookie.
2. Include the session cookie in all subsequent requests.
3. Call `POST /api/v1/auth/logout` to invalidate the session.

### Multi-Tenancy

All data is tenant-scoped. The tenant context is derived from the authenticated session. Users with multiple tenants can switch via `POST /api/v1/auth/switch-tenant`.

### Error Format

```json
{"detail": "Error message", "code": "error_code", "fields": {"field": "error"}}
```

### Pagination

List endpoints use `page` (1-based) and `page_size` (1-100) query parameters. Responses include `total`, `page`, `page_size`, and `items`.

---

## Core Routes

### health (1 endpoint)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/health` | Health check — no auth required. Returns status + DB/Redis/storage/worker checks. **Response model**: `HealthResponse` |

### metrics (1 endpoint)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/metrics` | Prometheus metrics endpoint. |

### auth (7 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/v1/auth/login` | Login with email+password. Sets session cookie. **Request**: `LoginRequest`, **Response**: `AuthResponse` |
| POST | `/api/v1/auth/logout` | Logout — invalidate session, clear cookie. **Response**: `MessageResponse` |
| GET | `/api/v1/auth/me` | Get current user + active tenant. **Response**: `AuthResponse` |
| GET | `/api/v1/auth/me/permissions` | Get resolved permissions for current user. |
| POST | `/api/v1/auth/switch-tenant` | Switch active tenant. **Request**: `SwitchTenantRequest` |
| POST | `/api/v1/auth/password-reset/request` | Request password reset email. **Request**: `PasswordResetRequest` |
| POST | `/api/v1/auth/password-reset/confirm` | Confirm password reset with token. **Request**: `PasswordResetConfirm` |

### users (5 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/users` | List users with pagination. **Response**: `PaginatedUsers` |
| POST | `/api/v1/users` | Create a new user (admin only). **Request**: `UserCreate`, **Response**: `UserResponse` |
| GET | `/api/v1/users/{user_id}` | Get a single user. **Response**: `UserResponse` |
| PATCH | `/api/v1/users/{user_id}` | Update user fields. **Request**: `UserUpdate` |
| DELETE | `/api/v1/users/{user_id}` | Delete/deactivate a user. |

### roles (5 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/roles` | List all roles. |
| POST | `/api/v1/roles` | Create a custom role. |
| GET | `/api/v1/roles/permissions` | Get all available permission definitions. |
| PATCH | `/api/v1/roles/{role_id}` | Update role permissions. |
| DELETE | `/api/v1/roles/{role_id}` | Delete a custom role. |

### groups (9 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/groups` | List all groups. |
| POST | `/api/v1/groups` | Create a new group. |
| GET | `/api/v1/groups/{group_id}` | Get a single group. |
| PATCH | `/api/v1/groups/{group_id}` | Update group. |
| DELETE | `/api/v1/groups/{group_id}` | Delete group. |
| GET | `/api/v1/groups/{group_id}/members` | List group members. |
| POST | `/api/v1/groups/{group_id}/members` | Add member to group. |
| DELETE | `/api/v1/groups/{group_id}/members/{user_id}` | Remove member from group. |
| GET | `/api/v1/groups/user/{user_id}` | Get groups for a user. |

### tenants (4 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/tenants` | List tenants for current user. |
| POST | `/api/v1/tenants` | Create a new tenant. |
| GET | `/api/v1/tenants/{tenant_id}/users` | List users in a tenant. |
| POST | `/api/v1/tenants/{tenant_id}/users` | Add user to tenant. |

### notifications (6 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/notifications` | List notifications with pagination. |
| PATCH | `/api/v1/notifications/{notification_id}/read` | Mark notification as read. |
| GET | `/api/v1/notifications/unread-count` | Get unread count. **Response**: `UnreadCountResponse` |
| GET | `/api/v1/notifications/types` | List notification types. |
| GET | `/api/v1/notifications/preferences` | Get notification preferences. |
| PATCH | `/api/v1/notifications/preferences/{type_key}` | Update notification preference. |

### contacts (10 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/contacts` | List contacts with pagination, FTS search, type/folder filter, sorting. |
| POST | `/api/v1/contacts` | Create a contact (company or person). |
| GET | `/api/v1/contacts/export` | Stream contacts as CSV. |
| GET | `/api/v1/contacts/{contact_id}` | Get a single contact. |
| PUT | `/api/v1/contacts/{contact_id}` | Update contact. |
| DELETE | `/api/v1/contacts/{contact_id}` | Soft-delete contact. |
| GET | `/api/v1/contacts/{contact_id}/persons` | List contact persons. |
| POST | `/api/v1/contacts/{contact_id}/persons` | Add contact person. |
| PUT | `/api/v1/contacts/{contact_id}/persons/{person_id}` | Update contact person. |
| DELETE | `/api/v1/contacts/{contact_id}/persons/{person_id}` | Delete contact person. |

### contact-folders (6 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/contact-folders` | List contact folders. |
| POST | `/api/v1/contact-folders` | Create a folder. |
| PUT | `/api/v1/contact-folders/{folder_id}` | Update folder. |
| DELETE | `/api/v1/contact-folders/{folder_id}` | Delete folder. |
| PUT | `/api/v1/contact-folders/{folder_id}/reorder` | Reorder folder. |
| PUT | `/api/v1/contact-folders/contacts/{contact_id}/move` | Move contact to folder. |

### entity-history (3 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/entity-history/{entity_type}/{entity_id}` | Get change history for an entity. |
| POST | `/api/v1/entity-history/undo/{entity_type}/{entity_id}` | Undo last change. |
| POST | `/api/v1/entity-history/restore` | Restore entity to a specific version. |

### import-export (2 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/v1/import` | Import data from file. |
| POST | `/api/v1/import/preview` | Preview import data. |

### plugins (11 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/plugins` | List all plugins. |
| GET | `/api/v1/plugins/manifest` | Get plugin manifest schema. |
| GET | `/api/v1/plugins/active-manifests` | Get manifests of all active plugins. |
| POST | `/api/v1/plugins/install-url` | Install plugin from URL. |
| POST | `/api/v1/plugins/upload` | Upload and install plugin ZIP. |
| POST | `/api/v1/plugins/{name}/install` | Install a discovered plugin. |
| POST | `/api/v1/plugins/{name}/activate` | Activate a plugin. |
| POST | `/api/v1/plugins/{name}/deactivate` | Deactivate a plugin. |
| GET | `/api/v1/plugins/{name}/config` | Get plugin configuration. |
| PATCH | `/api/v1/plugins/{name}/config` | Update plugin configuration. |
| DELETE | `/api/v1/plugins/{name}` | Uninstall a plugin. |

### ai-copilot (3 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/v1/ai/copilot/query` | Ask the AI copilot a question. |
| POST | `/api/v1/ai/copilot/execute` | Execute an AI copilot action. |
| GET | `/api/v1/ai/copilot/history` | Get copilot conversation history. |

### workflows (10 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/workflows` | List workflow definitions. |
| POST | `/api/v1/workflows` | Create a workflow. |
| GET | `/api/v1/workflows/{workflow_id}` | Get a workflow. |
| PATCH | `/api/v1/workflows/{workflow_id}` | Update a workflow. |
| DELETE | `/api/v1/workflows/{workflow_id}` | Delete a workflow. |
| POST | `/api/v1/workflows/{workflow_id}/instances` | Start a workflow instance. |
| GET | `/api/v1/workflows/instances` | List workflow instances. |
| GET | `/api/v1/workflows/instances/{instance_id}` | Get a workflow instance. |
| POST | `/api/v1/workflows/instances/{instance_id}/advance` | Advance workflow to next step. |
| POST | `/api/v1/workflows/instances/{instance_id}/cancel` | Cancel a workflow instance. |

### user-preferences (4 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/user/preferences` | Get all user preferences. |
| GET | `/api/v1/user/preferences/{key}` | Get a specific preference. |
| PUT | `/api/v1/user/preferences/{key}` | Set a preference. |
| DELETE | `/api/v1/user/preferences/{key}` | Delete a preference. |

### currencies (4 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/currencies` | List currencies. |
| POST | `/api/v1/currencies` | Create a currency. |
| PATCH | `/api/v1/currencies/{currency_id}` | Update a currency. |
| DELETE | `/api/v1/currencies/{currency_id}` | Delete a currency. |

### taxes (4 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/taxes` | List tax rates. |
| POST | `/api/v1/taxes` | Create a tax rate. |
| PATCH | `/api/v1/taxes/{tax_id}` | Update a tax rate. |
| DELETE | `/api/v1/taxes/{tax_id}` | Delete a tax rate. |

### sequences (4 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/sequences` | List number sequences. |
| POST | `/api/v1/sequences` | Create a sequence. |
| PATCH | `/api/v1/sequences/{sequence_id}` | Update a sequence. |
| DELETE | `/api/v1/sequences/{sequence_id}` | Delete a sequence. |

### system-settings (2 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/system-settings` | Get system settings. **Response**: `SystemSettingsResponse` |
| PUT | `/api/v1/system-settings` | Upsert system settings. **Request**: `SystemSettingsUpsert`, **Response**: `SystemSettingsResponse` |

### attachments (4 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/attachments` | List attachments. |
| POST | `/api/v1/attachments` | Upload an attachment. |
| GET | `/api/v1/attachments/{attachment_id}` | Download an attachment. |
| DELETE | `/api/v1/attachments/{attachment_id}` | Delete an attachment. |

### addresses (4 endpoints)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/addresses` | List addresses. |
| POST | `/api/v1/addresses` | Create an address. |
| PATCH | `/api/v1/addresses/{address_id}` | Update an address. |
| DELETE | `/api/v1/addresses/{address_id}` | Delete an address. |

### audit (1 endpoint)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/audit-log` | Query audit log entries. |

---

## Plugin Routes

### automation (Automation & Agents)

Agent Builder, Automation Builder, Cron-Scheduler, Agent Runner.

| Method | Path | Description |
|--------|------|-------------|
| GET/POST | `/api/v1/automation/*` | Automation definitions, triggers, execution logs. |

### agents (AI Agents)

| Method | Path | Description |
|--------|------|-------------|
| GET/POST/PUT/DELETE | `/api/v1/agents/*` | AI agent CRUD and runner endpoints. |

### dms (Document Management System)

19 endpoints for file and folder management.

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/dms/files` | List files. |
| POST | `/api/v1/dms/files/upload` | Upload a file. |
| GET | `/api/v1/dms/files/{file_id}` | Get file metadata. |
| GET | `/api/v1/dms/files/{file_id}/preview` | Preview a file. |
| POST | `/api/v1/dms/files/{file_id}/share` | Share a file. |
| GET/POST | `/api/v1/dms/folders` | Folder CRUD. |
| GET | `/api/v1/dms/search` | Search documents. |
| GET | `/api/v1/dms/shared-with-me` | Files shared with current user. |

### mail (Email Integration)

50 endpoints for IMAP/SMTP email management.

| Method | Path | Description |
|--------|------|-------------|
| GET/POST | `/api/v1/mail/accounts` | Email account management. |
| GET/POST | `/api/v1/mail/folders` | Folder management. |
| GET | `/api/v1/mail/{mail_id}` | Get a specific email. |
| POST | `/api/v1/mail/send` | Send an email. |
| POST | `/api/v1/mail/drafts` | Save draft. |
| GET | `/api/v1/mail/search` | Search emails. |
| GET | `/api/v1/mail/threads` | List email threads. |
| POST | `/api/v1/mail/pgp/keys` | PGP key management. |
| POST | `/api/v1/mail/rules` | Mail filter rules. |
| POST | `/api/v1/mail/vacation` | Vacation responder. |

### calendar (Calendar & Scheduling)

21 endpoints for calendar management.

| Method | Path | Description |
|--------|------|-------------|
| GET/POST | `/api/v1/calendar/entries` | Calendar entry CRUD. |
| GET/POST | `/api/v1/calendars` | Calendar CRUD. |
| GET | `/api/v1/calendar/kanban` | Kanban board view. |
| POST | `/api/v1/calendar/import` | Import ICS. |
| GET | `/api/v1/calendar/{calendar_id}/ics-feed` | ICS feed. |
| POST | `/api/v1/resources` | Resource booking. |

### search (Unified Search)

7 endpoints for cross-entity search.

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/v1/search` | Unified search across all entities. |
| GET | `/api/v1/search/providers` | List search providers. |
| POST | `/api/v1/search/reindex` | Rebuild search index. |
| POST | `/api/v1/search/similar` | Find similar entities. |
| GET | `/api/v1/search/suggest` | Search suggestions. |
| GET | `/api/v1/search/stats` | Search index statistics. |

### reports (Report Generator)

8 endpoints for report templates and generation.

| Method | Path | Description |
|--------|------|-------------|
| GET/POST | `/api/v1/reports/templates` | Report template CRUD. |
| POST | `/api/v1/reports/generate` | Generate a report. |
| GET | `/api/v1/reports/{report_id}` | Get report status. |
| GET | `/api/v1/reports/{report_id}/download` | Download generated report. |

### entity-links (Entity Linking)

4 endpoints for connecting entities.

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/contacts/{contact_id}/files` | Get files linked to a contact. |
| POST/DELETE | `/api/v1/dms/files/{file_id}/link` | Link/unlink a file to an entity. |
| GET | `/api/v1/dms/files/{file_id}/links` | Get all links for a file. |

### kommunikation (Unified Messaging)

23 endpoints for conversations and messages.

| Method | Path | Description |
|--------|------|-------------|
| GET/POST | `/api/v1/comm/conversations` | Conversation CRUD. |
| GET/POST | `/api/v1/comm/conversations/{id}/messages` | Message list and send. |
| POST | `/api/v1/comm/conversations/{id}/participants` | Manage participants. |
| POST | `/api/v1/comm/messages/{id}/reactions` | Message reactions. |
| GET | `/api/v1/comm/miniapps` | List mini-apps. |

### ai-proactive (Proactive AI)

8 endpoints for AI insights and suggestions.

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/ai-proactive/suggestions` | Get AI suggestions. |
| GET | `/api/v1/ai-proactive/suggestions/stream` | SSE stream of suggestions. |
| POST | `/api/v1/ai-proactive/suggestions/{id}/act` | Act on a suggestion. |
| POST | `/api/v1/ai-proactive/suggestions/{id}/dismiss` | Dismiss a suggestion. |
| GET/PUT | `/api/v1/ai-proactive/settings` | Proactive AI settings. |

### ai-assistant (AI Assistant)

30 endpoints for AI chat sessions, providers, models, and tools.

| Method | Path | Description |
|--------|------|-------------|
| GET/POST | `/api/v1/ai/sessions` | Chat session CRUD. |
| GET | `/api/v1/ai/sessions/{id}/messages` | List messages in session. |
| POST | `/api/v1/ai/sessions/{id}/stream` | Stream chat completion (SSE). |
| GET/POST | `/api/v1/ai/providers` | AI provider CRUD. |
| GET/POST | `/api/v1/ai/models` | AI model CRUD. |
| GET/POST | `/api/v1/ai/presets` | Preset CRUD. |
| GET | `/api/v1/ai/tools` | List available AI tools. |

### ai-ui-control (AI UI Control)

WebSocket and REST endpoints for AI-driven UI control.

| Method | Path | Description |
|--------|------|-------------|
| WebSocket | `/ws/ai-ui-control` | Real-time UI command stream. |
| POST | `/api/v1/ai-ui-control/command` | Send UI command from AI agent. |

### tags (Tag Management)

8 endpoints for tag CRUD and assignment.

| Method | Path | Description |
|--------|------|-------------|
| GET/POST | `/api/v1/tags` | Tag CRUD. |
| POST/DELETE | `/api/v1/tags/assign` | Assign/remove tag from entity. |
| POST | `/api/v1/tags/bulk-assign` | Bulk assign tags. |
| GET | `/api/v1/tags/{tag_id}/entities` | Get entities with a tag. |

### permissions (Permission Management)

5 endpoints for file-level permissions and share links.

| Method | Path | Description |
|--------|------|-------------|
| GET/POST | `/api/v1/dms/files/{file_id}/permissions` | File permission CRUD. |
| POST | `/api/v1/dms/files/{file_id}/share-link` | Create public share link. |
| DELETE | `/api/v1/dms/share-links/{link_id}` | Revoke share link. |

### public-share (Public Sharing)

2 endpoints — no auth required, token-based access.

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/public/share/{token}` | Access shared resource via token. |
| POST | `/api/public/share/{token}` | Interact with shared resource. |

---

## Schema Examples

### LoginRequest
```json
{"email": "admin@leocrm.local", "password": "secure-password"}
```

### AuthResponse
```json
{
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "admin@leocrm.local",
  "name": "Admin User",
  "role": "admin",
  "tenant_id": "550e8400-e29b-41d4-a716-446655440001",
  "tenant_name": "Acme GmbH"
}
```

### UserCreate
```json
{
  "email": "user@leocrm.local",
  "name": "John Doe",
  "password": "secure-password",
  "role": "viewer",
  "is_active": true
}
```

### UserResponse
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "user@leocrm.local",
  "name": "John Doe",
  "role": "viewer",
  "is_active": true,
  "tenant_id": "550e8400-e29b-41d4-a716-446655440001"
}
```

### HealthResponse
```json
{"status": "healthy", "version": "1.0.0"}
```

### UnreadCountResponse
```json
{"count": 5}
```

---

## KI Integration Notes

### For AI Agents

1. **Health Check**: Run `python scripts/ai_health_check.py --base-url <url> --token <token>` before and after updates.
2. **Deploy**: Use `python scripts/ai_deploy.py --dry-run` to preview, then `python scripts/ai_deploy.py` for real deployment.
3. **OpenAPI**: The full OpenAPI spec is available at `/openapi.json` — use it for dynamic endpoint discovery.
4. **Safe Methods**: GET endpoints are safe to probe. POST/PUT/DELETE require careful payload construction.
5. **Session Auth**: AI agents should call `POST /api/v1/auth/login` first, then use the returned cookie for all subsequent requests.
