Files
0pt/app/admin/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

136 lines
5.8 KiB
TypeScript

"use client";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { useT } from "@/components/locale-provider";
import { PortalShell, StatusPill } from "@/components/portal-shell";
import { LoadingSkeleton, ErrorState, EmptyState } from "@/components/states";
import { formatSEK } from "@/lib/data";
import { mergeOrders } from "@/lib/order-client";
interface Order {
order_id: string;
flow: string;
status: string;
total_ore: number;
deposit_ore: number;
created_at: string;
}
interface Metrics {
total: number;
in_production: number;
review: number;
delivered: number;
deposit_paid_ore: number;
pipeline_ore: number;
}
const NEXT_STATUS: Record<string, string> = {
draft: "quoted",
quoted: "in_production",
in_production: "review",
review: "accepted",
accepted: "delivered",
};
export default function AdminPage() {
const t = useT();
const [orders, setOrders] = useState<Order[] | null>(null);
const [metrics, setMetrics] = useState<Metrics | null>(null);
const [error, setError] = useState(false);
const load = useCallback(async () => {
setError(false);
try {
const [oRes, mRes] = await Promise.all([
fetch("/api/orders", { cache: "no-store" }),
fetch("/api/admin/metrics", { cache: "no-store" }),
]);
if (!oRes.ok || !mRes.ok) throw new Error("fetch failed");
const [o, m] = await Promise.all([oRes.json(), mRes.json()]);
if (!m || typeof m.total !== "number") throw new Error("bad metrics shape");
setOrders(mergeOrders(Array.isArray(o) ? o : []) as Order[]);
setMetrics(m);
} catch {
setError(true);
}
}, []);
useEffect(() => { void load(); }, [load]);
async function advance(id: string, status: string) {
const next = NEXT_STATUS[status];
if (!next) return;
try {
const r = await fetch(`/api/orders/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status: next }) });
if (r.ok) {
toast.success(`${id.slice(0, 8)}… → ${next}`);
void load();
} else {
toast.error(t({ en: "Could not advance order.", sv: "Kunde inte flytta fram ordern." }));
}
} catch {
toast.error(t({ en: "Network error.", sv: "Nätverksfel." }));
}
}
return (
<PortalShell variant="admin" title={t({ en: "Order queue & operations", sv: "Orderkö & drift" })}>
{error ? (
<ErrorState onRetry={load} />
) : !metrics || !orders ? (
<LoadingSkeleton rows={6} />
) : (
<>
<div className="grid grid-cols-2 gap-px border border-border bg-border md:grid-cols-5">
{[
[t({ en: "Orders", sv: "Ordrar" }), String(metrics.total)],
[t({ en: "In production", sv: "I produktion" }), String(metrics.in_production)],
[t({ en: "In review", sv: "Granskas" }), String(metrics.review)],
[t({ en: "Delivered", sv: "Levererade" }), String(metrics.delivered)],
[t({ en: "Deposits in", sv: "Förskott in" }), formatSEK((metrics.deposit_paid_ore || 0) / 100)],
].map(([l, v]) => (
<div key={l} className="bg-background p-5">
<p className="font-mono text-[10px] uppercase tracking-[0.12em] text-muted-foreground">{l}</p>
<p className="mt-2 text-2xl font-medium tabular-nums tracking-[-0.02em]">{v}</p>
</div>
))}
</div>
<section className="mt-10">
<h2 className="font-mono text-[11px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Order queue", sv: "Orderkö" })}</h2>
{orders.length === 0 ? (
<div className="mt-6"><EmptyState title={t({ en: "Empty queue.", sv: "Tom kö." })} line={t({ en: "No orders yet.", sv: "Inga ordrar än." })} /></div>
) : (
<div className="mt-4 border border-border">
<div className="grid grid-cols-[1.4fr_1.2fr_1fr_1fr_1.2fr] border-b border-border bg-secondary/50 px-4 py-2.5 font-mono text-[10px] uppercase tracking-[0.1em] text-muted-foreground">
<span>{t({ en: "ID", sv: "ID" })}</span><span>{t({ en: "Flow", sv: "Flöde" })}</span><span>{t({ en: "Status", sv: "Status" })}</span><span className="text-right">{t({ en: "Total", sv: "Summa" })}</span><span className="text-right">{t({ en: "Action", sv: "Åtgärd" })}</span>
</div>
{orders.map((o) => (
<div key={o.order_id} className="grid grid-cols-[1.4fr_1.2fr_1fr_1fr_1.2fr] items-center border-b border-border px-4 py-3 last:border-b-0">
<span className="font-mono text-[12px] tabular-nums">{o.order_id.slice(0, 8)}…</span>
<span className="text-sm">{o.flow}</span>
<StatusPill status={o.status} />
<span className="text-right font-mono text-[12px] tabular-nums">{formatSEK(o.total_ore / 100)}</span>
<span className="text-right">
{NEXT_STATUS[o.status] ? (
<button
onClick={() => advance(o.order_id, o.status)}
className="border border-foreground px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.08em] transition-colors hover:bg-foreground hover:text-background"
>
→ {NEXT_STATUS[o.status]}
</button>
) : (
<span className="font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">{t({ en: "done", sv: "klar" })}</span>
)}
</span>
</div>
))}
</div>
)}
</section>
</>
)}
</PortalShell>
);
}