feat(orders): CSV-import admin-yta — första riktiga ImportWizard-värden (C8)
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
CI (SIAX Cloud) / security (push) Successful in 22s
Security Scan (SIAX Cloud) / security (push) Successful in 22s
masterplan-lock / check (push) Successful in 31s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 6s
CI (SIAX Cloud) / security (pull_request) Successful in 18s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 20s
CI (SIAX Cloud) / quality (push) Successful in 1m1s
CI (SIAX Cloud) / integration (pull_request) Successful in 30s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m56s
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
CI (SIAX Cloud) / security (push) Successful in 22s
Security Scan (SIAX Cloud) / security (push) Successful in 22s
masterplan-lock / check (push) Successful in 31s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 6s
CI (SIAX Cloud) / security (pull_request) Successful in 18s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 20s
CI (SIAX Cloud) / quality (push) Successful in 1m1s
CI (SIAX Cloud) / integration (pull_request) Successful in 30s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m56s
Symmetrisk mot våg 3.4 CSV-export: POST /api/orders/import (validate | dry_run | execute) + /admin/import som renderar @siax/ui ImportWizard (0.14.0) över @siax/import-export runtime (0.2.0). - Servern är enda auktoritet: RFC4180-parse (ingen eval), omvalidering via frysta @siax/contracts-kerneln (validateRows) + hostregler, exekvering genom BEFINTLIG orderlogik (createOrder, tenant-guardad). - Fail-closed: 401 utan principal, 400 okänd header, 413 vid radtak (500), per-rad-atomsäkra inserts — felrad kan aldrig skada OK-rader. - Partiell import: OK-rader skapas, felrader rapporteras per rad (row/field/code). AUD0-audit via 0pts enda producer-boundary (durable outbox under DATABASE_URL). - Reload-persistens: efter execute läses /api/orders om och de nya raderna listas på sidan. - Tester: 12 route-test (happy, partial, auth fail-closed, tak, no-write validate, header, quoting, rad-fel mitt i batch) + 3 SSR-render-test av ImportWizard över runtime-storen. - Deps: @siax/ui ^0.14.0, @siax/charts ^0.5.0, @siax/import-export ^0.2.0; pnpm-overrides till contracts 0.10.0 / import-export 0.2.0 (ui 0.14.0 deklarerar 0.11.0/0.2.1 som ännu ej publicerats).
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user