wulf-pulse/app/api/dashboard/overview/route.ts
lorentz 9bfb57553d feat(design): nav/visual overhaul — brand layer, /status route, KPI dashboard, TanStack DataTable
Major UI refresh on the nav-design-improvements branch.  Drops 2013-era
inline styles and consolidates patterns behind shared primitives.

Foundation
- New Wulf brand layer in app/styles/brand.css repointing --primary to
  the standards-guide blue (#0075AD) with utility classes for numerics
  (.num / .num-lg / .num-xl), metric labels, surface tints, and the
  wolf-mark watermark
- Switch primary face to IBM Plex Sans + IBM Plex Mono via next/font;
  Helvetica/Arial stays in the fallback chain for brand fidelity
- Wordmark subtitle changed from "PSA Management System" to
  "Operations console" everywhere it appeared
- Tagline footer ("Don't be afraid to cry") on every non-mobile page

Status moved out of /dashboard
- New /status route with integration tiles grouped by category, sync
  health table, worker pulse cards (analyzer / RMM / sync scheduler),
  token-expiry section, conditional alert banner
- Top-bar StatusIndicator polls integration health every 60s and links
  to /status
- INTEGRATIONS_DISABLED env var suppresses operator-disabled
  integrations (e.g. SentinelOne) — no failure noise from broken-on-
  purpose entries.  Aliases supported (sentinelone → s1, etc.)

Dashboard rebuilt around KPIs
- /api/dashboard/overview adds today snapshot (opened, resolved, open
  total, SLA breaches) with delta math
- /api/dashboard/trends backs queue × priority heatmap, 30-day volume
  area chart, 30-day mean resolution time line chart, today's active
  engineers leaderboard

Components
- StatusBadge driven by lib/status-registry.ts (priority, ticket
  status, classification, source, company type, publish, active /
  yes-no / billable / approved registries)
- StatusLight (8px geometric square, five states, three sizes)
- EmptyState (shared dashed panel with icon + headline + optional CTA)
- KpiCard with delta indicator and tonal left border
- WulfMark (mark / wordmark variants from /public/branding)
- Skeleton helpers (SkeletonRow / Rows / Card / Chart / Header / Table)

Navigation
- Admin flat link → dropdown with seven shortcuts
- New UserMenu (initials avatar, role badge, settings + sign-out)
- Active-route highlight is now a 2px Wulf-blue underline echoing the
  PageHeader rule (consistent across flat links and submenu triggers);
  active children inside dropdowns use bg-primary/10
- Submenu width is content-driven (min-w 320 / max-w 440, single col)
- Mobile hamburger via Sheet, reuses the same nav config

Pages migrated
- 16 admin sub-pages adopt PageHeader (with accent prop)
- /addigy-devices: shadcn Table + Checkbox; PageHeader; status badges
- 10 raw <table> blocks across admin/sync/* migrated to shadcn Table
- /veeam-analysis migrated to shadcn Table (kept its expansion logic)
- Detail routes (analyzer ticket, analyzer analysis) get breadcrumbs

DataTable
- Rewritten on @tanstack/react-table v8 in manual mode; external API
  unchanged so all 10+ data-browser pages keep working
- New optional props for drill-down rows: getRowCanExpand + renderSubRow

Mobile
- Multi-select Popover gets max-w-[calc(100vw-1rem)] and
  collisionPadding so dropdowns can't overflow narrow viewports
- CI filter bar wraps and shrinks; stat pill flows below

Docs
- New ARCHITECTURE.md (load-bearing reference for runtime, data flow,
  workers, analyzer pipeline, auth, deployment, gotchas)
- New DESIGN.md (tokens, layout, navigation IA, component vocabulary,
  rolling backlog of remaining cleanup)
- CLAUDE.md refreshed with pointers to the two new docs and the
  INTEGRATIONS_DISABLED operator config note
- shadcn registry registered as project-level MCP server (.mcp.json)

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

222 lines
7.8 KiB
TypeScript

/**
* GET /api/dashboard/overview
* Single round-trip backing the new dashboard. All queries run in parallel.
*
* today — KPI snapshot: opened, resolved, open total, SLA breaches
* attention — counts that should pull a human's eyes
* observations — recent device_observations (loglift et al.)
* audits — recent endpoint_audits
* syncHealth — per-schedule last_run / last_status (consumed by /status)
* stats — small footer: companies, CIs, xref linkage
*/
import { NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
export async function GET() {
const { error } = await requireAuth();
if (error) return error;
type Counts = { count: string };
const [
todayRes,
yesterdayOpenedRes,
last7AvgResolvedRes,
linkConflictsRes,
itglueUnlinkedRes,
s1UnmappedRes,
schedulesRes,
observationsRes,
auditsRes,
syncHealthRes,
companiesRes,
ciRes,
xrefRes,
] = await Promise.all([
/* today snapshot — single row, all four KPIs */
postgresClient.query<{
opened_today: string;
resolved_today: string;
open_total: string;
sla_breaches: string;
}>(`
SELECT
COUNT(*) FILTER (WHERE create_date::date = CURRENT_DATE)::text AS opened_today,
COUNT(*) FILTER (WHERE completed_date::date = CURRENT_DATE)::text AS resolved_today,
COUNT(*) FILTER (WHERE completed_date IS NULL)::text AS open_total,
COUNT(*) FILTER (
WHERE completed_date IS NULL
AND due_date_time IS NOT NULL
AND due_date_time < NOW()
)::text AS sla_breaches
FROM tickets
WHERE is_deleted = false OR is_deleted IS NULL
`),
/* yesterday's opened count for the today-vs-yesterday delta */
postgresClient.query<{ count: string }>(`
SELECT COUNT(*)::text AS count
FROM tickets
WHERE create_date::date = CURRENT_DATE - INTERVAL '1 day'
AND (is_deleted = false OR is_deleted IS NULL)
`),
/* 7-day average resolved (excluding today) for the resolved delta */
postgresClient.query<{ avg_resolved: string }>(`
SELECT COALESCE(AVG(daily_count), 0)::text AS avg_resolved
FROM (
SELECT completed_date::date AS d, COUNT(*) AS daily_count
FROM tickets
WHERE completed_date >= CURRENT_DATE - INTERVAL '7 days'
AND completed_date < CURRENT_DATE
AND (is_deleted = false OR is_deleted IS NULL)
GROUP BY completed_date::date
) sub
`),
postgresClient.query<Counts>(
`SELECT COUNT(*)::text AS count FROM device_link_review WHERE resolved_at IS NULL`
),
postgresClient.query<Counts>(
`SELECT COUNT(*)::text AS count FROM device_external_ids WHERE source = 'itglue' AND configuration_item_id IS NULL`
),
postgresClient.query<Counts>(
`SELECT COUNT(*)::text AS count FROM device_external_ids WHERE source = 's1' AND configuration_item_id IS NULL`
),
postgresClient.query<{ enabled: string; total: string }>(
`SELECT
COUNT(*) FILTER (WHERE is_enabled)::text AS enabled,
COUNT(*)::text AS total
FROM sync_schedules`
),
postgresClient.query<{
id: string;
kind: string;
source: string;
collected_at: string;
hostname: string | null;
company_name: string | null;
run_id: string | null;
}>(
`SELECT o.id::text,
o.kind, o.source,
o.collected_at::text,
ci.reference_title AS hostname,
c.company_name,
o.run_id
FROM device_observations o
LEFT JOIN configuration_items ci ON ci.id = o.configuration_item_id
LEFT JOIN companies c ON c.id = ci.company_id
ORDER BY o.collected_at DESC
LIMIT 10`
),
postgresClient.query<{
id: string;
generated_at: string;
hostname: string | null;
company_name: string | null;
overall_score: string | null;
field_gaps_count: string;
status: string;
}>(
`SELECT a.id::text,
a.generated_at::text,
ci.reference_title AS hostname,
c.company_name,
a.overall_score::text,
jsonb_array_length(COALESCE(a.field_gaps, '[]'::jsonb))::text AS field_gaps_count,
a.status
FROM endpoint_audits a
LEFT JOIN configuration_items ci ON ci.id = a.configuration_item_id
LEFT JOIN companies c ON c.id = ci.company_id
ORDER BY a.generated_at DESC
LIMIT 10`
),
postgresClient.query<{
id: string;
name: string;
sync_type: string;
is_enabled: boolean;
last_run: string | null;
last_status: string | null;
last_error: string | null;
next_run: string | null;
}>(
`SELECT id, name, sync_type, is_enabled,
last_run::text, last_status, last_error,
next_run::text
FROM sync_schedules
ORDER BY name`
),
postgresClient.query<Counts>(
`SELECT COUNT(*)::text AS count FROM companies WHERE company_type = 1 AND is_active = true`
),
postgresClient.query<Counts>(
`SELECT COUNT(*)::text AS count FROM configuration_items WHERE is_deleted = false OR is_deleted IS NULL`
),
postgresClient.query<{ total: string; linked: string }>(
`SELECT COUNT(*)::text AS total,
COUNT(*) FILTER (WHERE configuration_item_id IS NOT NULL)::text AS linked
FROM device_external_ids`
),
]);
const today = todayRes.rows[0];
const yesterdayOpened = parseInt(yesterdayOpenedRes.rows[0]?.count ?? '0', 10);
const last7Avg = parseFloat(last7AvgResolvedRes.rows[0]?.avg_resolved ?? '0');
return NextResponse.json({
today: {
openedToday: parseInt(today?.opened_today ?? '0', 10),
resolvedToday: parseInt(today?.resolved_today ?? '0', 10),
openTotal: parseInt(today?.open_total ?? '0', 10),
slaBreaches: parseInt(today?.sla_breaches ?? '0', 10),
yesterdayOpened,
last7DayAvgResolved: Math.round(last7Avg * 10) / 10,
},
attention: {
linkConflicts: parseInt(linkConflictsRes.rows[0]?.count ?? '0', 10),
itglueUnlinked: parseInt(itglueUnlinkedRes.rows[0]?.count ?? '0', 10),
s1Unmapped: parseInt(s1UnmappedRes.rows[0]?.count ?? '0', 10),
schedules: {
enabled: parseInt(schedulesRes.rows[0]?.enabled ?? '0', 10),
total: parseInt(schedulesRes.rows[0]?.total ?? '0', 10),
},
},
observations: observationsRes.rows.map((r) => ({
id: r.id,
kind: r.kind,
source: r.source,
collectedAt: r.collected_at,
hostname: r.hostname,
companyName: r.company_name,
runId: r.run_id,
})),
audits: auditsRes.rows.map((r) => ({
id: r.id,
generatedAt: r.generated_at,
hostname: r.hostname,
companyName: r.company_name,
overallScore: r.overall_score === null ? null : Number(r.overall_score),
fieldGapsCount: parseInt(r.field_gaps_count, 10),
status: r.status,
})),
syncHealth: syncHealthRes.rows.map((r) => ({
id: r.id,
name: r.name,
syncType: r.sync_type,
isEnabled: r.is_enabled,
lastRun: r.last_run,
lastStatus: r.last_status,
lastError: r.last_error,
nextRun: r.next_run,
})),
stats: {
activeCompanies: parseInt(companiesRes.rows[0]?.count ?? '0', 10),
configurationItems: parseInt(ciRes.rows[0]?.count ?? '0', 10),
xref: {
total: parseInt(xrefRes.rows[0]?.total ?? '0', 10),
linked: parseInt(xrefRes.rows[0]?.linked ?? '0', 10),
},
},
});
}