diff --git a/app/admin/page.tsx b/app/admin/page.tsx index 95de2d7..575b4e5 100644 --- a/app/admin/page.tsx +++ b/app/admin/page.tsx @@ -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); diff --git a/app/bestall/beskriv/page.tsx b/app/bestall/beskriv/page.tsx index 5c08f96..0bf73e6 100644 --- a/app/bestall/beskriv/page.tsx +++ b/app/bestall/beskriv/page.tsx @@ -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); } diff --git a/app/bestall/page.tsx b/app/bestall/page.tsx index def616a..001cc28 100644 --- a/app/bestall/page.tsx +++ b/app/bestall/page.tsx @@ -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) => diff --git a/app/katalog/page.tsx b/app/katalog/page.tsx index e198c15..8fe7bb5 100644 --- a/app/katalog/page.tsx +++ b/app/katalog/page.tsx @@ -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(); + const router = useRouter(); const [items, setItems] = useState(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 (
@@ -118,7 +130,7 @@ export default function CatalogPage() { {formatSEK(Math.round(d.price_ore / 100))}
Visa → - Beställ +
diff --git a/app/order/[id]/page.tsx b/app/order/[id]/page.tsx index 74d5d16..68339ad 100644 --- a/app/order/[id]/page.tsx +++ b/app/order/[id]/page.tsx @@ -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 = () => { diff --git a/app/portal/page.tsx b/app/portal/page.tsx index eb4b72a..9bf1cfa 100644 --- a/app/portal/page.tsx +++ b/app/portal/page.tsx @@ -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); } }, []); diff --git a/lib/order-client.ts b/lib/order-client.ts new file mode 100644 index 0000000..2a14ed3 --- /dev/null +++ b/lib/order-client.ts @@ -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; + 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(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): Promise { + 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; +}