# FreePBX SIP Integration Plugin - Installation Guide

Complete FreePBX SIP telephony integration with AI voice agent support.

**Version:** 2.0.0
**Plugin Type:** Self-contained (Backend + Frontend)

---

## Quick Install (5 Minutes)

### Step 1: Copy Plugin Folder

Copy the entire `plugins/free-pbx/` folder to your project:

```bash
# From your project root
cp -r /path/to/halavoice.store/plugins/free-pbx ./plugins/
```

### Step 2: Backend Setup

In your main server file (e.g., `server/index.ts`):

```typescript
import { registerFreePBXSIPRoutes } from './plugins/free-pbx';

// Register the plugin
registerFreePBXSIPRoutes(app, {
  sessionAuthMiddleware: sessionAuth,  // Your session auth middleware
  adminAuthMiddleware: adminAuth,      // Your admin auth middleware
  httpServer,                          // HTTP server for WebSocket
});
```

### Step 3: Frontend Setup

In `client/src/main.tsx` (after other imports):

```typescript
// Import SIP plugin client bootstrap
import './plugins/free-pbx/client/bootstrap';
```

That's it! The plugin will auto-register all routes and UI components.

---

## Database Setup

Run the migration to create required tables:

```bash
psql -U your_user -d your_database -f plugins/free-pbx/migrations/001_sip_tables.sql
```

Or using Drizzle:

```bash
npm run db:push
```

---

## Environment Variables

Add to your `.env` file:

```bash
# FreePBX Webhook Secret (for signature verification)
FREEPBX_WEBHOOK_SECRET=your_webhook_secret_here

# OpenAI API (for voice AI)
OPENAI_API_KEY=sk-xxx

# Encryption (for SIP credentials)
SIP_ENCRYPTION_KEY=your_32_char_encryption_key
```

---

## What's Included

### Backend (Server-side)
```
plugins/free-pbx/
├── config/           # Configuration, constants, validation
├── core/             # Call manager, audio processor, SIP manager
├── integrations/     # FreePBX AMI, REST, ARI clients
├── middleware/       # Auth, rate limiting, webhook verification
├── repositories/     # Database access layer
├── routes/           # API endpoints (admin, user, webhooks, WebSocket)
├── services/         # Business logic layer
├── migrations/       # Database schema
├── client/           # Frontend UI components (self-contained)
├── types.ts          # TypeScript types
├── index.ts         # Server entry point
└── INSTALLATION.md  # This file
```

### Frontend (Client-side)
```
plugins/free-pbx/client/
├── pages/admin/
│   ├── SIPConnections.tsx   # Manage FreePBX servers
│   ├── SIPExtensions.tsx    # Manage extensions
│   └── SIPAssignments.tsx   # Manage user assignments
└── pages/user/
    ├── SIPExtensions.tsx     # Browse & request extensions
    └── SIPCalls.tsx          # Call history
```

---

## API Endpoints

### Admin (`/api/admin/sip/*`)

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/connections` | List FreePBX connections |
| POST | `/connections` | Create connection |
| PUT | `/connections/:id` | Update connection |
| DELETE | `/connections/:id` | Delete connection |
| POST | `/connections/:id/test` | Test connectivity |
| POST | `/connections/:id/sync` | Sync extensions from FreePBX |
| GET | `/extensions` | List all extensions |
| PUT | `/extensions/:id` | Update extension |
| DELETE | `/extensions/:id` | Delete extension |
| GET | `/assignments` | List user assignments |
| POST | `/assignments` | Assign extension to user |
| DELETE | `/assignments/:id` | Remove assignment |
| GET | `/analytics` | Dashboard statistics |

### User (`/api/sip/*`)

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/extensions/available` | Browse available extensions |
| GET | `/my-extensions` | My assigned extensions |
| POST | `/requests` | Request extension |
| GET | `/requests` | My extension requests |
| DELETE | `/requests/:id` | Cancel request |
| GET | `/calls` | My call history |
| GET | `/calls/:id` | Call details |
| GET | `/calls/:id/transcript` | Call transcript |
| POST | `/calls/initiate` | Make outbound call |

### Webhooks (`/api/webhooks/sip/*`)

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/call/:event` | Call events (start, answer, end, failed, busy) |
| POST | `/recording` | Recording ready notification |
| POST | `/dtmf` | DTMF events |

### WebSocket

| Endpoint | Purpose |
|----------|---------|
| `WS /ws/sip` | Real-time audio streaming |

---

## UI Pages

### Admin Pages

| Route | Page | Features |
|-------|------|----------|
| `/admin/sip/connections` | **Connections** | Add/edit FreePBX servers, test connection, sync extensions, view status |
| `/admin/sip/extensions` | **Extensions** | View all extensions, filter by status, assign to users, link AI agents |
| `/admin/sip/assignments` | **Assignments** | View active/expired assignments, revoke assignments, view usage stats |

### User Pages

| Route | Page | Features |
|-------|------|----------|
| `/app/sip/extensions` | **Extensions** | Browse available extensions, request assignment, select AI agent |
| `/app/sip/calls` | **Call History** | View all calls, play recordings, read transcripts, filter by status |

---

## FreePBX Configuration

### 1. Configure FreePBX REST API

Navigate to FreePBX Admin → REST API and create API credentials.

### 2. Setup Webhooks

Configure FreePBX to send webhooks to your server:

```
https://your-domain.com/api/webhooks/sip
```

### 3. AMI Access

Ensure AMI (Asterisk Manager Interface) is enabled:

```
/etc/asterisk/manager.conf
[admin]
secret = your_secret
permit = 0.0.0.0/0.0.0.0
read = system,call,log,verbose,agent,command,user
write = system,call,log,verbose,agent,command,user
```

---

## Usage Example

### 1. Add FreePBX Connection (Admin)

```typescript
const response = await fetch('/api/admin/sip/connections', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    name: 'Main PBX',
    host: 'pbx.example.com',
    amiPort: 5038,
    amiUsername: 'admin',
    amiSecret: 'secret',
    restApiUrl: 'https://pbx.example.com/api',
    restApiToken: 'token',
    autoSync: true,
  }),
});
```

### 2. Sync Extensions (Admin)

```typescript
await fetch(`/api/admin/sip/connections/${connectionId}/sync`, {
  method: 'POST',
});
```

### 3. Assign Extension to User (Admin)

```typescript
await fetch('/api/admin/sip/assignments', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    userId: 'user-uuid',
    extensionId: 'extension-uuid',
    agentId: 'agent-uuid',  // Links to AI agent
  }),
});
```

### 4. User Makes Call

```typescript
// User initiates call via UI or API
await fetch('/api/sip/calls/initiate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    destination: '+1234567890',
    extensionId: 'extension-uuid',
  }),
});
```

---

## SaaS Multi-Tenancy

The plugin supports full multi-tenancy:

```
SuperAdmin
    │
    ├── FreePBX Server 1 ─── Extensions 100-199 ─── Client A (5 extensions)
    │                                      └── Client B (3 extensions)
    │
    └── FreePBX Server 2 ─── Extensions 200-299 ─── Client C (10 extensions)
```

Each client:
- Has their own assigned extensions
- Links extensions to AI agents
- Views their own call history
- Manages their usage

---

## Uninstallation

### 1. Remove from Code

```typescript
// Remove from server/index.ts
- import { registerFreePBXSIPRoutes } from './plugins/free-pbx';
- registerFreePBXSIPRoutes(app, options);
```

```typescript
// Remove from client/src/main.tsx
- import './plugins/free-pbx/client/bootstrap';
```

### 2. Delete Database Tables

```sql
DROP TABLE IF EXISTS freepbx_calls;
DROP TABLE IF EXISTS sip_extension_assignments;
DROP TABLE IF EXISTS sip_extension_requests;
DROP TABLE IF EXISTS sip_extensions;
DROP TABLE IF EXISTS freepbx_connections;
```

### 3. Remove Plugin Folder

```bash
rm -rf plugins/free-pbx
```

---

## File List

All files are self-contained in `plugins/free-pbx/`:

**Server:**
- `index.ts` - Server entry point
- `config/index.ts` - Configuration
- `core/*.ts` - Core business logic
- `integrations/*.ts` - External integrations
- `middleware/*.ts` - Express middleware
- `repositories/*.ts` - Database access
- `routes/*.ts` - API routes
- `services/*.ts` - Services
- `types.ts` - TypeScript types
- `migrations/*.sql` - Database schema

**Client:**
- `client/index.ts` - Client entry
- `client/bootstrap.tsx` - Auto-registers UI
- `client/pages/admin/*.tsx` - Admin UI pages
- `client/pages/user/*.tsx` - User UI pages

---

## Troubleshooting

### WebSocket Connection Fails
- Ensure `httpServer` is passed to plugin options
- Check firewall allows WebSocket connections

### Webhook Signature Verification
- Set `FREEPBX_WEBHOOK_SECRET` in `.env`
- Ensure FreePBX sends `x-freepbx-signature` header

### Extension Sync Fails
- Verify FreePBX REST API credentials
- Check network connectivity to FreePBX server

### UI Pages Not Showing
- Check `client/bootstrap.tsx` is imported in `main.tsx`
- Verify plugin is marked as loaded in console

---

## Support

For issues or questions:
- Check `IMPLEMENTATION.md` for technical details
- Check `README.md` for architecture overview
- Review console logs for `[FreePBX SIP]` prefix
