wulf-pulse/app/api/analyzer/analyses/[id]/itglue-suggestions/route.ts
lorentz 1112a06afe feat: RMM Overshell, IT Glue audit/write-back, LogLift, link-aware bundles, dashboard overhaul
- RMM Overshell (migration 077): admin page, dispatch UI, executor/worker, target
  resolver, script registry (AD/DHCP/DNS/event-log/services/software/network/loglift)
- LogLift evidence pipeline (migration 078): upload webhook, B2 storage client,
  receiver/matcher, EventLogCollector PowerShell script
- IT Glue audit + write-back (migrations 075, 076): asset-audit runner, ticket
  xrefs, applications/configurations browse pages + apply/revert/audit endpoints
- Link-aware analyzer bundles (migration 073) + provider toggle (migration 074):
  link-discovery service, OpenRouter LLM provider, related-tickets/itglue-suggestion
  panels, analyze-bundle endpoint
- Endpoint data model + device-link reconciliation (migrations 079, 080): conflicts
  admin page, reconciler service, resolve endpoints
- Dashboard overhaul: integration-health service + alerts, overview/health endpoints
- Permissions: add itglue + rmm scopes; middleware: public /api/rmm/loglift route

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 07:13:18 -04:00

144 lines
4 KiB
TypeScript

/**
* GET /api/analyzer/analyses/:id/itglue-suggestions
* Returns matched IT Glue assets (flexible_asset + configuration) for the
* analysis, plus any existing ticket-scoped audits keyed by (assetType, assetId).
*
* POST /api/analyzer/analyses/:id/itglue-suggestions
* Body: { assetType: 'flexible_asset' | 'configuration', assetId, provider? }
* Runs a ticket-scoped audit (evidence = just this analysis). Returns the
* audit row.
*/
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { requireAuth } from '@/lib/auth-utils';
import { matchAssetsForAnalysis } from '@/lib/services/analyzer/asset-audit/asset-matcher';
import { runAssetAudit } from '@/lib/services/analyzer/asset-audit/runner';
import {
getAssetAuditById,
getLatestTicketScopedAudit,
} from '@/lib/services/analyzer/asset-audit/persistence';
import {
evaluateCost,
recordCostAuditDecision,
} from '@/lib/services/analyzer/cost-guard';
import { ProviderEnum } from '@/lib/types/analyzer';
const PER_AUDIT_COST_USD: Record<'anthropic' | 'openrouter', number> = {
anthropic: 0.05,
openrouter: 0.005,
};
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { error } = await requireAuth();
if (error) return error;
const { id } = await params;
const matched = await matchAssetsForAnalysis(id);
if (!matched) {
return NextResponse.json(
{ error: 'Analysis not found or not yet complete' },
{ status: 404 }
);
}
// For each match, look up an existing ticket-scoped audit if any.
const flexWithAudits = await Promise.all(
matched.flexibleAssets.map(async (m) => ({
...m,
latestAudit: await getLatestTicketScopedAudit(id, 'flexible_asset', m.id),
}))
);
const configWithAudits = await Promise.all(
matched.configurations.map(async (m) => ({
...m,
latestAudit: await getLatestTicketScopedAudit(id, 'configuration', m.id),
}))
);
return NextResponse.json({
ticketNumber: matched.ticketNumber,
organizationId: matched.organizationId,
organizationName: matched.organizationName,
flexibleAssets: flexWithAudits,
configurations: configWithAudits,
});
}
const PostBody = z.object({
assetType: z.enum(['flexible_asset', 'configuration']),
assetId: z.union([z.string(), z.number()]),
provider: ProviderEnum.optional().default('anthropic'),
});
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { session, error } = await requireAuth();
if (error) return error;
const { id: analysisId } = await params;
const body = await request.json().catch(() => ({}));
const parsed = PostBody.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid request body', details: parsed.error.issues },
{ status: 400 }
);
}
const { assetType, assetId, provider } = parsed.data;
const userId = (session?.user as { id: string } | undefined)?.id ?? null;
const evaluation = await evaluateCost({
userId,
estimatedCost: PER_AUDIT_COST_USD[provider],
confirmedCost: false,
});
await recordCostAuditDecision({
userId,
action: 'itglue_audit',
evaluation,
context: {
mode: 'ticket_scoped',
analysisId,
assetType,
assetId,
provider,
},
});
if (evaluation.decision === 'blocked') {
return NextResponse.json(
{
error: 'Daily cost limit reached',
message: evaluation.decisionReason,
},
{ status: 403 }
);
}
const result = await runAssetAudit({
assetType,
assetId,
generatedByUserId: userId,
provider,
ticketScopeAnalysisId: analysisId,
});
if (result.status === 'failed') {
return NextResponse.json(
{
error: 'Audit failed',
message: result.errorMessage,
auditId: result.auditId,
},
{ status: 500 }
);
}
const audit = await getAssetAuditById(result.auditId);
return NextResponse.json({ audit });
}