feat(analyzer): Phase 2 — full stage persistence, fingerprints, aggregate reports, cost guards

Eight sub-phases per docs/ticket-analyzer-phase2-spec.md:

2.1 Schema (migration 070): analyzer_stage_executions table; source_snapshot,
    aggregate_fingerprint, fingerprint_generated_at columns on analyzer_analyses.
    model_traces marked LEGACY (kept for back-compat).
2.2 Every pipeline stage records a row to analyzer_stage_executions, success
    or failure. Worker persists a status='failed' analyzer_analyses row when
    the pipeline throws so partial stage records have a parent. Pipeline
    exposes raw triage/sonnet/opus responses for downstream stages.
2.3 Stage 3 prompt updated with markdown formatting rules + banned filler
    phrases. Added react-markdown + remark-gfm + @tailwindcss/typography.
    New <AnalysisMarkdown> component replaces <ProseText>; coerces stray
    headers to bold paragraphs.
2.4 Stage 6 fingerprint (Haiku) runs after persistence, failure-tolerant.
    scripts/backfill-fingerprints.ts reconstructs Stage 6 input from the
    legacy model_traces blob.
2.5 Browse UI rebuild at /analyzer/tickets: multi-select for client/issue/
    queue/status/priority/assignee, sticky filter bar, active-filter chips,
    bulk selection persisted via localStorage, "Analyze N selected" +
    "Generate aggregate report" actions. New <MultiSelect> primitive.
    Staleness uses last_activity_date > completed_at heuristic per spec C.1.
2.6 Aggregate reports (migration 071): runner is fire-and-forget, persists
    SQL distributions immediately so UI shows partial state during the
    Sonnet reduce call. Three endpoints, three pages (/analyzer/reports[/new
    /:id]). IT Glue context fetcher capped at 200 doc titles.
2.7 Cost guards (migration 072): per-request $5 confirmation, soft-warn at
    $20/day, hard-block at $50/day with ANALYZER_DAILY_COST_OVERRIDE_USERS
    override. Every gating decision audited.
2.8 Runbook + build notes updated.

128 vitest tests passing, tsc clean. Migrations 070/071/072 idempotent
(IF NOT EXISTS). model_traces double-write retained — drop in a future
migration once aggregate reports have soaked.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
lorentz 2026-04-29 14:00:22 -04:00
parent b20c94ea1a
commit bd3401df1c
33 changed files with 7132 additions and 554 deletions

View file

@ -0,0 +1,489 @@
'use client';
import { useEffect, useState, use } from 'react';
import Link from 'next/link';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
ArrowLeft,
AlertTriangle,
Loader2,
CheckCircle2,
XCircle,
} from 'lucide-react';
import { AnalysisMarkdown } from '@/components/analyzer/analysis-markdown';
type Report = {
id: string;
generatedAt: string;
reportTitle: string | null;
ticketCount: number;
status: 'pending' | 'running' | 'complete' | 'failed';
errorMessage: string | null;
estimatedCostUsd: number | null;
modelUsed: string | null;
totalInputTokens: number | null;
totalOutputTokens: number | null;
itglueContextIncluded: boolean | null;
dateRangeActual: { earliest: string | null; latest: string | null } | null;
categoryDistribution: Record<string, number> | null;
clientDistribution: Record<string, number> | null;
resolutionPathDistribution: Record<string, number> | null;
rootCauseDistribution: Record<string, number> | null;
documentationGaps:
| Array<{
gap: string;
frequency: number;
example_ticket_numbers: string[];
evidence: string;
itglue_check: 'no_doc_exists' | 'doc_exists_but_unused' | 'unable_to_verify';
}>
| null;
processGaps:
| Array<{
gap: string;
frequency: number;
severity: 'low' | 'medium' | 'high';
example_ticket_numbers: string[];
evidence: string;
}>
| null;
clientPatterns:
| Array<{
client: string;
pattern: string;
frequency: number;
example_ticket_numbers: string[];
}>
| null;
recurrenceClusters:
| Array<{ theme: string; ticket_numbers: string[]; summary: string }>
| null;
systemicObservations:
| Array<{ observation: string; evidence: string; severity: 'low' | 'medium' | 'high' }>
| null;
recommendedActions:
| Array<{
action: string;
rationale: string;
priority: 'low' | 'medium' | 'high';
type: 'documentation' | 'process' | 'training' | 'tooling';
}>
| null;
narrativeSummary: string | null;
executiveSummary: string | null;
};
const SEVERITY_TONE: Record<string, string> = {
high: 'border-red-500 bg-red-500/5',
medium: 'border-amber-500 bg-amber-500/5',
low: 'border-blue-500 bg-blue-500/5',
};
const ITGLUE_CHECK_TONE: Record<string, string> = {
no_doc_exists: 'text-red-600 border-red-300 dark:text-red-400 dark:border-red-800',
doc_exists_but_unused:
'text-amber-600 border-amber-300 dark:text-amber-400 dark:border-amber-800',
unable_to_verify: 'text-muted-foreground',
};
const ITGLUE_CHECK_LABEL: Record<string, string> = {
no_doc_exists: 'No doc exists',
doc_exists_but_unused: 'Doc exists but unused',
unable_to_verify: 'Unable to verify',
};
function MiniBars({ data }: { data: Record<string, number> | null }) {
if (!data || Object.keys(data).length === 0) return null;
const entries = Object.entries(data).sort((a, b) => b[1] - a[1]);
const max = entries[0]?.[1] ?? 1;
return (
<div className="space-y-1.5">
{entries.map(([key, val]) => (
<div key={key} className="text-xs">
<div className="flex justify-between">
<span className="truncate">{key}</span>
<span className="text-muted-foreground tabular-nums ml-2">{val}</span>
</div>
<div className="h-1.5 bg-muted rounded overflow-hidden">
<div
className="h-full bg-primary rounded"
style={{ width: `${Math.round((val / max) * 100)}%` }}
/>
</div>
</div>
))}
</div>
);
}
export default function AggregateReportPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = use(params);
const [report, setReport] = useState<Report | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
async function load() {
try {
const res = await fetch(`/api/analyzer/aggregate-reports/${id}`);
if (!res.ok) {
throw new Error(`Request failed: ${res.status}`);
}
const { report } = (await res.json()) as { report: Report };
if (cancelled) return;
setReport(report);
setLoading(false);
if (report.status === 'pending' || report.status === 'running') {
timer = setTimeout(load, 3000);
}
} catch (err) {
if (cancelled) return;
setError(err instanceof Error ? err.message : 'Unknown error');
setLoading(false);
}
}
void load();
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
}, [id]);
if (loading && !report)
return <div className="p-6 text-sm text-muted-foreground">Loading</div>;
if (error)
return <div className="p-6 text-sm text-destructive">{error}</div>;
if (!report) return null;
return (
<div className="container mx-auto px-4 py-6 space-y-6 max-w-screen-xl">
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" asChild>
<Link href="/analyzer/reports">
<ArrowLeft className="w-4 h-4 mr-1" />
All reports
</Link>
</Button>
</div>
{/* Header */}
<Card>
<CardHeader>
<div className="flex items-start justify-between gap-4 flex-wrap">
<div className="space-y-1 min-w-0">
<CardTitle className="text-2xl">
{report.reportTitle ?? `Aggregate report · ${report.ticketCount} tickets`}
</CardTitle>
<p className="text-sm text-muted-foreground">
{new Date(report.generatedAt).toLocaleString()}
{report.modelUsed && ` · ${report.modelUsed}`}
{report.estimatedCostUsd !== null && (
<> · ${report.estimatedCostUsd.toFixed(4)}</>
)}
{report.itglueContextIncluded !== null && (
<>
{' · '}IT Glue context: {report.itglueContextIncluded ? 'included' : 'no'}
</>
)}
{report.dateRangeActual?.earliest && report.dateRangeActual?.latest && (
<>
{' · '}
{new Date(report.dateRangeActual.earliest).toLocaleDateString()}
{' '}
{new Date(report.dateRangeActual.latest).toLocaleDateString()}
</>
)}
</p>
</div>
<StatusBadge status={report.status} />
</div>
</CardHeader>
</Card>
{report.status === 'failed' && report.errorMessage && (
<Card className="border-destructive/40 bg-destructive/5">
<CardContent className="pt-6 flex items-start gap-3">
<AlertTriangle className="w-5 h-5 text-destructive shrink-0 mt-0.5" />
<div>
<p className="text-sm font-medium">Report generation failed</p>
<p className="text-sm text-muted-foreground mt-1 font-mono whitespace-pre-wrap">
{report.errorMessage}
</p>
</div>
</CardContent>
</Card>
)}
{(report.status === 'pending' || report.status === 'running') && (
<Card className="border-primary/40 bg-primary/5">
<CardContent className="pt-6 flex items-center gap-3">
<Loader2 className="w-5 h-5 animate-spin text-primary" />
<div className="text-sm">
{report.status === 'pending' ? 'Queued.' : 'Running.'} The page will
refresh automatically when the report is ready (typically 3090s).
</div>
</CardContent>
</Card>
)}
{/* Executive summary */}
{report.executiveSummary && (
<Card className="border-primary/40">
<CardHeader>
<CardTitle className="text-base text-primary uppercase tracking-wide font-semibold">
Executive Summary
</CardTitle>
</CardHeader>
<CardContent>
<AnalysisMarkdown className="text-base">
{report.executiveSummary}
</AnalysisMarkdown>
</CardContent>
</Card>
)}
{/* Distributions */}
{(report.categoryDistribution ||
report.rootCauseDistribution ||
report.resolutionPathDistribution ||
report.clientDistribution) && (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<Card>
<CardHeader>
<CardTitle className="text-sm uppercase tracking-wide">Categories</CardTitle>
</CardHeader>
<CardContent>
<MiniBars data={report.categoryDistribution} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-sm uppercase tracking-wide">Root cause</CardTitle>
</CardHeader>
<CardContent>
<MiniBars data={report.rootCauseDistribution} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-sm uppercase tracking-wide">Resolution</CardTitle>
</CardHeader>
<CardContent>
<MiniBars data={report.resolutionPathDistribution} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-sm uppercase tracking-wide">Clients</CardTitle>
</CardHeader>
<CardContent>
<MiniBars data={report.clientDistribution} />
</CardContent>
</Card>
</div>
)}
{/* Documentation gaps */}
{report.documentationGaps && report.documentationGaps.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Documentation gaps</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{report.documentationGaps.map((g, i) => (
<div
key={i}
className="rounded-lg border-l-4 border-blue-400 bg-blue-500/5 p-3"
>
<div className="flex items-center gap-2 flex-wrap">
<Badge
variant="outline"
className={ITGLUE_CHECK_TONE[g.itglue_check] ?? ''}
>
{ITGLUE_CHECK_LABEL[g.itglue_check]}
</Badge>
<Badge variant="secondary">{g.frequency}×</Badge>
<p className="text-sm font-medium">{g.gap}</p>
</div>
<p className="text-xs text-muted-foreground mt-2">{g.evidence}</p>
<div className="mt-2 text-xs flex flex-wrap gap-1">
{g.example_ticket_numbers.map((tn) => (
<Link
key={tn}
href={`/analyzer/ticket/${encodeURIComponent(tn)}`}
className="font-mono underline text-muted-foreground hover:text-foreground"
>
{tn}
</Link>
))}
</div>
</div>
))}
</CardContent>
</Card>
)}
{/* Process gaps */}
{report.processGaps && report.processGaps.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Process gaps</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{report.processGaps.map((g, i) => (
<div
key={i}
className={`rounded-lg border-l-4 p-3 ${SEVERITY_TONE[g.severity] ?? ''}`}
>
<div className="flex items-center gap-2 flex-wrap">
<Badge
variant={
g.severity === 'high'
? 'destructive'
: g.severity === 'medium'
? 'default'
: 'secondary'
}
>
{g.severity}
</Badge>
<Badge variant="secondary">{g.frequency}×</Badge>
<p className="text-sm font-medium">{g.gap}</p>
</div>
<p className="text-xs text-muted-foreground mt-2">{g.evidence}</p>
<div className="mt-2 text-xs flex flex-wrap gap-1">
{g.example_ticket_numbers.map((tn) => (
<Link
key={tn}
href={`/analyzer/ticket/${encodeURIComponent(tn)}`}
className="font-mono underline text-muted-foreground hover:text-foreground"
>
{tn}
</Link>
))}
</div>
</div>
))}
</CardContent>
</Card>
)}
{/* Recurrence clusters */}
{report.recurrenceClusters && report.recurrenceClusters.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Recurrence clusters</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{report.recurrenceClusters.map((c, i) => (
<div key={i} className="border rounded-lg p-4">
<div className="font-medium text-sm mb-2">{c.theme}</div>
<AnalysisMarkdown className="text-sm">{c.summary}</AnalysisMarkdown>
<div className="mt-2 text-xs flex flex-wrap gap-1">
{c.ticket_numbers.map((tn) => (
<Link
key={tn}
href={`/analyzer/ticket/${encodeURIComponent(tn)}`}
className="font-mono underline text-muted-foreground hover:text-foreground"
>
{tn}
</Link>
))}
</div>
</div>
))}
</CardContent>
</Card>
)}
{/* Recommended actions */}
{report.recommendedActions && report.recommendedActions.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Recommended actions</CardTitle>
</CardHeader>
<CardContent className="grid gap-3 md:grid-cols-2">
{report.recommendedActions
.slice()
.sort(
(a, b) =>
['low', 'medium', 'high'].indexOf(b.priority) -
['low', 'medium', 'high'].indexOf(a.priority)
)
.map((a, i) => (
<div key={i} className="border rounded-lg p-4 space-y-2">
<div className="flex items-center gap-2">
<Badge
variant={
a.priority === 'high'
? 'destructive'
: a.priority === 'medium'
? 'default'
: 'secondary'
}
>
{a.priority}
</Badge>
<Badge variant="outline" className="capitalize">
{a.type}
</Badge>
</div>
<AnalysisMarkdown className="text-sm prose-p:font-medium">
{a.action}
</AnalysisMarkdown>
<AnalysisMarkdown className="text-xs text-muted-foreground">
{a.rationale}
</AnalysisMarkdown>
</div>
))}
</CardContent>
</Card>
)}
{/* Narrative summary */}
{report.narrativeSummary && (
<Card>
<CardHeader>
<CardTitle>Narrative summary</CardTitle>
</CardHeader>
<CardContent>
<AnalysisMarkdown className="text-base">
{report.narrativeSummary}
</AnalysisMarkdown>
</CardContent>
</Card>
)}
</div>
);
}
function StatusBadge({ status }: { status: Report['status'] }) {
if (status === 'complete')
return (
<Badge className="bg-emerald-500/10 text-emerald-700 dark:text-emerald-400" variant="outline">
<CheckCircle2 className="w-3 h-3 mr-1" />
Complete
</Badge>
);
if (status === 'failed')
return (
<Badge variant="destructive">
<XCircle className="w-3 h-3 mr-1" />
Failed
</Badge>
);
return (
<Badge variant="secondary">
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
{status === 'pending' ? 'Queued' : 'Running'}
</Badge>
);
}

View file

@ -0,0 +1,222 @@
'use client';
import { useEffect, useMemo, useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { ArrowLeft, Sparkles, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';
function NewReportInner() {
const router = useRouter();
const params = useSearchParams();
const ticketNumbers = useMemo(
() =>
(params.get('ids') ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean),
[params]
);
const [title, setTitle] = useState('');
const [includeItglue, setIncludeItglue] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [warning, setWarning] = useState<string | null>(null);
useEffect(() => {
if (ticketNumbers.length === 0)
setWarning('No tickets specified. Pick tickets from the browse page first.');
else if (ticketNumbers.length > 100)
setWarning(
`${ticketNumbers.length} tickets selected — the cap is 100. Narrow the selection or split into multiple reports.`
);
else setWarning(null);
}, [ticketNumbers]);
async function postReport(confirmedCost: boolean) {
const res = await fetch('/api/analyzer/aggregate-reports', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ticketNumbers,
includeItglueContext: includeItglue,
reportTitle: title.trim() || null,
confirmedCost,
}),
});
return {
ok: res.ok,
status: res.status,
data: (await res.json().catch(() => ({}))) as {
reportId?: string;
error?: string;
message?: string;
missingFingerprint?: string[];
staleAnalyses?: string[];
hint?: string;
requiresConfirmation?: boolean;
estimatedCost?: number;
dailySpendBefore?: number;
},
};
}
async function handleGenerate() {
if (ticketNumbers.length === 0 || ticketNumbers.length > 100) return;
setSubmitting(true);
try {
let attempt = await postReport(false);
if (
!attempt.ok &&
attempt.status === 400 &&
attempt.data.requiresConfirmation &&
attempt.data.estimatedCost
) {
const ok = window.confirm(
`Estimated cost for this report is $${attempt.data.estimatedCost.toFixed(
2
)} (above $5 threshold). Daily spend so far: $${(attempt.data.dailySpendBefore ?? 0).toFixed(2)}.\n\nProceed?`
);
if (!ok) {
setSubmitting(false);
return;
}
attempt = await postReport(true);
}
if (!attempt.ok || !attempt.data.reportId) {
const d = attempt.data;
const detail = d.missingFingerprint?.length
? ` Missing fingerprint on: ${d.missingFingerprint.slice(0, 5).join(', ')}${
d.missingFingerprint.length > 5
? `, +${d.missingFingerprint.length - 5} more`
: ''
}.`
: d.staleAnalyses?.length
? ` Stale: ${d.staleAnalyses.slice(0, 5).join(', ')}${
d.staleAnalyses.length > 5
? `, +${d.staleAnalyses.length - 5} more`
: ''
}.`
: '';
throw new Error(
(d.message ?? d.error ?? 'Request failed') +
detail +
(d.hint ? ` (${d.hint})` : '')
);
}
router.push(`/analyzer/reports/${attempt.data.reportId}`);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Unknown error');
setSubmitting(false);
}
}
return (
<div className="container mx-auto px-4 py-6 space-y-6 max-w-3xl">
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" asChild>
<Link href="/analyzer/tickets">
<ArrowLeft className="w-4 h-4 mr-1" />
Back to browse
</Link>
</Button>
</div>
<div>
<h1 className="text-2xl font-semibold tracking-tight">
Generate aggregate report
</h1>
<p className="text-muted-foreground text-sm mt-1">
Cross-ticket analysis over the {ticketNumbers.length} ticket
{ticketNumbers.length === 1 ? '' : 's'} you selected.
</p>
</div>
{warning && (
<Card className="border-amber-300 bg-amber-50/50 dark:bg-amber-950/30">
<CardContent className="pt-6 flex items-start gap-3">
<AlertTriangle className="w-5 h-5 text-amber-600 shrink-0 mt-0.5" />
<p className="text-sm">{warning}</p>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Selected tickets</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-1.5 max-h-48 overflow-y-auto">
{ticketNumbers.length === 0 ? (
<span className="text-sm text-muted-foreground">None</span>
) : (
ticketNumbers.map((tn) => (
<Badge key={tn} variant="secondary" className="font-mono text-xs">
{tn}
</Badge>
))
)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Options</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="report-title">Report title (optional)</Label>
<Input
id="report-title"
placeholder="e.g. April backup tickets"
value={title}
onChange={(e) => setTitle(e.target.value)}
maxLength={200}
/>
</div>
<Label className="flex items-start gap-3 cursor-pointer">
<Checkbox
checked={includeItglue}
onCheckedChange={(c) => setIncludeItglue(c === true)}
className="mt-0.5"
/>
<span className="space-y-0.5">
<span className="text-sm font-medium block">Include IT Glue context</span>
<span className="text-xs text-muted-foreground block">
Fetch documentation titles for the affected clients so the model
can distinguish "no doc exists" from "doc exists but unused".
</span>
</span>
</Label>
</CardContent>
</Card>
<div className="flex justify-end gap-2">
<Button variant="outline" asChild>
<Link href="/analyzer/tickets">Cancel</Link>
</Button>
<Button
disabled={submitting || ticketNumbers.length === 0 || ticketNumbers.length > 100}
onClick={handleGenerate}
>
<Sparkles className="w-4 h-4 mr-2" />
{submitting ? 'Queueing…' : 'Generate report'}
</Button>
</div>
</div>
);
}
export default function NewReportPage() {
return (
<Suspense fallback={<div className="p-6 text-sm text-muted-foreground">Loading</div>}>
<NewReportInner />
</Suspense>
);
}

View file

@ -0,0 +1,152 @@
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { CheckCircle2, XCircle, Loader2 } from 'lucide-react';
interface ReportSummary {
id: string;
generatedAt: string;
reportTitle: string | null;
ticketCount: number;
status: 'pending' | 'running' | 'complete' | 'failed';
estimatedCostUsd: number | null;
modelUsed: string | null;
generatedByUserId: string | null;
}
export default function ReportsListPage() {
const [reports, setReports] = useState<ReportSummary[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
fetch('/api/analyzer/aggregate-reports')
.then((r) => (r.ok ? r.json() : Promise.reject(r)))
.then((data: { reports: ReportSummary[] }) => {
if (!cancelled) setReports(data.reports);
})
.catch((err) => {
if (!cancelled)
setError(err instanceof Error ? err.message : 'Failed to load reports');
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, []);
return (
<div className="container mx-auto px-4 py-6 space-y-6 max-w-screen-xl">
<div className="flex items-start justify-between gap-4 flex-wrap">
<div>
<h1 className="text-2xl font-semibold tracking-tight">
Aggregate reports
</h1>
<p className="text-muted-foreground text-sm mt-1">
Cross-ticket pattern analysis. Generate a new one from the browse
page.
</p>
</div>
<Button asChild>
<Link href="/analyzer/tickets">Browse tickets</Link>
</Button>
</div>
<Card>
<CardContent className="p-0">
{loading ? (
<div className="p-6 text-sm text-muted-foreground">Loading</div>
) : error ? (
<div className="p-6 text-sm text-destructive">{error}</div>
) : reports.length === 0 ? (
<div className="p-12 text-center text-muted-foreground">
<p>No reports yet.</p>
<p className="text-xs mt-1">
Pick tickets on the browse page and click{' '}
<em>Generate aggregate report</em>.
</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[110px]">Status</TableHead>
<TableHead>Title</TableHead>
<TableHead className="w-[100px]">Tickets</TableHead>
<TableHead className="w-[120px]">Model</TableHead>
<TableHead className="w-[100px]">Cost</TableHead>
<TableHead className="w-[160px]">Generated</TableHead>
<TableHead className="w-[100px] text-right">Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{reports.map((r) => (
<TableRow key={r.id}>
<TableCell>
{r.status === 'complete' ? (
<Badge
variant="outline"
className="bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"
>
<CheckCircle2 className="w-3 h-3 mr-1" />
Complete
</Badge>
) : r.status === 'failed' ? (
<Badge variant="destructive">
<XCircle className="w-3 h-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary">
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
{r.status}
</Badge>
)}
</TableCell>
<TableCell className="text-sm">
{r.reportTitle ?? (
<span className="text-muted-foreground italic">Untitled</span>
)}
</TableCell>
<TableCell className="text-sm">{r.ticketCount}</TableCell>
<TableCell className="text-xs text-muted-foreground">
{r.modelUsed ?? '—'}
</TableCell>
<TableCell className="text-xs">
{r.estimatedCostUsd === null
? '—'
: `$${r.estimatedCostUsd.toFixed(4)}`}
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{new Date(r.generatedAt).toLocaleString()}
</TableCell>
<TableCell className="text-right">
<Button variant="outline" size="sm" asChild>
<Link href={`/analyzer/reports/${r.id}`}>View</Link>
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,24 @@
/**
* GET /api/analyzer/aggregate-reports/:id
*
* Returns the full report row. Frontend polls this for completion when the
* report is in 'pending'/'running' status.
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import { getAggregateReport } from '@/lib/services/analyzer/aggregate-persistence';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { error } = await requireAuth();
if (error) return error;
const { id } = await params;
const report = await getAggregateReport(id);
if (!report) {
return NextResponse.json({ error: 'Report not found' }, { status: 404 });
}
return NextResponse.json({ report });
}

View file

@ -0,0 +1,210 @@
/**
* POST /api/analyzer/aggregate-reports
* GET /api/analyzer/aggregate-reports
*
* POST: queue a new aggregate report. Validates inputs, creates a 'pending'
* row, fires runAggregateReport in the background, returns immediately with
* the report id.
*
* GET: list reports (paginated, optionally filtered by user).
*/
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
import {
createAggregateReport,
listAggregateReports,
runAggregateReport,
} from '@/lib/services/analyzer/aggregate-persistence';
import {
estimateAggregateReportCost,
evaluateCost,
recordCostAuditDecision,
} from '@/lib/services/analyzer/cost-guard';
const MAX_TICKETS_PER_REPORT = 100;
const PostBody = z.object({
analysisIds: z.array(z.string().uuid()).max(MAX_TICKETS_PER_REPORT).optional(),
ticketNumbers: z.array(z.string()).max(MAX_TICKETS_PER_REPORT).optional(),
includeItglueContext: z.boolean().default(true),
reportTitle: z.string().max(200).nullable().optional(),
/** Acknowledges the per-request cost guard ($5 threshold). */
confirmedCost: z.boolean().default(false),
});
interface FingerprintCheckRow {
id: string;
ticket_number: string;
analysis_version: number;
has_fingerprint: boolean;
is_stale: boolean;
}
export async function POST(request: NextRequest) {
const { session, error } = await requireAuth();
if (error) return error;
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 { analysisIds, ticketNumbers, includeItglueContext, reportTitle } = parsed.data;
// Resolve analysisIds: explicit list > ticketNumbers (latest analysis per ticket).
let resolvedIds: string[] = [];
if (analysisIds && analysisIds.length > 0) {
resolvedIds = analysisIds;
} else if (ticketNumbers && ticketNumbers.length > 0) {
const res = await postgresClient.query<{ id: string }>(
`SELECT DISTINCT ON (ticket_number) id::text AS id
FROM analyzer_analyses
WHERE ticket_number = ANY($1::text[])
AND status = 'complete'
ORDER BY ticket_number, analysis_version DESC`,
[ticketNumbers]
);
resolvedIds = res.rows.map((r) => r.id);
} else {
return NextResponse.json(
{ error: 'Provide analysisIds or ticketNumbers' },
{ status: 400 }
);
}
if (resolvedIds.length === 0) {
return NextResponse.json(
{ error: 'No matching complete analyses found for the given inputs' },
{ status: 400 }
);
}
if (resolvedIds.length > MAX_TICKETS_PER_REPORT) {
return NextResponse.json(
{
error: `Too many tickets (${resolvedIds.length}). Cap is ${MAX_TICKETS_PER_REPORT}.`,
},
{ status: 400 }
);
}
// Validate fingerprints + staleness.
const validation = await postgresClient.query<FingerprintCheckRow>(
`SELECT aa.id::text AS id,
aa.ticket_number,
aa.analysis_version,
(aa.aggregate_fingerprint IS NOT NULL) AS has_fingerprint,
(t.last_activity_date > aa.completed_at) AS is_stale
FROM analyzer_analyses aa
LEFT JOIN tickets t ON t.ticket_number = aa.ticket_number
AND t.is_deleted = false
WHERE aa.id = ANY($1::uuid[])`,
[resolvedIds]
);
const missingFingerprint = validation.rows
.filter((r) => !r.has_fingerprint)
.map((r) => `${r.ticket_number} v${r.analysis_version}`);
const staleAnalyses = validation.rows
.filter((r) => r.is_stale)
.map((r) => `${r.ticket_number} v${r.analysis_version}`);
if (missingFingerprint.length > 0) {
return NextResponse.json(
{
error: 'Some analyses are missing aggregate_fingerprint',
missingFingerprint,
hint: 'Run scripts/backfill-fingerprints.ts to fill in legacy analyses, or re-analyze.',
},
{ status: 400 }
);
}
if (staleAnalyses.length > 0) {
return NextResponse.json(
{
error:
'Some selected tickets have new activity since their last analysis. Re-analyze first.',
staleAnalyses,
},
{ status: 400 }
);
}
const userId = (session?.user as { id: string } | undefined)?.id ?? null;
// Cost-guard evaluation. Hard-blocks at $50/day, asks for confirmation at >$5.
const estimatedCost = estimateAggregateReportCost({
ticketCount: resolvedIds.length,
includeItglueContext: parsed.data.includeItglueContext,
});
const evaluation = await evaluateCost({
userId,
estimatedCost,
confirmedCost: parsed.data.confirmedCost,
});
await recordCostAuditDecision({
userId,
action: 'aggregate_report',
evaluation,
context: { ticketCount: resolvedIds.length, includeItglueContext: parsed.data.includeItglueContext },
});
if (evaluation.decision === 'blocked') {
return NextResponse.json(
{
error: 'Daily cost limit reached',
message: evaluation.decisionReason,
estimatedCost: evaluation.estimatedCost,
dailySpendBefore: evaluation.dailySpendBefore,
},
{ status: 403 }
);
}
if (evaluation.decision === 'requires_confirmation') {
return NextResponse.json(
{
error: 'Confirmation required',
message: evaluation.decisionReason,
estimatedCost: evaluation.estimatedCost,
dailySpendBefore: evaluation.dailySpendBefore,
requiresConfirmation: true,
retryWith: { confirmedCost: true },
},
{ status: 400 }
);
}
const created = await createAggregateReport({
generatedByUserId: userId,
filterCriteria: { analysisIds: resolvedIds },
analysisIds: resolvedIds,
ticketCount: resolvedIds.length,
includeItglueContext,
reportTitle: reportTitle ?? null,
});
// Fire and forget — runner persists results when done.
void runAggregateReport(created.id).catch((err) => {
console.error('[ANALYZER-REPORT] background runner threw:', err);
});
return NextResponse.json({
reportId: created.id,
status: 'pending',
ticketCount: resolvedIds.length,
});
}
export async function GET(request: NextRequest) {
const { error } = await requireAuth();
if (error) return error;
const url = new URL(request.url);
const limit = Number(url.searchParams.get('limit') ?? 50);
const offset = Number(url.searchParams.get('offset') ?? 0);
const reports = await listAggregateReports({ limit, offset });
return NextResponse.json({ reports });
}

View file

@ -4,52 +4,78 @@
* Returns the dropdown source data for the analyzer ticket browser.
* Companies are limited to those that have at least one non-deleted ticket
* (255 typically ~150 with tickets) so the dropdown isn't padded with
* dormant accounts.
* dormant accounts. Resources are limited to active ones with at least one
* assigned ticket.
*/
import { NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
interface CompanyRow {
id: string;
company_name: string;
}
interface IssueTypeRow {
value: number;
label: string;
}
interface CompanyRow { id: string; company_name: string }
interface IssueTypeRow { value: number; label: string }
interface QueueRow { value: number; label: string }
interface StatusRow { value: number; label: string }
interface PriorityRow { value: number; label: string }
interface ResourceRow { id: string; full_name: string }
export async function GET() {
const { error } = await requireAuth();
if (error) return error;
const [companies, issueTypes] = await Promise.all([
postgresClient.query<CompanyRow>(
`SELECT c.id::text AS id, c.company_name
FROM companies c
WHERE c.is_active = true
AND c.is_deleted = false
AND EXISTS (
SELECT 1 FROM tickets t
WHERE t.company_id = c.id AND t.is_deleted = false
)
ORDER BY c.company_name`
),
postgresClient.query<IssueTypeRow>(
`SELECT value, label
FROM issue_types
WHERE is_active = true
AND is_deleted = false
ORDER BY sort_order NULLS LAST, label`
),
]);
const [companies, issueTypes, queues, statuses, priorities, resources] =
await Promise.all([
postgresClient.query<CompanyRow>(
`SELECT c.id::text AS id, c.company_name
FROM companies c
WHERE c.is_active = true
AND c.is_deleted = false
AND EXISTS (
SELECT 1 FROM tickets t
WHERE t.company_id = c.id AND t.is_deleted = false
)
ORDER BY c.company_name`
),
postgresClient.query<IssueTypeRow>(
`SELECT value, label FROM issue_types
WHERE is_active = true AND is_deleted = false
ORDER BY sort_order NULLS LAST, label`
),
postgresClient.query<QueueRow>(
`SELECT value, label FROM queues
WHERE is_active = true AND is_deleted = false
ORDER BY sort_order NULLS LAST, label`
),
postgresClient.query<StatusRow>(
`SELECT value, label FROM statuses
WHERE is_active = true AND is_deleted = false
ORDER BY sort_order NULLS LAST, label`
),
postgresClient.query<PriorityRow>(
`SELECT value, label FROM priorities
WHERE is_active = true AND is_deleted = false
ORDER BY value`
),
postgresClient.query<ResourceRow>(
`SELECT r.id::text AS id,
trim(coalesce(r.first_name,'') || ' ' || coalesce(r.last_name,'')) AS full_name
FROM resources r
WHERE r.is_active = true
AND r.is_deleted = false
AND EXISTS (
SELECT 1 FROM tickets t
WHERE t.assigned_resource_id = r.id AND t.is_deleted = false
)
ORDER BY 2`
),
]);
return NextResponse.json({
companies: companies.rows.map((r) => ({
id: r.id,
name: r.company_name,
})),
companies: companies.rows.map((r) => ({ id: r.id, name: r.company_name })),
issueTypes: issueTypes.rows,
queues: queues.rows,
statuses: statuses.rows,
priorities: priorities.rows,
resources: resources.rows.map((r) => ({ id: r.id, name: r.full_name })),
});
}

View file

@ -1,177 +0,0 @@
/**
* GET /api/analyzer/tickets/list
*
* Browse view backing the /analyzer/tickets page. Filters tickets by
* `last_activity_date` (the most useful axis for "what's worth analyzing
* right now") plus optional company / issue type / free-text search.
*
* Query params:
* period one of today | yesterday | this_week | last_week | last_30d | last_60d | all
* companyId numeric companies.id, optional
* issueType numeric issue_types.value, optional
* search substring match against ticket_number or title
* limit default 50, capped at 200
* offset default 0
*
* Returns:
* { tickets: TicketRow[], total: number }
*
* Each row carries `latestAnalysisId` if the ticket already has a complete
* analysis, so the UI can offer "View analysis" alongside "Analyze".
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
type Period =
| 'today'
| 'yesterday'
| 'this_week'
| 'last_week'
| 'last_30d'
| 'last_60d'
| 'all';
const ALLOWED_PERIODS: ReadonlySet<Period> = new Set([
'today',
'yesterday',
'this_week',
'last_week',
'last_30d',
'last_60d',
'all',
]);
/**
* Returns the SQL fragment for the date predicate. Uses Postgres-side NOW()
* so "today" reflects the database server's clock this is an internal tool
* and the DB and app process share the same clock.
*
* Returns the predicate string with no parameters these date expressions
* are constants from the API perspective, computed in Postgres.
*/
function periodPredicate(period: Period): string {
switch (period) {
case 'today':
return `t.last_activity_date >= date_trunc('day', NOW())`;
case 'yesterday':
return `t.last_activity_date >= date_trunc('day', NOW()) - INTERVAL '1 day'
AND t.last_activity_date < date_trunc('day', NOW())`;
case 'this_week':
return `t.last_activity_date >= date_trunc('week', NOW())`;
case 'last_week':
return `t.last_activity_date >= date_trunc('week', NOW()) - INTERVAL '1 week'
AND t.last_activity_date < date_trunc('week', NOW())`;
case 'last_30d':
return `t.last_activity_date >= NOW() - INTERVAL '30 days'`;
case 'last_60d':
return `t.last_activity_date >= NOW() - INTERVAL '60 days'`;
case 'all':
return `TRUE`;
}
}
interface TicketRow {
ticket_number: string;
title: string | null;
company_name: string | null;
issue_type_label: string | null;
status_label: string | null;
priority_label: string | null;
last_activity_date: Date | null;
create_date: Date | null;
latest_analysis_id: string | null;
latest_analysis_version: number | null;
total_count: string;
}
export async function GET(request: NextRequest) {
const { error } = await requireAuth();
if (error) return error;
const url = new URL(request.url);
const periodParam = (url.searchParams.get('period') ?? 'last_30d') as Period;
const period: Period = ALLOWED_PERIODS.has(periodParam) ? periodParam : 'last_30d';
const companyIdRaw = url.searchParams.get('companyId');
const companyId = companyIdRaw ? Number(companyIdRaw) : null;
const issueTypeRaw = url.searchParams.get('issueType');
const issueType = issueTypeRaw ? Number(issueTypeRaw) : null;
const search = (url.searchParams.get('search') ?? '').trim() || null;
const limit = Math.min(Number(url.searchParams.get('limit') ?? 50) || 50, 200);
const offset = Math.max(Number(url.searchParams.get('offset') ?? 0) || 0, 0);
const sql = `
WITH filtered AS (
SELECT t.id, t.ticket_number, t.title,
t.company_id, t.issue_type, t.status, t.priority,
t.last_activity_date, t.create_date
FROM tickets t
WHERE t.is_deleted = false
AND ${periodPredicate(period)}
AND ($1::bigint IS NULL OR t.company_id = $1::bigint)
AND ($2::int IS NULL OR t.issue_type = $2::int)
AND ($3::text IS NULL OR (
t.ticket_number ILIKE '%' || $3::text || '%'
OR t.title ILIKE '%' || $3::text || '%'
))
)
SELECT f.ticket_number,
f.title,
c.company_name,
it.label AS issue_type_label,
s.label AS status_label,
pr.label AS priority_label,
f.last_activity_date,
f.create_date,
latest.id::text AS latest_analysis_id,
latest.analysis_version AS latest_analysis_version,
COUNT(*) OVER () AS total_count
FROM filtered f
LEFT JOIN companies c ON c.id = f.company_id
LEFT JOIN issue_types it ON it.value = f.issue_type
LEFT JOIN statuses s ON s.value = f.status
LEFT JOIN priorities pr ON pr.value = f.priority
LEFT JOIN LATERAL (
SELECT aa.id, aa.analysis_version
FROM analyzer_analyses aa
WHERE aa.ticket_number = f.ticket_number
AND aa.status = 'complete'
ORDER BY aa.analysis_version DESC
LIMIT 1
) latest ON TRUE
ORDER BY f.last_activity_date DESC NULLS LAST
LIMIT $4 OFFSET $5
`;
const res = await postgresClient.query<TicketRow>(sql, [
companyId,
issueType,
search,
limit,
offset,
]);
const total = res.rows.length > 0 ? Number(res.rows[0].total_count) : 0;
return NextResponse.json({
period,
total,
limit,
offset,
tickets: res.rows.map((r) => ({
ticketNumber: r.ticket_number,
title: r.title,
companyName: r.company_name,
issueTypeLabel: r.issue_type_label,
statusLabel: r.status_label,
priorityLabel: r.priority_label,
lastActivityDate: r.last_activity_date
? r.last_activity_date.toISOString()
: null,
createDate: r.create_date ? r.create_date.toISOString() : null,
latestAnalysisId: r.latest_analysis_id,
latestAnalysisVersion: r.latest_analysis_version,
})),
});
}

View file

@ -0,0 +1,397 @@
/**
* GET /api/analyzer/tickets
*
* Browse view backing /analyzer/tickets. Filters tickets by activity window
* + multi-axis filter set. Joins to analyzer_analyses to surface analyzed
* state per ticket.
*
* Phase 2 staleness heuristic: a ticket is "stale" when
* tickets.last_activity_date > latest_analysis.completed_at
* The spec calls for content-hash-based staleness; that requires either
* caching the current hash on the tickets row or computing on read for the
* visible page. For Phase 2 V1 we use the date heuristic see
* docs/ticket-analyzer-phase2-spec.md C.1 ("compute on-read for now and
* discuss caching strategy after we see real load") and the build notes.
*
* Query params:
* period today|yesterday|this_week|last_week|last_30d|last_60d|custom|all
* startDate ISO date, only when period=custom
* endDate ISO date, only when period=custom (inclusive)
* clientId comma-separated companies.id values
* issueType comma-separated issue_types.value values
* queue comma-separated queues.value values
* status comma-separated statuses.value values
* priority comma-separated priorities.value values
* assignedTo comma-separated resources.id values
* analyzed any|yes|no|stale (default: any)
* needsReview true|false (default: any)
* sort created_desc|created_asc|last_activity_desc|last_activity_asc|priority
* search substring match against ticket_number or title
* limit default 50, max 200
* offset default 0
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
type Period =
| 'today'
| 'yesterday'
| 'this_week'
| 'last_week'
| 'last_30d'
| 'last_60d'
| 'custom'
| 'all';
const ALLOWED_PERIODS: ReadonlySet<Period> = new Set([
'today',
'yesterday',
'this_week',
'last_week',
'last_30d',
'last_60d',
'custom',
'all',
]);
type AnalyzedFilter = 'any' | 'yes' | 'no' | 'stale';
const ALLOWED_ANALYZED: ReadonlySet<AnalyzedFilter> = new Set([
'any',
'yes',
'no',
'stale',
]);
type SortKey =
| 'created_desc'
| 'created_asc'
| 'last_activity_desc'
| 'last_activity_asc'
| 'priority';
const ALLOWED_SORT: ReadonlySet<SortKey> = new Set([
'created_desc',
'created_asc',
'last_activity_desc',
'last_activity_asc',
'priority',
]);
function parseCsv(raw: string | null): number[] | null {
if (!raw) return null;
const parts = raw
.split(',')
.map((s) => Number(s.trim()))
.filter((n) => Number.isFinite(n));
return parts.length > 0 ? parts : null;
}
/** SQL fragment for the date predicate (no params — date math is in Postgres). */
function periodPredicate(
period: Period,
startDate: string | null,
endDate: string | null
): { sql: string; params: unknown[] } {
switch (period) {
case 'today':
return { sql: `t.last_activity_date >= date_trunc('day', NOW())`, params: [] };
case 'yesterday':
return {
sql: `t.last_activity_date >= date_trunc('day', NOW()) - INTERVAL '1 day'
AND t.last_activity_date < date_trunc('day', NOW())`,
params: [],
};
case 'this_week':
return { sql: `t.last_activity_date >= date_trunc('week', NOW())`, params: [] };
case 'last_week':
return {
sql: `t.last_activity_date >= date_trunc('week', NOW()) - INTERVAL '1 week'
AND t.last_activity_date < date_trunc('week', NOW())`,
params: [],
};
case 'last_30d':
return { sql: `t.last_activity_date >= NOW() - INTERVAL '30 days'`, params: [] };
case 'last_60d':
return { sql: `t.last_activity_date >= NOW() - INTERVAL '60 days'`, params: [] };
case 'custom':
// Both dates required; if missing fall through to "all".
if (!startDate || !endDate) return { sql: `TRUE`, params: [] };
return {
sql: `t.last_activity_date >= $__START__ AND t.last_activity_date < ($__END__::timestamptz + INTERVAL '1 day')`,
params: [startDate, endDate],
};
case 'all':
return { sql: `TRUE`, params: [] };
}
}
function sortClause(sort: SortKey): string {
switch (sort) {
case 'created_desc':
return `f.create_date DESC NULLS LAST`;
case 'created_asc':
return `f.create_date ASC NULLS LAST`;
case 'last_activity_desc':
return `f.last_activity_date DESC NULLS LAST`;
case 'last_activity_asc':
return `f.last_activity_date ASC NULLS LAST`;
case 'priority':
// Lower priority value = higher importance in Autotask.
return `f.priority ASC NULLS LAST, f.last_activity_date DESC NULLS LAST`;
}
}
interface TicketRow {
ticket_number: string;
autotask_ticket_id: string;
title: string | null;
client_name: string | null;
client_id: string | null;
status_label: string | null;
priority_label: string | null;
queue_label: string | null;
issue_type_label: string | null;
sub_issue_type_label: string | null;
assigned_resource_name: string | null;
create_date: Date | null;
last_activity_date: Date | null;
age_in_days: number | null;
latest_analysis_id: string | null;
latest_analysis_at: Date | null;
latest_completed_at: Date | null;
needs_human_review: boolean | null;
confidence_score: string | null;
primary_category: string | null;
total_count: string;
}
export async function GET(request: NextRequest) {
const { error } = await requireAuth();
if (error) return error;
const url = new URL(request.url);
const periodParam = (url.searchParams.get('period') ?? 'last_30d') as Period;
const period: Period = ALLOWED_PERIODS.has(periodParam) ? periodParam : 'last_30d';
const startDate = url.searchParams.get('startDate');
const endDate = url.searchParams.get('endDate');
const clientIds = parseCsv(url.searchParams.get('clientId'));
const issueTypes = parseCsv(url.searchParams.get('issueType'));
const queues = parseCsv(url.searchParams.get('queue'));
const statuses = parseCsv(url.searchParams.get('status'));
const priorities = parseCsv(url.searchParams.get('priority'));
const assignedTo = parseCsv(url.searchParams.get('assignedTo'));
const analyzedRaw = (url.searchParams.get('analyzed') ?? 'any') as AnalyzedFilter;
const analyzed: AnalyzedFilter = ALLOWED_ANALYZED.has(analyzedRaw) ? analyzedRaw : 'any';
const needsReviewRaw = url.searchParams.get('needsReview');
const needsReview =
needsReviewRaw === 'true' ? true : needsReviewRaw === 'false' ? false : null;
const sortRaw = (url.searchParams.get('sort') ?? 'last_activity_desc') as SortKey;
const sort: SortKey = ALLOWED_SORT.has(sortRaw) ? sortRaw : 'last_activity_desc';
const search = (url.searchParams.get('search') ?? '').trim() || null;
const limit = Math.min(Number(url.searchParams.get('limit') ?? 50) || 50, 200);
const offset = Math.max(Number(url.searchParams.get('offset') ?? 0) || 0, 0);
// Build the parameter list and SQL fragment incrementally so each filter is
// optional. Using $N indexed params; period predicate is an SQL fragment.
const params: unknown[] = [];
const where: string[] = ['t.is_deleted = false'];
const periodFragment = periodPredicate(period, startDate, endDate);
if (periodFragment.params.length > 0) {
params.push(...periodFragment.params);
let frag = periodFragment.sql;
frag = frag.replace('$__START__', `$${params.length - 1}::timestamptz`);
frag = frag.replace('$__END__', `$${params.length}::timestamptz`);
where.push(frag);
} else {
where.push(periodFragment.sql);
}
if (clientIds) {
params.push(clientIds);
where.push(`t.company_id = ANY($${params.length}::bigint[])`);
}
if (issueTypes) {
params.push(issueTypes);
where.push(`t.issue_type = ANY($${params.length}::int[])`);
}
if (queues) {
params.push(queues);
where.push(`t.queue_id = ANY($${params.length}::int[])`);
}
if (statuses) {
params.push(statuses);
where.push(`t.status = ANY($${params.length}::int[])`);
}
if (priorities) {
params.push(priorities);
where.push(`t.priority = ANY($${params.length}::int[])`);
}
if (assignedTo) {
params.push(assignedTo);
where.push(`t.assigned_resource_id = ANY($${params.length}::bigint[])`);
}
if (search) {
params.push(search);
where.push(
`(t.ticket_number ILIKE '%' || $${params.length} || '%' OR t.title ILIKE '%' || $${params.length} || '%')`
);
}
const analyzedHavingParts: string[] = [];
if (analyzed === 'yes') {
analyzedHavingParts.push(`latest.id IS NOT NULL`);
} else if (analyzed === 'no') {
analyzedHavingParts.push(`latest.id IS NULL`);
} else if (analyzed === 'stale') {
analyzedHavingParts.push(
`latest.id IS NOT NULL AND f.last_activity_date > latest.completed_at`
);
}
if (needsReview === true) {
analyzedHavingParts.push(`latest.needs_human_review = true`);
} else if (needsReview === false) {
analyzedHavingParts.push(
`(latest.needs_human_review IS DISTINCT FROM true)`
);
}
const havingFragment =
analyzedHavingParts.length > 0
? `WHERE ${analyzedHavingParts.join(' AND ')}`
: '';
params.push(limit);
const limitParamIdx = params.length;
params.push(offset);
const offsetParamIdx = params.length;
const sql = `
WITH filtered AS (
SELECT t.id, t.ticket_number, t.title,
t.company_id, t.issue_type, t.sub_issue_type,
t.status, t.priority, t.queue_id,
t.assigned_resource_id,
t.create_date, t.last_activity_date
FROM tickets t
WHERE ${where.join(' AND ')}
)
SELECT f.ticket_number,
f.id::text AS autotask_ticket_id,
f.title,
c.company_name AS client_name,
c.id::text AS client_id,
s.label AS status_label,
pr.label AS priority_label,
q.label AS queue_label,
it.label AS issue_type_label,
sit.label AS sub_issue_type_label,
CASE WHEN r.id IS NOT NULL
THEN trim(coalesce(r.first_name,'') || ' ' || coalesce(r.last_name,''))
ELSE NULL
END AS assigned_resource_name,
f.create_date,
f.last_activity_date,
CASE WHEN f.create_date IS NULL THEN NULL
ELSE EXTRACT(DAY FROM NOW() - f.create_date)::int
END AS age_in_days,
latest.id::text AS latest_analysis_id,
latest.triggered_at AS latest_analysis_at,
latest.completed_at AS latest_completed_at,
latest.needs_human_review,
latest.confidence_score::text AS confidence_score,
(latest.aggregate_fingerprint ->> 'category') AS primary_category,
COUNT(*) OVER () AS total_count
FROM filtered f
LEFT JOIN companies c ON c.id = f.company_id
LEFT JOIN issue_types it ON it.value = f.issue_type
LEFT JOIN issue_types sit ON sit.value = f.sub_issue_type
LEFT JOIN statuses s ON s.value = f.status
LEFT JOIN priorities pr ON pr.value = f.priority
LEFT JOIN queues q ON q.value = f.queue_id
LEFT JOIN resources r ON r.id = f.assigned_resource_id
LEFT JOIN LATERAL (
SELECT aa.id, aa.triggered_at, aa.completed_at,
aa.needs_human_review, aa.confidence_score,
aa.aggregate_fingerprint, aa.analysis_version
FROM analyzer_analyses aa
WHERE aa.ticket_number = f.ticket_number
AND aa.status = 'complete'
ORDER BY aa.analysis_version DESC
LIMIT 1
) latest ON TRUE
${havingFragment}
ORDER BY ${sortClause(sort)}
LIMIT $${limitParamIdx} OFFSET $${offsetParamIdx}
`;
const res = await postgresClient.query<TicketRow>(sql, params);
const total = res.rows.length > 0 ? Number(res.rows[0].total_count) : 0;
const tickets = res.rows.map((r) => {
let analyzedState: 'none' | 'current' | 'stale' = 'none';
if (r.latest_analysis_id) {
if (
r.last_activity_date &&
r.latest_completed_at &&
r.last_activity_date.getTime() > r.latest_completed_at.getTime()
) {
analyzedState = 'stale';
} else {
analyzedState = 'current';
}
}
return {
ticketNumber: r.ticket_number,
autotaskTicketId: Number(r.autotask_ticket_id),
title: r.title,
clientName: r.client_name,
clientId: r.client_id ? Number(r.client_id) : null,
status: r.status_label,
priority: r.priority_label,
queue: r.queue_label,
issueType: r.issue_type_label,
subIssueType: r.sub_issue_type_label,
assignedResourceName: r.assigned_resource_name,
createdAtAutotask: r.create_date ? r.create_date.toISOString() : null,
lastActivityAtAutotask: r.last_activity_date
? r.last_activity_date.toISOString()
: null,
ageInDays: r.age_in_days,
analyzedState,
latestAnalysisId: r.latest_analysis_id,
latestAnalysisAt: r.latest_analysis_at
? r.latest_analysis_at.toISOString()
: null,
needsHumanReview: r.needs_human_review ?? false,
confidenceScore: r.confidence_score === null ? null : Number(r.confidence_score),
primaryCategory: r.primary_category,
};
});
return NextResponse.json({
tickets,
total,
filters: {
period,
startDate,
endDate,
clientIds,
issueTypes,
queues,
statuses,
priorities,
assignedTo,
analyzed,
needsReview,
sort,
search,
limit,
offset,
},
});
}

View file

@ -1,5 +1,6 @@
@import "tailwindcss";
@import "tw-animate-css";
@plugin "@tailwindcss/typography";
@custom-variant dark (&:is(.dark *));