L3 Auftragsimport: Prüfmaske, Upload, API und Lane-Bericht
- /imports: Upload per Drag & Drop/Dateiauswahl mit Fortschritt, Liste mit Status, Neu verarbeiten
- /imports/[id]: Originaldokument + Prüfmaske (Kunde, Objekt, Ansprechpartner, Auftrag, Positionen),
unsichere Felder markiert, Kunden-/Objektentscheidung, Bestätigen/Verwerfen
- Datei-Route für die Vorschau, Server Actions (moduleGuard("imports"))
- API: POST /api/v1/work-orders/import, GET /api/v1/imports/[id], POST /api/v1/imports/[id]/confirm
- Texte messages/{de,en}/imports.json, Bericht docs/craftvia/lanes/import.md
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import { moduleGuard } from "@/server/action-guard";
|
||||
import { storage } from "@/server/storage/adapter";
|
||||
import { ctxFromGuard } from "@/server/services/context";
|
||||
import { getImportFile } from "@/server/services/imports/queries";
|
||||
|
||||
/**
|
||||
* GET /imports/[id]/file — original document of an import for the review mask preview.
|
||||
* Authorisation: session + DB-authoritative permission import:write + module + document
|
||||
* visibility (getImportFile). Unknown/foreign ids → 404. `?download=1` forces a download.
|
||||
* Inline delivery only for the allowlisted types stored by the import (PDF/JPEG/PNG) and
|
||||
* only framable by the own origin.
|
||||
*/
|
||||
const INLINE = new Set(["application/pdf", "image/jpeg", "image/png"]);
|
||||
|
||||
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
let file: { storageKey: string; mimeType: string; fileName: string };
|
||||
try {
|
||||
const ctx = ctxFromGuard(await moduleGuard("imports")("import:write"));
|
||||
const { id } = await params;
|
||||
file = await getImportFile(ctx, id);
|
||||
} catch {
|
||||
return new Response("Nicht gefunden.", { status: 404 });
|
||||
}
|
||||
|
||||
const content = await storage.get(file.storageKey);
|
||||
if (!content) return new Response("Datei nicht verfügbar.", { status: 404 });
|
||||
|
||||
const download = new URL(req.url).searchParams.get("download") === "1";
|
||||
const inline = !download && INLINE.has(file.mimeType);
|
||||
const asciiName = file.fileName.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
|
||||
const headers = new Headers({
|
||||
"Content-Type": INLINE.has(file.mimeType) ? file.mimeType : "application/octet-stream",
|
||||
"Content-Disposition": `${inline ? "inline" : "attachment"}; filename="${asciiName}"; filename*=UTF-8''${encodeURIComponent(file.fileName)}`,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Security-Policy": "frame-ancestors 'self'",
|
||||
"X-Frame-Options": "SAMEORIGIN",
|
||||
});
|
||||
if (content.size != null) headers.set("Content-Length", String(content.size));
|
||||
return new Response(content.stream, { headers });
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
import { ArrowLeft, CheckCircle2, Download, ExternalLink, Info, Loader2, XCircle } from "lucide-react";
|
||||
import { requireSession } from "@/server/auth";
|
||||
import { dbForTenant } from "@/server/db";
|
||||
import { hasPermission } from "@/server/rbac";
|
||||
import { ServiceError, type ServiceCtx } from "@/server/services/context";
|
||||
import { getImportDetail } from "@/server/services/imports/queries";
|
||||
import { confirmImportAction, discardImportAction, retryImportAction, searchCustomersAction } from "@/server/actions/imports/imports";
|
||||
import { PageHead } from "@/components/mockup-ui";
|
||||
import { ImportStatusPill } from "@/components/imports/status-pill";
|
||||
import { AutoRefresh } from "@/components/imports/auto-refresh";
|
||||
import { DiscardImportButton, RetryImportButton } from "@/components/imports/job-actions";
|
||||
import { ImportReviewForm } from "@/components/imports/review-form";
|
||||
import { extractionToForm, formFieldMeta } from "@/lib/imports/review";
|
||||
import { IMPORT_IN_PROGRESS } from "@/lib/imports/status";
|
||||
|
||||
/** /imports/[id] — review mask: original document left, form right (spec §9.6, US-002/003). */
|
||||
export default async function ImportDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const session = await requireSession();
|
||||
if (!hasPermission(session, "import:write")) redirect("/imports");
|
||||
const { id } = await params;
|
||||
const t = await getTranslations("imports");
|
||||
const locale = await getLocale();
|
||||
const ctx: ServiceCtx = {
|
||||
db: dbForTenant(session.user.tenantId),
|
||||
tenantId: session.user.tenantId,
|
||||
userId: session.user.id,
|
||||
permissions: new Set(session.user.permissions),
|
||||
};
|
||||
|
||||
let detail;
|
||||
try {
|
||||
detail = await getImportDetail(ctx, id);
|
||||
} catch (err) {
|
||||
if (err instanceof ServiceError) notFound();
|
||||
throw err;
|
||||
}
|
||||
|
||||
const fmt = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" });
|
||||
const fileUrl = `/imports/${detail.id}/file`;
|
||||
const isPdf = detail.document?.mimeType === "application/pdf";
|
||||
const fields = detail.extraction.fields;
|
||||
const top = detail.customerCandidates[0];
|
||||
const topSite = top ? detail.siteCandidates.find((s) => s.customerId === top.customerId) : undefined;
|
||||
const inProgress = IMPORT_IN_PROGRESS.includes(detail.status);
|
||||
const errorKey = detail.errorMessage && t.has(`errors.${detail.errorMessage}`) ? `errors.${detail.errorMessage}` : null;
|
||||
const correctionCount =
|
||||
detail.corrections && typeof detail.corrections === "object" && "fields" in detail.corrections
|
||||
? Object.keys((detail.corrections as { fields?: Record<string, unknown> }).fields ?? {}).length
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<main className="flex-1 p-4 sm:p-6">
|
||||
<AutoRefresh active={inProgress} />
|
||||
<Link href="/imports" className="inline-flex min-h-11 items-center gap-1.5 text-[12.5px] font-semibold text-muted-foreground hover:text-foreground">
|
||||
<ArrowLeft className="size-4" aria-hidden /> {t("detail.back")}
|
||||
</Link>
|
||||
<PageHead
|
||||
crumb={t("title")}
|
||||
title={detail.document?.fileName ?? t("title")}
|
||||
sub={t("detail.meta", { file: detail.document?.fileName ?? "—", date: fmt.format(detail.createdAt), user: detail.importedByName ?? "—" })}
|
||||
actions={<ImportStatusPill status={detail.status} label={t(`status.${detail.status}`)} />}
|
||||
/>
|
||||
|
||||
<div className="grid gap-5 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)]">
|
||||
{/* Original document */}
|
||||
<section aria-labelledby="imp-preview" className="lg:sticky lg:top-20 lg:self-start">
|
||||
<div className="shadow-card rounded-xl border bg-card p-3">
|
||||
<div className="mb-2 flex flex-wrap items-center justify-between gap-2 px-1">
|
||||
<h2 id="imp-preview" className="font-heading text-[15px] font-semibold">{t("detail.preview")}</h2>
|
||||
<div className="flex gap-3 text-[12.5px] font-semibold">
|
||||
<a href={fileUrl} target="_blank" rel="noreferrer" className="inline-flex min-h-11 items-center gap-1 text-[var(--ui-primary)] hover:underline">
|
||||
<ExternalLink className="size-3.5" aria-hidden /> {t("detail.openNewTab")}
|
||||
</a>
|
||||
<a href={`${fileUrl}?download=1`} className="inline-flex min-h-11 items-center gap-1 text-[var(--ui-primary)] hover:underline">
|
||||
<Download className="size-3.5" aria-hidden /> {t("detail.download")}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{isPdf ? (
|
||||
<iframe src={fileUrl} title={t("detail.previewTitle")} className="h-[55vh] w-full rounded-lg border bg-muted lg:h-[calc(100vh-11rem)]" />
|
||||
) : (
|
||||
// eslint-disable-next-line @next/next/no-img-element -- authenticated same-origin file, no optimisation
|
||||
<img src={fileUrl} alt={t("detail.previewTitle")} className="max-h-[calc(100vh-11rem)] w-full rounded-lg border object-contain" />
|
||||
)}
|
||||
{detail.extractionModel && <p className="mt-2 px-1 text-[12px] text-muted-foreground">{t("detail.model", { model: detail.extractionModel })}</p>}
|
||||
</div>
|
||||
<details className="shadow-card mt-3 rounded-xl border bg-card p-3">
|
||||
<summary className="min-h-11 cursor-pointer content-center px-1 font-heading text-sm font-semibold">{t("detail.extractedText")}</summary>
|
||||
<pre className="mt-2 max-h-80 overflow-auto whitespace-pre-wrap px-1 text-[12px]">{detail.extractedText || t("detail.noText")}</pre>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
{/* Status / review mask */}
|
||||
<section aria-labelledby="imp-review">
|
||||
<h2 id="imp-review" className="mb-1 font-heading text-[17px] font-semibold">{t("review.title")}</h2>
|
||||
|
||||
{inProgress && (
|
||||
<div className="shadow-card flex items-start gap-3 rounded-xl border bg-card p-5" role="status">
|
||||
<Loader2 className="mt-0.5 size-5 shrink-0 animate-spin text-[var(--info)]" aria-hidden />
|
||||
<p className="text-sm">{t("detail.processing")}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail.status === "failed" && (
|
||||
<div className="shadow-card space-y-3 rounded-xl border border-[var(--risk)] bg-card p-5" role="alert">
|
||||
<p className="flex items-center gap-2 font-heading text-sm font-semibold text-[var(--risk)]">
|
||||
<XCircle className="size-4" aria-hidden /> {t("detail.failed")}
|
||||
</p>
|
||||
<p className="text-[13px] text-muted-foreground">
|
||||
{errorKey ? t(errorKey) : t("detail.failedDetail", { message: detail.errorMessage ?? "—" })}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<RetryImportButton action={retryImportAction.bind(null, detail.id)} />
|
||||
<DiscardImportButton action={discardImportAction.bind(null, detail.id)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail.status === "confirmed" && (
|
||||
<div className="shadow-card space-y-2 rounded-xl border border-[var(--ok)] bg-card p-5" role="status">
|
||||
<p className="flex items-center gap-2 font-heading text-sm font-semibold text-[var(--ok)]">
|
||||
<CheckCircle2 className="size-4" aria-hidden /> {t("detail.confirmed", { number: detail.createdWorkOrder?.number ?? "—" })}
|
||||
</p>
|
||||
<p className="text-[13px] text-muted-foreground">{t("detail.corrections", { count: correctionCount })}</p>
|
||||
{detail.createdWorkOrder && (
|
||||
<Link href={`/work-orders/${detail.createdWorkOrder.id}`} className="inline-flex min-h-11 items-center rounded-lg bg-[var(--ui-accent)] px-4 font-heading text-[13px] font-semibold text-[var(--ui-accent-foreground)] hover:opacity-90">
|
||||
{t("detail.openWorkOrder")}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail.status === "discarded" && (
|
||||
<div className="shadow-card flex items-start gap-3 rounded-xl border bg-card p-5" role="status">
|
||||
<Info className="mt-0.5 size-5 shrink-0 text-muted-foreground" aria-hidden />
|
||||
<p className="text-sm">{t("detail.discarded")}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail.status === "review_required" && (
|
||||
<>
|
||||
<p className="mb-3 text-[13px] text-muted-foreground">
|
||||
{detail.extraction.hints.some((h) => h.code === "manual_entry") ? t("review.manualEntry") : t("review.intro")}
|
||||
</p>
|
||||
<ImportReviewForm
|
||||
initial={extractionToForm(fields, { customerId: top && top.score >= 0.6 ? top.customerId : null, siteId: top && top.score >= 0.6 ? topSite?.siteId ?? null : null })}
|
||||
meta={formFieldMeta(fields)}
|
||||
hints={detail.extraction.hints.filter((h) => h.code !== "manual_entry")}
|
||||
customerCandidates={detail.customerCandidates}
|
||||
siteCandidates={detail.siteCandidates}
|
||||
confirmAction={confirmImportAction.bind(null, detail.id)}
|
||||
searchAction={searchCustomersAction}
|
||||
/>
|
||||
<div className="mt-3">
|
||||
<DiscardImportButton action={discardImportAction.bind(null, detail.id)} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user