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,266 @@
'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>
);
}
@@ -0,0 +1,8 @@
import { setRequestLocale } from 'next-intl/server';
import { Bandeja } from './bandeja';
export default async function BandejaPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params;
setRequestLocale(locale);
return <Bandeja locale={locale} />;
}
@@ -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} />;
}
@@ -0,0 +1,8 @@
import { setRequestLocale } from 'next-intl/server';
import { ScanScreen } from './scan-screen';
export default async function ScanPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params;
setRequestLocale(locale);
return <ScanScreen locale={locale} />;
}
@@ -0,0 +1,308 @@
'use client';
import type { DocumentDto, ScanResultDto } from '@impuestos/contracts';
import { formatDateLong, formatGs, type Locale } from '@impuestos/i18n';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Flashlight, Upload } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Button, buttonClasses } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Link, useRouter } from '@/i18n/navigation';
import { useT } from '@/i18n/t';
import { api } from '@/lib/api';
import { captureFrame, decodeQr, decodeQrFromVideo } from '@/lib/qr';
import { cn } from '@/lib/utils';
/** How long to look for a QR before offering the plain photo path (FLOWS.md B1). */
const NO_QR_HINT_AFTER_MS = 4000;
const DECODE_INTERVAL_MS = 250;
type Outcome =
| { kind: 'document'; document: DocumentDto }
| { kind: 'needs_manual'; fileId: string };
export function ScanScreen({ locale }: { locale: string }) {
const t = useT();
const router = useRouter();
const queryClient = useQueryClient();
const video = useRef<HTMLVideoElement>(null);
const stream = useRef<MediaStream | null>(null);
const busy = useRef(false);
const [cameraFailed, setCameraFailed] = useState(false);
const [showNoQrHint, setShowNoQrHint] = useState(false);
const [torchOn, setTorchOn] = useState(false);
const [outcome, setOutcome] = useState<Outcome | null>(null);
const upload = useMutation({
mutationFn: async (input: { file: File; qrPayload: string | null }) => {
const result: ScanResultDto = await api.scanDocument(input.file, input.qrPayload);
return result;
},
onSuccess: async (result) => {
await queryClient.invalidateQueries({ queryKey: ['documents'] });
if ('needsManual' in result) {
setOutcome({ kind: 'needs_manual', fileId: result.fileId });
return;
}
setOutcome({ kind: 'document', document: result });
},
});
const submit = useCallback(
(file: File, qrPayload: string | null) => {
if (busy.current) return;
busy.current = true;
upload.mutate({ file, qrPayload }, { onSettled: () => (busy.current = false) });
},
[upload],
);
// Live capture: the camera is only opened here, and always released on unmount.
useEffect(() => {
if (outcome) return;
let cancelled = false;
async function open() {
try {
const media = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' },
audio: false,
});
if (cancelled) {
media.getTracks().forEach((track) => track.stop());
return;
}
stream.current = media;
if (video.current) {
video.current.srcObject = media;
await video.current.play().catch(() => undefined);
}
} catch {
if (!cancelled) setCameraFailed(true);
}
}
void open();
return () => {
cancelled = true;
stream.current?.getTracks().forEach((track) => track.stop());
stream.current = null;
};
}, [outcome]);
// A QR hit auto-captures: there is nothing for the user to decide once we have it.
useEffect(() => {
if (cameraFailed || outcome) return;
const hintTimer = setTimeout(() => setShowNoQrHint(true), NO_QR_HINT_AFTER_MS);
const timer = setInterval(() => {
void (async () => {
if (!video.current || busy.current) return;
const payload = await decodeQrFromVideo(video.current);
if (!payload || !video.current) return;
const frame = await captureFrame(video.current);
if (frame) {
navigator.vibrate?.(40);
submit(frame, payload);
}
})();
}, DECODE_INTERVAL_MS);
return () => {
clearTimeout(hintTimer);
clearInterval(timer);
};
}, [cameraFailed, outcome, submit]);
async function toggleTorch() {
const track = stream.current?.getVideoTracks()[0];
if (!track) return;
try {
const next = !torchOn;
// `torch` is a real constraint on mobile but is not in the DOM lib's type yet.
await track.applyConstraints({ advanced: [{ torch: next }] } as unknown as MediaTrackConstraints);
setTorchOn(next);
} catch {
// Most desktop cameras have no torch. Nothing to say about it.
}
}
async function onPick(file: File) {
// Decoding before upload keeps the QR path working for a photo from the gallery.
submit(file, await decodeQr(file));
}
if (outcome?.kind === 'document') {
return (
<ScanResult
document={outcome.document}
locale={locale as Locale}
onAnother={() => setOutcome(null)}
/>
);
}
if (outcome?.kind === 'needs_manual') {
router.push(`/comprobantes/nuevo?fileId=${encodeURIComponent(outcome.fileId)}`);
return (
<Card className="my-4">
<Skeleton name="profile-section" />
</Card>
);
}
return (
<div className="space-y-4 py-4">
<h1 className="text-2xl font-semibold tracking-tight">{t('scan.title')}</h1>
<div className="relative overflow-hidden rounded-2xl bg-black">
<video
ref={video}
playsInline
muted
aria-label={t('scan.hint')}
className={cn('aspect-3/4 w-full object-cover', cameraFailed && 'hidden')}
/>
{cameraFailed ? (
<p className="p-8 text-center text-sm text-white">{t('scan.cameraDenied')}</p>
) : (
<>
{/* Frame guide: shows where the QR has to sit. */}
<div
aria-hidden
className="pointer-events-none absolute inset-x-8 top-1/4 aspect-square rounded-2xl border-2 border-white/70"
/>
<button
type="button"
onClick={() => void toggleTorch()}
aria-pressed={torchOn}
className="absolute top-3 right-3 rounded-full bg-black/50 p-2.5 text-white"
>
<Flashlight aria-hidden className="size-5" />
<span className="sr-only">{t('scan.torch')}</span>
</button>
</>
)}
</div>
<p className="text-center text-sm text-[var(--text-muted)]">
{showNoQrHint || cameraFailed ? t('scan.noQrHint') : t('scan.hint')}
</p>
{upload.isPending ? (
<Card>
<p className="mb-3 text-sm text-[var(--text-muted)]">{t('scan.processing')}</p>
<Skeleton name="bandeja-card" />
</Card>
) : null}
{upload.isError ? (
<p role="alert" className="text-center text-sm text-overdue">
{t('common.error.generic')}
</p>
) : null}
<div className="space-y-2">
<label className={cn(buttonClasses({ variant: 'secondary', size: 'lg', block: true }), 'cursor-pointer')}>
<Upload aria-hidden className="size-4" />
{t('scan.upload')}
<input
type="file"
accept="image/*,application/pdf"
className="sr-only"
onChange={(event) => {
const file = event.target.files?.[0];
if (file) void onPick(file);
}}
/>
</label>
{!cameraFailed ? (
<Button
type="button"
size="lg"
block
disabled={upload.isPending}
onClick={() => {
void (async () => {
if (!video.current) return;
const frame = await captureFrame(video.current);
if (frame) submit(frame, await decodeQr(frame));
})();
}}
>
{t('scan.shutter')}
</Button>
) : null}
</div>
</div>
);
}
function ScanResult({
document,
locale,
onAnother,
}: {
document: DocumentDto;
locale: Locale;
onAnother: () => void;
}) {
const t = useT();
const merged = document.merged === true;
return (
<div className="space-y-4 py-4">
<Card className="space-y-4">
<div className="flex items-center justify-between gap-3">
<h1 className="text-xl font-semibold tracking-tight text-balance">
{merged ? t('scan.duplicate.title') : t('scan.result.title')}
</h1>
<span className="shrink-0 rounded-full bg-positive-soft px-2.5 py-0.5 text-xs font-medium text-positive">
{document.verifiedDnit ? t('scan.verified') : t('scan.registered')}
</span>
</div>
{merged ? (
<p className="text-sm text-[var(--text-muted)] text-pretty">
{t('scan.duplicate.body', { date: formatDateLong(locale, document.issueDate) })}
</p>
) : null}
<dl className="space-y-2 text-sm">
<Row label={t('scan.result.emitter')} value={document.emitterName} />
<Row label={t('scan.result.date')} value={formatDateLong(locale, document.issueDate)} />
<Row label={t('scan.result.total')} value={formatGs(document.total)} />
{document.classification ? (
<Row
label={t('bandeja.category')}
value={t(`categories.${document.classification.irpCategory}` as const)}
/>
) : null}
</dl>
<div className="flex flex-col gap-2">
<Link href="/bandeja" className={buttonClasses({ size: 'lg', block: true })}>
{t('scan.goToBandeja')}
</Link>
<Button type="button" variant="secondary" block onClick={onAnother}>
{t('scan.another')}
</Button>
</div>
</Card>
</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="text-right font-medium">{value}</dd>
</div>
);
}
+2 -3
View File
@@ -44,11 +44,10 @@ export default async function InicioPage({ params }: { params: Promise<{ locale:
body={t('home.firstRun.body')}
action={
<div className="flex flex-col items-center gap-2">
{/* Scanning and manual entry arrive with the ingestion pipeline in phase 3. */}
<Link href="/comprobantes" className={buttonClasses({ size: 'lg' })}>
<Link href="/escanear" className={buttonClasses({ size: 'lg' })}>
{t('home.firstRun.scan')}
</Link>
<Link href="/comprobantes" className="text-sm text-accent-700 hover:underline">
<Link href="/comprobantes/nuevo" className="text-sm text-accent-700 hover:underline">
{t('home.firstRun.manual')}
</Link>
</div>
+2 -1
View File
@@ -23,7 +23,8 @@
"react": "^19.2.8",
"react-dom": "^19.2.8",
"tailwind-merge": "^3.6.0",
"zod": "^4.5.4"
"zod": "^4.5.4",
"zxing-wasm": "^3.1.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.3",
+21
View File
@@ -0,0 +1,21 @@
// Copies the ZXing reader wasm into public/ so the browser loads it from our own origin.
//
// zxing-wasm fetches it from a CDN by default, which the CSP forbids (SPEC.md section 14:
// no third party scripts) and which would break the offline scan queue. Runs before dev
// and build, so a fresh clone never has to remember.
import { copyFileSync, mkdirSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
// Walk up from whichever build the resolver picked to the package root, so the path does
// not depend on cjs vs es. The package does not export ./package.json.
const readerEntry = require.resolve('zxing-wasm/reader');
const packageRoot = readerEntry.slice(0, readerEntry.lastIndexOf(`${sep}dist${sep}`));
const source = join(packageRoot, 'dist', 'reader', 'zxing_reader.wasm');
const targetDir = join(dirname(dirname(fileURLToPath(import.meta.url))), 'public', 'zxing');
mkdirSync(targetDir, { recursive: true });
copyFileSync(source, join(targetDir, 'zxing_reader.wasm'));
console.info(`[zxing] wasm copied to ${targetDir}`);
@@ -0,0 +1,82 @@
'use client';
import { IRP_CATEGORIES, type IrpCategory } from '@impuestos/contracts';
import {
Apple,
Car,
Clapperboard,
GraduationCap,
HeartPulse,
House,
Shirt,
Users,
} from 'lucide-react';
import type { ComponentType } from 'react';
import { useT } from '@/i18n/t';
import { cn } from '@/lib/utils';
const ICONS: Record<IrpCategory, ComponentType<{ className?: string }>> = {
alimentacion: Apple,
salud: HeartPulse,
educacion: GraduationCap,
vivienda: House,
vestimenta: Shirt,
esparcimiento: Clapperboard,
vehiculo: Car,
familiares: Users,
};
/**
* The eight IRP categories as an icon grid. Ordered as IRP_CATEGORIES, because the
* keyboard shortcuts in the bandeja are 1 to 8 against that same order.
*/
export function CategoryPicker({
value,
onSelect,
}: {
value: IrpCategory | 'none';
onSelect: (category: IrpCategory | 'none') => void;
}) {
const t = useT();
return (
<div className="grid grid-cols-4 gap-2">
{IRP_CATEGORIES.map((category, index) => {
const Icon = ICONS[category];
const selected = value === category;
return (
<button
key={category}
type="button"
aria-pressed={selected}
aria-label={t(`categories.${category}` as const)}
onClick={() => onSelect(category)}
className={cn(
'flex flex-col items-center gap-1.5 rounded-2xl border p-3 text-center transition-colors',
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent-600',
selected ? 'border-accent-600 bg-accent-50' : 'bg-[var(--surface-raised)]',
)}
>
<Icon className="size-5 text-accent-700" />
<span className="text-xs leading-tight">{t(`categories.${category}` as const)}</span>
{/* The keyboard shortcut, shown but not announced: it is not part of the name. */}
<span aria-hidden className="tnum text-[10px] text-[var(--text-muted)]">
{String(index + 1)}
</span>
</button>
);
})}
<button
type="button"
aria-pressed={value === 'none'}
onClick={() => onSelect('none')}
className={cn(
'col-span-4 rounded-2xl border p-2.5 text-sm transition-colors',
value === 'none' ? 'border-accent-600 bg-accent-50' : 'bg-[var(--surface-raised)]',
)}
>
{t('categories.none')}
</button>
</div>
);
}
+36
View File
@@ -0,0 +1,36 @@
import type { DocumentDto } from '@impuestos/contracts';
import { formatDateShort, type Locale } from '@impuestos/i18n';
import { Money } from '@/components/ui/money';
import { StatusChip } from '@/components/ui/status-chip';
import { cn } from '@/lib/utils';
/** One comprobante, the same shape in the bandeja and in the list (FLOWS.md section 1). */
export function DocCard({
document,
locale,
categoryLabel,
statusLabel,
compact,
}: {
document: DocumentDto;
locale: Locale;
categoryLabel: string;
statusLabel: string;
compact?: boolean;
}) {
return (
<div className={cn('flex items-start justify-between gap-4', compact ? 'py-3' : 'py-1')}>
<div className="min-w-0 space-y-1">
<p className="truncate font-medium">{document.emitterName}</p>
<p className="text-sm text-[var(--text-muted)]">
{formatDateShort(locale, document.issueDate)}
</p>
<div className="flex flex-wrap items-center gap-2 pt-1">
<StatusChip status={document.status} label={statusLabel} />
<span className="text-xs text-[var(--text-muted)]">{categoryLabel}</span>
</div>
</div>
<Money value={document.total} className="shrink-0" />
</div>
);
}
@@ -0,0 +1,18 @@
import type { DocStatus } from '@impuestos/contracts';
import { cn } from '@/lib/utils';
/** The status vocabulary, coloured the same way on every screen (FLOWS.md section 1). */
export function StatusChip({ status, label }: { status: DocStatus; label: string }) {
return (
<span
className={cn(
'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
status === 'confirmed' && 'bg-positive-soft text-positive',
status === 'needs_review' && 'bg-attention-soft text-attention',
status === 'rejected' && 'bg-[var(--surface)] text-[var(--text-muted)]',
)}
>
{label}
</span>
);
}
+105
View File
@@ -0,0 +1,105 @@
'use client';
/**
* Client side QR decoding (SPEC.md section 3). The platform decoder is tried first, since
* it is hardware accelerated and costs nothing to load; ZXing is the fallback for browsers
* that do not ship one, loaded lazily so the ~1MB wasm is fetched only when it is needed.
*
* The wasm is served from our own origin (public/zxing), not a CDN: the CSP forbids third
* party scripts and the offline queue has to keep working with no network.
*/
import type * as ZxingReaderModule from 'zxing-wasm/reader';
const WASM_PATH = '/zxing/zxing_reader.wasm';
type BarcodeDetectorLike = {
detect(source: ImageBitmapSource): Promise<{ rawValue: string }[]>;
};
type ZxingReader = typeof ZxingReaderModule;
let zxingReady: Promise<ZxingReader> | null = null;
async function loadZxing() {
zxingReady ??= (async () => {
const module = await import('zxing-wasm/reader');
module.prepareZXingModule({ overrides: { locateFile: () => WASM_PATH }, fireImmediately: false });
return module;
})();
return zxingReady;
}
function nativeDetector(): BarcodeDetectorLike | null {
const candidate = (globalThis as { BarcodeDetector?: new (options: { formats: string[] }) => BarcodeDetectorLike })
.BarcodeDetector;
if (!candidate) return null;
try {
return new candidate({ formats: ['qr_code'] });
} catch {
return null;
}
}
/** Returns the payload of the first QR found, or null. Never throws for a QR-less image. */
export async function decodeQr(source: Blob): Promise<string | null> {
const native = nativeDetector();
if (native) {
try {
const bitmap = await createImageBitmap(source);
const results = await native.detect(bitmap);
bitmap.close();
const value = results[0]?.rawValue;
if (value) return value;
} catch {
// Fall through: a detector that throws is a detector we do not have.
}
}
try {
const { readBarcodes } = await loadZxing();
const results = await readBarcodes(source, { tryHarder: true, formats: ['QRCode'] });
return results[0]?.text ?? null;
} catch {
return null;
}
}
/** Decodes a single video frame, for the live camera view. */
export async function decodeQrFromVideo(video: HTMLVideoElement): Promise<string | null> {
if (video.readyState < 2 || video.videoWidth === 0) return null;
const native = nativeDetector();
if (native) {
try {
const results = await native.detect(video);
const value = results[0]?.rawValue;
if (value) return value;
} catch {
// Fall through to the canvas path below.
}
}
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');
if (!context) return null;
context.drawImage(video, 0, 0);
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.9));
return blob ? decodeQr(blob) : null;
}
/** Grabs the current frame as a file, so a QR hit can auto-capture without a shutter. */
export async function captureFrame(video: HTMLVideoElement): Promise<File | null> {
if (video.videoWidth === 0) return null;
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');
if (!context) return null;
context.drawImage(video, 0, 0);
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.92));
return blob ? new File([blob], 'captura.jpg', { type: 'image/jpeg' }) : null;
}