wulf-pulse/app/admin/display-settings/page.tsx

323 lines
9.9 KiB
TypeScript
Raw Normal View History

"use client";
import { useState, useEffect, useCallback } from "react";
import { Loader2, Save, SlidersHorizontal, X } from "lucide-react";
import { toast } from "sonner";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
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
import { PageHeader } from '@/components/navigation/page-header';
interface CompanyCategory {
value: number;
label: string;
is_active: boolean;
}
interface Company {
id: number;
company_name: string;
}
interface SectionSettings {
company_category_ids: number[];
excluded_company_ids: number[];
}
interface DisplaySettings {
kiosk: SectionSettings;
mobile: SectionSettings;
}
function CompanySearch({
selectedIds,
categoryIds,
onAdd,
onRemove,
allCompanies,
}: {
selectedIds: number[];
categoryIds: number[];
onAdd: (id: number) => void;
onRemove: (id: number) => void;
allCompanies: Company[];
}) {
const [query, setQuery] = useState("");
const [open, setOpen] = useState(false);
const available = allCompanies.filter(
(c) =>
!selectedIds.includes(c.id) &&
(query === "" || c.company_name.toLowerCase().includes(query.toLowerCase()))
);
const selected = allCompanies.filter((c) => selectedIds.includes(c.id));
return (
<div className="space-y-2">
<div className="flex flex-wrap gap-1 min-h-[28px]">
{selected.map((c) => (
<Badge key={c.id} variant="secondary" className="gap-1">
{c.company_name}
<button
onClick={() => onRemove(c.id)}
className="ml-1 hover:text-destructive"
aria-label={`Remove ${c.company_name}`}
>
<X className="h-3 w-3" />
</button>
</Badge>
))}
{selected.length === 0 && (
<span className="text-xs text-muted-foreground italic">No exclusions</span>
)}
</div>
<div className="relative">
<input
type="text"
placeholder="Search companies to exclude..."
value={query}
onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
onFocus={() => setOpen(true)}
onBlur={() => setTimeout(() => setOpen(false), 150)}
className="w-full rounded-md border border-input bg-background px-3 py-1.5 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
/>
{open && available.length > 0 && (
<div className="absolute z-50 mt-1 w-full max-h-52 overflow-auto rounded-md border bg-popover shadow-md">
{available.slice(0, 30).map((c) => (
<button
key={c.id}
className="w-full px-3 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground"
onMouseDown={() => { onAdd(c.id); setQuery(""); }}
>
{c.company_name}
<span className="ml-2 text-xs text-muted-foreground">#{c.id}</span>
</button>
))}
</div>
)}
</div>
</div>
);
}
function Section({
title,
description,
settingsKey,
settings,
categories,
companies,
onSaved,
}: {
title: string;
description: string;
settingsKey: "kiosk" | "mobile";
settings: SectionSettings;
categories: CompanyCategory[];
companies: Company[];
onSaved: (key: "kiosk" | "mobile", updated: SectionSettings) => void;
}) {
const [local, setLocal] = useState<SectionSettings>(settings);
const [saving, setSaving] = useState(false);
useEffect(() => { setLocal(settings); }, [settings]);
function toggleCategory(value: number) {
setLocal((prev) => ({
...prev,
company_category_ids: prev.company_category_ids.includes(value)
? prev.company_category_ids.filter((v) => v !== value)
: [...prev.company_category_ids, value],
}));
}
function addExclusion(id: number) {
setLocal((prev) => ({ ...prev, excluded_company_ids: [...prev.excluded_company_ids, id] }));
}
function removeExclusion(id: number) {
setLocal((prev) => ({ ...prev, excluded_company_ids: prev.excluded_company_ids.filter((v) => v !== id) }));
}
async function save() {
setSaving(true);
try {
await Promise.all([
fetch("/api/admin/display-settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
setting_key: `${settingsKey}_company_category_ids`,
setting_value: local.company_category_ids,
}),
}),
fetch("/api/admin/display-settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
setting_key: `${settingsKey}_excluded_company_ids`,
setting_value: local.excluded_company_ids,
}),
}),
]);
toast.success(`${title} settings saved`);
onSaved(settingsKey, local);
} catch {
toast.error(`Failed to save ${title} settings`);
} finally {
setSaving(false);
}
}
const filteredCompanies = companies.filter((c) =>
local.company_category_ids.length === 0
? true
: true
);
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<SlidersHorizontal className="h-5 w-5" />
{title}
</CardTitle>
<CardDescription>{description}</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div>
<h3 className="text-sm font-medium mb-3">Company Categories to Include</h3>
{categories.length === 0 ? (
<p className="text-sm text-muted-foreground italic">
No categories synced yet. Run a sync to populate.
</p>
) : (
<div className="space-y-2">
{categories.map((cat) => (
<div key={cat.value} className="flex items-center gap-2">
<Checkbox
id={`${settingsKey}-cat-${cat.value}`}
checked={local.company_category_ids.includes(cat.value)}
onCheckedChange={() => toggleCategory(cat.value)}
/>
<Label
htmlFor={`${settingsKey}-cat-${cat.value}`}
className="cursor-pointer font-normal"
>
{cat.label}
<span className="ml-2 text-xs text-muted-foreground">id={cat.value}</span>
</Label>
</div>
))}
</div>
)}
</div>
<div>
<h3 className="text-sm font-medium mb-1">Excluded Companies</h3>
<p className="text-xs text-muted-foreground mb-2">
Individual companies to hide even if they match the selected categories.
</p>
<CompanySearch
selectedIds={local.excluded_company_ids}
categoryIds={local.company_category_ids}
allCompanies={filteredCompanies}
onAdd={addExclusion}
onRemove={removeExclusion}
/>
</div>
<Button onClick={save} disabled={saving} size="sm">
{saving ? (
<><Loader2 className="mr-2 h-4 w-4 animate-spin" />Saving</>
) : (
<><Save className="mr-2 h-4 w-4" />Save {title} Settings</>
)}
</Button>
</CardContent>
</Card>
);
}
export default function DisplaySettingsPage() {
const [settings, setSettings] = useState<DisplaySettings | null>(null);
const [categories, setCategories] = useState<CompanyCategory[]>([]);
const [companies, setCompanies] = useState<Company[]>([]);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
try {
const [settingsRes, catsRes, companiesRes] = await Promise.all([
fetch("/api/admin/display-settings"),
fetch("/api/data/company-categories"),
fetch("/api/data/companies-list"),
]);
if (settingsRes.ok) setSettings(await settingsRes.json());
if (catsRes.ok) setCategories(await catsRes.json());
if (companiesRes.ok) setCompanies(await companiesRes.json());
} catch {
toast.error("Failed to load display settings");
} finally {
setLoading(false);
}
}, []);
useEffect(() => { load(); }, [load]);
function handleSaved(key: "kiosk" | "mobile", updated: SectionSettings) {
setSettings((prev) => prev ? { ...prev, [key]: updated } : prev);
}
if (loading) {
return (
<div className="container mx-auto py-8 px-4 flex justify-center">
<Loader2 className="h-8 w-8 animate-spin" />
</div>
);
}
if (!settings) {
return (
<div className="container mx-auto py-8 px-4">
<p className="text-destructive">Failed to load settings.</p>
</div>
);
}
return (
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
<>
<PageHeader
title="Display Settings"
description="Configure which companies appear in the Kiosk and Mobile dashboards."
breadcrumbs={[{ label: 'Admin', href: '/admin' }, { label: 'Display Settings' }]}
accent
/>
<div className="container mx-auto py-8 px-4 max-w-5xl">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Section
title="Kiosk"
description="Settings for the executive kiosk display."
settingsKey="kiosk"
settings={settings.kiosk}
categories={categories}
companies={companies}
onSaved={handleSaved}
/>
<Section
title="Mobile"
description="Settings for the mobile dashboard."
settingsKey="mobile"
settings={settings.mobile}
categories={categories}
companies={companies}
onSaved={handleSaved}
/>
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
</div>
</div>
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
</>
);
}