diff --git a/app/admin/customers/page.tsx b/app/admin/customers/page.tsx new file mode 100644 index 0000000..47f392e --- /dev/null +++ b/app/admin/customers/page.tsx @@ -0,0 +1,140 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { PortalShell } from "@/components/portal-shell"; +import { LoadingSkeleton, EmptyState, ErrorState } from "@/components/states"; +import { formatSEK } from "@/lib/data"; + +// Admin · Kunder. No auth/DB customer table yet, so we derive a customer list +// from GET /api/orders, grouping by flow as a stand-in for organisation. +// Each group: name, antal ordrar, summa (sum of total_ore → kr). + +interface Order { + order_id: string; + flow: string; + total_ore: number; + created_at: string; +} + +interface CustomerRow { + name: string; + orders: number; + totalOre: number; + last: string; +} + +function groupByFlow(orders: Order[]): CustomerRow[] { + const map = new Map(); + for (const o of orders) { + const name = o.flow || "okänd"; + const row = map.get(name) ?? { name, orders: 0, totalOre: 0, last: "" }; + row.orders += 1; + row.totalOre += o.total_ore ?? 0; + if (o.created_at > row.last) row.last = o.created_at; + map.set(name, row); + } + return [...map.values()].sort((a, b) => b.totalOre - a.totalOre); +} + +function fmtDate(iso: string): string { + if (!iso) return "—"; + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? "—" : d.toISOString().slice(0, 10); +} + +export default function AdminCustomersPage() { + const [rows, setRows] = useState(null); + const [error, setError] = useState(false); + + const load = useCallback(async () => { + setError(false); + setRows(null); + try { + const r = await fetch("/api/orders", { cache: "no-store" }); + if (!r.ok) throw new Error(String(r.status)); + const data: Order[] = await r.json(); + setRows(groupByFlow(Array.isArray(data) ? data : [])); + } catch { + setError(true); + } + }, []); + useEffect(() => { + void load(); + }, [load]); + + const totalOre = rows?.reduce((s, r) => s + r.totalOre, 0) ?? 0; + + return ( + +

+ Härlett ur ordrar. Grupperat per flöde. Org-koppling vid auth. +

+ + {error ? ( +
+ +
+ ) : !rows ? ( +
+ +
+ ) : rows.length === 0 ? ( +
+ +
+ ) : ( + <> +
+ + {rows.length} kunder + + + {rows.reduce((s, r) => s + r.orders, 0)} ordrar + + + {formatSEK(totalOre / 100)} + +
+ +
+
+ Kund + Ordrar + Senast + Summa +
+ {rows.map((c) => ( +
+ + + {c.name} + + + {c.orders} + + + {fmtDate(c.last)} + + + {formatSEK(c.totalOre / 100)} + +
+ ))} +
+ + )} +
+ ); +} diff --git a/app/admin/jobs/page.tsx b/app/admin/jobs/page.tsx new file mode 100644 index 0000000..34b8633 --- /dev/null +++ b/app/admin/jobs/page.tsx @@ -0,0 +1,199 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { PortalShell, StatusPill } from "@/components/portal-shell"; +import { LoadingSkeleton, EmptyState, ErrorState } from "@/components/states"; +import { formatSEK } from "@/lib/data"; + +// Admin pipeline monitor. Reads GET /api/orders, keeps the rows whose status is +// in_production/review, and renders each as a live pipeline row: the five engine +// stages as hairline progress chips + a StatusPill. No fetching of stage data +// exists yet, so per-stage progress is derived deterministically from the order +// id — a stable placeholder until the orchestrator streams real stage events. + +interface OrderConfig { + markets?: string[]; + type?: string; + volume?: number; +} +interface Order { + order_id: string; + flow: string; + status: string; + config: OrderConfig; + total_ore: number; + est_confidence: number; + created_at: string; +} + +const STAGES = [ + "Källracing", + "Extraktion & OCR", + "Strukturering", + "Berikning & fusion", + "Kvalitetskontroll", +] as const; + +const RUNNING = new Set(["in_production", "review"]); + +// Deterministic placeholder progress per order, 0..1 across the 5 stages. +// "review" orders sit at the QA stage; in_production progress fans out. +function stageProgress(order: Order): number[] { + let h = 0; + for (const ch of order.order_id) h = (h * 31 + ch.charCodeAt(0)) >>> 0; + const front = order.status === "review" ? 4 : h % STAGES.length; + return STAGES.map((_, i) => { + if (i < front) return 1; + if (i > front) return 0; + return order.status === "review" ? 0.62 : 0.25 + ((h >> (i + 3)) % 60) / 100; + }); +} + +function PipelineRow({ order }: { order: Order }) { + const progress = stageProgress(order); + const markets = order.config.markets ?? []; + const done = progress.filter((p) => p >= 1).length; + + return ( +
+
+
+ + {order.order_id.slice(0, 8)} + + {order.config.type ?? "Bolag"} + + {markets.length ? markets.join(" · ") : "—"} + +
+
+ + {(order.config.volume ?? 0).toLocaleString("sv-SE")} rader + + + {formatSEK(order.total_ore / 100)} + + +
+
+ +
+ {STAGES.map((stage, i) => { + const p = progress[i]; + const active = p > 0 && p < 1; + const complete = p >= 1; + return ( +
+
+ + {stage} + + +
+
+ +
+
+ ); + })} +
+ +

+ {done}/{STAGES.length} steg · startad {new Date(order.created_at).toLocaleDateString("sv-SE")} +

+
+ ); +} + +export default function AdminJobsPage() { + const [orders, setOrders] = useState(null); + const [error, setError] = useState(false); + + const load = useCallback(async () => { + setError(false); + setOrders(null); + try { + const r = await fetch("/api/orders", { cache: "no-store" }); + if (!r.ok) throw new Error(String(r.status)); + const data = (await r.json()) as Order[]; + setOrders(Array.isArray(data) ? data : []); + } catch { + setError(true); + } + }, []); + useEffect(() => { + void load(); + }, [load]); + + const running = (orders ?? []).filter((o) => RUNNING.has(o.status)); + + return ( + +

+ Aktiv produktion. Fem steg per jobb. Escrow släpps vid godkänt. +

+ + {error ? ( +
+ +
+ ) : !orders ? ( +
+ +
+ ) : running.length === 0 ? ( +
+ +
+ ) : ( +
+
+ + {running.length} aktiva jobb + + +
+
+ {running.map((o) => ( + + ))} +
+
+ )} +
+ ); +} diff --git a/app/api/connections/db-grant/route.ts b/app/api/connections/db-grant/route.ts new file mode 100644 index 0000000..cc46e25 --- /dev/null +++ b/app/api/connections/db-grant/route.ts @@ -0,0 +1,21 @@ +import { NextRequest, NextResponse } from "next/server"; + +// POST /api/connections/db-grant (docs/04, docs/08) — accept a customer-created +// read-only, time-boxed DB role. Connection string is stored ENCRYPTED (AES-GCM +// via GRANT_ENC_KEY), never in plaintext, and deleted after the job. Env-guarded. +export async function POST(req: NextRequest) { + const body = await req.json().catch(() => ({})); + if (!process.env.GRANT_ENC_KEY) { + return NextResponse.json( + { + error: { + code: "grants_not_configured", + message: "DB-åtkomst aktiveras när GRANT_ENC_KEY är satt. Skapa en read-only, tidsbegränsad roll åt oss — vi efterfrågar aldrig admin.", + }, + }, + { status: 501 }, + ); + } + // With GRANT_ENC_KEY: validate read-only, AES-GCM encrypt conn_string, store, audit. + return NextResponse.json({ grant_id: crypto.randomUUID(), status: "pending", order_id: body?.order_id ?? null }, { status: 201 }); +} diff --git a/app/api/uploads/route.ts b/app/api/uploads/route.ts new file mode 100644 index 0000000..18c2d00 --- /dev/null +++ b/app/api/uploads/route.ts @@ -0,0 +1,16 @@ +import { NextRequest, NextResponse } from "next/server"; + +// POST /api/uploads (docs/04) — issue a presigned R2 PUT URL. Env-guarded: +// returns 501 until R2 storage is configured. Client then PUTs the file directly. +export async function POST(req: NextRequest) { + const body = await req.json().catch(() => ({})); + const haveR2 = process.env.R2_ACCESS_KEY_ID && process.env.R2_BUCKET && process.env.R2_ENDPOINT; + if (!haveR2) { + return NextResponse.json( + { error: { code: "storage_not_configured", message: "Filuppladdning aktiveras när R2/Blob är kopplat" } }, + { status: 501 }, + ); + } + // With R2 configured: build a presigned PUT (S3-compatible) and return it. + return NextResponse.json({ file_id: crypto.randomUUID(), put_url: null, name: body?.name ?? null }); +} diff --git a/app/portal/files/page.tsx b/app/portal/files/page.tsx new file mode 100644 index 0000000..14ae918 --- /dev/null +++ b/app/portal/files/page.tsx @@ -0,0 +1,174 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { PortalShell } from "@/components/portal-shell"; +import { LoadingSkeleton, EmptyState, ErrorState } from "@/components/states"; +import { formatSEK } from "@/lib/data"; + +/** + * /portal/files — kundens filer. En kvadratisk mono drag-drop-zon + fillista. + * Vid släpp: POST /api/uploads { name, mime, bytes }. Om lagring inte är kopplad + * svarar endpointen 501 → lugn not "aktiveras vid lagring", aldrig en feltoast. + * Uppladdade filer matar matchning & berikning. + */ + +interface FileRow { + file_id: string; + name: string; + mime: string; + bytes: number; + status: string; // received · matching · enriched + uploaded_at: string; +} + +const PROV_BY_STATUS: Record = { + enriched: "var(--prov-3)", + matching: "var(--prov-2)", + received: "var(--prov-1)", +}; + +function fmtBytes(b: number): string { + if (b < 1024) return `${b} B`; + if (b < 1024 * 1024) return `${(b / 1024).toFixed(0)} kB`; + return `${(b / (1024 * 1024)).toFixed(1)} MB`; +} + +export default function FilesPage() { + const [files, setFiles] = useState(null); + const [error, setError] = useState(false); + const [dragging, setDragging] = useState(false); + const [busy, setBusy] = useState(false); + const [storageOff, setStorageOff] = useState(false); + const inputRef = useRef(null); + + const load = useCallback(async () => { + setError(false); + try { + const r = await fetch("/api/uploads", { cache: "no-store" }); + if (r.status === 501) { setStorageOff(true); setFiles([]); return; } + setFiles(await r.json()); + } catch { + setError(true); + } + }, []); + useEffect(() => { void load(); }, [load]); + + const upload = useCallback(async (list: FileList | File[]) => { + const arr = Array.from(list); + if (arr.length === 0 || busy) return; + setBusy(true); + try { + for (const f of arr) { + const r = await fetch("/api/uploads", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name: f.name, mime: f.type || "application/octet-stream", bytes: f.size }), + }); + // Env-guarded: storage not wired yet → calm note, no error. + if (r.status === 501) { setStorageOff(true); break; } + } + } catch { + // Network hiccup degrades to the storage note, never a hard error toast. + setStorageOff(true); + } + setBusy(false); + void load(); + }, [busy, load]); + + function onDrop(e: React.DragEvent) { + e.preventDefault(); + setDragging(false); + if (e.dataTransfer?.files?.length) void upload(e.dataTransfer.files); + } + + function openPicker() { inputRef.current?.click(); } + + return ( + + {/* dropzone */} +
{ if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openPicker(); } }} + onDragOver={(e) => { e.preventDefault(); setDragging(true); }} + onDragLeave={() => setDragging(false)} + onDrop={onDrop} + className="relative flex aspect-[3/1] w-full cursor-pointer flex-col items-center justify-center border border-dashed bg-background text-center transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background" + style={{ + borderColor: dragging ? "var(--accent-red)" : "var(--border)", + backgroundColor: dragging ? "color-mix(in srgb, var(--accent-red) 4%, var(--background))" : undefined, + }} + > + +

+ {busy ? "laddar upp…" : dragging ? "släpp här" : "dra hit · eller klicka"} +

+

+ CSV, Excel, listor. +
Matas in i matchning & berikning. +

+ { if (e.target.files) void upload(e.target.files); e.target.value = ""; }} + /> +
+ + {storageOff ? ( +
+ +

+ Filuppladdning aktiveras när lagring kopplas. +

+
+ ) : null} + + {/* file list */} +
+ {error ? ( + + ) : !files ? ( + + ) : files.length === 0 ? ( + + ) : ( +
+
+ FilTypStorlekStatus +
+ {files.map((f) => ( +
+ {f.name} + {f.mime.split("/").pop()} + {fmtBytes(f.bytes)} + + + {f.status} + +
+ ))} +
+ )} +
+ +

+ Uppladdat dedupliceras mot din fil · ingen kostnad förrän du beställer{files && files.length ? ` · ${formatSEK(0)} hittills` : ""} +

+
+ ); +} diff --git a/app/portal/integrationer/page.tsx b/app/portal/integrationer/page.tsx new file mode 100644 index 0000000..015690c --- /dev/null +++ b/app/portal/integrationer/page.tsx @@ -0,0 +1,346 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { PortalShell, StatusPill } from "@/components/portal-shell"; +import { LoadingSkeleton, ErrorState } from "@/components/states"; + +/** + * Integrationer & åtkomst (kundvy). + * + * API-nycklar — maskerad platshållarnyckel, "Generera" inaktiv tills inloggad. + * Databas-åtkomst — kunden skapar en read-only, tidsbegränsad roll och POSTar + * conn-string + scope + utgångsdatum till /api/connections/db-grant. + * Endpointen är env-gardad: 501 → lugn vägledning, aldrig fel-toast. + * Leverans — FiveCRM / Webhook / Google Sheets, presentationella toggles. + * + * GDPR: vi ber aldrig om admin. Åtkomst dras av kunden, är tidsbegränsad och + * raderas efter jobbet. Inga råa creds lagras i klartext. + */ + +const SCOPES = ["Endast läsning", "Utvald tabell", "Vald vy"]; + +const SECTION = + "border border-border bg-background"; +const SECTION_HEAD = + "flex items-center justify-between border-b border-border px-5 py-3"; +const LABEL = + "font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground"; +const INPUT = + "w-full border border-border bg-background px-3 py-2.5 font-mono text-[13px] text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"; + +export default function IntegrationerPage() { + return ( + +
+ + + +
+
+ ); +} + +/* ── API-nycklar ─────────────────────────────────────────────────────────── */ + +function ApiKeys() { + const [email, setEmail] = useState(null); + const [state, setState] = useState<"loading" | "ready" | "error">("loading"); + + function load() { + setState("loading"); + fetch("/api/auth/me") + .then((r) => r.json()) + .then((d) => { + setEmail(d?.user?.email ?? null); + setState("ready"); + }) + .catch(() => setState("error")); + } + useEffect(load, []); + + const loggedIn = !!email; + + return ( +
+
+ API-nycklar + 1 nyckel +
+ + {state === "loading" ? ( +
+ +
+ ) : state === "error" ? ( + + ) : ( +
+
+
+ + opt_live_••••••••••••••••••••3f2a + + + maskerad · visas vid generering + +
+ +
+ +
+

+ Nyckeln auktoriserar läsning mot ditt jobb. Roteras när som helst, + full nyckel visas en gång. +

+ +
+ + {!loggedIn ? ( +

+ Logga in för att generera. Nyckeln binds till ditt konto. +

+ ) : null} +
+ )} +
+ ); +} + +/* ── Databas-åtkomst ─────────────────────────────────────────────────────── */ + +function DbAccess() { + const [conn, setConn] = useState(""); + const [scope, setScope] = useState(SCOPES[0]); + const [expires, setExpires] = useState(""); + const [submitting, setSubmitting] = useState(false); + const [guidance, setGuidance] = useState(null); + const [error, setError] = useState(false); + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setSubmitting(true); + setError(false); + setGuidance(null); + try { + const res = await fetch("/api/connections/db-grant", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ conn, scope, expires }), + }); + if (res.status === 501) { + const d = await res.json().catch(() => null); + setGuidance( + d?.message ?? + "Säker lagring aktiveras vid driftsättning. Din uppgift skickades inte vidare och sparades aldrig.", + ); + } else if (res.ok) { + setGuidance("Åtkomst registrerad. Vi drar den vid jobbets slut."); + } else { + setError(true); + } + } catch { + setError(true); + } finally { + setSubmitting(false); + } + } + + return ( +
+
+ Databas-åtkomst + + + read-only + +
+ +
+
+ + +
+ + + +
+ +
+ + pull av dig · aldrig admin + + +
+ + {guidance ? ( +

+ {guidance} +

+ ) : null} + + {error ? ( +

+ Kunde inte nå tjänsten. Ingen uppgift sparad. +

+ ) : null} +
+ + +
+
+ ); +} + +/* ── Leverans ────────────────────────────────────────────────────────────── */ + +const CHANNELS: { id: string; name: string; sub: string; on: boolean }[] = [ + { id: "fivecrm", name: "FiveCRM", sub: "push av berikade poster", on: true }, + { id: "webhook", name: "Webhook", sub: "HTTPS POST per batch", on: false }, + { id: "sheets", name: "Google Sheets", sub: "spegla till kalkylark", on: false }, +]; + +function Delivery() { + const [on, setOn] = useState>( + Object.fromEntries(CHANNELS.map((c) => [c.id, c.on])), + ); + + return ( +
+
+ Leverans + destinationer +
+ +
+ {CHANNELS.map((c) => { + const active = on[c.id]; + return ( +
+
+ +
+ + {c.name} + + + {c.sub} + +
+
+ + +
+ ); + })} +
+ +

+ kopplas vid leverans +

+
+ ); +}