feat: buy everything + monitor everything in UI (client order ledger)
lib/order-client: createOrder records each order to a localStorage ledger; portal dashboard + admin queue merge it with /api/orders; order tracker falls back to it. Wired all buy paths: configurator, beskriv (custom services), and one-click catalog Beställ. Makes buy->monitor work in the browser now; becomes server-truth when Postgres is connected. tsc 0, build green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+2
-1
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from "react";
|
||||
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;
|
||||
@@ -42,7 +43,7 @@ export default function AdminPage() {
|
||||
fetch("/api/orders", { cache: "no-store" }).then((r) => r.json()),
|
||||
fetch("/api/admin/metrics", { cache: "no-store" }).then((r) => r.json()),
|
||||
]);
|
||||
setOrders(Array.isArray(o) ? o : []);
|
||||
setOrders(mergeOrders(Array.isArray(o) ? o : []) as Order[]);
|
||||
setMetrics(m);
|
||||
} catch {
|
||||
setError(true);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useEffect, useState } from "react";
|
||||
import { Header } from "@/components/header";
|
||||
import { OrderStepper } from "@/components/order-stepper";
|
||||
import { SERVICES, DESTINATIONS_CRM, serviceById } from "@/lib/services";
|
||||
import { createOrder } from "@/lib/order-client";
|
||||
|
||||
const PLACEHOLDER =
|
||||
"T.ex. \"Konsolidera vår admindata och pusha alla svenska kunder med omsättning och beslutsfattare till HubSpot\" eller \"Skrapa alla norska bolag inom bygg med e-post\".";
|
||||
@@ -39,12 +40,9 @@ export default function DescribePage() {
|
||||
setRationale(d.rationale ?? "");
|
||||
}
|
||||
} catch {}
|
||||
try {
|
||||
const flow = svc?.flow === "subscription" ? "subscription" : "custom";
|
||||
const res = await fetch("/api/orders", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ flow, config }) });
|
||||
const o = await res.json();
|
||||
if (o?.order_id) { router.push(`/bestall/forskott?order=${encodeURIComponent(o.order_id)}`); return; }
|
||||
} catch {}
|
||||
const flow = svc?.flow === "subscription" ? "subscription" : "custom";
|
||||
const id = await createOrder(flow, config);
|
||||
if (id) { router.push(`/bestall/forskott?order=${encodeURIComponent(id)}`); return; }
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
|
||||
+3
-14
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useMemo, useState, useEffect } from "react";
|
||||
import { OrderStepper } from "@/components/order-stepper";
|
||||
import { ProvenanceBadge } from "@/components/provenance-badge";
|
||||
import { createOrder } from "@/lib/order-client";
|
||||
import {
|
||||
MARKETS,
|
||||
ENTITY_TYPES,
|
||||
@@ -55,20 +56,8 @@ export default function ConfiguratorPage() {
|
||||
if (creating) return;
|
||||
setCreating(true);
|
||||
const config = { markets, type, fieldIds, enrichmentIds, volume, frequency, confidence, formats };
|
||||
try {
|
||||
const res = await fetch("/api/orders", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ flow: frequency === "Engångs" ? "custom" : "subscription", config }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data?.order_id) {
|
||||
router.push(`/bestall/forskott?order=${encodeURIComponent(data.order_id)}`);
|
||||
return;
|
||||
}
|
||||
} catch {}
|
||||
setCreating(false);
|
||||
router.push("/bestall/forskott");
|
||||
const id = await createOrder(frequency === "Engångs" ? "custom" : "subscription", config);
|
||||
router.push(id ? `/bestall/forskott?order=${encodeURIComponent(id)}` : "/bestall/forskott");
|
||||
}
|
||||
|
||||
const toggle = (arr: string[], v: string, set: (x: string[]) => void) =>
|
||||
|
||||
+13
-1
@@ -1,12 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Header } from "@/components/header";
|
||||
import { useReveal } from "@/hooks/use-reveal";
|
||||
import { CellProvenance } from "@/components/provenance-badge";
|
||||
import { LoadingSkeleton, EmptyState, ErrorState } from "@/components/states";
|
||||
import { formatSEK, type ProvLevel } from "@/lib/data";
|
||||
import { createOrder } from "@/lib/order-client";
|
||||
|
||||
interface CatalogItem {
|
||||
id: string;
|
||||
@@ -36,6 +38,7 @@ function level(c: number): ProvLevel {
|
||||
|
||||
export default function CatalogPage() {
|
||||
const ref = useReveal<HTMLDivElement>();
|
||||
const router = useRouter();
|
||||
const [items, setItems] = useState<CatalogItem[] | null>(null);
|
||||
const [err, setErr] = useState(false);
|
||||
const [filter, setFilter] = useState("all");
|
||||
@@ -60,6 +63,15 @@ export default function CatalogPage() {
|
||||
);
|
||||
}, [items, filter, q]);
|
||||
|
||||
async function buy(d: CatalogItem) {
|
||||
const id = await createOrder("catalog", {
|
||||
catalog_id: d.id, title: d.title, markets: d.markets, type: "Bolag",
|
||||
fieldIds: ["identity"], enrichmentIds: [], volume: 1000, frequency: "Engångs",
|
||||
confidence: Math.round(d.confidence * 100),
|
||||
});
|
||||
router.push(id ? `/bestall/forskott?order=${id}` : "/bestall");
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-background text-foreground">
|
||||
<Header />
|
||||
@@ -118,7 +130,7 @@ export default function CatalogPage() {
|
||||
<span className="font-mono text-sm tabular-nums">{formatSEK(Math.round(d.price_ore / 100))}</span>
|
||||
<div className="flex items-center gap-4">
|
||||
<Link href={`/katalog/${d.id}`} className="font-mono text-[11px] uppercase tracking-[0.08em] underline-offset-4 hover:underline">Visa →</Link>
|
||||
<Link href="/bestall" className="border border-foreground px-3 py-1.5 font-mono text-[11px] uppercase tracking-[0.08em] transition-colors hover:bg-foreground hover:text-background">Beställ</Link>
|
||||
<button onClick={() => buy(d)} className="border border-foreground px-3 py-1.5 font-mono text-[11px] uppercase tracking-[0.08em] transition-colors hover:bg-foreground hover:text-background">Beställ</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+11
-2
@@ -5,6 +5,7 @@ import { useParams } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { OrderStepper } from "@/components/order-stepper";
|
||||
import { useReveal } from "@/hooks/use-reveal";
|
||||
import { getLocalOrder } from "@/lib/order-client";
|
||||
|
||||
const STAGES = [
|
||||
{ key: "source", title: "Källracing", meta: "GLEIF · Brreg · CVR · PRH" },
|
||||
@@ -37,10 +38,18 @@ export default function ProductionPage() {
|
||||
const tick = useRef(0);
|
||||
const [order, setOrder] = useState<{ markets: string[]; volume: number } | null>(null);
|
||||
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) => { if (o?.config) setOrder({ markets: o.config.markets ?? [], volume: o.config.volume ?? 0 }); })
|
||||
.catch(() => {});
|
||||
.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 = () => {
|
||||
|
||||
+5
-4
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { Header } from "@/components/header";
|
||||
import { EmptyState, ErrorState, LoadingSkeleton } from "@/components/states";
|
||||
import { formatSEK } from "@/lib/data";
|
||||
import { mergeOrders, getLocalOrders } from "@/lib/order-client";
|
||||
|
||||
// Dashboard "Mina beställningar". Fetches GET /api/orders and renders the
|
||||
// customer's order ledger. Money arrives in öre; status follows the canonical
|
||||
@@ -54,11 +55,11 @@ export default function PortalPage() {
|
||||
setOrders(null);
|
||||
try {
|
||||
const res = await fetch("/api/orders", { cache: "no-store" });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const data = (await res.json()) as OrderRow[];
|
||||
setOrders(Array.isArray(data) ? data : []);
|
||||
const data = res.ok ? ((await res.json()) as OrderRow[]) : [];
|
||||
setOrders(mergeOrders(Array.isArray(data) ? data : []) as OrderRow[]);
|
||||
} catch {
|
||||
setError(true);
|
||||
const local = getLocalOrders() as unknown as OrderRow[];
|
||||
if (local.length) setOrders(local); else setError(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
// Client-side order ledger. Every buy path writes here; every monitoring surface
|
||||
// reads it merged with /api/orders. This makes buy → monitor work in the browser
|
||||
// before the database is provisioned; once POSTGRES_URL is set the API is the
|
||||
// source of truth and this becomes a local cache.
|
||||
export interface LocalOrder {
|
||||
order_id: string;
|
||||
flow: string;
|
||||
status: string;
|
||||
total_ore: number;
|
||||
deposit_ore: number;
|
||||
balance_ore: number;
|
||||
config?: Record<string, unknown>;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const KEY = "0pt-orders";
|
||||
|
||||
export function getLocalOrders(): LocalOrder[] {
|
||||
if (typeof window === "undefined") return [];
|
||||
try { return JSON.parse(localStorage.getItem(KEY) || "[]"); } catch { return []; }
|
||||
}
|
||||
|
||||
export function saveLocalOrder(o: LocalOrder): void {
|
||||
if (typeof window === "undefined") return;
|
||||
const all = getLocalOrders().filter((x) => x.order_id !== o.order_id);
|
||||
all.unshift(o);
|
||||
localStorage.setItem(KEY, JSON.stringify(all.slice(0, 200)));
|
||||
}
|
||||
|
||||
export function getLocalOrder(id: string): LocalOrder | null {
|
||||
return getLocalOrders().find((o) => o.order_id === id) ?? null;
|
||||
}
|
||||
|
||||
export function setLocalStatus(id: string, status: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
const all = getLocalOrders();
|
||||
const o = all.find((x) => x.order_id === id);
|
||||
if (o) { o.status = status; localStorage.setItem(KEY, JSON.stringify(all)); }
|
||||
}
|
||||
|
||||
/** Merge server orders with local ones (server wins on conflict). */
|
||||
export function mergeOrders<T extends { order_id: string }>(server: T[]): (T | LocalOrder)[] {
|
||||
const ids = new Set(server.map((s) => s.order_id));
|
||||
return [...server, ...getLocalOrders().filter((l) => !ids.has(l.order_id))];
|
||||
}
|
||||
|
||||
/** Create an order via the API and record it locally. Returns the id (or null). */
|
||||
export async function createOrder(flow: string, config: Record<string, unknown>): Promise<string | null> {
|
||||
try {
|
||||
const res = await fetch("/api/orders", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ flow, config }),
|
||||
});
|
||||
const o = await res.json();
|
||||
if (o?.order_id) {
|
||||
const total = o.total_ore ?? 0;
|
||||
const deposit = o.deposit_ore ?? Math.round(total / 2);
|
||||
saveLocalOrder({
|
||||
order_id: o.order_id, flow, status: "draft",
|
||||
total_ore: total, deposit_ore: deposit, balance_ore: total - deposit,
|
||||
config, created_at: new Date().toISOString(),
|
||||
});
|
||||
return o.order_id;
|
||||
}
|
||||
} catch {}
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user