wulf-pulse/autotask-app/app/api/configuration-items/[id]/route.ts
Lorentz Hinrichsen f429f3af54 Add Addigy API integration and Docker deployment with Redis caching
- Implemented complete Addigy API v2 client with authentication via x-api-key
- Added device and policy endpoints with automatic org ID resolution
- Created field mapping from snake_case to Title Case for UI compatibility
- Handles nested 'facts' response structure from Addigy devices API
- Added comprehensive API documentation in ADDIGY_API_GUIDE.md

- Multi-stage Dockerfile with optimized production build
- Custom ports: App on 3100, Redis on 6380 (avoids conflicts)
- Docker Compose orchestration with health checks
- Standalone Next.js output for smaller container images
- Non-root user execution for security

- Implemented Redis caching layer for API responses
- 5-minute TTL with graceful fallback if Redis unavailable
- Cache key structure: service:entity:filter1:filter2
- Applied to Addigy devices endpoint with cache hit/miss logging

- Fixed TypeScript strict mode errors for production builds
- Added null safety checks with optional chaining throughout API routes
- Wrapped useSearchParams in Suspense boundary for Next.js 15+ compatibility
- Fixed type assertions for dynamic API responses
- Corrected Set<string> type mismatches in device comparison logic

- Created DOCKER_README.md with complete deployment guide
- Updated ADDIGY_API_GUIDE.md with real-world API patterns
- Documented response structures, field mappings, and troubleshooting

- Next.js 16.0.0 with Turbopack
- Redis 7 with AOF persistence
- Podman/Docker compatible
- TypeScript strict mode compliant
2025-10-28 22:49:08 -04:00

172 lines
6.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { getAutotaskClient } from '@/lib/services/autotask-factory';
import { getDattoRMMClient } from '@/lib/services/datto-rmm-factory';
import { ConfigurationItem } from '@/lib/types/autotask';
import { DattoRMMDevice } from '@/lib/types/datto-rmm';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const searchParams = request.nextUrl.searchParams;
const type = searchParams.get('type') || 'autotask';
let autotaskDevice: ConfigurationItem | null = null;
let rmmDevice: DattoRMMDevice | null = null;
let companyName: string | null = null;
if (type === 'autotask') {
// Fetch Autotask configuration item
const autotaskClient = getAutotaskClient();
autotaskDevice = await autotaskClient.getConfigurationItemById(parseInt(id));
if (autotaskDevice) {
// Get company name
const company = await autotaskClient.getCompanyById(autotaskDevice.companyID);
companyName = company?.companyName || null;
// Try to find matching RMM device
console.log('Looking for RMM device for Autotask item:', {
id: autotaskDevice.id,
companyID: autotaskDevice.companyID,
companyName: companyName,
rmmDeviceUID: autotaskDevice.rmmDeviceUID,
rmmDeviceID: autotaskDevice.rmmDeviceID,
serialNumber: autotaskDevice.serialNumber,
hostname: autotaskDevice.rmmDeviceAuditHostname
});
try {
const rmmClient = getDattoRMMClient();
// First priority: Match by RMM Device UID if available
if (autotaskDevice?.rmmDeviceUID) {
const devices = await rmmClient.getAllDevices();
rmmDevice = devices.find(d => d.uid === autotaskDevice?.rmmDeviceUID) || null;
if (rmmDevice) {
console.log('Matched by RMM UID:', rmmDevice.uid);
}
}
// Second priority: Match by RMM Device ID if available
if (!rmmDevice && autotaskDevice?.rmmDeviceID) {
try {
rmmDevice = await rmmClient.getDeviceById(autotaskDevice.rmmDeviceID);
if (rmmDevice) {
console.log('Matched by RMM ID:', rmmDevice.id);
}
} catch (err) {
console.log('Could not find device by RMM ID:', autotaskDevice.rmmDeviceID);
}
}
// Third priority: Match by serial number
if (!rmmDevice && autotaskDevice?.serialNumber) {
const devices = await rmmClient.getAllDevices();
rmmDevice = devices.find(d =>
d.serialNumber?.toLowerCase() === autotaskDevice?.serialNumber?.toLowerCase()
) || null;
if (rmmDevice) {
console.log('Matched by serial number:', rmmDevice.serialNumber);
}
}
// Fourth priority: Match by hostname
if (!rmmDevice && autotaskDevice?.rmmDeviceAuditHostname) {
const devices = await rmmClient.getAllDevices();
rmmDevice = devices.find(d =>
d.hostname?.toLowerCase() === autotaskDevice?.rmmDeviceAuditHostname?.toLowerCase()
) || null;
if (rmmDevice) console.log('Matched by hostname within company');
}
if (!rmmDevice) {
console.log('No RMM device match found');
} else {
console.log('Found RMM device:', {
id: rmmDevice.id,
uid: rmmDevice.uid,
hostname: rmmDevice.hostname,
siteName: rmmDevice.siteName
});
// Try to get additional audit data for more detailed information
try {
const deviceWithAudit = await rmmClient.getDeviceWithAudit(rmmDevice.id);
if (deviceWithAudit) {
rmmDevice = deviceWithAudit;
console.log('Enhanced device with audit data');
}
} catch (err) {
console.log('Could not fetch audit data:', err);
}
}
} catch (err) {
console.error('Failed to fetch RMM device:', err);
}
}
} else if (type === 'rmm') {
// Fetch RMM device
try {
const rmmClient = getDattoRMMClient();
rmmDevice = await rmmClient.getDeviceById(id);
if (rmmDevice) {
// Try to find matching Autotask device
const autotaskClient = getAutotaskClient();
const configItems = await autotaskClient.getAllConfigurationItems();
autotaskDevice = configItems.find(ci =>
ci.rmmDeviceUID === rmmDevice?.uid ||
ci.serialNumber === rmmDevice?.serialNumber
) || null;
if (autotaskDevice) {
const company = await autotaskClient.getCompanyById(autotaskDevice.companyID);
companyName = company?.companyName || null;
}
}
} catch (err) {
console.error('Failed to fetch RMM device:', err);
}
}
return NextResponse.json({
autotaskDevice,
rmmDevice,
companyName
});
} catch (error) {
console.error('Error fetching configuration item:', error);
return NextResponse.json(
{ error: 'Failed to fetch configuration item details' },
{ status: 500 }
);
}
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const body = await request.json();
const idNum = parseInt(id);
const autotaskClient = getAutotaskClient();
const updatedItem = await autotaskClient.updateConfigurationItem(idNum, body);
return NextResponse.json({
configurationItem: updatedItem,
message: 'Configuration item updated successfully'
});
} catch (error) {
console.error('Error updating configuration item:', error);
return NextResponse.json(
{ error: 'Failed to update configuration item' },
{ status: 500 }
);
}
}