fix(recovery): restore source removed by production documentation merge
This commit is contained in:
+42
@@ -0,0 +1,42 @@
|
||||
// Lightweight signed-session scaffold (HMAC-SHA256 via Web Crypto, no deps).
|
||||
// Production auth = Auth.js + Postgres adapter + OAuth (docs/02) — wired once the
|
||||
// database is provisioned. This provides the session shape + a guarded dev login.
|
||||
const enc = new TextEncoder();
|
||||
export const SESSION_COOKIE = "0pt_session";
|
||||
|
||||
function b64url(buf: ArrayBuffer | Uint8Array): string {
|
||||
const b = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
||||
let s = "";
|
||||
for (const x of b) s += String.fromCharCode(x);
|
||||
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
function fromB64url(s: string): Uint8Array {
|
||||
s = s.replace(/-/g, "+").replace(/_/g, "/");
|
||||
s += "=".repeat((4 - (s.length % 4)) % 4);
|
||||
const bin = atob(s);
|
||||
const u = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);
|
||||
return u;
|
||||
}
|
||||
async function hmacKey(): Promise<CryptoKey> {
|
||||
return crypto.subtle.importKey("raw", enc.encode(process.env.AUTH_SECRET ?? ""), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
||||
}
|
||||
|
||||
export async function signSession(payload: Record<string, unknown>): Promise<string> {
|
||||
const body = b64url(enc.encode(JSON.stringify(payload)));
|
||||
const sig = await crypto.subtle.sign("HMAC", await hmacKey(), enc.encode(body));
|
||||
return `${body}.${b64url(sig)}`;
|
||||
}
|
||||
|
||||
export async function verifySession(token: string | undefined | null): Promise<Record<string, unknown> | null> {
|
||||
if (!token || !process.env.AUTH_SECRET) return null;
|
||||
const [body, sig] = token.split(".");
|
||||
if (!body || !sig) return null;
|
||||
const ok = await crypto.subtle.verify("HMAC", await hmacKey(), fromB64url(sig) as BufferSource, enc.encode(body));
|
||||
if (!ok) return null;
|
||||
try {
|
||||
return JSON.parse(new TextDecoder().decode(fromB64url(body)));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
// Central mock data + the live-estimate pricing model shared by the order flow.
|
||||
// No real backend yet — the configurator's price/timeline/confidence come from
|
||||
// computeEstimate(); replace with a call to the FastAPI /estimates later.
|
||||
//
|
||||
// i18n: IDs/values (used as keys + in pricing logic) stay stable; only DISPLAY
|
||||
// labels are localized as { en, sv } and resolved with useT() at the render site.
|
||||
|
||||
export type ProvLevel = 0 | 1 | 2 | 3; // 0 licence/none · 1 one source · 2 partial · 3 multi-source
|
||||
export type Loc = { en: string; sv: string };
|
||||
|
||||
export interface Market {
|
||||
code: string;
|
||||
name: Loc;
|
||||
live: boolean;
|
||||
coverage: number; // %
|
||||
}
|
||||
|
||||
// 20 European markets (Nordics live first, rest coming).
|
||||
export const MARKETS: Market[] = [
|
||||
{ code: "SE", name: { en: "Sweden", sv: "Sverige" }, live: true, coverage: 98 },
|
||||
{ code: "NO", name: { en: "Norway", sv: "Norge" }, live: true, coverage: 96 },
|
||||
{ code: "DK", name: { en: "Denmark", sv: "Danmark" }, live: true, coverage: 94 },
|
||||
{ code: "FI", name: { en: "Finland", sv: "Finland" }, live: true, coverage: 89 },
|
||||
{ code: "IS", name: { en: "Iceland", sv: "Island" }, live: false, coverage: 0 },
|
||||
{ code: "NL", name: { en: "Netherlands", sv: "Nederländerna" }, live: false, coverage: 0 },
|
||||
{ code: "DE", name: { en: "Germany", sv: "Tyskland" }, live: false, coverage: 0 },
|
||||
{ code: "BE", name: { en: "Belgium", sv: "Belgien" }, live: false, coverage: 0 },
|
||||
{ code: "IE", name: { en: "Ireland", sv: "Irland" }, live: false, coverage: 0 },
|
||||
{ code: "FR", name: { en: "France", sv: "Frankrike" }, live: false, coverage: 0 },
|
||||
{ code: "GB", name: { en: "United Kingdom", sv: "Storbritannien" }, live: false, coverage: 0 },
|
||||
{ code: "AT", name: { en: "Austria", sv: "Österrike" }, live: false, coverage: 0 },
|
||||
{ code: "CH", name: { en: "Switzerland", sv: "Schweiz" }, live: false, coverage: 0 },
|
||||
{ code: "IT", name: { en: "Italy", sv: "Italien" }, live: false, coverage: 0 },
|
||||
{ code: "ES", name: { en: "Spain", sv: "Spanien" }, live: false, coverage: 0 },
|
||||
{ code: "PT", name: { en: "Portugal", sv: "Portugal" }, live: false, coverage: 0 },
|
||||
{ code: "PL", name: { en: "Poland", sv: "Polen" }, live: false, coverage: 0 },
|
||||
{ code: "CZ", name: { en: "Czechia", sv: "Tjeckien" }, live: false, coverage: 0 },
|
||||
{ code: "HU", name: { en: "Hungary", sv: "Ungern" }, live: false, coverage: 0 },
|
||||
{ code: "LU", name: { en: "Luxembourg", sv: "Luxemburg" }, live: false, coverage: 0 },
|
||||
];
|
||||
|
||||
// Stable IDs (also the stored value + pricing key). Display via entityLabel().
|
||||
export type EntityType = "Bolag" | "Beslutsfattare" | "Fordon";
|
||||
export const ENTITY_TYPES: { id: EntityType; label: Loc; mult: number }[] = [
|
||||
{ id: "Bolag", label: { en: "Companies", sv: "Bolag" }, mult: 1.0 },
|
||||
{ id: "Beslutsfattare", label: { en: "Decision-makers", sv: "Beslutsfattare" }, mult: 1.4 },
|
||||
{ id: "Fordon", label: { en: "Vehicles", sv: "Fordon" }, mult: 1.2 },
|
||||
];
|
||||
export function entityLabel(id: EntityType): Loc {
|
||||
return ENTITY_TYPES.find((e) => e.id === id)?.label ?? { en: id, sv: id };
|
||||
}
|
||||
|
||||
export interface Field {
|
||||
id: string;
|
||||
name: Loc;
|
||||
sub: Loc;
|
||||
level: ProvLevel;
|
||||
source: Loc;
|
||||
freshness: Loc;
|
||||
weight: number;
|
||||
locked?: boolean;
|
||||
}
|
||||
|
||||
// Each field carries its honest provenance: source · freshness · confidence level.
|
||||
export const FIELDS: Field[] = [
|
||||
{ id: "identity", name: { en: "Identity & registered office", sv: "Identitet & säte" }, sub: { en: "reg. no., name, address", sv: "org.nr, namn, adress" }, level: 3, source: { en: "GLEIF · Brreg", sv: "GLEIF · Brreg" }, freshness: { en: "daily", sv: "daglig" }, weight: 1.0, locked: true },
|
||||
{ id: "lei", name: { en: "LEI / cross-border key", sv: "LEI / cross-border-nyckel" }, sub: { en: "GLEIF golden copy", sv: "GLEIF golden copy" }, level: 3, source: { en: "GLEIF", sv: "GLEIF" }, freshness: { en: "daily", sv: "daglig" }, weight: 0.8 },
|
||||
{ id: "financials", name: { en: "Financials", sv: "Finansiellt" }, sub: { en: "revenue, profit, key ratios", sv: "omsättning, resultat, nyckeltal" }, level: 2, source: { en: "register", sv: "register" }, freshness: { en: "annual", sv: "årlig" }, weight: 1.6 },
|
||||
{ id: "ubo", name: { en: "Beneficial owner (UBO)", sv: "Verklig huvudman (UBO)" }, sub: { en: "ownership chain", sv: "ägarkedja" }, level: 2, source: { en: "register", sv: "register" }, freshness: { en: "on change", sv: "vid ändring" }, weight: 1.4 },
|
||||
{ id: "contact", name: { en: "Contact: email & phone", sv: "Kontakt: e-post & telefon" }, sub: { en: "licence required in DE/FR", sv: "licens krävs i DE/FR" }, level: 1, source: { en: "public web", sv: "publik webb" }, freshness: { en: "weekly", sv: "veckovis" }, weight: 1.8 },
|
||||
{ id: "intent", name: { en: "Buying signals & intent", sv: "Köpsignaler & intent" }, sub: { en: "job ads, news, tech", sv: "jobbannonser, nyheter, tech" }, level: 1, source: { en: "web", sv: "webb" }, freshness: { en: "weekly", sv: "veckovis" }, weight: 1.5 },
|
||||
];
|
||||
|
||||
export interface Enrichment {
|
||||
id: string;
|
||||
label: Loc;
|
||||
weight: number;
|
||||
}
|
||||
export const ENRICHMENTS: Enrichment[] = [
|
||||
{ id: "dedup", label: { en: "Dedup against my file", sv: "Dedup mot min fil" }, weight: 0.1 },
|
||||
{ id: "crm", label: { en: "Match & enrich my CRM export", sv: "Matcha & berika min CRM-export" }, weight: 0.2 },
|
||||
{ id: "sanctions", label: { en: "Sanctions / PEP flag", sv: "Sanktioner / PEP-flagg" }, weight: 0.15 },
|
||||
{ id: "nace", label: { en: "Industry class (NACE/SNI)", sv: "Branschklassning (NACE/SNI)" }, weight: 0.1 },
|
||||
{ id: "tech", label: { en: "Website & tech stack", sv: "Webbplats & teknikstack" }, weight: 0.15 },
|
||||
];
|
||||
|
||||
// Stable values (stored + used by computeEstimate); display via FREQUENCY_LABEL.
|
||||
export type Frequency = "Engångs" | "Veckovis" | "Dagligt flöde";
|
||||
export const FREQUENCIES: Frequency[] = ["Engångs", "Veckovis", "Dagligt flöde"];
|
||||
export const FREQUENCY_LABEL: Record<Frequency, Loc> = {
|
||||
"Engångs": { en: "One-time", sv: "Engångs" },
|
||||
"Veckovis": { en: "Weekly", sv: "Veckovis" },
|
||||
"Dagligt flöde": { en: "Daily feed", sv: "Dagligt flöde" },
|
||||
};
|
||||
|
||||
// Stable values (stored in config.formats); display via FORMAT_LABEL.
|
||||
export const DELIVERY_FORMATS = [
|
||||
"CSV",
|
||||
"Tabellvy (NocoDB)",
|
||||
"Parquet",
|
||||
"JSON",
|
||||
"Dashboard (Metabase)",
|
||||
"API / webhook",
|
||||
"Push → FiveCRM",
|
||||
];
|
||||
export const FORMAT_LABEL: Record<string, Loc> = {
|
||||
"CSV": { en: "CSV", sv: "CSV" },
|
||||
"Tabellvy (NocoDB)": { en: "Table view (NocoDB)", sv: "Tabellvy (NocoDB)" },
|
||||
"Parquet": { en: "Parquet", sv: "Parquet" },
|
||||
"JSON": { en: "JSON", sv: "JSON" },
|
||||
"Dashboard (Metabase)": { en: "Dashboard (Metabase)", sv: "Dashboard (Metabase)" },
|
||||
"API / webhook": { en: "API / webhook", sv: "API / webhook" },
|
||||
"Push → FiveCRM": { en: "Push → FiveCRM", sv: "Push → FiveCRM" },
|
||||
};
|
||||
|
||||
const FIELD_RATE = 240; // kr per field-weight per 1000 rows per market
|
||||
|
||||
export interface EstimateInput {
|
||||
markets: string[];
|
||||
type: EntityType;
|
||||
fieldIds: string[];
|
||||
enrichmentIds: string[];
|
||||
volume: number;
|
||||
frequency: Frequency;
|
||||
confidence: number; // target 80–99
|
||||
serviceMult?: number; // service-type price multiplier (see lib/services)
|
||||
}
|
||||
|
||||
export interface Estimate {
|
||||
price: number;
|
||||
deposit: number;
|
||||
remainder: number;
|
||||
timelineDays: number;
|
||||
estConfidence: number;
|
||||
recurring: boolean;
|
||||
}
|
||||
|
||||
export function computeEstimate(input: EstimateInput): Estimate {
|
||||
const markets = Math.max(1, input.markets.length);
|
||||
const fields = FIELDS.filter((f) => input.fieldIds.includes(f.id) || f.locked);
|
||||
const fieldWeight = fields.reduce((s, f) => s + f.weight, 0) || 1;
|
||||
const entityMult = ENTITY_TYPES.find((e) => e.id === input.type)?.mult ?? 1;
|
||||
const confidenceMult = 1 + Math.max(0, input.confidence - 90) * 0.03;
|
||||
const enrichWeight = ENRICHMENTS.filter((e) => input.enrichmentIds.includes(e.id)).reduce((s, e) => s + e.weight, 0);
|
||||
|
||||
const serviceMult = input.serviceMult ?? 1;
|
||||
const base = fieldWeight * markets * FIELD_RATE * (input.volume / 1000) * entityMult * confidenceMult * serviceMult;
|
||||
const price = Math.round((base * (1 + enrichWeight)) / 5) * 5; // round to 5 kr
|
||||
const deposit = Math.round(price / 2);
|
||||
|
||||
const timelineDays = Math.min(
|
||||
14,
|
||||
Math.max(1, Math.round(1 + markets * 0.4 + input.volume / 6000 + fields.length * 0.25)),
|
||||
);
|
||||
|
||||
// Honest estimated confidence: bounded by the provenance of the chosen fields.
|
||||
const avgLevel = fields.reduce((s, f) => s + f.level, 0) / fields.length; // 0..3
|
||||
const fieldCeiling = Math.round(82 + avgLevel * 5); // ~82..97
|
||||
const estConfidence = Math.min(input.confidence, fieldCeiling);
|
||||
|
||||
return {
|
||||
price,
|
||||
deposit,
|
||||
remainder: price - deposit,
|
||||
timelineDays,
|
||||
estConfidence,
|
||||
recurring: input.frequency !== "Engångs",
|
||||
};
|
||||
}
|
||||
|
||||
export function formatSEK(n: number): string {
|
||||
return new Intl.NumberFormat("sv-SE").format(Math.round(n)) + " kr";
|
||||
}
|
||||
|
||||
// Sample Nordic rows reused by the validation table.
|
||||
export interface SampleRow {
|
||||
orgnr: string;
|
||||
bolag: string;
|
||||
sate: string;
|
||||
sni: string;
|
||||
anstallda: number;
|
||||
oms: number; // tkr
|
||||
epost: string;
|
||||
epostLevel: ProvLevel;
|
||||
lei: string;
|
||||
}
|
||||
export const SAMPLE_ROWS: SampleRow[] = [
|
||||
{ orgnr: "556016-0680", bolag: "Volvo Group", sate: "Göteborg", sni: "29100", anstallda: 95000, oms: 553000000, epost: "info@volvo.com", epostLevel: 2, lei: "5493000XYZ..." },
|
||||
{ orgnr: "556036-0793", bolag: "Spotify AB", sate: "Stockholm", sni: "63110", anstallda: 9800, oms: 132000000, epost: "press@spotify.com", epostLevel: 2, lei: "549300ABC..." },
|
||||
{ orgnr: "915933149", bolag: "Equinor ASA", sate: "Stavanger", sni: "06100", anstallda: 22000, oms: 980000000, epost: "kontakt@equinor.no", epostLevel: 1, lei: "549300NOR..." },
|
||||
{ orgnr: "25052943", bolag: "Maersk A/S", sate: "København", sni: "50200", anstallda: 100000, oms: 510000000, epost: "info@maersk.dk", epostLevel: 1, lei: "549300DNK..." },
|
||||
{ orgnr: "0112038-9", bolag: "Nokia Oyj", sate: "Espoo", sni: "26300", anstallda: 86000, oms: 221000000, epost: "", epostLevel: 0, lei: "549300FIN..." },
|
||||
];
|
||||
@@ -0,0 +1,73 @@
|
||||
import postgres from "postgres";
|
||||
import { resolveStoreMode } from "@/src/platform/dependency-mode";
|
||||
|
||||
// Lazy, env-guarded Postgres client. Works with Vercel Postgres (POSTGRES_URL)
|
||||
// or any DATABASE_URL. Returns null when no DB is configured so the app still
|
||||
// builds/runs (with in-memory fallback) before storage is provisioned.
|
||||
let _sql: ReturnType<typeof postgres> | null = null;
|
||||
|
||||
export function dbUrl(): string | undefined {
|
||||
return process.env.DATABASE_URL || process.env.POSTGRES_URL || process.env.POSTGRES_PRISMA_URL;
|
||||
}
|
||||
|
||||
export function hasDb(): boolean {
|
||||
return Boolean(dbUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* P014 fix: `ssl` used to be hardcoded to `"require"` unconditionally. That
|
||||
* is the right default for every REAL deployment target this app has
|
||||
* (Vercel Postgres, managed Postgres providers), but it made `compose.dev.yaml`'s
|
||||
* local Postgres container -- which speaks plain, non-TLS Postgres -- and
|
||||
* ANY other throwaway/local Postgres (e.g. a restore-drill target) silently
|
||||
* unreachable via this function, contradicting that file's own doc comment
|
||||
* ("local-only Postgres for developers who want real persistence") and its
|
||||
* own "UNVERIFIED... not smoke-tested end to end" caveat -- this is
|
||||
* precisely why it was never smoke-tested: it could not have worked.
|
||||
* `DATABASE_SSL` is opt-in-to-disable ONLY; absence (the default, matching
|
||||
* every existing deployment's actual env) keeps the exact prior behavior.
|
||||
*/
|
||||
export function sslMode(): "require" | false {
|
||||
const raw = process.env.DATABASE_SSL?.trim().toLowerCase();
|
||||
if (raw === "false" || raw === "disable" || raw === "off" || raw === "0") return false;
|
||||
return "require";
|
||||
}
|
||||
|
||||
export function getSql() {
|
||||
const url = dbUrl();
|
||||
if (!url) return null;
|
||||
if (!_sql) {
|
||||
_sql = postgres(url, { prepare: false, idle_timeout: 20, max: 5, ssl: sslMode() });
|
||||
}
|
||||
return _sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Durable-store accessor for the legacy Next.js stores (`lib/orders-store.ts`,
|
||||
* `lib/subscriptions-store.ts`).
|
||||
*
|
||||
* Those stores predate `src/platform/dependency-mode.ts` and still call
|
||||
* `getSql()` directly, so when no database is configured they silently fall
|
||||
* back to module-global `Map`s. For orders, payments and subscriptions that is
|
||||
* not a degraded mode, it is invisible data loss: the API accepts an order,
|
||||
* returns 201, and the row evaporates on the next restart or on any other
|
||||
* container replica. Money-bearing state must never have a process-memory
|
||||
* "success" path in production.
|
||||
*
|
||||
* This routes those stores through the SAME decision every `src/repositories/*`
|
||||
* store already uses — `resolveStoreMode` — rather than re-implementing a
|
||||
* second production check. Reusing it matters for more than tidiness:
|
||||
* `isProductionRuntime` deliberately exempts `NEXT_PHASE=phase-production-build`,
|
||||
* because `next build` runs page-data collection under NODE_ENV=production
|
||||
* while serving nothing. A naive `process.env.NODE_ENV === "production"` test
|
||||
* here would fail the BUILD instead of protecting a request path.
|
||||
*
|
||||
* Returns a `sql` client when a database is configured, `null` outside
|
||||
* production when it is not (keeping the in-memory seam for tests/local dev),
|
||||
* and throws `SiaxError("DEPENDENCY_UNAVAILABLE")` in a production runtime.
|
||||
*/
|
||||
export function getSqlForDurableStore(storeName: string) {
|
||||
const mode = resolveStoreMode(storeName, dbUrl());
|
||||
if (mode.mode === "memory") return null;
|
||||
return getSql();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Bridge from the Vercel edge (Next route handlers) to the FastAPI data engine
|
||||
// (services/api) running on the VPS. When ENGINE_URL is set, the edge defers to
|
||||
// the engine as the single source of truth; otherwise it computes locally.
|
||||
export function hasEngine(): boolean {
|
||||
return Boolean(process.env.ENGINE_URL);
|
||||
}
|
||||
|
||||
export async function engineFetch(path: string, init?: RequestInit): Promise<Response | null> {
|
||||
const base = process.env.ENGINE_URL;
|
||||
if (!base) return null;
|
||||
try {
|
||||
return await fetch(`${base}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Internal-Token": process.env.INTERNAL_TOKEN ?? "",
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
// Dependency health probes shared by GET /api/health (liveness) and
|
||||
// GET /api/ready (readiness). See docs/architecture/ARCHITECTURE.md
|
||||
// "Hälsokontroll" and BACKLOG P0-3 for the finding this fixes: the old
|
||||
// /api/health handler only ever checked *presence* of an env var and
|
||||
// hardcoded `ok: true` regardless of whether anything was actually
|
||||
// reachable -- "an uptime monitor watching HTTP 200 would show green for a
|
||||
// dying instance". Each check below returns one of four honest states:
|
||||
//
|
||||
// "ok" -- configured AND a live round trip succeeded.
|
||||
// "error" -- configured but the round trip failed (bad creds,
|
||||
// host unreachable, timeout, ...). detail carries the
|
||||
// underlying error message.
|
||||
// "not_configured" -- no env var set. Not a failure by itself (0pt is
|
||||
// designed to build/boot with everything unset).
|
||||
// "not_integrated" -- env var IS set, but no client code in this repo
|
||||
// actually uses it (currently only REDIS_URL/queue --
|
||||
// see .env.example). Reporting "ok" here would be a
|
||||
// fabricated check; reporting "not_configured" would
|
||||
// hide that a value was provided. This is its own
|
||||
// honest state rather than either of those two.
|
||||
import net from "node:net";
|
||||
import tls from "node:tls";
|
||||
import { dbUrl, getSql } from "./db";
|
||||
import { getStripe } from "./stripe";
|
||||
import { hasEngine } from "./engine";
|
||||
|
||||
export type DepStatus = "ok" | "error" | "not_configured" | "not_integrated";
|
||||
|
||||
export interface DepResult {
|
||||
status: DepStatus;
|
||||
detail?: string;
|
||||
latencyMs?: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 2000;
|
||||
|
||||
function errMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
|
||||
promise.then(
|
||||
(v) => {
|
||||
clearTimeout(timer);
|
||||
resolve(v);
|
||||
},
|
||||
(e) => {
|
||||
clearTimeout(timer);
|
||||
reject(e);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Minimal shape of the one call site needs from the postgres client --
|
||||
// matches `postgres`'s tagged-template callable, but kept narrow so tests
|
||||
// can inject a fake without constructing a real `postgres.Sql`.
|
||||
export type SqlPing = (strings: TemplateStringsArray, ...values: unknown[]) => Promise<unknown>;
|
||||
|
||||
/**
|
||||
* Postgres reachability. `select 1` is the standard zero-cost liveness query
|
||||
* -- it never touches application tables, so it can't fail on schema drift.
|
||||
*/
|
||||
export async function checkDatabase(
|
||||
sqlClient: SqlPing | null = getSql() as unknown as SqlPing | null,
|
||||
timeoutMs: number = DEFAULT_TIMEOUT_MS,
|
||||
): Promise<DepResult> {
|
||||
if (!dbUrl() || !sqlClient) return { status: "not_configured" };
|
||||
const start = Date.now();
|
||||
try {
|
||||
await withTimeout(sqlClient`select 1`, timeoutMs, "database ping");
|
||||
return { status: "ok", latencyMs: Date.now() - start };
|
||||
} catch (err) {
|
||||
return { status: "error", detail: errMessage(err), latencyMs: Date.now() - start };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* FastAPI data engine (services/api) reachability via its own `GET /health`
|
||||
* (services/api/orchestrator/main.py). Uses a real HTTP round trip, not just
|
||||
* `hasEngine()` presence -- ENGINE_URL pointing at a dead host used to read
|
||||
* as healthy.
|
||||
*/
|
||||
export async function checkEngine(
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
timeoutMs: number = DEFAULT_TIMEOUT_MS,
|
||||
): Promise<DepResult> {
|
||||
if (!hasEngine()) return { status: "not_configured" };
|
||||
const base = process.env.ENGINE_URL as string;
|
||||
const start = Date.now();
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const res = await fetchImpl(`${base}/health`, {
|
||||
signal: controller.signal,
|
||||
cache: "no-store",
|
||||
headers: { "X-Internal-Token": process.env.INTERNAL_TOKEN ?? "" },
|
||||
});
|
||||
if (!res.ok) {
|
||||
return { status: "error", detail: `HTTP ${res.status}`, latencyMs: Date.now() - start };
|
||||
}
|
||||
return { status: "ok", latencyMs: Date.now() - start };
|
||||
} catch (err) {
|
||||
return { status: "error", detail: errMessage(err), latencyMs: Date.now() - start };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
// Minimal shape of the one Stripe call this needs -- matches
|
||||
// `Stripe#balance.retrieve`, kept narrow so tests can inject a fake instead
|
||||
// of constructing a real Stripe client.
|
||||
export interface StripeBalanceClient {
|
||||
balance: { retrieve(): Promise<unknown> };
|
||||
}
|
||||
|
||||
/**
|
||||
* Stripe reachability. `balance.retrieve()` is Stripe's documented
|
||||
* lightweight "is this key valid and can I reach the API" call -- it makes
|
||||
* one real API round trip (catching e.g. a revoked/placeholder key) without
|
||||
* mutating anything or touching a specific resource.
|
||||
*/
|
||||
export async function checkStripe(
|
||||
client: StripeBalanceClient | null = getStripe() as unknown as StripeBalanceClient | null,
|
||||
timeoutMs: number = DEFAULT_TIMEOUT_MS,
|
||||
): Promise<DepResult> {
|
||||
if (!client) return { status: "not_configured" };
|
||||
const start = Date.now();
|
||||
try {
|
||||
await withTimeout(client.balance.retrieve(), timeoutMs, "stripe balance.retrieve");
|
||||
return { status: "ok", latencyMs: Date.now() - start };
|
||||
} catch (err) {
|
||||
return { status: "error", detail: errMessage(err), latencyMs: Date.now() - start };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Redis/queue reachability.
|
||||
*
|
||||
* This used to report `not_integrated` because no code opened REDIS_URL. The
|
||||
* readiness probe now performs a real round trip (AUTH when the URL carries a
|
||||
* password, then PING -> +PONG) using only `node:net`/`node:tls`, so a queue
|
||||
* that is configured but dead fails readiness instead of hiding behind
|
||||
* `not_integrated`. The probe is injectable for tests.
|
||||
*/
|
||||
export type QueueProbe = (redisUrl: string, timeoutMs: number) => Promise<void>;
|
||||
|
||||
export function redisPing(redisUrl: string, timeoutMs: number): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(redisUrl);
|
||||
} catch {
|
||||
reject(new Error("Invalid REDIS_URL"));
|
||||
return;
|
||||
}
|
||||
if (url.protocol !== "redis:" && url.protocol !== "rediss:") {
|
||||
reject(new Error("Unsupported REDIS_URL scheme"));
|
||||
return;
|
||||
}
|
||||
const port = url.port ? Number(url.port) : 6379;
|
||||
if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
|
||||
reject(new Error("Invalid REDIS_URL port"));
|
||||
return;
|
||||
}
|
||||
const socket =
|
||||
url.protocol === "rediss:"
|
||||
? tls.connect({ host: url.hostname, port, servername: url.hostname })
|
||||
: net.connect({ host: url.hostname, port });
|
||||
let settled = false;
|
||||
const done = (error?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
socket.destroy();
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
};
|
||||
const timer = setTimeout(() => done(new Error("redis ping timed out")), timeoutMs);
|
||||
let buffer = "";
|
||||
socket.on("error", (error: Error) => done(error));
|
||||
socket.on("close", () => {
|
||||
if (!settled) done(new Error("redis connection closed before PONG"));
|
||||
});
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
buffer += chunk.toString("utf8");
|
||||
if (buffer.includes("+PONG")) {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
if (buffer.startsWith("-")) {
|
||||
done(new Error(`redis error: ${buffer.trim()}`));
|
||||
return;
|
||||
}
|
||||
// AUTH succeeded (or was unnecessary) but PING has not answered yet.
|
||||
});
|
||||
socket.on("connect", () => {
|
||||
const password = url.password ? decodeURIComponent(url.password) : "";
|
||||
if (url.username && url.username !== "default" && !password) {
|
||||
done(new Error("redis username without password is not supported"));
|
||||
return;
|
||||
}
|
||||
// RESP arrays: correct for any password content, unlike inline commands.
|
||||
const encode = (parts: string[]): string =>
|
||||
`*${parts.length}\r\n${parts
|
||||
.map((part) => `$${Buffer.byteLength(part, "utf8")}\r\n${part}\r\n`)
|
||||
.join("")}`;
|
||||
const payload =
|
||||
(password ? encode(["AUTH", password]) : "") + encode(["PING"]);
|
||||
socket.write(payload);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkQueue(
|
||||
probe: QueueProbe = redisPing,
|
||||
timeoutMs: number = DEFAULT_TIMEOUT_MS,
|
||||
): Promise<DepResult> {
|
||||
const redisUrl = process.env.REDIS_URL;
|
||||
if (!redisUrl) return { status: "not_configured" };
|
||||
const start = Date.now();
|
||||
try {
|
||||
await withTimeout(probe(redisUrl, timeoutMs), timeoutMs + 250, "redis ping");
|
||||
return { status: "ok", latencyMs: Date.now() - start };
|
||||
} catch (err) {
|
||||
return { status: "error", detail: errMessage(err), latencyMs: Date.now() - start };
|
||||
}
|
||||
}
|
||||
|
||||
export interface DependencyResults {
|
||||
db: DepResult;
|
||||
engine: DepResult;
|
||||
stripe: DepResult;
|
||||
queue: DepResult;
|
||||
}
|
||||
|
||||
export async function checkAllDependencies(): Promise<DependencyResults> {
|
||||
const [db, engine, stripe, queue] = await Promise.all([
|
||||
checkDatabase(),
|
||||
checkEngine(),
|
||||
checkStripe(),
|
||||
checkQueue(),
|
||||
]);
|
||||
return { db, engine, stripe, queue };
|
||||
}
|
||||
|
||||
/** True when any dependency that IS configured/integrated is broken. */
|
||||
export function hasDegradedDependency(deps: DependencyResults): boolean {
|
||||
return Object.values(deps).some((d) => d.status === "error");
|
||||
}
|
||||
|
||||
/**
|
||||
* Readiness (unlike liveness) treats "not configured" for the deps this app
|
||||
* cannot serve real traffic without as not-ready too. `db` is the only
|
||||
* dependency that is load-bearing merely by being absent -- engine/stripe/
|
||||
* queue are optional integrations the app is designed to run WITHOUT (see
|
||||
* .env.example), so "not_configured" for those stays ready.
|
||||
*
|
||||
* But "optional to run without" is not the same as "optional to run BROKEN".
|
||||
* A dependency in the "error" state was deliberately configured by an
|
||||
* operator AND then failed a live round trip -- somebody asked for it and it
|
||||
* is not answering. Readiness fails closed on that too.
|
||||
*
|
||||
* Measured 2026-09-25 on the production deployment (0pt.app / api.0pt.app),
|
||||
* which is exactly the hole this closes:
|
||||
*
|
||||
* GET /api/health -> HTTP 200 {"ok":false, ..., "engine":"error",
|
||||
* "detail":{"engine":"This operation was aborted"}}
|
||||
* GET /api/ready -> HTTP 200 {"ready":true, "db":"ok", "engine":"error"}
|
||||
*
|
||||
* ENGINE_URL pointed at `http://0pt-engine:8000`, a hostname with no DNS
|
||||
* record anywhere on the fleet (`getent hosts 0pt-engine` -> nothing; no such
|
||||
* container on server5-11). The data engine -- 0pt's whole product -- had
|
||||
* been absent for the container's entire 17.9 h uptime, and every signal
|
||||
* above it was green. `ok:false` in a 200 body is not a signal; nothing reads
|
||||
* bodies.
|
||||
*/
|
||||
export function isReady(deps: DependencyResults): boolean {
|
||||
if (deps.db.status !== "ok") return false;
|
||||
return !Object.values(deps).some((d) => d.status === "error");
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// DES1GN ADR D3 (§31): bulk-import dispatch-policy — ETT objekt, en sanning.
|
||||
//
|
||||
// Import-routen (/api/orders/import) är inline-exekvering med hårt tak. Rader
|
||||
// över maxRows är DES1GN D3:s signal för N0D-dispatch (job_type
|
||||
// 0pt.import_execute_job / capability 0pt.import_execute i n0d:s
|
||||
// JOB_TYPE_REGISTRY). TILLS descriptor-gaten släpper (N0D-worker
|
||||
// UNVERIFIED) svarar routen 413 med n0d_dispatch_required + hint — aldrig
|
||||
// tyst trunkering, aldrig tyst dispatch.
|
||||
export const IMPORT_DISPATCH_POLICY = {
|
||||
/** Inline-tak i import-routen (oförändrat beteendekontrakt, 0pt#53). */
|
||||
maxInlineRows: 500,
|
||||
/** N0D-dispatch-signal: rader över detta är ett N0D-jobb, inget HTTP-anrop. */
|
||||
maxRows: 5000,
|
||||
/** Byte-tak för hela CSV-kroppen (UTF-8). */
|
||||
maxBytes: 1_000_000,
|
||||
/** Format-allowlist — endast RFC 4180 CSV i dag. */
|
||||
allowedFormats: ["csv"] as readonly string[],
|
||||
} as const;
|
||||
|
||||
export type ImportDispatchPolicy = typeof IMPORT_DISPATCH_POLICY;
|
||||
|
||||
export type ImportDispatchVerdict =
|
||||
| { verdict: "inline" }
|
||||
| { verdict: "unsupported_format"; format: string }
|
||||
| { verdict: "byte_cap_exceeded"; bytes: number; maxBytes: number }
|
||||
| { verdict: "row_cap_exceeded"; rows: number; maxInlineRows: number }
|
||||
| { verdict: "dispatch_n0d"; rows: number; maxRows: number };
|
||||
|
||||
/** Ren funktion — inga I/O, fullt deterministisk, testad per kombination. */
|
||||
export function evaluateImportDispatch(
|
||||
input: { format: string; bytes: number; rows: number },
|
||||
policy: ImportDispatchPolicy = IMPORT_DISPATCH_POLICY,
|
||||
): ImportDispatchVerdict {
|
||||
if (!policy.allowedFormats.includes(input.format)) {
|
||||
return { verdict: "unsupported_format", format: input.format };
|
||||
}
|
||||
if (input.bytes > policy.maxBytes) {
|
||||
return { verdict: "byte_cap_exceeded", bytes: input.bytes, maxBytes: policy.maxBytes };
|
||||
}
|
||||
if (input.rows > policy.maxRows) {
|
||||
return { verdict: "dispatch_n0d", rows: input.rows, maxRows: policy.maxRows };
|
||||
}
|
||||
if (input.rows > policy.maxInlineRows) {
|
||||
return { verdict: "row_cap_exceeded", rows: input.rows, maxInlineRows: policy.maxInlineRows };
|
||||
}
|
||||
return { verdict: "inline" };
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Zitadel OIDC Authorization Code + PKCE for the 0pt portal.
|
||||
*
|
||||
* The portal previously had no way to obtain a verified principal: the
|
||||
* `/api/0pt/*` routes require a Bearer token, but the browser only had the
|
||||
* dev-only HMAC session cookie. This module implements the standard web login
|
||||
* so a real user can reach the document workspace.
|
||||
*
|
||||
* Secrets (client id/secret, AUTH_SECRET) are server-only env values.
|
||||
*/
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';
|
||||
import { deriveTenantId, zitadelIssuer } from '@/src/auth/zitadel';
|
||||
|
||||
export const OIDC_STATE_COOKIE = '0pt_oidc';
|
||||
export const OIDC_SESSION_TTL_SECONDS = 60 * 60 * 24 * 7;
|
||||
|
||||
export interface OidcConfig {
|
||||
issuer: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
redirectUri: string;
|
||||
}
|
||||
|
||||
export function appBaseUrl(): string {
|
||||
const configured = process.env.NEXT_PUBLIC_APP_URL;
|
||||
if (configured && /^https?:\/\//.test(configured)) return configured.replace(/\/+$/, '');
|
||||
return 'http://localhost:3000';
|
||||
}
|
||||
|
||||
export function readOidcConfig(): OidcConfig | undefined {
|
||||
const issuer = (process.env.ZITADEL_ISSUER || zitadelIssuer()).replace(/\/+$/, '');
|
||||
const clientId = process.env.ZITADEL_OIDC_CLIENT_ID;
|
||||
const clientSecret = process.env.ZITADEL_OIDC_CLIENT_SECRET;
|
||||
if (!clientId || !clientSecret || !/^https:\/\//.test(issuer)) return undefined;
|
||||
return {
|
||||
issuer,
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri: `${appBaseUrl()}/api/auth/callback`,
|
||||
};
|
||||
}
|
||||
|
||||
function base64url(buffer: Buffer): string {
|
||||
return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
export function createPkce(): { verifier: string; challenge: string } {
|
||||
const verifier = base64url(randomBytes(48));
|
||||
const challenge = base64url(createHash('sha256').update(verifier).digest());
|
||||
return { verifier, challenge };
|
||||
}
|
||||
|
||||
export function createOidcState(): { state: string; nonce: string } {
|
||||
return { state: base64url(randomBytes(24)), nonce: base64url(randomBytes(24)) };
|
||||
}
|
||||
|
||||
export function authorizeUrl(config: OidcConfig, state: string, nonce: string, challenge: string): string {
|
||||
const params = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: config.redirectUri,
|
||||
response_type: 'code',
|
||||
scope: 'openid profile email urn:zitadel:iam:user:resourceowner',
|
||||
state,
|
||||
nonce,
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
return `${config.issuer}/oauth/v2/authorize?${params.toString()}`;
|
||||
}
|
||||
|
||||
interface TokenResponse {
|
||||
id_token?: unknown;
|
||||
access_token?: unknown;
|
||||
token_type?: unknown;
|
||||
}
|
||||
|
||||
export async function exchangeCode(
|
||||
config: OidcConfig,
|
||||
code: string,
|
||||
verifier: string,
|
||||
): Promise<{ idToken: string; accessToken?: string }> {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: config.redirectUri,
|
||||
client_id: config.clientId,
|
||||
client_secret: config.clientSecret,
|
||||
code_verifier: verifier,
|
||||
});
|
||||
const response = await fetch(`${config.issuer}/oauth/v2/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
cache: 'no-store',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!response.ok) throw new Error('token_exchange_failed');
|
||||
const data = (await response.json()) as TokenResponse;
|
||||
if (typeof data.id_token !== 'string' || !data.id_token) {
|
||||
throw new Error('token_missing_id_token');
|
||||
}
|
||||
return {
|
||||
idToken: data.id_token,
|
||||
...(typeof data.access_token === 'string' ? { accessToken: data.access_token } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
let jwks: ReturnType<typeof createRemoteJWKSet> | undefined;
|
||||
let jwksIssuer: string | undefined;
|
||||
|
||||
function keySet(issuer: string) {
|
||||
if (!jwks || jwksIssuer !== issuer) {
|
||||
jwks = createRemoteJWKSet(new URL(`${issuer}/oauth/v2/keys`));
|
||||
jwksIssuer = issuer;
|
||||
}
|
||||
return jwks;
|
||||
}
|
||||
|
||||
export interface VerifiedIdToken {
|
||||
sub: string;
|
||||
tenantId: string;
|
||||
email?: string;
|
||||
claims: JWTPayload;
|
||||
}
|
||||
|
||||
export async function verifyIdToken(
|
||||
config: OidcConfig,
|
||||
idToken: string,
|
||||
expectedNonce: string,
|
||||
accessToken?: string,
|
||||
): Promise<VerifiedIdToken> {
|
||||
const { payload } = await jwtVerify(idToken, keySet(config.issuer), {
|
||||
issuer: config.issuer,
|
||||
audience: config.clientId,
|
||||
});
|
||||
if (typeof payload.sub !== 'string' || !payload.sub) {
|
||||
throw new Error('id_token_missing_sub');
|
||||
}
|
||||
if (expectedNonce && payload.nonce !== expectedNonce) {
|
||||
throw new Error('id_token_nonce_mismatch');
|
||||
}
|
||||
const tenantId = deriveTenantId(payload);
|
||||
if (!tenantId) throw new Error('id_token_missing_tenant');
|
||||
return {
|
||||
sub: payload.sub,
|
||||
tenantId,
|
||||
...(typeof payload.email === 'string' ? { email: payload.email } : {}),
|
||||
claims: payload,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { createInboxItem, type InboxItem } from "@siax/contracts/inbox";
|
||||
import { resolveAction, type ResolvedAction } from "@siax/contracts/authz-ux";
|
||||
|
||||
/**
|
||||
* Kanonisk orderstatus (ADR-0002, C3 2026-09-29): kodnivå-union som är den
|
||||
* ENDA sanningskällan för vilka statusar som existerar. DB-kolumnen är fortfarande
|
||||
* `text` (sql/001_init.sql line ~92) men guardas av sql/015_order_status_check.sql
|
||||
* (CHECK ... NOT VALID + VALIDATE i två steg, körs EJ automatiskt mot prod).
|
||||
* 'cancelled' ingår: tests/order-flow.test.ts behandlar den som terminal status.
|
||||
*/
|
||||
export type OrderStatus =
|
||||
| "draft"
|
||||
| "quoted"
|
||||
| "in_production"
|
||||
| "review"
|
||||
| "accepted"
|
||||
| "delivered"
|
||||
| "cancelled";
|
||||
|
||||
/** Uttömmande, kanonisk lista — SQL-constrainten i sql/015 MÅSTE spegla denna. */
|
||||
export const ORDER_STATUSES = [
|
||||
"draft",
|
||||
"quoted",
|
||||
"in_production",
|
||||
"review",
|
||||
"accepted",
|
||||
"delivered",
|
||||
"cancelled",
|
||||
] as const satisfies readonly OrderStatus[];
|
||||
|
||||
/** Typ-vakt: fri text ur DB/payload klassas mot unionen (fail-closed mot read_only). */
|
||||
export function isKnownOrderStatus(status: string): status is OrderStatus {
|
||||
return (ORDER_STATUSES as readonly string[]).includes(status);
|
||||
}
|
||||
|
||||
/** Statusar som kan flyttas fram; delivered/cancelled är terminala. */
|
||||
type AdvanceableStatus = Exclude<OrderStatus, "delivered" | "cancelled">;
|
||||
|
||||
/** Kanoniskt flöde — servern äger resolutionen (ADR-0001), UI renderar. */
|
||||
export const NEXT_STATUS: Record<AdvanceableStatus, OrderStatus> = {
|
||||
draft: "quoted",
|
||||
quoted: "in_production",
|
||||
in_production: "review",
|
||||
review: "accepted",
|
||||
accepted: "delivered",
|
||||
};
|
||||
|
||||
/** Guardad nästa-status: okänd/terminal status → null (aldrig påhittat steg). */
|
||||
export function nextOrderStatus(status: string): OrderStatus | null {
|
||||
if (!isKnownOrderStatus(status)) return null;
|
||||
return NEXT_STATUS[status as AdvanceableStatus] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-renderad action-resolution för advance-steget (ADR-0001):
|
||||
* ägarskapenforces redan av requireOrderOwner på GET/PATCH; tillståndet
|
||||
* avgör read_only. Innan Session/roller finns i 0pt är permission alltid
|
||||
* granted för autentiserade ägare — hårdkoda aldrig denna resolve i klienten.
|
||||
* Okänd status (fri text ur DB innan sql/015-valideringen körts) → read_only.
|
||||
*/
|
||||
export function resolveAdvanceAction(status: string): ResolvedAction {
|
||||
if (nextOrderStatus(status)) {
|
||||
return resolveAction({ permission: "granted", entitlement: "active", approval: "not_required", readOnly: false });
|
||||
}
|
||||
return resolveAction({ permission: "granted", entitlement: "active", approval: "not_required", readOnly: true });
|
||||
}
|
||||
|
||||
/** Orderstatus som utgör en inkorgspost (våg 3.3: orders kö = inbox). */
|
||||
const INBOX_ELIGIBLE: Partial<Record<OrderStatus, { kind: "task" | "approval"; priority: "normal" | "high" }>> = {
|
||||
draft: { kind: "task", priority: "normal" },
|
||||
quoted: { kind: "task", priority: "normal" },
|
||||
in_production: { kind: "task", priority: "normal" },
|
||||
review: { kind: "approval", priority: "high" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Server-renderad inkorgspost (ADR-0001-mönstret): en order som väntar på
|
||||
* nästa steg projiceras på universal-inbox-konvolverna. Terminala statusar
|
||||
* (delivered/cancelled) och okända statusar ger ingen post — inboxen är
|
||||
* öppna arbetsobjekt.
|
||||
*/
|
||||
export function buildOrderInboxItem(order: {
|
||||
order_id: string;
|
||||
status: string;
|
||||
flow: string;
|
||||
total_ore?: number | null;
|
||||
}): InboxItem | null {
|
||||
const next = nextOrderStatus(order.status);
|
||||
const eligible = isKnownOrderStatus(order.status) ? INBOX_ELIGIBLE[order.status] : undefined;
|
||||
if (!eligible || !next) return null;
|
||||
return createInboxItem({
|
||||
id: `order:${order.order_id}`,
|
||||
kind: eligible.kind,
|
||||
tenantId: "0pt",
|
||||
subject: `Order ${order.order_id.slice(0, 8)} — ${order.status} → ${next}`,
|
||||
priority: eligible.priority,
|
||||
createdAt: new Date().toISOString(),
|
||||
source: { system: "0pt", channel: "order-queue" },
|
||||
entity: { type: "order", id: order.order_id },
|
||||
actions: [{ id: "advance", label: `→ ${next}` }],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// Klient-adapter: kernel-transport (@siax/collaboration CollaborationTransport)
|
||||
// över 0pts host-API (/api/admin/order-notes). Admin-ytan pratar ALDRIG med
|
||||
// fetch direkt — allt går genom denna adapter, så offline-läge och
|
||||
// versionskonflikter hanteras på ETT ställe:
|
||||
// - offline: send() är ett medvetet NO-OP som kastar OfflineError — utkastet
|
||||
// behålls i UI:t och användaren får en varning. Ingen tyst förlust.
|
||||
// - 409: ConflictError med serverns aktuella version -> UI laddar om.
|
||||
// Presence går via kernelns upsertPresence (status offline/online per författare).
|
||||
import {
|
||||
nextLamportClock,
|
||||
upsertPresence,
|
||||
type CollaborationOperation,
|
||||
type CollaborationTransport,
|
||||
type PresenceState,
|
||||
} from "@siax/collaboration";
|
||||
|
||||
export interface OrderNoteDto {
|
||||
note_id: string;
|
||||
order_id: string;
|
||||
author_id: string;
|
||||
body: string;
|
||||
version: number;
|
||||
clock: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export class OfflineError extends Error {
|
||||
constructor() {
|
||||
super("Offline: note change was NOT sent — draft kept locally, nothing lost");
|
||||
this.name = "OfflineError";
|
||||
}
|
||||
}
|
||||
|
||||
export class ConflictError extends Error {
|
||||
constructor(
|
||||
public readonly noteId: string,
|
||||
public readonly currentVersion: number,
|
||||
) {
|
||||
super(`Note ${noteId} changed server-side (current version ${currentVersion})`);
|
||||
this.name = "ConflictError";
|
||||
}
|
||||
}
|
||||
|
||||
export class OrderNotesTransport implements CollaborationTransport<{ body: string }> {
|
||||
private listeners = new Set<(op: CollaborationOperation<{ body: string }>) => void>();
|
||||
private presenceListeners = new Set<(p: PresenceState) => void>();
|
||||
private presence = new Map<string, PresenceState>();
|
||||
private localClock = 0;
|
||||
private offline = false;
|
||||
|
||||
constructor(readonly actorId: string) {}
|
||||
|
||||
setOffline(offline: boolean): void {
|
||||
this.offline = offline;
|
||||
this.setPresence({ participantId: this.actorId, status: offline ? "offline" : "online" });
|
||||
}
|
||||
|
||||
isOffline(): boolean {
|
||||
return this.offline;
|
||||
}
|
||||
|
||||
getPresence(): PresenceState[] {
|
||||
return [...this.presence.values()];
|
||||
}
|
||||
|
||||
setPresence(presence: PresenceState): void {
|
||||
this.presence = upsertPresence(this.presence, presence);
|
||||
for (const l of this.presenceListeners) l(presence);
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.setOffline(false);
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.setOffline(true);
|
||||
}
|
||||
|
||||
onOperation(listener: (op: CollaborationOperation<{ body: string }>) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
onPresence(listener: (p: PresenceState) => void): () => void {
|
||||
this.presenceListeners.add(listener);
|
||||
return () => this.presenceListeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Replay a server op into local listeners + advance the Lamport clock. */
|
||||
observeRemote(operation: CollaborationOperation<{ body: string }>): void {
|
||||
this.localClock = nextLamportClock(this.localClock, operation.clock);
|
||||
this.setPresence({
|
||||
participantId: operation.actorId,
|
||||
status: this.presence.get(operation.actorId)?.status ?? "online",
|
||||
});
|
||||
for (const l of this.listeners) l(operation);
|
||||
}
|
||||
|
||||
async send(operation: CollaborationOperation<{ body: string }>): Promise<void> {
|
||||
if (this.offline) throw new OfflineError();
|
||||
this.localClock = nextLamportClock(this.localClock, operation.clock);
|
||||
for (const l of this.listeners) l(operation);
|
||||
}
|
||||
}
|
||||
|
||||
export interface NotesApiResult {
|
||||
notes: OrderNoteDto[];
|
||||
/** Version per note — the optimistic-concurrency handle the UI PATCHes with. */
|
||||
versions: Map<string, number>;
|
||||
}
|
||||
|
||||
export class OrderNotesClient {
|
||||
readonly transport: OrderNotesTransport;
|
||||
|
||||
constructor(actorId: string) {
|
||||
this.transport = new OrderNotesTransport(actorId);
|
||||
}
|
||||
|
||||
async load(orderId: string): Promise<NotesApiResult> {
|
||||
const res = await fetch(`/api/admin/order-notes?order_id=${encodeURIComponent(orderId)}`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) throw new Error(`load failed: ${res.status}`);
|
||||
const body = (await res.json()) as { notes: OrderNoteDto[] };
|
||||
const versions = new Map<string, number>();
|
||||
for (const note of body.notes) {
|
||||
versions.set(note.note_id, note.version);
|
||||
this.transport.observeRemote({
|
||||
id: note.note_id,
|
||||
actorId: note.author_id,
|
||||
clock: note.clock,
|
||||
type: "note.upsert",
|
||||
payload: { body: note.body },
|
||||
});
|
||||
}
|
||||
return { notes: body.notes, versions };
|
||||
}
|
||||
|
||||
async add(orderId: string, body: string): Promise<OrderNoteDto> {
|
||||
const op: CollaborationOperation<{ body: string }> = {
|
||||
id: `local_${crypto.randomUUID()}`,
|
||||
actorId: this.transport.actorId,
|
||||
clock: 0,
|
||||
type: "note.create",
|
||||
payload: { body },
|
||||
};
|
||||
await this.transport.send(op);
|
||||
const res = await fetch("/api/admin/order-notes", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ order_id: orderId, body }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`add failed: ${res.status}`);
|
||||
return (await res.json()) as OrderNoteDto;
|
||||
}
|
||||
|
||||
async update(note: OrderNoteDto, body: string, expectedVersion: number): Promise<OrderNoteDto> {
|
||||
await this.transport.send({
|
||||
id: note.note_id,
|
||||
actorId: "self",
|
||||
clock: note.clock,
|
||||
type: "note.update",
|
||||
payload: { body },
|
||||
});
|
||||
const res = await fetch("/api/admin/order-notes", {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ note_id: note.note_id, body, version: expectedVersion }),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
const err = (await res.json()) as { current_version?: number };
|
||||
throw new ConflictError(note.note_id, err.current_version ?? 0);
|
||||
}
|
||||
if (!res.ok) throw new Error(`update failed: ${res.status}`);
|
||||
return (await res.json()) as OrderNoteDto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// Order notes — SIAX collaboration-kernelns första produktkonsument (spår C).
|
||||
//
|
||||
// Server-authoritative store över 0pts data-lager (Postgres när DATABASE_URL
|
||||
// är satt, annars samma dokumenterade in-memory-fallback som orders-store).
|
||||
// Kernel-semantik (@siax/collaboration 0.3.0):
|
||||
// - varje note ÄR en CollaborationOperation (id/actorId/clock/type/payload)
|
||||
// - nya operationer får sin klocka via nextLamportClock (max lokal/observerad + 1)
|
||||
// - listning återställs deterministiskt via mergeOperationLog/compareOperations
|
||||
// (klocka -> actorId -> id), så två repliker listar i SAMMA ordning
|
||||
// - samtidighet: optimistisk version; stale skrivning kastar
|
||||
// NoteVersionConflictError -> routen svarar 409 (conflict behavior).
|
||||
import {
|
||||
mergeOperationLog,
|
||||
nextLamportClock,
|
||||
type CollaborationOperation,
|
||||
} from "@siax/collaboration";
|
||||
|
||||
import { getSqlForDurableStore } from "@/lib/db";
|
||||
|
||||
export interface OrderNote {
|
||||
note_id: string;
|
||||
order_id: string;
|
||||
tenant_id: string | null;
|
||||
author_id: string;
|
||||
body: string;
|
||||
version: number;
|
||||
clock: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export class NoteVersionConflictError extends Error {
|
||||
constructor(
|
||||
public readonly noteId: string,
|
||||
public readonly expectedVersion: number,
|
||||
public readonly currentVersion: number,
|
||||
) {
|
||||
super(
|
||||
`Note "${noteId}" was updated by someone else: expected version ${expectedVersion}, current is ${currentVersion}`,
|
||||
);
|
||||
this.name = "NoteVersionConflictError";
|
||||
}
|
||||
}
|
||||
|
||||
export class NoteNotFoundError extends Error {
|
||||
constructor(public readonly noteId: string) {
|
||||
super(`Note "${noteId}" does not exist`);
|
||||
this.name = "NoteNotFoundError";
|
||||
}
|
||||
}
|
||||
|
||||
export class OrderNotFoundError extends Error {
|
||||
constructor(public readonly orderId: string) {
|
||||
super(`Order "${orderId}" does not exist`);
|
||||
this.name = "OrderNotFoundError";
|
||||
}
|
||||
}
|
||||
|
||||
// Non-durable fallback used only until a database is provisioned (same
|
||||
// decision as lib/orders-store.ts — resolveStoreMode fails hard in production
|
||||
// without a URL, so this path cannot silently swallow production writes).
|
||||
const mem = new Map<string, OrderNote>();
|
||||
|
||||
/** Kernel-projection: a note row IS a collaboration operation. */
|
||||
function toOperation(note: OrderNote): CollaborationOperation<{ body: string }> {
|
||||
return {
|
||||
id: note.note_id,
|
||||
actorId: note.author_id,
|
||||
clock: note.clock,
|
||||
type: "note.upsert",
|
||||
payload: { body: note.body },
|
||||
};
|
||||
}
|
||||
|
||||
/** Deterministic snapshot: kernel merge wins, never insertion order. */
|
||||
function snapshot(notes: Iterable<OrderNote>): OrderNote[] {
|
||||
const log = mergeOperationLog([...notes].map(toOperation));
|
||||
const byId = new Map([...notes].map((n) => [n.note_id, n]));
|
||||
return log
|
||||
.map((op) => byId.get(op.id))
|
||||
.filter((n): n is OrderNote => Boolean(n));
|
||||
}
|
||||
|
||||
function rowToNote(row: Record<string, unknown>): OrderNote {
|
||||
return {
|
||||
note_id: String(row.note_id),
|
||||
order_id: String(row.order_id),
|
||||
tenant_id: row.tenant_id === null || row.tenant_id === undefined ? null : String(row.tenant_id),
|
||||
author_id: String(row.author_id),
|
||||
body: String(row.body),
|
||||
version: Number(row.version),
|
||||
clock: Number(row.clock),
|
||||
created_at: new Date(row.created_at as string).toISOString(),
|
||||
updated_at: new Date(row.updated_at as string).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
type NotesSql = NonNullable<ReturnType<typeof getSqlForDurableStore>>;
|
||||
|
||||
async function maxClock(sql: NotesSql, orderId: string): Promise<number> {
|
||||
const rows = await sql`
|
||||
SELECT COALESCE(MAX(clock), 0) AS max_clock FROM order_notes WHERE order_id = ${orderId}
|
||||
`;
|
||||
return Number(rows[0]?.max_clock ?? 0);
|
||||
}
|
||||
|
||||
export async function listNotes(orderId: string): Promise<OrderNote[]> {
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) {
|
||||
return snapshot(
|
||||
[...mem.values()].filter((n) => n.order_id === orderId),
|
||||
);
|
||||
}
|
||||
const rows = await sql`
|
||||
SELECT * FROM order_notes WHERE order_id = ${orderId}
|
||||
`;
|
||||
return snapshot(rows.map(rowToNote));
|
||||
}
|
||||
|
||||
export interface AddNoteInput {
|
||||
order_id: string;
|
||||
tenant_id: string | null;
|
||||
author_id: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export async function addNote(input: AddNoteInput): Promise<OrderNote> {
|
||||
const body = input.body.trim();
|
||||
if (!body) throw new TypeError("note body must be non-empty");
|
||||
const note: OrderNote = {
|
||||
note_id: `note_${crypto.randomUUID()}`,
|
||||
order_id: input.order_id,
|
||||
tenant_id: input.tenant_id,
|
||||
author_id: input.author_id,
|
||||
body,
|
||||
version: 1,
|
||||
// Kernel: Lamport-klockan = max(lokal, observerad) + 1.
|
||||
clock: 1,
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
note.clock = nextLamportClock(await peekMaxClock(input.order_id));
|
||||
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) {
|
||||
mem.set(note.note_id, note);
|
||||
return note;
|
||||
}
|
||||
const rows = await sql`
|
||||
INSERT INTO order_notes (note_id, order_id, tenant_id, author_id, body, version, clock, created_at, updated_at)
|
||||
VALUES (${note.note_id}, ${note.order_id}, ${note.tenant_id}, ${note.author_id}, ${note.body},
|
||||
${note.version}, ${note.clock}, ${note.created_at}, ${note.updated_at})
|
||||
RETURNING *
|
||||
`;
|
||||
return rowToNote(rows[0]);
|
||||
}
|
||||
|
||||
async function peekMaxClock(orderId: string): Promise<number> {
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) {
|
||||
let max = 0;
|
||||
for (const n of mem.values()) if (n.order_id === orderId && n.clock > max) max = n.clock;
|
||||
return max;
|
||||
}
|
||||
return maxClock(sql, orderId);
|
||||
}
|
||||
|
||||
export interface UpdateNoteInput {
|
||||
note_id: string;
|
||||
author_id: string;
|
||||
body: string;
|
||||
/** Optimistic concurrency: must equal the caller's seen version, else 409. */
|
||||
expected_version: number;
|
||||
}
|
||||
|
||||
export async function updateNote(input: UpdateNoteInput): Promise<OrderNote> {
|
||||
const body = input.body.trim();
|
||||
if (!body) throw new TypeError("note body must be non-empty");
|
||||
if (!Number.isInteger(input.expected_version) || input.expected_version < 1) {
|
||||
throw new TypeError("expected_version must be a positive integer");
|
||||
}
|
||||
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) {
|
||||
const current = mem.get(input.note_id);
|
||||
if (!current) throw new NoteNotFoundError(input.note_id);
|
||||
if (current.version !== input.expected_version) {
|
||||
throw new NoteVersionConflictError(input.note_id, input.expected_version, current.version);
|
||||
}
|
||||
const updated: OrderNote = {
|
||||
...current,
|
||||
body,
|
||||
version: current.version + 1,
|
||||
clock: nextLamportClock(current.clock),
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
mem.set(updated.note_id, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
const rows = await sql`
|
||||
UPDATE order_notes
|
||||
SET body = ${body},
|
||||
version = version + 1,
|
||||
clock = clock + 1,
|
||||
updated_at = ${new Date().toISOString()}
|
||||
WHERE note_id = ${input.note_id} AND version = ${input.expected_version}
|
||||
RETURNING *
|
||||
`;
|
||||
if (rows.length === 0) {
|
||||
const existing = await sql`SELECT * FROM order_notes WHERE note_id = ${input.note_id}`;
|
||||
if (existing.length === 0) throw new NoteNotFoundError(input.note_id);
|
||||
throw new NoteVersionConflictError(
|
||||
input.note_id,
|
||||
input.expected_version,
|
||||
Number(existing[0].version),
|
||||
);
|
||||
}
|
||||
return rowToNote(rows[0]);
|
||||
}
|
||||
|
||||
/** Direct read by note id — used by the route for server-authoritative tenant checks. */
|
||||
export async function findNote(noteId: string): Promise<OrderNote | null> {
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) return mem.get(noteId) ?? null;
|
||||
const rows = await sql`SELECT * FROM order_notes WHERE note_id = ${noteId}`;
|
||||
return rows.length > 0 ? rowToNote(rows[0]) : null;
|
||||
}
|
||||
|
||||
/** Delete for tests: the in-memory fallback needs isolation between tests. */
|
||||
export function resetOrderNotesMemoryForTests(): void {
|
||||
mem.clear();
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { getSqlForDurableStore } from "@/lib/db";
|
||||
import { computeEstimate, type EntityType, type Frequency } from "@/lib/data";
|
||||
import { serviceById } from "@/lib/services";
|
||||
|
||||
export interface OrderConfig {
|
||||
markets?: string[];
|
||||
type?: EntityType;
|
||||
fieldIds?: string[];
|
||||
enrichmentIds?: string[];
|
||||
volume?: number;
|
||||
frequency?: Frequency;
|
||||
confidence?: number;
|
||||
formats?: string[];
|
||||
service_type?: string;
|
||||
}
|
||||
|
||||
export interface Order {
|
||||
order_id: string;
|
||||
/** NULL for legacy anonymous drafts; never inferred from request config. */
|
||||
tenant_id?: string | null;
|
||||
buyer_subject?: string | null;
|
||||
flow: string;
|
||||
status: string;
|
||||
config: OrderConfig;
|
||||
total_ore: number;
|
||||
deposit_ore: number;
|
||||
balance_ore: number;
|
||||
est_days: number;
|
||||
est_confidence: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface OrderOwner {
|
||||
tenantId: string;
|
||||
subject: string;
|
||||
}
|
||||
|
||||
/** Collision-free namespace within the existing global idempotency index. */
|
||||
function ownedIdempotencyKey(owner: OrderOwner, key: string): string {
|
||||
return `owned:${owner.tenantId.length}:${owner.tenantId}:${key}`;
|
||||
}
|
||||
|
||||
// Non-durable fallback used only until a database is provisioned.
|
||||
const mem = new Map<string, Order>();
|
||||
// idempotency_key -> order_id, mirroring the Postgres unique index added by
|
||||
// sql/006_orders_idempotency.sql for the in-memory fallback path.
|
||||
const memIdempotencyIndex = new Map<string, string>();
|
||||
|
||||
/**
|
||||
* Thrown by {@link createOrder} when a caller reuses an `Idempotency-Key`
|
||||
* for a semantically different request (different `flow` and/or `config`)
|
||||
* than the one that key was first used with. A route handler should map
|
||||
* this to HTTP 409 -- silently returning either order would be wrong (the
|
||||
* caller asked for the SAME operation to be safely retried, not for two
|
||||
* different operations to collapse into one).
|
||||
*/
|
||||
export class IdempotencyKeyConflictError extends Error {
|
||||
constructor(public readonly idempotencyKey: string) {
|
||||
super(`Idempotency-Key "${idempotencyKey}" was already used to create a different order (different flow/config)`);
|
||||
this.name = "IdempotencyKeyConflictError";
|
||||
}
|
||||
}
|
||||
|
||||
/** Postgres error code 23505 = unique_violation (postgres.js surfaces it as `.code`). */
|
||||
function isUniqueViolation(err: unknown): boolean {
|
||||
return typeof err === "object" && err !== null && (err as { code?: unknown }).code === "23505";
|
||||
}
|
||||
|
||||
function sameSubmission(a: Order, flow: string, config: OrderConfig, owner?: OrderOwner): boolean {
|
||||
return a.flow === flow && JSON.stringify(a.config) === JSON.stringify(config)
|
||||
&& (!owner || (a.tenant_id === owner.tenantId && a.buyer_subject === owner.subject));
|
||||
}
|
||||
|
||||
export async function findOrderByIdempotencyKey(key: string): Promise<Order | null> {
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
|
||||
FROM orders WHERE idempotency_key = ${key} LIMIT 1`;
|
||||
return rows[0] ? coerceOrder(rows[0]) : null;
|
||||
}
|
||||
const id = memIdempotencyIndex.get(key);
|
||||
return id ? mem.get(id) ?? null : null;
|
||||
}
|
||||
|
||||
// postgres.js (pinned v3.4.9) returns bigint (total_ore/deposit_ore/balance_ore)
|
||||
// and numeric (est_confidence) columns as strings by default, not JS numbers.
|
||||
// Coerce only these four fields on rows read back from SQL -- not the shared
|
||||
// `sql` client's global type map, which would silently affect every other
|
||||
// table's bigint/numeric columns too (e.g. jobs.pct, deliveries.avg_confidence).
|
||||
function coerceOrder(row: Order): Order {
|
||||
return {
|
||||
...row,
|
||||
total_ore: Number(row.total_ore),
|
||||
deposit_ore: Number(row.deposit_ore),
|
||||
balance_ore: Number(row.balance_ore),
|
||||
est_confidence: Number(row.est_confidence),
|
||||
};
|
||||
}
|
||||
|
||||
function estimateFor(config: OrderConfig) {
|
||||
return computeEstimate({
|
||||
markets: config.markets ?? [],
|
||||
type: config.type ?? "Bolag",
|
||||
fieldIds: config.fieldIds ?? [],
|
||||
enrichmentIds: config.enrichmentIds ?? [],
|
||||
volume: config.volume ?? 1000,
|
||||
frequency: config.frequency ?? "Engångs",
|
||||
confidence: config.confidence ?? 92,
|
||||
serviceMult: serviceById(config.service_type ?? "")?.mult ?? 1,
|
||||
});
|
||||
}
|
||||
|
||||
export interface CreateOrderResult {
|
||||
order: Order;
|
||||
/** True when this call returned a PRE-EXISTING order (a safe retry under the same Idempotency-Key), not a newly created one. */
|
||||
replayed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* P014: `idempotencyKey` is optional -- a caller that omits it (or the
|
||||
* pre-P014 call shape) behaves exactly as before, creating a fresh row every
|
||||
* call. When supplied (the `Idempotency-Key` header convention, see
|
||||
* sql/006_orders_idempotency.sql), a retry with the SAME key returns the
|
||||
* original order unchanged (`replayed: true`) instead of creating a
|
||||
* duplicate; a retry with the same key but a DIFFERENT flow/config throws
|
||||
* {@link IdempotencyKeyConflictError} rather than silently picking one.
|
||||
*
|
||||
* The Postgres path checks-then-inserts, which has a real (if narrow) race
|
||||
* window between two concurrent requests carrying the same fresh key -- the
|
||||
* UNIQUE INDEX from sql/006 is the actual source of truth, and a
|
||||
* unique-violation on INSERT is caught and re-resolved the same way a
|
||||
* pre-existing row would be, rather than surfacing a raw DB error.
|
||||
*/
|
||||
export async function createOrder(flow: string, config: OrderConfig, idempotencyKey?: string, owner?: OrderOwner): Promise<CreateOrderResult> {
|
||||
if (owner && (!owner.tenantId.trim() || !owner.subject.trim())) throw new Error("Verified order owner is required");
|
||||
const rawKey = idempotencyKey?.trim() || undefined;
|
||||
const key = rawKey && owner ? ownedIdempotencyKey(owner, rawKey) : rawKey;
|
||||
if (key) {
|
||||
const existing = await findOrderByIdempotencyKey(key);
|
||||
if (existing) {
|
||||
if (sameSubmission(existing, flow, config, owner)) return { order: existing, replayed: true };
|
||||
throw new IdempotencyKeyConflictError(key);
|
||||
}
|
||||
}
|
||||
|
||||
const est = estimateFor(config);
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
try {
|
||||
const [row] = await sql<{ order_id: string; created_at: string }[]>`
|
||||
INSERT INTO orders (tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, idempotency_key)
|
||||
VALUES (${owner?.tenantId ?? null}, ${owner?.subject ?? null}, ${flow}, 'draft', ${sql.json(config as Parameters<typeof sql.json>[0])},
|
||||
${est.price * 100}, ${est.deposit * 100}, ${est.remainder * 100},
|
||||
${est.timelineDays}, ${est.estConfidence / 100}, ${key ?? null})
|
||||
RETURNING order_id, created_at`;
|
||||
return {
|
||||
order: {
|
||||
order_id: row.order_id, tenant_id: owner?.tenantId ?? null, buyer_subject: owner?.subject ?? null,
|
||||
flow, status: "draft", config,
|
||||
total_ore: est.price * 100, deposit_ore: est.deposit * 100, balance_ore: est.remainder * 100,
|
||||
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: row.created_at,
|
||||
},
|
||||
replayed: false,
|
||||
};
|
||||
} catch (err) {
|
||||
if (key && isUniqueViolation(err)) {
|
||||
const raced = await findOrderByIdempotencyKey(key);
|
||||
if (raced) {
|
||||
if (sameSubmission(raced, flow, config, owner)) return { order: raced, replayed: true };
|
||||
throw new IdempotencyKeyConflictError(key);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const id = (globalThis.crypto?.randomUUID?.() ?? `SX-${Math.floor(1000 + Math.random() * 9000)}`);
|
||||
const order: Order = {
|
||||
order_id: id, tenant_id: owner?.tenantId ?? null, buyer_subject: owner?.subject ?? null,
|
||||
flow, status: "draft", config,
|
||||
total_ore: est.price * 100, deposit_ore: est.deposit * 100, balance_ore: est.remainder * 100,
|
||||
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: new Date().toISOString(),
|
||||
};
|
||||
mem.set(id, order);
|
||||
if (key) memIdempotencyIndex.set(key, id);
|
||||
return { order, replayed: false };
|
||||
}
|
||||
|
||||
export async function getOrder(id: string): Promise<Order | null> {
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
|
||||
FROM orders WHERE order_id::text = ${id} LIMIT 1`;
|
||||
return rows[0] ? coerceOrder(rows[0]) : null;
|
||||
}
|
||||
return mem.get(id) ?? null;
|
||||
}
|
||||
|
||||
/** Buyer read is scoped in SQL itself; legacy NULL-owned rows are invisible. */
|
||||
export async function getOwnedOrder(id: string, tenantId: string): Promise<Order | null> {
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
|
||||
FROM orders WHERE order_id::text = ${id} AND tenant_id = ${tenantId} LIMIT 1`;
|
||||
return rows[0] ? coerceOrder(rows[0]) : null;
|
||||
}
|
||||
const order = mem.get(id);
|
||||
return order?.tenant_id === tenantId ? order : null;
|
||||
}
|
||||
|
||||
export async function listOwnedOrders(tenantId: string): Promise<Order[]> {
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
|
||||
FROM orders WHERE tenant_id = ${tenantId} ORDER BY created_at DESC LIMIT 100`;
|
||||
return rows.map(coerceOrder);
|
||||
}
|
||||
return [...mem.values()].filter((o) => o.tenant_id === tenantId)
|
||||
.sort((a, b) => b.created_at.localeCompare(a.created_at));
|
||||
}
|
||||
|
||||
export async function listOrders(): Promise<Order[]> {
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
|
||||
FROM orders ORDER BY created_at DESC LIMIT 100`;
|
||||
return rows.map(coerceOrder);
|
||||
}
|
||||
return [...mem.values()].sort((a, b) => b.created_at.localeCompare(a.created_at));
|
||||
}
|
||||
|
||||
export async function setStatus(id: string, status: string): Promise<Order | null> {
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
UPDATE orders SET status = ${status}, updated_at = now() WHERE order_id::text = ${id}
|
||||
RETURNING order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at`;
|
||||
return rows[0] ? coerceOrder(rows[0]) : null;
|
||||
}
|
||||
const o = mem.get(id);
|
||||
if (o) { o.status = status; mem.set(id, o); }
|
||||
return o ?? null;
|
||||
}
|
||||
|
||||
/** Atomic status transition; rejects stale concurrent writers instead of overwriting them. */
|
||||
export async function setStatusIfCurrent(id: string, current: string, next: string): Promise<Order | null> {
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
UPDATE orders SET status = ${next}, updated_at = now()
|
||||
WHERE order_id::text = ${id} AND status = ${current}
|
||||
RETURNING order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at`;
|
||||
return rows[0] ? coerceOrder(rows[0]) : null;
|
||||
}
|
||||
const order = mem.get(id);
|
||||
if (!order || order.status !== current) return null;
|
||||
order.status = next;
|
||||
mem.set(id, order);
|
||||
return order;
|
||||
}
|
||||
|
||||
/** Buyer status change is both atomic and tenant-scoped at the SQL boundary. */
|
||||
export async function setOwnedStatusIfCurrent(
|
||||
id: string, tenantId: string, current: string, next: string,
|
||||
): Promise<Order | null> {
|
||||
const sql = getSqlForDurableStore("0pt.orders");
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
UPDATE orders SET status = ${next}, updated_at = now()
|
||||
WHERE order_id::text = ${id} AND tenant_id = ${tenantId} AND status = ${current}
|
||||
RETURNING order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore,
|
||||
balance_ore, est_days, est_confidence, created_at`;
|
||||
return rows[0] ? coerceOrder(rows[0]) : null;
|
||||
}
|
||||
const order = mem.get(id);
|
||||
if (!order || order.tenant_id !== tenantId || order.status !== current) return null;
|
||||
order.status = next;
|
||||
mem.set(id, order);
|
||||
return order;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// The 0pt service catalog. Every sellable service maps to one of the three flows
|
||||
// (docs/01): catalog product, custom job, subscription. Categories are tags within
|
||||
// those flows — not separate machinery.
|
||||
//
|
||||
// i18n: id/flow stay stable (keys); display fields are localized { en, sv } and
|
||||
// resolved with useT() at the render site.
|
||||
|
||||
import type { Loc } from "@/lib/data";
|
||||
|
||||
export type Flow = "catalog" | "custom" | "subscription";
|
||||
|
||||
export interface Service {
|
||||
id: string;
|
||||
name: Loc;
|
||||
tagline: Loc; // terse, confident
|
||||
covers: Loc; // one line of scope
|
||||
flow: Flow;
|
||||
deliverable: Loc;
|
||||
mult: number; // price multiplier vs a base dataset job
|
||||
}
|
||||
|
||||
export const SERVICES: Service[] = [
|
||||
{ id: "data", name: { en: "Data delivery", sv: "Dataleverans" }, tagline: { en: "Ready-made or bespoke.", sv: "Färdig eller skräddarsydd." }, covers: { en: "Companies, decision-makers, vehicles, financials — per field, with provenance.", sv: "Bolag, beslutsfattare, fordon, finansiellt — per fält med härkomst." }, flow: "custom", deliverable: { en: "CSV · Parquet · JSON · API", sv: "CSV · Parquet · JSON · API" }, mult: 1.0 },
|
||||
{ id: "scraping", name: { en: "Web scraping", sv: "Webbskrapning" }, tagline: { en: "Legally collected.", sv: "Lagligt insamlat." }, covers: { en: "Official APIs and clearly public pages. Never behind a login.", sv: "Officiella API:er och tydligt publika sidor. Aldrig bakom inloggning." }, flow: "custom", deliverable: { en: "Structured dataset + source per field", sv: "Strukturerat dataset + källa per fält" }, mult: 1.1 },
|
||||
{ id: "mapping", name: { en: "Mapping & matching", sv: "Mappning & matchning" }, tagline: { en: "Your data against the world.", sv: "Era data mot världen." }, covers: { en: "Link your records to org. no./LEI and external keys. Cross-border.", sv: "Koppla era poster mot orgnr/LEI och externa nycklar. Cross-border." }, flow: "custom", deliverable: { en: "Matched file + match confidence", sv: "Matchad fil + matchningskonfidens" }, mult: 1.2 },
|
||||
{ id: "normalization", name: { en: "Normalization", sv: "Normalisering" }, tagline: { en: "Cleaned. Standardized.", sv: "Städat. Standardiserat." }, covers: { en: "Format, duplicates, validation (email/phone), unified taxonomy.", sv: "Format, dubbletter, validering (e-post/telefon), enhetlig taxonomi." }, flow: "custom", deliverable: { en: "Clean data model + quality report", sv: "Ren datamodell + kvalitetsrapport" }, mult: 1.1 },
|
||||
{ id: "consolidation", name: { en: "Consolidation → CRM/ERP", sv: "Konsolidering → CRM/ERP" }, tagline: { en: "One truth. The right system.", sv: "En sanning. Rätt system." }, covers: { en: "Merge admin data and push to HubSpot, Salesforce, Dynamics, Pipedrive, FiveCRM.", sv: "Slå ihop admindata och pusha till HubSpot, Salesforce, Dynamics, Pipedrive, FiveCRM." }, flow: "custom", deliverable: { en: "Consolidated data + push/sync", sv: "Konsoliderad data + push/sync" }, mult: 1.4 },
|
||||
{ id: "documents", name: { en: "Documents & OCR", sv: "Dokument & OCR" }, tagline: { en: "Pixels to records.", sv: "Pixlar till poster." }, covers: { en: "PDFs, images, scanned official documents → structured fields.", sv: "PDF, bilder, scannade myndighetsdokument → strukturerade fält." }, flow: "custom", deliverable: { en: "Structured dataset from documents", sv: "Strukturerat dataset från dokument" }, mult: 1.3 },
|
||||
{ id: "enrichment", name: { en: "Enrichment", sv: "Berikning" }, tagline: { en: "Fill the gaps.", sv: "Fyll luckorna." }, covers: { en: "Contacts, firmographics, financials, buying signals — with a lawful basis.", sv: "Kontakter, firmografik, finansiellt, köpsignaler — med laglig grund." }, flow: "subscription", deliverable: { en: "Enriched file or ongoing feed", sv: "Berikad fil eller löpande flöde" }, mult: 1.2 },
|
||||
{ id: "icp", name: { en: "ICP & leads", sv: "ICP & leads" }, tagline: { en: "The right audience.", sv: "Rätt målgrupp." }, covers: { en: "Target lists with decision-makers, provenance per contact.", sv: "Målgruppslistor med beslutsfattare, härkomst per kontakt." }, flow: "catalog", deliverable: { en: "Lead list + export to CRM", sv: "Lead-lista + export till CRM" }, mult: 1.2 },
|
||||
{ id: "ml", name: { en: "ML jobs", sv: "ML-jobb" }, tagline: { en: "Models on your data.", sv: "Modeller på er data." }, covers: { en: "Scoring, matching, forecasting, clustering — trained on your + our data.", sv: "Scoring, matchning, prognos, klustring — tränat på era + våra data." }, flow: "custom", deliverable: { en: "Model + predictions + API", sv: "Modell + prediktioner + API" }, mult: 1.8 },
|
||||
{ id: "bi", name: { en: "BI & market analysis", sv: "BI & marknadsanalys" }, tagline: { en: "Decisions, not just numbers.", sv: "Beslut, inte bara siffror." }, covers: { en: "Dashboards, market overviews, competitor and coverage analysis.", sv: "Dashboards, marknadsöversikter, konkurrent- och täckningsanalys." }, flow: "custom", deliverable: { en: "Metabase dashboard + report", sv: "Metabase-dashboard + rapport" }, mult: 1.5 },
|
||||
{ id: "feeds", name: { en: "Feeds & monitoring", sv: "Flöden & övervakning" }, tagline: { en: "Always fresh.", sv: "Alltid färskt." }, covers: { en: "Recurring delivery, freshness monitoring, webhook on change.", sv: "Återkommande leverans, freshness-bevakning, webhook vid förändring." }, flow: "subscription", deliverable: { en: "Webhook/feed + alerts", sv: "Webhook/feed + larm" }, mult: 1.3 },
|
||||
];
|
||||
|
||||
export const FLOW_LABEL: Record<Flow, Loc> = {
|
||||
catalog: { en: "Catalog", sv: "Katalog" },
|
||||
custom: { en: "Bespoke", sv: "Skräddarsytt" },
|
||||
subscription: { en: "Feed", sv: "Flöde" },
|
||||
};
|
||||
|
||||
// CRM/ERP destinations for the consolidation/push services.
|
||||
export const DESTINATIONS_CRM = ["HubSpot", "Salesforce", "Microsoft Dynamics", "Pipedrive", "FiveCRM", "Google Sheets", "CSV / API"];
|
||||
|
||||
export function serviceById(id: string): Service | undefined {
|
||||
return SERVICES.find((s) => s.id === id);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import Stripe from "stripe";
|
||||
|
||||
// Lazy, env-guarded Stripe client. Returns null when STRIPE_SECRET_KEY is unset
|
||||
// so the app builds/runs without keys; payment routes 501 until configured.
|
||||
let _stripe: Stripe | null = null;
|
||||
|
||||
export function getStripe(): Stripe | null {
|
||||
const key = process.env.STRIPE_SECRET_KEY;
|
||||
if (!key) return null;
|
||||
if (!_stripe) _stripe = new Stripe(key);
|
||||
return _stripe;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { getSqlForDurableStore } from "@/lib/db";
|
||||
|
||||
export interface Subscription {
|
||||
sub_id: string;
|
||||
order_id: string;
|
||||
cadence: string;
|
||||
webhook_url: string | null;
|
||||
status: string;
|
||||
next_run_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const mem = new Map<string, Subscription>();
|
||||
|
||||
export async function createSubscription(order_id: string, cadence: string, webhook_url: string | null): Promise<Subscription> {
|
||||
const sql = getSqlForDurableStore("0pt.subscriptions");
|
||||
if (sql) {
|
||||
const [row] = await sql<Subscription[]>`
|
||||
INSERT INTO subscriptions (order_id, cadence, webhook_url, status)
|
||||
VALUES (${order_id}, ${cadence}, ${webhook_url}, 'active')
|
||||
RETURNING sub_id, order_id, cadence, webhook_url, status, next_run_at, now() AS created_at`;
|
||||
return row;
|
||||
}
|
||||
const id = globalThis.crypto?.randomUUID?.() ?? `sub-${Math.floor(Math.random() * 1e9)}`;
|
||||
const sub: Subscription = { sub_id: id, order_id, cadence, webhook_url, status: "active", next_run_at: null, created_at: new Date().toISOString() };
|
||||
mem.set(id, sub);
|
||||
return sub;
|
||||
}
|
||||
|
||||
export async function listSubscriptions(): Promise<Subscription[]> {
|
||||
const sql = getSqlForDurableStore("0pt.subscriptions");
|
||||
if (sql) {
|
||||
return sql<Subscription[]>`SELECT sub_id, order_id, cadence, webhook_url, status, next_run_at, created_at FROM subscriptions ORDER BY created_at DESC LIMIT 100`;
|
||||
}
|
||||
return [...mem.values()].sort((a, b) => b.created_at.localeCompare(a.created_at));
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
Reference in New Issue
Block a user