Files
0pt/app/order/[id]/page.tsx
T
adminandClaude Opus 4.8 e6d3101501 fix: 17 confirmed bugs from full-repo audit (edge + Python engine) (#5)
* docs: correct stale quality-check-service.ts comment references

Two source comments still cited src/services/quality-check-service.ts as an
existing precedent. It doesn't exist anywhere in this repo's history (git
log --all: zero commits, any branch, ever) -- confirmed during the earlier
full-doc-corpus accuracy pass. Points each comment at the real precedent
instead (document-extraction-service.ts / iceberg-write-service.ts).

Applied from task_05ec36aa, spun off during that pass.

* fix: 17 confirmed bugs from full-repo audit (edge + Python engine)

Found by an 8-finder bug hunt across app/api, src/services, src/clients,
frontend, the Python engine, the data layer, config/infra, and tests, then
independently adversarially verified per finding (32 raw findings -> 27
confirmed real bugs; 5 refuted). This commit applies the 17 confirmed as
safe, mechanical fixes -- no architecture/design decision required. The
other 10 need a decision and are reported separately, not touched here.

Most consequential, app/api/payments/[order_id]/deposit/route.ts:
the client-supplied Origin request header was trusted unsanitized both as
a server-side fetch target (SSRF) and as Stripe Checkout success/cancel
redirect URLs (open redirect tied to a real payment flow), and a failed
order lookup silently fell through to a hardcoded deposit amount instead
of 404. Fixed by reading the order directly via lib/orders-store.ts
(mirroring the sibling release/route.ts, which already did this correctly)
instead of both trusting the Origin header and self-issuing an HTTP fetch.

Also fixed:
- 5 routes (orders, orders/[id], estimates, subscriptions, ai/parse) that
  500'd instead of 400ing on a literal JSON `null` body, since req.json()
  resolves (not rejects) for that input and bypasses the try/catch guard.
- app/api/0pt/lakehouse/mappings/{,[mappingId]/{,writes/}}route.ts each
  instantiated their own private service instances, so a mapping created
  via POST was invisible to the sibling GET and writes routes even before
  the separately-tracked dataset-registration gap. Extracted a shared
  singleton module, src/services/lakehouse-mapping-registry.ts.
- app/api/0pt/documents/[documentId]/extraction/route.ts collapsed every
  error (not-configured, policy-denied, policy-approval-required,
  not-found) into a blanket 400; now status-mapped like the sibling
  sources/[sourceId]/query route.
- app/api/vehicles/route.ts: plate query param wasn't URL-encoded before
  being concatenated into the outbound RDW request, allowing extra query
  parameters to be injected; added a strict allowlist + encodeURIComponent.
- app/api/uploads/route.ts: POST returned a fake 200 success with
  put_url: null even when "configured", instead of continuing to report
  501 until presign generation is actually implemented.
- src/adapters/document-intelligence-adapter.ts: the result-polling loop
  never checked response.ok, so a non-2xx poll response (auth expiry,
  429, 5xx) was silently retried until a generic timeout masked the real
  error.
- app/order/[id]/page.tsx: finish() never cleared the production-simulation
  setInterval, so it kept firing (and re-rendering) forever after delivery.
- app/admin/page.tsx: the metrics fetch had no response/shape validation
  (unlike the adjacent orders fetch), rendering literal "undefined" stat
  tiles on a malformed response instead of falling back to <ErrorState/>.
- services/api/workers/pipeline.py: `config.get("seeds") or DEMO_SEEDS`
  used truthy-or, so an explicit empty seeds dict was silently replaced
  with hardcoded demo org numbers instead of being respected as empty.
- services/api/workers/resolve.py: corroboration (confidence/agreed_sources
  bump) no longer fires for two hits from the same source under fuzzy
  match -- only a genuinely independent source now counts, per docs/06's
  own ">=2 independent sources agree" definition -- and a merged record's
  provenance array now actually includes the corroborating source's
  fields instead of only a bare source-name string.
- services/api/orchestrator/main.py: create_order's int(...) on
  unvalidated client volume/confidence fields raised on any
  decimal-formatted input (int("92.5") -> ValueError); now coerced via
  float() first with a safe default. /vehicles/{plate} and /screen also
  now catch connector exceptions and degrade gracefully, matching
  pipeline.py's existing pattern for the same connectors.
- lib/orders-store.ts: postgres.js (pinned v3.4.9) returns bigint/numeric
  columns as strings by default; getOrder/listOrders/setStatus were
  silently handing callers stringified money fields. Added a narrow
  per-row coercion instead of touching the shared client's global type
  map (which would affect unrelated tables' bigint/numeric columns too).
- lib/subscriptions-store.ts: the in-memory fallback returned
  oldest-first while the Postgres branch explicitly orders newest-first;
  now consistent, mirroring the identical fix already in orders-store.ts.
- app/api/auth/login/route.ts: DEV_LOGIN_KEY was compared with a plain
  !==, a non-constant-time comparison; replaced with crypto.timingSafeEqual.

Verified before commit: tsc --noEmit clean; vitest run 88 passed, 1 todo,
0 failures (13 files, unchanged from before this commit -- no existing
test's assertions needed to change). services/api/workers/resolve.py's
source-novelty and provenance-merge logic additionally verified by direct
execution against synthetic same-source/cross-source inputs (no Python
test suite exists in this repo to add to). services/api/workers/pipeline.py
and services/api/orchestrator/main.py verified with python -m py_compile
(no httpx/fastapi installed in this environment to run them directly).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(engine): treat explicit seeds:null as missing to avoid 500 in run_job

Four-eyes follow-up to this PR's own seeds change. Switching from
`config.get('seeds') or DEMO_SEEDS` to `config['seeds'] if 'seeds' in config`
correctly stopped an explicit empty {} from being backfilled with DEMO_SEEDS,
but regressed on client-controlled `{"seeds": null}`: seeds became None and
the downstream `seeds.get(market, [])` raised AttributeError -> 500. That path
is reachable (POST /orders stores raw body.config; POST /orders/{id}/run passes
it straight to run_job). Using `config.get('seeds') is not None` keeps the
intended behaviour (explicit {} honoured, never silently seeded with demo data)
while restoring the None-tolerance the old idiom had.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 18:52:19 +02:00

297 lines
15 KiB
TypeScript

"use client";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { OrderStepper } from "@/components/order-stepper";
import { useT } from "@/components/locale-provider";
import { useReveal } from "@/hooks/use-reveal";
import { getLocalOrder } from "@/lib/order-client";
const STAGES: { key: string; title: { en: string; sv: string }; meta: { en: string; sv: string } }[] = [
{ key: "source", title: { en: "Source race", sv: "Källracing" }, meta: { en: "GLEIF · Brreg · CVR · PRH", sv: "GLEIF · Brreg · CVR · PRH" } },
{ key: "extract", title: { en: "Extraction & OCR", sv: "Extraktion & OCR" }, meta: { en: "register-API · documents", sv: "register-API · dokument" } },
{ key: "structure", title: { en: "Structuring & matching", sv: "Strukturering & matchning"}, meta: { en: "NER · entity resolution · LEI-link", sv: "NER · entity resolution · LEI-länk" } },
{ key: "enrich", title: { en: "Enrichment & fusion", sv: "Berikning & fusion" }, meta: { en: "multi-source agreement", sv: "multi-source agreement" } },
{ key: "quality", title: { en: "Quality control", sv: "Kvalitetskontroll" }, meta: { en: "expectations · dedup · threshold", sv: "expectations · dedup · tröskel" } },
];
const MARKET_KEYS = [
{ code: "SE", speed: 1.0 },
{ code: "NO", speed: 0.85 },
{ code: "DK", speed: 0.7 },
{ code: "FI", speed: 0.5 },
];
function prefersReduced() {
return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
}
export default function ProductionPage() {
const t = useT();
const { id } = useParams<{ id: string }>();
const searchParams = useSearchParams();
const reveal = useReveal<HTMLDivElement>();
const [running, setRunning] = useState(false);
const [done, setDone] = useState(false);
const [progress, setProgress] = useState<number[]>([0, 0, 0, 0, 0]);
const [markets, setMarkets] = useState<number[]>([0, 0, 0, 0]);
const [conf, setConf] = useState(0);
const [feed, setFeed] = useState<{ t: string; msg: string; kind: "ok" | "run" }[]>([]);
const timer = useRef<ReturnType<typeof setInterval> | null>(null);
const tick = useRef(0);
const [order, setOrder] = useState<{ markets: string[]; volume: number } | null>(null);
useEffect(() => {
if (searchParams.get("deposit") === "success") {
toast.success(t({ en: "Deposit received. Production has started.", sv: "Förskott mottaget. Produktionen har startat." }));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const fromLocal = () => {
const c = getLocalOrder(id)?.config as { markets?: string[]; volume?: number } | undefined;
if (c) setOrder({ markets: c.markets ?? [], volume: c.volume ?? 0 });
};
fetch(`/api/orders/${id}`)
.then((r) => (r.ok ? r.json() : null))
.then((o) => {
const c = o?.config as { markets?: string[]; volume?: number } | undefined;
if (c) setOrder({ markets: c.markets ?? [], volume: c.volume ?? 0 });
else fromLocal();
})
.catch(fromLocal);
}, [id]);
const finish = () => {
if (timer.current) {
clearInterval(timer.current);
timer.current = null;
}
setProgress([100, 100, 100, 100, 100]);
setMarkets([100, 100, 100, 100]);
setConf(94);
setDone(true);
setRunning(false);
setFeed((f) => [{ t: stamp(), msg: t({ en: "Delivered. 94% confidence. 4,980 records.", sv: "Levererad. 94 % konfidens. 4 980 poster." }), kind: "ok" }, ...f]);
};
const stamp = () => {
const s = 10 + Math.floor(tick.current / 2);
return `00:${String(s).padStart(2, "0")}`;
};
const start = () => {
if (running || done) return;
if (prefersReduced()) {
finish();
return;
}
setRunning(true);
setFeed([{ t: "00:00", msg: t({ en: `Order ${id}. Deposit received.`, sv: `Order ${id}. Depå mottagen.` }), kind: "run" }]);
timer.current = setInterval(() => {
tick.current += 1;
setProgress((prev) => {
const next = [...prev];
const i = next.findIndex((p) => p < 100);
if (i === -1) return prev;
next[i] = Math.min(100, next[i] + 8 + Math.random() * 10);
if (next[i] >= 100 && i < STAGES.length) {
setFeed((f) => [{ t: stamp(), msg: t({ en: `${STAGES[i].title.en}. Done.`, sv: `${STAGES[i].title.sv}. Klar.` }), kind: "ok" as const }, ...f].slice(0, 12));
}
return next;
});
setMarkets((prev) => prev.map((m, idx) => Math.min(100, m + (6 + Math.random() * 6) * MARKET_KEYS[idx].speed)));
setConf((c) => Math.min(94, c + 2.5 + Math.random() * 2));
}, 320);
};
useEffect(() => {
if (progress.every((p) => p >= 100) && running) finish();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [progress, running]);
useEffect(() => () => { if (timer.current) clearInterval(timer.current); }, []);
const overall = Math.round(progress.reduce((a, b) => a + b, 0) / STAGES.length);
const status = done ? t({ en: "Delivered", sv: "Levererad" }) : running ? `${overall} %` : t({ en: "Waiting", sv: "Väntar" });
return (
<main id="main-content" className="min-h-screen bg-background text-foreground">
<OrderStepper active={3} />
<div ref={reveal} className="mx-auto max-w-[80rem] px-6">
{/* masthead — oversized numeral as graphic texture */}
<header className="relative border-b border-border py-16 md:py-20">
<span
aria-hidden
className="pointer-events-none absolute -top-6 right-0 select-none font-mono text-[clamp(7rem,18vw,15rem)] font-medium leading-none tracking-[-0.04em] text-foreground/[0.04]"
>
03
</span>
<p className="reveal font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
{t({ en: "Step 03 — Production", sv: "Steg 03 — Produktion" })}
</p>
<h1 className="reveal delay-1 mt-5 max-w-[18ch] text-[clamp(2.6rem,7vw,5.5rem)] font-medium leading-[0.95] tracking-[-0.035em]">
{t({ en: "Watch it happen.", sv: "Se det hända." })}
</h1>
<p className="reveal delay-2 mt-5 font-mono text-sm text-muted-foreground">
{order
? `${order.markets.join(" · ") || "—"} · ${new Intl.NumberFormat("sv-SE").format(order.volume)} ${t({ en: "records", sv: "poster" })}`
: t({ en: "Live. Source by source.", sv: "Live. Källa för källa." })}
</p>
</header>
{/* control row — single shared baseline */}
<div className="reveal delay-2 flex flex-wrap items-stretch gap-px border-b border-border bg-border">
<button
type="button"
onClick={start}
disabled={running || done}
className="group flex items-center gap-3 bg-background px-6 py-5 font-mono text-[12px] uppercase tracking-[0.12em] transition-colors hover:bg-foreground hover:text-background disabled:opacity-40 disabled:hover:bg-background disabled:hover:text-foreground"
>
<span className="text-[var(--accent-red)] transition-colors group-hover:text-background group-disabled:text-foreground">
{done ? "✓" : running ? "●" : "▸"}
</span>
{done ? t({ en: "Done", sv: "Klar" }) : running ? t({ en: "Running", sv: "Kör" }) : t({ en: "Start", sv: "Starta" })}
</button>
<span className="flex flex-1 items-center bg-background px-6 py-5 font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground">
{t({ en: "Order", sv: "Order" })} {id}
</span>
<span className="flex items-center gap-3 bg-background px-6 py-5 font-mono text-[11px] uppercase tracking-[0.1em]">
<span className="text-muted-foreground">{t({ en: "Status", sv: "Status" })}</span>
<span className="tabular-nums text-foreground">{status}</span>
</span>
<span className="flex items-center gap-3 bg-background px-6 py-5 font-mono text-[11px] uppercase tracking-[0.1em]">
<span className="text-muted-foreground">{t({ en: "ETA", sv: "ETA" })}</span>
<span className="tabular-nums text-foreground">{t({ en: "≈ 4 days", sv: "≈ 4 dgr" })}</span>
</span>
</div>
<div className="grid grid-cols-1 lg:grid-cols-[1fr_340px]">
{/* stages — numbered ledger, hairline-separated */}
<div className="reveal-left delay-1 border-border lg:border-r">
{STAGES.map((s, i) => {
const p = Math.round(progress[i]);
const isDone = p >= 100;
const isRun = !isDone && (i === 0 || progress[i - 1] >= 100) && running;
const accent = isDone ? "var(--prov-3)" : isRun ? "var(--accent-red)" : "var(--muted-foreground)";
return (
<div
key={s.key}
className="group relative border-b border-border py-7 pl-6 pr-6 transition-colors hover:bg-secondary/40"
>
{/* state marker rail */}
<span
aria-hidden
className="absolute left-0 top-0 h-full w-px transition-all"
style={{ backgroundColor: isDone || isRun ? accent : "transparent" }}
/>
<div className="flex items-baseline justify-between gap-4">
<div className="flex items-baseline gap-4">
<span className="font-mono text-[11px] tabular-nums text-muted-foreground">
{String(i + 1).padStart(2, "0")}
</span>
<span className="text-base font-medium tracking-[-0.01em]">{t(s.title)}</span>
</div>
<span className="font-mono text-sm tabular-nums" style={{ color: accent }}>
{p}%
</span>
</div>
<div className="mt-4 h-px w-full bg-border">
<div
className="h-px transition-all duration-300"
style={{ width: `${p}%`, backgroundColor: isDone ? "var(--prov-3)" : "var(--foreground)" }}
/>
</div>
<p className="mt-3 pl-10 font-mono text-[10.5px] uppercase tracking-[0.08em] text-muted-foreground">
{t(s.meta)}
</p>
</div>
);
})}
</div>
{/* right column — gauge, markets, feed */}
<aside className="reveal-right delay-2 flex flex-col">
{/* confidence gauge */}
<div className="border-b border-border px-6 py-10 text-center">
<ConfidenceRing value={conf} unitLabel={t({ en: "PERCENT", sv: "PROCENT" })} />
<p className="mt-5 font-mono text-[10.5px] uppercase tracking-[0.14em] text-muted-foreground">
{t({ en: "Confidence — deliverable", sv: "Konfidens — levererbart" })}
</p>
</div>
{/* per market */}
<div className="border-b border-border px-6 py-7">
<p className="font-mono text-[10.5px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Per market", sv: "Per marknad" })}</p>
<div className="mt-5 flex flex-col gap-3.5">
{MARKET_KEYS.map((m, i) => (
<div key={m.code} className="flex items-center gap-3">
<span className="w-7 font-mono text-xs tabular-nums">{m.code}</span>
<div className="h-px flex-1 bg-border">
<div className="h-px bg-foreground transition-all duration-300" style={{ width: `${Math.round(markets[i])}%` }} />
</div>
<span className="w-10 text-right font-mono text-[10.5px] tabular-nums text-muted-foreground">
{Math.round(markets[i])}%
</span>
</div>
))}
</div>
</div>
{/* activity */}
<div className="px-6 py-7">
<p className="font-mono text-[10.5px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Activity", sv: "Aktivitet" })}</p>
<div className="mt-5 flex flex-col gap-2 font-mono text-[11px] leading-relaxed">
{feed.length === 0 ? <span className="text-muted-foreground">{t({ en: "Nothing yet.", sv: "Inget än." })}</span> : null}
{feed.map((f, i) => (
<div key={i} className="flex gap-3">
<span className="tabular-nums text-muted-foreground">{f.t}</span>
<span style={{ color: f.kind === "ok" ? "var(--prov-3)" : "var(--accent-red)" }}>{f.msg}</span>
</div>
))}
</div>
</div>
</aside>
</div>
{done ? (
<div className="border-t border-border py-12">
<Link
href={`/order/${id}/validera`}
className="group inline-flex items-center gap-3 bg-foreground px-7 py-4 font-mono text-[12px] uppercase tracking-[0.12em] text-background transition-colors hover:bg-[var(--accent-red)]"
>
{t({ en: "Review the result", sv: "Granska resultatet" })}
<span className="transition-transform duration-300 group-hover:translate-x-1">→</span>
</Link>
</div>
) : null}
</div>
</main>
);
}
function ConfidenceRing({ value, unitLabel }: { value: number; unitLabel: string }) {
const r = 52;
const c = 2 * Math.PI * r;
const off = c - (value / 100) * c;
return (
<svg viewBox="0 0 130 130" className="mx-auto h-40 w-40">
<circle cx="65" cy="65" r={r} fill="none" stroke="var(--secondary)" strokeWidth="6" />
<circle
cx="65" cy="65" r={r} fill="none" stroke="var(--prov-3)" strokeWidth="6"
strokeDasharray={c} strokeDashoffset={off} strokeLinecap="butt"
transform="rotate(-90 65 65)" style={{ transition: "stroke-dashoffset .3s" }}
/>
<text x="65" y="64" textAnchor="middle" className="fill-foreground font-mono" style={{ fontSize: 30, letterSpacing: "-0.02em" }}>
{Math.round(value)}
</text>
<text x="65" y="84" textAnchor="middle" className="fill-muted-foreground font-mono" style={{ fontSize: 10, letterSpacing: "0.14em" }}>
{unitLabel}
</text>
</svg>
);
}