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>
This commit is contained in:
Michilis
2026-09-04 02:20:31 +00:00
co-authored by Claude Opus 5
parent 0d7651b17c
commit b074456b70
64 changed files with 5504 additions and 23 deletions
@@ -0,0 +1,164 @@
'use client';
import { isApiError, type IrpCategory } from '@impuestos/contracts';
import { formatDateLong, formatGs, type Locale } from '@impuestos/i18n';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { CategoryPicker } from '@/components/category-picker';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { StatusChip } from '@/components/ui/status-chip';
import { Switch } from '@/components/ui/switch';
import { useT } from '@/i18n/t';
import { api } from '@/lib/api';
/** Flow E1 detail: the data, the image, and the classification the user can override. */
export function DocumentDetail({ id, locale }: { id: string; locale: string }) {
const t = useT();
const queryClient = useQueryClient();
const [editing, setEditing] = useState(false);
const document = useQuery({
queryKey: ['documents', id],
queryFn: ({ signal }) => api.getDocument(id, signal),
retry: (count, error) => !isApiError(error) && count < 1,
});
const reclassify = useMutation({
mutationFn: (patch: { irpCategory?: IrpCategory | 'none'; ivaCreditEligible?: boolean }) =>
api.patchClassification(id, patch),
onSuccess: async () => {
setEditing(false);
await queryClient.invalidateQueries({ queryKey: ['documents'] });
},
});
if (document.isPending) {
return (
<Card className="my-4">
<Skeleton name="declaration-summary" />
</Card>
);
}
if (document.isError || !document.data) {
const missing = isApiError(document.error) && document.error.code === 'not_found';
return (
<Card className="my-4 space-y-3">
<p role="alert" className="text-sm">
{missing ? t('error.not_found') : t('common.error.generic')}
</p>
{!missing ? (
<Button type="button" onClick={() => void document.refetch()}>
{t('common.retry')}
</Button>
) : null}
</Card>
);
}
const doc = document.data;
const classification = doc.classification;
const category = classification?.irpCategory ?? 'none';
return (
<div className="space-y-4 py-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h1 className="truncate text-2xl font-semibold tracking-tight">{doc.emitterName}</h1>
<p className="text-sm text-[var(--text-muted)]">
{formatDateLong(locale as Locale, doc.issueDate)}
</p>
</div>
<StatusChip status={doc.status} label={t(`status.${doc.status}` as const)} />
</div>
<Card className="space-y-3">
<p className="tnum text-4xl font-semibold tracking-tight">{formatGs(doc.total)}</p>
<dl className="space-y-2 text-sm">
<Row label={t('manual.iva10')} value={formatGs(doc.iva10)} />
<Row label={t('manual.iva5')} value={formatGs(doc.iva5)} />
<Row label={t('manual.exenta')} value={formatGs(doc.amountExenta)} />
<Row label={t('manual.emitterRuc')} value={`${doc.emitterRuc}-${doc.emitterDv ?? ''}`} />
<Row label={t('docs.detail.source.manual')} value={t(`docs.detail.source.${doc.source}` as const)} />
</dl>
</Card>
<Card className="space-y-4">
<div className="flex items-center justify-between gap-3">
<h2 className="font-semibold tracking-tight">{t('bandeja.category')}</h2>
<Button type="button" variant="ghost" onClick={() => setEditing(!editing)}>
{editing ? t('common.cancel') : t('common.edit')}
</Button>
</div>
{editing ? (
<CategoryPicker
value={category}
onSelect={(next) => reclassify.mutate({ irpCategory: next })}
/>
) : (
<p data-testid="document-category" className="text-lg font-medium">
{t(`categories.${category}` as const)}
</p>
)}
{classification ? (
<div className="space-y-3 border-t pt-4 text-sm">
<Row
label={t('docs.detail.ivaCredit')}
value={formatGs(classification.ivaCreditAmount)}
/>
<Row
label={t('docs.detail.deductible')}
value={
classification.irpDeductibleAmount > 0
? formatGs(classification.irpDeductibleAmount)
: t('docs.detail.notDeductible')
}
/>
<label className="flex items-center justify-between gap-4">
<span>{t('docs.detail.ivaCredit')}</span>
<Switch
checked={classification.ivaCreditEligible}
onCheckedChange={(next) => reclassify.mutate({ ivaCreditEligible: next })}
label={t('docs.detail.ivaCredit')}
/>
</label>
{classification.reasons.length > 0 ? (
<ul className="space-y-1 text-xs text-[var(--text-muted)]">
{classification.reasons.map((reason) => (
<li key={reason}>
{t(`classification.reason.${reason}` as 'classification.reason.irp_no_category')}
</li>
))}
</ul>
) : null}
</div>
) : null}
</Card>
{doc.fileUrl ? (
<Card className="p-0">
{/* The stored photograph. Served through the authenticated file route. */}
<img
src={doc.fileUrl}
alt={doc.emitterName}
className="w-full rounded-2xl object-contain"
/>
</Card>
) : null}
</div>
);
}
function Row({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-baseline justify-between gap-4">
<dt className="text-[var(--text-muted)]">{label}</dt>
<dd className="tnum text-right font-medium">{value}</dd>
</div>
);
}
@@ -0,0 +1,12 @@
import { setRequestLocale } from 'next-intl/server';
import { DocumentDetail } from './document-detail';
export default async function DocumentPage({
params,
}: {
params: Promise<{ locale: string; id: string }>;
}) {
const { locale, id } = await params;
setRequestLocale(locale);
return <DocumentDetail id={id} locale={locale} />;
}
@@ -0,0 +1,188 @@
'use client';
import type { Direction, DocStatus } from '@impuestos/contracts';
import { formatGs, type Locale } from '@impuestos/i18n';
import { useQuery } from '@tanstack/react-query';
import { FileText } from 'lucide-react';
import { useState } from 'react';
import { DocCard } from '@/components/doc-card';
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';
/** Flow E1: filterable list with a monthly total header. */
export function DocumentsScreen({ locale }: { locale: string }) {
const t = useT();
const [direction, setDirection] = useState<Direction | undefined>();
const [status, setStatus] = useState<DocStatus | undefined>();
const [search, setSearch] = useState('');
const query = {
...(direction ? { direction } : {}),
...(status ? { status } : {}),
...(search.trim() ? { q: search.trim() } : {}),
};
const documents = useQuery({
queryKey: ['documents', query],
queryFn: ({ signal }) => api.listDocuments(query, signal),
});
const items = documents.data?.items ?? [];
const total = items.reduce((sum, doc) => sum + (doc.direction === 'purchase' ? doc.total : 0), 0);
const errors = useQuery({
queryKey: ['documents', 'errors'],
queryFn: ({ signal }) => api.listIngestErrors(signal),
});
return (
<div className="space-y-4 py-4">
<div className="flex items-center justify-between gap-3">
<h1 className="text-2xl font-semibold tracking-tight">{t('docs.title')}</h1>
<Link href="/escanear" className={buttonClasses({ size: 'md' })}>
{t('scan.fab')}
</Link>
</div>
<input
type="search"
aria-label={t('common.search')}
placeholder={t('common.search')}
value={search}
onChange={(event) => setSearch(event.target.value)}
className="h-11 w-full rounded-2xl border bg-[var(--surface-raised)] px-4"
/>
<div className="flex flex-wrap gap-2">
<Filter label={t('docs.filter.all')} active={!direction && !status} onClick={() => {
setDirection(undefined);
setStatus(undefined);
}} />
<Filter
label={t('manual.direction.purchase')}
active={direction === 'purchase'}
onClick={() => setDirection(direction === 'purchase' ? undefined : 'purchase')}
/>
<Filter
label={t('manual.direction.sale')}
active={direction === 'sale'}
onClick={() => setDirection(direction === 'sale' ? undefined : 'sale')}
/>
<Filter
label={t('status.needs_review')}
active={status === 'needs_review'}
onClick={() => setStatus(status === 'needs_review' ? undefined : 'needs_review')}
/>
</div>
{errors.data && errors.data.length > 0 ? (
<Card className="space-y-2 border-attention">
<h2 className="font-medium text-attention">{t('docs.errors.title')}</h2>
<ul className="space-y-1 text-sm text-[var(--text-muted)]">
{errors.data.map((error) => (
<li key={error.id}>{error.message}</li>
))}
</ul>
<Link href="/comprobantes/nuevo" className="text-sm text-accent-700 underline">
{t('docs.errors.retry')}
</Link>
</Card>
) : null}
{documents.isPending ? (
<Card>
<Skeleton name="doc-list-item" count={5} />
</Card>
) : null}
{documents.isError ? (
<Card className="space-y-3">
<p role="alert" className="text-sm">
{t('common.error.generic')}
</p>
<Button type="button" onClick={() => void documents.refetch()}>
{t('common.retry')}
</Button>
</Card>
) : null}
{documents.data && items.length === 0 ? (
<Card>
<EmptyState
icon={<FileText aria-hidden className="size-8" />}
title={t('docs.empty')}
action={
<Link href="/escanear" className={buttonClasses({ size: 'lg' })}>
{t('docs.emptyCta')}
</Link>
}
/>
</Card>
) : null}
{items.length > 0 ? (
<>
<Card className="flex items-baseline justify-between">
<div>
<p className="text-sm text-[var(--text-muted)]">{t('docs.monthTotal')}</p>
<p className="tnum text-2xl font-semibold tracking-tight">{formatGs(total)}</p>
</div>
<p className="text-sm text-[var(--text-muted)]">
{t('docs.count', { count: documents.data?.total ?? items.length })}
</p>
</Card>
<Card className="divide-y p-0">
<ul>
{items.map((document) => (
<li key={document.id} className="px-6">
<Link href={`/comprobantes/${document.id}`} className="block">
<DocCard
document={document}
locale={locale as Locale}
compact
categoryLabel={t(
`categories.${document.classification?.irpCategory ?? 'none'}` as const,
)}
statusLabel={t(`status.${document.status}` as const)}
/>
</Link>
</li>
))}
</ul>
</Card>
</>
) : null}
</div>
);
}
function Filter({
label,
active,
onClick,
}: {
label: string;
active: boolean;
onClick: () => void;
}) {
return (
<button
type="button"
aria-pressed={active}
onClick={onClick}
className={cn(
'rounded-full border px-3 py-1.5 text-sm transition-colors',
active ? 'border-accent-600 bg-accent-50 text-accent-700' : 'bg-[var(--surface-raised)]',
)}
>
{label}
</button>
);
}
@@ -0,0 +1,233 @@
'use client';
import type { Direction, SupplierRegimeHint } from '@impuestos/contracts';
import { formatGsAmount } from '@impuestos/i18n';
import { computeRucDv, parseRuc, validateRuc } from '@impuestos/rules';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useSearchParams } from 'next/navigation';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useRouter } from '@/i18n/navigation';
import { useT } from '@/i18n/t';
import { api } from '@/lib/api';
import { cn } from '@/lib/utils';
const REGIMES: SupplierRegimeHint[] = ['normal', 'resimple', 'unknown'];
/**
* Flow B3. One screen, numeric keypads for the money, and the IVA split worked out from
* the total with an override, because retyping a number the factura already prints is how
* people give up halfway.
*/
export function ManualForm() {
const t = useT();
const router = useRouter();
const queryClient = useQueryClient();
const fileId = useSearchParams().get('fileId');
const [direction, setDirection] = useState<Direction>('purchase');
const [ruc, setRuc] = useState('');
const [emitterName, setEmitterName] = useState('');
const [issueDate, setIssueDate] = useState(() => new Date().toISOString().slice(0, 10));
const [total, setTotal] = useState('');
const [allTenPercent, setAllTenPercent] = useState(true);
const [regime, setRegime] = useState<SupplierRegimeHint>('unknown');
const [override, setOverride] = useState<{ iva10: string; iva5: string; exenta: string } | null>(null);
const parsedRuc = parseRuc(ruc.trim());
const rucValid = parsedRuc ? validateRuc(parsedRuc.base, parsedRuc.dv) : /^\d{1,8}$/.test(ruc.trim());
const totalValue = total === '' ? 0 : Number(total);
// IVA is inside the printed total: at 10% the tax is a eleventh of it, at 5% a twenty first.
const derived = allTenPercent
? { iva10: Math.round(totalValue / 11), iva5: 0, exenta: 0 }
: { iva10: 0, iva5: Math.round(totalValue / 21), exenta: 0 };
const split = override
? {
iva10: Number(override.iva10 || '0'),
iva5: Number(override.iva5 || '0'),
exenta: Number(override.exenta || '0'),
}
: derived;
const save = useMutation({
mutationFn: () => {
const base = parsedRuc?.base ?? ruc.trim();
return api.createManualDocument({
...(fileId ? { fileId } : {}),
direction,
docKind: 'factura',
emitterRuc: base,
emitterDv: parsedRuc ? String(parsedRuc.dv) : String(computeRucDv(base)),
emitterName: emitterName.trim(),
issueDate,
total: totalValue,
amountIva10: split.iva10 > 0 ? totalValue - split.iva10 - split.exenta : 0,
amountIva5: split.iva5 > 0 ? totalValue - split.iva5 - split.exenta : 0,
amountExenta: split.exenta,
iva10: split.iva10,
iva5: split.iva5,
supplierRegimeHint: regime,
});
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['documents'] });
router.push('/bandeja');
},
});
const canSave = rucValid && emitterName.trim().length > 0 && totalValue > 0;
return (
<div className="space-y-4 py-4">
<h1 className="text-2xl font-semibold tracking-tight">{t('manual.title')}</h1>
{fileId ? <p className="text-sm text-[var(--text-muted)]">{t('scan.needsManual')}</p> : null}
<Card className="space-y-5">
<fieldset className="space-y-2">
<legend className="text-sm font-medium text-[var(--text-muted)]">
{t('manual.direction')}
</legend>
<div className="grid grid-cols-2 gap-2">
{(['purchase', 'sale'] as const).map((value) => (
<button
key={value}
type="button"
aria-pressed={direction === value}
onClick={() => setDirection(value)}
className={cn(
'rounded-2xl border p-3 text-sm transition-colors',
direction === value ? 'border-accent-600 bg-accent-50' : 'bg-[var(--surface-raised)]',
)}
>
{t(`manual.direction.${value}` as const)}
</button>
))}
</div>
</fieldset>
<div className="space-y-1.5">
<Label htmlFor="ruc">{t('manual.emitterRuc')}</Label>
<Input
id="ruc"
inputMode="numeric"
value={ruc}
aria-invalid={ruc.length > 0 && !rucValid}
onChange={(event) => setRuc(event.target.value)}
/>
{ruc.length > 0 && !rucValid ? (
<p role="alert" className="text-sm text-overdue">
{t('landing.invalidDoc')}
</p>
) : null}
</div>
<div className="space-y-1.5">
<Label htmlFor="emitterName">{t('manual.emitterName')}</Label>
<Input
id="emitterName"
value={emitterName}
onChange={(event) => setEmitterName(event.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="issueDate">{t('manual.date')}</Label>
<Input
id="issueDate"
type="date"
value={issueDate}
onChange={(event) => setIssueDate(event.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="total">{t('manual.total')}</Label>
<Input
id="total"
inputMode="numeric"
className="tnum text-2xl"
value={total === '' ? '' : formatGsAmount(totalValue)}
onChange={(event) => setTotal(event.target.value.replace(/\D/g, ''))}
/>
</div>
<div className="space-y-3">
<label className="flex items-center justify-between gap-4">
<span className="text-sm">{t('manual.ivaSplit.q')}</span>
<Switch
checked={allTenPercent}
onCheckedChange={(next) => {
setAllTenPercent(next);
setOverride(null);
}}
label={t('manual.ivaSplit.q')}
/>
</label>
<p className="text-sm text-[var(--text-muted)] text-pretty">{t('manual.ivaSplit.help')}</p>
<div className="grid grid-cols-3 gap-2">
{(
[
['iva10', t('manual.iva10')],
['iva5', t('manual.iva5')],
['exenta', t('manual.exenta')],
] as const
).map(([key, label]) => (
<div key={key} className="space-y-1">
<Label htmlFor={key} className="text-xs">
{label}
</Label>
<Input
id={key}
inputMode="numeric"
className="tnum"
value={formatGsAmount(split[key])}
onChange={(event) => {
const digits = event.target.value.replace(/\D/g, '');
setOverride({
iva10: String(split.iva10),
iva5: String(split.iva5),
exenta: String(split.exenta),
[key]: digits,
});
}}
/>
</div>
))}
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="regime">{t('manual.regime')}</Label>
<select
id="regime"
value={regime}
onChange={(event) => setRegime(event.target.value as SupplierRegimeHint)}
className="h-12 w-full rounded-2xl border bg-[var(--surface-raised)] px-3 text-base"
>
{REGIMES.map((value) => (
<option key={value} value={value}>
{t(`manual.regime.${value}` as const)}
</option>
))}
</select>
</div>
{save.isError ? (
<p role="alert" className="text-sm text-overdue">
{t('common.error.generic')}
</p>
) : null}
<Button type="button" size="lg" block disabled={!canSave || save.isPending} onClick={() => save.mutate()}>
{save.isPending ? t('common.saving') : t('manual.submit')}
</Button>
</Card>
</div>
);
}
@@ -0,0 +1,21 @@
import { setRequestLocale } from 'next-intl/server';
import { Suspense } from 'react';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { ManualForm } from './manual-form';
export default async function ManualPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params;
setRequestLocale(locale);
return (
<Suspense
fallback={
<Card className="my-4">
<Skeleton name="profile-section" />
</Card>
}
>
<ManualForm />
</Suspense>
);
}
@@ -0,0 +1,8 @@
import { setRequestLocale } from 'next-intl/server';
import { DocumentsScreen } from './documents-screen';
export default async function DocumentsPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params;
setRequestLocale(locale);
return <DocumentsScreen locale={locale} />;
}