# Addigy Organization Mapping Implementation

## Overview
This document describes the implementation of Addigy organization to Autotask company mappings for the Pulse application. This feature allows administrators to map Addigy organizations to Autotask companies, enabling proper device synchronization and management for Apple devices.

## Components Created

### 1. Database Schema
**File:** `/migrations/011_create_addigy_org_mappings.sql`

Created the `addigy_org_mappings` table with the following structure:
- `id` - Primary key (auto-increment)
- `addigy_org_id` - Unique identifier for Addigy organization
- `addigy_org_name` - Display name of the Addigy organization
- `autotask_company_id` - Foreign key to Autotask company
- `autotask_company_name` - Cached company name for display
- `created_at` - Timestamp of mapping creation
- `updated_at` - Timestamp of last update (auto-updated via trigger)

**Indexes:**
- `idx_addigy_org_id` - Fast lookup by Addigy organization ID
- `idx_addigy_autotask_company_id` - Fast lookup by Autotask company ID

**Features:**
- Unique constraint on `addigy_org_id` to prevent duplicate mappings
- Automatic `updated_at` timestamp via PostgreSQL trigger
- Follows the same pattern as Auvik and RMM mappings

### 2. TypeScript Types
**File:** `/lib/types/addigy.ts`

Added `AddigyOrgMapping` interface:
```typescript
export interface AddigyOrgMapping {
  id: number;
  addigyOrgId: string;
  addigyOrgName: string;
  autotaskCompanyId: number;
  autotaskCompanyName: string;
  createdAt: string;
  updatedAt: string;
}
```

### 3. API Endpoints
**File:** `/app/api/addigy/org-mappings/route.ts`

Implements three REST endpoints:

#### GET `/api/addigy/org-mappings`
- Retrieves all organization mappings from the database
- Query parameter `includeUnmapped=true` fetches unmapped organizations from Addigy API
- Returns mapped and unmapped organizations with statistics

#### POST `/api/addigy/org-mappings`
- Creates or updates an organization mapping
- Uses `ON CONFLICT` to handle upserts
- Validates required fields (addigyOrgId, autotaskCompanyId)

#### DELETE `/api/addigy/org-mappings?id={mappingId}`
- Removes a mapping by ID
- Returns success status

### 4. User Interface
**File:** `/app/addigy-mappings/page.tsx`

Full-featured mapping management page with:

**Features:**
- **Stats Dashboard** - Shows total, mapped, and unmapped organization counts
- **Search & Filter** - Real-time search and status filtering (all/mapped/unmapped)
- **Mapping Table** - Displays all organizations with mapping controls
- **Inline Editing** - Select company from dropdown, save button appears on change
- **Delete Functionality** - Remove existing mappings
- **Loading States** - Skeleton loaders during data fetch
- **Error Handling** - Toast notifications for success/error states

**UI Components Used:**
- Card, Table, Select, Input, Button, Badge, Skeleton from shadcn/ui
- Lucide icons (Smartphone, Building2, CheckCircle, XCircle, etc.)
- Responsive layout with Tailwind CSS

### 5. Navigation Integration
**File:** `/components/navigation/app-navigation.tsx`

Already includes Addigy mappings in the Admin menu:
- Title: "Apple RMM Mapping (Addigy)"
- Icon: Smartphone (orange)
- Route: `/addigy-mappings`
- Description: "Map Addigy devices to companies"

## Installation Instructions

### 1. Apply Database Migration
Run the migration script to create the database table:

```bash
# Apply specific migration
./scripts/apply-migrations.sh 011_create_addigy_org_mappings.sql

# Or apply all pending migrations
./scripts/apply-migrations.sh
```

For Docker environments:
```bash
docker exec -i pulse-postgres psql -U pulse_user -d pulse_autotask < /opt/stacks/pulse/migrations/011_create_addigy_org_mappings.sql
```

### 2. Verify Addigy Client Configuration
Ensure the Addigy API client is properly configured with:
- `ADDIGY_API_URL` environment variable
- `ADDIGY_API_TOKEN` environment variable

The client is accessed via `/lib/services/addigy-factory.ts` which provides `getAddigyClient()`.

### 3. Access the Page
Navigate to: `http://localhost:3000/addigy-mappings`

Or use the navigation menu: **Admin → Apple RMM Mapping (Addigy)**

## Usage Workflow

1. **View Organizations** - Page loads all Addigy organizations (mapped and unmapped)
2. **Create Mapping** - Select an Autotask company from the dropdown for an organization
3. **Save Mapping** - Click the "Save" button that appears after making a change
4. **Update Mapping** - Change the company selection and save again
5. **Delete Mapping** - Click the trash icon to remove a mapping
6. **Search/Filter** - Use search box or filter dropdown to find specific organizations

## Architecture Pattern

This implementation follows the established pattern used for:
- **Auvik Tenant Mappings** (`/auvik-mappings`)
- **RMM Site Mappings** (`/rmm-mappings`)

Benefits of this consistency:
- Familiar UI/UX for administrators
- Reusable code patterns
- Consistent database schema design
- Similar API endpoint structure

## Future Enhancements

Potential improvements for future iterations:

1. **Device Count Display** - Show number of devices per organization
2. **Auto-Discovery** - Suggest mappings based on name matching
3. **Bulk Operations** - Map multiple organizations at once
4. **Sync Integration** - Trigger device sync after mapping changes
5. **Audit Trail** - Track who created/modified mappings
6. **Policy Mapping** - Map Addigy policies to Autotask service plans
7. **Device Filtering** - Filter devices by organization in main device view

## Related Files

- Database: `/migrations/011_create_addigy_org_mappings.sql`
- Types: `/lib/types/addigy.ts`
- API: `/app/api/addigy/org-mappings/route.ts`
- UI: `/app/addigy-mappings/page.tsx`
- Navigation: `/components/navigation/app-navigation.tsx`
- Client: `/lib/services/addigy-client.ts`
- Factory: `/lib/services/addigy-factory.ts`

## Testing Checklist

- [ ] Database migration applies successfully
- [ ] API endpoints return correct data
- [ ] Page loads without errors
- [ ] Organizations display in table
- [ ] Search functionality works
- [ ] Filter dropdown works
- [ ] Mapping creation succeeds
- [ ] Mapping update succeeds
- [ ] Mapping deletion succeeds
- [ ] Error handling displays appropriate messages
- [ ] Loading states display correctly
- [ ] Dark mode styling works
- [ ] Responsive layout on mobile devices
