From 15c65a584c9e7f2be53d11418edad4a04a339eb5 Mon Sep 17 00:00:00 2001 From: Simon Axelsson Date: Wed, 24 Jun 2026 17:56:30 +0200 Subject: [PATCH] feat(api): Vercel-native platform API + Postgres schema Route Handlers (Vercel Functions): /api/health, /api/estimates (single-source estimate math, ore), /api/catalog, /api/sources (legal sourcing map). sql/001_init.sql = full docs/03 data model (entities + bridge_provenance + platform tables, pgvector). Ready to wire Vercel Postgres. Co-Authored-By: Claude Opus 4.8 --- app/api/catalog/route.ts | 15 ++++ app/api/estimates/route.ts | 41 +++++++++++ app/api/health/route.ts | 12 ++++ app/api/sources/route.ts | 19 +++++ sql/001_init.sql | 137 +++++++++++++++++++++++++++++++++++++ 5 files changed, 224 insertions(+) create mode 100644 app/api/catalog/route.ts create mode 100644 app/api/estimates/route.ts create mode 100644 app/api/health/route.ts create mode 100644 app/api/sources/route.ts create mode 100644 sql/001_init.sql diff --git a/app/api/catalog/route.ts b/app/api/catalog/route.ts new file mode 100644 index 0000000..cefff7e --- /dev/null +++ b/app/api/catalog/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; + +// GET /api/catalog (docs/04) — ready-made datasets. Static seed until DB is provisioned. +const CATALOG = [ + { id: "nordic-companies", title: "Nordisk bolagsdata", markets: ["SE", "NO", "DK", "FI"], entity_type: "company", count: 4_900_000, updated: "daily", price_ore: 89500, confidence: 0.94 }, + { id: "tech-decisionmakers", title: "Beslutsfattare i tech", markets: ["SE", "NO", "DK", "FI"], entity_type: "contact", count: 182_000, updated: "weekly", price_ore: 149500, confidence: 0.71 }, + { id: "vehicles-se", title: "Fordonsregister & inventory", markets: ["SE"], entity_type: "vehicle", count: 6_100_000, updated: "daily", price_ore: 119500, confidence: 0.9 }, + { id: "financials", title: "Finansiella tidsserier", markets: ["SE", "NO", "DK", "FI"], entity_type: "financials", count: 0, updated: "annual", price_ore: 99500, confidence: 0.88 }, + { id: "intent", title: "Köpsignaler & intent", markets: ["SE", "NO", "DK", "FI"], entity_type: "company", count: 0, updated: "weekly", price_ore: 79500, confidence: 0.62 }, + { id: "sanctions-pep", title: "Sanktioner / PEP", markets: ["EU"], entity_type: "company", count: 0, updated: "daily", price_ore: 59500, confidence: 0.95 }, +]; + +export async function GET() { + return NextResponse.json(CATALOG); +} diff --git a/app/api/estimates/route.ts b/app/api/estimates/route.ts new file mode 100644 index 0000000..29d9edf --- /dev/null +++ b/app/api/estimates/route.ts @@ -0,0 +1,41 @@ +import { NextRequest, NextResponse } from "next/server"; +import { computeEstimate, type EntityType, type Frequency } from "@/lib/data"; + +// POST /api/estimates (docs/04) — price/time/confidence for a configured job. +// Single source of truth for the estimate math; the configurator calls this. +export async function POST(req: NextRequest) { + let body: Record; + try { + body = await req.json(); + } catch { + return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 }); + } + + const markets = Array.isArray(body.markets) ? (body.markets as string[]) : []; + const entity_type = (body.entity_type as EntityType) || "Bolag"; + const fields = Array.isArray(body.fields) ? (body.fields as string[]) : []; + const enrichment = Array.isArray(body.enrichment) ? (body.enrichment as string[]) : []; + const volume = Number(body.volume) || 1000; + const frequency = (body.frequency as Frequency) || "Engångs"; + const confidence_target = Number(body.confidence_target) || 92; + + const est = computeEstimate({ + markets, + type: entity_type, + fieldIds: fields, + enrichmentIds: enrichment, + volume, + frequency, + confidence: confidence_target, + }); + + // amounts in öre (docs/03 convention) + return NextResponse.json({ + total_ore: est.price * 100, + deposit_ore: est.deposit * 100, + balance_ore: est.remainder * 100, + est_days: est.timelineDays, + est_confidence: est.estConfidence / 100, + recurring: est.recurring, + }); +} diff --git a/app/api/health/route.ts b/app/api/health/route.ts new file mode 100644 index 0000000..282ff75 --- /dev/null +++ b/app/api/health/route.ts @@ -0,0 +1,12 @@ +import { NextResponse } from "next/server"; + +// GET /api/health — platform liveness (docs/04). DB/queue wired when provisioned. +export async function GET() { + return NextResponse.json({ + ok: true, + service: "0pt-web", + db: Boolean(process.env.DATABASE_URL) ? "configured" : "not_configured", + queue: Boolean(process.env.REDIS_URL) ? "configured" : "not_configured", + ts: new Date().toISOString(), + }); +} diff --git a/app/api/sources/route.ts b/app/api/sources/route.ts new file mode 100644 index 0000000..674cc0b --- /dev/null +++ b/app/api/sources/route.ts @@ -0,0 +1,19 @@ +import { NextResponse } from "next/server"; + +// GET /api/sources (docs/04) — the transparency moat. Legal sourcing only (CLAUDE.md §1). +// access: api | bulk | authorized_web | licensed. VERIFY current terms before relying. +const SOURCES = [ + { source_id: "gleif", name: "GLEIF (LEI)", market: "global", access: "api", licence: "open (CC0) — verify", cadence: "daily", confidence: 0.98 }, + { source_id: "brreg", name: "Brønnøysundregistrene", market: "NO", access: "api", licence: "NLOD open — verify", cadence: "daily", confidence: 0.97 }, + { source_id: "companies_house", name: "Companies House", market: "GB", access: "api", licence: "free (key) — verify", cadence: "daily", confidence: 0.97 }, + { source_id: "cvr", name: "CVR / Virk", market: "DK", access: "api", licence: "terms apply — verify", cadence: "daily", confidence: 0.95 }, + { source_id: "prh", name: "PRH avoindata", market: "FI", access: "api", licence: "CC-BY — verify", cadence: "daily", confidence: 0.93 }, + { source_id: "bolagsverket", name: "Bolagsverket", market: "SE", access: "licensed", licence: "restricted bulk — partner route", cadence: "daily", confidence: 0.92 }, + { source_id: "rdw", name: "RDW (vehicles)", market: "NL", access: "api", licence: "open — verify", cadence: "daily", confidence: 0.9 }, + { source_id: "traficom", name: "Traficom (vehicles)", market: "FI", access: "bulk", licence: "CC-BY — verify", cadence: "quarterly", confidence: 0.88 }, + { source_id: "opensanctions", name: "OpenSanctions", market: "global", access: "bulk", licence: "open — verify commercial terms", cadence: "daily", confidence: 0.95 }, +]; + +export async function GET() { + return NextResponse.json(SOURCES); +} diff --git a/sql/001_init.sql b/sql/001_init.sql new file mode 100644 index 0000000..cb119c4 --- /dev/null +++ b/sql/001_init.sql @@ -0,0 +1,137 @@ +-- 0pt — initial schema (docs/03-data-model.md). Postgres + pgvector. +-- Amounts in öre (integer). Every fact links to bridge_provenance. +CREATE EXTENSION IF NOT EXISTS vector; +CREATE EXTENSION IF NOT EXISTS pgcrypto; + +-- ── Data entities ─────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS dim_source ( + source_id text PRIMARY KEY, + name text NOT NULL, + market text, + access text, -- api | bulk | authorized_web | licensed + licence text, + cadence text, + url text +); + +CREATE TABLE IF NOT EXISTS dim_company ( + org_nr text PRIMARY KEY, + market text NOT NULL, + lei text, + name text NOT NULL, + status text, + nace text, + registered_at date, + address jsonb, + website text, + updated_at timestamptz NOT NULL DEFAULT now(), + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS fact_financials ( + org_nr text REFERENCES dim_company(org_nr), + fiscal_year int NOT NULL, + revenue bigint, result bigint, employees int, + source_id text REFERENCES dim_source(source_id), + PRIMARY KEY (org_nr, fiscal_year) +); + +CREATE TABLE IF NOT EXISTS dim_contact ( + contact_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_nr text REFERENCES dim_company(org_nr), + name text, role text, email text, phone text, linkedin text, + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS dim_ubo ( + ubo_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_nr text REFERENCES dim_company(org_nr), + owner text, share numeric(5,2) +); + +CREATE TABLE IF NOT EXISTS dim_vehicle ( + vin text PRIMARY KEY, + market text NOT NULL, + reg_plate text, make text, model text, year int, + owner_org text REFERENCES dim_company(org_nr), + specs jsonb, + updated_at timestamptz NOT NULL DEFAULT now() +); + +-- ── Provenance (the signature) ────────────────────────────────── +CREATE TABLE IF NOT EXISTS bridge_provenance ( + field_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + entity_type text NOT NULL, -- company|contact|vehicle|financials + entity_key text NOT NULL, + field_name text NOT NULL, + source_id text REFERENCES dim_source(source_id), + freshness date, + confidence numeric(4,3) NOT NULL, + level smallint NOT NULL, -- 0 unavailable/licensed,1 single,2 partial,3 corroborated + agreed_sources int DEFAULT 1, + UNIQUE (entity_type, entity_key, field_name) +); +CREATE INDEX IF NOT EXISTS idx_prov_entity ON bridge_provenance (entity_type, entity_key); + +-- ── Platform tables ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS orgs ( + org_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + name text NOT NULL, created_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS users ( + user_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid REFERENCES orgs(org_id), + email text UNIQUE NOT NULL, + role text NOT NULL DEFAULT 'member', + created_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS orders ( + order_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid REFERENCES orgs(org_id), + flow text NOT NULL, + status text NOT NULL DEFAULT 'draft', + config jsonb NOT NULL, + total_ore bigint, deposit_ore bigint, balance_ore bigint, + est_days int, est_confidence numeric(4,3), + created_at timestamptz DEFAULT now(), updated_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS jobs ( + job_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + order_id uuid REFERENCES orders(order_id), + stage text, pct numeric(5,2) DEFAULT 0, state text DEFAULT 'queued', + metrics jsonb, started_at timestamptz, finished_at timestamptz +); +CREATE TABLE IF NOT EXISTS deliveries ( + delivery_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + order_id uuid REFERENCES orders(order_id), + formats text[], destinations text[], + record_count int, avg_confidence numeric(4,3), + quality_report jsonb, provenance_export_url text, files jsonb, + created_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS subscriptions ( + sub_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + order_id uuid REFERENCES orders(order_id), + cadence text, webhook_url text, status text DEFAULT 'active', next_run_at timestamptz +); +CREATE TABLE IF NOT EXISTS files ( + file_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid REFERENCES orgs(org_id), order_id uuid REFERENCES orders(order_id), + name text, mime text, bytes bigint, r2_key text, created_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS db_grants ( + grant_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid REFERENCES orgs(org_id), order_id uuid REFERENCES orders(order_id), + conn_encrypted bytea NOT NULL, scope text, expires_at timestamptz, revoked_at timestamptz, + created_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS payments ( + payment_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + order_id uuid REFERENCES orders(order_id), + kind text, amount_ore bigint, stripe_ref text, status text, + created_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS audit_log ( + id bigserial PRIMARY KEY, + actor text, action text, target text, meta jsonb, at timestamptz DEFAULT now() +);