Files
impuestospy/apps/web/app/[locale]/(app)/bandeja/bandeja.tsx
T
MichilisandClaude Opus 5 b074456b70 phase-3: ingestion, from a QR in the camera to a card in the bandeja
The whole pipeline: storage behind one driver interface (local disk and S3),
a portable job queue with a poller, QR and CDC parsing, OCR through the
Anthropic API, dedupe, manual entry, and the bandeja that turns all of it into
one decision per card.

Scanning tries the trustworthy door first: a QR is parsed and prefilled from
its CDC; a photo without one is queued for OCR when a key is configured and
otherwise opens the manual form against the stored file. A QR that will not
parse records an ingest error and falls through rather than losing the photo.

Job claiming is the only dialect divergence, as SPEC allows: FOR UPDATE SKIP
LOCKED on Postgres, a conditional UPDATE against SQLite's single writer. Retry
backoff follows SPEC exactly and a job abandoned by a killed process returns to
the queue once its lock goes stale, which is the phase 3 acceptance case.

OCR uses structured outputs rather than parsing prose, so the model cannot
return anything but the RULES.md schema, and every field is nullable because
unreadable is a real answer.

Web: scan with live QR decoding (BarcodeDetector, ZXing fallback, wasm served
from our own origin), manual entry with the IVA split worked out from the
total, the bandeja with swipe, buttons and keyboard all doing the same thing,
and the documents list and detail with an editable classification.

The seed now carries Maria's 34 purchases and 8 sales and Carlos's 6, all
classified through the real rules, plus the two open ingest errors.

Two defects found and fixed with tests: seeded documents could be dated in the
future, which would corrupt any projection computed from them, and the category
buttons announced their keyboard shortcut as part of their name.

255 vitest tests, 37 Playwright tests, rules coverage still 100%, typecheck and
lint clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 02:20:31 +00:00

267 lines
9.2 KiB
TypeScript

'use client';
import type { IrpCategory } from '@impuestos/contracts';
import { formatDateLong, formatGs, type Locale } from '@impuestos/i18n';
import { IRP_CATEGORIES } from '@impuestos/rules';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Check, X } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { CategoryPicker } from '@/components/category-picker';
import { Button, buttonClasses } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { EmptyState } from '@/components/ui/empty-state';
import { Skeleton } from '@/components/ui/skeleton';
import { Link } from '@/i18n/navigation';
import { useT } from '@/i18n/t';
import { api } from '@/lib/api';
import { cn } from '@/lib/utils';
/** Past this many pixels, letting go commits the swipe. */
const COMMIT_PX = 96;
/**
* Flow B4. A stack of documents waiting for a yes. Every gesture has a button and a key,
* because a swipe is unusable with a keyboard and invisible to a screen reader.
*/
export function Bandeja({ locale }: { locale: string }) {
const t = useT();
const queryClient = useQueryClient();
const [index, setIndex] = useState(0);
const [picking, setPicking] = useState(false);
const [drag, setDrag] = useState(0);
const [dragging, setDragging] = useState(false);
const dragStart = useRef<number | null>(null);
const pending = useQuery({
queryKey: ['documents', { status: 'needs_review' }],
queryFn: ({ signal }) => api.listDocuments({ status: 'needs_review' }, signal),
});
const documents = pending.data?.items ?? [];
// Confirming the last card shortens the list under us. Clamping here rather than in an
// effect keeps the render consistent and avoids a cascading update.
const safeIndex = Math.min(index, Math.max(0, documents.length - 1));
const current = documents[safeIndex];
const invalidate = useCallback(
() => queryClient.invalidateQueries({ queryKey: ['documents'] }),
[queryClient],
);
const confirm = useMutation({
mutationFn: (id: string) => api.confirmDocument(id),
onSuccess: async () => {
setDrag(0);
await invalidate();
},
});
const reject = useMutation({
mutationFn: (args: { id: string; reason: 'not_mine' | 'duplicate' | 'other' }) =>
api.rejectDocument(args.id, { reason: args.reason }),
onSuccess: async () => {
setDrag(0);
await invalidate();
},
});
const reclassify = useMutation({
mutationFn: (args: { id: string; irpCategory: IrpCategory | 'none' }) =>
api.patchClassification(args.id, { irpCategory: args.irpCategory }),
onSuccess: async () => {
setPicking(false);
await invalidate();
},
});
// Desktop keyboard mirrors of every gesture (FLOWS.md B4).
useEffect(() => {
function onKey(event: KeyboardEvent) {
if (!current || picking) return;
if (event.key === 'j') setIndex(Math.min(safeIndex + 1, documents.length - 1));
else if (event.key === 'k') setIndex(Math.max(safeIndex - 1, 0));
else if (event.key === 'Enter') confirm.mutate(current.id);
else if (event.key === 'x' || event.key === 'X') reject.mutate({ id: current.id, reason: 'other' });
else if (/^[1-8]$/.test(event.key)) {
const category = IRP_CATEGORIES[Number(event.key) - 1];
if (category) reclassify.mutate({ id: current.id, irpCategory: category });
} else return;
event.preventDefault();
}
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [current, documents.length, safeIndex, picking, confirm, reject, reclassify]);
if (pending.isPending) {
return (
<div className="space-y-4 py-4">
<Card>
<Skeleton name="bandeja-card" />
</Card>
<Card>
<Skeleton name="bandeja-card" />
</Card>
</div>
);
}
if (pending.isError) {
return (
<Card className="my-4 space-y-3">
<p role="alert" className="text-sm">
{t('common.error.generic')}
</p>
<Button type="button" onClick={() => void pending.refetch()}>
{t('common.retry')}
</Button>
</Card>
);
}
if (!current) {
return (
<div className="py-4">
<Card>
<EmptyState
icon={<Check aria-hidden className="size-8" />}
title={t('bandeja.empty')}
body={t('bandeja.emptyBody')}
action={
<Link href="/escanear" className={buttonClasses({ size: 'lg' })}>
{t('scan.fab')}
</Link>
}
/>
</Card>
</div>
);
}
const category = current.classification?.irpCategory ?? 'none';
const highConfidence = (current.classification?.confidence ?? 0) >= 0.8;
return (
<div className="space-y-4 py-4">
<div className="flex items-baseline justify-between">
<h1 className="text-2xl font-semibold tracking-tight">{t('bandeja.title')}</h1>
<span className="text-sm text-[var(--text-muted)]">
{t('bandeja.count', { count: documents.length })}
</span>
</div>
<Card
data-testid="bandeja-card"
className="touch-pan-y space-y-4 select-none"
style={{
transform: `translateX(${drag}px) rotate(${drag / 40}deg)`,
transition: dragging ? 'none' : 'transform 200ms ease-out',
}}
onPointerDown={(event) => {
dragStart.current = event.clientX;
setDragging(true);
event.currentTarget.setPointerCapture(event.pointerId);
}}
onPointerMove={(event) => {
if (dragStart.current === null) return;
setDrag(event.clientX - dragStart.current);
}}
onPointerUp={() => {
const offset = drag;
dragStart.current = null;
setDragging(false);
if (offset > COMMIT_PX) confirm.mutate(current.id);
else if (offset < -COMMIT_PX) {
setPicking(true);
setDrag(0);
} else setDrag(0);
}}
>
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<p className="truncate text-lg font-medium">{current.emitterName}</p>
<p className="text-sm text-[var(--text-muted)]">
{formatDateLong(locale as Locale, current.issueDate)}
</p>
</div>
<span
className={cn(
'shrink-0 rounded-full px-2.5 py-0.5 text-xs font-medium',
highConfidence ? 'bg-positive-soft text-positive' : 'bg-attention-soft text-attention',
)}
>
{highConfidence ? t('bandeja.confidence.high') : t('bandeja.confidence.low')}
</span>
</div>
<p className="tnum text-4xl font-semibold tracking-tight">{formatGs(current.total)}</p>
<p className="text-sm text-[var(--text-muted)]">
{t('scan.result.suggested', { category: t(`categories.${category}` as const) })}
</p>
{current.classification?.reasons.length ? (
<ul className="space-y-1 text-xs text-[var(--text-muted)]">
{current.classification.reasons.map((reason) => (
<li key={reason}>{t(`classification.reason.${reason}` as 'classification.reason.irp_no_category')}</li>
))}
</ul>
) : null}
</Card>
{picking ? (
<Card className="space-y-3">
<h2 className="font-medium">{t('scan.result.changeCat')}</h2>
<CategoryPicker
value={category}
onSelect={(next) => reclassify.mutate({ id: current.id, irpCategory: next })}
/>
<Button type="button" variant="ghost" block onClick={() => setPicking(false)}>
{t('common.cancel')}
</Button>
</Card>
) : (
/* Confirm leads and takes the full width: it is the action on almost every card,
and three buttons across a 390px screen wraps the longest label. */
<div className="space-y-2">
<Button
type="button"
size="lg"
block
disabled={confirm.isPending}
onClick={() => confirm.mutate(current.id)}
>
<Check aria-hidden className="size-4" />
{t('bandeja.confirm')}
</Button>
<div className="grid grid-cols-2 gap-2">
<Button
type="button"
variant="secondary"
disabled={reject.isPending}
onClick={() => reject.mutate({ id: current.id, reason: 'other' })}
>
<X aria-hidden className="size-4" />
{t('scan.result.discard')}
</Button>
<Button type="button" variant="secondary" onClick={() => setPicking(true)}>
{t('scan.result.changeCat')}
</Button>
</div>
</div>
)}
<div className="space-y-1 text-xs text-[var(--text-muted)]">
<p>{t('bandeja.swipeHint')}</p>
<p className="hidden sm:block">{t('bandeja.keyboardHint')}</p>
<p>
{t('bandeja.autoConfirmNote', { days: 7 })}{' '}
<Link href="/perfil" className="underline">
{t('bandeja.autoConfirmLink')}
</Link>
</p>
</div>
</div>
);
}