feat(orders): CSV-import admin-yta — första riktiga ImportWizard-värden (C8) #145
@@ -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<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
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 { 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).
|
||||
|
||||
export const MAX_IMPORT_ROWS = 500;
|
||||
const MAX_CSV_CHARS = 1_000_000;
|
||||
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 });
|
||||
}
|
||||
if (csv.length > MAX_CSV_CHARS) {
|
||||
return NextResponse.json({ error: { code: "csv_too_large", message: `CSV större än ${MAX_CSV_CHARS} tecken` } }, { status: 413 });
|
||||
}
|
||||
try {
|
||||
const { report, rows, headerError } = validateImport(csv);
|
||||
if (headerError) {
|
||||
return NextResponse.json({ error: { code: "bad_header", message: headerError }, report }, { status: 400 });
|
||||
}
|
||||
if (rows.length > MAX_IMPORT_ROWS) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
+8
-7
@@ -52,11 +52,11 @@
|
||||
"@radix-ui/react-toggle-group": "1.1.19",
|
||||
"@radix-ui/react-tooltip": "1.2.16",
|
||||
"@siax/0pt-decision": "workspace:*",
|
||||
"@siax/charts": "^0.4.0",
|
||||
"@siax/charts": "^0.5.0",
|
||||
"@siax/config": "^0.2.1",
|
||||
"@siax/contracts": "^0.10.0",
|
||||
"@siax/tokens": "^0.1.2",
|
||||
"@siax/ui": "^0.12.0",
|
||||
"@siax/ui": "^0.14.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -79,7 +79,8 @@
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vaul": "^1.1.2",
|
||||
"zod": "3.25.76"
|
||||
"zod": "3.25.76",
|
||||
"@siax/import-export": "^0.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.15.0",
|
||||
@@ -99,9 +100,9 @@
|
||||
"vitest": "^3.2.7"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
"sharp",
|
||||
"esbuild"
|
||||
]
|
||||
"overrides": {
|
||||
"@siax/ui>@siax/contracts": "0.10.0",
|
||||
"@siax/ui>@siax/import-export": "0.2.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+28
-291
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* C8: tests for POST /api/orders/import — the symmetric counterpart of the
|
||||
* våg-3.4 CSV export and the first real product host of the @siax/ui
|
||||
* ImportWizard kernel. Follows the suite pattern of calling the route handler
|
||||
* directly with a hand-built NextRequest and mocked auth/store/audit.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const mockOwner = { owner: { tenantId: "tenant-test", subject: "buyer-test" } };
|
||||
const requireOrderOwnerMock = vi.fn();
|
||||
vi.mock("@/src/auth/require-order-owner", () => ({
|
||||
requireOrderOwner: (...args: unknown[]) => requireOrderOwnerMock(...args),
|
||||
}));
|
||||
|
||||
const createOrderMock = vi.fn();
|
||||
vi.mock("@/lib/orders-store", () => ({
|
||||
createOrder: (...args: unknown[]) => createOrderMock(...args),
|
||||
}));
|
||||
|
||||
const ingestEventMock = vi.fn().mockResolvedValue({});
|
||||
vi.mock("@/src/clients/aud0-client", () => ({
|
||||
createAud0Client: () => ({ ingestEvent: ingestEventMock }),
|
||||
}));
|
||||
|
||||
import { POST, parseCsv, validateImport, MAX_IMPORT_ROWS } from "@/app/api/orders/import/route";
|
||||
|
||||
function postReq(body: unknown, withAuth = true): NextRequest {
|
||||
requireOrderOwnerMock.mockResolvedValue(withAuth ? mockOwner : { response: NextResponse.json({ error: "OPT_UNAUTHENTICATED" }, { status: 401 }) });
|
||||
return new NextRequest(new URL("/api/orders/import", "http://localhost"), {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
headers: withAuth ? { authorization: "Bearer x" } : {},
|
||||
});
|
||||
}
|
||||
|
||||
const HEADER = "flow,service_type,type,volume,frequency,markets";
|
||||
|
||||
function csv(lines: string[]): string {
|
||||
return [HEADER, ...lines].join("\r\n") + "\r\n";
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
createOrderMock.mockReset();
|
||||
ingestEventMock.mockClear();
|
||||
createOrderMock.mockImplementation(async (flow: string, config: unknown, _key: unknown, owner: { tenantId: string }) => ({
|
||||
order: { order_id: `ord_${createOrderMock.mock.calls.length}`, flow, status: "draft", config, tenant_id: owner.tenantId },
|
||||
replayed: false,
|
||||
}));
|
||||
});
|
||||
|
||||
describe("parseCsv (server-parsed, RFC 4180, no eval)", () => {
|
||||
it("parses quoted fields with doubled quotes", () => {
|
||||
const { rows } = parseCsv('flow,markets\r\ncustom,"A;""B,C"""\r\n');
|
||||
expect(rows[0].flow).toBe("custom");
|
||||
expect(rows[0].markets).toBe('A;"B,C"');
|
||||
});
|
||||
|
||||
it("rejects unknown header columns (fail-closed, never silently dropped)", () => {
|
||||
const { headerError } = parseCsv("flow,evil\r\ncustom,x\r\n");
|
||||
expect(headerError).toMatch(/Okänd kolumn: evil/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateImport — kernel + host rules", () => {
|
||||
it("reports missing required flow as missing_required", () => {
|
||||
const { report } = validateImport(csv([",icp,Bolag,10,Engångs,SE"]));
|
||||
expect(report.errorCount).toBeGreaterThan(0);
|
||||
expect(report.errors.some((e) => e.code === "missing_required")).toBe(true);
|
||||
});
|
||||
|
||||
it("reports bad host fields with row/field/code", () => {
|
||||
const { report } = validateImport(csv(["nope,icp,Bolag,-5,Engångs,SE"]));
|
||||
const fields = report.errors.map((e) => e.field).sort();
|
||||
expect(fields).toContain("flow");
|
||||
expect(fields).toContain("volume");
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/orders/import", () => {
|
||||
it("happy path: execute imports all valid rows through createOrder with the verified owner + emits AUD0", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(["custom,icp,Bolag,10,Engångs,SE", "catalog,icp,Fordon,2,Engångs,", "subscription,,Beslutsfattare,50,Veckovis,SE;NO"]) }));
|
||||
expect(r.status).toBe(200);
|
||||
const body = await r.json();
|
||||
expect(body.imported).toBe(3);
|
||||
expect(body.errors).toHaveLength(0);
|
||||
expect(body.order_ids).toHaveLength(3);
|
||||
expect(createOrderMock).toHaveBeenCalledTimes(3);
|
||||
expect(createOrderMock.mock.calls[0][3]).toEqual({ tenantId: "tenant-test", subject: "buyer-test" });
|
||||
expect(createOrderMock.mock.calls[0][1]).toMatchObject({ service_type: "icp", type: "Bolag", volume: 10, frequency: "Engångs", markets: ["SE"] });
|
||||
expect(createOrderMock.mock.calls[2][1]).toMatchObject({ markets: ["SE", "NO"] });
|
||||
expect(ingestEventMock).toHaveBeenCalledTimes(1);
|
||||
expect(ingestEventMock.mock.calls[0][0]).toMatchObject({ event_type: "0pt.orders.import", tenant_id: "tenant-test", risk_level: "L2" });
|
||||
});
|
||||
|
||||
it("partial success: failing rows are reported per row and never created; passing rows import", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(["custom,icp,Bolag,10,Engångs,SE", "bogus_flow,icp,Bolag,10,Engångs,SE", "catalog,icp,Bolag,notanumber,Engångs,SE"]) }));
|
||||
expect(r.status).toBe(200);
|
||||
const body = await r.json();
|
||||
expect(body.imported).toBe(1);
|
||||
expect(body.errorCount).toBe(2);
|
||||
const badFlow = body.errors.find((e: { field: string }) => e.field === "flow");
|
||||
const badVol = body.errors.find((e: { field: string }) => e.field === "volume");
|
||||
expect(badFlow.row).toBe(2);
|
||||
expect(badVol.row).toBe(3);
|
||||
expect(createOrderMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("validate/dry_run never write (createOrder not called)", async () => {
|
||||
const r1 = await POST(postReq({ mode: "validate", csv: csv(["custom,icp,Bolag,10,Engångs,SE"]) }));
|
||||
expect(r1.status).toBe(200);
|
||||
const b1 = await r1.json();
|
||||
expect(b1.validRows).toBe(1);
|
||||
expect(b1.would_import).toBe(1);
|
||||
const r2 = await POST(postReq({ mode: "dry_run", csv: csv(["custom,icp,Bolag,10,Engångs,SE"]) }));
|
||||
expect(r2.status).toBe(200);
|
||||
expect(createOrderMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fail-closed auth: no principal → 401 and createOrder is never reached", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(["custom,icp,Bolag,10,Engångs,SE"]) }, false));
|
||||
expect(r.status).toBe(401);
|
||||
expect(createOrderMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("row cap: more than MAX_IMPORT_ROWS data rows → 413, no writes", async () => {
|
||||
const lines = Array.from({ length: MAX_IMPORT_ROWS + 1 }, () => "custom,icp,Bolag,10,Engångs,SE");
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(lines) }));
|
||||
expect(r.status).toBe(413);
|
||||
expect(createOrderMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("unknown header → 400 fail-closed", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: "flow,evil\r\ncustom,x\r\n" }));
|
||||
expect(r.status).toBe(400);
|
||||
const body = await r.json();
|
||||
expect(body.error.code).toBe("bad_header");
|
||||
});
|
||||
|
||||
it("empty/missing csv → 400", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: " " }));
|
||||
expect(r.status).toBe(400);
|
||||
});
|
||||
|
||||
it("execute-time creation failure is reported per row without aborting the batch", async () => {
|
||||
createOrderMock.mockImplementationOnce(async () => {
|
||||
throw new Error("db down");
|
||||
});
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(["custom,icp,Bolag,10,Engångs,SE", "catalog,icp,Bolag,1,Engångs,SE"]) }));
|
||||
expect(r.status).toBe(200);
|
||||
const body = await r.json();
|
||||
expect(body.imported).toBe(1);
|
||||
expect(body.errors[0].row).toBe(1);
|
||||
expect(body.errors[0].message).toContain("db down");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* C8: SSR-render proof that the host can render the @siax/ui ImportWizard over
|
||||
* the @siax/import-export runtime store (the exact packages the admin import
|
||||
* page uses). Node environment — react-dom/server, no DOM needed.
|
||||
*/
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
// ImportWizard subscribes to the runtime store via useSyncExternalStore, which
|
||||
// demands getServerSnapshot under react-dom/server. For a static render proof
|
||||
// the snapshot read is enough — reactivity is the browser's concern.
|
||||
vi.mock("react", async (importOriginal) => {
|
||||
const React = await importOriginal<typeof import("react")>();
|
||||
return { ...React, useSyncExternalStore: ((_subscribe: unknown, getSnapshot: () => unknown) => getSnapshot()) as typeof React.useSyncExternalStore };
|
||||
});
|
||||
import { createElement } from "react";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { ImportWizard } from "@siax/ui";
|
||||
import { createImportRunStore } from "@siax/import-export";
|
||||
import { createImportJob } from "@siax/contracts/import-export";
|
||||
|
||||
function makeStore(rows: Record<string, string>[]) {
|
||||
return createImportRunStore({
|
||||
job: createImportJob({
|
||||
id: "test-import",
|
||||
tenantId: "tenant-test",
|
||||
entity: "orders",
|
||||
format: "csv",
|
||||
source: { system: "0pt-admin", channel: "web" },
|
||||
createdAt: "2026-09-30T00:00:00Z",
|
||||
}),
|
||||
rows,
|
||||
});
|
||||
}
|
||||
|
||||
describe("ImportWizard renders over the runtime store (host integration)", () => {
|
||||
it("empty store → explicit empty state with the pipeline <ol>", () => {
|
||||
const html = renderToString(
|
||||
createElement(ImportWizard, { store: makeStore([]), onExecute: async () => {} }),
|
||||
);
|
||||
expect(html).toContain("<ol");
|
||||
expect(html.length).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
it("rows present → pipeline steps render; mapped stage shows mapping table", () => {
|
||||
const store = makeStore([{ flow: "custom", service_type: "icp", type: "Bolag", volume: "10", frequency: "Engångs", markets: "SE" }]);
|
||||
store.detect();
|
||||
let html = renderToString(createElement(ImportWizard, { store, columns: [{ source: "flow", target: "flow" }], onExecute: async () => {} }));
|
||||
expect(html).toContain("<ol");
|
||||
expect(html).toContain("aria-current=\"step\"");
|
||||
store.map({ columns: [{ source: "flow", target: "flow", required: true }] });
|
||||
html = renderToString(createElement(ImportWizard, { store, onExecute: async () => {} }));
|
||||
expect(html).toContain("flow");
|
||||
});
|
||||
|
||||
it("failed store renders the failure report with role=alert", () => {
|
||||
const store = makeStore([{ flow: "custom" }]);
|
||||
store.detect();
|
||||
store.fail("Servern avvisade exekveringen");
|
||||
const html = renderToString(createElement(ImportWizard, { store, onExecute: async () => {} }));
|
||||
expect(html).toContain("alert");
|
||||
expect(html).toContain("Servern avvisade exekveringen");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user