Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d907d23a48 | ||
|
|
7a07fb0d2c | ||
|
|
166516cdb7 |
@@ -68,10 +68,6 @@ INTERNAL_TOKEN=change-me-internal-token
|
||||
#
|
||||
# Fleet Zitadel issuer (OIDC). Default when unset: https://id-customers.siax.io
|
||||
ZITADEL_ISSUER=https://id-customers.siax.io
|
||||
# Browser login (Authorization Code + PKCE). Create a Web application in the
|
||||
# Zitadel project with redirect URI https://0pt.app/api/auth/callback.
|
||||
ZITADEL_OIDC_CLIENT_ID=
|
||||
ZITADEL_OIDC_CLIENT_SECRET=
|
||||
# Enforcement is FAIL-CLOSED. Leave this UNSET (or set it to "true") and a
|
||||
# valid, verified Bearer token is REQUIRED on /api/0pt/* -- 401 on
|
||||
# missing/invalid, 403 when X-Tenant-Id disagrees with the token tenant.
|
||||
@@ -206,81 +202,3 @@ NOCODB_API_TOKEN=
|
||||
# Test-only (tests/p0 real-infra suite; not needed to run the app)
|
||||
# ---------------------------------------------------------------------------
|
||||
# ST0RE_TEST_TENANT_ID=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Document workbench (upload -> DOC0 -> INF0 -> validated export -> credits)
|
||||
# Wired in code today: app/api/0pt/documents/*, app/api/0pt/credits/*.
|
||||
# Every value is optional to boot and mandatory to USE: a missing integration
|
||||
# makes its route answer 503 "not configured" instead of fabricating success.
|
||||
# ---------------------------------------------------------------------------
|
||||
# DOC0 document service. URL must be absolute HTTPS; token is a service PAT.
|
||||
DOC0_URL=https://doc0.siax.io
|
||||
DOC0_SERVICE_TOKEN=
|
||||
# The DOC0 service identity's own actor id (token subject). DOC0 rejects an
|
||||
# x-actor-id it has no actor_grant for; 0pt keeps the end-user actor in its own
|
||||
# journal and lets the DOC0 call act as the service.
|
||||
DOC0_SERVICE_ACTOR_ID=
|
||||
# Maximum accepted upload size (bytes). Default 25 MiB.
|
||||
OPT_MAX_UPLOAD_BYTES=26214400
|
||||
|
||||
# Interim AI path: self-hosted Ollama on the SIAX decision server
|
||||
# (server-decision-01). Internal only; no provider key and no per-token cost.
|
||||
# Plain HTTP is accepted only for loopback/RFC1918/tailnet hosts.
|
||||
DECISION_OLLAMA_URL=http://100.96.133.104:11434
|
||||
DECISION_OLLAMA_MODEL=hermes-qwen3.5:9b
|
||||
|
||||
# INF0 AI gateway (model calls). No provider key is ever placed in this repo.
|
||||
# Live path today: the LiteLLM gateway (OpenAI-compatible). The native
|
||||
# /v1/inf0/* surface is contract-only; INF0_URL is used as a fallback.
|
||||
INF0_GATEWAY_URL=https://ai-gateway.siax.io/v1
|
||||
INF0_GATEWAY_LITELLM_KEY=
|
||||
INF0_GATEWAY_PROVIDER_KIND=external
|
||||
INF0_URL=https://api.inf0.siax.io
|
||||
INF0_API_TOKEN=
|
||||
|
||||
# PAY0 (optional; Stripe is used directly for credit checkout today).
|
||||
PAY0_URL=https://pay0.siax.io
|
||||
PAY0_API_TOKEN=
|
||||
|
||||
# N0D / ST0RE (used by the broader pipeline; not required by the routes above).
|
||||
N0D_URL=https://api.n0d.siax.io
|
||||
N0D_API_TOKEN=
|
||||
ST0RE_URL=https://api.st0re.siax.io
|
||||
ST0RE_API_TOKEN=
|
||||
|
||||
# OpenFGA project authorization. Without all four values, document routes fail
|
||||
# closed with PROJECT_AUTHORIZATION_NOT_CONFIGURED.
|
||||
OPENFGA_API_URL=https://fga.siax.io
|
||||
OPENFGA_STORE_ID=
|
||||
OPENFGA_MODEL_ID=
|
||||
OPENFGA_AUTH_TOKEN=
|
||||
|
||||
# Transitional, server-owned project grants used only when OpenFGA is not
|
||||
# configured. JSON array; actorId "*" means every verified actor in the tenant.
|
||||
# OPT_PROJECT_GRANTS=[{"tenantId":"379976258701823235","projectId":"prj_demo","actorId":"*"}]
|
||||
OPT_PROJECT_GRANTS=
|
||||
|
||||
# Model policy for the document workbench. Without this, structuring answers
|
||||
# MODEL_POLICY_NOT_CONFIGURED.
|
||||
OPT_ALLOWED_MODELS=
|
||||
OPT_ALLOWED_DATA_CLASSES=none,low
|
||||
OPT_MODEL_DESTINATION=external
|
||||
OPT_EXTERNAL_TRANSFER_ALLOWED=false
|
||||
OPT_MODEL_MAX_INPUT_TOKENS=60000
|
||||
OPT_MODEL_MAX_OUTPUT_TOKENS=4000
|
||||
|
||||
# Server-owned, versioned credit price book (JSON, one line). No price is ever
|
||||
# read from a browser. Without it, credit packs/checkout/structuring answer
|
||||
# PRICE_BOOK_NOT_CONFIGURED.
|
||||
# {"version":"2026-11-01","currency":"SEK","packs":[{"id":"starter","credits":100,"amountMinor":9900}],"metering":{"pagesPerCredit":5,"inputTokensPerCredit":20000,"outputTokensPerCredit":4000}}
|
||||
OPT_CREDIT_PRICE_BOOK=
|
||||
|
||||
# Pilot switch. `off` runs document structuring without a wallet; it is
|
||||
# explicit (never a silent fallback), the response reports `credits: null`, and
|
||||
# purchases stay disabled. Unset/`on` requires the price book + ledger.
|
||||
OPT_CREDITS_MODE=
|
||||
|
||||
# Central Keycloak (SIAX Portal)
|
||||
KEYCLOAK_ISSUER=https://auth.portal.siax.dev/realms/portal
|
||||
KEYCLOAK_EXPECTED_AUDIENCE=account
|
||||
KEYCLOAK_AUTHORIZED_PARTY=siax-portal
|
||||
|
||||
+8
-17
@@ -6,30 +6,21 @@ name: Deploy to Coolify
|
||||
# Dockerfile (build_pack: dockerfile) -- this workflow only fires the
|
||||
# rebuild+redeploy, it doesn't build or push an image itself.
|
||||
#
|
||||
# STATUS (verified 2026-11-02): LIVE. The Coolify application exists
|
||||
# (dockerfile build pack, git.siax.io/sax3l/0pt, branch main) and its UUID is
|
||||
# supplied by the repository variable COOLIFY_APP_ID; COOLIFY_TOKEN and the
|
||||
# registry/cosign secrets are set. A push to main, or a manual
|
||||
# workflow_dispatch of this file, has been proven to verify the signed
|
||||
# attestation for the exact commit and then return HTTP 200 from Coolify.
|
||||
# The placeholder guard below remains as a fail-closed guard, not as a TODO.
|
||||
# Operational procedure and verification live in docs/runbook/deploy.md.
|
||||
# STATUS (2026-08-09): no Coolify application has been provisioned for 0pt
|
||||
# yet -- siax.config.json's `deploy.target` was flipped from "vercel" to
|
||||
# "coolify" to state the intended platform, but there is no app UUID to
|
||||
# point at. COOLIFY_APP_ID below is a literal placeholder. The guard step
|
||||
# fails the job loudly (rather than silently POSTing to a bogus/empty URL)
|
||||
# until both the Coolify app exists and its real UUID replaces the
|
||||
# placeholder here. See docs/architecture/ARCHITECTURE.md §5/§8 for the
|
||||
# open "Vercel or fleet" question this resolves the config side of.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
# Never let two deploys race the same Coolify app. Unlike CI we do NOT cancel an
|
||||
# in-flight deploy (it may already be restarting the container); the newest
|
||||
# commit still wins because Coolify builds from the branch head.
|
||||
concurrency:
|
||||
group: deploy-0pt-main
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
COOLIFY_APP_ID: ${{ vars.COOLIFY_APP_ID || 'TODO-no-coolify-app-provisioned-yet' }}
|
||||
IMAGE_REPO: git.cloud.siax.io/sax3l/0pt
|
||||
|
||||
+2
-50
@@ -17,20 +17,13 @@ name: CI (SIAX Cloud)
|
||||
# push/PR/weekly scanner (this file is push/PR-only).
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
# One run per ref; a branch push that also updates a PR used to start two full
|
||||
# quality runs (and, on main, two deploy chains). Cancel the superseded one.
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
@@ -44,13 +37,6 @@ jobs:
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Typecheck (tsc over src/ + tests/ -- blocking)
|
||||
run: pnpm run typecheck
|
||||
# UI-09: 0pt carried 82 axe color-contrast violations (impact=serious), the
|
||||
# estate's largest single a11y defect, and every one came from a Tailwind
|
||||
# alpha modifier on a text colour. The unmodified token measures 4.73:1
|
||||
# light / 7.63:1 dark and passes AA; every faded variant fails. Blocking,
|
||||
# because a contrast regression is invisible in review.
|
||||
- name: Text contrast shape (WCAG 2.2 AA 1.4.3 -- blocking)
|
||||
run: pnpm run check:contrast
|
||||
- name: Test (vitest -- blocking)
|
||||
run: pnpm run test
|
||||
- name: Lint (eslint -- advisory; legacy tree has pre-existing noise)
|
||||
@@ -83,7 +69,6 @@ jobs:
|
||||
# ordinary branch pushes still run blocking quality/security.
|
||||
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
services:
|
||||
opt-ci-opensearch:
|
||||
image: opensearchproject/opensearch:2.11.1
|
||||
@@ -234,44 +219,11 @@ jobs:
|
||||
# measurable blind spot into declared policy.
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Trivy
|
||||
run: |
|
||||
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
|
||||
# `siax/sbom/` är CycloneDX-evidenens för REDAN BYGGDA images (release-kedjan),
|
||||
# inte källberoenden. Att scanna dem här återrapporterar gamla image-versioner
|
||||
# (next 16.3.x, sharp 0.35.4) och blockerar källfixar som redan är patchade.
|
||||
# Image-SBOM:erna verifieras i release/image-pipelinen.
|
||||
- name: Trivy scan (vuln + secrets -- BLOCKING, fails on HIGH/CRITICAL)
|
||||
run: |
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 --skip-dirs 'siax/sbom' .
|
||||
|
||||
sonar:
|
||||
# SonarQube Community Build har inget separat PR-analysläge (en enda "main"-gren
|
||||
# per projekt) — en analys från en PR-branch eller en tagg-push som inte pekar på
|
||||
# main skulle skriva över kvalitetshistoriken. Kör därför bara
|
||||
# vid push till main.
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: SonarQube analysis (self-hosted sonar.siax.io)
|
||||
env:
|
||||
SONAR_HOST_URL: https://sonar.siax.io
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -n "$SONAR_TOKEN" || { echo "::error::SONAR_TOKEN repo secret missing"; exit 1; }
|
||||
# Jobbet kör i en container på act_runner; "docker run -v \"\$PWD:...\""
|
||||
# skulle montera VÄRDENS (tomma) sökväg. Kopiera in källträdet istället.
|
||||
cid=$(docker create -e SONAR_HOST_URL -e SONAR_TOKEN -w /usr/src \
|
||||
sonarsource/sonar-scanner-cli:latest \
|
||||
sonar-scanner -Dsonar.projectKey=0pt -Dsonar.host.url="$SONAR_HOST_URL")
|
||||
trap 'docker rm -f "$cid" >/dev/null 2>&1 || true' EXIT
|
||||
docker cp . "$cid":/usr/src
|
||||
docker start -a "$cid"
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 .
|
||||
|
||||
@@ -15,7 +15,6 @@ on:
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Masterplan lock check
|
||||
|
||||
@@ -8,14 +8,9 @@ on:
|
||||
schedule:
|
||||
- cron: "0 4 * * *" # daily 04:00 UTC
|
||||
|
||||
concurrency:
|
||||
group: nightly-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
@@ -39,7 +34,6 @@ jobs:
|
||||
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Trivy
|
||||
@@ -51,4 +45,4 @@ jobs:
|
||||
# detection was the one guaranteed to stay green. Fixed 2026-09-08.
|
||||
- name: Trivy fs scan (vuln + secrets -- fails on HIGH/CRITICAL)
|
||||
run: |
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 --skip-dirs 'siax/sbom' .
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 .
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
name: Production smoke (0pt.app)
|
||||
|
||||
# Automated end-to-end delivery verification. Every 30 minutes (and on demand)
|
||||
# this checks that the live service is actually ready and that the running
|
||||
# container is the commit that main points at — so a green deploy is never
|
||||
# confused with a healthy, current service.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "*/30 * * * *"
|
||||
|
||||
concurrency:
|
||||
group: prod-smoke
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
smoke:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Readiness (retry on a fresh deploy)
|
||||
run: |
|
||||
set -eu
|
||||
for attempt in 1 2 3 4 5 6; do
|
||||
body="$(curl -fsS --max-time 15 https://0pt.app/api/ready || true)"
|
||||
echo "attempt $attempt: ${body:-<no response>}"
|
||||
if printf '%s' "$body" | grep -q '"ready":true'; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 20
|
||||
done
|
||||
echo "::error::0pt.app/api/ready never reported ready:true"
|
||||
exit 1
|
||||
|
||||
- name: Health envelope
|
||||
run: |
|
||||
set -eu
|
||||
body="$(curl -fsS --max-time 15 https://0pt.app/api/health)"
|
||||
echo "$body"
|
||||
printf '%s' "$body" | grep -q '"db":"ok"' || { echo "::error::database is not ok"; exit 1; }
|
||||
printf '%s' "$body" | grep -q '"stripe":"ok"' || { echo "::error::stripe is not ok"; exit 1; }
|
||||
|
||||
- name: Deployed commit equals main
|
||||
env:
|
||||
SIAX_CI_TOKEN: ${{ secrets.SIAX_CI_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
version="$(curl -fsS --max-time 15 https://0pt.app/api/version)"
|
||||
echo "$version"
|
||||
running="$(printf '%s' "$version" | sed -n 's/.*"commit":"\([0-9a-f]*\)".*/\1/p')"
|
||||
[ -n "$running" ] || { echo "::error::/api/version returned no commit"; exit 1; }
|
||||
if [ -z "${SIAX_CI_TOKEN:-}" ]; then
|
||||
echo "::warning::SIAX_CI_TOKEN is not set — cannot compare with main; commit $running is live"
|
||||
exit 0
|
||||
fi
|
||||
expected="$(curl -fsS --max-time 15 \
|
||||
-H "Authorization: token ${SIAX_CI_TOKEN}" \
|
||||
"https://git.siax.io/api/v1/repos/admin/0pt/commits?limit=1" \
|
||||
| python3 -c 'import sys,json; print(json.load(sys.stdin)[0]["sha"])')"
|
||||
echo "running=$running expected(main)=$expected"
|
||||
[ -n "$expected" ] || { echo "::error::could not read main SHA from Gitea"; exit 1; }
|
||||
[ "$running" = "$expected" ] || {
|
||||
echo "::error::production is $running but main is $expected — deploy did not land"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Document pipeline surface responds (auth required, never 404/5xx)
|
||||
run: |
|
||||
set -eu
|
||||
for path in /api/0pt/documents/upload /api/0pt/documents/structure /api/0pt/documents/models /api/0pt/credits/balance; do
|
||||
code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -X POST "https://0pt.app${path}")"
|
||||
echo "$path -> $code"
|
||||
case "$code" in
|
||||
401|405) ;; # unauthenticated or method guard: the route exists
|
||||
*) echo "::error::$path returned $code (expected 401/405)"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
@@ -29,8 +29,8 @@ name: Release chain (G17, ADR-W16-003)
|
||||
# workflow file -- learned the hard way on sax3l/h0st's and sax3l/aud0's
|
||||
# own G17 migrations. 0pt does not wire a G20 post-deploy step in this
|
||||
# pass at all (see `.siax/hooks/README.md` "G20 -- deliberately not wired
|
||||
# yet": the app is now provisioned and `/api/version` exists, but G20 is still
|
||||
# not wired in this pass), so the single-job constraint that forces G20 into its own
|
||||
# yet": no Coolify application provisioned for 0pt, no `/version`
|
||||
# endpoint), so the single-job constraint that forces G20 into its own
|
||||
# workflow file elsewhere does not yet bite here -- documented anyway so a
|
||||
# future PR adding G20 does not repeat the mistake.
|
||||
|
||||
@@ -39,11 +39,6 @@ on:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
IMAGE_REPO: git.cloud.siax.io/sax3l/0pt
|
||||
DOCKERFILE: Dockerfile
|
||||
@@ -55,75 +50,41 @@ env:
|
||||
# G17_LICENSE_ALLOW policy in .siax/hooks/G17.sh) and #59 (G20 retry
|
||||
# logic -- not used by 0pt yet, but the pin picks up main's current tip
|
||||
# rather than an older commit, matching what a fresh migration reviews).
|
||||
#
|
||||
# Re-pin 2026-09-25 (medveten, granskad): 9a3a0aa -> 09504e3a. Deltaet ar
|
||||
# EN merge, siax-templates #138 "Upload complete release evidence and
|
||||
# validate artifact receipt". Enda berorda filer under ci/v2 ar
|
||||
# reference-hooks/{G17.sh, G17-ADR-W16-003.md, lib/emit-release-evidence.py,
|
||||
# lib/test_emit_release_evidence.py}. Andringen ar bakatkompatibel by
|
||||
# design: ST0RE-uppladdningen ar OPT-IN via G17_REQUIRE_ST0RE (default 0),
|
||||
# sa en AUD0-only-konsument som 0pt kor exakt samma vag som forut.
|
||||
#
|
||||
# Deliberately NO branch name here: the pinned commit is checked out
|
||||
# DIRECTLY (see the step below). The previous shape -- clone `main`, then
|
||||
# require its HEAD to equal this pin -- turned every unrelated merge in
|
||||
# siax-templates into a red release chain here (CD-03 / CI-RED-02) while
|
||||
# nothing was actually unsafe. Checking the pin out directly keeps the pin
|
||||
# a real supply-chain control (the gate runs exactly this reviewed commit,
|
||||
# or it fails) without coupling it to someone else's branch tip.
|
||||
SIAX_TEMPLATES_PINNED_SHA: 09504e3a593ee8ce0eaba606df31c349a3d52277
|
||||
SIAX_TEMPLATES_REF: main
|
||||
SIAX_TEMPLATES_PINNED_SHA: 9a3a0aa93c28a4538ecdb98658158f19cb23a6f9
|
||||
SIAX_TEMPLATES_DIR: /tmp/siax-templates-g17-ref
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Build, push, G17 (SBOM/scan/attest/verify/evidence)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: https://git.siax.io/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4, mirrored + SHA-pinned (SUP-06, same pin n0d/cl0ud/st0re/h0st already use)
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# --- fetch the shared G17 reference implementation -----------------
|
||||
# Same authenticated-fetch-at-runtime mechanism this repo's OLD
|
||||
# Same authenticated-clone-at-runtime mechanism this repo's OLD
|
||||
# release.yml already used SIAX_CI_TOKEN for (the evidence-commit
|
||||
# push a prior PR deleted) -- see .siax/hooks/G17.sh's header for why
|
||||
# push this PR deletes) -- see .siax/hooks/G17.sh's header for why
|
||||
# NOT a `uses:` reusable workflow / submodule / vendored copy. Fails
|
||||
# closed if the exact commit this adapter was reviewed against cannot
|
||||
# be checked out (removed or rewritten upstream); an unrelated merge
|
||||
# on siax-templates' own main is NOT a failure and never was a real
|
||||
# signal.
|
||||
- name: Fetch siax-templates G17 reference (pinned commit)
|
||||
# closed if the branch has moved past the exact commit this adapter
|
||||
# was reviewed against.
|
||||
- name: Fetch siax-templates G17 reference (pinned)
|
||||
env:
|
||||
SIAX_CI_TOKEN: ${{ secrets.SIAX_CI_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -rf "$SIAX_TEMPLATES_DIR"
|
||||
mkdir -p "$SIAX_TEMPLATES_DIR"
|
||||
git -C "$SIAX_TEMPLATES_DIR" init --quiet
|
||||
git -C "$SIAX_TEMPLATES_DIR" remote add origin \
|
||||
"https://oauth2:${SIAX_CI_TOKEN}@git.siax.io/${SIAX_TEMPLATES_REPO}.git"
|
||||
# Ask for the pinned commit by SHA -- one shallow commit, no branch
|
||||
# involved. A server with uploadpack.allowReachableSHA1InWant off
|
||||
# refuses that, so fall back to fetching the branches and taking the
|
||||
# same commit out of them. Either way the work tree ends up at
|
||||
# exactly $SIAX_TEMPLATES_PINNED_SHA, never at a branch tip.
|
||||
if ! git -C "$SIAX_TEMPLATES_DIR" fetch --quiet --depth 1 origin "$SIAX_TEMPLATES_PINNED_SHA"; then
|
||||
echo "note: server refused a by-SHA fetch; falling back to fetching all branches"
|
||||
git -C "$SIAX_TEMPLATES_DIR" fetch --quiet origin
|
||||
fi
|
||||
if ! git -C "$SIAX_TEMPLATES_DIR" -c advice.detachedHead=false \
|
||||
checkout --quiet --detach "$SIAX_TEMPLATES_PINNED_SHA"; then
|
||||
echo "::error::siax-templates commit $SIAX_TEMPLATES_PINNED_SHA not found in $SIAX_TEMPLATES_REPO -- the reviewed commit was removed or rewritten upstream. Re-review siax-templates and update SIAX_TEMPLATES_PINNED_SHA deliberately."
|
||||
exit 1
|
||||
fi
|
||||
git clone --quiet --branch "$SIAX_TEMPLATES_REF" \
|
||||
"https://oauth2:${SIAX_CI_TOKEN}@git.siax.io/${SIAX_TEMPLATES_REPO}.git" "$SIAX_TEMPLATES_DIR"
|
||||
actual_sha="$(git -C "$SIAX_TEMPLATES_DIR" rev-parse HEAD)"
|
||||
if [ "$actual_sha" != "$SIAX_TEMPLATES_PINNED_SHA" ]; then
|
||||
echo "::error::checked-out siax-templates HEAD is $actual_sha, expected the pinned $SIAX_TEMPLATES_PINNED_SHA -- refusing to run an unreviewed version of the gate."
|
||||
echo "::error::siax-templates $SIAX_TEMPLATES_REF moved (now $actual_sha, pinned $SIAX_TEMPLATES_PINNED_SHA) -- refusing to run an unreviewed version of the gate. Re-review and update SIAX_TEMPLATES_PINNED_SHA deliberately."
|
||||
exit 1
|
||||
fi
|
||||
chmod +x "$SIAX_TEMPLATES_DIR/ci/v2/reference-hooks/"*.sh "$SIAX_TEMPLATES_DIR/ci/v2/reference-hooks/lib/"*.sh
|
||||
echo "siax-templates G17 reference @ $actual_sha (pinned commit, checked out directly)"
|
||||
echo "siax-templates G17 reference @ $actual_sha (pinned, verified)"
|
||||
|
||||
- name: Resolve SHA + tag (never :latest)
|
||||
id: sha
|
||||
@@ -181,4 +142,3 @@ jobs:
|
||||
# submission (bar item 7, step above) is already the durable evidence
|
||||
# record; a convenience local copy is not worth re-triggering that
|
||||
# known breakage.
|
||||
|
||||
|
||||
@@ -19,20 +19,15 @@ name: Security Scan (SIAX Cloud)
|
||||
# and docs/compliance/GOLDEN-STANDARD-REPORT.md control C6 for full context.
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 5 * * 1" # weekly Monday re-scan
|
||||
|
||||
|
||||
concurrency:
|
||||
group: security-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Trivy
|
||||
@@ -40,4 +35,4 @@ jobs:
|
||||
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
|
||||
- name: Trivy fs scan (vuln + secrets -- fails on HIGH/CRITICAL)
|
||||
run: |
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 --skip-dirs 'siax/sbom' .
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 .
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
name: VehIQ OLTP extractor (0pt ingestion)
|
||||
|
||||
# P070 — scheduled poll of app.dealer_stock_entry/app.deal (VehIQ, server10)
|
||||
# into opt_dataset_projection (ClickHouse), via the watermark extractor in
|
||||
# src/ingestion/vehiq-oltp-ingest-runner.ts. See docs/P070_VEHIQ_OLTP_
|
||||
# EXTRACTOR.md for the full design and "what activating this requires".
|
||||
#
|
||||
# SAFE BY DEFAULT: VEHIQ_INGEST_MODE defaults to "preview" (read-only, never
|
||||
# commits a checkpoint, never writes) below. With no VEHIQ_SOURCE_DATABASE_URL
|
||||
# secret configured on this repo, the script logs "not_configured" and exits
|
||||
# 0 — this workflow can be left enabled indefinitely with zero effect on
|
||||
# anything until BOTH the secret is added AND VEHIQ_INGEST_MODE is changed
|
||||
# to "run". Neither is done by this workflow file itself.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "*/15 * * * *"
|
||||
|
||||
jobs:
|
||||
extract:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
VEHIQ_SOURCE_DATABASE_URL: ${{ secrets.VEHIQ_SOURCE_DATABASE_URL }}
|
||||
DATABASE_URL: ${{ secrets.DATABASE_URL }}
|
||||
OPT_ANALYTICS_CLICKHOUSE_BASE_URL: ${{ secrets.OPT_ANALYTICS_CLICKHOUSE_BASE_URL }}
|
||||
OPT_ANALYTICS_CLICKHOUSE_BASIC_AUTH: ${{ secrets.OPT_ANALYTICS_CLICKHOUSE_BASIC_AUTH }}
|
||||
OPT_ANALYTICS_CLICKHOUSE_DATABASE: opt_analytics
|
||||
# Activation gate — see docs/P070_VEHIQ_OLTP_EXTRACTOR.md. Flip to
|
||||
# "run" only once steps 1-4 in that doc's "What activating this
|
||||
# requires" section are actually done.
|
||||
VEHIQ_INGEST_MODE: preview
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Enable corepack + pin pnpm@9
|
||||
run: |
|
||||
corepack enable
|
||||
corepack prepare pnpm@9 --activate
|
||||
- name: Install (frozen lockfile)
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Run the extractor (preview mode unless activated)
|
||||
run: pnpm run vehiq:oltp-ingest
|
||||
@@ -52,6 +52,3 @@ services/scrapers/output/
|
||||
# local-only environment overrides (all real values live in Infisical)
|
||||
.env.local
|
||||
.env.production
|
||||
|
||||
# parallel git worktrees (policy: hidden inside the repo, never committed)
|
||||
/.worktrees/
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# Build output and local worktrees are not source.
|
||||
.next/
|
||||
out/
|
||||
build/
|
||||
dist/
|
||||
node_modules/
|
||||
.worktrees/
|
||||
coverage/
|
||||
*.min.js
|
||||
*.min.css
|
||||
pnpm-lock.yaml
|
||||
@@ -4,9 +4,9 @@ schemaVersion: siax.des1gn-consumer/v1
|
||||
repo: 0pt
|
||||
generatedAt: 2026-09-23T21:12:27.075Z
|
||||
consumes:
|
||||
'@siax/0pt-decision': 'härlett ur package.json (deklarerad workspace:*)'
|
||||
'@siax/config': 'härlett ur package.json (deklarerad ^0.2.1)'
|
||||
'@siax/tokens': 'härlett ur package.json (deklarerad ^0.1.2)'
|
||||
'@siax/ui': 'härlett ur package.json (deklarerad ^0.4.1)'
|
||||
@siax/0pt-decision: 'härlett ur package.json (deklarerad workspace:*)'
|
||||
@siax/config: 'härlett ur package.json (deklarerad ^0.2.1)'
|
||||
@siax/tokens: 'härlett ur package.json (deklarerad ^0.1.2)'
|
||||
@siax/ui: 'härlett ur package.json (deklarerad ^0.4.1)'
|
||||
localPrimitives: []
|
||||
notes: GENERATED stub - tomt ar den arliga baseline-formen; konsumerade kanoniska DES1GN-paket (pinned) listas under consumes, kvarvarande lokala primitives motiveras i notes.
|
||||
|
||||
+3
-4
@@ -70,10 +70,9 @@
|
||||
# picks up main's current tip rather than an older commit, matching what a
|
||||
# fresh migration reviews). Pinned at
|
||||
# 384e35060b91ea78ec045e14af114abf5d5eb23b -- the exact ref lives in
|
||||
# `.gitea/workflows/release.yml` (SIAX_TEMPLATES_PINNED_SHA, which is
|
||||
# fetched and checked out DIRECTLY by SHA -- no branch is consulted, so an
|
||||
# unrelated merge on siax-templates' main does not fail this gate; a pinned
|
||||
# commit that no longer exists upstream does).
|
||||
# `.gitea/workflows/release.yml` (SIAX_TEMPLATES_REF=main +
|
||||
# SIAX_TEMPLATES_PINNED_SHA, which refuses to run if main has moved past
|
||||
# the pin).
|
||||
set -euo pipefail
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
|
||||
@@ -45,15 +45,10 @@ Pinned to `sax3l/siax-templates` main at
|
||||
(`feat/g17-signed-deploy-gate-adr-w16-003`) merged, plus follow-up fixes
|
||||
#56/#57 (SPDX compound-license-expression evaluation, exercised live by
|
||||
this adapter's own `G17_LICENSE_ALLOW` policy) and #59 (G20 retry logic;
|
||||
not used by 0pt yet, see below). `.gitea/workflows/release.yml` fetches
|
||||
and checks out `SIAX_TEMPLATES_PINNED_SHA` **directly by SHA** and refuses
|
||||
to run if that exact commit cannot be checked out (removed or rewritten
|
||||
upstream) -- bumping the pin is a reviewed, source-controlled diff to that
|
||||
one line, never a silent re-resolution. It deliberately does **not**
|
||||
compare the pin against `main`: that branch tip moves whenever anything
|
||||
unrelated merges in `siax-templates`, and failing this chain on that said
|
||||
nothing about whether the reviewed gate was safe (CD-03 / CI-RED-02). The
|
||||
authoritative pin value is the one in `release.yml`.
|
||||
not used by 0pt yet, see below). `.gitea/workflows/release.yml`'s own
|
||||
`SIAX_TEMPLATES_PINNED_SHA` step refuses to run if `siax-templates` main
|
||||
has moved past this exact commit -- bumping the pin is a reviewed,
|
||||
source-controlled diff to that one line, never a silent re-resolution.
|
||||
|
||||
## G20 (live-digest-equality) -- deliberately not wired yet
|
||||
|
||||
|
||||
@@ -53,12 +53,7 @@ RUN corepack enable && for i in 1 2 3 4 5 6 7 8; do corepack prepare pnpm@9 --ac
|
||||
# (`.` och `packages/schemas`), och --frozen-lockfile vägrar om medlemmens
|
||||
# manifest saknas på disk.
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
|
||||
# Every workspace importer in pnpm-lock.yaml must have its manifest on disk,
|
||||
# otherwise --frozen-lockfile refuses to install. Keep this list in sync with
|
||||
# `packages/*/package.json`.
|
||||
COPY packages/schemas/package.json ./packages/schemas/package.json
|
||||
COPY packages/decision/package.json ./packages/decision/package.json
|
||||
COPY packages/siax-access/package.json ./packages/siax-access/package.json
|
||||
|
||||
# --prod=false: se punkt 4 ovan. Utan den dör `next build` på saknad typescript
|
||||
# så fort byggmiljön råkar ha NODE_ENV=production satt.
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
"use client";
|
||||
|
||||
// C8: "Importera ordrar" — the first real product host of the @siax/ui
|
||||
// ImportWizard + @siax/import-export runtime. The wizard renders the frozen
|
||||
// store snapshot; THIS host owns every pipeline step's execution and all
|
||||
// server I/O. The server (POST /api/orders/import) is the only authority:
|
||||
// it re-parses and re-validates the raw CSV, so the client-side parse below
|
||||
// exists purely to give the wizard rows to render.
|
||||
|
||||
import { ImportWizard } from "@siax/ui";
|
||||
import { createImportRunStore, type ImportRunStore, type ImportRunSnapshot } from "@siax/import-export";
|
||||
import { createImportJob } from "@siax/contracts/import-export";
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
const IMPORT_COLUMNS = ["flow", "service_type", "type", "volume", "frequency", "markets"] as const;
|
||||
|
||||
interface ServerReport {
|
||||
imported?: number;
|
||||
totalRows?: number;
|
||||
validRows?: number;
|
||||
errorCount?: number;
|
||||
errors?: { row: number; field: string; code: string; message?: string }[];
|
||||
order_ids?: string[];
|
||||
}
|
||||
|
||||
/** Client-side RFC 4180 parse — presentation only; the server re-parses the raw CSV. */
|
||||
function clientParse(text: string): Record<string, string>[] {
|
||||
const rows: string[][] = [];
|
||||
let field = "";
|
||||
let row: string[] = [];
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else inQuotes = false;
|
||||
} else field += ch;
|
||||
} else if (ch === '"') inQuotes = true;
|
||||
else if (ch === ",") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
} else if (ch === "\n") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
rows.push(row);
|
||||
row = [];
|
||||
} else if (ch !== "\r") field += ch;
|
||||
}
|
||||
if (field.length > 0 || row.length > 0) {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
}
|
||||
const nonEmpty = rows.filter((r) => r.length > 1 || (r[0] ?? "").trim() !== "");
|
||||
if (nonEmpty.length === 0) return [];
|
||||
const header = nonEmpty[0].map((h) => h.trim().toLowerCase());
|
||||
return nonEmpty.slice(1).map((cells) => {
|
||||
const obj: Record<string, string> = {};
|
||||
header.forEach((h, idx) => {
|
||||
if (h) obj[h] = (cells[idx] ?? "").trim();
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
}
|
||||
|
||||
async function postImport(mode: "validate" | "dry_run" | "execute", csv: string): Promise<{ ok: boolean; status: number; data: ServerReport & { error?: { message?: string } } }> {
|
||||
const res = await fetch("/api/orders/import", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ mode, csv }),
|
||||
});
|
||||
let data: ServerReport & { error?: { message?: string } } = {};
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
data = { error: { message: `HTTP ${res.status}` } };
|
||||
}
|
||||
return { ok: res.ok, status: res.status, data };
|
||||
}
|
||||
|
||||
export default function AdminImportPage() {
|
||||
const [rawCsv, setRawCsv] = useState<string | null>(null);
|
||||
const [store, setStore] = useState<ImportRunStore | null>(null);
|
||||
const [serverReport, setServerReport] = useState<ServerReport | null>(null);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [recentOrders, setRecentOrders] = useState<{ order_id: string; flow: string; status: string }[] | null>(null);
|
||||
|
||||
const onFile = useCallback(async (file: File) => {
|
||||
const text = await file.text();
|
||||
setRawCsv(text);
|
||||
setServerReport(null);
|
||||
setServerError(null);
|
||||
setRecentOrders(null);
|
||||
const rows = clientParse(text);
|
||||
const s = createImportRunStore({
|
||||
job: createImportJob({
|
||||
id: globalThis.crypto?.randomUUID?.() ?? `imp-${Date.now()}`,
|
||||
tenantId: "current",
|
||||
entity: "orders",
|
||||
format: "csv",
|
||||
source: { system: "0pt-admin", channel: "web" },
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
rows,
|
||||
});
|
||||
s.detect();
|
||||
setStore(s);
|
||||
}, []);
|
||||
|
||||
const onValidate = useCallback(async () => {
|
||||
if (!store || !rawCsv) return;
|
||||
setServerError(null);
|
||||
const { ok, status, data } = await postImport("validate", rawCsv);
|
||||
setServerReport(data);
|
||||
store.validate(); // local snapshot for the wizard report (same frozen kernel)
|
||||
if (!ok) setServerError(`Servervalidering avvisade filen (HTTP ${status}): ${data.error?.message ?? "okänt fel"}`);
|
||||
}, [store, rawCsv]);
|
||||
|
||||
const onDryRun = useCallback(async () => {
|
||||
if (!store || !rawCsv) return;
|
||||
setServerError(null);
|
||||
const { ok, status, data } = await postImport("dry_run", rawCsv);
|
||||
setServerReport(data);
|
||||
store.dryRun();
|
||||
if (!ok) setServerError(`Servern nekade generalrepet (HTTP ${status}): ${data.error?.message ?? "okänt fel"}`);
|
||||
}, [store, rawCsv]);
|
||||
|
||||
const onExecute = useCallback(async () => {
|
||||
if (!store || !rawCsv) return;
|
||||
setServerError(null);
|
||||
const { ok, status, data } = await postImport("execute", rawCsv);
|
||||
setServerReport(data);
|
||||
if (!ok) {
|
||||
// Server is the authority — a failed execute is terminal for this run.
|
||||
store.fail(`Servern avvisade exekveringen (HTTP ${status}): ${data.error?.message ?? "okänt fel"}`);
|
||||
return;
|
||||
}
|
||||
// Host executor proxies the server result into the store's hard gates.
|
||||
const snapshot: ImportRunSnapshot = await store.execute(async () => ({ imported: data.imported ?? 0 }));
|
||||
// Reload-persistence proof: re-read the REAL order list after import.
|
||||
try {
|
||||
const res = await fetch("/api/orders", { cache: "no-store" });
|
||||
if (res.ok) {
|
||||
const orders = (await res.json()) as { order_id: string; flow: string; status: string }[];
|
||||
const importedIds = new Set(data.order_ids ?? []);
|
||||
setRecentOrders(orders.filter((o) => importedIds.has(o.order_id)));
|
||||
}
|
||||
} catch {
|
||||
/* panel stays null — server report above still shows the truth */
|
||||
}
|
||||
void snapshot;
|
||||
}, [store, rawCsv]);
|
||||
|
||||
return (
|
||||
<main style={{ maxWidth: 720, margin: "0 auto", padding: "2rem 1rem" }}>
|
||||
<h1 style={{ fontSize: "1.5rem", marginBottom: "0.5rem" }}>Importera ordrar</h1>
|
||||
<p style={{ marginBottom: "1rem", opacity: 0.8 }}>
|
||||
CSV med kolumnerna: {IMPORT_COLUMNS.join(", ")}. Endast <code>flow</code> är obligatorisk
|
||||
(catalog | custom | subscription). Parsering och validering sker på servern —
|
||||
filen laddas inte upp förrän ett steg körs.
|
||||
</p>
|
||||
<input
|
||||
type="file"
|
||||
accept=".csv,text/csv"
|
||||
aria-label="Välj CSV-fil"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
if (f) void onFile(f);
|
||||
}}
|
||||
/>
|
||||
{store && (
|
||||
<div style={{ marginTop: "1.5rem" }}>
|
||||
<ImportWizard
|
||||
store={store}
|
||||
columns={IMPORT_COLUMNS.map((c) => ({ source: c, target: c }))}
|
||||
onMap={() => {
|
||||
store.map({ columns: IMPORT_COLUMNS.map((c) => ({ source: c, target: c, required: c === "flow" })) });
|
||||
}}
|
||||
onValidate={onValidate}
|
||||
onDryRun={onDryRun}
|
||||
onExecute={onExecute}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{serverError && (
|
||||
<p role="alert" style={{ marginTop: "1rem", color: "crimson" }}>
|
||||
{serverError}
|
||||
</p>
|
||||
)}
|
||||
{serverReport && (serverReport.errorCount ?? 0) > 0 && (
|
||||
<section style={{ marginTop: "1.5rem" }} aria-label="Felrapport från servern">
|
||||
<h2 style={{ fontSize: "1.1rem" }}>Felrader (serverns rapport)</h2>
|
||||
<ul>
|
||||
{(serverReport.errors ?? []).map((e, i) => (
|
||||
<li key={i}>
|
||||
Rad {e.row} · {e.field} · {e.code}
|
||||
{e.message ? ` — ${e.message}` : ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{recentOrders && (
|
||||
<section style={{ marginTop: "1.5rem" }} aria-label="Importerade ordrar efter reload">
|
||||
<h2 style={{ fontSize: "1.1rem" }}>Importerade ordrar (lästa från /api/orders efter import)</h2>
|
||||
{recentOrders.length === 0 ? (
|
||||
<p>Inga importerade ordrar hittades vid reload.</p>
|
||||
) : (
|
||||
<ul>
|
||||
{recentOrders.map((o) => (
|
||||
<li key={o.order_id}>
|
||||
<code>{o.order_id}</code> — {o.flow} — {o.status}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
"use client";
|
||||
|
||||
// Admin-yta: anteckningar på order — @siax/collaboration-kernelns första
|
||||
// produktkonsument (spår C). Allt nätverk går via lib/order-notes-client.ts
|
||||
// (kernel-transport över host-API): offline-läge = medvetet no-op med varning
|
||||
// (utkastet bevaras, ingen tyst förlust), stale skrivning = 409 -> banner +
|
||||
// reload av serverns aktuella version.
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { PortalShell } from "@/components/portal-shell";
|
||||
import { EmptyState, ErrorState, LoadingSkeleton } from "@/components/states";
|
||||
import {
|
||||
ConflictError,
|
||||
OfflineError,
|
||||
OrderNotesClient,
|
||||
type OrderNoteDto,
|
||||
} from "@/lib/order-notes-client";
|
||||
|
||||
interface Order {
|
||||
order_id: string;
|
||||
flow: string;
|
||||
status: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export default function OrderNotesPage() {
|
||||
const [orders, setOrders] = useState<Order[] | null>(null);
|
||||
const [orderId, setOrderId] = useState<string>("");
|
||||
const [notes, setNotes] = useState<OrderNoteDto[] | null>(null);
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
const [offlineMode, setOfflineMode] = useState(false);
|
||||
const [draft, setDraft] = useState("");
|
||||
const [editing, setEditing] = useState<{ note: OrderNoteDto; body: string } | null>(null);
|
||||
|
||||
const client = useMemo(() => new OrderNotesClient("admin-simon"), []);
|
||||
|
||||
useEffect(() => {
|
||||
client.transport.setOffline(offlineMode);
|
||||
}, [client, offlineMode]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/orders", { cache: "no-store" });
|
||||
if (!res.ok) throw new Error("orders fetch failed");
|
||||
const body = await res.json();
|
||||
setOrders(Array.isArray(body) ? body : []);
|
||||
} catch {
|
||||
setLoadError(true);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const loadNotes = useCallback(
|
||||
async (id: string) => {
|
||||
setNotes(null);
|
||||
setLoadError(false);
|
||||
try {
|
||||
const { notes: loaded } = await client.load(id);
|
||||
setNotes(loaded);
|
||||
} catch {
|
||||
setLoadError(true);
|
||||
}
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
const addNote = useCallback(async () => {
|
||||
if (!orderId || !draft.trim()) return;
|
||||
if (offlineMode) {
|
||||
// Offline = klient-varning + no-op. Utkastet ligger kvar i rutan —
|
||||
// INGET skickas, inget försvinner tyst.
|
||||
toast.warning("Offline-läge: anteckningen SKICKAS EJ. Utkastet är bevarat i rutan.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const note = await client.add(orderId, draft);
|
||||
setDraft("");
|
||||
setNotes((prev) => [...(prev ?? []), note]);
|
||||
toast.success("Anteckning sparad");
|
||||
} catch (err) {
|
||||
if (err instanceof OfflineError) {
|
||||
toast.warning("Offline: inget skickades — utkastet är bevarat.");
|
||||
return;
|
||||
}
|
||||
setLoadError(true);
|
||||
}
|
||||
}, [client, draft, offlineMode, orderId]);
|
||||
|
||||
const saveEdit = useCallback(async () => {
|
||||
if (!editing) return;
|
||||
if (offlineMode) {
|
||||
toast.warning("Offline-läge: ändringen SKICKAS EJ. Texten är bevarad i redigeringsrutan.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const updated = await client.update(editing.note, editing.body, editing.note.version);
|
||||
setNotes((prev) => (prev ?? []).map((n) => (n.note_id === updated.note_id ? updated : n)));
|
||||
setEditing(null);
|
||||
toast.success("Anteckning uppdaterad");
|
||||
} catch (err) {
|
||||
if (err instanceof ConflictError) {
|
||||
// Någon annan skrev samtidigt (stale version -> 409). Ladda om
|
||||
// serverns aktuella version — förlora ALDRIG den lokala texten tyst.
|
||||
toast.error(`Konflikt: anteckningen ändrades av någon annan (serverversion ${err.currentVersion}). Laddar om — din text finns kvar nedan.`);
|
||||
setDraft((prev) => (prev ? prev : editing.body));
|
||||
await loadNotes(orderId);
|
||||
setEditing(null);
|
||||
return;
|
||||
}
|
||||
if (err instanceof OfflineError) {
|
||||
toast.warning("Offline: inget skickades — ändringen är bevarad.");
|
||||
return;
|
||||
}
|
||||
setLoadError(true);
|
||||
}
|
||||
}, [client, editing, loadNotes, offlineMode, orderId]);
|
||||
|
||||
return (
|
||||
<PortalShell variant="admin" title="Orderanteckningar">
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={offlineMode}
|
||||
onChange={(e) => setOfflineMode(e.target.checked)}
|
||||
/>
|
||||
Offline-läge (blockera utskick — varning + no-op, utkast bevaras)
|
||||
</label>
|
||||
{offlineMode && (
|
||||
<div role="alert" className="rounded border border-amber-400 bg-amber-50 p-2 text-sm">
|
||||
Offline-läge aktivt: inga anteckningar skickas till servern. Utkast bevaras lokalt —
|
||||
ingen tyst förlust.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loadError ? (
|
||||
<ErrorState onRetry={() => orderId && loadNotes(orderId)} />
|
||||
) : orders === null ? (
|
||||
<LoadingSkeleton />
|
||||
) : orders.length === 0 ? (
|
||||
<EmptyState title="Inga ordrar" line="Inga ordrar att annotera ännu." />
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
Order:{" "}
|
||||
<select
|
||||
aria-label="Välj order"
|
||||
value={orderId}
|
||||
onChange={(e) => {
|
||||
setOrderId(e.target.value);
|
||||
void loadNotes(e.target.value);
|
||||
}}
|
||||
className="rounded border px-2 py-1"
|
||||
>
|
||||
<option value="">— välj —</option>
|
||||
{orders.map((o) => (
|
||||
<option key={o.order_id} value={o.order_id}>
|
||||
{o.order_id} ({o.flow}, {o.status})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{orderId === "" ? (
|
||||
<EmptyState title="Välj order" line="Välj en order för att se och skriva anteckningar." />
|
||||
) : notes === null ? (
|
||||
<LoadingSkeleton />
|
||||
) : notes.length === 0 ? (
|
||||
<EmptyState title="Tomt" line="Inga anteckningar på den här ordern ännu." />
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{notes.map((n) => (
|
||||
<li key={n.note_id} className="rounded border p-3 text-sm">
|
||||
<div className="mb-1 flex justify-between text-xs opacity-70">
|
||||
<span>
|
||||
{n.author_id} · v{n.version} · klocka {n.clock}
|
||||
</span>
|
||||
<span>{new Date(n.updated_at).toLocaleString("sv-SE")}</span>
|
||||
</div>
|
||||
{editing?.note.note_id === n.note_id ? (
|
||||
<div className="space-y-2">
|
||||
<textarea
|
||||
aria-label="Redigera anteckning"
|
||||
value={editing.body}
|
||||
onChange={(e) => setEditing({ ...editing, body: e.target.value })}
|
||||
className="w-full rounded border p-2"
|
||||
rows={3}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button className="rounded bg-black px-3 py-1 text-white" onClick={() => void saveEdit()}>
|
||||
Spara (v{editing.note.version} → v{editing.note.version + 1})
|
||||
</button>
|
||||
<button className="rounded border px-3 py-1" onClick={() => setEditing(null)}>
|
||||
Avbryt
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="whitespace-pre-wrap">{n.body}</p>
|
||||
<button
|
||||
className="mt-2 text-xs underline"
|
||||
onClick={() => setEditing({ note: n, body: n.body })}
|
||||
>
|
||||
Redigera
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{orderId !== "" && (
|
||||
<div className="space-y-2">
|
||||
<textarea
|
||||
aria-label="Ny anteckning"
|
||||
placeholder="Skriv en anteckning på ordern…"
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
className="w-full rounded border p-2"
|
||||
rows={3}
|
||||
/>
|
||||
<button
|
||||
className="rounded bg-black px-4 py-2 text-sm text-white disabled:opacity-40"
|
||||
disabled={!draft.trim() || notes === null}
|
||||
onClick={() => void addNote()}
|
||||
>
|
||||
Lägg till anteckning
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</PortalShell>
|
||||
);
|
||||
}
|
||||
+14
-34
@@ -1,8 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { ActionGate, InboxList } from "@siax/ui";
|
||||
import { nextOrderStatus } from "@/lib/order-flow";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
@@ -28,6 +25,13 @@ interface Metrics {
|
||||
pipeline_ore: number;
|
||||
}
|
||||
|
||||
const NEXT_STATUS: Record<string, string> = {
|
||||
draft: "quoted",
|
||||
quoted: "in_production",
|
||||
in_production: "review",
|
||||
review: "accepted",
|
||||
accepted: "delivered",
|
||||
};
|
||||
|
||||
export default function AdminPage() {
|
||||
const t = useT();
|
||||
@@ -54,7 +58,7 @@ export default function AdminPage() {
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
|
||||
async function advance(id: string, status: string) {
|
||||
const next = nextOrderStatus(status);
|
||||
const next = NEXT_STATUS[status];
|
||||
if (!next) return;
|
||||
try {
|
||||
const r = await fetch(`/api/orders/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status: next }) });
|
||||
@@ -92,34 +96,8 @@ export default function AdminPage() {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{orders.some((o) => o.inbox_item) ? (
|
||||
<section className="mt-10">
|
||||
<h2 className="font-mono text-[11px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Inbox", sv: "Inkorg" })}</h2>
|
||||
<div className="mt-4">
|
||||
<InboxList
|
||||
items={orders.map((o) => o.inbox_item).filter(Boolean)}
|
||||
labels={{
|
||||
resolve: t({ en: "Advance", sv: "Flytta fram" }),
|
||||
emptyTitle: t({ en: "Inbox is empty", sv: "Inkorgen är tom" }),
|
||||
}}
|
||||
onResolve={(item) => {
|
||||
const order = orders.find((o) => `order:${o.order_id}` === item.id);
|
||||
if (order?.advance_action?.state === "available" && nextOrderStatus(order.status)) {
|
||||
advance(order.order_id, order.status);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
<section className="mt-10">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-mono text-[11px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Order queue", sv: "Orderkö" })}</h2>
|
||||
{/* DoD §65: real anchor, not a JS-handler button — the download is a plain GET of the CSV endpoint. */}
|
||||
<a href="/api/orders/export" download className="border border-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground transition-colors hover:bg-foreground hover:text-background">
|
||||
{t({ en: "Export CSV", sv: "Exportera CSV" })}
|
||||
</a>
|
||||
</div>
|
||||
<h2 className="font-mono text-[11px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Order queue", sv: "Orderkö" })}</h2>
|
||||
{orders.length === 0 ? (
|
||||
<div className="mt-6"><EmptyState title={t({ en: "Empty queue.", sv: "Tom kö." })} line={t({ en: "No orders yet.", sv: "Inga ordrar än." })} /></div>
|
||||
) : (
|
||||
@@ -134,14 +112,16 @@ export default function AdminPage() {
|
||||
<StatusPill status={o.status} />
|
||||
<span className="text-right font-mono text-[12px] tabular-nums">{formatSEK(o.total_ore / 100)}</span>
|
||||
<span className="text-right">
|
||||
<ActionGate action={o.advance_action} className="inline-block text-right">
|
||||
{NEXT_STATUS[o.status] ? (
|
||||
<button
|
||||
onClick={() => advance(o.order_id, o.status)}
|
||||
className="border border-foreground px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.08em] transition-colors hover:bg-foreground hover:text-background"
|
||||
>
|
||||
→ {nextOrderStatus(o.status) ?? t({ en: "done", sv: "klar" })}
|
||||
→ {NEXT_STATUS[o.status]}
|
||||
</button>
|
||||
</ActionGate>
|
||||
) : (
|
||||
<span className="font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">{t({ en: "done", sv: "klar" })}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -88,7 +88,7 @@ function ScreenTool() {
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="mt-3 text-[10.5px] text-muted-foreground">{t({ en: "Requires verified OpenSanctions terms/key for full matches.", sv: "Kräver verifierade OpenSanctions-villkor/nyckel för fullständiga träffar." })}</p>
|
||||
<p className="mt-3 text-[10.5px] text-muted-foreground/70">{t({ en: "Requires verified OpenSanctions terms/key for full matches.", sv: "Kräver verifierade OpenSanctions-villkor/nyckel för fullständiga träffar." })}</p>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/** GET /api/0pt/credits/balance — the authenticated tenant's credit balance. */
|
||||
export async function GET(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
|
||||
const url = repositoryDatabaseUrl();
|
||||
if (!url) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Credits are not available until the database is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const ledger = new PostgresCreditLedger(getRepositorySql(url));
|
||||
const balance = await ledger.balance(verified.scope.tenantId);
|
||||
return NextResponse.json({ tenant_id: verified.scope.tenantId, ...balance });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Credit balance unavailable';
|
||||
const notConfigured = /RLS-enforced|isolation migration/i.test(message);
|
||||
return NextResponse.json(
|
||||
{ error: notConfigured ? 'CREDITS_NOT_CONFIGURED' : 'CREDITS_UNAVAILABLE', message },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { getStripe } from '@/lib/stripe';
|
||||
import { PostgresCreditPurchaseStore } from '@/src/document-workbench/credit-purchase-store';
|
||||
import { findPack, readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
function appBaseUrl(request: NextRequest): string {
|
||||
const configured = process.env.NEXT_PUBLIC_APP_URL;
|
||||
if (configured && /^https:\/\//.test(configured)) return configured.replace(/\/+$/, '');
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/0pt/credits/checkout { pack_id }
|
||||
*
|
||||
* Creates a Stripe Checkout Session and stores the server-owned price snapshot
|
||||
* BEFORE any credit exists. Credits are granted only when the Stripe webhook
|
||||
* re-reads the session and its payment intent and the ledger accepts the
|
||||
* idempotent verified-payment command.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId } = verified.scope;
|
||||
|
||||
const book = readCreditPriceBook();
|
||||
if (!book) {
|
||||
return NextResponse.json(
|
||||
{ error: 'PRICE_BOOK_NOT_CONFIGURED', message: 'Credit purchases are not available yet' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return NextResponse.json(
|
||||
{ error: 'STRIPE_NOT_CONFIGURED', message: 'Payments are not available yet' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const databaseUrl = repositoryDatabaseUrl();
|
||||
if (!databaseUrl) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Credits are not available until the database is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'INVALID_BODY', message: 'JSON body required' }, { status: 400 });
|
||||
}
|
||||
const packId = (body as { pack_id?: unknown } | null)?.pack_id;
|
||||
if (typeof packId !== 'string' || !isValidScopeId(packId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_PACK', message: 'A valid pack_id is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const pack = findPack(book, packId);
|
||||
if (!pack) {
|
||||
return NextResponse.json({ error: 'UNKNOWN_PACK', message: 'Unknown credit pack' }, { status: 404 });
|
||||
}
|
||||
|
||||
const purchaseId = crypto.randomUUID();
|
||||
const base = appBaseUrl(request);
|
||||
const metadata = {
|
||||
kind: '0pt_credit_purchase',
|
||||
tenant_id: tenantId,
|
||||
purchase_id: purchaseId,
|
||||
price_book_version: book.version,
|
||||
};
|
||||
|
||||
let session;
|
||||
try {
|
||||
session = await stripe.checkout.sessions.create({
|
||||
mode: 'payment',
|
||||
client_reference_id: tenantId,
|
||||
line_items: [
|
||||
{
|
||||
quantity: 1,
|
||||
price_data: {
|
||||
currency: book.currency.toLowerCase(),
|
||||
unit_amount: pack.amountMinor,
|
||||
product_data: { name: `${pack.credits} 0pt credits` },
|
||||
},
|
||||
},
|
||||
],
|
||||
metadata,
|
||||
payment_intent_data: { metadata },
|
||||
success_url: `${base}/portal/krediter?status=success&purchase=${encodeURIComponent(purchaseId)}`,
|
||||
cancel_url: `${base}/portal/krediter?status=cancelled`,
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: 'CHECKOUT_UNAVAILABLE', message: 'The payment provider could not start a checkout' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await new PostgresCreditPurchaseStore(getRepositorySql(databaseUrl)).create({
|
||||
tenantId,
|
||||
purchaseId,
|
||||
checkoutSessionId: session.id,
|
||||
amountMinor: pack.amountMinor,
|
||||
currency: book.currency,
|
||||
credits: pack.credits,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
// Never leave a payable session with no server-side snapshot behind it.
|
||||
try {
|
||||
await stripe.checkout.sessions.expire(session.id);
|
||||
} catch {
|
||||
/* best effort; the webhook will refuse the unmatched session */
|
||||
}
|
||||
const message = error instanceof Error ? error.message : 'Credit purchase could not be stored';
|
||||
return NextResponse.json({ error: 'CREDITS_NOT_CONFIGURED', message }, { status: 503 });
|
||||
}
|
||||
|
||||
if (!session.url) {
|
||||
return NextResponse.json(
|
||||
{ error: 'CHECKOUT_UNAVAILABLE', message: 'The payment provider returned no checkout URL' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
purchase_id: purchaseId,
|
||||
checkout_url: session.url,
|
||||
credits: pack.credits,
|
||||
amount_minor: pack.amountMinor,
|
||||
currency: book.currency,
|
||||
},
|
||||
{ status: 201 },
|
||||
);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/**
|
||||
* GET /api/0pt/credits/packs — sellable credit packs from the server-owned
|
||||
* price book. No price is ever accepted from the client.
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
|
||||
const book = readCreditPriceBook();
|
||||
if (!book) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'PRICE_BOOK_NOT_CONFIGURED',
|
||||
message: 'Credit packs are not available until the server price book is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
version: book.version,
|
||||
currency: book.currency,
|
||||
packs: book.packs.map((pack) => ({
|
||||
id: pack.id,
|
||||
credits: pack.credits,
|
||||
amount_minor: pack.amountMinor,
|
||||
})),
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, documentExtractionSchema } from "@/src/validation/0pt-schemas";
|
||||
import { documentExtractionService } from "@/src/services/document-extraction-service";
|
||||
import { assertTenantMatchesVerified, resolveDocumentActor } from "@/src/http/tenant-guard";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
|
||||
try {
|
||||
@@ -14,16 +14,11 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const actor = resolveDocumentActor(request, body.actor_id);
|
||||
if (actor.response) return actor.response;
|
||||
if (!actor.actorId || !body.model_id) {
|
||||
return NextResponse.json({ error: "actor and model_id are required" }, { status: 400 });
|
||||
}
|
||||
const result = await documentExtractionService.extractDocument(documentId, {
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
actor_id: actor.actorId,
|
||||
correlation_id: body.correlation_id ?? crypto.randomUUID(),
|
||||
actor_id: body.actor_id,
|
||||
correlation_id: body.correlation_id,
|
||||
model_id: body.model_id,
|
||||
});
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, documentCaptureSchema } from "@/src/validation/0pt-schemas";
|
||||
import { documentCaptureService } from "@/src/services/document-capture-service";
|
||||
import { assertTenantMatchesVerified, resolveDocumentActor } from "@/src/http/tenant-guard";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -13,8 +13,6 @@ export async function POST(request: NextRequest) {
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const actor = resolveDocumentActor(request, body.actor_id);
|
||||
if (actor.response) return actor.response;
|
||||
const result = await documentCaptureService.captureFromMailbox(
|
||||
{
|
||||
mailbox: {
|
||||
@@ -31,9 +29,17 @@ export async function POST(request: NextRequest) {
|
||||
{
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
// In enforced mode middleware supplies the verified subject; the
|
||||
// body can only agree with it. Development retains the old fallback.
|
||||
actor_id: actor.actorId ?? "",
|
||||
// documentCaptureSchema types these optional (pre-existing, listed
|
||||
// among package.json's "9 pre-existing errors ... Wave 2 Zod
|
||||
// schemas type fields as plain string while the services want
|
||||
// narrower unions" -- deliberately left to its own change, not
|
||||
// widened here). CaptureMailboxContext requires actor_id as a
|
||||
// non-empty string and captureFromMailbox already throws a clear
|
||||
// "missing tenant_id/project_id/actor_id" error when it's falsy, so
|
||||
// `?? ""` changes no runtime behavior -- it only satisfies the type
|
||||
// checker, which previously never saw this file (nothing under
|
||||
// tests/ imported it before P014's cross-tenant regression tests).
|
||||
actor_id: body.actor_id ?? "",
|
||||
correlation_id: body.correlation_id ?? "",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
function csv(value: string | undefined): string[] {
|
||||
return (value ?? '')
|
||||
.split(',')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/0pt/documents/models — the server-approved model routes and limits
|
||||
* the customer may choose from. Never a free-form model list.
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
|
||||
const models = csv(process.env.OPT_ALLOWED_MODELS);
|
||||
const dataClasses = csv(process.env.OPT_ALLOWED_DATA_CLASSES);
|
||||
const destination = process.env.OPT_MODEL_DESTINATION;
|
||||
const maxInputTokens = Number(process.env.OPT_MODEL_MAX_INPUT_TOKENS ?? '0');
|
||||
const maxOutputTokens = Number(process.env.OPT_MODEL_MAX_OUTPUT_TOKENS ?? '0');
|
||||
if (
|
||||
models.length === 0 ||
|
||||
dataClasses.length === 0 ||
|
||||
(destination !== 'internal' && destination !== 'external') ||
|
||||
!Number.isSafeInteger(maxInputTokens) ||
|
||||
maxInputTokens <= 0 ||
|
||||
!Number.isSafeInteger(maxOutputTokens) ||
|
||||
maxOutputTokens <= 0
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'MODEL_POLICY_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until the model policy is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const book = readCreditPriceBook();
|
||||
return NextResponse.json({
|
||||
models,
|
||||
data_classes: dataClasses,
|
||||
destination,
|
||||
external_transfer_allowed: process.env.OPT_EXTERNAL_TRANSFER_ALLOWED === 'true',
|
||||
max_input_tokens: maxInputTokens,
|
||||
max_output_tokens: maxOutputTokens,
|
||||
price_book_version: book?.version ?? null,
|
||||
});
|
||||
}
|
||||
@@ -1,443 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { Doc0SourceClient, Doc0SourceUnavailableError } from '@/src/document-workbench/doc0-source-client';
|
||||
import { Inf0OutcomeUnknownError } from '@/src/document-workbench/inf0-gateway-client';
|
||||
import { createInf0Gateway } from '@/src/document-workbench/inf0-gateway';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { creditsForUsage, readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { structureDocument } from '@/src/document-workbench/structure-document';
|
||||
import { exportValidatedOutput } from '@/src/document-workbench/export-validated-output';
|
||||
import type {
|
||||
OutputFieldContract,
|
||||
OutputFieldType,
|
||||
} from '@/src/document-workbench/structured-output-validation';
|
||||
import { readDocumentWorkbenchRuntime } from '@/src/document-workbench/runtime-config';
|
||||
import { createProjectAuthorizer } from '@/src/document-workbench/project-access';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const FIELD_TYPES: readonly OutputFieldType[] = ['string', 'integer', 'boolean', 'decimal', 'date'];
|
||||
const DATA_CLASSES = ['none', 'low', 'medium', 'high', 'restricted'] as const;
|
||||
|
||||
function csv(value: string | undefined): string[] {
|
||||
return (value ?? '')
|
||||
.split(',')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function modelPolicy() {
|
||||
const allowedModelIds = csv(process.env.OPT_ALLOWED_MODELS);
|
||||
const allowedDataClasses = csv(process.env.OPT_ALLOWED_DATA_CLASSES);
|
||||
const destination = process.env.OPT_MODEL_DESTINATION;
|
||||
const maxInputTokens = Number(process.env.OPT_MODEL_MAX_INPUT_TOKENS ?? '0');
|
||||
const maxOutputTokens = Number(process.env.OPT_MODEL_MAX_OUTPUT_TOKENS ?? '0');
|
||||
if (
|
||||
allowedModelIds.length === 0 ||
|
||||
allowedDataClasses.length === 0 ||
|
||||
(destination !== 'internal' && destination !== 'external') ||
|
||||
!Number.isSafeInteger(maxInputTokens) ||
|
||||
maxInputTokens <= 0 ||
|
||||
!Number.isSafeInteger(maxOutputTokens) ||
|
||||
maxOutputTokens <= 0
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
allowedModelIds,
|
||||
allowedDataClasses,
|
||||
destination: destination as 'internal' | 'external',
|
||||
externalTransferAllowed: process.env.OPT_EXTERNAL_TRANSFER_ALLOWED === 'true',
|
||||
maxInputTokens,
|
||||
maxOutputTokens,
|
||||
};
|
||||
}
|
||||
|
||||
function parseFields(raw: unknown): OutputFieldContract[] | undefined {
|
||||
if (!Array.isArray(raw) || raw.length === 0 || raw.length > 100) return undefined;
|
||||
const fields: OutputFieldContract[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const item of raw) {
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
|
||||
const field = item as Record<string, unknown>;
|
||||
if (
|
||||
typeof field.name !== 'string' ||
|
||||
!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(field.name) ||
|
||||
seen.has(field.name) ||
|
||||
typeof field.type !== 'string' ||
|
||||
!FIELD_TYPES.includes(field.type as OutputFieldType)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
seen.add(field.name);
|
||||
fields.push({ name: field.name, type: field.type as OutputFieldType, required: true });
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
interface StructureBody {
|
||||
project_id?: unknown;
|
||||
document_id?: unknown;
|
||||
version_id?: unknown;
|
||||
checksum_sha256?: unknown;
|
||||
pipeline_stage?: unknown;
|
||||
instruction?: unknown;
|
||||
fields?: unknown;
|
||||
model_id?: unknown;
|
||||
data_class?: unknown;
|
||||
format?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/0pt/documents/structure
|
||||
*
|
||||
* Upload → DOC0 segments → INF0 model → mechanically validated, evidence-bound
|
||||
* output (optionally exported). Credits are reserved before the model runs and
|
||||
* settled to the measured usage afterwards.
|
||||
*
|
||||
* Nothing is trusted from the client except the requested target fields and
|
||||
* instruction. Source text is re-read from DOC0 and every returned value must
|
||||
* point at an exact span in that text.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId, actorId } = verified.scope;
|
||||
|
||||
const runtimeConfig = readDocumentWorkbenchRuntime();
|
||||
const gateway = createInf0Gateway();
|
||||
if (!runtimeConfig.doc0 || !gateway) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'WORKBENCH_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until DOC0 and INF0 are configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const policy = modelPolicy();
|
||||
if (!policy) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'MODEL_POLICY_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until the model policy is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
// Explicit pilot switch: `OPT_CREDITS_MODE=off` runs structuring without a
|
||||
// wallet. It is deliberately NOT a silent fallback — the response reports
|
||||
// `credits: null` and the operator has named the mode.
|
||||
const creditsEnabled =
|
||||
process.env.OPT_CREDITS_MODE !== 'off' &&
|
||||
Boolean(readCreditPriceBook()) &&
|
||||
Boolean(repositoryDatabaseUrl());
|
||||
const priceBook = creditsEnabled ? readCreditPriceBook() : undefined;
|
||||
const databaseUrl = creditsEnabled ? repositoryDatabaseUrl() : undefined;
|
||||
if (!creditsEnabled && process.env.OPT_CREDITS_MODE !== 'off') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until credits are configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
let body: StructureBody;
|
||||
try {
|
||||
body = (await request.json()) as StructureBody;
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'INVALID_BODY', message: 'JSON body required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const projectId = body.project_id;
|
||||
const documentId = body.document_id;
|
||||
const versionId = body.version_id;
|
||||
const checksum = body.checksum_sha256;
|
||||
const pipelineStage = body.pipeline_stage;
|
||||
const instruction = body.instruction;
|
||||
const modelId = body.model_id;
|
||||
const dataClass = body.data_class ?? 'low';
|
||||
const format = body.format ?? 'json';
|
||||
|
||||
if (
|
||||
!isValidScopeId(projectId) ||
|
||||
!isValidScopeId(documentId) ||
|
||||
!isValidScopeId(versionId) ||
|
||||
typeof checksum !== 'string' ||
|
||||
!/^[0-9a-f]{64}$/.test(checksum) ||
|
||||
pipelineStage !== 'parsed' ||
|
||||
typeof instruction !== 'string' ||
|
||||
!instruction.trim() ||
|
||||
instruction.length > 4000 ||
|
||||
typeof modelId !== 'string' ||
|
||||
!policy.allowedModelIds.includes(modelId) ||
|
||||
typeof dataClass !== 'string' ||
|
||||
!(DATA_CLASSES as readonly string[]).includes(dataClass) ||
|
||||
(format !== 'json' && format !== 'csv')
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_REQUEST', message: 'Invalid document structure request' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const fields = parseFields(body.fields);
|
||||
if (!fields) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_FIELDS', message: 'A valid field contract is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const authorize = createProjectAuthorizer();
|
||||
if (!(await authorize({ tenantId, projectId, actorId }))) {
|
||||
return NextResponse.json(
|
||||
{ error: 'OPT_ACCESS_DENIED', message: 'Project access is not authorized' },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const correlationId = request.headers.get('x-request-id') ?? crypto.randomUUID();
|
||||
const context = {
|
||||
tenantId,
|
||||
projectId,
|
||||
actorId,
|
||||
capability: '0pt.document.structure.v1',
|
||||
correlationId,
|
||||
idempotencyKey: correlationId,
|
||||
};
|
||||
|
||||
let sources;
|
||||
try {
|
||||
sources = await new Doc0SourceClient({
|
||||
baseUrl: runtimeConfig.doc0.baseUrl,
|
||||
serviceToken: runtimeConfig.doc0.serviceToken,
|
||||
}).read({
|
||||
tenantId,
|
||||
projectId,
|
||||
actorId: runtimeConfig.doc0.actorId ?? actorId,
|
||||
requestId: correlationId,
|
||||
receipt: {
|
||||
documentId,
|
||||
versionId,
|
||||
checksumSha256: checksum,
|
||||
pipelineStage: 'parsed',
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Doc0SourceUnavailableError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'DOC0_SOURCE_UNAVAILABLE',
|
||||
message:
|
||||
'The extracted source could not be verified (version, checksum, page cap or tenant). Review or reconciliation is required.',
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: 'DOC0_SOURCE_UNAVAILABLE', message: 'The extracted source is unavailable' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
console.log('[0pt-workbench] doc0 source read:', sources.sources.length, 'segments');
|
||||
const sourceChars = sources.sources.reduce((total, source) => total + source.text.length, 0);
|
||||
const estimatedInputTokens = Math.ceil(JSON.stringify(sources.sources).length / 4) + 1024;
|
||||
if (estimatedInputTokens > policy.maxInputTokens) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'SOURCE_TOO_LARGE',
|
||||
message: 'The document is larger than the configured model input limit',
|
||||
},
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
const maximumCredits =
|
||||
creditsEnabled && priceBook
|
||||
? creditsForUsage(priceBook, {
|
||||
pages: Math.max(1, Math.ceil(sourceChars / 1800)),
|
||||
inputTokens: estimatedInputTokens,
|
||||
outputTokens: policy.maxOutputTokens,
|
||||
})
|
||||
: 0;
|
||||
const reservationId = crypto.randomUUID();
|
||||
const ledger =
|
||||
creditsEnabled && databaseUrl ? new PostgresCreditLedger(getRepositorySql(databaseUrl)) : undefined;
|
||||
if (ledger) {
|
||||
try {
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `reserve:${reservationId}`,
|
||||
kind: 'reserve',
|
||||
reference: reservationId,
|
||||
amount: maximumCredits,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Credit reservation failed';
|
||||
if (/Insufficient available credits/i.test(message)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'INSUFFICIENT_CREDITS',
|
||||
message: 'Not enough credits for this job',
|
||||
required_credits: maximumCredits,
|
||||
},
|
||||
{ status: 402 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ error: 'CREDITS_UNAVAILABLE', message }, { status: 503 });
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await structureDocument({
|
||||
gateway,
|
||||
request: {
|
||||
context,
|
||||
admission: {
|
||||
tenantId,
|
||||
projectId,
|
||||
jobId: `doc:${documentId}:${correlationId}`,
|
||||
modelId,
|
||||
dataClass,
|
||||
maxInputTokens: policy.maxInputTokens,
|
||||
maxOutputTokens: policy.maxOutputTokens,
|
||||
maximumCredits,
|
||||
},
|
||||
policy: {
|
||||
tenantId,
|
||||
projectId,
|
||||
allowedModelIds: policy.allowedModelIds,
|
||||
allowedDataClasses: policy.allowedDataClasses,
|
||||
destination: policy.destination,
|
||||
externalTransferAllowed: policy.externalTransferAllowed,
|
||||
maxInputTokens: policy.maxInputTokens,
|
||||
maxOutputTokens: policy.maxOutputTokens,
|
||||
},
|
||||
reservation: ledger
|
||||
? {
|
||||
tenantId,
|
||||
projectId,
|
||||
jobId: `doc:${documentId}:${correlationId}`,
|
||||
status: 'reserved',
|
||||
credits: maximumCredits,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
countTokens: async (messages) => Math.ceil(JSON.stringify(messages).length / 4),
|
||||
instructions: instruction,
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
});
|
||||
|
||||
const charged =
|
||||
ledger && priceBook
|
||||
? Math.min(
|
||||
maximumCredits,
|
||||
creditsForUsage(priceBook, {
|
||||
pages: Math.max(1, Math.ceil(sourceChars / 1800)),
|
||||
inputTokens: result.model.promptTokens,
|
||||
outputTokens: result.model.completionTokens,
|
||||
}),
|
||||
)
|
||||
: 0;
|
||||
let balance;
|
||||
if (ledger) {
|
||||
try {
|
||||
balance = (
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `settle:${reservationId}`,
|
||||
kind: 'settle',
|
||||
reference: reservationId,
|
||||
amount: charged,
|
||||
})
|
||||
).balance;
|
||||
} catch {
|
||||
// The model result is real; keep the reservation for reconciliation
|
||||
// rather than reporting a balance we could not write.
|
||||
balance = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.status !== 'mechanically_validated') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'needs_review',
|
||||
issues: result.issues,
|
||||
model: result.model,
|
||||
credits: ledger ? { reserved: maximumCredits, charged, balance } : null,
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
|
||||
const exported =
|
||||
format === 'json'
|
||||
? exportValidatedOutput({
|
||||
format: 'json',
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
})
|
||||
: exportValidatedOutput({
|
||||
format: 'csv',
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'mechanically_validated',
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
model: result.model,
|
||||
credits: ledger ? { reserved: maximumCredits, charged, balance } : null,
|
||||
export:
|
||||
exported.status === 'ready'
|
||||
? { media_type: exported.mediaType, content: exported.content }
|
||||
: undefined,
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Inf0OutcomeUnknownError) {
|
||||
// Never release a reservation whose model call may have completed.
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'outcome_unknown',
|
||||
message:
|
||||
'The model call may have completed. The credit reservation is kept until its usage is reconciled.',
|
||||
reservation_id: reservationId,
|
||||
},
|
||||
{ status: 202 },
|
||||
);
|
||||
}
|
||||
if (ledger) {
|
||||
try {
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `release:${reservationId}`,
|
||||
kind: 'release',
|
||||
reference: reservationId,
|
||||
amount: 0,
|
||||
});
|
||||
} catch {
|
||||
/* the reservation stays for reconciliation */
|
||||
}
|
||||
}
|
||||
const message = error instanceof Error ? error.message : 'Structuring failed';
|
||||
console.error('[0pt-workbench] structure failed:', message);
|
||||
return NextResponse.json(
|
||||
{ error: 'STRUCTURE_FAILED', message, reservation_id: reservationId },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { Doc0UploadClient } from '@/src/document-workbench/doc0-upload-client';
|
||||
import {
|
||||
DocumentUploadCoordinator,
|
||||
type CoordinatedUpload,
|
||||
} from '@/src/document-workbench/upload-coordinator';
|
||||
import { PostgresUploadAttemptStore } from '@/src/document-workbench/upload-attempt-store';
|
||||
import {
|
||||
createProjectAuthorizer,
|
||||
projectAuthorizationConfigured,
|
||||
} from '@/src/document-workbench/project-access';
|
||||
import { readDocumentWorkbenchRuntime } from '@/src/document-workbench/runtime-config';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const CLASSIFICATIONS = [
|
||||
'public',
|
||||
'internal',
|
||||
'confidential',
|
||||
'restricted',
|
||||
'personal-data',
|
||||
'financial',
|
||||
'legal',
|
||||
] as const;
|
||||
|
||||
function isClassification(value: string): value is (typeof CLASSIFICATIONS)[number] {
|
||||
return (CLASSIFICATIONS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function idempotencyKey(request: NextRequest, form: FormData): string | undefined {
|
||||
const fromHeader = request.headers.get('idempotency-key');
|
||||
const fromBody = form.get('idempotency_key');
|
||||
const value = fromHeader ?? (typeof fromBody === 'string' ? fromBody : undefined);
|
||||
return value && /^[\x21-\x7e]{1,256}$/.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/0pt/documents/upload — customer document upload.
|
||||
*
|
||||
* multipart/form-data:
|
||||
* file (required) the original bytes; never trusted metadata
|
||||
* project_id (required) verified project the file belongs to
|
||||
* idempotency_key (required) or `Idempotency-Key` header
|
||||
* classification optional, defaults to `restricted` (conservative)
|
||||
*
|
||||
* The tenant and actor come ONLY from middleware's verified headers. The route
|
||||
* fails closed when project authorization or DOC0 is not configured.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId, actorId } = verified.scope;
|
||||
|
||||
const runtimeConfig = readDocumentWorkbenchRuntime();
|
||||
if (!runtimeConfig.doc0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'DOC0_NOT_CONFIGURED',
|
||||
message: 'Document upload is not available until DOC0 is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
if (!projectAuthorizationConfigured()) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'PROJECT_AUTHORIZATION_NOT_CONFIGURED',
|
||||
message: 'Document upload is not available until project authorization is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const databaseUrl = repositoryDatabaseUrl();
|
||||
if (!databaseUrl) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'UPLOAD_JOURNAL_NOT_CONFIGURED',
|
||||
message: 'Document upload is not available until its durable journal is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const declaredLength = Number(request.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declaredLength) && declaredLength > runtimeConfig.doc0.maxUploadBytes + 128 * 1024) {
|
||||
return NextResponse.json(
|
||||
{ error: 'PAYLOAD_TOO_LARGE', message: 'The uploaded file is too large' },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
let form: FormData;
|
||||
try {
|
||||
form = await request.formData();
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_UPLOAD', message: 'A multipart form with a file is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const file = form.get('file');
|
||||
const projectId = form.get('project_id');
|
||||
const key = idempotencyKey(request, form);
|
||||
const classificationRaw = form.get('classification');
|
||||
const classification =
|
||||
typeof classificationRaw === 'string' && classificationRaw.trim()
|
||||
? classificationRaw.trim()
|
||||
: 'restricted';
|
||||
|
||||
if (!(file instanceof File) || file.size <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_UPLOAD', message: 'A non-empty file is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (!isValidScopeId(projectId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_PROJECT', message: 'A valid project_id is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (!key) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'IDEMPOTENCY_KEY_REQUIRED',
|
||||
message: 'An idempotency key is required for document uploads',
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (!isClassification(classification)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_CLASSIFICATION', message: 'Unknown classification' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (file.size > runtimeConfig.doc0.maxUploadBytes) {
|
||||
return NextResponse.json(
|
||||
{ error: 'PAYLOAD_TOO_LARGE', message: 'The uploaded file is too large' },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
let bytes: Uint8Array;
|
||||
try {
|
||||
bytes = new Uint8Array(await file.arrayBuffer());
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_UPLOAD', message: 'The uploaded file could not be read' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (bytes.byteLength === 0 || bytes.byteLength !== file.size) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_UPLOAD', message: 'The uploaded file is incomplete' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const authorize = createProjectAuthorizer();
|
||||
const sql = getRepositorySql(databaseUrl);
|
||||
// DOC0 authorizes the SERVICE identity and requires x-actor-id to be an
|
||||
// actor that identity holds a grant for. The end-user actor is still the
|
||||
// journal/authorization scope on our side; only the DOC0 call acts as the
|
||||
// service.
|
||||
const doc0ActorId = runtimeConfig.doc0.actorId ?? actorId;
|
||||
const doc0Client = new Doc0UploadClient({
|
||||
baseUrl: runtimeConfig.doc0.baseUrl,
|
||||
serviceToken: runtimeConfig.doc0.serviceToken,
|
||||
maxBytes: runtimeConfig.doc0.maxUploadBytes,
|
||||
});
|
||||
const coordinator = new DocumentUploadCoordinator({
|
||||
attempts: new PostgresUploadAttemptStore(sql),
|
||||
doc0: {
|
||||
upload: (input) => doc0Client.upload({ ...input, actorId: doc0ActorId }),
|
||||
inspect: (input) => doc0Client.inspect({ ...input, actorId: doc0ActorId }),
|
||||
},
|
||||
authorize: async (scope) => authorize(scope),
|
||||
maxBytes: runtimeConfig.doc0.maxUploadBytes,
|
||||
});
|
||||
|
||||
let outcome: CoordinatedUpload;
|
||||
try {
|
||||
outcome = await coordinator.execute({
|
||||
tenantId,
|
||||
projectId,
|
||||
actorId,
|
||||
requestId: request.headers.get('x-request-id') ?? crypto.randomUUID(),
|
||||
idempotencyKey: key,
|
||||
filename: file.name || 'source',
|
||||
mimeType: file.type || 'application/octet-stream',
|
||||
classification,
|
||||
bytes,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Upload failed';
|
||||
if (/not authorized/i.test(message)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'OPT_ACCESS_DENIED', message: 'Project access is not authorized' },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
if (/cannot be reused/i.test(message)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'IDEMPOTENCY_CONFLICT',
|
||||
message: 'The idempotency key was already used for different content',
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ error: 'UPLOAD_FAILED', message }, { status: 400 });
|
||||
}
|
||||
|
||||
if (outcome.status === 'receipt_verified') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'receipt_verified',
|
||||
document_id: outcome.receipt.documentId,
|
||||
version_id: outcome.receipt.versionId,
|
||||
checksum_sha256: outcome.receipt.checksumSha256,
|
||||
pipeline_stage: outcome.receipt.pipelineStage,
|
||||
},
|
||||
{ status: 201 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'outcome_unknown',
|
||||
message:
|
||||
'The upload may have been accepted. Its journal record is reported below; it does not prove storage or extraction.',
|
||||
observation: outcome.observation ?? { status: 'reconciliation_required' },
|
||||
},
|
||||
{ status: 202 },
|
||||
);
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { requireRouteAuth } from "@/src/auth/require-route-auth";
|
||||
import { createAud0Client } from "@/src/clients/aud0-client";
|
||||
import {
|
||||
addNote,
|
||||
findNote,
|
||||
listNotes,
|
||||
NoteNotFoundError,
|
||||
NoteVersionConflictError,
|
||||
updateNote,
|
||||
} from "@/lib/order-notes-store";
|
||||
import { getOrder } from "@/lib/orders-store";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
|
||||
// GET/POST/PATCH /api/admin/order-notes — persisted collaboration state på
|
||||
// admin-orders (kernel: @siax/collaboration). Ligger utanför middleware.ts:s
|
||||
// matcher (/api/0pt/*), så auth läggs på direkt via requireRouteAuth, precis
|
||||
// som /api/admin/metrics — fail-closed Zitadel-verifiering, 401 utan token.
|
||||
//
|
||||
// Tenant-guard: tenant_id hämtas SERVER-SIDE från ordern (aldrig från
|
||||
// klienten) och jämförs mot den verifierade kontextens tenant — mismatch är
|
||||
// 403. Conflict semantics: PATCH med stale `version` -> 409 + aktuell version
|
||||
// (optimistisk samtidighet; last-write-wins först EFTER en medveten reload).
|
||||
|
||||
const AUDIT_CAPABILITY = "admin.order_notes";
|
||||
|
||||
async function audit(
|
||||
tenantId: string | null,
|
||||
actorId: string,
|
||||
resourceId: string,
|
||||
eventType: string,
|
||||
payload: unknown,
|
||||
): Promise<void> {
|
||||
// Best effort: AUD0 är evidence, inte en skriv-buffert — ett audit-fel får
|
||||
// aldrig rulla tillbaka en lyckad note-skrivning.
|
||||
try {
|
||||
await createAud0Client().ingestEvent({
|
||||
event_id: `aud_${crypto.randomUUID()}`,
|
||||
event_type: eventType,
|
||||
tenant_id: tenantId ?? "anonymous",
|
||||
project_id: "0pt",
|
||||
actor_id: actorId,
|
||||
app_id: "0pt",
|
||||
capability_id: AUDIT_CAPABILITY,
|
||||
resource_type: "order_note",
|
||||
resource_id: resourceId,
|
||||
risk_level: "L1",
|
||||
payload,
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
} catch {
|
||||
// swallow — see comment above
|
||||
}
|
||||
}
|
||||
|
||||
function tenantGuard(ctxTenant: string, orderTenant: string | null | undefined): NextResponse | null {
|
||||
if (!orderTenant) return null; // legacy anonymous draft — admin-ytan får annotera
|
||||
if (ctxTenant !== orderTenant) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "OPT_ACCESS_DENIED",
|
||||
message: "order belongs to a different tenant than the authenticated token",
|
||||
details: { order_tenant: orderTenant },
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
const orderId = req.nextUrl.searchParams.get("order_id");
|
||||
if (!orderId) {
|
||||
return NextResponse.json({ error: "order_id query parameter is required" }, { status: 400 });
|
||||
}
|
||||
const order = await getOrder(orderId);
|
||||
if (!order) {
|
||||
return NextResponse.json({ error: "order_not_found", order_id: orderId }, { status: 404 });
|
||||
}
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order.tenant_id);
|
||||
if (denied) return denied;
|
||||
const notes = await listNotes(orderId);
|
||||
return NextResponse.json({ order_id: orderId, notes });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
let body: { order_id?: string; body?: string };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
if (!body.order_id || !body.body || !String(body.body).trim()) {
|
||||
return NextResponse.json(
|
||||
{ error: "order_id and non-empty body are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const order = await getOrder(body.order_id);
|
||||
if (!order) {
|
||||
return NextResponse.json({ error: "order_not_found", order_id: body.order_id }, { status: 404 });
|
||||
}
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order.tenant_id);
|
||||
if (denied) return denied;
|
||||
try {
|
||||
const note = await addNote({
|
||||
order_id: body.order_id,
|
||||
tenant_id: order.tenant_id ?? null,
|
||||
author_id: auth.ctx.actorId,
|
||||
body: String(body.body),
|
||||
});
|
||||
await audit(note.tenant_id, auth.ctx.actorId, note.note_id, "order_note.created", {
|
||||
order_id: note.order_id,
|
||||
clock: note.clock,
|
||||
});
|
||||
return NextResponse.json(note, { status: 201 });
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
let body: { note_id?: string; body?: string; version?: number };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
if (!body.note_id || !body.body || !Number.isInteger(body.version)) {
|
||||
return NextResponse.json(
|
||||
{ error: "note_id, body and integer version are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
// Server-authoritative tenant check: slå upp noten (och dess order) INNAN
|
||||
// någon skrivning — klienten får aldrig säga vilken tenant en note tillhör.
|
||||
const existing = await findNote(body.note_id);
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "note_not_found" }, { status: 404 });
|
||||
}
|
||||
const order = await getOrder(existing.order_id);
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order?.tenant_id ?? existing.tenant_id);
|
||||
if (denied) return denied;
|
||||
try {
|
||||
const note = await updateNote({
|
||||
note_id: body.note_id,
|
||||
author_id: auth.ctx.actorId,
|
||||
body: String(body.body),
|
||||
expected_version: body.version as number,
|
||||
});
|
||||
await audit(note.tenant_id, auth.ctx.actorId, note.note_id, "order_note.updated", {
|
||||
order_id: note.order_id,
|
||||
version: note.version,
|
||||
clock: note.clock,
|
||||
});
|
||||
return NextResponse.json(note);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NoteVersionConflictError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "version_conflict",
|
||||
message: err.message,
|
||||
expected_version: err.expectedVersion,
|
||||
current_version: err.currentVersion,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
if (err instanceof NoteNotFoundError) {
|
||||
return NextResponse.json({ error: "note_not_found" }, { status: 404 });
|
||||
}
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { signSession, SESSION_COOKIE } from '@/lib/auth';
|
||||
import {
|
||||
OIDC_SESSION_TTL_SECONDS,
|
||||
OIDC_STATE_COOKIE,
|
||||
appBaseUrl,
|
||||
exchangeCode,
|
||||
readOidcConfig,
|
||||
verifyIdToken,
|
||||
} from '@/lib/oidc';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
function safeNext(value: unknown): string {
|
||||
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) {
|
||||
return '/portal/dokument';
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** GET /api/auth/callback — finish OIDC, verify the id_token, set the session. */
|
||||
export async function GET(request: NextRequest) {
|
||||
const config = readOidcConfig();
|
||||
const fail = (reason: string) =>
|
||||
NextResponse.redirect(`${appBaseUrl()}/portal/dokument?auth_error=${encodeURIComponent(reason)}`);
|
||||
if (!config) return fail('auth_not_configured');
|
||||
|
||||
const state = request.nextUrl.searchParams.get('state');
|
||||
const code = request.nextUrl.searchParams.get('code');
|
||||
const error = request.nextUrl.searchParams.get('error');
|
||||
if (error) return fail('provider_error');
|
||||
if (!state || !code) return fail('missing_code');
|
||||
|
||||
const raw = request.cookies.get(OIDC_STATE_COOKIE)?.value;
|
||||
if (!raw) return fail('missing_state');
|
||||
let stored: { state?: unknown; nonce?: unknown; verifier?: unknown; next?: unknown; ts?: unknown };
|
||||
try {
|
||||
stored = JSON.parse(raw);
|
||||
} catch {
|
||||
return fail('bad_state');
|
||||
}
|
||||
if (
|
||||
stored.state !== state ||
|
||||
typeof stored.nonce !== 'string' ||
|
||||
typeof stored.verifier !== 'string' ||
|
||||
typeof stored.ts !== 'number' ||
|
||||
Date.now() - stored.ts > 10 * 60 * 1000
|
||||
) {
|
||||
return fail('bad_state');
|
||||
}
|
||||
|
||||
try {
|
||||
const { idToken, accessToken } = await exchangeCode(config, code, stored.verifier);
|
||||
const verified = await verifyIdToken(config, idToken, stored.nonce, accessToken);
|
||||
const session = await signSession({
|
||||
sub: verified.sub,
|
||||
tenantId: verified.tenantId,
|
||||
email: verified.email ?? '',
|
||||
exp: Date.now() + OIDC_SESSION_TTL_SECONDS * 1000,
|
||||
});
|
||||
const response = NextResponse.redirect(`${appBaseUrl()}${safeNext(stored.next)}`);
|
||||
response.cookies.set(SESSION_COOKIE, session, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: appBaseUrl().startsWith('https://'),
|
||||
path: '/',
|
||||
maxAge: OIDC_SESSION_TTL_SECONDS,
|
||||
});
|
||||
response.cookies.set(OIDC_STATE_COOKIE, '', { path: '/', maxAge: 0 });
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
// Codes only (e.g. token_exchange_failed), never tokens or claims.
|
||||
console.error(
|
||||
'[0pt-auth] oidc callback failed:',
|
||||
error instanceof Error ? error.message : 'unknown_error',
|
||||
);
|
||||
return fail('verification_failed');
|
||||
}
|
||||
}
|
||||
+13
-79
@@ -1,95 +1,29 @@
|
||||
import { timingSafeEqual } from 'node:crypto';
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { signSession, SESSION_COOKIE } from '@/lib/auth';
|
||||
import {
|
||||
OIDC_STATE_COOKIE,
|
||||
appBaseUrl,
|
||||
authorizeUrl,
|
||||
createOidcState,
|
||||
createPkce,
|
||||
readOidcConfig,
|
||||
} from '@/lib/oidc';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
function safeNext(value: string | null): string {
|
||||
if (!value) return '/portal/dokument';
|
||||
if (!value.startsWith('/') || value.startsWith('//')) return '/portal/dokument';
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/auth/login — start the Zitadel OIDC Authorization Code + PKCE flow.
|
||||
* Redirects back to /api/auth/callback, which sets the verified session cookie.
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const config = readOidcConfig();
|
||||
if (!config) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'auth_not_configured',
|
||||
message: 'Zitadel OIDC is not configured (ZITADEL_OIDC_CLIENT_ID/SECRET)',
|
||||
},
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const next = safeNext(request.nextUrl.searchParams.get('next'));
|
||||
const { state, nonce } = createOidcState();
|
||||
const { verifier, challenge } = createPkce();
|
||||
const response = NextResponse.redirect(authorizeUrl(config, state, nonce, challenge));
|
||||
response.cookies.set(OIDC_STATE_COOKIE, JSON.stringify({ state, nonce, verifier, next, ts: Date.now() }), {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: appBaseUrl().startsWith('https://'),
|
||||
path: '/',
|
||||
maxAge: 600,
|
||||
});
|
||||
return response;
|
||||
}
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { signSession, SESSION_COOKIE } from "@/lib/auth";
|
||||
|
||||
// POST /api/auth/login — guarded dev login (scaffold). Requires AUTH_SECRET +
|
||||
// a matching DEV_LOGIN_KEY. Never available in production; real login is GET.
|
||||
// a matching DEV_LOGIN_KEY. Production replaces this with Auth.js + OAuth.
|
||||
export async function POST(req: NextRequest) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'forbidden', message: 'Dev-login is disabled in production' } },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
const { email, key } = await req.json().catch(() => ({ email: undefined, key: undefined }));
|
||||
if (!process.env.AUTH_SECRET) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'auth_not_configured', message: 'AUTH_SECRET saknas' } },
|
||||
{ status: 501 },
|
||||
);
|
||||
return NextResponse.json({ error: { code: "auth_not_configured", message: "AUTH_SECRET saknas" } }, { status: 501 });
|
||||
}
|
||||
const devKey = process.env.DEV_LOGIN_KEY;
|
||||
// Constant-time compare: a plain !== leaks the number of matching leading
|
||||
// bytes via response timing, letting an attacker recover DEV_LOGIN_KEY
|
||||
// byte-by-byte instead of an all-or-nothing guess.
|
||||
const keyBuf = Buffer.from(typeof key === 'string' ? key : '');
|
||||
const devKeyBuf = Buffer.from(devKey ?? '');
|
||||
const keysMatch =
|
||||
Boolean(devKey) && keyBuf.length === devKeyBuf.length && timingSafeEqual(keyBuf, devKeyBuf);
|
||||
// byte-by-byte instead of it being an all-or-nothing guess.
|
||||
const keyBuf = Buffer.from(typeof key === "string" ? key : "");
|
||||
const devKeyBuf = Buffer.from(devKey ?? "");
|
||||
const keysMatch = Boolean(devKey) && keyBuf.length === devKeyBuf.length && timingSafeEqual(keyBuf, devKeyBuf);
|
||||
if (!keysMatch) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'forbidden', message: 'Dev-login kräver giltig nyckel' } },
|
||||
{ status: 403 },
|
||||
);
|
||||
return NextResponse.json({ error: { code: "forbidden", message: "Dev-login kräver giltig nyckel" } }, { status: 403 });
|
||||
}
|
||||
if (!email) {
|
||||
return NextResponse.json({ error: { code: 'bad_request', message: 'email krävs' } }, { status: 400 });
|
||||
return NextResponse.json({ error: { code: "bad_request", message: "email krävs" } }, { status: 400 });
|
||||
}
|
||||
const token = await signSession({ email, exp: Date.now() + 7 * 24 * 60 * 60 * 1000 });
|
||||
const token = await signSession({ email, iat: Date.now() });
|
||||
const res = NextResponse.json({ ok: true, email });
|
||||
res.cookies.set(SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: true,
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
});
|
||||
res.cookies.set(SESSION_COOKIE, token, { httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge: 60 * 60 * 24 * 7 });
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { verifySession, SESSION_COOKIE } from '@/lib/auth';
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { verifySession, SESSION_COOKIE } from "@/lib/auth";
|
||||
|
||||
// GET /api/auth/me — current session (or null).
|
||||
export async function GET(req: NextRequest) {
|
||||
const token = req.cookies.get(SESSION_COOKIE)?.value;
|
||||
const session = await verifySession(token);
|
||||
return NextResponse.json({
|
||||
user: session
|
||||
? {
|
||||
email: session.email ?? null,
|
||||
sub: typeof session.sub === 'string' ? session.sub : null,
|
||||
tenantId: typeof session.tenantId === 'string' ? session.tenantId : null,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
return NextResponse.json({ user: session ? { email: session.email } : null });
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { listOwnedOrders } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
|
||||
/**
|
||||
* GET /api/orders/export (våg 3.4, DoD §56) — CSV-export of the authenticated
|
||||
* owner's orders. Same fail-closed auth as GET/POST /api/orders (this path is
|
||||
* outside middleware.ts's /api/0pt matcher, so the Zitadel verifier runs here).
|
||||
*
|
||||
* RFC 4180: CRLF line endings, fields containing comma, quote or newline are
|
||||
* quoted with doubled quotes, header row always present.
|
||||
*
|
||||
* Locale note: deposit_ore / total_ore are exported as RAW ÖRE — öre is the
|
||||
* canonical unit in the order contract; formatting (SEK, thousand separators)
|
||||
* happens in the UI layer, never in the export.
|
||||
*
|
||||
* Cap note (DoD §56): NO row truncation/limiting — an export must be complete.
|
||||
*/
|
||||
|
||||
function csvEscape(value: string): string {
|
||||
if (/[",\r\n]/.test(value)) return `"${value.replace(/"/g, '""')}"`;
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
try {
|
||||
const orders = await listOwnedOrders(auth.owner.tenantId);
|
||||
const header = ["order_id", "flow", "status", "deposit_ore", "total_ore"];
|
||||
const rows = orders.map((o) =>
|
||||
[o.order_id, o.flow, o.status, String(o.deposit_ore), String(o.total_ore)].map(csvEscape).join(","),
|
||||
);
|
||||
const csv = [header.join(","), ...rows].join("\r\n") + "\r\n";
|
||||
const date = new Date().toISOString().slice(0, 10);
|
||||
return new NextResponse(csv, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="orders-${date}.csv"`,
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createOrder, type OrderConfig, type OrderOwner } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
import { createAud0Client } from "@/src/clients/aud0-client";
|
||||
import { validateRows, defineMapping, type RowError } from "@siax/contracts/import-export";
|
||||
import { serviceById, type Flow } from "@/lib/services";
|
||||
import { IMPORT_DISPATCH_POLICY, evaluateImportDispatch } from "@/lib/import-dispatch-policy";
|
||||
import { ENTITY_TYPES, FREQUENCIES, type EntityType, type Frequency } from "@/lib/data";
|
||||
|
||||
// C8: CSV-import of orders — the symmetric counterpart of GET /api/orders/export
|
||||
// (våg 3.4). The server is the ONLY authority: the raw CSV is parsed here
|
||||
// (RFC 4180, no eval), re-validated here via the frozen @siax/contracts kernel
|
||||
// (validateRows) plus host field rules, and executed through the EXISTING order
|
||||
// creation logic (createOrder) so imported rows are real tenant-owned orders.
|
||||
// Client-side wizard parsing is presentation entropy, never trusted.
|
||||
//
|
||||
// Fail-closed properties:
|
||||
// - No principal (requireOrderOwner) → 401, no parse, no writes.
|
||||
// - Unknown header column → 400 (never silently dropped).
|
||||
// - More than MAX_IMPORT_ROWS data rows → 413 (cap, never truncate silently).
|
||||
// - execute() re-validates and imports only rows that pass; failing rows are
|
||||
// reported per row (row/field/code) and never created. Each order insert is
|
||||
// individually atomic via createOrder (per-row transactional semantics);
|
||||
// a failing row can never corrupt a passing one.
|
||||
// - Audit: every successful execute emits an AUD0 event via 0pt's sole producer
|
||||
// boundary (durable outbox when DATABASE_URL is configured). Emission failure
|
||||
// is logged, never blocks the import (the outbox pattern owns delivery).
|
||||
|
||||
// DES1GN ADR D3 (§31): taken härstammar från ImportDispatchPolicy — ett objekt,
|
||||
// en sanning. Inline-taket är oförändrat (500); rader > policy.maxRows (5000)
|
||||
// är N0D-dispatch-signalen (descriptor-gate: svarar 413 + hint tills N0D-workern
|
||||
// är verifierad — aldrig tyst trunkering, aldrig tyst dispatch).
|
||||
export const MAX_IMPORT_ROWS = IMPORT_DISPATCH_POLICY.maxInlineRows;
|
||||
const MAX_CSV_CHARS = IMPORT_DISPATCH_POLICY.maxBytes;
|
||||
const IMPORT_COLUMNS = ["flow", "service_type", "type", "volume", "frequency", "markets"] as const;
|
||||
const FLOWS: readonly Flow[] = ["catalog", "custom", "subscription"];
|
||||
const MAX_VOLUME = 1_000_000;
|
||||
|
||||
interface ImportRowError extends RowError {
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface ParsedCsv {
|
||||
rows: Record<string, string>[];
|
||||
headerError?: string;
|
||||
}
|
||||
|
||||
/** Minimal RFC 4180 parser: quoted fields, doubled quotes, CRLF or LF. No eval. */
|
||||
export function parseCsv(text: string): ParsedCsv {
|
||||
const rows: string[][] = [];
|
||||
let field = "";
|
||||
let row: string[] = [];
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
}
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
} else if (ch === '"') {
|
||||
inQuotes = true;
|
||||
} else if (ch === ",") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
} else if (ch === "\n") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
rows.push(row);
|
||||
row = [];
|
||||
} else if (ch === "\r") {
|
||||
// consumed by the following \n (or ignored for bare CR)
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
}
|
||||
if (field.length > 0 || row.length > 0) {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
}
|
||||
const nonEmpty = rows.filter((r) => r.length > 1 || (r[0] ?? "").trim() !== "");
|
||||
if (nonEmpty.length === 0) return { rows: [] };
|
||||
const header = nonEmpty[0].map((h) => h.trim().toLowerCase());
|
||||
const unknown = header.filter((h) => h !== "" && !(IMPORT_COLUMNS as readonly string[]).includes(h));
|
||||
if (unknown.length > 0) {
|
||||
return { rows: [], headerError: `Okänd kolumn: ${unknown.join(", ")} (tillåtna: ${IMPORT_COLUMNS.join(", ")})` };
|
||||
}
|
||||
return {
|
||||
rows: nonEmpty.slice(1).map((cells) => {
|
||||
const obj: Record<string, string> = {};
|
||||
header.forEach((h, idx) => {
|
||||
if (h) obj[h] = (cells[idx] ?? "").trim();
|
||||
});
|
||||
return obj;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Host field rules on top of the kernel's required/type checks. */
|
||||
function hostValidate(rows: Record<string, string>[]): ImportRowError[] {
|
||||
const errors: ImportRowError[] = [];
|
||||
rows.forEach((r, idx) => {
|
||||
const rowNo = idx + 1;
|
||||
const flow = (r.flow ?? "").trim() as Flow;
|
||||
if (flow && !FLOWS.includes(flow)) {
|
||||
errors.push({ row: rowNo, field: "flow", code: "bad_type", message: `Ogiltigt flow "${r.flow}" (tillåtna: ${FLOWS.join(", ")})` });
|
||||
}
|
||||
const st = (r.service_type ?? "").trim();
|
||||
if (st && !serviceById(st)) {
|
||||
errors.push({ row: rowNo, field: "service_type", code: "bad_type", message: `Okänd service_type "${st}"` });
|
||||
}
|
||||
const type = (r.type ?? "").trim();
|
||||
if (type && !ENTITY_TYPES.some((t) => t.id === type)) {
|
||||
errors.push({ row: rowNo, field: "type", code: "bad_type", message: `Ogiltig typ "${type}" (tillåtna: ${ENTITY_TYPES.map((t) => t.id).join(", ")})` });
|
||||
}
|
||||
const volume = (r.volume ?? "").trim();
|
||||
if (volume === "") {
|
||||
// optional — order logic applies flow defaults
|
||||
} else if (!/^\d+$/.test(volume) || Number(volume) < 1 || Number(volume) > MAX_VOLUME) {
|
||||
errors.push({ row: rowNo, field: "volume", code: "bad_type", message: `volume måste vara ett positivt heltal ≤ ${MAX_VOLUME}` });
|
||||
}
|
||||
const freq = (r.frequency ?? "").trim();
|
||||
if (freq && !FREQUENCIES.includes(freq as Frequency)) {
|
||||
errors.push({ row: rowNo, field: "frequency", code: "bad_type", message: `Ogiltig frequency "${freq}" (tillåtna: ${FREQUENCIES.join(", ")})` });
|
||||
}
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
function buildConfig(r: Record<string, string>): OrderConfig {
|
||||
const config: OrderConfig = {};
|
||||
if ((r.service_type ?? "").trim()) config.service_type = r.service_type.trim();
|
||||
if ((r.type ?? "").trim()) config.type = r.type.trim() as EntityType;
|
||||
if ((r.volume ?? "").trim()) config.volume = Number(r.volume.trim());
|
||||
if ((r.frequency ?? "").trim()) config.frequency = r.frequency.trim() as Frequency;
|
||||
if ((r.markets ?? "").trim()) {
|
||||
config.markets = r.markets.split(";").map((m) => m.trim()).filter(Boolean);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
export interface ImportReport {
|
||||
totalRows: number;
|
||||
validRows: number;
|
||||
errorCount: number;
|
||||
errors: ImportRowError[];
|
||||
}
|
||||
|
||||
/** Server-authoritative validation: kernel required/type checks + host rules. */
|
||||
export function validateImport(csv: string): { report: ImportReport; rows: Record<string, string>[]; headerError?: string } {
|
||||
const { rows, headerError } = parseCsv(csv);
|
||||
if (headerError) return { report: { totalRows: 0, validRows: 0, errorCount: 1, errors: [{ row: 0, field: "header", code: "format", message: headerError }] }, rows: [], headerError };
|
||||
const mapping = defineMapping({ columns: IMPORT_COLUMNS.map((c) => ({ source: c, target: c, required: c === "flow" })) });
|
||||
const kernel = validateRows(rows, mapping);
|
||||
const host = hostValidate(rows);
|
||||
const kernelErrors: ImportRowError[] = kernel.errors.map((e) => ({ ...e, message: e.message ?? `Valideringsfel (${e.code})` }));
|
||||
const errors = [...kernelErrors, ...host];
|
||||
return {
|
||||
report: {
|
||||
totalRows: rows.length,
|
||||
validRows: rows.length - new Set(errors.map((e) => e.row)).size,
|
||||
errorCount: errors.length,
|
||||
errors,
|
||||
},
|
||||
rows,
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
const owner: OrderOwner = auth.owner;
|
||||
|
||||
let body: { mode?: string; csv?: string };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON" } }, { status: 400 });
|
||||
}
|
||||
const mode = body.mode;
|
||||
const csv = body.csv;
|
||||
if (!mode || !["validate", "dry_run", "execute"].includes(mode)) {
|
||||
return NextResponse.json({ error: { code: "bad_mode", message: "mode måste vara validate | dry_run | execute" } }, { status: 400 });
|
||||
}
|
||||
if (typeof csv !== "string" || csv.trim() === "") {
|
||||
return NextResponse.json({ error: { code: "bad_csv", message: "csv saknas eller är tom" } }, { status: 400 });
|
||||
}
|
||||
const csvBytes = Buffer.byteLength(csv, "utf8");
|
||||
if (evaluateImportDispatch({ format: "csv", bytes: csvBytes, rows: 0 }).verdict === "byte_cap_exceeded") {
|
||||
return NextResponse.json({ error: { code: "csv_too_large", message: `CSV större än ${MAX_CSV_CHARS} bytes` } }, { status: 413 });
|
||||
}
|
||||
try {
|
||||
const { report, rows, headerError } = validateImport(csv);
|
||||
if (headerError) {
|
||||
return NextResponse.json({ error: { code: "bad_header", message: headerError }, report }, { status: 400 });
|
||||
}
|
||||
const dispatchVerdict = evaluateImportDispatch({ format: "csv", bytes: csvBytes, rows: rows.length });
|
||||
if (dispatchVerdict.verdict === "dispatch_n0d") {
|
||||
// DES1GN D3-signalen: den här volymen ÄR ett N0D-jobb (0pt.import_execute_job).
|
||||
// Descriptor-gaten är stängd (N0D-worker UNVERIFIED) -> fail-closed 413 med hint.
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: "n0d_dispatch_required",
|
||||
message: `Import med ${rows.length} rader ska köras som N0D-jobb (0pt.import_execute_job); dispatch är ännu inte aktiverad`,
|
||||
hint: { capability_id: "0pt.import_execute", job_type: "0pt.import_execute_job", status: "UNVERIFIED" },
|
||||
},
|
||||
},
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
if (dispatchVerdict.verdict === "row_cap_exceeded") {
|
||||
return NextResponse.json({ error: { code: "row_cap_exceeded", message: `Max ${MAX_IMPORT_ROWS} rader per import` } }, { status: 413 });
|
||||
}
|
||||
|
||||
if (mode === "validate" || mode === "dry_run") {
|
||||
// No writes — dry_run is exactly validate plus an explicit rehearsal count.
|
||||
return NextResponse.json({ mode, ...report, would_import: report.validRows });
|
||||
}
|
||||
|
||||
// mode === "execute": server re-validates and imports ONLY passing rows.
|
||||
const failedRows = new Set(report.errors.map((e) => e.row));
|
||||
const orderIds: string[] = [];
|
||||
let imported = 0;
|
||||
for (let idx = 0; idx < rows.length; idx++) {
|
||||
if (failedRows.has(idx + 1)) continue;
|
||||
const r = rows[idx];
|
||||
try {
|
||||
const { order } = await createOrder((r.flow ?? "").trim(), buildConfig(r), undefined, owner);
|
||||
orderIds.push(order.order_id);
|
||||
imported++;
|
||||
} catch (err: unknown) {
|
||||
report.errors.push({ row: idx + 1, field: "row", code: "format", message: `Skapning misslyckades: ${err instanceof Error ? err.message : "okänt fel"}` });
|
||||
}
|
||||
}
|
||||
|
||||
// AUD0 audit — 0pt's sole producer boundary; durable outbox under DATABASE_URL.
|
||||
try {
|
||||
const aud0 = createAud0Client();
|
||||
await aud0.ingestEvent({
|
||||
event_id: (globalThis.crypto?.randomUUID?.() ?? `evt-${Date.now()}`),
|
||||
event_type: "0pt.orders.import",
|
||||
tenant_id: owner.tenantId,
|
||||
project_id: "0pt-orders",
|
||||
actor_id: owner.subject,
|
||||
app_id: "0pt",
|
||||
capability_id: "orders.import",
|
||||
resource_type: "order",
|
||||
resource_id: orderIds[0] ?? "none",
|
||||
risk_level: "L2",
|
||||
payload: { imported, total_rows: report.totalRows, error_count: report.errors.length, order_ids: orderIds },
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
} catch (auditErr: unknown) {
|
||||
console.error("[0pt-orders-import] AUD0 emission failed (import not rolled back):", auditErr);
|
||||
}
|
||||
|
||||
return NextResponse.json({ mode, imported, totalRows: report.totalRows, validRows: report.validRows, errorCount: report.errors.length, errors: report.errors.slice(0, 100), order_ids: orderIds });
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createOrder, listOwnedOrders, IdempotencyKeyConflictError, type OrderConfig } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { resolveAdvanceAction, buildOrderInboxItem } from "@/lib/order-flow";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../siax-error-mapping";
|
||||
|
||||
// POST /api/orders (docs/04) — create a draft order from a configurator config.
|
||||
@@ -57,10 +56,7 @@ export async function GET(req: NextRequest) {
|
||||
if (auth.response) return auth.response;
|
||||
try {
|
||||
const orders = await listOwnedOrders(auth.owner.tenantId);
|
||||
// ADR-0001: servern resolvér advance-aktionen per order — klienten
|
||||
// renderar bara (ActionGate). Policy ägs här, inte i UI-lagret.
|
||||
const withActions = orders.map((o) => ({ ...o, advance_action: resolveAdvanceAction(o.status), inbox_item: buildOrderInboxItem(o) }));
|
||||
return NextResponse.json(withActions);
|
||||
return NextResponse.json(orders);
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
|
||||
@@ -10,11 +10,9 @@ import { checkAllDependencies, isReady } from "@/lib/health-checks";
|
||||
// readiness probe at this route, not /api/health, to stop routing traffic to
|
||||
// an instance whose database is down without restarting it.
|
||||
//
|
||||
// Load-bearing by absence: only the database (see
|
||||
// Today the only load-bearing dependency is the database (see
|
||||
// `lib/health-checks.ts#isReady`) -- engine/stripe/queue are optional
|
||||
// integrations 0pt is designed to run without. Load-bearing by FAILURE: all
|
||||
// of them. A dependency somebody configured and that then fails a live round
|
||||
// trip makes this instance not-ready, whichever one it is.
|
||||
// integrations 0pt is designed to run without.
|
||||
export async function GET() {
|
||||
const deps = await checkAllDependencies();
|
||||
const ready = isReady(deps);
|
||||
|
||||
+20
-23
@@ -1,30 +1,27 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { engineFetch, hasEngine } from "@/lib/engine";
|
||||
import { engineFetch } from "@/lib/engine";
|
||||
|
||||
// An unavailable or malformed screening source is never evidence of no match.
|
||||
// GET /api/screen?q=Name — OpenSanctions screening (sanctions/PEP). VERIFY
|
||||
// commercial terms before production volume. Defers to engine when running.
|
||||
export async function GET(req: NextRequest) {
|
||||
const q = req.nextUrl.searchParams.get("q")?.trim() ?? "";
|
||||
if (!q) return NextResponse.json({ error: { code: "bad_request", message: "q krävs" } }, { status: 400 });
|
||||
const unavailable = () => NextResponse.json({ error: { code: "source_unavailable", message: "Screeningkällan är inte tillgänglig" } }, { status: 503 });
|
||||
const q = req.nextUrl.searchParams.get("q") ?? "";
|
||||
if (!q) return NextResponse.json({ matches: [] });
|
||||
|
||||
const eng = await engineFetch(`/screen?q=${encodeURIComponent(q)}`);
|
||||
if (eng && eng.ok) return NextResponse.json(await eng.json());
|
||||
|
||||
try {
|
||||
if (hasEngine()) {
|
||||
const eng = await engineFetch(`/screen?q=${encodeURIComponent(q)}`);
|
||||
if (!eng?.ok) return unavailable();
|
||||
const data: unknown = await eng.json();
|
||||
if (!data || typeof data !== "object" || (!Array.isArray((data as { matches?: unknown }).matches) || (data as { source_status?: unknown }).source_status !== "ok")) return unavailable();
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
const r = await fetch(`https://api.opensanctions.org/search/default?q=${encodeURIComponent(q)}&limit=5`, {
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" }, cache: "no-store",
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" },
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!r.ok) return unavailable();
|
||||
const data: unknown = await r.json();
|
||||
if (!data || typeof data !== "object" || !Array.isArray((data as { results?: unknown }).results)) return unavailable();
|
||||
const results = (data as { results: unknown[] }).results;
|
||||
if (results.some((item) => !item || typeof item !== "object" || Array.isArray(item))) return unavailable();
|
||||
return NextResponse.json({ source: "opensanctions", matches: results.map((item) => {
|
||||
const x = item as { caption?: unknown; score?: unknown; schema?: unknown };
|
||||
return { name: x.caption ?? null, score: x.score ?? null, schema: x.schema ?? null };
|
||||
}) });
|
||||
} catch { return unavailable(); }
|
||||
if (!r.ok) return NextResponse.json({ matches: [], source: "opensanctions" });
|
||||
const data = (await r.json()) as { results?: { caption?: string; score?: number; schema?: string }[] };
|
||||
return NextResponse.json({
|
||||
source: "opensanctions",
|
||||
matches: (data.results ?? []).map((x) => ({ name: x.caption ?? null, score: x.score ?? null, schema: x.schema ?? null })),
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json({ matches: [], source: "opensanctions" });
|
||||
}
|
||||
}
|
||||
|
||||
+25
-21
@@ -1,30 +1,34 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { engineFetch, hasEngine } from "@/lib/engine";
|
||||
import { engineFetch } from "@/lib/engine";
|
||||
|
||||
// A missing record is distinct from an unavailable or malformed source.
|
||||
// GET /api/vehicles?plate=XX-99-YY — RDW (NL) open vehicle data (technical/fleet
|
||||
// only, no owner PII). Defers to the engine when running; else calls RDW directly.
|
||||
export async function GET(req: NextRequest) {
|
||||
const plate = (req.nextUrl.searchParams.get("plate") ?? "").toUpperCase().replace(/[-\s]/g, "").replace(/[^A-Z0-9]/g, "");
|
||||
if (!plate) return NextResponse.json({ error: { code: "bad_request", message: "plate krävs" } }, { status: 400 });
|
||||
const unavailable = () => NextResponse.json({ error: { code: "source_unavailable", message: "Fordonskällan är inte tillgänglig" } }, { status: 503 });
|
||||
|
||||
const eng = await engineFetch(`/vehicles/${plate}`);
|
||||
if (eng && eng.ok) return NextResponse.json(await eng.json());
|
||||
|
||||
try {
|
||||
if (hasEngine()) {
|
||||
const eng = await engineFetch(`/vehicles/${plate}`);
|
||||
if (!eng?.ok) return unavailable();
|
||||
const data: unknown = await eng.json();
|
||||
if (!data || typeof data !== "object" || Array.isArray(data) || (data as { source_status?: unknown }).source_status !== "ok") return unavailable();
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
const r = await fetch(`https://opendata.rdw.nl/resource/m9d7-ebf2.json?kenteken=${encodeURIComponent(plate)}`, {
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" }, cache: "no-store",
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" },
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!r.ok) return unavailable();
|
||||
const data: unknown = await r.json();
|
||||
if (!Array.isArray(data) || data.some((item) => !item || typeof item !== "object" || Array.isArray(item))) return unavailable();
|
||||
if (!data.length) return NextResponse.json({ vehicle: null });
|
||||
const d = data[0] as Record<string, string>;
|
||||
if (d.datum_eerste_toelating != null && typeof d.datum_eerste_toelating !== "string") return unavailable();
|
||||
return NextResponse.json({ source: "rdw", vehicle: { reg_plate: plate, market: "NL", make: d.merk ?? null,
|
||||
model: d.handelsbenaming ?? null, year: (d.datum_eerste_toelating ?? "").slice(0, 4) || null },
|
||||
provenance: { level: 3, source: "rdw" } });
|
||||
} catch { return unavailable(); }
|
||||
if (!r.ok) return NextResponse.json({ vehicle: null }, { status: 200 });
|
||||
const arr = (await r.json()) as Record<string, string>[];
|
||||
if (!arr.length) return NextResponse.json({ vehicle: null });
|
||||
const d = arr[0];
|
||||
return NextResponse.json({
|
||||
source: "rdw",
|
||||
vehicle: {
|
||||
reg_plate: plate, market: "NL",
|
||||
make: d.merk ?? null, model: d.handelsbenaming ?? null,
|
||||
year: (d.datum_eerste_toelating ?? "").slice(0, 4) || null,
|
||||
},
|
||||
provenance: { level: 3, source: "rdw" },
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json({ vehicle: null, error: "fetch_failed" }, { status: 200 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/**
|
||||
* GET /api/version — deployment identity for automated verification.
|
||||
*
|
||||
* Returns only non-sensitive build identity (no env values, no config). The
|
||||
* scheduled prod-smoke workflow compares `commit` with the current main SHA so
|
||||
* "the container is up" is never confused with "the intended commit is live".
|
||||
*/
|
||||
export async function GET() {
|
||||
const commit =
|
||||
process.env.SOURCE_COMMIT ?? process.env.GIT_COMMIT_SHA ?? process.env.VERCEL_GIT_COMMIT_SHA ?? null;
|
||||
return NextResponse.json(
|
||||
{
|
||||
service: '0pt-web',
|
||||
commit,
|
||||
built_at: process.env.BUILD_TIME ?? null,
|
||||
},
|
||||
{ headers: { 'cache-control': 'no-store' } },
|
||||
);
|
||||
}
|
||||
@@ -1,97 +1,38 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import type Stripe from 'stripe';
|
||||
import { getStripe } from '@/lib/stripe';
|
||||
import { getOrder, setStatusIfCurrent } from '@/lib/orders-store';
|
||||
import { isSiaxError } from '../../siax-error-mapping';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { PostgresCreditPurchaseStore } from '@/src/document-workbench/credit-purchase-store';
|
||||
import {
|
||||
StripeCreditVerificationError,
|
||||
verifyStripeCreditPurchase,
|
||||
} from '@/src/document-workbench/stripe-credit-verification';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* Credit purchases are granted ONLY from Stripe's own re-read of the session
|
||||
* and payment intent. The webhook body is a trigger, never proof of price or
|
||||
* payment. The ledger command is idempotent, so duplicate deliveries are safe.
|
||||
*/
|
||||
async function handleCreditPurchase(
|
||||
stripe: NonNullable<ReturnType<typeof getStripe>>,
|
||||
session: Stripe.Checkout.Session,
|
||||
) {
|
||||
const tenantId = session.metadata?.tenant_id;
|
||||
const purchaseId = session.metadata?.purchase_id;
|
||||
if (!tenantId || !purchaseId) {
|
||||
return NextResponse.json({ error: 'unmatched_session' }, { status: 422 });
|
||||
}
|
||||
const url = repositoryDatabaseUrl();
|
||||
if (!url) {
|
||||
return NextResponse.json({ received: false, reason: 'credits_not_configured' }, { status: 503 });
|
||||
}
|
||||
try {
|
||||
const store = new PostgresCreditPurchaseStore(getRepositorySql(url));
|
||||
const snapshot = await store.get(tenantId, purchaseId);
|
||||
if (!snapshot) {
|
||||
// Do not acknowledge a paid purchase we cannot bind to a server snapshot.
|
||||
return NextResponse.json({ received: false, reason: 'purchase_not_found' }, { status: 503 });
|
||||
}
|
||||
if (snapshot.checkoutSessionId !== session.id) {
|
||||
return NextResponse.json({ error: 'session_mismatch' }, { status: 422 });
|
||||
}
|
||||
const command = await verifyStripeCreditPurchase(stripe, snapshot, { tenantId });
|
||||
const result = await new PostgresCreditLedger(getRepositorySql(url)).apply(command);
|
||||
return NextResponse.json({ received: true, credited: !result.replay, balance: result.balance });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Credit reconciliation failed';
|
||||
if (error instanceof StripeCreditVerificationError) {
|
||||
const terminal = ['mismatch', 'not_paid', 'refunded', 'unsupported'].includes(error.reason);
|
||||
return NextResponse.json(
|
||||
{ received: false, reason: error.reason, message },
|
||||
{ status: terminal ? 422 : 503 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ received: false, reason: 'ledger_unavailable', message }, { status: 503 });
|
||||
}
|
||||
}
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
import { getStripe } from "@/lib/stripe";
|
||||
import { getOrder, setStatusIfCurrent } from "@/lib/orders-store";
|
||||
import { isSiaxError } from "../../siax-error-mapping";
|
||||
|
||||
// POST /api/webhooks/stripe (docs/04) — verify signature, advance order status.
|
||||
export async function POST(req: NextRequest) {
|
||||
const stripe = getStripe();
|
||||
const whSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
||||
const sig = req.headers.get('stripe-signature');
|
||||
const sig = req.headers.get("stripe-signature");
|
||||
if (!stripe || !whSecret) {
|
||||
// Never acknowledge an event that was not signature-verified and processed.
|
||||
// A non-2xx response keeps Stripe's delivery retry/reconciliation path open.
|
||||
return NextResponse.json({ received: false, reason: 'not_configured' }, { status: 503 });
|
||||
return NextResponse.json({ received: false, reason: "not_configured" }, { status: 503 });
|
||||
}
|
||||
if (!sig) {
|
||||
return NextResponse.json({ error: 'missing_signature' }, { status: 400 });
|
||||
return NextResponse.json({ error: "missing_signature" }, { status: 400 });
|
||||
}
|
||||
const body = await req.text();
|
||||
let event;
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(body, sig, whSecret);
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'bad_signature' }, { status: 400 });
|
||||
return NextResponse.json({ error: "bad_signature" }, { status: 400 });
|
||||
}
|
||||
if (
|
||||
event.type === 'checkout.session.completed' ||
|
||||
event.type === 'checkout.session.async_payment_succeeded'
|
||||
) {
|
||||
if (event.type === "checkout.session.completed") {
|
||||
const s = event.data.object as Stripe.Checkout.Session;
|
||||
const oid = s.metadata?.order_id;
|
||||
const kind = s.metadata?.kind;
|
||||
if (kind === '0pt_credit_purchase') {
|
||||
return handleCreditPurchase(stripe, s);
|
||||
if (!oid || (kind !== "deposit" && kind !== "balance")) {
|
||||
return NextResponse.json({ error: "unmatched_session" }, { status: 422 });
|
||||
}
|
||||
if (!oid || (kind !== 'deposit' && kind !== 'balance')) {
|
||||
return NextResponse.json({ error: 'unmatched_session' }, { status: 422 });
|
||||
}
|
||||
if (s.payment_status !== 'paid') {
|
||||
return NextResponse.json({ error: 'payment_not_confirmed' }, { status: 503 });
|
||||
if (s.payment_status !== "paid") {
|
||||
return NextResponse.json({ error: "payment_not_confirmed" }, { status: 503 });
|
||||
}
|
||||
// 0pt#53: durable-store failure -> documented non-2xx (never an opaque 500,
|
||||
// and never a silent received:true for a paid event that was NOT processed —
|
||||
@@ -100,52 +41,47 @@ export async function POST(req: NextRequest) {
|
||||
try {
|
||||
order = await getOrder(oid);
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err))
|
||||
return NextResponse.json({ received: false, reason: 'store_unavailable' }, { status: 503 });
|
||||
if (isSiaxError(err)) return NextResponse.json({ received: false, reason: "store_unavailable" }, { status: 503 });
|
||||
throw err;
|
||||
}
|
||||
if (!order) return NextResponse.json({ error: 'order_not_found' }, { status: 503 });
|
||||
if (!order) return NextResponse.json({ error: "order_not_found" }, { status: 503 });
|
||||
if (!order.tenant_id || !order.buyer_subject) {
|
||||
// A legacy anonymous draft is not a payable order. Do not silently
|
||||
// acknowledge a paid event until an audited owner-remediation path exists.
|
||||
return NextResponse.json({ error: 'order_owner_missing' }, { status: 503 });
|
||||
return NextResponse.json({ error: "order_owner_missing" }, { status: 503 });
|
||||
}
|
||||
const expectedAmount = kind === 'balance' ? order.balance_ore : order.deposit_ore;
|
||||
if (s.amount_total !== expectedAmount || s.currency?.toLowerCase() !== 'sek') {
|
||||
return NextResponse.json({ error: 'payment_mismatch' }, { status: 422 });
|
||||
const expectedAmount = kind === "balance" ? order.balance_ore : order.deposit_ore;
|
||||
if (s.amount_total !== expectedAmount || s.currency?.toLowerCase() !== "sek") {
|
||||
return NextResponse.json({ error: "payment_mismatch" }, { status: 422 });
|
||||
}
|
||||
if (kind === 'balance') {
|
||||
if (order.status !== 'accepted' && order.status !== 'delivered') {
|
||||
return NextResponse.json({ error: 'invalid_order_state' }, { status: 409 });
|
||||
if (kind === "balance") {
|
||||
if (order.status !== "accepted" && order.status !== "delivered") {
|
||||
return NextResponse.json({ error: "invalid_order_state" }, { status: 409 });
|
||||
}
|
||||
let delivered = false;
|
||||
try {
|
||||
delivered = order.status === 'accepted' && !!(await setStatusIfCurrent(oid, 'accepted', 'delivered'));
|
||||
delivered = order.status === "accepted" && !!(await setStatusIfCurrent(oid, "accepted", "delivered"));
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err))
|
||||
return NextResponse.json({ received: false, reason: 'store_unavailable' }, { status: 503 });
|
||||
if (isSiaxError(err)) return NextResponse.json({ received: false, reason: "store_unavailable" }, { status: 503 });
|
||||
throw err;
|
||||
}
|
||||
if (order.status === 'accepted' && !delivered) {
|
||||
return NextResponse.json({ error: 'order_update_failed' }, { status: 503 });
|
||||
if (order.status === "accepted" && !delivered) {
|
||||
return NextResponse.json({ error: "order_update_failed" }, { status: 503 });
|
||||
}
|
||||
} else {
|
||||
const alreadyAdvanced = ['in_production', 'review', 'revision', 'accepted', 'delivered'].includes(
|
||||
order.status,
|
||||
);
|
||||
if (order.status !== 'draft' && order.status !== 'deposit_pending' && !alreadyAdvanced) {
|
||||
return NextResponse.json({ error: 'invalid_order_state' }, { status: 409 });
|
||||
const alreadyAdvanced = ["in_production", "review", "revision", "accepted", "delivered"].includes(order.status);
|
||||
if (order.status !== "draft" && order.status !== "deposit_pending" && !alreadyAdvanced) {
|
||||
return NextResponse.json({ error: "invalid_order_state" }, { status: 409 });
|
||||
}
|
||||
let advanced = true;
|
||||
try {
|
||||
advanced = alreadyAdvanced || !!(await setStatusIfCurrent(oid, order.status, 'in_production'));
|
||||
advanced = alreadyAdvanced || !!(await setStatusIfCurrent(oid, order.status, "in_production"));
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err))
|
||||
return NextResponse.json({ received: false, reason: 'store_unavailable' }, { status: 503 });
|
||||
if (isSiaxError(err)) return NextResponse.json({ received: false, reason: "store_unavailable" }, { status: 503 });
|
||||
throw err;
|
||||
}
|
||||
if (!advanced) {
|
||||
return NextResponse.json({ error: 'order_update_failed' }, { status: 503 });
|
||||
return NextResponse.json({ error: "order_update_failed" }, { status: 503 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ export default function DescribePage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{svc ? <p className="mt-3 text-sm text-muted-foreground">{t(svc.covers)} <span className="text-muted-foreground">→ {t(svc.deliverable)}</span></p> : null}
|
||||
{svc ? <p className="mt-3 text-sm text-muted-foreground">{t(svc.covers)} <span className="text-muted-foreground/60">→ {t(svc.deliverable)}</span></p> : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-8">
|
||||
|
||||
+2
-2
@@ -273,7 +273,7 @@ export default function SourcesPage() {
|
||||
>
|
||||
<td className="px-3 py-3 align-top">
|
||||
<span className="text-[15px] tracking-tight">{s.name}</span>
|
||||
<span className="ml-2 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">
|
||||
<span className="ml-2 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground/60">
|
||||
{s.source_id}
|
||||
</span>
|
||||
</td>
|
||||
@@ -301,7 +301,7 @@ export default function SourcesPage() {
|
||||
<p className="font-mono text-[10.5px] uppercase tracking-[0.08em] text-muted-foreground">
|
||||
{rows.length} {t({ en: "sources · every field carries its provenance", sv: "källor · varje fält bär sin härkomst" })}
|
||||
</p>
|
||||
<p className="font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">
|
||||
<p className="font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
{t({ en: "Licence terms verified before use", sv: "Licensvillkor verifieras innan användning" })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import { Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Header } from "@/components/header";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
import { DataArtifact } from "@/components/data-artifact";
|
||||
@@ -142,43 +142,14 @@ function findDataset(raw: string | undefined): Dataset | undefined {
|
||||
return CATALOG.find((d) => d.id === slug);
|
||||
}
|
||||
|
||||
const TAB_KEYS = TABS.map((t) => t.key);
|
||||
function isTabKey(value: string | null): value is TabKey {
|
||||
return value !== null && (TAB_KEYS as string[]).includes(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flikvalet lever i URL:en (?tab=…, kernel-konventionen: URL state är kanoniskt)
|
||||
* — "Tillbaka" återställer flik, och en delad länk öppnar samma flik. Komponenten
|
||||
* wrappas i Suspense eftersom useSearchParams kräver det vid prerender.
|
||||
*/
|
||||
export default function DatasetDetailPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<DatasetDetailInner />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function DatasetDetailInner() {
|
||||
const t = useT();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const reveal = useReveal<HTMLDivElement>();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const tabParam = searchParams.get("tab");
|
||||
const tab: TabKey = isTabKey(tabParam) ? tabParam : "overview";
|
||||
function setTabNext(next: TabKey) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (next === "overview") params.delete("tab");
|
||||
else params.set("tab", next);
|
||||
const qs = params.toString();
|
||||
router.replace(qs ? `?${qs}` : window.location.pathname, { scroll: false });
|
||||
}
|
||||
|
||||
const [status, setStatus] = useState<"loading" | "ready" | "empty" | "error">("loading");
|
||||
const [dataset, setDataset] = useState<Dataset | null>(null);
|
||||
const [tab, setTab] = useState<TabKey>("overview");
|
||||
const attempt = useRef(0);
|
||||
|
||||
const load = useCallback(() => {
|
||||
@@ -224,7 +195,7 @@ function DatasetDetailInner() {
|
||||
<section className="py-24">
|
||||
<ErrorState title={t({ en: "Couldn't load the dataset", sv: "Kunde inte hämta datasetet" })} onRetry={load} />
|
||||
<div className="mt-10">
|
||||
<Link href="/katalog" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
|
||||
<Link href="/#katalog" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
|
||||
{t({ en: "← Back to the catalog", sv: "← Till katalogen" })}
|
||||
</Link>
|
||||
</div>
|
||||
@@ -240,14 +211,14 @@ function DatasetDetailInner() {
|
||||
ctaLabel={t({ en: "Compose a job", sv: "Komponera ett jobb" })}
|
||||
/>
|
||||
<div className="mt-10">
|
||||
<Link href="/katalog" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
|
||||
<Link href="/#katalog" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
|
||||
{t({ en: "← Back to the catalog", sv: "← Till katalogen" })}
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{status === "ready" && dataset ? <DatasetView d={dataset} tab={tab} setTab={setTabNext} /> : null}
|
||||
{status === "ready" && dataset ? <DatasetView d={dataset} tab={tab} setTab={setTab} /> : null}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
@@ -278,7 +249,7 @@ function DatasetView({ d, tab, setTab }: { d: Dataset; tab: TabKey; setTab: (k:
|
||||
<div ref={revealRef}>
|
||||
{/* breadcrumb */}
|
||||
<div className="reveal flex items-center gap-2 border-b border-border py-4 font-mono text-[11px] uppercase tracking-[0.12em] text-muted-foreground">
|
||||
<Link href="/katalog" className="underline-offset-4 transition-colors hover:text-foreground hover:underline">
|
||||
<Link href="/#katalog" className="underline-offset-4 transition-colors hover:text-foreground hover:underline">
|
||||
{t({ en: "Catalog", sv: "Katalog" })}
|
||||
</Link>
|
||||
<span className="text-border">/</span>
|
||||
|
||||
+7
-49
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
import { Header } from "@/components/header";
|
||||
import { useReveal } from "@/hooks/use-reveal";
|
||||
@@ -37,56 +37,14 @@ function level(c: number): ProvLevel {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter + sök lever i URL:en (kernel-konventionen: URL state är kanoniskt och
|
||||
* återställbart) — "Tillbaka" från en detaljsida återställer exakt vy, och en
|
||||
* delad länk öppnar samma filtrering. pages-komponenten wrappar i Suspense
|
||||
* eftersom useSearchParams kräver det vid prerender.
|
||||
*/
|
||||
export default function CatalogPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<CatalogInner />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function CatalogInner() {
|
||||
const t = useT();
|
||||
const ref = useReveal<HTMLDivElement>();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [items, setItems] = useState<CatalogItem[] | null>(null);
|
||||
const [err, setErr] = useState(false);
|
||||
const filter = searchParams.get("filter") ?? "all";
|
||||
const q = searchParams.get("q") ?? "";
|
||||
// Lokalt utkast för sökfältet (skrivtick), synkat debouncerat till URL:en.
|
||||
const [qDraft, setQDraft] = useState(q);
|
||||
const urlSync = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useEffect(() => { setQDraft(q); }, [q]);
|
||||
|
||||
function applyState(next: { q?: string; filter?: string }) {
|
||||
const params = new URLSearchParams();
|
||||
const nq = (next.q ?? q).trim().slice(0, 120);
|
||||
const nf = next.filter ?? filter;
|
||||
if (nq) params.set("q", nq);
|
||||
if (nf && nf !== "all") params.set("filter", nf);
|
||||
const qs = params.toString();
|
||||
router.replace(qs ? `/katalog?${qs}` : "/katalog", { scroll: false });
|
||||
}
|
||||
|
||||
function setFilterNext(next: string) {
|
||||
if (urlSync.current) clearTimeout(urlSync.current);
|
||||
applyState({ filter: next });
|
||||
}
|
||||
|
||||
function setQNext(next: string) {
|
||||
setQDraft(next);
|
||||
if (urlSync.current) clearTimeout(urlSync.current);
|
||||
urlSync.current = setTimeout(() => applyState({ q: next }), 250);
|
||||
}
|
||||
|
||||
useEffect(() => () => { if (urlSync.current) clearTimeout(urlSync.current); }, []);
|
||||
const [filter, setFilter] = useState("all");
|
||||
const [q, setQ] = useState("");
|
||||
|
||||
function load() {
|
||||
setErr(false);
|
||||
@@ -131,7 +89,7 @@ function CatalogInner() {
|
||||
{FILTERS.map((f) => (
|
||||
<button
|
||||
key={f.key}
|
||||
onClick={() => setFilterNext(f.key)}
|
||||
onClick={() => setFilter(f.key)}
|
||||
aria-pressed={filter === f.key}
|
||||
className="border px-3 py-1.5 font-mono text-[11px] uppercase tracking-[0.08em] transition-colors"
|
||||
style={{
|
||||
@@ -145,8 +103,8 @@ function CatalogInner() {
|
||||
))}
|
||||
</div>
|
||||
<input
|
||||
value={qDraft}
|
||||
onChange={(e) => setQNext(e.target.value)}
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder={t({ en: "Search datasets…", sv: "Sök dataset…" })}
|
||||
aria-label={t({ en: "Search datasets", sv: "Sök dataset" })}
|
||||
className="w-full max-w-xs border border-border bg-input px-3 py-2 font-mono text-xs outline-none focus:border-foreground sm:w-auto"
|
||||
|
||||
@@ -1,524 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useT } from '@/components/locale-provider';
|
||||
import { PortalShell } from '@/components/portal-shell';
|
||||
|
||||
/**
|
||||
* /portal/dokument — the customer's document workspace.
|
||||
*
|
||||
* Three honest steps:
|
||||
* 1. Upload the original file (real bytes, multipart) into DOC0.
|
||||
* 2. Describe the structure you want and the fields to extract.
|
||||
* 3. Review the evidence-bound output and download JSON/CSV.
|
||||
*
|
||||
* Nothing on this page fabricates success: a 503 means the capability is not
|
||||
* configured, and an "outcome unknown" upload is shown as exactly that.
|
||||
*/
|
||||
|
||||
type Receipt = {
|
||||
document_id: string;
|
||||
version_id: string;
|
||||
checksum_sha256: string;
|
||||
pipeline_stage: string;
|
||||
};
|
||||
|
||||
type FieldRow = { name: string; type: 'string' | 'integer' | 'boolean' | 'decimal' | 'date' };
|
||||
|
||||
type Evidence = {
|
||||
field: string;
|
||||
sourceId: string;
|
||||
start: number;
|
||||
end: number;
|
||||
transform: string;
|
||||
};
|
||||
|
||||
type StructureResponse = {
|
||||
status: 'mechanically_validated' | 'needs_review' | 'outcome_unknown';
|
||||
value?: Record<string, string | number | boolean>;
|
||||
evidence?: Evidence[];
|
||||
issues?: { field: string; code: string; row?: number }[];
|
||||
model?: {
|
||||
modelExecuted: string;
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
totalTokens: number;
|
||||
costUsd?: number;
|
||||
};
|
||||
credits?: { reserved: number; charged: number; balance?: { available: number; reserved: number } };
|
||||
export?: { media_type: string; content: string };
|
||||
message?: string;
|
||||
error?: string;
|
||||
reservation_id?: string;
|
||||
};
|
||||
|
||||
type ModelsResponse = {
|
||||
models: string[];
|
||||
data_classes: string[];
|
||||
destination: string;
|
||||
external_transfer_allowed: boolean;
|
||||
max_input_tokens: number;
|
||||
max_output_tokens: number;
|
||||
price_book_version: string | null;
|
||||
};
|
||||
|
||||
const TYPES: FieldRow['type'][] = ['string', 'integer', 'decimal', 'date', 'boolean'];
|
||||
|
||||
export default function DocumentsPage() {
|
||||
const t = useT();
|
||||
const [projectId, setProjectId] = useState('');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [receipt, setReceipt] = useState<Receipt | null>(null);
|
||||
const [uploadNote, setUploadNote] = useState<string | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [unknownOutcome, setUnknownOutcome] = useState<unknown | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [instruction, setInstruction] = useState('');
|
||||
const [fields, setFields] = useState<FieldRow[]>([{ name: 'organization', type: 'string' }]);
|
||||
const [models, setModels] = useState<ModelsResponse | null>(null);
|
||||
const [modelsError, setModelsError] = useState<string | null>(null);
|
||||
const [modelId, setModelId] = useState('');
|
||||
const [dataClass, setDataClass] = useState('low');
|
||||
const [format, setFormat] = useState<'json' | 'csv'>('json');
|
||||
const [structuring, setStructuring] = useState(false);
|
||||
const [result, setResult] = useState<StructureResponse | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const stored = window.localStorage.getItem('0pt.project_id');
|
||||
if (stored) setProjectId(stored);
|
||||
fetch('/api/0pt/documents/models', { cache: 'no-store' })
|
||||
.then(async (r) => {
|
||||
const body = (await r.json()) as ModelsResponse & { message?: string };
|
||||
if (!r.ok) {
|
||||
setModelsError(body.message ?? 'Modellpolicyn är inte konfigurerad');
|
||||
return;
|
||||
}
|
||||
setModels(body);
|
||||
setModelId((current) => current || body.models[0] || '');
|
||||
setDataClass((current) =>
|
||||
body.data_classes.includes(current) ? current : (body.data_classes[0] ?? 'low'),
|
||||
);
|
||||
})
|
||||
.catch(() => setModelsError('Kunde inte läsa modellpolicyn'));
|
||||
}, []);
|
||||
|
||||
const upload = useCallback(async () => {
|
||||
if (!file || uploading) return;
|
||||
if (!projectId.trim()) {
|
||||
setError(t({ en: 'A project id is required', sv: 'Ett projekt-id krävs' }));
|
||||
return;
|
||||
}
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
setUploadNote(null);
|
||||
setUnknownOutcome(null);
|
||||
setReceipt(null);
|
||||
window.localStorage.setItem('0pt.project_id', projectId.trim());
|
||||
const form = new FormData();
|
||||
form.set('file', file);
|
||||
form.set('project_id', projectId.trim());
|
||||
form.set('idempotency_key', crypto.randomUUID());
|
||||
form.set('classification', 'restricted');
|
||||
try {
|
||||
const response = await fetch('/api/0pt/documents/upload', {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
headers: { 'x-request-id': crypto.randomUUID() },
|
||||
});
|
||||
const body = (await response.json().catch(() => ({}))) as Record<string, unknown> & {
|
||||
status?: string;
|
||||
message?: string;
|
||||
error?: string;
|
||||
};
|
||||
if (response.status === 201) {
|
||||
setReceipt({
|
||||
document_id: String(body.document_id),
|
||||
version_id: String(body.version_id),
|
||||
checksum_sha256: String(body.checksum_sha256),
|
||||
pipeline_stage: String(body.pipeline_stage),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (response.status === 202) {
|
||||
setUnknownOutcome(body.observation ?? body);
|
||||
setUploadNote(
|
||||
t({
|
||||
en: 'The upload may have been accepted. It is not confirmed.',
|
||||
sv: 'Uppladdningen kan ha tagits emot. Den är inte bekräftad.',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setUploadNote(
|
||||
body.message ?? body.error ?? t({ en: 'Upload failed', sv: 'Uppladdningen misslyckades' }),
|
||||
);
|
||||
} catch {
|
||||
setUploadNote(t({ en: 'Upload failed', sv: 'Uppladdningen misslyckades' }));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}, [file, projectId, t, uploading]);
|
||||
|
||||
const structure = useCallback(async () => {
|
||||
if (!receipt || structuring) return;
|
||||
if (!instruction.trim()) {
|
||||
setError(t({ en: 'Describe the structure you want', sv: 'Beskriv strukturen du vill ha' }));
|
||||
return;
|
||||
}
|
||||
if (!modelId) {
|
||||
setError(t({ en: 'No approved model is configured', sv: 'Ingen godkänd modell är konfigurerad' }));
|
||||
return;
|
||||
}
|
||||
setStructuring(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
try {
|
||||
const response = await fetch('/api/0pt/documents/structure', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-request-id': crypto.randomUUID() },
|
||||
body: JSON.stringify({
|
||||
project_id: projectId.trim(),
|
||||
document_id: receipt.document_id,
|
||||
version_id: receipt.version_id,
|
||||
checksum_sha256: receipt.checksum_sha256,
|
||||
pipeline_stage: receipt.pipeline_stage,
|
||||
instruction,
|
||||
fields,
|
||||
model_id: modelId,
|
||||
data_class: dataClass,
|
||||
format,
|
||||
}),
|
||||
});
|
||||
const body = (await response.json().catch(() => ({}))) as StructureResponse;
|
||||
if (response.ok || response.status === 202) {
|
||||
setResult(body);
|
||||
} else {
|
||||
setError(
|
||||
body.message ?? body.error ?? t({ en: 'Structuring failed', sv: 'Struktureringen misslyckades' }),
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
setError(t({ en: 'Structuring failed', sv: 'Struktureringen misslyckades' }));
|
||||
} finally {
|
||||
setStructuring(false);
|
||||
}
|
||||
}, [receipt, structuring, instruction, modelId, dataClass, projectId, fields, format, t]);
|
||||
|
||||
function download() {
|
||||
if (!result?.export) return;
|
||||
const blob = new Blob([result.export.content], { type: result.export.media_type });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = `0pt-${receipt?.document_id ?? 'result'}.${format}`;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function addField() {
|
||||
if (fields.length >= 100) return;
|
||||
setFields((current) => [...current, { name: `field_${current.length + 1}`, type: 'string' }]);
|
||||
}
|
||||
|
||||
function updateField(index: number, patch: Partial<FieldRow>) {
|
||||
setFields((current) => current.map((row, i) => (i === index ? { ...row, ...patch } : row)));
|
||||
}
|
||||
|
||||
function removeField(index: number) {
|
||||
setFields((current) => current.filter((_, i) => i !== index));
|
||||
}
|
||||
|
||||
const card = 'border border-border bg-background p-6';
|
||||
const label = 'font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground';
|
||||
const input =
|
||||
'mt-2 w-full border border-border bg-background px-3 py-2 font-mono text-[13px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
|
||||
|
||||
return (
|
||||
<PortalShell variant="customer" title={t({ en: 'Documents', sv: 'Dokument' })}>
|
||||
<div className="mx-auto w-full max-w-4xl space-y-6">
|
||||
<p className="max-w-2xl text-pretty text-[15px] leading-relaxed text-muted-foreground">
|
||||
{t({
|
||||
en: 'Upload a file, describe how it should be structured, and get evidence-bound data you can download.',
|
||||
sv: 'Ladda upp en fil, beskriv hur den ska struktureras och få evidensbunden data som du kan ladda ner.',
|
||||
})}
|
||||
</p>
|
||||
|
||||
{/* 1 · upload */}
|
||||
<section className={card}>
|
||||
<div className="flex items-baseline justify-between gap-4">
|
||||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||||
{t({ en: '1 · Source', sv: '1 · Underlag' })}
|
||||
</h2>
|
||||
{receipt ? (
|
||||
<span
|
||||
className="font-mono text-[10px] uppercase tracking-[0.18em]"
|
||||
style={{ color: 'var(--accent-red)' }}
|
||||
>
|
||||
{t({ en: 'uploaded', sv: 'uppladdad' })}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<label className="mt-4 block">
|
||||
<span className={label}>{t({ en: 'project id', sv: 'projekt-id' })}</span>
|
||||
<input
|
||||
className={input}
|
||||
value={projectId}
|
||||
onChange={(event) => setProjectId(event.target.value)}
|
||||
placeholder="prj_…"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
inputRef.current?.click();
|
||||
}
|
||||
}}
|
||||
className="mt-4 flex cursor-pointer flex-col items-center justify-center border border-dashed border-border px-6 py-10 text-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<span className={label}>{t({ en: 'choose a file', sv: 'välj en fil' })}</span>
|
||||
<span className="mt-3 text-[15px]">
|
||||
{file
|
||||
? file.name
|
||||
: t({ en: 'PDF, Word, Excel, CSV, images…', sv: 'PDF, Word, Excel, CSV, bilder…' })}
|
||||
</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={upload}
|
||||
disabled={!file || uploading}
|
||||
className="mt-4 border border-foreground bg-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em] text-background disabled:opacity-40"
|
||||
>
|
||||
{uploading ? t({ en: 'uploading…', sv: 'laddar upp…' }) : t({ en: 'upload', sv: 'ladda upp' })}
|
||||
</button>
|
||||
|
||||
{receipt ? (
|
||||
<dl className="mt-4 grid gap-2 font-mono text-[11px] text-muted-foreground sm:grid-cols-2">
|
||||
<div>
|
||||
<dt className="uppercase tracking-[0.16em]">document</dt>
|
||||
<dd className="break-all">{receipt.document_id}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="uppercase tracking-[0.16em]">version</dt>
|
||||
<dd className="break-all">{receipt.version_id}</dd>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<dt className="uppercase tracking-[0.16em]">sha-256</dt>
|
||||
<dd className="break-all">{receipt.checksum_sha256}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
) : null}
|
||||
{uploadNote ? <p className="mt-4 text-[14px] text-muted-foreground">{uploadNote}</p> : null}
|
||||
{unknownOutcome ? (
|
||||
<pre className="mt-3 overflow-auto border border-border bg-muted/30 p-3 font-mono text-[11px]">
|
||||
{JSON.stringify(unknownOutcome, null, 2)}
|
||||
</pre>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{/* 2 · structure */}
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||||
{t({ en: '2 · Desired structure', sv: '2 · Önskad struktur' })}
|
||||
</h2>
|
||||
|
||||
<label className="mt-4 block">
|
||||
<span className={label}>{t({ en: 'instruction', sv: 'instruktion' })}</span>
|
||||
<textarea
|
||||
className={`${input} min-h-[96px]`}
|
||||
value={instruction}
|
||||
maxLength={4000}
|
||||
onChange={(event) => setInstruction(event.target.value)}
|
||||
placeholder={t({
|
||||
en: 'One row per agreement with parties, term, price and notice period.',
|
||||
sv: 'En rad per avtal med parter, avtalstid, pris och uppsägningstid.',
|
||||
})}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="mt-4">
|
||||
<span className={label}>{t({ en: 'fields', sv: 'fält' })}</span>
|
||||
<div className="mt-2 space-y-2">
|
||||
{fields.map((field, index) => (
|
||||
<div key={index} className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
className="min-w-[160px] flex-1 border border-border bg-background px-3 py-2 font-mono text-[12px]"
|
||||
value={field.name}
|
||||
onChange={(event) => updateField(index, { name: event.target.value })}
|
||||
aria-label={`field ${index + 1}`}
|
||||
/>
|
||||
<select
|
||||
className="border border-border bg-background px-3 py-2 font-mono text-[12px]"
|
||||
value={field.type}
|
||||
onChange={(event) => updateField(index, { type: event.target.value as FieldRow['type'] })}
|
||||
>
|
||||
{TYPES.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeField(index)}
|
||||
className="px-2 font-mono text-[11px] text-muted-foreground"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addField}
|
||||
className="mt-2 font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground"
|
||||
>
|
||||
+ {t({ en: 'add field', sv: 'lägg till fält' })}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 sm:grid-cols-2">
|
||||
<label className="block">
|
||||
<span className={label}>{t({ en: 'model', sv: 'modell' })}</span>
|
||||
<select
|
||||
className={input}
|
||||
value={modelId}
|
||||
onChange={(event) => setModelId(event.target.value)}
|
||||
disabled={!models}
|
||||
>
|
||||
{models?.models.map((model) => (
|
||||
<option key={model} value={model}>
|
||||
{model}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className={label}>{t({ en: 'format', sv: 'format' })}</span>
|
||||
<select
|
||||
className={input}
|
||||
value={format}
|
||||
onChange={(event) => setFormat(event.target.value as 'json' | 'csv')}
|
||||
>
|
||||
<option value="json">JSON</option>
|
||||
<option value="csv">CSV</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className={label}>{t({ en: 'data class', sv: 'dataklass' })}</span>
|
||||
<select
|
||||
className={input}
|
||||
value={dataClass}
|
||||
onChange={(event) => setDataClass(event.target.value)}
|
||||
disabled={!models}
|
||||
>
|
||||
{(models?.data_classes ?? [dataClass]).map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{value}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<p className="mt-2 font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">
|
||||
{t({
|
||||
en: 'External models are refused for high/restricted data.',
|
||||
sv: 'Externa modeller nekas för hög/restricted data.',
|
||||
})}
|
||||
</p>
|
||||
|
||||
{modelsError ? <p className="mt-3 text-[13px] text-muted-foreground">{modelsError}</p> : null}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={structure}
|
||||
disabled={!receipt || structuring}
|
||||
className="mt-4 border border-foreground bg-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em] text-background disabled:opacity-40"
|
||||
>
|
||||
{structuring
|
||||
? t({ en: 'structuring…', sv: 'strukturerar…' })
|
||||
: t({ en: 'structure', sv: 'strukturera' })}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
{/* 3 · result */}
|
||||
{(result || error) && (
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||||
{t({ en: '3 · Result', sv: '3 · Resultat' })}
|
||||
</h2>
|
||||
{error ? <p className="mt-4 text-[14px]">{error}</p> : null}
|
||||
|
||||
{result?.status === 'mechanically_validated' ? (
|
||||
<>
|
||||
<div className="mt-4 overflow-auto border border-border">
|
||||
<table className="w-full border-collapse text-left font-mono text-[12px]">
|
||||
<tbody>
|
||||
{Object.entries(result.value ?? {}).map(([key, value]) => (
|
||||
<tr key={key} className="border-b border-border last:border-b-0">
|
||||
<th className="px-3 py-2 font-normal uppercase tracking-[0.14em] text-muted-foreground">
|
||||
{key}
|
||||
</th>
|
||||
<td className="px-3 py-2">{String(value)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p className="mt-3 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
|
||||
{result.evidence?.length ?? 0} {t({ en: 'evidence spans', sv: 'evidensspann' })}
|
||||
{result.credits ? ` · ${result.credits.charged} credits` : ''}
|
||||
</p>
|
||||
{result.export ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={download}
|
||||
className="mt-4 border border-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em]"
|
||||
>
|
||||
{t({ en: 'download', sv: 'ladda ner' })} {format.toUpperCase()}
|
||||
</button>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{result?.status === 'needs_review' ? (
|
||||
<div className="mt-4">
|
||||
<p className="text-[14px]">
|
||||
{t({
|
||||
en: 'The model output did not pass evidence validation. Nothing was exported.',
|
||||
sv: 'Modellens svar klarade inte evidenskontrollen. Inget exporterades.',
|
||||
})}
|
||||
</p>
|
||||
<ul className="mt-3 space-y-1 font-mono text-[11px] text-muted-foreground">
|
||||
{result.issues?.map((issue, index) => (
|
||||
<li key={index}>
|
||||
{issue.field || '(root)'} · {issue.code}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{result?.status === 'outcome_unknown' ? (
|
||||
<p className="mt-4 text-[14px]">{result.message}</p>
|
||||
) : null}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</PortalShell>
|
||||
);
|
||||
}
|
||||
+175
-5
@@ -1,10 +1,180 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
import { PortalShell } from "@/components/portal-shell";
|
||||
import { LoadingSkeleton, EmptyState, ErrorState } from "@/components/states";
|
||||
import { formatSEK } from "@/lib/data";
|
||||
|
||||
/**
|
||||
* The old `/portal/files` page only sent metadata and always hit the 501
|
||||
* storage stub. Real uploads now live at `/portal/dokument`; keep the old URL
|
||||
* working instead of leaving a second, non-functional upload surface.
|
||||
* /portal/files — kundens filer. En kvadratisk mono drag-drop-zon + fillista.
|
||||
* Vid släpp: POST /api/uploads { name, mime, bytes }. Om lagring inte är kopplad
|
||||
* svarar endpointen 501 → lugn not "aktiveras vid lagring", aldrig en feltoast.
|
||||
* Uppladdade filer matar matchning & berikning.
|
||||
*/
|
||||
|
||||
interface FileRow {
|
||||
file_id: string;
|
||||
name: string;
|
||||
mime: string;
|
||||
bytes: number;
|
||||
status: string; // received · matching · enriched
|
||||
uploaded_at: string;
|
||||
}
|
||||
|
||||
const PROV_BY_STATUS: Record<string, string> = {
|
||||
enriched: "var(--prov-3)",
|
||||
matching: "var(--prov-2)",
|
||||
received: "var(--prov-1)",
|
||||
};
|
||||
|
||||
function fmtBytes(b: number): string {
|
||||
if (b < 1024) return `${b} B`;
|
||||
if (b < 1024 * 1024) return `${(b / 1024).toFixed(0)} kB`;
|
||||
return `${(b / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export default function FilesPage() {
|
||||
redirect('/portal/dokument');
|
||||
const t = useT();
|
||||
const [files, setFiles] = useState<FileRow[] | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [storageOff, setStorageOff] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError(false);
|
||||
try {
|
||||
const r = await fetch("/api/uploads", { cache: "no-store" });
|
||||
if (r.status === 501) { setStorageOff(true); setFiles([]); return; }
|
||||
setFiles(await r.json());
|
||||
} catch {
|
||||
setError(true);
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
|
||||
const upload = useCallback(async (list: FileList | File[]) => {
|
||||
const arr = Array.from(list);
|
||||
if (arr.length === 0 || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
for (const f of arr) {
|
||||
const r = await fetch("/api/uploads", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: f.name, mime: f.type || "application/octet-stream", bytes: f.size }),
|
||||
});
|
||||
// Env-guarded: storage not wired yet → calm note, no error.
|
||||
if (r.status === 501) { setStorageOff(true); break; }
|
||||
}
|
||||
} catch {
|
||||
// Network hiccup degrades to the storage note, never a hard error toast.
|
||||
setStorageOff(true);
|
||||
}
|
||||
setBusy(false);
|
||||
void load();
|
||||
}, [busy, load]);
|
||||
|
||||
function onDrop(e: React.DragEvent) {
|
||||
e.preventDefault();
|
||||
setDragging(false);
|
||||
if (e.dataTransfer?.files?.length) void upload(e.dataTransfer.files);
|
||||
}
|
||||
|
||||
function openPicker() { inputRef.current?.click(); }
|
||||
|
||||
return (
|
||||
<PortalShell variant="customer" title={t({ en: "Files", sv: "Filer" })}>
|
||||
{/* dropzone */}
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={t({ en: "Drop files to upload", sv: "Släpp filer för att ladda upp" })}
|
||||
onClick={openPicker}
|
||||
onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openPicker(); } }}
|
||||
onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={onDrop}
|
||||
className="relative flex aspect-[3/1] w-full cursor-pointer flex-col items-center justify-center border border-dashed bg-background text-center transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
style={{
|
||||
borderColor: dragging ? "var(--accent-red)" : "var(--border)",
|
||||
backgroundColor: dragging ? "color-mix(in srgb, var(--accent-red) 4%, var(--background))" : undefined,
|
||||
}}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="mb-5 inline-block h-3.5 w-3.5"
|
||||
style={{ backgroundColor: dragging ? "var(--accent-red)" : "var(--foreground)" }}
|
||||
/>
|
||||
<p className="font-mono text-[10px] uppercase tracking-[0.22em] text-muted-foreground">
|
||||
{busy
|
||||
? t({ en: "uploading…", sv: "laddar upp…" })
|
||||
: dragging
|
||||
? t({ en: "drop here", sv: "släpp här" })
|
||||
: t({ en: "drag here · or click", sv: "dra hit · eller klicka" })}
|
||||
</p>
|
||||
<p className="mt-3 max-w-sm text-pretty text-[15px] leading-relaxed text-muted-foreground">
|
||||
{t({ en: "CSV, Excel, lists.", sv: "CSV, Excel, listor." })}
|
||||
<br />{t({ en: "Fed straight into matching & enrichment.", sv: "Matas in i matchning & berikning." })}
|
||||
</p>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="sr-only"
|
||||
onChange={(e) => { if (e.target.files) void upload(e.target.files); e.target.value = ""; }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{storageOff ? (
|
||||
<div className="mt-4 flex items-center gap-3 border border-border bg-secondary/40 px-4 py-3">
|
||||
<span aria-hidden className="inline-block h-2 w-2 shrink-0" style={{ backgroundColor: "var(--muted-foreground)" }} />
|
||||
<p className="font-mono text-[11px] leading-relaxed tracking-tight text-muted-foreground">
|
||||
{t({ en: "File upload activates once storage is connected.", sv: "Filuppladdning aktiveras när lagring kopplas." })}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* file list */}
|
||||
<div className="mt-8">
|
||||
{error ? (
|
||||
<ErrorState onRetry={load} />
|
||||
) : !files ? (
|
||||
<LoadingSkeleton rows={4} />
|
||||
) : files.length === 0 ? (
|
||||
<EmptyState
|
||||
title={t({ en: "No files yet.", sv: "Inga filer än." })}
|
||||
line={t({ en: "Drag in a list. It feeds straight into matching and enrichment.", sv: "Dra in en lista. Den matas direkt in i matchning och berikning." })}
|
||||
/>
|
||||
) : (
|
||||
<div className="border border-border">
|
||||
<div className="grid grid-cols-[2fr_1fr_1fr_1fr] border-b border-border bg-secondary/50 px-4 py-2.5 font-mono text-[10px] uppercase tracking-[0.1em] text-muted-foreground">
|
||||
<span>{t({ en: "File", sv: "Fil" })}</span><span>{t({ en: "Type", sv: "Typ" })}</span><span>{t({ en: "Size", sv: "Storlek" })}</span><span>{t({ en: "Status", sv: "Status" })}</span>
|
||||
</div>
|
||||
{files.map((f) => (
|
||||
<div key={f.file_id} className="grid grid-cols-[2fr_1fr_1fr_1fr] items-center border-b border-border px-4 py-3 text-sm transition-colors duration-200 last:border-b-0 hover:bg-secondary">
|
||||
<span className="truncate text-[15px] tracking-tight">{f.name}</span>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground">{f.mime.split("/").pop()}</span>
|
||||
<span className="font-mono text-[12px] tabular-nums text-muted-foreground">{fmtBytes(f.bytes)}</span>
|
||||
<span className="inline-flex items-center gap-2 font-mono text-[10.5px] uppercase tracking-[0.08em]">
|
||||
<span
|
||||
aria-hidden
|
||||
className="inline-block h-2 w-2 shrink-0"
|
||||
style={{ backgroundColor: PROV_BY_STATUS[f.status] ?? "var(--prov-0)" }}
|
||||
/>
|
||||
{f.status}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="mt-6 font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">
|
||||
{t({ en: "Uploads are deduplicated against your file · no cost until you order", sv: "Uppladdat dedupliceras mot din fil · ingen kostnad förrän du beställer" })}{files && files.length ? ` · ${formatSEK(0)} ${t({ en: "so far", sv: "hittills" })}` : ""}
|
||||
</p>
|
||||
</PortalShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useT } from '@/components/locale-provider';
|
||||
import { PortalShell } from '@/components/portal-shell';
|
||||
import { formatSEK } from '@/lib/data';
|
||||
|
||||
type Pack = { id: string; credits: number; amount_minor: number };
|
||||
|
||||
export default function CreditsPage() {
|
||||
const t = useT();
|
||||
const [balance, setBalance] = useState<{ available: number; reserved: number } | null>(null);
|
||||
const [balanceNote, setBalanceNote] = useState<string | null>(null);
|
||||
const [packs, setPacks] = useState<Pack[]>([]);
|
||||
const [currency, setCurrency] = useState('SEK');
|
||||
const [packsNote, setPacksNote] = useState<string | null>(null);
|
||||
const [buying, setBuying] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const r = await fetch('/api/0pt/credits/balance', { cache: 'no-store' });
|
||||
const body = (await r.json()) as { available?: number; reserved?: number; message?: string };
|
||||
if (r.ok) setBalance({ available: body.available ?? 0, reserved: body.reserved ?? 0 });
|
||||
else
|
||||
setBalanceNote(
|
||||
body.message ?? t({ en: 'Credits are not available', sv: 'Krediter är inte tillgängliga' }),
|
||||
);
|
||||
} catch {
|
||||
setBalanceNote(t({ en: 'Could not read the balance', sv: 'Kunde inte läsa saldot' }));
|
||||
}
|
||||
try {
|
||||
const r = await fetch('/api/0pt/credits/packs', { cache: 'no-store' });
|
||||
const body = (await r.json()) as { packs?: Pack[]; currency?: string; message?: string };
|
||||
if (r.ok && body.packs) {
|
||||
setPacks(body.packs);
|
||||
setCurrency(body.currency ?? 'SEK');
|
||||
} else {
|
||||
setPacksNote(
|
||||
body.message ??
|
||||
t({ en: 'Credit packs are not configured', sv: 'Kreditpaket är inte konfigurerade' }),
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
setPacksNote(t({ en: 'Could not read credit packs', sv: 'Kunde inte läsa kreditpaket' }));
|
||||
}
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const state = params.get('status');
|
||||
if (state === 'success') {
|
||||
setStatus(
|
||||
t({
|
||||
en: 'Payment received. Credits are added when Stripe confirms the payment.',
|
||||
sv: 'Betalning mottagen. Krediter läggs till när Stripe bekräftar betalningen.',
|
||||
}),
|
||||
);
|
||||
} else if (state === 'cancelled') {
|
||||
setStatus(t({ en: 'Checkout cancelled.', sv: 'Betalningen avbröts.' }));
|
||||
}
|
||||
}, [load, t]);
|
||||
|
||||
const buy = useCallback(
|
||||
async (packId: string) => {
|
||||
setBuying(packId);
|
||||
setStatus(null);
|
||||
try {
|
||||
const response = await fetch('/api/0pt/credits/checkout', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ pack_id: packId }),
|
||||
});
|
||||
const body = (await response.json().catch(() => ({}))) as { checkout_url?: string; message?: string };
|
||||
if (response.ok && body.checkout_url) {
|
||||
window.location.href = body.checkout_url;
|
||||
return;
|
||||
}
|
||||
setStatus(
|
||||
body.message ?? t({ en: 'Checkout is not available', sv: 'Betalning är inte tillgänglig' }),
|
||||
);
|
||||
} catch {
|
||||
setStatus(t({ en: 'Checkout is not available', sv: 'Betalning är inte tillgänglig' }));
|
||||
} finally {
|
||||
setBuying(null);
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
const card = 'border border-border bg-background p-6';
|
||||
|
||||
return (
|
||||
<PortalShell variant="customer" title={t({ en: 'Credits', sv: 'Krediter' })}>
|
||||
<div className="mx-auto w-full max-w-3xl space-y-6">
|
||||
<section className={card}>
|
||||
<span className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
|
||||
{t({ en: 'balance', sv: 'saldo' })}
|
||||
</span>
|
||||
{balance ? (
|
||||
<p className="mt-3 font-mono text-3xl tracking-[-0.02em]">
|
||||
{balance.available}
|
||||
<span className="ml-2 text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
|
||||
{t({ en: 'available', sv: 'tillgängliga' })} · {balance.reserved}{' '}
|
||||
{t({ en: 'reserved', sv: 'reserverade' })}
|
||||
</span>
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-3 text-[14px] text-muted-foreground">{balanceNote ?? '…'}</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||||
{t({ en: 'Buy credits', sv: 'Köp krediter' })}
|
||||
</h2>
|
||||
{packs.length === 0 ? (
|
||||
<p className="mt-3 text-[14px] text-muted-foreground">{packsNote ?? '…'}</p>
|
||||
) : (
|
||||
<ul className="mt-4 divide-y divide-border border-y border-border">
|
||||
{packs.map((pack) => (
|
||||
<li key={pack.id} className="flex items-center justify-between gap-4 py-3">
|
||||
<div>
|
||||
<p className="font-mono text-[13px]">{pack.credits} credits</p>
|
||||
<p className="font-mono text-[11px] text-muted-foreground">
|
||||
{formatSEK(pack.amount_minor / 100)}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => buy(pack.id)}
|
||||
disabled={buying !== null}
|
||||
className="border border-foreground px-4 py-2 font-mono text-[11px] uppercase tracking-[0.18em] disabled:opacity-40"
|
||||
>
|
||||
{buying === pack.id ? t({ en: 'opening…', sv: 'öppnar…' }) : t({ en: 'buy', sv: 'köp' })}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{status ? <p className="mt-4 text-[14px] text-muted-foreground">{status}</p> : null}
|
||||
<p className="mt-4 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
|
||||
{currency}
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</PortalShell>
|
||||
);
|
||||
}
|
||||
+2
-3
@@ -36,8 +36,7 @@ const STATUS_LABEL: Record<string, { en: string; sv: string }> = {
|
||||
const NAV: { label: { en: string; sv: string }; href: string }[] = [
|
||||
{ label: { en: "Overview", sv: "Översikt" }, href: "/portal" },
|
||||
{ label: { en: "Subscriptions", sv: "Prenumerationer" }, href: "/portal/subscriptions" },
|
||||
{ label: { en: "Documents", sv: "Dokument" }, href: "/portal/dokument" },
|
||||
{ label: { en: "Credits", sv: "Krediter" }, href: "/portal/krediter" },
|
||||
{ label: { en: "Files", sv: "Filer" }, href: "/portal/files" },
|
||||
{ label: { en: "Integrations", sv: "Integrationer" }, href: "/portal/integrationer" },
|
||||
{ label: { en: "Settings", sv: "Inställningar" }, href: "/portal/settings" },
|
||||
{ label: { en: "Admin", sv: "Admin" }, href: "/admin" },
|
||||
@@ -287,7 +286,7 @@ function CopyId({ id }: { id: string }) {
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
});
|
||||
}}
|
||||
className="text-muted-foreground transition-colors hover:text-foreground"
|
||||
className="text-foreground/20 transition-colors hover:text-foreground/60"
|
||||
>
|
||||
{copied ? "✓" : "⧉"}
|
||||
</button>
|
||||
|
||||
@@ -40,7 +40,7 @@ export default function ServicesPage() {
|
||||
<section key={flow} className="mt-16">
|
||||
<div className="flex items-baseline justify-between border-b border-border pb-4">
|
||||
<h2 className="font-mono text-[11px] uppercase tracking-[0.16em] text-muted-foreground">{t(FLOW_LABEL[flow])}</h2>
|
||||
<span className="font-mono text-[11px] tabular-nums text-muted-foreground">{String(items.length).padStart(2, "0")}</span>
|
||||
<span className="font-mono text-[11px] tabular-nums text-muted-foreground/60">{String(items.length).padStart(2, "0")}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-px border border-border bg-border md:grid-cols-2 lg:grid-cols-3">
|
||||
{items.map((s, i) => {
|
||||
@@ -50,7 +50,7 @@ export default function ServicesPage() {
|
||||
<h3 className="text-lg font-semibold tracking-[-0.01em]">{t(s.name)}</h3>
|
||||
<p className="mt-1 font-mono text-[11px] uppercase tracking-[0.06em] text-muted-foreground">{t(s.tagline)}</p>
|
||||
<p className="mt-4 flex-1 text-sm text-muted-foreground">{t(s.covers)}</p>
|
||||
<p className="mt-4 font-mono text-[10.5px] uppercase tracking-[0.08em] text-muted-foreground">→ {t(s.deliverable)}</p>
|
||||
<p className="mt-4 font-mono text-[10.5px] uppercase tracking-[0.08em] text-muted-foreground/70">→ {t(s.deliverable)}</p>
|
||||
<Link href={cta.href} className="mt-5 inline-flex items-center gap-2 font-mono text-[11px] uppercase tracking-[0.1em] underline-offset-4 hover:underline">
|
||||
{t(cta.label)}
|
||||
<span aria-hidden className="transition-transform duration-300 group-hover:translate-x-1">→</span>
|
||||
|
||||
@@ -123,7 +123,7 @@ export function Header() {
|
||||
className="flex items-baseline justify-between border-b border-border py-4 font-mono text-[12px] uppercase tracking-[0.12em] text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<span>{t(n.label)}</span>
|
||||
<span className="text-[10px] tabular-nums text-muted-foreground">{String(i + 1).padStart(2, "0")}</span>
|
||||
<span className="text-[10px] tabular-nums text-muted-foreground/50">{String(i + 1).padStart(2, "0")}</span>
|
||||
</Link>
|
||||
))}
|
||||
<div className="flex items-center justify-between py-4">
|
||||
|
||||
+37
-52
@@ -1,27 +1,26 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useT } from '@/components/locale-provider';
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
|
||||
export type NavItem = { label: { en: string; sv: string }; href: string };
|
||||
|
||||
const CUSTOMER_NAV: NavItem[] = [
|
||||
{ label: { en: 'Overview', sv: 'Översikt' }, href: '/portal' },
|
||||
{ label: { en: 'Subscriptions', sv: 'Prenumerationer' }, href: '/portal/subscriptions' },
|
||||
{ label: { en: 'Documents', sv: 'Dokument' }, href: '/portal/dokument' },
|
||||
{ label: { en: 'Credits', sv: 'Krediter' }, href: '/portal/krediter' },
|
||||
{ label: { en: 'Integrations', sv: 'Integrationer' }, href: '/portal/integrationer' },
|
||||
{ label: { en: 'Settings', sv: 'Inställningar' }, href: '/portal/settings' },
|
||||
{ label: { en: "Overview", sv: "Översikt" }, href: "/portal" },
|
||||
{ label: { en: "Subscriptions", sv: "Prenumerationer" }, href: "/portal/subscriptions" },
|
||||
{ label: { en: "Files", sv: "Filer" }, href: "/portal/files" },
|
||||
{ label: { en: "Integrations", sv: "Integrationer" }, href: "/portal/integrationer" },
|
||||
{ label: { en: "Settings", sv: "Inställningar" }, href: "/portal/settings" },
|
||||
];
|
||||
|
||||
const ADMIN_NAV: NavItem[] = [
|
||||
{ label: { en: 'Overview', sv: 'Översikt' }, href: '/admin' },
|
||||
{ label: { en: 'Sources', sv: 'Källor' }, href: '/admin/sources' },
|
||||
{ label: { en: 'Jobs', sv: 'Jobb' }, href: '/admin/jobs' },
|
||||
{ label: { en: 'Tools', sv: 'Verktyg' }, href: '/admin/verktyg' },
|
||||
{ label: { en: 'Customers', sv: 'Kunder' }, href: '/admin/customers' },
|
||||
{ label: { en: "Overview", sv: "Översikt" }, href: "/admin" },
|
||||
{ label: { en: "Sources", sv: "Källor" }, href: "/admin/sources" },
|
||||
{ label: { en: "Jobs", sv: "Jobb" }, href: "/admin/jobs" },
|
||||
{ label: { en: "Tools", sv: "Verktyg" }, href: "/admin/verktyg" },
|
||||
{ label: { en: "Customers", sv: "Kunder" }, href: "/admin/customers" },
|
||||
];
|
||||
|
||||
export function PortalShell({
|
||||
@@ -29,24 +28,24 @@ export function PortalShell({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
variant: 'customer' | 'admin';
|
||||
variant: "customer" | "admin";
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const t = useT();
|
||||
const pathname = usePathname();
|
||||
const nav = variant === 'admin' ? ADMIN_NAV : CUSTOMER_NAV;
|
||||
const nav = variant === "admin" ? ADMIN_NAV : CUSTOMER_NAV;
|
||||
const [email, setEmail] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/auth/me')
|
||||
fetch("/api/auth/me")
|
||||
.then((r) => r.json())
|
||||
.then((d) => setEmail(d?.user?.email ?? null))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
async function logout() {
|
||||
await fetch('/api/auth/logout', { method: 'POST' }).catch(() => {});
|
||||
await fetch("/api/auth/logout", { method: "POST" }).catch(() => {});
|
||||
setEmail(null);
|
||||
}
|
||||
|
||||
@@ -56,29 +55,23 @@ export function PortalShell({
|
||||
<div className="sticky top-0 z-40 flex h-16 items-center justify-between border-b border-border bg-background px-6">
|
||||
<Link href="/" className="flex items-center gap-2">
|
||||
<span className="text-lg font-semibold tracking-[-0.04em]">0pt</span>
|
||||
<span className="inline-block h-1 w-1" style={{ backgroundColor: 'var(--accent-red)' }} />
|
||||
<span className="inline-block h-1 w-1" style={{ backgroundColor: "var(--accent-red)" }} />
|
||||
<span className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
|
||||
{variant === 'admin' ? 'admin' : 'portal'}
|
||||
{variant === "admin" ? "admin" : "portal"}
|
||||
</span>
|
||||
</Link>
|
||||
<div className="flex items-center gap-4">
|
||||
{email ? (
|
||||
<>
|
||||
<span className="font-mono text-[11px] text-muted-foreground">{email}</span>
|
||||
<button
|
||||
onClick={logout}
|
||||
className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t({ en: 'Log out', sv: 'Logga ut' })}
|
||||
<button onClick={logout} className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground">
|
||||
{t({ en: "Log out", sv: "Logga ut" })}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<a
|
||||
href="/api/auth/login?next=/portal/dokument"
|
||||
className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t({ en: 'Log in', sv: 'Logga in' })}
|
||||
</a>
|
||||
<Link href="/portal/settings" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground">
|
||||
{t({ en: "Log in", sv: "Logga in" })}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -93,30 +86,24 @@ export function PortalShell({
|
||||
<Link
|
||||
key={n.href}
|
||||
href={n.href}
|
||||
aria-current={active ? 'page' : undefined}
|
||||
aria-current={active ? "page" : undefined}
|
||||
className="border-l-2 px-4 py-2.5 font-mono text-[11px] uppercase tracking-[0.1em] transition-colors"
|
||||
style={{
|
||||
borderColor: active ? 'var(--accent-red)' : 'transparent',
|
||||
color: active ? 'var(--foreground)' : 'var(--muted-foreground)',
|
||||
borderColor: active ? "var(--accent-red)" : "transparent",
|
||||
color: active ? "var(--foreground)" : "var(--muted-foreground)",
|
||||
}}
|
||||
>
|
||||
{t(n.label)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
{variant === 'customer' ? (
|
||||
<Link
|
||||
href="/bestall"
|
||||
className="mt-2 bg-foreground px-4 py-2.5 text-center font-mono text-[11px] uppercase tracking-[0.1em] text-background hover:bg-[var(--accent-red)]"
|
||||
>
|
||||
{t({ en: 'New order', sv: 'Ny beställning' })}
|
||||
{variant === "customer" ? (
|
||||
<Link href="/bestall" className="mt-2 bg-foreground px-4 py-2.5 text-center font-mono text-[11px] uppercase tracking-[0.1em] text-background hover:bg-[var(--accent-red)]">
|
||||
{t({ en: "New order", sv: "Ny beställning" })}
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
href="/portal"
|
||||
className="mt-2 border border-border px-4 py-2.5 text-center font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t({ en: '← Customer view', sv: '← Kundvy' })}
|
||||
<Link href="/portal" className="mt-2 border border-border px-4 py-2.5 text-center font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground">
|
||||
{t({ en: "← Customer view", sv: "← Kundvy" })}
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
@@ -134,11 +121,9 @@ export function PortalShell({
|
||||
|
||||
export function StatusPill({ status }: { status: string }) {
|
||||
const color =
|
||||
status === 'delivered' || status === 'accepted'
|
||||
? 'var(--prov-3)'
|
||||
: status === 'in_production' || status === 'review'
|
||||
? 'var(--accent-red)'
|
||||
: 'var(--muted-foreground)';
|
||||
status === "delivered" || status === "accepted" ? "var(--prov-3)"
|
||||
: status === "in_production" || status === "review" ? "var(--accent-red)"
|
||||
: "var(--muted-foreground)";
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 font-mono text-[10.5px] uppercase tracking-[0.08em]">
|
||||
<span className="inline-block h-2 w-2" style={{ backgroundColor: color }} />
|
||||
|
||||
@@ -44,7 +44,7 @@ export function CollectionSection() {
|
||||
>
|
||||
<div className="flex items-baseline justify-between">
|
||||
<p className="font-mono text-sm font-semibold tracking-tight">{m.code}</p>
|
||||
<span className="font-mono text-[9px] text-muted-foreground">{String(i + 1).padStart(2, "0")}</span>
|
||||
<span className="font-mono text-[9px] text-muted-foreground/60">{String(i + 1).padStart(2, "0")}</span>
|
||||
</div>
|
||||
<p className="mt-1 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">
|
||||
{m.live ? `${m.coverage}%` : t({ en: "coming", sv: "kommande" })}
|
||||
|
||||
@@ -91,7 +91,7 @@ export function FeaturedProductsSection() {
|
||||
<span className="absolute left-0 top-0 h-px w-0 transition-all duration-300 group-hover:w-full" style={{ backgroundColor: "var(--accent-red)" }} />
|
||||
<div className="flex items-baseline justify-between">
|
||||
<p className="font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">{d.markets}</p>
|
||||
<span className="font-mono text-[10px] tabular-nums text-muted-foreground">{String(i + 1).padStart(2, "0")}</span>
|
||||
<span className="font-mono text-[10px] tabular-nums text-foreground/20">{String(i + 1).padStart(2, "0")}</span>
|
||||
</div>
|
||||
<h3 className="mt-5 text-xl font-semibold tracking-[-0.01em] transition-transform duration-300 group-hover:translate-x-1">{t(d.title)}</h3>
|
||||
<p className="mt-2 text-sm text-muted-foreground">{t(d.desc)}</p>
|
||||
|
||||
@@ -33,7 +33,7 @@ export function PhilosophySection() {
|
||||
className={`reveal delay-${i + 1} group relative grid grid-cols-[3.5rem_1fr] items-baseline gap-8 border-b border-border py-8 transition-[padding] duration-300 ease-out hover:pl-2`}
|
||||
>
|
||||
<span className="absolute -left-2 top-0 h-px w-0 bg-foreground transition-all duration-500 ease-out group-hover:w-full group-hover:opacity-100" aria-hidden />
|
||||
<span className="font-mono text-[clamp(1.5rem,2vw,2.25rem)] font-medium leading-none tracking-[-0.02em] text-muted-foreground transition-colors duration-300 group-hover:text-foreground">
|
||||
<span className="font-mono text-[clamp(1.5rem,2vw,2.25rem)] font-medium leading-none tracking-[-0.02em] text-muted-foreground/40 transition-colors duration-300 group-hover:text-foreground">
|
||||
{n}
|
||||
</span>
|
||||
<div>
|
||||
|
||||
@@ -64,7 +64,7 @@ export function PricingSection() {
|
||||
{MODELS.map((m, i) => (
|
||||
<div key={m.index} className={`reveal delay-${i + 1} group relative flex flex-col bg-background p-8`}>
|
||||
<div className="flex items-start justify-between">
|
||||
<span className="font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground">{m.index}</span>
|
||||
<span className="font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground/60">{m.index}</span>
|
||||
{m.featured ? <span className="mt-1 inline-block h-2 w-2" style={{ backgroundColor: "var(--accent-red)" }} /> : null}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ export function TestimonialsSection() {
|
||||
key={l.sv}
|
||||
className={`reveal delay-${i + 2} group relative border-b border-border py-12 sm:border-b-0 sm:border-l sm:py-0 sm:pl-8 sm:pr-4 ${i === 0 ? "sm:border-l-0 sm:pl-0" : ""}`}
|
||||
>
|
||||
<p className="font-mono text-[11px] tabular-nums text-muted-foreground">0{i + 1}</p>
|
||||
<p className="font-mono text-[11px] tabular-nums text-muted-foreground/60">0{i + 1}</p>
|
||||
<p
|
||||
className="mt-3 text-[clamp(3.2rem,8vw,6rem)] font-semibold leading-[0.9] tracking-[-0.04em] transition-transform duration-300 group-hover:-translate-y-0.5"
|
||||
style={{ color: red ? "var(--accent-red)" : "var(--foreground)" }}
|
||||
|
||||
@@ -46,7 +46,7 @@ export function LoadingSkeleton({ rows = 5 }: { rows?: number }) {
|
||||
))}
|
||||
<span className="sr-only">{t({ en: "Loading content", sv: "Laddar innehåll" })}</span>
|
||||
|
||||
<style>{`
|
||||
<style jsx>{`
|
||||
.opt-shimmer {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import * as RechartsPrimitive from 'recharts'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||
const THEMES = { light: '', dark: '.dark' } as const
|
||||
|
||||
export type ChartConfig = {
|
||||
[k in string]: {
|
||||
label?: React.ReactNode
|
||||
icon?: React.ComponentType
|
||||
} & (
|
||||
| { color?: string; theme?: never }
|
||||
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
||||
)
|
||||
}
|
||||
|
||||
type ChartContextProps = {
|
||||
config: ChartConfig
|
||||
}
|
||||
|
||||
const ChartContext = React.createContext<ChartContextProps | null>(null)
|
||||
|
||||
function useChart() {
|
||||
const context = React.useContext(ChartContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useChart must be used within a <ChartContainer />')
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function ChartContainer({
|
||||
id,
|
||||
className,
|
||||
children,
|
||||
config,
|
||||
...props
|
||||
}: React.ComponentProps<'div'> & {
|
||||
config: ChartConfig
|
||||
children: React.ComponentProps<
|
||||
typeof RechartsPrimitive.ResponsiveContainer
|
||||
>['children']
|
||||
}) {
|
||||
const uniqueId = React.useId()
|
||||
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`
|
||||
|
||||
return (
|
||||
<ChartContext.Provider value={{ config }}>
|
||||
<div
|
||||
data-slot="chart"
|
||||
data-chart={chartId}
|
||||
className={cn(
|
||||
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChartStyle id={chartId} config={config} />
|
||||
<RechartsPrimitive.ResponsiveContainer>
|
||||
{children}
|
||||
</RechartsPrimitive.ResponsiveContainer>
|
||||
</div>
|
||||
</ChartContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||
const colorConfig = Object.entries(config).filter(
|
||||
([, config]) => config.theme || config.color,
|
||||
)
|
||||
|
||||
if (!colorConfig.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<style
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: Object.entries(THEMES)
|
||||
.map(
|
||||
([theme, prefix]) => `
|
||||
${prefix} [data-chart=${id}] {
|
||||
${colorConfig
|
||||
.map(([key, itemConfig]) => {
|
||||
const color =
|
||||
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
|
||||
itemConfig.color
|
||||
return color ? ` --color-${key}: ${color};` : null
|
||||
})
|
||||
.join('\n')}
|
||||
}
|
||||
`,
|
||||
)
|
||||
.join('\n'),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartTooltip = RechartsPrimitive.Tooltip
|
||||
|
||||
function ChartTooltipContent({
|
||||
active,
|
||||
payload,
|
||||
className,
|
||||
indicator = 'dot',
|
||||
hideLabel = false,
|
||||
hideIndicator = false,
|
||||
label,
|
||||
labelFormatter,
|
||||
labelClassName,
|
||||
formatter,
|
||||
color,
|
||||
nameKey,
|
||||
labelKey,
|
||||
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
||||
React.ComponentProps<'div'> & {
|
||||
hideLabel?: boolean
|
||||
hideIndicator?: boolean
|
||||
indicator?: 'line' | 'dot' | 'dashed'
|
||||
nameKey?: string
|
||||
labelKey?: string
|
||||
}) {
|
||||
const { config } = useChart()
|
||||
|
||||
const tooltipLabel = React.useMemo(() => {
|
||||
if (hideLabel || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [item] = payload
|
||||
const key = `${labelKey || item?.dataKey || item?.name || 'value'}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const value =
|
||||
!labelKey && typeof label === 'string'
|
||||
? config[label as keyof typeof config]?.label || label
|
||||
: itemConfig?.label
|
||||
|
||||
if (labelFormatter) {
|
||||
return (
|
||||
<div className={cn('font-medium', labelClassName)}>
|
||||
{labelFormatter(value, payload)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <div className={cn('font-medium', labelClassName)}>{value}</div>
|
||||
}, [
|
||||
label,
|
||||
labelFormatter,
|
||||
payload,
|
||||
hideLabel,
|
||||
labelClassName,
|
||||
config,
|
||||
labelKey,
|
||||
])
|
||||
|
||||
if (!active || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const nestLabel = payload.length === 1 && indicator !== 'dot'
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{!nestLabel ? tooltipLabel : null}
|
||||
<div className="grid gap-1.5">
|
||||
{payload.map((item, index) => {
|
||||
const key = `${nameKey || item.name || item.dataKey || 'value'}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const indicatorColor = color || item.payload.fill || item.color
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.dataKey}
|
||||
className={cn(
|
||||
'[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5',
|
||||
indicator === 'dot' && 'items-center',
|
||||
)}
|
||||
>
|
||||
{formatter && item?.value !== undefined && item.name ? (
|
||||
formatter(item.value, item.name, item, index, item.payload)
|
||||
) : (
|
||||
<>
|
||||
{itemConfig?.icon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
!hideIndicator && (
|
||||
<div
|
||||
className={cn(
|
||||
'shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)',
|
||||
{
|
||||
'h-2.5 w-2.5': indicator === 'dot',
|
||||
'w-1': indicator === 'line',
|
||||
'w-0 border-[1.5px] border-dashed bg-transparent':
|
||||
indicator === 'dashed',
|
||||
'my-0.5': nestLabel && indicator === 'dashed',
|
||||
},
|
||||
)}
|
||||
style={
|
||||
{
|
||||
'--color-bg': indicatorColor,
|
||||
'--color-border': indicatorColor,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-1 justify-between leading-none',
|
||||
nestLabel ? 'items-end' : 'items-center',
|
||||
)}
|
||||
>
|
||||
<div className="grid gap-1.5">
|
||||
{nestLabel ? tooltipLabel : null}
|
||||
<span className="text-muted-foreground">
|
||||
{itemConfig?.label || item.name}
|
||||
</span>
|
||||
</div>
|
||||
{item.value && (
|
||||
<span className="text-foreground font-mono font-medium tabular-nums">
|
||||
{item.value.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartLegend = RechartsPrimitive.Legend
|
||||
|
||||
function ChartLegendContent({
|
||||
className,
|
||||
hideIcon = false,
|
||||
payload,
|
||||
verticalAlign = 'bottom',
|
||||
nameKey,
|
||||
}: React.ComponentProps<'div'> &
|
||||
Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & {
|
||||
hideIcon?: boolean
|
||||
nameKey?: string
|
||||
}) {
|
||||
const { config } = useChart()
|
||||
|
||||
if (!payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-center gap-4',
|
||||
verticalAlign === 'top' ? 'pb-3' : 'pt-3',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{payload.map((item) => {
|
||||
const key = `${nameKey || item.dataKey || 'value'}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.value}
|
||||
className={
|
||||
'[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3'
|
||||
}
|
||||
>
|
||||
{itemConfig?.icon && !hideIcon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
<div
|
||||
className="h-2 w-2 shrink-0 rounded-[2px]"
|
||||
style={{
|
||||
backgroundColor: item.color,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{itemConfig?.label}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to extract item config from a payload.
|
||||
function getPayloadConfigFromPayload(
|
||||
config: ChartConfig,
|
||||
payload: unknown,
|
||||
key: string,
|
||||
) {
|
||||
if (typeof payload !== 'object' || payload === null) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const payloadPayload =
|
||||
'payload' in payload &&
|
||||
typeof payload.payload === 'object' &&
|
||||
payload.payload !== null
|
||||
? payload.payload
|
||||
: undefined
|
||||
|
||||
let configLabelKey: string = key
|
||||
|
||||
if (
|
||||
key in payload &&
|
||||
typeof payload[key as keyof typeof payload] === 'string'
|
||||
) {
|
||||
configLabelKey = payload[key as keyof typeof payload] as string
|
||||
} else if (
|
||||
payloadPayload &&
|
||||
key in payloadPayload &&
|
||||
typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
|
||||
) {
|
||||
configLabelKey = payloadPayload[
|
||||
key as keyof typeof payloadPayload
|
||||
] as string
|
||||
}
|
||||
|
||||
return configLabelKey in config
|
||||
? config[configLabelKey]
|
||||
: config[key as keyof typeof config]
|
||||
}
|
||||
|
||||
export {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
ChartLegend,
|
||||
ChartLegendContent,
|
||||
ChartStyle,
|
||||
}
|
||||
@@ -77,7 +77,7 @@ const ToastClose = React.forwardRef<
|
||||
<ToastPrimitives.Close
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'absolute right-2 top-2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
|
||||
'absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
|
||||
className,
|
||||
)}
|
||||
toast-close=""
|
||||
|
||||
@@ -367,60 +367,6 @@ paths:
|
||||
$ref: "#/components/schemas/ProvenanceRecord"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
/v1/0pt/parsing/route:
|
||||
post:
|
||||
operationId: 0pt.route_parsing
|
||||
summary: >
|
||||
(TARGET) Parser-routing/selektiv OCR-beslut (BTI-DOC-02/03/04/05).
|
||||
Kontrakt-first — real kod i 0pt-motor/motor/parsing/routing.py
|
||||
(route_parser m.fl.), INTEGRATION_TESTED men ej driftsatt bakom
|
||||
denna route.
|
||||
x-siax-status: target
|
||||
security: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RouteParsingRequest"
|
||||
responses:
|
||||
"200":
|
||||
description: Routingbeslut (parser/OCR-gren) + ev. nyckeltalskonflikter mellan parsers
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RouteParsingResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
/v1/0pt/normalize:
|
||||
post:
|
||||
operationId: 0pt.normalize_value
|
||||
summary: >
|
||||
(TARGET) Lokal-medveten normalisering — belopp/skala/datum (BTI-NLP-03)
|
||||
och identifierare/checksummor (BTI-NLP-02). Kontrakt-first — real kod
|
||||
i 0pt-motor/motor/normalization/{amounts,identifiers}.py,
|
||||
INTEGRATION_TESTED men ej driftsatt bakom denna route.
|
||||
x-siax-status: target
|
||||
security: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/NormalizeValueRequest"
|
||||
responses:
|
||||
"200":
|
||||
description: Normaliserat värde — format_valid/review, aldrig en påhittad korrigering
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/NormalizeValueResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Internal service-to-service (Python-engine bridge) — P-002 internal OpenAPI.
|
||||
@@ -865,91 +811,3 @@ components:
|
||||
type: object
|
||||
additionalProperties:
|
||||
$ref: "#/components/schemas/FieldProvenance"
|
||||
RouteParsingRequest:
|
||||
type: object
|
||||
required: [digital_text_page]
|
||||
properties:
|
||||
digital_text_page:
|
||||
type: boolean
|
||||
description: True om sidan har ett digitalt textlager (ej scannad).
|
||||
ocr_available:
|
||||
type: boolean
|
||||
default: false
|
||||
parser_result:
|
||||
type: object
|
||||
description: Föregående parser-försök, om något (tom text = kandidat för OCR-gren).
|
||||
properties:
|
||||
parser:
|
||||
type: string
|
||||
text:
|
||||
type: string
|
||||
key_figures:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: number
|
||||
compare_with:
|
||||
type: object
|
||||
description: (Valfritt) ett andra parser-resultat att stämma av mot — avvikande nyckeltal blir en konflikt, aldrig en tyst ersättning.
|
||||
properties:
|
||||
parser:
|
||||
type: string
|
||||
text:
|
||||
type: string
|
||||
key_figures:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: number
|
||||
RouteParsingResponse:
|
||||
type: object
|
||||
required: [routing]
|
||||
properties:
|
||||
routing:
|
||||
type: string
|
||||
enum: [text_parser, ocr_branch, explicit_unavailable]
|
||||
conflicts:
|
||||
type: object
|
||||
description: Fält där de två parser-resultatens nyckeltal skiljer sig (present endast om compare_with skickades).
|
||||
additionalProperties: true
|
||||
NormalizeValueRequest:
|
||||
type: object
|
||||
required: [kind, value]
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum: [amount, percent, date, identifier]
|
||||
description: amount/percent/date = motor/normalization/amounts.py. identifier = motor/normalization/identifiers.py.
|
||||
value:
|
||||
type: string
|
||||
description: Rå textsträng att normalisera (belopp, procentsats, datum eller identifierare).
|
||||
locale:
|
||||
type: string
|
||||
description: (kind=amount, valfritt) comma_decimal|dot_decimal — auto-detekteras annars.
|
||||
unit:
|
||||
type: string
|
||||
description: (kind=amount|percent) t.ex. SEK/KSEK/MSEK/GSEK eller "%"/"pp".
|
||||
identifier_kind:
|
||||
type: string
|
||||
enum: [orgnr, cvr, vat, ocr]
|
||||
description: (kind=identifier, krävs) vilken identifierartyp som ska valideras.
|
||||
country:
|
||||
type: string
|
||||
description: (kind=identifier, krävs) ISO-3166 alpha-2, t.ex. SE/NO/DK.
|
||||
description: >
|
||||
Ett fält, en normalisering. amount/percent/date har alltid en explicit
|
||||
precision/skala (aldrig en påhittad dag eller sammanblandad enhet).
|
||||
identifier ger format_valid eller review — aldrig en tyst korrigerad
|
||||
checksumma; existens i register verifieras inte här.
|
||||
NormalizeValueResponse:
|
||||
type: object
|
||||
required: [kind, status]
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum: [amount, percent, date, identifier]
|
||||
status:
|
||||
type: string
|
||||
enum: [ok, format_valid, format_invalid, review, unparseable]
|
||||
result:
|
||||
type: object
|
||||
description: Normaliserat resultat, formen beror på kind (se motor/normalization/{amounts,identifiers}.py).
|
||||
additionalProperties: true
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
# P070 — VehIQ OLTP -> 0pt watermark extractor
|
||||
|
||||
Status: built, tested, verified read-only against production. **Not scheduled/activated in production.** Read "What activating this requires" before turning the workflow on.
|
||||
|
||||
## What this is
|
||||
|
||||
A controlled, incremental extractor implementing exactly the pattern Simon specified (`admin/vehiq` 2026-09-25 pass, "Locked architecture decisions from Simon" / `docs/adr/0035-bi-analytics-architecture-product-firewall.md`):
|
||||
|
||||
```
|
||||
OLTP operational tables -> read-only analytical extraction -> watermark ->
|
||||
0pt ingestion -> ClickHouse (opt_dataset_projection)
|
||||
```
|
||||
|
||||
Source: `app.dealer_stock_entry` and `app.deal` on production Postgres (`vehiq-db`, server10) — read-only `SELECT`, never a schema/config change, never touching `wal_level` or replication, never a permanent replica. Sink: `SiaxAnalyticsEngine.ingestProjection` (BI-P009, `opt_dataset_projection` in ClickHouse). Vehicle dimension: a narrow, keyed lookup against `vehiq.vehicle` (98M rows / 85GB) scoped to exactly the `vehicle_id`s referenced by the `dealer_stock_entry` batch just read — never `SELECT * FROM vehicle`, never a full scan.
|
||||
|
||||
## Why this lives in `admin/0pt`, not `admin/vehiq`
|
||||
|
||||
The task that produced this work described building it as a new package inside `admin/vehiq` (e.g. `packages/opt-ingest`). Before writing any code, this repo's own `docs/adr/0035-bi-analytics-architecture-product-firewall.md` (decisions 1, 2, 10 — decided the same day, one-way-door, CI-enforced by `tools/validate_engine_firewall.py`) was read and is unambiguous:
|
||||
|
||||
> VehIQ's own codebase must **never** get its own ClickHouse or DuckDB credentials, and must never import a ClickHouse/DuckDB client directly. ... Product code must never hammer the live OLTP Postgres with analytical queries directly.
|
||||
|
||||
And `admin/vehiq`'s `docs/CURRENT_STATE.md` ("Connection details for a future API0 connector", same pass) says explicitly:
|
||||
|
||||
> VehIQ's own codebase must never see any of this. This is 0pt's data plane; only a future `admin/api0` connector should hold these details.
|
||||
|
||||
Building the extractor inside `admin/vehiq` would have failed `validate_engine_firewall.py` the moment it imported a ClickHouse client or held a `CLICKHOUSE_*` env var, and would have been the exact "temporary VehIQ-owned data-access surface" ADR-0035 names as the failure mode it exists to prevent. So this extractor was built here instead — `admin/0pt`, 0pt's own data plane, a sibling of `admin/api0` (the mechanics belong next to the P060-P068 ingestion plane and the BI-P009/P010 ClickHouse engine that already live in this repo). **`admin/vehiq` was not modified by this work.**
|
||||
|
||||
This is a deliberate deviation from the task's literal repo suggestion, made because the suggestion conflicted with Simon's own same-day, explicit, locked architecture decision discovered while reading the target repo — not a judgment call made against that decision.
|
||||
|
||||
## Real production schema does not match the task's assumed column names
|
||||
|
||||
The task (and `admin/vehiq`'s `docs/CURRENT_STATE.md`) assumed all three OLTP tables carry a generic `updated_at` ("the columns already exist"). Verified live against production (server10, `vehiq-db`, read-only `information_schema.columns`, 2026-09-25) — **this is not true**:
|
||||
|
||||
| table | live columns | usable watermark |
|
||||
|---|---|---|
|
||||
| `app.dealer_stock_entry` | `id, tenant_id, vehicle_id, lot_location, floorplan_status, listed_at, sold_at` | `listed_at` (NOT NULL, insert-time only) |
|
||||
| `app.deal` | `id, tenant_id, party_id, vehicle_id, sale_price_minor, currency, status, created_at` | `created_at` (NOT NULL DEFAULT now(), insert-time only) |
|
||||
| `app.listing` | `id, tenant_id, vehicle_id, asking_price_minor, currency, channels, status` | **none** |
|
||||
|
||||
**`app.listing` has no timestamp column of any kind today.** `admin/vehiq` migration `0084_listing_deal_lifecycle_timestamps.sql` (already written, adds `published_at`/`unpublished_at` to `listing` and `closed_at`/`listing_id` to `deal`) exists in the repo but is **not yet applied to production** (verified: those columns are absent live). Until it lands, there is no honest way to build a watermark connector for `app.listing` — one is not built here. **This extractor covers `dealer_stock_entry` and `deal` only, not `listing`.**
|
||||
|
||||
**Caveat on the two sources that ARE built:** `listed_at`/`created_at` are set once, at INSERT. Neither table has a column that advances when an *existing* row changes (`sold_at`/`floorplan_status` on `dealer_stock_entry`; `status` on `deal`). This extractor reliably sees every new row; it does **not** see an in-place UPDATE to a row it already read, because that row has already passed the watermark. Closing this gap needs either `listing_id`/`closed_at` (migration 0084, once applied) plus an equivalent for `dealer_stock_entry`, or a generic `updated_at` + trigger — a schema decision for Simon, not something this pass made unilaterally (per the hard "never a schema/config change" rule).
|
||||
|
||||
Also found and corrected while building: `vehiq.vehicle`'s primary key column is `vehicle_id`, not `id` (verified via schema introspection only — no vehicle data rows were read to establish this).
|
||||
|
||||
## Where the code lives
|
||||
|
||||
- `src/connectors/postgres-watermark-connector.ts` — the P061 `Connector` implementing `WHERE watermark_col > $1 OR (watermark_col = $1 AND key_col > $2) ORDER BY watermark_col, key_col LIMIT $3` (the `OR` tuple form, not a bare `>`, so a same-timestamp tie at a page boundary is not silently dropped — see the file's own header for the bug this avoids). Explicit column allow-list, never `SELECT *`. `validate()` structurally refuses any config pointed at `vehiq.vehicle`.
|
||||
- `src/connectors/postgres-keyed-lookup-connector.ts` — the narrow vehicle-dimension connector. Config carries an already-resolved, finite `keys` array; `connect()` refuses an empty list rather than defaulting to a full read; every query is `WHERE vehicle_id = ANY($1)` chunked to `keys_per_query` (default 500).
|
||||
- `src/connectors/postgres-query-impl.ts` — the real `postgres` (postgres.js) implementation of the connectors' injectable `QueryImpl`, used only by the orchestration script. Refuses to execute anything whose first keyword isn't `SELECT`, independent of the DB role's own privileges.
|
||||
- `src/ingestion/projection-sink.ts` — adapts the P062 runner's `IngestionSink` onto `SiaxAnalyticsEngine.ingestProjection` (writes `opt_dataset_projection`). No ClickHouse import — only the `SiaxAnalyticsEngine` port type.
|
||||
- `src/ingestion/vehiq-oltp-ingest-runner.ts` — the orchestration: `previewVehiqOltpSource` (one bounded read-only read, never commits, safe against production at any time) and `runVehiqOltpIngestion` (the real P062-runner path).
|
||||
- `scripts/vehiq-oltp-ingest/run.ts` — thin CLI (`pnpm run vehiq:oltp-ingest`), env-driven, defaults to `preview` mode.
|
||||
- Tests: `tests/connectors/postgres-watermark-connector.test.ts`, `tests/connectors/postgres-keyed-lookup-connector.test.ts`, `tests/ingestion/vehiq-oltp-ingest-runner.test.ts`.
|
||||
|
||||
## Checkpoint field mapping
|
||||
|
||||
Simon's own specified checkpoint columns — `source, table, last_updated_at, last_id, batch_count, checksum, ingested_at` — mapped onto the **existing** P062 `IngestionCheckpoint` (reused, not duplicated, per the "no double truths" rule):
|
||||
|
||||
| Simon's field | Canonical field |
|
||||
|---|---|
|
||||
| `source` | `IngestionCheckpoint.source_id` |
|
||||
| `table` | `IngestionCheckpoint.partition_key` |
|
||||
| `last_updated_at` | decoded from `IngestionCheckpoint.cursor` (JSON `WatermarkCursor`) |
|
||||
| `last_id` | decoded from `IngestionCheckpoint.cursor` |
|
||||
| `checksum` | decoded from `IngestionCheckpoint.cursor` — sha256 of the page just landed |
|
||||
| `batch_count` | `IngestionCheckpoint.records_committed` (cumulative); a per-run page count is also in each run's `PartitionRunReport` |
|
||||
| `ingested_at` | `IngestionCheckpoint.committed_at` |
|
||||
|
||||
Durable storage: `createIngestionRepository(DATABASE_URL)` — Postgres-backed when `DATABASE_URL` (0pt's own metadata store) is set, in-memory only in non-production/tests. `run` mode refuses to start without `DATABASE_URL` explicitly, so a scheduled run can never silently fall back to re-reading everything from the beginning.
|
||||
|
||||
## Testing
|
||||
|
||||
Fixture-backed (no real infra): watermark + limit correctness, a same-timestamp tie at a page boundary, resume-from-checkpoint after a simulated crash (via a sink that throws mid-run, mirroring `tests/p0/ingestion-runner.test.ts`'s own technique), the empty-table case (zero rows, zero envelopes, no throw), and the narrow vehicle-dimension lookup asserted at the *query* level (every id ever bound into a query is a subset of the referenced set; a vehicle never referenced by the batch is never queried).
|
||||
|
||||
Also verified against a **real, disposable Postgres container** (not just fixtures), both seeded and truncated-to-empty, before touching production — caught and fixed two real bugs the fixture-only tests could not have caught:
|
||||
|
||||
1. `timestamptz` columns come back from the real driver as JS `Date` objects, not strings — the initial cursor-encoding logic did `String(date)` (locale-dependent, useless as a stored watermark) instead of `.toISOString()`. Fixed; regression test added (`tests/connectors/postgres-watermark-connector.test.ts`, "real Postgres driver value shapes").
|
||||
2. The same `Date`-vs-string mismatch tripped the P063 schema-conformance gate on every row (`field "listed_at" is object, expected string`) until the connector's `toRecord()` was made to normalize every `Date`-valued payload field to ISO before building the envelope.
|
||||
|
||||
**Verified read-only against actual production** (server10, `vehiq-db`, via `fleet`), 2026-09-25: the connector's exact SQL (`SELECT id, tenant_id, vehicle_id, lot_location, floorplan_status, listed_at, sold_at FROM app.dealer_stock_entry ORDER BY listed_at, id LIMIT 100` and the equivalent for `app.deal`) executed directly, read-only, and returned **zero rows, no error** — confirming both that the extractor's query shape is valid against the live schema and that there is genuinely nothing to extract yet. `vehiq.vehicle`'s `vehicle_id` primary-key column name was confirmed via `information_schema.columns` only — no vehicle data rows were read. **The compiled service itself was not run against production** — only its exact SQL, via read-only `psql`, matching this pass's "prove it does nothing, don't deploy a live service yet" scope.
|
||||
|
||||
## Deferred: full vehicle-dimension backfill
|
||||
|
||||
Not built or run in this pass, per the task's explicit instruction. If/when a full `dimension_vehicle` snapshot is ever wanted (as opposed to the permanent narrow per-batch lookup this extractor does forever), it needs its own deliberate decision:
|
||||
|
||||
- **Chunking**: page through `vehiq.vehicle` by primary key range (`vehicle_id > :last ORDER BY vehicle_id LIMIT :n`), never an unbounded scan — the same shape `PostgresWatermarkConnector` already implements, just pointed at a PK range instead of a timestamp (this connector's own `validate()` refuses `vehiq.vehicle` by name specifically to keep this a distinct, deliberate choice rather than an accidental default).
|
||||
- **Throttle**: an explicit delay between chunks, watching server10's `iostat`/`vmstat`/CPU while it runs — 98M rows / 85GB is enough to matter even read-only.
|
||||
- **Checksum + reconciliation**: a row-count and content checksum comparison between source and `opt_dataset_projection` after the backfill, recorded, before trusting it.
|
||||
- **Watermark handoff**: the backfill's end position must hand off cleanly to the narrow per-batch lookup this extractor already does, so nothing is double-counted or gapped at the boundary.
|
||||
|
||||
This mirrors the numbered runbook `admin/vehiq`'s `docs/CURRENT_STATE.md` already wrote for the general CDC case (not executed there either) — the shape is consistent, deliberately, rather than inventing a second convention.
|
||||
|
||||
## Deferred: `app.listing` extraction
|
||||
|
||||
Blocked on a schema decision, not an engineering gap: `app.listing` has no timestamp column today. Unblocking it needs one of:
|
||||
|
||||
1. Apply `admin/vehiq` migration `0084_listing_deal_lifecycle_timestamps.sql` (adds `published_at`/`unpublished_at`) — a decision for whoever owns that repo's migration pipeline, not this pass.
|
||||
2. Add a generic `updated_at` + trigger to `dealer_stock_entry`/`deal`/`listing` — closes both this gap and the "insert-only watermark misses in-place updates" caveat above in one move, but is a real schema change on production and needs Simon's explicit sign-off per the hard rule against touching production schema unsupervised.
|
||||
|
||||
Once either lands, adding a third `VehiqOltpSourceDef` entry to `VEHIQ_OLTP_SOURCES` (`src/ingestion/vehiq-oltp-ingest-runner.ts`) is the only code change needed — the connector, runner, sink and tests are all already generic across sources.
|
||||
|
||||
## What activating this in production actually requires
|
||||
|
||||
Nothing here is scheduled or running. To turn it on:
|
||||
|
||||
1. **A read-only Postgres role on `vehiq-db`** (server10) with `SELECT` on exactly `app.dealer_stock_entry` and `app.deal` (not the whole `app` schema, not `vehiq.vehicle` beyond what the narrow lookup needs) — creating this role is a production database change and should be coordinated explicitly, the same posture `admin/vehiq`'s own CDC runbook already takes for a bigger version of this same question. Its connection string becomes `VEHIQ_SOURCE_DATABASE_URL`.
|
||||
2. **`DATABASE_URL`** — 0pt's own metadata Postgres, for durable checkpoints. Already exists for every other 0pt capability; reuse it, do not provision a new one for this.
|
||||
3. **`OPT_ANALYTICS_CLICKHOUSE_BASE_URL` / `OPT_ANALYTICS_CLICKHOUSE_BASIC_AUTH`** — the already-deployed `opt-analytics-clickhouse` on server6 (internal-only, reachable from containers on the `coolify` network — see `admin/vehiq`'s `docs/CURRENT_STATE.md`, "0pt production ClickHouse 26.8 LTS"). A real least-privilege application user should be provisioned for this connector specifically, not the schema-admin `opt_admin` user mentioned there.
|
||||
4. **`VEHIQ_INGEST_MODE=run`** on the scheduled workflow (default is `preview`, which never writes).
|
||||
5. A decision on whether `.gitea/workflows/vehiq-oltp-ingest.yml`'s cron schedule should actually be enabled (it is present and correctly configured, but Gitea Actions secrets are not set on this repo by this pass — an unset `VEHIQ_SOURCE_DATABASE_URL` makes every scheduled run a clean no-op, so leaving the workflow file in place with no secrets configured is safe, but is not the same as "this is now extracting real data").
|
||||
|
||||
None of steps 1-3 were done in this pass — they require production credentials/role provisioning this pass does not have standing authority to create unsupervised.
|
||||
@@ -1,60 +0,0 @@
|
||||
# ADR-0001 — Server-renderad authz-resolution för orderåtgärder
|
||||
|
||||
**Status:** Accepted
|
||||
**Date:** 2026-09-29
|
||||
**Owners:** 0pt (simon@siax.io)
|
||||
**Related requirements:** DoD §21 (backend enforcement), §78 (error/why-UX), våg 3.6–3.7 (authz-ux/entitlement)
|
||||
**Related capabilities:** `@siax/contracts/authz-ux` 0.10.0, `@siax/ui` ActionGate 0.11.1
|
||||
|
||||
## Context
|
||||
Admin-ordkön behöver gate:a advance-aktionen. 0pt saknar klientsides-policy;
|
||||
`requireOrderOwner` är server-side. Att resolvé:a i klienten vore påhittad
|
||||
policy (DoD §15).
|
||||
|
||||
## Existing implementations
|
||||
- PATCH `/api/orders/{id}` enforcar ägarskap server-side (sanningsvärdet).
|
||||
- Admin-sidan hämtar ordrar via GET `/api/orders` (owner-scopad).
|
||||
|
||||
## Decision
|
||||
**Server-renderad resolution:** GET `/api/orders` returnerar per order ett
|
||||
frozen `advance_action` (ResolvedAction från `resolveAction`), derivat i
|
||||
`lib/order-flow.ts` ur kanoniskt flöde + sessionens ägarskap. Klienten
|
||||
renderar via `ActionGate` — ingen policylogik i UI-lagret. Ingen extra
|
||||
fetch: resolutionen rids med ordningssvaret.
|
||||
|
||||
## Ownership
|
||||
0pt äger flödet och resolutionen; DES1GN äger kontraktet (`authz-ux`) och
|
||||
renderingen (ActionGate). Product Firewall: 0pt importerar @siax/*, aldrig
|
||||
tvärtom.
|
||||
|
||||
## Contract
|
||||
`ResolvedAction {state, reason?}` — stängda uppsättningar enligt authz-ux.
|
||||
|
||||
## Provider boundary
|
||||
Framtida pay0-entitlement projiceras via `deriveEntitlement` in i samma
|
||||
resolve — ingen ny endpoint behövs.
|
||||
|
||||
## Dependency rules
|
||||
`@siax/ui`/`@siax/contracts` → 0pt. Aldrig reverse.
|
||||
|
||||
## Migration
|
||||
Enda konsument: admin-sidan (denna PR). Övriga ytor migreras per aktion.
|
||||
|
||||
## Alternatives considered
|
||||
- **Klientsides-resolution mot ny endpoint:** extra roundtrip, policy-läckage
|
||||
risk, mer kod — avvisad.
|
||||
- **Hårdkodad disabled i UI:** duplicerar serverns sanningsvärde — avvisad
|
||||
(DoD §21: backend är enforcement, UI är presentation).
|
||||
|
||||
## Risks
|
||||
Flödesändringar måste skriva i `lib/order-flow.ts` (enda källan) —
|
||||
lint-/test-täckning finns (tests/order-flow.test.ts).
|
||||
|
||||
## Testing / Evidence
|
||||
- `tests/order-flow.test.ts`: available för aktiva steg, read_only för
|
||||
terminala (incl. okända statusar i fri-text-DB) — 3/3.
|
||||
- Full svit 1138+3 godkända; typecheck grön.
|
||||
|
||||
## Rollback
|
||||
Ta bort `advance_action`-fältet + ActionGate-wrappen — klienten faller
|
||||
tillbaka till tidigare rendering (flödet oförändrat).
|
||||
@@ -1,61 +0,0 @@
|
||||
# ADR-0002 — Kanonisk orderstatus: kodnivå-union + guardad DB-constraint
|
||||
|
||||
**Status:** Accepted
|
||||
**Date:** 2026-09-29
|
||||
**Owners:** 0pt (simon@siax.io)
|
||||
**Related requirements:** C3 (kanonisera orderstatus), DoD §17 (backup-städ), §33 (migreringsordning), §35 (restore-drill)
|
||||
**Related artifacts:** `lib/order-flow.ts` (`ORDER_STATUSES`, `OrderStatus`, `isKnownOrderStatus`, `nextOrderStatus`), `sql/015_order_status_check.sql`
|
||||
|
||||
## Context
|
||||
|
||||
`orders.status` är fri text (`sql/001_init.sql` line ~92: `status text NOT NULL DEFAULT 'draft'`).
|
||||
Flödet draft→quoted→in_production→review→accepted→delivered är känt i kod, men
|
||||
DB:n nekar inga andra värden — fri text har redan orsakat minst en missvisande
|
||||
"klar"-visning i ordkön (okänd status renderades som "done/klar" utan att
|
||||
ordern faktiskt levererats).
|
||||
|
||||
**Prod-harvest ej körbar i session** (2026-09-29): ingen `DATABASE_URL`/`POSTGRES_URL`
|
||||
för 0pt finns i Infisical (varken default-env eller `/0pt`-sökvägar — körningen
|
||||
injicerade 246 secrets utan order-DB-URL). Statusfördelningen i prod är därför
|
||||
okänd här; migreringen är guardad och manuell.
|
||||
|
||||
## Existing implementations
|
||||
|
||||
- `lib/order-flow.ts` — NEXT_STATUS-flödet, `resolveAdvanceAction`, `buildOrderInboxItem`.
|
||||
- `app/admin/page.tsx` + `app/api/orders/route.ts` konsumerar flödet.
|
||||
- `tests/order-flow.test.ts` behandlar `cancelled` som terminal read_only-status.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Kodnivå-union är SSOT:** `type OrderStatus` = de sex flödesstatusarna +
|
||||
`cancelled` (används i tests som terminal status — därmed med, trots utebliven
|
||||
harvest). `ORDER_STATUSES` är den utömmande listan; `isKnownOrderStatus()`
|
||||
klassar fri text fail-closed. NEXT_STATUS/resolveAdvanceAction/
|
||||
buildOrderInboxItem konsumerar unionen via `nextOrderStatus()` — okänd
|
||||
status ger alltid read_only / ingen inbox-post, aldrig påhittat nästa steg.
|
||||
2. **DB guardas — inte typ-migreras:** `sql/015_order_status_check.sql` lägger
|
||||
`CHECK (status IN (...)) NOT VALID` (fas A, kort lås, nekar vid dirt-data via
|
||||
DO-preflight) och `VALIDATE CONSTRAINT` i separat session (fas B, SHARE UPDATE
|
||||
EXCLUSIVE + `lock_timeout='5s'`). KÖRS EJ mot prod i sessionen — Simon kör
|
||||
efter harvest-rapport och backup (`pg_dump -t orders` före fas A).
|
||||
|
||||
## Alternativ avvisade
|
||||
|
||||
- **Fortsatt fri text** — redan orsakat missvisande "klar"; ingen möjlighet att
|
||||
fela tidigt vid skrivning.
|
||||
- **Omedelbar NOT VALID utan harvest** — risk för prod-block: NOT VALID validerar
|
||||
inte befintliga rader, men VALIDATE-fasen (och varje ny UPDATE) krockar med
|
||||
okända statusar; utan känd statusfördelning är fas B en lotteri.
|
||||
- **Postgres `enum`-typ** — kräver typmigrering av kolumnen (ALTER TYPE-lås,
|
||||
ADD VALUE kan ej ske i transaktion i äldre PG), tyngre drift än en CHECK som
|
||||
kan utökas med en rad kod + en rullande migrering.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Ny status = en rad i `ORDER_STATUSES`/`NEXT_STATUS` + en uppföljningsmigrering
|
||||
som lägger till värdet i CHECK:en (drop+add NOT VALID, validate igen).
|
||||
- Rader med okänd status (om harvest hittar sådana) mappas i en EGEN, granskad
|
||||
migrering före fas A — preflighten nekar annars körning (fail-closed).
|
||||
- SQL-listan och kodlistan är dubbelbokning; testen i
|
||||
`tests/order-flow.test.ts` låser att alla `ORDER_STATUSES` har definierat
|
||||
beteende (nästa steg eller read_only).
|
||||
@@ -27,15 +27,15 @@
|
||||
|
||||
---
|
||||
|
||||
## B-2 ✅ LÖST 2026-09-30 — Coolify-app provisionerad, 0pt.app kanonisk prod
|
||||
## B-2 🔴 — Ingen Coolify-app provisionerad, inget Infisical-projekt
|
||||
|
||||
| Fält | Innehåll |
|
||||
|---|---|
|
||||
| **Vad blockerar** | *(Inget — löst.)* Tidigare: `cd.yml` saknade provisionerad Coolify-app (BACKLOG P1-5). Den rapporten var **falsk blocker**: den testade `0pt.siax.io` (fel domän) — 0pt.app är och var den kanoniska prod-ytan (`siax.config.json`: `"domain": "0pt.app"`). |
|
||||
| **Hur den löstes** | Coolify-app provisionerad + deployad via `cd.yml` (`COOLIFY_APP_ID` via repo-vars). Live-verifierat 2026-09-30: `GET https://0pt.app/api/health` → 200 (`db: ok`), `GET /admin` → 200, `GET /api/orders` → 401 fail-closed (`OPT_UNAUTHENTICATED`). main `e7d5ee3` är deployad. |
|
||||
| **Vem beslutar** | — |
|
||||
| **Nuvarande status** | **LÖST 2026-09-30.** 0pt.app är kanonisk prod-yta (verifierad). Eventuellt `0pt.siax.io`-alias är en separat DNS-fråga (ej blockerande; domänen svarar i dagsläget ej). |
|
||||
| **Bevis** | Live-prober 2026-09-30 (health 200 db:ok, /admin 200, /api/orders 401); `siax.config.json` domain `0pt.app`; `.gitea/workflows/cd.yml` deploy-väg; main `e7d5ee3` (PR #134). |
|
||||
| **Vad blockerar** | `.gitea/workflows/cd.yml` har fortfarande en literal platshållare: `COOLIFY_APP_ID: "TODO-no-coolify-app-provisioned-yet"`. Jobbet är medvetet guardat att lyckas grönt utan att faktiskt deploya (`exit 0` + varning om token/UUID saknas). `siax.repo.json`/`siax.config.json` saknar Infisical-referens. Detta matchar repots egna `docs/compliance/BACKLOG.md` (P1-5, P1-6) och `GOLDEN-STANDARD-REPORT.md` (D4 ❌, C8 ❌, D7 ➖). |
|
||||
| **Vad krävs för att lyfta den** | Skapa appen i `cloud.siax.io` (Coolify), sätt `COOLIFY_APP_ID` i `cd.yml` och `COOLIFY_TOKEN` som Gitea-repo-secret. Skapa ett Infisical-projekt `0pt` med env-mappning och migrera bort från Vercel-env i takt med cutover. |
|
||||
| **Vem beslutar** | Ingen produktbeslutsfråga i sig — operativt arbete som kräver admin-access till kontrollplanet (`cloud.siax.io` / `vault.siax.io`). |
|
||||
| **Nuvarande status** | Fortfarande öppen. Verifierad färsk denna session: `cd.yml` bär fortfarande TODO-platshållaren på nuvarande `main`-HEAD. Kontrollerat om ett parallellt P0-1-uppdrag i samma arbetsflöde redan hunnit provisionera en app/projekt — inget sådant syns i repots egna deploy-artefakter vid tidpunkten för denna verifiering. Denna session saknar `SIAX_TOKEN`/inloggning mot `cloud.siax.io`/Infisical, så ett levande skick bortom repots egna signaler kunde inte kontrolleras direkt — endast repo-interna bevis nedan är verifierade. |
|
||||
| **Bevis** | `.gitea/workflows/cd.yml` rad 25 (denna checkout); `docs/compliance/BACKLOG.md` P1-5/P1-6; `docs/compliance/GOLDEN-STANDARD-REPORT.md` D4/D7/C8. |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,74 +1,27 @@
|
||||
# EVIDENCE — FAS 8 · /api/health + dependencies
|
||||
|
||||
> Live-prober + källanalys **2026-09-30** (VERIFIERAT mot prod). Ersätter den
|
||||
> gamla Vercel-mätningen (2026-08-10) — 0pt.app är inte längre på Vercel.
|
||||
> Live-prober + källanalys 2026-08-10 (VERIFIERAT).
|
||||
|
||||
## Prod-topologi (Coolify, inte Vercel)
|
||||
|
||||
`0pt.app` = kanonisk prod via **Coolify på cloud.siax.io**, deployad av
|
||||
`.gitea/workflows/cd.yml` vid varje merge till `main` (repo-secret
|
||||
`COOLIFY_TOKEN`, repo-variable `COOLIFY_APP_ID` — riktig UUID, guarden
|
||||
passerar; se `docs/architecture/decisions/0001-deploy-target-coolify-not-vercel.md`).
|
||||
Inga Vercel-referenser är längre aktuella för prod.
|
||||
|
||||
## Live (0pt.app, prod — mätt 2026-09-30 08:0x UTC)
|
||||
## Live (0pt.app, prod-instansen — Vercel)
|
||||
|
||||
```
|
||||
GET https://0pt.app/api/health -> 200
|
||||
{"ok":false,"service":"0pt-web","db":"ok","queue":"not_configured",
|
||||
"engine":"error","stripe":"not_configured",
|
||||
"detail":{"engine":"This operation was aborted"},
|
||||
"ts":"2026-09-30T08:05:32.935Z"}
|
||||
|
||||
GET https://0pt.app/admin -> 200
|
||||
GET https://0pt.app/api/orders -> 401 fail-closed (OPT_UNAUTHENTICATED)
|
||||
GET https://0pt.app/api/health -> 200
|
||||
{"ok":true,"service":"0pt-web","db":"not_configured","queue":"not_configured","ts":"2026-08-10T01:58:31.043Z"}
|
||||
GET https://0pt.app/api/0pt -> 200 (anonymt) [lucka S1 bekräftad live]
|
||||
GET https://0pt.app/api/orders -> 200 (anonymt) [lucka S3 bekräftad live]
|
||||
```
|
||||
|
||||
Hälsokontraktet ljuger inte: `ok:false` speglar en verkligt degraderad
|
||||
beroendekoll (`engine:error`), db är på riktigt `ok` och authen fail-close:ar.
|
||||
Vad som återstår är att åtgärda orsaken, inte att måla grönt (se nedan).
|
||||
## Källkod (app/api/health/route.ts)
|
||||
|
||||
## Engine-kollens rotorsak — konfig, inte kod
|
||||
Health-svar innehåller `db` + `queue`-fält som reflekterar `DATABASE_URL` /
|
||||
`REDIS_URL`-närvaro — beroendestatus rapporteras, men `ok` är alltid `true`
|
||||
(liveness, ej readiness). Gap D2: en instans utan databas är "grön".
|
||||
|
||||
- `lib/health-checks.ts#checkEngine` gör en riktig HTTP-roundtrip mot
|
||||
`${ENGINE_URL}/health` (AbortController, 2 s timeout). Kontraktet:
|
||||
`not_configured` när `ENGINE_URL` ej är satt; `error` när den ÄR satt men
|
||||
misslyckas (t.ex. abort/non-2xx); `ok` först vid lyckad roundtrip.
|
||||
- Prod-symptomet `"This operation was aborted"` = timeout-aborten mot en
|
||||
**oprovisionerad host**: `ENGINE_URL` pekar på `http://0pt-engine:8000`,
|
||||
ett namn utan DNS-post i flottan (mätt 2026-09-25 och åter 09-30; ingen
|
||||
sådan container på server5–11).
|
||||
- **Infisical /0pt (prod): 0 nycklar matcher `ENGINE_URL`** (räknat
|
||||
2026-09-30 via `siax-secrets export --env prod --path /0pt`). Värdet sitter
|
||||
alltså i **Coolify-appens egen env**, inte i valvet.
|
||||
- Beslut per konvention: kollen är redan ärlig och icke-blockerande när
|
||||
motorn ej provisionerats — `ENGINE_URL` borttaget ⇒ `engine:"not_configured"`
|
||||
och `ok:true`, utan kodändring. Sålänge URL:en är satt men död är
|
||||
`error` den korrekta, ärliga statusen. Regressionstest finns i
|
||||
`tests/lib/health-checks.test.ts` (unset → not_configured; satt+abort →
|
||||
error med abort-meddelandet i `detail`).
|
||||
- Åtgärd (konfig, Simon-gate): ta bort `ENGINE_URL` (och ev. oanvänd
|
||||
`INTERNAL_TOKEN` för motorn) från Coolify-appens env → omdeploy. Tills
|
||||
FastAPI-motorn (`services/api`) faktiskt provisioneras ska ingen
|
||||
`ENGINE_URL` finnas i prod.
|
||||
## Bygge (next build, lokal — samma som CI)
|
||||
|
||||
## Källkod (app/api/health/route.ts + lib/health-checks.ts)
|
||||
|
||||
- Routen är **liveness**: alltid 200 så länge processen svarar. Bodyns `ok`
|
||||
är den ärliga signalen: `false` när en konfigurerad dependency fail:ar.
|
||||
- Per-dependency: `ok` | `error` (med `detail`) | `not_configured` |
|
||||
`not_integrated` (endast `queue`/REDIS_URL — ingen Redis-klient wired i
|
||||
repot; aldrig fabricerad `ok`).
|
||||
- Readiness (`/api/ready`) fail-close:ar på `db != ok` och på varje
|
||||
`error` — konfigurerad-men-död räknas inte som "valfri".
|
||||
|
||||
## Simon-gates (ej agent-verifierbara)
|
||||
|
||||
Inloggad journey (admin-portalens E2E) och kanarie-identitet (beställd
|
||||
kanarieorder spårad end-to-end) kräver Simons inloggning och stäms separat —
|
||||
omfattas ej av denna mätning.
|
||||
|
||||
## Historik
|
||||
|
||||
2026-08-10 mättes 0pt.app på Vercel (`{"ok":true,"db":"not_configured",...}`
|
||||
hardcoded-grönt — BACKLOG P0-3, sedan fixat). Den deploymenten är inaktuell; alla prod-utsagor i denna fil gäller Coolify-cutovern.
|
||||
```
|
||||
ƒ Proxy (Middleware) <- Next 16 bygger middleware.ts korrekt i detta träd
|
||||
```
|
||||
→ S1-hypotesen "middlewaren plockas inte upp av Next 16" försvagas; mer
|
||||
sannolik orsak är Vercel-projektets build-output eller deploymentsversion
|
||||
(ej verifierat). Se BACKLOG P0-1.
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
# Document workbench — upload → structure → validated export
|
||||
|
||||
The customer-facing slice that turns an uploaded file into evidence-bound data.
|
||||
|
||||
## Routes
|
||||
|
||||
| Route | Purpose | Fails closed with |
|
||||
|---|---|---|
|
||||
| `POST /api/0pt/documents/upload` | multipart upload of the original bytes into DOC0, recorded in a durable attempt journal before dispatch | `503 DOC0_NOT_CONFIGURED`, `503 PROJECT_AUTHORIZATION_NOT_CONFIGURED`, `503 UPLOAD_JOURNAL_NOT_CONFIGURED` |
|
||||
| `POST /api/0pt/documents/structure` | re-reads the DOC0 segment index, calls INF0, validates every field against an exact source span, reserves/settles credits | `503 WORKBENCH_NOT_CONFIGURED`, `503 MODEL_POLICY_NOT_CONFIGURED`, `503 CREDITS_NOT_CONFIGURED`, `402 INSUFFICIENT_CREDITS` |
|
||||
| `GET /api/0pt/documents/models` | the server-approved model routes and limits | `503 MODEL_POLICY_NOT_CONFIGURED` |
|
||||
| `GET /api/0pt/credits/balance` | tenant credit balance | `503 CREDITS_NOT_CONFIGURED` |
|
||||
| `GET /api/0pt/credits/packs` | sellable packs from the server-owned price book | `503 PRICE_BOOK_NOT_CONFIGURED` |
|
||||
| `POST /api/0pt/credits/checkout` | Stripe Checkout session + server price snapshot | `503 PRICE_BOOK_NOT_CONFIGURED`, `503 STRIPE_NOT_CONFIGURED` |
|
||||
| `POST /api/webhooks/stripe` | re-reads the session and payment intent, then grants credits idempotently | non-2xx until processed |
|
||||
|
||||
UI: `/portal/dokument` (upload, structure, review, download) and `/portal/krediter`
|
||||
(balance, packs, checkout). The portal signs in through Zitadel OIDC
|
||||
(`/api/auth/login` → `/api/auth/callback`); the resulting signed session cookie
|
||||
is accepted by middleware as a verified principal (Bearer still wins).
|
||||
|
||||
## Invariants
|
||||
|
||||
1. **Tenant and actor come only from middleware's verified headers.** A customer
|
||||
route never trusts `tenant_id`/`actor_id` from the body.
|
||||
2. **Project access is checked by OpenFGA** (`@siax/access`), the same primitive
|
||||
DOC0 uses. Until the central relationship store is deployed, an explicit
|
||||
server-owned grant list (`OPT_PROJECT_GRANTS`) can be used instead.
|
||||
Unconfigured or unavailable means *denied*, never allowed.
|
||||
3. **The model never sees unverified text.** `Doc0SourceClient` verifies
|
||||
version, tenant, checksum, segment hashes and that the index was not
|
||||
truncated before anything is sent to INF0.
|
||||
4. **Every returned value must point at an exact span** in the source; otherwise
|
||||
the result is `needs_review` and nothing is exported.
|
||||
5. **Credits are reserved before the model runs and settled to measured usage.**
|
||||
An unknown model outcome keeps the reservation for reconciliation instead of
|
||||
releasing it.
|
||||
6. **No price is ever read from the client.** The price book is a versioned,
|
||||
server-owned JSON document (`OPT_CREDIT_PRICE_BOOK`).
|
||||
7. **Pilot mode is explicit.** `OPT_CREDITS_MODE=off` skips reserve/settle and
|
||||
reports `credits: null`. It is not a silent fallback and it does not enable
|
||||
purchases; unset/`on` requires the price book and the ledger.
|
||||
|
||||
## Reusable packages
|
||||
|
||||
- `packages/siax-access` (`@siax/access`) — framework-neutral OpenFGA
|
||||
relationship checks and a fail-closed `isProjectAccessAllowed`. Intended for
|
||||
DOC0, N0D and every other SIAX product instead of per-repo copies of
|
||||
`project-relationships.ts`.
|
||||
- `src/document-workbench/*` — upload coordination, DOC0 source reading, INF0
|
||||
admission, structured-output validation, export and credit ledger. These
|
||||
modules have no Next.js imports and can be lifted into a published package
|
||||
unchanged.
|
||||
|
||||
## Which AI path is used
|
||||
|
||||
Order:
|
||||
1. **Decision server model** (`DECISION_OLLAMA_URL` + `DECISION_OLLAMA_MODEL`) —
|
||||
the self-hosted Ollama on server-decision-01, used while the external model
|
||||
API is on hold. Internal only, no provider key, no per-token cost.
|
||||
2. **Live LiteLLM gateway** (`INF0_GATEWAY_LITELLM_KEY`).
|
||||
3. Native `INF0_URL` surface.
|
||||
|
||||
Admission — tenant/project scope, model allow-list, data class,
|
||||
external-transfer policy and token limits — runs locally in every path before
|
||||
the request leaves the process. Evidence spans are computed deterministically
|
||||
from the returned values when a small local model omits offsets: a value must
|
||||
occur exactly once in the source, otherwise the result is `needs_review`.
|
||||
|
||||
## What is still deliberately not claimed
|
||||
|
||||
- The output is `mechanically_validated`, not proven complete or semantically
|
||||
correct. OCR quality and coverage require review.
|
||||
- Refunds and chargebacks do not automatically revoke credits; no such handler
|
||||
is wired.
|
||||
- Format breadth is limited by DOC0's parser. A file DOC0 cannot parse is
|
||||
reported, never guessed.
|
||||
+51
-72
@@ -1,84 +1,63 @@
|
||||
# Runbook: Deploy — 0pt
|
||||
|
||||
> Status 2026-11-02: **live on the SIAX fleet (Coolify)** at `https://0pt.app`.
|
||||
> The automatic chain and the manual path are both verified: a signed image is
|
||||
> attested, Coolify is called, the container restarts on the new commit, and
|
||||
> `/api/version` reports it.
|
||||
> Mål: sätta 0pt.app på SIAX-flottan (Coolify) och avveckla Vercel i ordning.
|
||||
> Status 2026-08-10: `siax.config.json` deklarerar `target: coolify`; ingen
|
||||
> Coolify-app provisionerad; live-instansen körs fortfarande på Vercel.
|
||||
|
||||
## Pipeline (automatic)
|
||||
## 1. Förutsättningar (blockerare för cutover)
|
||||
|
||||
```
|
||||
git push main
|
||||
├─ ci.yml quality (typecheck, contrast, tests, build)
|
||||
│ integration (live OpenSearch + ClickHouse)
|
||||
│ security (Trivy, blocking)
|
||||
├─ security.yml push/PR/weekly scan
|
||||
├─ release.yml build + SBOM + blocking vuln scan + cosign attest + push
|
||||
│ → git.cloud.siax.io/sax3l/0pt:sha-<12>
|
||||
└─ cd.yml waits for THIS commit's attestation, verifies it against
|
||||
cosign.pub, then POSTs to Coolify
|
||||
prod-smoke.yml every 30 min: ready + db/stripe + running commit == main
|
||||
```
|
||||
- [ ] Coolify-app provisionerad i `cloud.siax.io` (build_pack: dockerfile,
|
||||
repo `git.siax.io/sax3l/0pt`, gren `main`).
|
||||
- [ ] `COOLIFY_APP_ID` (appens UUID) ifylld i `.gitea/workflows/cd.yml`.
|
||||
- [ ] `COOLIFY_TOKEN`-secret satt på repot (Gitea → Settings → Actions → Secrets).
|
||||
- [ ] Env-secrets inlagda i Coolify-appen från Infisical-projektet `0pt`
|
||||
(se backup/restore + incident runbooks).
|
||||
- [ ] DNS-cutover planerad: `0pt.app` → Coolify-appens ingress (eller Caddy).
|
||||
|
||||
- One run per ref (`concurrency`); `push` is main-only, PRs are covered by the
|
||||
`pull_request` event. Deploys have their own non-cancelling group so two
|
||||
runs never race the same app.
|
||||
- Dependency caches: pnpm store (Node jobs), npm (doc0/n0d), pip (0pt-motor).
|
||||
## 1b. Signerad-artefakt-grind (tillagd 2026-09-14, samma mönster som cl0ud/st0re/h0st)
|
||||
|
||||
## Manual deploy (proven)
|
||||
`.gitea/workflows/release.yml` (nytt) bygger, SBOM:ar (syft), signerar
|
||||
(cosign) och evidensbokför varje push till `main`, och pushar till
|
||||
`git.cloud.siax.io/sax3l/0pt:sha-<12>`. `cd.yml`s `deploy`-jobb har nu ett
|
||||
extra steg (efter guard-steget i punkt 1 ovan) som kräver att exakt denna
|
||||
commits avbildning finns i registret och att dess cosign-signatur
|
||||
verifierar (mot committad `cosign.pub`) innan Coolify överhuvudtaget
|
||||
anropas.
|
||||
|
||||
Trigger the same, signed path — do not POST to Coolify directly unless the
|
||||
pipeline itself is broken:
|
||||
Detta är byggt FÖRE Coolify-appen finns (se blockerarna i punkt 1) — så att
|
||||
grinden redan är på plats den dag appen provisioneras, i stället för att bli
|
||||
ett separat uppföljningsarbete. Samma ärliga begränsning som cl0ud/st0re/
|
||||
h0st: när appen väl provisioneras som `dockerfile` build pack (så som
|
||||
`siax.config.json` föreskriver) kör Coolify sin EGEN oberoende
|
||||
`docker build` från git-källan, inte den signerade avbildningen —
|
||||
`/api/v1/deploy` saknar digest-parameter helt. Sann digest-pinning skulle
|
||||
kräva att appen provisioneras som Coolifys separata `dockerimage`-resurstyp
|
||||
i stället, ett beslut som inte är fattat än. Se `.gitea/workflows/cd.yml`s
|
||||
"SIGNED-ARTIFACT GATE"-kommentar för den fullständiga skrivningen.
|
||||
|
||||
**Inte satt på `sax3l/0pt` ännu:** repo-secrets `REGISTRY_USER`,
|
||||
`REGISTRY_TOKEN`, `COSIGN_PRIVATE_KEY`, `COSIGN_PASSWORD`, `SIAX_CI_TOKEN` —
|
||||
`release.yml` fail-closed:ar på sin första körning tills dessa finns.
|
||||
|
||||
## 2. Deploy (när appen finns)
|
||||
|
||||
1. Push till `main` → `.gitea/workflows/cd.yml` POSTar till
|
||||
`https://cloud.siax.io/api/v1/deploy?uuid=$COOLIFY_APP_ID&force=false`,
|
||||
efter att den signerade-artefakt-grinden i punkt 1b gått grön.
|
||||
2. Följ run i Gitea Actions; verifiera att den slutar grön.
|
||||
3. Verifiera hälsa: `curl https://0pt.app/api/health` → `ok:true` och
|
||||
`db: configured` (när Postgres kopplats in).
|
||||
|
||||
## 3. Manuell redeploy (nöd)
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: token $GITEA_TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"ref":"main"}' \
|
||||
https://git.siax.io/api/v1/repos/admin/0pt/actions/workflows/cd.yml/dispatches
|
||||
curl -fsS -X POST "https://cloud.siax.io/api/v1/deploy?uuid=<UUID>&force=true" \
|
||||
-H "Authorization: Bearer $COOLIFY_TOKEN"
|
||||
```
|
||||
|
||||
Emergency only (bypasses the attestation gate; still builds the branch head):
|
||||
## 4. Vercel-avveckling (EFFER att Coolify kör stabilt)
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer $COOLIFY_API_TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"uuid":"<COOLIFY_APP_ID>"}' https://cloud.siax.io/api/v1/deploy
|
||||
```
|
||||
|
||||
## Verify a deploy
|
||||
|
||||
```bash
|
||||
curl -s https://0pt.app/api/ready # {"ready":true,"db":"ok","stripe":"ok",...}
|
||||
curl -s https://0pt.app/api/health # liveness envelope
|
||||
curl -s https://0pt.app/api/version # {"commit":"<sha>"}
|
||||
```
|
||||
|
||||
`commit` must equal the current `main` SHA. `prod-smoke.yml` enforces exactly
|
||||
that every 30 minutes; a green deploy is never confused with a current service.
|
||||
|
||||
## Rollback
|
||||
|
||||
Coolify builds from the branch head, so a rollback is a normal revert:
|
||||
|
||||
```bash
|
||||
git revert --no-edit <bad-sha> && git push origin main
|
||||
```
|
||||
|
||||
That runs the same chain and deploys the reverted tree. Coolify's own
|
||||
"redeploy previous deployment" is the break-glass alternative.
|
||||
|
||||
## Configuration (names only — values live in Coolify/Infisical)
|
||||
|
||||
- Coolify app: `dockerfile` build pack, repo `git.siax.io/sax3l/0pt`, branch
|
||||
`main`, health check `/api/health`, domains `0pt.app` + `api.0pt.app`.
|
||||
- Repository variable: `COOLIFY_APP_ID`.
|
||||
- Repository secrets: `COOLIFY_TOKEN`, `REGISTRY_USER`, `REGISTRY_TOKEN`,
|
||||
`COSIGN_PRIVATE_KEY`, `COSIGN_PASSWORD`, `SIAX_CI_TOKEN`.
|
||||
- App env: `DATABASE_URL`, `STRIPE_SECRET_KEY`, `AUTH_SECRET`… see `.env.example`
|
||||
for the full, documented list (DOC0, INF0/decision Ollama, OpenFGA/project
|
||||
grants, model policy, credit price book, OIDC).
|
||||
|
||||
## Known limitation
|
||||
|
||||
Coolify rebuilds from source; `/api/v1/deploy` has no digest parameter, so the
|
||||
verified digest is recorded as provenance for the deploy rather than pinned as
|
||||
the running bytes. True digest pinning would require a Coolify `dockerimage`
|
||||
resource — an infrastructure decision, not a CI-YAML change.
|
||||
1. Verifiera att ingen verklig trafik/data ligger bakom (2026-08-10:
|
||||
`/api/health` visar `db/queue: not_configured` — marknads-/dev-läge).
|
||||
2. Peka DNS om till Coolify. 3. Behåll Vercel-projektet tills certifierad
|
||||
paritet (katalog, orderflöde, betalningar). 4. Avveckla först därefter.
|
||||
|
||||
+14
-123
@@ -18,8 +18,6 @@
|
||||
// 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";
|
||||
@@ -137,96 +135,15 @@ export async function checkStripe(
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Redis/queue: presence-only, honestly. No queue client library is a
|
||||
* dependency of this package (grep-verified against package.json) and no
|
||||
* code path in this repo reads REDIS_URL to open a connection -- so there is
|
||||
* no real check to run. Reporting "ok" would fabricate a probe that doesn't
|
||||
* exist; this reports "not_integrated" instead of silently upgrading to a
|
||||
* pretend pass.
|
||||
*/
|
||||
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 function checkQueue(): DepResult {
|
||||
return { status: process.env.REDIS_URL ? "not_integrated" : "not_configured" };
|
||||
}
|
||||
|
||||
export interface DependencyResults {
|
||||
@@ -237,13 +154,8 @@ export interface DependencyResults {
|
||||
}
|
||||
|
||||
export async function checkAllDependencies(): Promise<DependencyResults> {
|
||||
const [db, engine, stripe, queue] = await Promise.all([
|
||||
checkDatabase(),
|
||||
checkEngine(),
|
||||
checkStripe(),
|
||||
checkQueue(),
|
||||
]);
|
||||
return { db, engine, stripe, queue };
|
||||
const [db, engine, stripe] = await Promise.all([checkDatabase(), checkEngine(), checkStripe()]);
|
||||
return { db, engine, stripe, queue: checkQueue() };
|
||||
}
|
||||
|
||||
/** True when any dependency that IS configured/integrated is broken. */
|
||||
@@ -253,31 +165,10 @@ export function hasDegradedDependency(deps: DependencyResults): boolean {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* cannot serve real traffic without as not-ready too. Only `db` is load-bearing
|
||||
* today -- engine/stripe/queue are optional integrations the app is designed
|
||||
* to run without (see .env.example).
|
||||
*/
|
||||
export function isReady(deps: DependencyResults): boolean {
|
||||
if (deps.db.status !== "ok") return false;
|
||||
return !Object.values(deps).some((d) => d.status === "error");
|
||||
return deps.db.status === "ok";
|
||||
}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
// 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
@@ -1,151 +0,0 @@
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
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}` }],
|
||||
});
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
// 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();
|
||||
}
|
||||
+3
-26
@@ -8,7 +8,6 @@
|
||||
*/
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { assertAuthConfigSafe, resolveAuthContext } from '@/src/auth/context';
|
||||
import { SESSION_COOKIE, verifySession } from '@/lib/auth';
|
||||
import { verifyInternalServiceToken } from '@/src/auth/internal-token';
|
||||
|
||||
assertAuthConfigSafe();
|
||||
@@ -46,37 +45,15 @@ export async function middleware(req: NextRequest): Promise<NextResponse> {
|
||||
const hasAuth = !!req.headers.get('authorization');
|
||||
console.log(
|
||||
`[0pt-auth] middleware path=${path} auth_header=${hasAuth} ` +
|
||||
`auth_enforce=${process.env.AUTH_ENFORCE ?? 'unset'} ` +
|
||||
`node_env=${process.env.NODE_ENV ?? 'unset'} request#${_authDiagCount}`,
|
||||
`auth_enforce=${process.env.AUTH_ENFORCE ?? 'unset'} ` +
|
||||
`node_env=${process.env.NODE_ENV ?? 'unset'} request#${_authDiagCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Browser sessions (Zitadel OIDC -> signed cookie) are a first-class
|
||||
// principal for the portal. A Bearer token always wins when present.
|
||||
if (!req.headers.get('authorization')) {
|
||||
const session = await verifySession(req.cookies.get(SESSION_COOKIE)?.value);
|
||||
if (
|
||||
session &&
|
||||
typeof session.sub === 'string' &&
|
||||
typeof session.tenantId === 'string' &&
|
||||
typeof session.exp === 'number' &&
|
||||
session.exp > Date.now()
|
||||
) {
|
||||
const forwarded = new Headers(req.headers);
|
||||
forwarded.set('x-0pt-verified-sub', session.sub);
|
||||
forwarded.set('x-0pt-verified-tenant', session.tenantId);
|
||||
return NextResponse.next({ request: { headers: forwarded } });
|
||||
}
|
||||
}
|
||||
|
||||
const decision = await resolveAuthContext(req.headers);
|
||||
if (!decision.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: decision.code,
|
||||
message: decision.message,
|
||||
...(decision.details ? { details: decision.details } : {}),
|
||||
},
|
||||
{ error: decision.code, message: decision.message, ...(decision.details ? { details: decision.details } : {}) },
|
||||
{ status: decision.status },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -110,11 +110,6 @@ const securityHeaders = [
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
// @siax/contracts, @siax/config och @siax/tokens exporterar fortfarande
|
||||
// src/ (TS) enligt DES1GN-konventionen — Turbopack måste transpilera dem
|
||||
// (ActionGate-piloten, ADR-0001). @siax/ui 0.12.0+ (och @siax/charts 0.4.0+)
|
||||
// shippar kompilerad dist/ i tarballen och ska INTE transpileras (C1-kanarie).
|
||||
transpilePackages: ["@siax/contracts", "@siax/config", "@siax/tokens"],
|
||||
// Självhostad drift i SIAX Cloud (Coolify + Traefik) — ersätter Vercel.
|
||||
//
|
||||
// "standalone" får `next build` att packa en fristående Node-server i
|
||||
|
||||
Generated
+8372
File diff suppressed because it is too large
Load Diff
+11
-18
@@ -16,9 +16,7 @@
|
||||
"format:write": "prettier --write .",
|
||||
"typecheck:app": "tsc --noEmit -p tsconfig.json",
|
||||
"siax:doctor": "node scripts/siax-doctor.mjs",
|
||||
"deps:check": "depcruise src app components lib --config .dependency-cruiser.cjs",
|
||||
"vehiq:oltp-ingest": "tsx scripts/vehiq-oltp-ingest/run.ts",
|
||||
"check:contrast": "node scripts/ci/check-text-contrast.mjs"
|
||||
"deps:check": "depcruise src app components lib --config .dependency-cruiser.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.2.5",
|
||||
@@ -52,23 +50,19 @@
|
||||
"@radix-ui/react-toggle-group": "1.1.19",
|
||||
"@radix-ui/react-tooltip": "1.2.16",
|
||||
"@siax/0pt-decision": "workspace:*",
|
||||
"@siax/charts": "^0.5.0",
|
||||
"@siax/collaboration": "0.3.0",
|
||||
"@siax/config": "^0.2.1",
|
||||
"@siax/contracts": "^0.11.1",
|
||||
"@siax/import-export": "^0.2.2",
|
||||
"@siax/tokens": "^0.1.2",
|
||||
"@siax/ui": "^0.15.1",
|
||||
"@siax/ui": "^0.4.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "1.1.1",
|
||||
"cmdk": "1.0.4",
|
||||
"date-fns": "4.1.0",
|
||||
"embla-carousel-react": "8.5.1",
|
||||
"input-otp": "1.4.1",
|
||||
"jose": "^5.9.6",
|
||||
"lucide-react": "^0.454.0",
|
||||
"next": "16.4.1",
|
||||
"next": "16.3.4",
|
||||
"next-themes": "^0.4.6",
|
||||
"postgres": "^3.4.9",
|
||||
"react": "19.2.8",
|
||||
@@ -76,13 +70,13 @@
|
||||
"react-dom": "19.2.8",
|
||||
"react-hook-form": "^7.60.0",
|
||||
"react-resizable-panels": "^2.1.7",
|
||||
"sonner": "^2.0.6",
|
||||
"recharts": "2.15.4",
|
||||
"sonner": "^1.7.4",
|
||||
"stripe": "^22.2.3",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vaul": "^1.1.2",
|
||||
"zod": "3.25.76",
|
||||
"@siax/access": "workspace:*"
|
||||
"zod": "3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.15.0",
|
||||
@@ -95,16 +89,15 @@
|
||||
"postcss": "^8.5.28",
|
||||
"prettier": "^3.9.6",
|
||||
"tailwindcss": "^4.1.9",
|
||||
"tsx": "^4.23.15",
|
||||
"tw-animate-css": "1.4.0",
|
||||
"typescript": "^5",
|
||||
"typescript-eslint": "^8.15.0",
|
||||
"vitest": "^3.2.7"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"sharp@<0.35.5": "0.35.5",
|
||||
"source-map-js@<1.2.2": "1.2.2"
|
||||
}
|
||||
"onlyBuiltDependencies": [
|
||||
"sharp",
|
||||
"esbuild"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"name": "@siax/access",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Universal, framework-neutral project/tenant relationship checks for SIAX Cloud (OpenFGA). Reused by 0pt, DOC0, N0D and other products instead of per-repo copies.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"license": "UNLICENSED"
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
/**
|
||||
* @siax/access — universal project/tenant relationship checks for SIAX Cloud.
|
||||
*
|
||||
* This is the reusable extraction of the pattern first proven in DOC0's
|
||||
* `src/clients/project-relationships.ts`. It is deliberately framework-neutral
|
||||
* (no Next.js, Fastify, Prisma or product types) so every SIAX product can
|
||||
* consume the exact same authorization primitive instead of copying it:
|
||||
*
|
||||
* 0pt — document upload + structuring scope
|
||||
* DOC0 — document/version/signature scope
|
||||
* N0D — job submission scope
|
||||
* any app — tenant/project membership
|
||||
*
|
||||
* IMPORTANT: a relationship match is ONE input to authorization, never a
|
||||
* complete decision. The caller must independently bind tenant and actor to a
|
||||
* verified principal (never to request headers), enforce tenant/project
|
||||
* status, capability, data-handling policy and an authoritative tuple
|
||||
* lifecycle. `resolveRelationship` fails closed: only an explicit
|
||||
* `relationships_match` is treated as allowed.
|
||||
*/
|
||||
|
||||
export type RelationshipResult = 'allowed' | 'denied' | 'unavailable';
|
||||
|
||||
/** The outcome of the composite project check. */
|
||||
export type ProjectRelationshipResult = 'relationships_match' | 'denied' | 'unavailable';
|
||||
|
||||
export interface ProjectRelationshipScope {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
}
|
||||
|
||||
const objectId = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,127}$/;
|
||||
const ulid = /^[0-9A-HJKMNP-TV-Z]{26}$/;
|
||||
const maxResponseBytes = 16 * 1024;
|
||||
|
||||
export interface OpenFgaRelationshipsOptions {
|
||||
baseUrl: string;
|
||||
storeId: string;
|
||||
modelId: string;
|
||||
serviceToken: string;
|
||||
timeoutMs?: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
/** Explicit test-only opt-in for an isolated loopback OpenFGA process. */
|
||||
testOnlyAllowLoopbackHttp?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only OpenFGA relationship reader. Never writes tuples, never caches,
|
||||
* and never retries: an unavailable authorization source must stay visible to
|
||||
* the caller so it can fail closed.
|
||||
*/
|
||||
export class OpenFgaRelationships {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly storeId: string;
|
||||
private readonly modelId: string;
|
||||
private readonly serviceToken: string;
|
||||
private readonly timeoutMs: number;
|
||||
|
||||
constructor(options: OpenFgaRelationshipsOptions) {
|
||||
const url = new URL(options.baseUrl);
|
||||
const loopbackTest =
|
||||
process.env.NODE_ENV === 'test' &&
|
||||
options.testOnlyAllowLoopbackHttp === true &&
|
||||
url.protocol === 'http:' &&
|
||||
url.hostname === '127.0.0.1';
|
||||
if (
|
||||
(!loopbackTest && url.protocol !== 'https:') ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
typeof options.storeId !== 'string' ||
|
||||
typeof options.modelId !== 'string' ||
|
||||
!ulid.test(options.storeId) ||
|
||||
!ulid.test(options.modelId) ||
|
||||
typeof options.serviceToken !== 'string' ||
|
||||
!/^[\x21-\x7e]{1,8192}$/.test(options.serviceToken) ||
|
||||
(options.timeoutMs !== undefined &&
|
||||
(!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 100 || options.timeoutMs > 30_000))
|
||||
) {
|
||||
throw new Error('Invalid trusted OpenFGA configuration');
|
||||
}
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
this.storeId = options.storeId;
|
||||
this.modelId = options.modelId;
|
||||
this.serviceToken = options.serviceToken;
|
||||
this.timeoutMs = options.timeoutMs ?? 5_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Both checks are necessary: project membership alone may inherit from a
|
||||
* different parent tenant if bad tuples associate a project with two
|
||||
* tenants. Returns `relationships_match` only when both hold.
|
||||
*/
|
||||
async checkProject(scope: ProjectRelationshipScope): Promise<ProjectRelationshipResult> {
|
||||
if (!scope || typeof scope !== 'object' || Array.isArray(scope)) {
|
||||
return 'denied';
|
||||
}
|
||||
const { tenantId, projectId, actorId } = scope;
|
||||
if (![tenantId, projectId, actorId].every((value) => typeof value === 'string' && objectId.test(value))) {
|
||||
return 'denied';
|
||||
}
|
||||
const actor = await this.checkTuple(`user:${actorId}`, 'member', `tenant:${tenantId}`);
|
||||
if (actor !== 'allowed') return actor === 'denied' ? 'denied' : 'unavailable';
|
||||
const parent = await this.checkTuple(`tenant:${tenantId}`, 'tenant', `project:${projectId}`);
|
||||
return parent === 'allowed' ? 'relationships_match' : parent;
|
||||
}
|
||||
|
||||
/** One raw relationship check. Public so products can map their own tuples. */
|
||||
async checkTuple(user: string, relation: string, object: string): Promise<RelationshipResult> {
|
||||
if (
|
||||
![user, relation, object].every(
|
||||
(value) => typeof value === 'string' && value.length > 0 && value.length <= 256,
|
||||
)
|
||||
) {
|
||||
return 'denied';
|
||||
}
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.baseUrl}/stores/${this.storeId}/check`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${this.serviceToken}`,
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
authorization_model_id: this.modelId,
|
||||
consistency: 'HIGHER_CONSISTENCY',
|
||||
tuple_key: { user, relation, object },
|
||||
}),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
});
|
||||
if (!response.ok || !response.body) return 'unavailable';
|
||||
const reader = response.body.getReader();
|
||||
try {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
total += part.value.byteLength;
|
||||
if (total > maxResponseBytes) {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
return 'unavailable';
|
||||
}
|
||||
chunks.push(part.value);
|
||||
}
|
||||
const result: unknown = JSON.parse(
|
||||
new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)),
|
||||
);
|
||||
if (
|
||||
!result ||
|
||||
typeof result !== 'object' ||
|
||||
Array.isArray(result) ||
|
||||
typeof (result as { allowed?: unknown }).allowed !== 'boolean'
|
||||
) {
|
||||
return 'unavailable';
|
||||
}
|
||||
return (result as { allowed: boolean }).allowed ? 'allowed' : 'denied';
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical environment variable names used across the fleet. Reads are
|
||||
* explicit (no implicit defaults) so a missing value is visible.
|
||||
*/
|
||||
export const OPENFGA_ENV = {
|
||||
baseUrl: 'OPENFGA_API_URL',
|
||||
storeId: 'OPENFGA_STORE_ID',
|
||||
modelId: 'OPENFGA_MODEL_ID',
|
||||
serviceToken: 'OPENFGA_AUTH_TOKEN',
|
||||
} as const;
|
||||
|
||||
export interface ProjectAccessOptions {
|
||||
/** The already-configured relationship reader, or undefined when OpenFGA is not configured. */
|
||||
relationships?: OpenFgaRelationships;
|
||||
/**
|
||||
* Optional extra policy (project status, capability, data-handling). It runs
|
||||
* only after the relationship check matched; a rejection is final.
|
||||
*/
|
||||
additionalPolicy?: (scope: ProjectRelationshipScope) => Promise<boolean> | boolean;
|
||||
}
|
||||
|
||||
/** Fail closed: only an explicit match with no policy objection is allowed. */
|
||||
export async function isProjectAccessAllowed(
|
||||
scope: ProjectRelationshipScope,
|
||||
options: ProjectAccessOptions,
|
||||
): Promise<boolean> {
|
||||
if (!options.relationships) return false;
|
||||
const result = await options.relationships.checkProject(scope);
|
||||
if (result !== 'relationships_match') return false;
|
||||
if (options.additionalPolicy) {
|
||||
try {
|
||||
return (await options.additionalPolicy(scope)) === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a relationship reader from a `NodeJS.ProcessEnv`-shaped object.
|
||||
* Returns `undefined` (fail closed) when any value is missing or invalid.
|
||||
*/
|
||||
export function openFgaFromEnv(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
fetchImpl?: typeof fetch,
|
||||
): OpenFgaRelationships | undefined {
|
||||
const baseUrl = env[OPENFGA_ENV.baseUrl];
|
||||
const storeId = env[OPENFGA_ENV.storeId];
|
||||
const modelId = env[OPENFGA_ENV.modelId];
|
||||
const serviceToken = env[OPENFGA_ENV.serviceToken];
|
||||
if (!baseUrl || !storeId || !modelId || !serviceToken) return undefined;
|
||||
try {
|
||||
return new OpenFgaRelationships({
|
||||
baseUrl,
|
||||
storeId,
|
||||
modelId,
|
||||
serviceToken,
|
||||
...(fetchImpl ? { fetchImpl } : {}),
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
Generated
+572
-375
File diff suppressed because it is too large
Load Diff
@@ -1,74 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Blocking guard for finding UI-09 (measured 2026-09-26): 0pt.app carried 82
|
||||
* `color-contrast` violations at axe-core 4.10.2 impact=serious — the estate's
|
||||
* single largest a11y defect. Every one of them came from the same shape: a
|
||||
* Tailwind alpha modifier on a muted text colour.
|
||||
*
|
||||
* Measured WCAG 2.2 contrast against the two theme backgrounds in
|
||||
* styles/globals.css (--background: oklch(1 0 0) light / oklch(0.145 0 0) dark,
|
||||
* --muted-foreground: oklch(0.556 0 0) / oklch(0.708 0 0)):
|
||||
*
|
||||
* text-muted-foreground 4.73:1 light 7.63:1 dark PASS (AA needs 4.5)
|
||||
* text-muted-foreground/70 2.71:1 4.20:1 FAIL
|
||||
* text-muted-foreground/60 2.29:1 3.37:1 FAIL
|
||||
* text-muted-foreground/50 1.96:1 2.67:1 FAIL
|
||||
* text-muted-foreground/40 1.69:1 2.11:1 FAIL
|
||||
* text-muted-foreground/10 1.13:1 1.13:1 FAIL
|
||||
*
|
||||
* The unmodified token passes in both themes, so the fix is simply never to
|
||||
* fade it. Purely decorative text is exempt — but it has to SAY so: the element
|
||||
* must carry `aria-hidden`, which is also what makes axe skip it. The single
|
||||
* remaining case (app/bestall/page.tsx, the oversized "01" masthead numeral) is
|
||||
* `aria-hidden` + `select-none` + `pointer-events-none` and is allowed by that
|
||||
* rule.
|
||||
*
|
||||
* This is a source-level guard, not a browser run. The full axe-core job that
|
||||
* UI-09 also asks for needs a build + serve in CI and is tracked separately;
|
||||
* until it exists this stops the regression at the shape that caused it.
|
||||
*/
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
|
||||
const ROOT = new URL('../..', import.meta.url).pathname.replace(/\/$/, '');
|
||||
const SKIP = new Set(['node_modules', '.next', '.git', 'dist', 'build', 'coverage', '.turbo']);
|
||||
const EXT = /\.(tsx|ts|jsx|js|css)$/;
|
||||
/** Alpha-modified colour utilities on TEXT. Background/border alphas are fine. */
|
||||
const PATTERN = /\btext-(muted-foreground|foreground|primary|secondary|accent-foreground|card-foreground|popover-foreground)\/\d+/g;
|
||||
|
||||
function walk(dir, out = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (SKIP.has(name)) continue;
|
||||
const p = join(dir, name);
|
||||
if (statSync(p).isDirectory()) walk(p, out);
|
||||
else if (EXT.test(name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const violations = [];
|
||||
for (const file of walk(ROOT)) {
|
||||
const src = readFileSync(file, 'utf8');
|
||||
const lines = src.split('\n');
|
||||
lines.forEach((line, i) => {
|
||||
for (const m of line.matchAll(PATTERN)) {
|
||||
// Decorative text is exempt when the element declares itself hidden to AT.
|
||||
// The attribute may sit on an earlier line of the same JSX element.
|
||||
const window = lines.slice(Math.max(0, i - 6), i + 1).join('\n');
|
||||
if (/\baria-hidden\b/.test(window)) continue;
|
||||
violations.push({ file: relative(ROOT, file), line: i + 1, token: m[0], text: line.trim() });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (violations.length) {
|
||||
console.error(`\n✗ ${violations.length} alpha-faded text colour(s) found — WCAG 2.2 AA 1.4.3 (finding UI-09).\n`);
|
||||
for (const v of violations) {
|
||||
console.error(` ${v.file}:${v.line} ${v.token}`);
|
||||
console.error(` ${v.text.slice(0, 160)}`);
|
||||
}
|
||||
console.error('\n Use the unmodified token (text-muted-foreground = 4.73:1 light / 7.63:1 dark).');
|
||||
console.error(' If the text really is decoration, put aria-hidden on the element.\n');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('✓ no alpha-faded text colours — WCAG 2.2 AA 1.4.3 contrast shape is clean (UI-09)');
|
||||
@@ -1,137 +0,0 @@
|
||||
#!/usr/bin/env -S node
|
||||
/**
|
||||
* scripts/vehiq-oltp-ingest/run.ts
|
||||
* ===================================
|
||||
* Thin CLI shim over src/ingestion/vehiq-oltp-ingest-runner.ts. All the
|
||||
* actual logic (connectors, the runner call, the checkpoint mapping) is in
|
||||
* that blocking-typechecked, tested `src/` module; this file only reads
|
||||
* `process.env`, wires real implementations, and prints a summary.
|
||||
*
|
||||
* TWO MODES, PREVIEW IS THE DEFAULT — this is the activation gate:
|
||||
*
|
||||
* VEHIQ_INGEST_MODE=preview (default)
|
||||
* One bounded read-only connect+discover+read per source, against
|
||||
* whatever checkpoint already exists. NEVER commits a checkpoint, NEVER
|
||||
* calls the sink, NEVER touches ClickHouse. Safe to run against real
|
||||
* production at any time — this is what proves "zero batches, zero
|
||||
* writes" without activating anything.
|
||||
*
|
||||
* VEHIQ_INGEST_MODE=run
|
||||
* The real, scheduled path: P062 runner, durable checkpoints, writes
|
||||
* landing in `opt_dataset_projection`. Requires DATABASE_URL (0pt's own
|
||||
* metadata store, for durable checkpoints) and the OPT_ANALYTICS_
|
||||
* CLICKHOUSE_* vars (the write target) to be set, or it refuses to run
|
||||
* rather than silently falling back to in-memory checkpoints or a
|
||||
* no-op sink — see docs/P070_VEHIQ_OLTP_EXTRACTOR.md "What activating
|
||||
* this in production actually requires".
|
||||
*
|
||||
* NO VEHIQ_SOURCE_DATABASE_URL AT ALL -> exits 0 having done nothing. This
|
||||
* is what makes the scheduled workflow (.gitea/workflows/vehiq-oltp-
|
||||
* ingest.yml) safe to leave enabled with no secret configured: cron fires,
|
||||
* the script logs "not configured", exits 0, no error, no alert.
|
||||
*/
|
||||
import {
|
||||
VEHIQ_OLTP_SOURCES,
|
||||
previewVehiqOltpSource,
|
||||
runVehiqOltpIngestion,
|
||||
} from "../../src/ingestion/vehiq-oltp-ingest-runner";
|
||||
import { makePostgresQueryImpl } from "../../src/connectors/postgres-query-impl";
|
||||
import { createIngestionRepository } from "../../src/repositories/ingestion-repository";
|
||||
import { SchemaRegistry } from "../../src/schema/schema-registry";
|
||||
import { LineageStore } from "../../src/lineage/lineage-store";
|
||||
import { ClickHouseAnalyticsEngine } from "../../src/analytics/engine/clickhouse-engine";
|
||||
import { projectionSink } from "../../src/ingestion/projection-sink";
|
||||
import type { AnalyticsIdentity } from "../../src/analytics/engine/siax-analytics-engine";
|
||||
|
||||
const TENANT_ID = process.env.VEHIQ_INGEST_TENANT_ID ?? "t_vehiq";
|
||||
const PROJECT_ID = process.env.VEHIQ_INGEST_PROJECT_ID ?? "vehiq";
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const sourceUrl = process.env.VEHIQ_SOURCE_DATABASE_URL;
|
||||
if (!sourceUrl) {
|
||||
console.log(
|
||||
JSON.stringify({ status: "not_configured", detail: "VEHIQ_SOURCE_DATABASE_URL is unset — nothing to do" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const mode = process.env.VEHIQ_INGEST_MODE === "run" ? "run" : "preview";
|
||||
const { query, close } = makePostgresQueryImpl({
|
||||
connectionString: sourceUrl,
|
||||
ssl: process.env.VEHIQ_SOURCE_PGSSL === "require" ? "require" : false,
|
||||
statementTimeoutMs: process.env.VEHIQ_SOURCE_STATEMENT_TIMEOUT_MS
|
||||
? Number(process.env.VEHIQ_SOURCE_STATEMENT_TIMEOUT_MS)
|
||||
: undefined,
|
||||
});
|
||||
|
||||
try {
|
||||
if (mode === "preview") {
|
||||
const repo = createIngestionRepository(process.env.DATABASE_URL);
|
||||
const results = [];
|
||||
for (const source of VEHIQ_OLTP_SOURCES) {
|
||||
results.push(
|
||||
await previewVehiqOltpSource(source, query, repo, {
|
||||
sourceId: "vehiq_oltp",
|
||||
tenantId: TENANT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
limit: 100,
|
||||
}),
|
||||
);
|
||||
}
|
||||
console.log(JSON.stringify({ status: "preview", mode, results }, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
// mode === "run" — the activation-gated real path.
|
||||
if (!process.env.DATABASE_URL) {
|
||||
throw new Error(
|
||||
"VEHIQ_INGEST_MODE=run requires DATABASE_URL (0pt's own metadata store, for durable checkpoints) — " +
|
||||
"refusing to run with in-memory checkpoints, which would silently re-read every row on every scheduled invocation",
|
||||
);
|
||||
}
|
||||
const chBaseUrl = process.env.OPT_ANALYTICS_CLICKHOUSE_BASE_URL;
|
||||
if (!chBaseUrl) {
|
||||
throw new Error(
|
||||
"VEHIQ_INGEST_MODE=run requires OPT_ANALYTICS_CLICKHOUSE_BASE_URL — refusing to run with no write target",
|
||||
);
|
||||
}
|
||||
|
||||
const repo = createIngestionRepository(process.env.DATABASE_URL);
|
||||
const schemas = new SchemaRegistry(repo);
|
||||
const lineage = new LineageStore(repo);
|
||||
const engine = new ClickHouseAnalyticsEngine({
|
||||
baseUrl: chBaseUrl,
|
||||
basicAuth: process.env.OPT_ANALYTICS_CLICKHOUSE_BASIC_AUTH,
|
||||
database: process.env.OPT_ANALYTICS_CLICKHOUSE_DATABASE ?? "opt_analytics",
|
||||
});
|
||||
const identity: AnalyticsIdentity = {
|
||||
tenant_id: TENANT_ID,
|
||||
project_id: PROJECT_ID,
|
||||
principal_id: "svc_vehiq_oltp_extractor",
|
||||
};
|
||||
const sink = projectionSink({
|
||||
engine,
|
||||
identity,
|
||||
datasetIdFor: (partitionKey) => `vehiq.${partitionKey}`,
|
||||
});
|
||||
|
||||
const summary = await runVehiqOltpIngestion({
|
||||
repo,
|
||||
schemas,
|
||||
lineage,
|
||||
sourceQuery: query,
|
||||
oltpSink: sink,
|
||||
dimensionSink: sink,
|
||||
tenantId: TENANT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
});
|
||||
console.log(JSON.stringify({ status: "ran", mode, summary }, null, 2));
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(JSON.stringify({ status: "error", detail: err instanceof Error ? err.message : String(err) }));
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -1,57 +0,0 @@
|
||||
/** Run with DOC0_CHECKOUT=/absolute/path "$DOC0_CHECKOUT/node_modules/.bin/tsx" scripts/verify-doc0-source-wire.ts.
|
||||
* In-memory test only: proves the current DOC0 response shape, not production auth or storage. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { isAbsolute, resolve } from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { Doc0SourceClient } from '../src/document-workbench/doc0-source-client';
|
||||
import { structureDocumentBatch } from '../src/document-workbench/structure-document-batch';
|
||||
import { exportValidatedBatch } from '../src/document-workbench/structured-batch';
|
||||
|
||||
async function main() {
|
||||
const checkout = process.env.DOC0_CHECKOUT;
|
||||
if (!checkout || !isAbsolute(checkout)) throw new Error('DOC0_CHECKOUT must name an absolute local checkout');
|
||||
const load = (path: string) => import(pathToFileURL(resolve(checkout, path)).href);
|
||||
const [{ buildServer }, { InMemoryDocumentStore }, { InMemoryDocumentVersionStore }, { InMemoryParseStore }, { segmentText }] = await Promise.all([
|
||||
load('src/api/app.ts'), load('src/domains/document/store.ts'), load('src/domains/document-version/store.ts'),
|
||||
load('src/domains/parse/store.ts'), load('src/parsing/segments.ts'),
|
||||
]);
|
||||
process.env.AUTH_ENFORCE = 'false';
|
||||
Object.assign(process.env, { NODE_ENV: 'test' });
|
||||
const documents = new InMemoryDocumentStore(), versions = new InMemoryDocumentVersionStore(), parses = new InMemoryParseStore();
|
||||
const input = { tenantId: 't-test', projectId: 'p-test', actorId: 'actor', requestId: 'req', receipt: {
|
||||
documentId: 'doc', versionId: 'v1', checksumSha256: createHash('sha256').update('fixture bytes').digest('hex'), pipelineStage: 'parsed',
|
||||
} };
|
||||
await documents.create({ tenantId: 't-test', projectId: 'p-test', documentId: 'doc', appId: 'test', displayName: 'fixture', documentType: 'unknown', classification: 'internal', tags: [], createdBy: 'actor' });
|
||||
await versions.append({ tenantId: 't-test', documentId: 'doc', versionId: 'v1', versionNumber: 1, checksumSha256: input.receipt.checksumSha256, sizeBytes: 13, mimeType: 'text/plain', st0reArtifactRef: 'fixture', pipelineStage: 'parsed', extractedMetadata: {}, customMetadata: {}, createdBy: 'actor' });
|
||||
const parts = segmentText('Acme AB\n\nInvoice 123');
|
||||
await parses.appendDocumentText({ tenantId: 't-test', documentId: 'doc', versionId: 'v1', documentTextId: 'txt', parserRunId: 'run', charCount: parts.charCount, segmentCount: parts.segments.length, segmentsTruncated: parts.truncated, textSha256: parts.textSha256 });
|
||||
await parses.appendTextSegments(parts.segments.map((s: object, i: number) => ({ ...s, tenantId: 't-test', documentId: 'doc', versionId: 'v1', documentTextId: 'txt', parserRunId: 'run', segmentId: `seg-${i}`, sourceVersionSha256: input.receipt.checksumSha256 })));
|
||||
const app = buildServer({ documentStore: documents, versionStore: versions, parseStore: parses });
|
||||
const fetchImpl: typeof fetch = async (url, init) => {
|
||||
const target = new URL(String(url));
|
||||
const out = await app.inject({ method: 'GET', url: target.pathname + target.search, headers: Object.fromEntries(new Headers(init?.headers).entries()) });
|
||||
return new Response(out.body, { status: out.statusCode, headers: { 'content-type': 'application/json' } });
|
||||
};
|
||||
try {
|
||||
const client = new Doc0SourceClient({ baseUrl: 'https://doc0.example', serviceToken: 'fixture', fetchImpl });
|
||||
const result = await client.read(input);
|
||||
if (result.sources.length !== 2 || result.sources[0]?.text !== 'Acme AB' || result.sources[1]?.text !== 'Invoice 123') throw new Error('DOC0 wire mismatch');
|
||||
const fields = [{ name: 'value', type: 'string' as const, required: true }];
|
||||
const records = result.sources.map((source) => ({ value: { value: source.text }, evidence: [{ field: 'value', sourceId: source.id, start: 0, end: source.text.length, transform: 'exact' }] }));
|
||||
const request = {
|
||||
context: { tenantId: 't-test', projectId: 'p-test', actorId: 'actor', capability: 'inf0.complete', correlationId: 'req' },
|
||||
admission: { tenantId: 't-test', projectId: 'p-test', jobId: 'j', modelId: 'local_only', dataClass: 'high', maxInputTokens: 200, maxOutputTokens: 100, maximumCredits: 5 },
|
||||
policy: { tenantId: 't-test', projectId: 'p-test', allowedModelIds: ['local_only'], allowedDataClasses: ['high'], destination: 'internal' as const, externalTransferAllowed: false, maxInputTokens: 200, maxOutputTokens: 100 },
|
||||
reservation: { tenantId: 't-test', projectId: 'p-test', jobId: 'j', status: 'reserved' as const, credits: 5 },
|
||||
};
|
||||
const structured = await structureDocumentBatch({ request, fields, sources: result.sources, instructions: 'Extract values', countTokens: async () => 50,
|
||||
gateway: { complete: async () => ({ status: 'model_stopped', content: JSON.stringify({ records }), modelExecuted: 'fixture', providerKind: 'local', promptTokens: 50, completionTokens: 20, totalTokens: 70 }) } });
|
||||
if (structured.status !== 'mechanically_validated') throw new Error('model fixture evidence failed');
|
||||
const exported = exportValidatedBatch({ format: 'json', fields, sources: result.sources, records: structured.records });
|
||||
if (exported.status !== 'ready' || JSON.parse(exported.content).length !== 2) throw new Error('export fixture failed');
|
||||
const revision = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: checkout, encoding: 'utf8' }).trim();
|
||||
console.log(`DOC0 ${revision}: actual route through 0pt source and validated export; in-memory stores, test auth and model fixture`);
|
||||
} finally { await app.close(); }
|
||||
}
|
||||
main().catch((error: unknown) => { console.error(error); process.exitCode = 1; });
|
||||
@@ -169,18 +169,17 @@ async def sources_for(market: str):
|
||||
async def vehicle(plate: str):
|
||||
try:
|
||||
v = await rdw_vehicle(plate)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail="vehicle source unavailable") from exc
|
||||
return {**(v or {"vehicle": None}), "source_status": "ok"}
|
||||
except Exception:
|
||||
v = None
|
||||
return v or {"vehicle": None}
|
||||
|
||||
|
||||
@app.get("/screen")
|
||||
async def screen(q: str):
|
||||
try:
|
||||
result = await opensanctions_screen(q)
|
||||
return {**result, "source_status": "ok"}
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail="screening source unavailable") from exc
|
||||
return await opensanctions_screen(q)
|
||||
except Exception:
|
||||
return {"matches": [], "source": "opensanctions"}
|
||||
|
||||
|
||||
@app.post("/estimates")
|
||||
|
||||
@@ -268,10 +268,9 @@ async def rdw_vehicle(kenteken: str) -> dict[str, Any] | None:
|
||||
url = f"https://opendata.rdw.nl/resource/m9d7-ebf2.json?kenteken={plate}"
|
||||
async with _client() as c:
|
||||
r = await c.get(url)
|
||||
r.raise_for_status()
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
arr = r.json()
|
||||
if not isinstance(arr, list) or any(not isinstance(item, dict) for item in arr):
|
||||
raise ValueError("invalid RDW response")
|
||||
if not arr:
|
||||
return None
|
||||
d = arr[0]
|
||||
@@ -297,13 +296,9 @@ async def opensanctions_screen(name: str) -> dict[str, Any]:
|
||||
url = "https://api.opensanctions.org/search/default"
|
||||
async with _client() as c:
|
||||
r = await c.get(url, params={"q": name, "limit": 5})
|
||||
r.raise_for_status()
|
||||
payload = r.json()
|
||||
if not isinstance(payload, dict) or not isinstance(payload.get("results"), list) or any(
|
||||
not isinstance(item, dict) for item in payload["results"]
|
||||
):
|
||||
raise ValueError("invalid OpenSanctions response")
|
||||
results = payload["results"]
|
||||
if r.status_code != 200:
|
||||
return {"matches": [], "source": "opensanctions"}
|
||||
results = r.json().get("results", [])
|
||||
return {
|
||||
"source": "opensanctions",
|
||||
"matches": [{"name": x.get("caption"), "score": x.get("score"), "schema": x.get("schema")} for x in results],
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
"""A failed or malformed source must never become a verified empty result."""
|
||||
import httpx
|
||||
import pytest
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from orchestrator import main
|
||||
from sources.connectors import opensanctions_screen, rdw_vehicle
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("status", [403, 429, 500])
|
||||
async def test_source_http_failure_raises(status):
|
||||
with respx.mock:
|
||||
respx.get("https://api.opensanctions.org/search/default").respond(status)
|
||||
respx.get("https://opendata.rdw.nl/resource/m9d7-ebf2.json").respond(status)
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
await opensanctions_screen("example")
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
await rdw_vehicle("AB123")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_malformed_and_valid_empty_are_distinct():
|
||||
with respx.mock:
|
||||
screen = respx.get("https://api.opensanctions.org/search/default").respond(200, json={})
|
||||
vehicle = respx.get("https://opendata.rdw.nl/resource/m9d7-ebf2.json").respond(200, json={})
|
||||
with pytest.raises(ValueError):
|
||||
await opensanctions_screen("example")
|
||||
with pytest.raises(ValueError):
|
||||
await rdw_vehicle("AB123")
|
||||
screen.respond(200, json={"results": []})
|
||||
vehicle.respond(200, json=[])
|
||||
assert (await opensanctions_screen("example"))["matches"] == []
|
||||
assert await rdw_vehicle("AB123") is None
|
||||
|
||||
|
||||
def test_routes_return_503_on_source_failure_and_mark_verified_empty(monkeypatch):
|
||||
async def failed(*args):
|
||||
raise RuntimeError("fixture failure")
|
||||
async def empty_screen(*args):
|
||||
return {"source": "opensanctions", "matches": []}
|
||||
async def empty_vehicle(*args):
|
||||
return None
|
||||
monkeypatch.setattr(main, "_INTERNAL_TOKEN", "")
|
||||
monkeypatch.setattr(main, "opensanctions_screen", failed)
|
||||
monkeypatch.setattr(main, "rdw_vehicle", failed)
|
||||
client = TestClient(main.app)
|
||||
assert client.get('/screen?q=example').status_code == 503
|
||||
assert client.get('/vehicles/AB123').status_code == 503
|
||||
monkeypatch.setattr(main, "opensanctions_screen", empty_screen)
|
||||
monkeypatch.setattr(main, "rdw_vehicle", empty_vehicle)
|
||||
assert client.get('/screen?q=example').json() == {"source": "opensanctions", "source_status": "ok", "matches": []}
|
||||
assert client.get('/vehicles/AB123').json() == {"vehicle": None, "source_status": "ok"}
|
||||
@@ -1,72 +0,0 @@
|
||||
{
|
||||
"$schema": "https://git.siax.io/sax3l/siax-standard/raw/branch/main/schema/siax.repo.schema.json",
|
||||
"repo": "0pt",
|
||||
"standardVersion": "2.0",
|
||||
"category": "platform",
|
||||
"subcategory": "data-os",
|
||||
"appId": "0PT",
|
||||
"capabilityPrefix": "0pt",
|
||||
"packageName": "@siax/0pt",
|
||||
"owner": "SIAX Technology AB",
|
||||
"codeowners": [
|
||||
"@sax3l"
|
||||
],
|
||||
"lifecycle": "active",
|
||||
"operationalState": "running",
|
||||
"gitHost": "git.siax.io",
|
||||
"node": null,
|
||||
"domains": [
|
||||
{
|
||||
"fqdn": "0pt.app",
|
||||
"env": "prod",
|
||||
"purpose": "Next.js edge plane -- marketing, catalog, order flow, customer/admin portal, capability API. LIVE på SIAX-flottan via signerad release-kedja (probe 2026-09-22: HTTP 200, /api/ready ready:true, db ok, engine ok). Tidigare Vercel 402-probe 2026-09-07 är föråldrad — cutover till flottan genomförd.",
|
||||
"registrar": "verifierad via release-kedjan (se docs/runbook/) — BACKLOG P0-15 kvarstår för registrar-autentisering"
|
||||
},
|
||||
{
|
||||
"fqdn": "api.0pt.app",
|
||||
"env": "prod",
|
||||
"purpose": "Target API host (Caddy) -- documented target in contracts/openapi.yaml servers list, never live. Probe 2026-09-07 `curl -sSI https://api.0pt.app/health` returned HTTP 404 with server: Vercel and x-vercel-error: DEPLOYMENT_NOT_FOUND",
|
||||
"registrar": "EJ VERIFIERAT fran detta repo -- se docs/architecture/ARCHITECTURE.md SS6/SS9 (BACKLOG P0-15)"
|
||||
}
|
||||
],
|
||||
"consumes": [
|
||||
"CL0UD",
|
||||
"ST0RE",
|
||||
"N0D",
|
||||
"AUD0",
|
||||
"INF0"
|
||||
],
|
||||
"consumedBy": [],
|
||||
"children": [
|
||||
{
|
||||
"path": "app",
|
||||
"purpose": "Next.js edge plane -- UI + capability/order/payment API route handlers",
|
||||
"lifecycle": "active"
|
||||
},
|
||||
{
|
||||
"path": "services/api",
|
||||
"purpose": "FastAPI data engine (orchestrator + workers) -- legal sourcing chain, estimates/orders/screening",
|
||||
"lifecycle": "active"
|
||||
},
|
||||
{
|
||||
"path": "services/scrapers",
|
||||
"purpose": "Scraper stack including WAF-bypass code -- kept per a dated, attributed account-owner decision under active review; NOT part of the compliant sourcing chain (see SECURITY.md, CLAUDE.md SS1)",
|
||||
"lifecycle": "active"
|
||||
},
|
||||
{
|
||||
"path": "packages/schemas",
|
||||
"purpose": "Shared JSON Schema definitions for 0pt data contracts (dataset/iceberg/lineage/signal/rate-policy)",
|
||||
"lifecycle": "active"
|
||||
}
|
||||
],
|
||||
"replacesSaaS": [
|
||||
"Apollo",
|
||||
"Cognism",
|
||||
"ZoomInfo",
|
||||
"Clearbit"
|
||||
],
|
||||
"contracts": {
|
||||
"openapi": "contracts/openapi.yaml"
|
||||
},
|
||||
"decoupled": false
|
||||
}
|
||||
+1
-1
@@ -123,7 +123,7 @@
|
||||
},
|
||||
"reliability": {
|
||||
"backupFrequency": "none",
|
||||
"provenRestore": true
|
||||
"provenRestore": false
|
||||
},
|
||||
"engines": [
|
||||
"postgres",
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"id": "pe-0pt-f6a29da7e586",
|
||||
"repo": "0pt",
|
||||
"evidenceType": "deploy-log",
|
||||
"result": "pass",
|
||||
"verifiedAt": "2026-09-22T18:52:42Z",
|
||||
"verifiedBy": "coolify-deployment-db (application_deployment_queues, senaste finished-deploy)",
|
||||
"proofRef": "coolify://deployment/75me1uneekzvjevgqeewcovm",
|
||||
"sourceSha": "f6a29da7e58601ce426181b11ea4959e90f07dcc"
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"id": "pe-sbom-0pt-f6a29da7e586",
|
||||
"repo": "0pt",
|
||||
"evidenceType": "sbom",
|
||||
"result": "pass",
|
||||
"verifiedAt": "2026-09-23T16:22:09Z",
|
||||
"verifiedBy": "syft (estate-kampanj issue #76, skannad vid deployad commit)",
|
||||
"proofRef": "siax/sbom/sbom-0pt-f6a29da7e586.json",
|
||||
"sourceSha": "f6a29da7e58601ce426181b11ea4959e90f07dcc",
|
||||
"tool": "syft",
|
||||
"sbomFormat": "cyclonedx-json"
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,4 +0,0 @@
|
||||
# 0pt — cosign-signeringskedjan (2026-09-29)
|
||||
|
||||
Prod-imagen git.cloud.siax.io/sax3l/0pt:prod-6bbd333a22 (sha256:7cbc75bb363c1ee47f8aa86cfbaf996e648e4a0c0c5c5f79a09b87fef93db03b) är cosign-signerad
|
||||
med nyckelparet vars pubkey ligger här. Privata nyckeln raderad efter signering.
|
||||
@@ -1,4 +0,0 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELOI331jmeMp5t0XySt0ls4XH0Msr
|
||||
2k7neTq+QtRAOuLL4b5Nj3xdHLpDBjaX82zI6XXbJRixh0TeWrp0Y0SF3Q==
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"id": "sb-0pt-f6a29da7e586",
|
||||
"repo": "0pt",
|
||||
"commitSha": "f6a29da7e58601ce426181b11ea4959e90f07dcc",
|
||||
"branch": "main",
|
||||
"producedAt": "2026-09-22T18:52:42Z"
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
sonar.projectKey=0pt
|
||||
sonar.host.url=https://sonar.siax.io
|
||||
sonar.exclusions=**/node_modules/**,**/dist/**,**/build/**,**/.next/**,**/out/**,**/coverage/**,**/__pycache__/**,**/*.min.js,**/.venv/**,**/.pnpm-store/**,**/.opt-blobs/**,**/.data/**
|
||||
@@ -1,64 +0,0 @@
|
||||
-- 015_order_status_check.sql — Kanonisk orderstatus (ADR-0002, C3 2026-09-29)
|
||||
--
|
||||
-- Guardar `orders.status` (fri text sedan sql/001_init.sql line ~92) mot den
|
||||
-- kanoniska unionen i lib/order-flow.ts (ORDER_STATUSES). Denna fil KÖRS EJ
|
||||
-- automatiskt av deploy — Simon kör den manuellt mot prod efter harvest.
|
||||
--
|
||||
-- KÖRORDNING (DoD §17 backup-städ, §33 migreringsordning, §35 restore-drill):
|
||||
-- 1. BACKUP FÖRST: pg_dump "$DATABASE_URL" -t orders -Fc -f orders-pre-015.dump
|
||||
-- (och verifiera att restore-drillen har körts nyligen — §35).
|
||||
-- 2. HARVEST-PREFLIGHT (läs-only, körs före fas A):
|
||||
-- SELECT status, COUNT(*) FROM orders GROUP BY status ORDER BY 2 DESC;
|
||||
-- Alla rader MÅSTE ligga i listan nedan. Finns okända statusar:
|
||||
-- AVBRYT — mappa dem först (UPDATE ... WHERE status = '<okänd>') i en
|
||||
-- egen, granskad migrering; kör aldrig fas A med okända rader kvar.
|
||||
-- 3. FAS A ( TRANSACTIONEN NEDAN — ADD CONSTRAINT ... NOT VALID ):
|
||||
-- tar bara ett kort ACCESS EXCLUSIVE-lås vid själva katalogändringen,
|
||||
-- validerar INTE befintliga rader, blockerar inte skrivningar längre tid.
|
||||
-- 4. FAS B (SEPARAT session/transaktion — VALIDATE CONSTRAINT):
|
||||
-- BEGIN; SET lock_timeout = '5s';
|
||||
-- ALTER TABLE orders VALIDATE CONSTRAINT order_status_check;
|
||||
-- COMMIT;
|
||||
-- VALIDATE tar SHARE UPDATE EXCLUSIVE (skrivningar tillåtna); med
|
||||
-- lock_timeout stänger vi ute långa låsköer. Misslyckas fas B: retry.
|
||||
--
|
||||
-- Listan är kod-SSOT: håll synkroniserad med ORDER_STATUSES i lib/order-flow.ts.
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- Preflight-guard: fas A nekar om okända statusar finns (fail-closed).
|
||||
-- (SELECT ... FOR UPDATE-stil låsning behövs ej — NOT VALID-constrainten
|
||||
-- läser inga rader; vi vill bara neka körning vid dirt-data.)
|
||||
DO $preflight$
|
||||
DECLARE
|
||||
unknown_rows bigint;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO unknown_rows
|
||||
FROM orders
|
||||
WHERE status NOT IN ('draft', 'quoted', 'in_production', 'review', 'accepted', 'delivered', 'cancelled');
|
||||
IF unknown_rows > 0 THEN
|
||||
RAISE EXCEPTION
|
||||
'order_status_check preflight: % rader med status utanför den kanoniska unionen — kör harvest (SELECT status, COUNT(*) FROM orders GROUP BY status), mappa okända statusar, KÖR EJ fas A', unknown_rows;
|
||||
END IF;
|
||||
END
|
||||
$preflight$;
|
||||
|
||||
-- Rapportera (loggar) okända statusar om preflighten ändå passerar tom:
|
||||
SELECT status, COUNT(*) AS n
|
||||
FROM orders
|
||||
WHERE status NOT IN ('draft', 'quoted', 'in_production', 'review', 'accepted', 'delivered', 'cancelled')
|
||||
GROUP BY status;
|
||||
-- (0 rader = grönt; >0 rader = ovanstående DO-block har redan avbrutit.)
|
||||
|
||||
ALTER TABLE orders
|
||||
ADD CONSTRAINT order_status_check
|
||||
CHECK (status IN ('draft', 'quoted', 'in_production', 'review', 'accepted', 'delivered', 'cancelled'))
|
||||
NOT VALID;
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- FAS B körs i EGEN session (se körordning steg 4) — kommenterad här för att
|
||||
-- den ALDRIG ska ligga i samma transaktion som fas A:
|
||||
-- BEGIN; SET lock_timeout = '5s';
|
||||
-- ALTER TABLE orders VALIDATE CONSTRAINT order_status_check;
|
||||
-- COMMIT;
|
||||
@@ -1,16 +0,0 @@
|
||||
-- 016: order notes — persisted collaboration state för admin-orders
|
||||
-- (@siax/collaboration-kernelns första produktkonsument, spår C).
|
||||
-- Varje note är en kernel-CollaborationOperation: `clock` är Lamport-klockan,
|
||||
-- `version` är optimistisk samtidighetskontroll (stale skrivning -> HTTP 409).
|
||||
CREATE TABLE IF NOT EXISTS order_notes (
|
||||
note_id TEXT PRIMARY KEY,
|
||||
order_id TEXT NOT NULL,
|
||||
tenant_id TEXT,
|
||||
author_id TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
clock BIGINT NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS order_notes_order_idx ON order_notes(order_id);
|
||||
@@ -1,41 +0,0 @@
|
||||
-- Internal credit ledger foundation; no public payment or credit-grant route.
|
||||
CREATE TABLE IF NOT EXISTS opt_credit_accounts (
|
||||
tenant_id text PRIMARY KEY CHECK (length(tenant_id) > 0),
|
||||
available bigint NOT NULL DEFAULT 0 CHECK (available >= 0 AND available <= 9007199254740991),
|
||||
reserved bigint NOT NULL DEFAULT 0 CHECK (reserved >= 0 AND reserved <= 9007199254740991)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS opt_credit_reservations (
|
||||
tenant_id text NOT NULL REFERENCES opt_credit_accounts(tenant_id),
|
||||
reservation_id text NOT NULL CHECK (length(reservation_id) > 0),
|
||||
amount bigint NOT NULL CHECK (amount > 0 AND amount <= 9007199254740991),
|
||||
status text NOT NULL CHECK (status IN ('reserved', 'settled', 'released')),
|
||||
settled_amount bigint CHECK (settled_amount >= 0 AND settled_amount <= amount),
|
||||
PRIMARY KEY (tenant_id, reservation_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS opt_credit_events (
|
||||
event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
tenant_id text NOT NULL REFERENCES opt_credit_accounts(tenant_id),
|
||||
idempotency_key text NOT NULL CHECK (length(idempotency_key) > 0),
|
||||
kind text NOT NULL CHECK (kind IN ('verified_payment', 'reserve', 'settle', 'release')),
|
||||
amount bigint NOT NULL CHECK (amount >= 0 AND amount <= 9007199254740991),
|
||||
reference text NOT NULL CHECK (length(reference) > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (tenant_id, idempotency_key)
|
||||
);
|
||||
-- A single external payment cannot fund multiple tenants or grants.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS opt_credit_verified_payment_reference
|
||||
ON opt_credit_events(reference) WHERE kind = 'verified_payment';
|
||||
|
||||
-- Server-owned price snapshot. Never read price or credits from PAY0 metadata.
|
||||
CREATE TABLE IF NOT EXISTS opt_credit_purchases (
|
||||
tenant_id text NOT NULL CHECK (length(tenant_id) > 0),
|
||||
purchase_id text NOT NULL CHECK (length(purchase_id) > 0),
|
||||
checkout_session_id text NOT NULL UNIQUE CHECK (length(checkout_session_id) > 0),
|
||||
amount_minor bigint NOT NULL CHECK (amount_minor > 0 AND amount_minor <= 9007199254740991),
|
||||
currency text NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),
|
||||
credits bigint NOT NULL CHECK (credits > 0 AND credits <= 9007199254740991),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (tenant_id, purchase_id)
|
||||
);
|
||||
@@ -1,23 +0,0 @@
|
||||
-- Internal coordination only: raw bytes remain in the document storage service.
|
||||
CREATE TABLE opt_document_upload_attempts (
|
||||
tenant_id text NOT NULL CHECK (length(tenant_id) BETWEEN 1 AND 256),
|
||||
project_id text NOT NULL CHECK (length(project_id) BETWEEN 1 AND 256),
|
||||
actor_id text NOT NULL CHECK (length(actor_id) BETWEEN 1 AND 256),
|
||||
attempt_id text NOT NULL CHECK (length(attempt_id) BETWEEN 1 AND 256),
|
||||
source_sha256 text NOT NULL CHECK (source_sha256 ~ '^[0-9a-f]{64}$'),
|
||||
source_size_bytes bigint NOT NULL CHECK (source_size_bytes > 0 AND source_size_bytes <= 9007199254740991),
|
||||
request_fingerprint text NOT NULL CHECK (request_fingerprint ~ '^[0-9a-f]{64}$'),
|
||||
state text NOT NULL CHECK (state IN ('prepared', 'dispatch_started')),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
PRIMARY KEY (tenant_id, attempt_id)
|
||||
);
|
||||
ALTER TABLE opt_document_upload_attempts ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE opt_document_upload_attempts FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY opt_document_upload_attempt_scope ON opt_document_upload_attempts
|
||||
USING (tenant_id = current_setting('app.opt_tenant_id', true)
|
||||
AND project_id = current_setting('app.opt_project_id', true)
|
||||
AND actor_id = current_setting('app.opt_actor_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.opt_tenant_id', true)
|
||||
AND project_id = current_setting('app.opt_project_id', true)
|
||||
AND actor_id = current_setting('app.opt_actor_id', true));
|
||||
@@ -1,25 +0,0 @@
|
||||
-- The GUC is transaction-local and supplied only by trusted server code.
|
||||
-- RLS is a defense against missing tenant predicates, not authentication.
|
||||
ALTER TABLE opt_credit_accounts ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE opt_credit_accounts FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY opt_credit_accounts_tenant ON opt_credit_accounts
|
||||
USING (tenant_id = current_setting('app.opt_credit_tenant_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.opt_credit_tenant_id', true));
|
||||
|
||||
ALTER TABLE opt_credit_reservations ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE opt_credit_reservations FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY opt_credit_reservations_tenant ON opt_credit_reservations
|
||||
USING (tenant_id = current_setting('app.opt_credit_tenant_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.opt_credit_tenant_id', true));
|
||||
|
||||
ALTER TABLE opt_credit_events ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE opt_credit_events FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY opt_credit_events_tenant ON opt_credit_events
|
||||
USING (tenant_id = current_setting('app.opt_credit_tenant_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.opt_credit_tenant_id', true));
|
||||
|
||||
ALTER TABLE opt_credit_purchases ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE opt_credit_purchases FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY opt_credit_purchases_tenant ON opt_credit_purchases
|
||||
USING (tenant_id = current_setting('app.opt_credit_tenant_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.opt_credit_tenant_id', true));
|
||||
@@ -113,15 +113,10 @@ export class GraphMailboxAdapter {
|
||||
return this.cachedToken.token;
|
||||
}
|
||||
|
||||
// Graph-API:t är genuint ostrukturerat JSON (value-array med fri form);
|
||||
// full typning av hela Graph-ytan är egen insats — any här är medveten
|
||||
// och avgränsad till denna adapter (eslint-undantag med skäl, DoD §13).
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private async get(path: string): Promise<any> {
|
||||
const token = await this.getToken();
|
||||
const url = path.startsWith("http") ? path : `${GRAPH_BASE}${path}`;
|
||||
const res = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Graph-JSON är genuint ostrukturerat; full Graph-typning är egen insats
|
||||
const json: any = await res.json();
|
||||
if (!res.ok) {
|
||||
throw new Error(`Graph GET ${path} -> ${json.error?.code || res.status}: ${json.error?.message || ""}`);
|
||||
@@ -155,7 +150,7 @@ export class GraphMailboxAdapter {
|
||||
receivedAt: m.receivedDateTime || null,
|
||||
senderName: m.from?.emailAddress?.name || null,
|
||||
senderEmail: m.from?.emailAddress?.address || null,
|
||||
toRecipients: (m.toRecipients || []).map((r: { emailAddress?: { address?: string } }) => r.emailAddress?.address).filter(Boolean),
|
||||
toRecipients: (m.toRecipients || []).map((r: any) => r.emailAddress?.address).filter(Boolean),
|
||||
subject: m.subject || null,
|
||||
bodyPreview: m.bodyPreview || null,
|
||||
bodyText: m.body?.content ? stripHtml(m.body.content) : m.bodyPreview || null,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user