Files
pn-new-crm/src/components/admin/ocr-settings-form.tsx

291 lines
9.0 KiB
TypeScript
Raw Normal View History

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>
2026-04-28 17:21:55 +02:00
'use client';
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { CheckCircle2, Eye, EyeOff, Loader2, XCircle } from 'lucide-react';
import { PageHeader } from '@/components/shared/page-header';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { usePermissions } from '@/hooks/use-permissions';
import { apiFetch } from '@/lib/api/client';
type Provider = 'openai' | 'claude';
interface ConfigResp {
data: {
provider: Provider;
model: string;
hasApiKey: boolean;
useGlobal: boolean;
};
models: Record<Provider, string[]>;
}
type Scope = 'port' | 'global';
interface SettingsBlockProps {
scope: Scope;
title: string;
description: string;
/** Hide the "use global" checkbox on the global tab. */
showUseGlobal?: boolean;
}
function SettingsBlock({ scope, title, description, showUseGlobal }: SettingsBlockProps) {
const queryClient = useQueryClient();
const queryKey = ['ocr-settings', scope];
const { data, isLoading } = useQuery<ConfigResp>({
queryKey,
queryFn: () => apiFetch<ConfigResp>(`/api/v1/admin/ocr-settings?scope=${scope}`),
});
const [provider, setProvider] = useState<Provider>('openai');
const [model, setModel] = useState<string>('gpt-4o-mini');
const [apiKey, setApiKey] = useState('');
const [showKey, setShowKey] = useState(false);
const [useGlobal, setUseGlobal] = useState(false);
const [testStatus, setTestStatus] = useState<null | { ok: true } | { ok: false; reason: string }>(
null,
);
useEffect(() => {
if (!data?.data) return;
setProvider(data.data.provider);
setModel(data.data.model);
setUseGlobal(data.data.useGlobal);
}, [data?.data]);
const save = useMutation({
mutationFn: (clearApiKey?: boolean) =>
apiFetch('/api/v1/admin/ocr-settings', {
method: 'PUT',
body: {
scope,
provider,
model,
apiKey: apiKey.length > 0 ? apiKey : undefined,
clearApiKey: Boolean(clearApiKey),
useGlobal: scope === 'global' ? false : useGlobal,
},
}),
onSuccess: () => {
setApiKey('');
queryClient.invalidateQueries({ queryKey });
},
});
const test = useMutation({
mutationFn: () =>
apiFetch<{ ok: boolean; reason?: string }>(`/api/v1/admin/ocr-settings/test`, {
method: 'POST',
body: { provider, model, apiKey },
}),
onSuccess: (res) =>
setTestStatus(res.ok ? { ok: true } : { ok: false, reason: res.reason ?? 'Unknown' }),
onError: (err: unknown) =>
setTestStatus({
ok: false,
reason: err instanceof Error ? err.message : 'Network error',
}),
});
const models = data?.models[provider] ?? [];
const hasKey = data?.data.hasApiKey ?? false;
if (isLoading) {
return (
<Card>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>{title}</CardTitle>
<p className="text-sm text-muted-foreground">{description}</p>
</CardHeader>
<CardContent className="space-y-4">
{showUseGlobal ? (
<div className="flex items-start gap-2 rounded-lg border border-border bg-muted/30 p-3">
<Checkbox
id={`useGlobal-${scope}`}
checked={useGlobal}
onCheckedChange={(v) => setUseGlobal(v === true)}
/>
<div className="space-y-0.5">
<Label htmlFor={`useGlobal-${scope}`} className="text-sm font-medium">
Use the global API key for this port
</Label>
<p className="text-xs text-muted-foreground">
When enabled, this port falls back to the system-wide OCR settings. Per-port
provider/model/key are ignored.
</p>
</div>
</div>
) : null}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor={`provider-${scope}`}>Provider</Label>
<Select
value={provider}
onValueChange={(v) => {
const p = v as Provider;
setProvider(p);
setModel(data?.models[p][0] ?? '');
setTestStatus(null);
}}
>
<SelectTrigger id={`provider-${scope}`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="openai">OpenAI</SelectItem>
<SelectItem value="claude">Claude (Anthropic)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor={`model-${scope}`}>Model</Label>
<Select value={model} onValueChange={setModel}>
<SelectTrigger id={`model-${scope}`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{models.map((m) => (
<SelectItem key={m} value={m}>
{m}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor={`apiKey-${scope}`}>API key</Label>
<div className="flex gap-2">
<Input
id={`apiKey-${scope}`}
type={showKey ? 'text' : 'password'}
autoComplete="off"
placeholder={hasKey ? '•••••• (saved — leave blank to keep)' : 'sk-…'}
value={apiKey}
onChange={(e) => {
setApiKey(e.target.value);
setTestStatus(null);
}}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() => setShowKey((v) => !v)}
aria-label={showKey ? 'Hide key' : 'Show key'}
>
{showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
<p className="text-xs text-muted-foreground">
Stored encrypted at rest. Never re-displayed after saving.
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button
onClick={() => save.mutate(false)}
disabled={save.isPending}
data-testid={`save-${scope}`}
>
{save.isPending ? <Loader2 className="mr-1.5 h-3 w-3 animate-spin" /> : null}
Save settings
</Button>
<Button
type="button"
variant="outline"
onClick={() => test.mutate()}
disabled={test.isPending || apiKey.length === 0}
>
{test.isPending ? <Loader2 className="mr-1.5 h-3 w-3 animate-spin" /> : null}
Test connection
</Button>
{hasKey ? (
<Button
type="button"
variant="ghost"
onClick={() => save.mutate(true)}
disabled={save.isPending}
className="text-destructive"
>
Clear stored key
</Button>
) : null}
{testStatus?.ok ? (
<span className="inline-flex items-center gap-1 text-sm text-green-700">
<CheckCircle2 className="h-4 w-4" />
Connection OK
</span>
) : null}
{testStatus && !testStatus.ok ? (
<span className="inline-flex items-center gap-1 text-sm text-destructive">
<XCircle className="h-4 w-4" />
{testStatus.reason}
</span>
) : null}
</div>
</CardContent>
</Card>
);
}
export function OcrSettingsForm() {
const { isSuperAdmin } = usePermissions();
return (
<div className="space-y-6">
<PageHeader
title="Receipt OCR"
eyebrow="Admin"
description="Configure the AI provider used to read receipts captured via the mobile scanner."
variant="gradient"
/>
<SettingsBlock
scope="port"
title="This port"
description="Provider and key used when staff at this port scan a receipt."
showUseGlobal
/>
{isSuperAdmin ? (
<SettingsBlock
scope="global"
title="Global default"
description="Used by any port that opted into the global key. Super-admin only."
/>
) : null}
</div>
);
}