# Auvik Tenant Mapping

## Overview
The Auvik Tenant Mapping feature allows administrators to manually map Auvik tenants to Autotask companies. This ensures accurate device matching when company names don't align between systems.

## Features

### 1. **Tenant Mapping Page** (`/auvik-mappings`)
- View all Auvik tenants (mapped and unmapped)
- Map tenants to Autotask companies via dropdown selection
- Search and filter tenants by status
- Real-time statistics dashboard
- Save/delete mappings with immediate feedback

### 2. **Database Storage**
- Mappings stored in `auvik_tenant_mappings` table
- Unique constraint on `auvik_tenant_id` (one tenant = one company)
- Automatic timestamp tracking (created_at, updated_at)
- Indexed for fast lookups

### 3. **API Endpoints**

#### GET `/api/auvik/tenant-mappings`
Fetch all tenant mappings
- Query param: `includeUnmapped=true` - includes unmapped tenants from Auvik API
- Returns: `{ mappings: AuvikTenantMapping[], totalMapped: number, totalUnmapped: number }`

#### POST `/api/auvik/tenant-mappings`
Create or update a tenant mapping
- Body: `{ auvikTenantId, auvikTenantName, autotaskCompanyId, autotaskCompanyName }`
- Returns: `{ mapping: AuvikTenantMapping }`

#### DELETE `/api/auvik/tenant-mappings?id={id}`
Delete a tenant mapping
- Query param: `id` - mapping ID to delete
- Returns: `{ success: true }`

### 4. **Integration with Device Matching**

The Auvik client now prioritizes database mappings over fuzzy matching:

1. **Primary**: Check database for explicit company ID → tenant mapping
2. **Fallback**: Use fuzzy name matching (existing logic)

This ensures:
- Accurate matching even when names differ significantly
- User control over tenant associations
- No breaking changes to existing functionality

## Usage

### Step 1: Access the Mapping Page
Navigate to: `https://pulse.wulfconsulting.cloud/auvik-mappings`

### Step 2: Map Tenants
1. Find an unmapped tenant (orange badge)
2. Click the dropdown in the "Autotask Company" column
3. Select the corresponding company
4. Click "Save"

### Step 3: Verify
- The status badge changes to green "Mapped"
- Stats update automatically
- Configuration items page will now use this mapping

### Step 4: View Devices
Go to `/configuration-items`, select the mapped company, and see Auvik devices appear in the Auvik column and tab.

## Database Schema

```sql
CREATE TABLE auvik_tenant_mappings (
    id SERIAL PRIMARY KEY,
    auvik_tenant_id VARCHAR(255) NOT NULL UNIQUE,
    auvik_tenant_name VARCHAR(255) NOT NULL,
    autotask_company_id INTEGER NOT NULL,
    autotask_company_name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
```

## Migration Applied
- **File**: `migrations/009_create_auvik_tenant_mappings.sql`
- **Status**: ✅ Applied to database
- **Command**: `docker exec pulse-postgres psql -U pulse_user -d pulse_autotask -f /docker-entrypoint-initdb.d/009_create_auvik_tenant_mappings.sql`

## Files Created/Modified

### New Files
- `/app/auvik-mappings/page.tsx` - Main mapping UI
- `/app/api/auvik/tenant-mappings/route.ts` - API endpoints
- `/migrations/009_create_auvik_tenant_mappings.sql` - Database schema
- `/lib/types/auvik.ts` - Added `AuvikTenantMapping` interface

### Modified Files
- `/lib/services/auvik-client.ts` - Added `findTenantByCompanyId()` method
- `/docker-compose.yml` - Added Auvik environment variables

## Next Steps

1. **Add Navigation Link**: Add a link to `/auvik-mappings` in the main navigation menu
2. **Enhance Toast**: Replace simple alert-based toast with a proper toast component library
3. **Bulk Import**: Add ability to import mappings from CSV
4. **Auto-Suggest**: Add AI-powered suggestions for likely company matches based on name similarity
5. **Audit Log**: Track who created/modified mappings and when

## Troubleshooting

### No Tenants Showing
- Check Auvik API credentials in `.env.local`
- Verify Auvik client initialization in logs: `docker logs pulse-app | grep -i auvik`

### Mapping Not Working
- Verify database migration was applied
- Check API endpoint response: `curl http://localhost:3100/api/auvik/tenant-mappings`
- Review console logs for errors

### Companies Not Loading
- Ensure Autotask API is accessible
- Check `/api/companies` endpoint returns data
