diff --git a/.gitea/workflows/cd.yml b/.gitea/workflows/cd.yml index 51b9583..db27b2a 100644 --- a/.gitea/workflows/cd.yml +++ b/.gitea/workflows/cd.yml @@ -21,6 +21,7 @@ on: 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 diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 05ed9df..6cb4b42 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -24,6 +24,7 @@ on: jobs: quality: runs-on: ubuntu-latest + timeout-minutes: 30 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -37,6 +38,13 @@ 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) @@ -69,6 +77,7 @@ 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 @@ -219,6 +228,7 @@ jobs: # measurable blind spot into declared policy. security: runs-on: ubuntu-latest + timeout-minutes: 15 steps: - uses: actions/checkout@v4 - name: Install Trivy @@ -227,3 +237,31 @@ jobs: - name: Trivy scan (vuln + secrets -- BLOCKING, fails on HIGH/CRITICAL) run: | trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 . + + 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" diff --git a/.gitea/workflows/masterplan-lock.yml b/.gitea/workflows/masterplan-lock.yml index b3bc95a..2a8d813 100644 --- a/.gitea/workflows/masterplan-lock.yml +++ b/.gitea/workflows/masterplan-lock.yml @@ -15,6 +15,7 @@ on: jobs: check: runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@v4 - name: Masterplan lock check diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index e4f5684..b86713d 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -50,41 +50,75 @@ 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). - SIAX_TEMPLATES_REF: main - SIAX_TEMPLATES_PINNED_SHA: a401880aa19a9bf99fbd796c0be481db2705fcaa + # + # 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_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-clone-at-runtime mechanism this repo's OLD + # Same authenticated-fetch-at-runtime mechanism this repo's OLD # release.yml already used SIAX_CI_TOKEN for (the evidence-commit - # push this PR deletes) -- see .siax/hooks/G17.sh's header for why + # push a prior PR deleted) -- see .siax/hooks/G17.sh's header for why # NOT a `uses:` reusable workflow / submodule / vendored copy. Fails - # closed if the branch has moved past the exact commit this adapter - # was reviewed against. - - name: Fetch siax-templates G17 reference (pinned) + # 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) env: SIAX_CI_TOKEN: ${{ secrets.SIAX_CI_TOKEN }} run: | set -euo pipefail rm -rf "$SIAX_TEMPLATES_DIR" - git clone --quiet --branch "$SIAX_TEMPLATES_REF" \ - "https://oauth2:${SIAX_CI_TOKEN}@git.siax.io/${SIAX_TEMPLATES_REPO}.git" "$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 actual_sha="$(git -C "$SIAX_TEMPLATES_DIR" rev-parse HEAD)" if [ "$actual_sha" != "$SIAX_TEMPLATES_PINNED_SHA" ]; then - 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." + 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." 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, verified)" + echo "siax-templates G17 reference @ $actual_sha (pinned commit, checked out directly)" - name: Resolve SHA + tag (never :latest) id: sha @@ -142,3 +176,4 @@ 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. + diff --git a/.gitea/workflows/security.yml b/.gitea/workflows/security.yml index bcd987c..94f3eaa 100644 --- a/.gitea/workflows/security.yml +++ b/.gitea/workflows/security.yml @@ -28,6 +28,7 @@ on: jobs: security: runs-on: ubuntu-latest + timeout-minutes: 15 steps: - uses: actions/checkout@v4 - name: Install Trivy diff --git a/.gitea/workflows/vehiq-oltp-ingest.yml b/.gitea/workflows/vehiq-oltp-ingest.yml new file mode 100644 index 0000000..3ddfe45 --- /dev/null +++ b/.gitea/workflows/vehiq-oltp-ingest.yml @@ -0,0 +1,44 @@ +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 diff --git a/.siax/contract-lock.json b/.siax/contract-lock.json new file mode 100644 index 0000000..01ddb62 --- /dev/null +++ b/.siax/contract-lock.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "1.0", + "repo": "0pt", + "generatedAt": "2026-09-23T21:12:27.075Z", + "standard": { + "canonicalRemote": "https://git.siax.io/sax3l/siax-standard.git", + "ref": "main", + "sha": "0000000000000000000000000000000000000000" + }, + "repoRole": "LEGACY", + "schemaBundleDigest": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "ownerRegistryDigest": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "productFirewallDigest": "sha256:0000000000000000000000000000000000000000000000000000000000000000" +} diff --git a/.siax/decision-usage.yaml b/.siax/decision-usage.yaml new file mode 100644 index 0000000..99d9df8 --- /dev/null +++ b/.siax/decision-usage.yaml @@ -0,0 +1,8 @@ +# GENERATED by siax-doctor repo-contract --apply (repo-contract-gate/v2 — 2026-09-23T21:12:27.075Z); template-fil, redigera via siax-templates - EJ handredigering. Saknas en rad här upptäcks det av RC-lagret. +# decision-usage — 0pt +schemaVersion: siax.decision-usage/v1 +repo: 0pt +generatedAt: 2026-09-23T21:12:27.075Z +owners: [simon@siax.io] +decisions: [] +notes: GENERATED stub - tomt ar den arliga 'inga beslut materialiserade'-formen; varje beslut under osakerhet listas har (required/advisory/shadow), produkter anropar aldrig Jev/providers direkt. diff --git a/.siax/des1gn-consumer.yaml b/.siax/des1gn-consumer.yaml new file mode 100644 index 0000000..87b56e9 --- /dev/null +++ b/.siax/des1gn-consumer.yaml @@ -0,0 +1,12 @@ +# GENERATED by siax-doctor repo-contract --apply (repo-contract-gate/v2 — 2026-09-23T21:12:27.075Z); template-fil, redigera via siax-templates - EJ handredigering. Saknas en rad här upptäcks det av RC-lagret. +# des1gn-consumer — 0pt (GENERATED neutral baseline; anpassa via siax-templates) +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)' +localPrimitives: [] +notes: GENERATED stub - tomt ar den arliga baseline-formen; konsumerade kanoniska DES1GN-paket (pinned) listas under consumes, kvarvarande lokala primitives motiveras i notes. diff --git a/.siax/dev-profile.yaml b/.siax/dev-profile.yaml new file mode 100644 index 0000000..659ac66 --- /dev/null +++ b/.siax/dev-profile.yaml @@ -0,0 +1,24 @@ +# GENERATED by siax-doctor repo-contract --apply (repo-contract-gate/v2 — 2026-09-23T21:12:27.074Z); template-fil, redigera via siax-templates - EJ handredigering. Saknas en rad här upptäcks det av RC-lagret. +# dev-profile — 0pt (neutral, kanoniskt giltig baseline; anpassa per repo via siax-templates) +schemaVersion: siax.dev-profile/v1 +repoType: library +riskDefault: L2 +capabilities: + stateful: false + deployable: false + publicApi: false + aiEnabled: false + userFacing: false + tenantScoped: false + handlesSecrets: false +gates: + realDatabase: required_when_changed + migrationUpgrade: required_when_changed + e2e: required_when_changed + accessibility: required_when_changed + visualRegression: required_when_changed + mutation: required_when_changed + performance: required_when_changed +release: + owner: sax3l + strategy: same-digest-promotion diff --git a/.siax/feature-packs.yaml b/.siax/feature-packs.yaml new file mode 100644 index 0000000..dbb54f5 --- /dev/null +++ b/.siax/feature-packs.yaml @@ -0,0 +1,9 @@ +# GENERATED by siax-doctor repo-contract --apply (repo-contract-gate/v2 — 2026-09-23T21:12:27.075Z); template-fil, redigera via siax-templates - EJ handredigering. Saknas en rad här upptäcks det av RC-lagret. +# feature-packs — 0pt +schemaVersion: siax.feature-packs/v1 +repo: 0pt +generatedAt: 2026-09-23T21:12:27.075Z +packs: +permissions: [] +states: [] +notes: GENERATED stub - tomt ar den arliga baseline-formen; varje pack binder 'version owner backendOwner' (kanonisk backend-agare, aldrig kopierad implementation). diff --git a/.siax/hooks/G17.sh b/.siax/hooks/G17.sh index ae34de4..029c7e6 100644 --- a/.siax/hooks/G17.sh +++ b/.siax/hooks/G17.sh @@ -70,9 +70,10 @@ # 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_REF=main + -# SIAX_TEMPLATES_PINNED_SHA, which refuses to run if main has moved past -# the pin). +# `.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). set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" diff --git a/.siax/hooks/README.md b/.siax/hooks/README.md index 1100b8c..74318bc 100644 --- a/.siax/hooks/README.md +++ b/.siax/hooks/README.md @@ -45,10 +45,15 @@ 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`'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. +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`. ## G20 (live-digest-equality) -- deliberately not wired yet diff --git a/.siax/product-blueprint.yaml b/.siax/product-blueprint.yaml new file mode 100644 index 0000000..6700b3f --- /dev/null +++ b/.siax/product-blueprint.yaml @@ -0,0 +1,14 @@ +# GENERATED by siax-doctor repo-contract --apply (repo-contract-gate/v2 — 2026-09-23T21:12:27.075Z); template-fil, redigera via siax-templates - EJ handredigering. Saknas en rad här upptäcks det av RC-lagret. +# product-blueprint — 0pt +schemaVersion: siax.product-blueprint/v1 +repo: 0pt +generatedAt: 2026-09-23T21:12:27.075Z +productClass: unspecified +archetypes: [unspecified] +surfaces: [web] +users: [] +packs: +decisions: [] +visualDna: siax +compliance: [] +notes: GENERATED stub - unspecified-vardena ar arliga platshaltere tills riktig klassning (PROMPT-031); blueprinet ska driva factory, tests, release och live verification. diff --git a/.siax/reuse-manifest.yaml b/.siax/reuse-manifest.yaml new file mode 100644 index 0000000..c080d7f --- /dev/null +++ b/.siax/reuse-manifest.yaml @@ -0,0 +1,9 @@ +# GENERATED by siax-doctor repo-contract --apply (repo-contract-gate/v2 — 2026-09-23T21:12:27.075Z); template-fil, redigera via siax-templates - EJ handredigering. Saknas en rad här upptäcks det av RC-lagret. +# reuse-manifest — 0pt +schemaVersion: siax.reuse-manifest/v1 +repo: 0pt +generatedAt: 2026-09-23T21:12:27.075Z +policy: reuse-before-build +consumes: [] +rebuilt: [] +notes: GENERATED stub - tomma listor ar giltiga; konsumtion av plattforms-capabilities och VARJE medveten aterbyggnad (med motivering) listas har. diff --git a/.siax/skills-lock.json b/.siax/skills-lock.json new file mode 100644 index 0000000..2c3df20 --- /dev/null +++ b/.siax/skills-lock.json @@ -0,0 +1,7 @@ +{ + "schemaVersion": "siax.skills-lock/v1", + "repo": "0pt", + "generatedAt": "2026-09-23T21:12:27.075Z", + "skills": [], + "notes": "GENERATED stub - tomt ar den arliga 'inga skills deklarerade'-formen; fyll i via siax-templates." +} diff --git a/.siax/state-flow-manifest.yaml b/.siax/state-flow-manifest.yaml new file mode 100644 index 0000000..4c7f977 --- /dev/null +++ b/.siax/state-flow-manifest.yaml @@ -0,0 +1,9 @@ +# GENERATED by siax-doctor repo-contract --apply (repo-contract-gate/v2 — 2026-09-23T21:12:27.075Z); template-fil, redigera via siax-templates - EJ handredigering. Saknas en rad här upptäcks det av RC-lagret. +# state-flow-manifest — 0pt +schemaVersion: siax.state-flow-manifest/v1 +repo: 0pt +generatedAt: 2026-09-23T21:12:27.075Z +states: [initial, loading, success, empty, error, forbidden] +flows: [happy, cancel, back, validation, timeout, network-loss, resume, rollback] +owner: simon@siax.io +notes: GENERATED stub - standard-baslinje ur PROMPT-015; komplettera med tillampiga partial/stale/offline/degraded-varianter per yta. diff --git a/app/admin/import/page.tsx b/app/admin/import/page.tsx new file mode 100644 index 0000000..f89363c --- /dev/null +++ b/app/admin/import/page.tsx @@ -0,0 +1,223 @@ +"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[] { + 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 = {}; + 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(null); + const [store, setStore] = useState(null); + const [serverReport, setServerReport] = useState(null); + const [serverError, setServerError] = useState(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 ( +
+

Importera ordrar

+

+ CSV med kolumnerna: {IMPORT_COLUMNS.join(", ")}. Endast flow är obligatorisk + (catalog | custom | subscription). Parsering och validering sker på servern — + filen laddas inte upp förrän ett steg körs. +

+ { + const f = e.target.files?.[0]; + if (f) void onFile(f); + }} + /> + {store && ( +
+ ({ 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} + /> +
+ )} + {serverError && ( +

+ {serverError} +

+ )} + {serverReport && (serverReport.errorCount ?? 0) > 0 && ( +
+

Felrader (serverns rapport)

+
    + {(serverReport.errors ?? []).map((e, i) => ( +
  • + Rad {e.row} · {e.field} · {e.code} + {e.message ? ` — ${e.message}` : ""} +
  • + ))} +
+
+ )} + {recentOrders && ( +
+

Importerade ordrar (lästa från /api/orders efter import)

+ {recentOrders.length === 0 ? ( +

Inga importerade ordrar hittades vid reload.

+ ) : ( +
    + {recentOrders.map((o) => ( +
  • + {o.order_id} — {o.flow} — {o.status} +
  • + ))} +
+ )} +
+ )} +
+ ); +} diff --git a/app/admin/notes/page.tsx b/app/admin/notes/page.tsx new file mode 100644 index 0000000..97a0de4 --- /dev/null +++ b/app/admin/notes/page.tsx @@ -0,0 +1,238 @@ +"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(null); + const [orderId, setOrderId] = useState(""); + const [notes, setNotes] = useState(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 ( + + + {offlineMode && ( +
+ Offline-läge aktivt: inga anteckningar skickas till servern. Utkast bevaras lokalt — + ingen tyst förlust. +
+ )} + + {loadError ? ( + orderId && loadNotes(orderId)} /> + ) : orders === null ? ( + + ) : orders.length === 0 ? ( + + ) : ( +
+ + + {orderId === "" ? ( + + ) : notes === null ? ( + + ) : notes.length === 0 ? ( + + ) : ( +
    + {notes.map((n) => ( +
  • +
    + + {n.author_id} · v{n.version} · klocka {n.clock} + + {new Date(n.updated_at).toLocaleString("sv-SE")} +
    + {editing?.note.note_id === n.note_id ? ( +
    +