feat(phase-b): ship analytics dashboard, alerts, scanner PWA, dedup, audit view

Phase B (Insights & Alerts) PR4-11 in one drop. Builds on the schema +
service skeletons committed in PRs 1-3.

PR4  Analytics dashboard — 4 chart types (funnel/timeline/breakdown/source),
     date-range picker (today/7d/30d/90d), CSV+PNG export per card.
PR5  Alert rail UI + /alerts page — topbar bell w/ live count, dashboard
     right-rail, three-tab page (active/dismissed/resolved), socket-driven
     invalidation. Bell lazy-loads list on popover open to keep cold pages
     fast in non-dashboard routes.
PR6  EOI queue tab on documents hub — filters to in-flight EOIs, count
     surfaces in tab label.
PR7  Interests-by-berth tab on berth detail — replaces the stub.
PR8  Expense duplicate detection — BullMQ job runs scan on create, yellow
     banner on detail w/ Merge / Not-a-duplicate, transactional merge
     consolidates receipts and archives the source.
PR9  Receipt scanner PWA + multi-provider AI — port-scoped /scan route in
     its own (scanner) group with no dashboard chrome, dynamic per-port
     manifest, OpenAI + Claude provider abstraction, admin OCR settings
     page (port-level + super-admin global default w/ opt-in fallback),
     test-connection endpoint, manual-entry fallback when no key is
     configured. Verify form always shown before save — no ghost rows.
PR10 Audit log read view — swap to tsvector full-text search on the
     existing GIN index, cursor pagination, filters for entity/action/user
     /date range, batched actor-email resolution.
PR11 Real-API tests — opt-in receipt-ocr.spec (admin save+test, optional
     real-receipt parse via REALAPI_RECEIPT_FIXTURE) and alert-engine
     socket-fanout spec gated behind RUN_ALERT_ENGINE_REALAPI. Both skip
     cleanly without their gate envs so CI stays green.

Test totals: vitest 690 -> 713, smoke 130 -> 138, realapi +2 opt-in.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-04-28 17:21:55 +02:00
parent 2fa70f4582
commit f52d21df83
63 changed files with 4459 additions and 206 deletions

View File

@@ -29,6 +29,9 @@ export interface ExpenseRow {
receiptFileIds: string[] | null;
archivedAt: string | null;
createdAt: string;
/** Set by the dedup engine when this expense looks like a duplicate of another. */
duplicateOf: string | null;
dedupScannedAt: string | null;
}
const PAYMENT_STATUS_COLORS: Record<string, string> = {
@@ -94,7 +97,8 @@ export function getExpenseColumns({
cell: ({ row }) =>
row.original.amountUsd ? (
<span className="text-sm text-muted-foreground tabular-nums">
${Number(row.original.amountUsd).toLocaleString('en-US', {
$
{Number(row.original.amountUsd).toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}
@@ -125,10 +129,7 @@ export function getExpenseColumns({
const status = (getValue() as string | null) ?? 'unpaid';
const colorClass = PAYMENT_STATUS_COLORS[status] ?? '';
return (
<Badge
variant="outline"
className={`capitalize text-xs border ${colorClass}`}
>
<Badge variant="outline" className={`capitalize text-xs border ${colorClass}`}>
{status}
</Badge>
);
@@ -162,10 +163,7 @@ export function getExpenseColumns({
<Pencil className="mr-2 h-3.5 w-3.5" />
Edit
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive"
onClick={() => onArchive(row.original)}
>
<DropdownMenuItem className="text-destructive" onClick={() => onArchive(row.original)}>
<Archive className="mr-2 h-3.5 w-3.5" />
Archive
</DropdownMenuItem>

View File

@@ -11,6 +11,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ArchiveConfirmDialog } from '@/components/shared/archive-confirm-dialog';
import { apiFetch } from '@/lib/api/client';
import type { ExpenseRow } from './expense-columns';
import { ExpenseDuplicateBanner } from './expense-duplicate-banner';
const PAYMENT_STATUS_COLORS: Record<string, string> = {
unpaid: 'bg-red-100 text-red-700 border-red-200',
@@ -52,9 +53,7 @@ export function ExpenseDetail({ expenseId, onEdit, onArchived }: ExpenseDetailPr
if (error || !data?.data) {
return (
<div className="p-6 text-center text-muted-foreground">
Failed to load expense details.
</div>
<div className="p-6 text-center text-muted-foreground">Failed to load expense details.</div>
);
}
@@ -64,6 +63,7 @@ export function ExpenseDetail({ expenseId, onEdit, onArchived }: ExpenseDetailPr
return (
<div className="space-y-6">
<ExpenseDuplicateBanner expense={expense} />
<div className="flex items-center justify-between">
<div>
<h2 className="text-xl font-semibold">
@@ -107,10 +107,12 @@ export function ExpenseDetail({ expenseId, onEdit, onArchived }: ExpenseDetailPr
</p>
{expense.amountUsd && expense.currency !== 'USD' && (
<p className="text-sm text-muted-foreground mt-1">
${Number(expense.amountUsd).toLocaleString('en-US', {
$
{Number(expense.amountUsd).toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})} USD
})}{' '}
USD
</p>
)}
</CardContent>
@@ -121,10 +123,7 @@ export function ExpenseDetail({ expenseId, onEdit, onArchived }: ExpenseDetailPr
<CardTitle className="text-sm font-medium">Payment Status</CardTitle>
</CardHeader>
<CardContent>
<Badge
variant="outline"
className={`capitalize text-sm border ${statusColor}`}
>
<Badge variant="outline" className={`capitalize text-sm border ${statusColor}`}>
{status}
</Badge>
</CardContent>
@@ -138,15 +137,11 @@ export function ExpenseDetail({ expenseId, onEdit, onArchived }: ExpenseDetailPr
<CardContent className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-muted-foreground">Category</span>
<p className="mt-0.5 capitalize">
{expense.category?.replace(/_/g, ' ') ?? '—'}
</p>
<p className="mt-0.5 capitalize">{expense.category?.replace(/_/g, ' ') ?? '—'}</p>
</div>
<div>
<span className="text-muted-foreground">Payment Method</span>
<p className="mt-0.5 capitalize">
{expense.paymentMethod?.replace(/_/g, ' ') ?? '—'}
</p>
<p className="mt-0.5 capitalize">{expense.paymentMethod?.replace(/_/g, ' ') ?? '—'}</p>
</div>
<div>
<span className="text-muted-foreground">Payer</span>

View File

@@ -0,0 +1,121 @@
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { AlertTriangle, ExternalLink } from 'lucide-react';
import { format } from 'date-fns';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';
import type { ExpenseRow } from './expense-columns';
interface Props {
expense: ExpenseRow;
}
export function ExpenseDuplicateBanner({ expense }: Props) {
const params = useParams<{ portSlug: string }>();
const portSlug = params?.portSlug ?? '';
const queryClient = useQueryClient();
const [resolving, setResolving] = useState(false);
// Fetch the candidate expense for context.
const { data: candidateResp } = useQuery<{ data: ExpenseRow }>({
queryKey: ['expenses', expense.duplicateOf],
queryFn: () => apiFetch(`/api/v1/expenses/${expense.duplicateOf}`),
enabled: Boolean(expense.duplicateOf),
staleTime: 30_000,
});
const candidate = candidateResp?.data;
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: ['expenses'] });
};
const merge = useMutation({
mutationFn: () =>
apiFetch(`/api/v1/expenses/${expense.id}/merge`, {
method: 'POST',
body: { targetId: expense.duplicateOf },
}),
onSuccess: () => {
invalidate();
setResolving(false);
},
});
const clear = useMutation({
mutationFn: () =>
apiFetch(`/api/v1/expenses/${expense.id}/clear-duplicate`, { method: 'POST' }),
onSuccess: () => {
invalidate();
setResolving(false);
},
});
if (!expense.duplicateOf) return null;
const candidateLabel = candidate
? `${candidate.establishmentName ?? 'Unnamed expense'} · ${
candidate.amount
} ${candidate.currency} · ${format(new Date(candidate.expenseDate), 'd MMM yyyy')}`
: 'a previously recorded expense';
return (
<div
data-testid="expense-duplicate-banner"
className={cn(
'flex flex-col gap-2 rounded-lg border border-amber-300 bg-amber-50 px-4 py-3 text-sm text-amber-900',
'sm:flex-row sm:items-center sm:justify-between',
)}
>
<div className="flex min-w-0 items-start gap-2">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
<div className="min-w-0">
<p className="font-medium">Looks like a duplicate</p>
<p className="mt-0.5 text-xs text-amber-800">
This expense matches{' '}
<Link
href={`/${portSlug}/expenses/${expense.duplicateOf}` as never}
className="inline-flex items-center gap-1 font-medium underline-offset-2 hover:underline"
>
{candidateLabel}
<ExternalLink className="h-3 w-3" aria-hidden />
</Link>
. Merge to consolidate, or mark as not a duplicate to keep them separate.
</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<Button
variant="outline"
size="sm"
className="border-amber-400 bg-white"
disabled={resolving || merge.isPending || clear.isPending}
onClick={() => {
setResolving(true);
merge.mutate();
}}
data-testid="expense-merge-btn"
>
Merge them
</Button>
<Button
variant="ghost"
size="sm"
disabled={resolving || merge.isPending || clear.isPending}
onClick={() => {
setResolving(true);
clear.mutate();
}}
data-testid="expense-not-duplicate-btn"
>
Not a duplicate
</Button>
</div>
</div>
);
}