From d5a9356bd3e26edb8eab65f0535277480b1bdad4 Mon Sep 17 00:00:00 2001 From: Maaxxs <61059039+MaaxxsDev@users.noreply.github.com> Date: Mon, 19 Oct 2026 18:13:17 +0200 Subject: [PATCH] DHL-Versand: Labels aus der Bestellung, Sendungsverfolgung im Bestellstatus Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL --- .../20261019155908_dhl/migration.sql | 5 + prisma/schema.prisma | 4 + .../(shop)/konto/bestellung/[number]/page.tsx | 9 +- .../(panel)/bestellungen/[id]/label/route.ts | 21 ++ .../admin/(panel)/bestellungen/[id]/page.tsx | 9 +- src/app/admin/(panel)/bestellungen/actions.ts | 60 ++++ src/app/admin/(panel)/dhl/actions.ts | 62 ++++ src/app/admin/(panel)/dhl/page.tsx | 71 +++++ src/app/admin/(panel)/produkte/[id]/page.tsx | 1 + src/app/admin/(panel)/produkte/actions.ts | 1 + src/app/admin/(panel)/produkte/neu/page.tsx | 2 +- src/components/admin/DhlCard.tsx | 69 ++++ src/components/admin/ProductForm.tsx | 6 +- src/components/admin/nav.ts | 1 + src/components/shop/DhlTracking.tsx | 27 ++ src/lib/dhl.ts | 298 ++++++++++++++++++ src/styles/shop.css | 11 + 17 files changed, 652 insertions(+), 5 deletions(-) create mode 100644 prisma/migrations/20261019155908_dhl/migration.sql create mode 100644 src/app/admin/(panel)/bestellungen/[id]/label/route.ts create mode 100644 src/app/admin/(panel)/dhl/actions.ts create mode 100644 src/app/admin/(panel)/dhl/page.tsx create mode 100644 src/components/admin/DhlCard.tsx create mode 100644 src/components/shop/DhlTracking.tsx create mode 100644 src/lib/dhl.ts diff --git a/prisma/migrations/20261019155908_dhl/migration.sql b/prisma/migrations/20261019155908_dhl/migration.sql new file mode 100644 index 0000000..d328dcb --- /dev/null +++ b/prisma/migrations/20261019155908_dhl/migration.sql @@ -0,0 +1,5 @@ +-- AlterTable +ALTER TABLE "Order" ADD COLUMN "labelFile" TEXT NOT NULL DEFAULT ''; + +-- AlterTable +ALTER TABLE "Product" ADD COLUMN "weight" INTEGER NOT NULL DEFAULT 0; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 78f8a3b..8ee2c6c 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -107,6 +107,8 @@ model Product { description String @default("") details String @default("") // Material & Pflege sku String @default("") + // Versandgewicht in Gramm, für DHL-Labels (0 = unbekannt) + weight Int @default(0) // Preise in Cent, brutto price Int compareAtPrice Int? @@ -182,6 +184,8 @@ model Order { note String @default("") internalNote String @default("") trackingNumber String @default("") + // Über die DHL-Schnittstelle erzeugtes Versandlabel (Dateiname im Label-Ordner) + labelFile String @default("") items OrderItem[] events OrderEvent[] createdAt DateTime @default(now()) diff --git a/src/app/(shop)/konto/bestellung/[number]/page.tsx b/src/app/(shop)/konto/bestellung/[number]/page.tsx index 4bae1fa..9b8af28 100644 --- a/src/app/(shop)/konto/bestellung/[number]/page.tsx +++ b/src/app/(shop)/konto/bestellung/[number]/page.tsx @@ -6,6 +6,8 @@ import { formatPrice } from "@/lib/money"; import { ORDER_STATUS, PAYMENT_STATUS, dayFmt } from "@/lib/status"; import type { AddressData } from "@/lib/checkout"; import { AddressLines } from "@/components/shop/AddressLines"; +import { DhlTracking } from "@/components/shop/DhlTracking"; +import { fetchTracking, getDhlConfig, syncDelivered } from "@/lib/dhl"; export default async function OrderDetail({ params }: { params: Promise<{ number: string }> }) { const { number } = await params; @@ -13,15 +15,18 @@ export default async function OrderDetail({ params }: { params: Promise<{ number if (!user) redirect("/konto/anmelden"); const order = await db.order.findUnique({ where: { number }, include: { items: true } }); if (!order || order.userId !== user.id) notFound(); + const dhl = await getDhlConfig(); + const tracking = order.trackingNumber ? await fetchTracking(dhl, order.trackingNumber) : null; + if (await syncDelivered(dhl, order, tracking)) order.status = "COMPLETED"; return (
← Zurück zum Konto

Bestellung {order.number}

vom {dayFmt.format(order.createdAt)} · {ORDER_STATUS[order.status].label} · {PAYMENT_STATUS[order.paymentStatus].label} - {order.trackingNumber && <> · Sendungsnummer {order.trackingNumber}}

-
+ {order.trackingNumber && } +
{order.items.map((i) => ( diff --git a/src/app/admin/(panel)/bestellungen/[id]/label/route.ts b/src/app/admin/(panel)/bestellungen/[id]/label/route.ts new file mode 100644 index 0000000..c39eef6 --- /dev/null +++ b/src/app/admin/(panel)/bestellungen/[id]/label/route.ts @@ -0,0 +1,21 @@ +import { readFile } from "node:fs/promises"; +import { NextResponse } from "next/server"; +import { can, getCurrentUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { labelPath } from "@/lib/dhl"; + +// Labels enthalten Adressen und liegen deshalb nicht im öffentlichen Upload-Bereich +export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) { + const user = await getCurrentUser(); + if (!can(user, "orders.view")) return new NextResponse("Kein Zugriff", { status: 403 }); + const order = await db.order.findUnique({ where: { id: (await params).id }, select: { number: true, labelFile: true } }); + if (!order?.labelFile) return new NextResponse("Kein Label vorhanden", { status: 404 }); + try { + const data = await readFile(labelPath(order.labelFile)); + return new NextResponse(new Uint8Array(data), { + headers: { "Content-Type": "application/pdf", "Content-Disposition": `inline; filename="DHL-${order.number}.pdf"`, "Cache-Control": "private, no-store" }, + }); + } catch { + return new NextResponse("Label-Datei nicht gefunden", { status: 404 }); + } +} diff --git a/src/app/admin/(panel)/bestellungen/[id]/page.tsx b/src/app/admin/(panel)/bestellungen/[id]/page.tsx index e4d58af..d621fde 100644 --- a/src/app/admin/(panel)/bestellungen/[id]/page.tsx +++ b/src/app/admin/(panel)/bestellungen/[id]/page.tsx @@ -10,12 +10,18 @@ import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm"; import { Card, PageHead, Pill } from "@/components/admin/ui"; import { SelectField, TextareaField, Field } from "@/components/Field"; import { addOrderNote, cancelOrder, updateOrder } from "../actions"; +import { estimateWeight, fetchTracking, getDhlConfig, syncDelivered } from "@/lib/dhl"; +import { DhlCard } from "@/components/admin/DhlCard"; export default async function OrderDetail({ params }: { params: Promise<{ id: string }> }) { const user = await requireAdmin("orders.view"); const { id } = await params; - const order = await db.order.findUnique({ where: { id }, include: { items: true, events: { orderBy: { createdAt: "desc" } }, user: true } }); + const load = () => db.order.findUnique({ where: { id }, include: { items: { include: { product: { select: { weight: true } } } }, events: { orderBy: { createdAt: "desc" } }, user: true } }); + let order = await load(); if (!order) notFound(); + const dhl = await getDhlConfig(); + const tracking = order.trackingNumber ? await fetchTracking(dhl, order.trackingNumber) : null; + if (await syncDelivered(dhl, order, tracking)) order = (await load())!; const payment = await db.paymentMethod.findUnique({ where: { code: order.paymentMethod } }); const canEdit = can(user, "orders.edit"); const closed = order.status === "CANCELLED" || order.status === "REFUNDED"; @@ -84,6 +90,7 @@ export default async function OrderDetail({ params }: { params: Promise<{ id: st
+
E-Mail
{order.email}
diff --git a/src/app/admin/(panel)/bestellungen/actions.ts b/src/app/admin/(panel)/bestellungen/actions.ts index b18d67d..3b25da5 100644 --- a/src/app/admin/(panel)/bestellungen/actions.ts +++ b/src/app/admin/(panel)/bestellungen/actions.ts @@ -9,6 +9,8 @@ import { ORDER_STATUS, PAYMENT_STATUS } from "@/lib/status"; import { getDefinition } from "@/lib/payments/catalog"; import { getCredentials } from "@/lib/payments/credentials"; import { refundPayment } from "@/lib/payments/stripe"; +import type { AddressData } from "@/lib/checkout"; +import { cancelLabel, canCreateLabels, createLabel, getDhlConfig } from "@/lib/dhl"; const authorName = (u: { firstName: string; lastName: string; email: string }) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email; @@ -35,6 +37,8 @@ export async function updateOrder(_prev: ActionResult, fd: FormData): Promise ({ message, author: authorName(user) })) }, }, @@ -85,3 +89,59 @@ export async function cancelOrder(fd: FormData) { await audit(user, wasPaid ? "Bestellung erstattet" : "Bestellung storniert", order.number); revalidatePath(`/admin/bestellungen/${id}`); } + +export async function createDhlLabel(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("orders.edit"); + const id = String(fd.get("id")); + const order = await db.order.findUnique({ where: { id } }); + if (!order) return fail("Bestellung nicht gefunden."); + if (order.labelFile) return fail("Für diese Bestellung gibt es schon ein DHL-Label."); + if (order.status === "CANCELLED" || order.status === "REFUNDED") return fail("Die Bestellung ist storniert."); + const config = await getDhlConfig(); + if (!canCreateLabels(config)) return fail("DHL ist noch nicht eingerichtet (Einstellungen → DHL-Versand)."); + const kg = Number(String(fd.get("weight") ?? "").replace(",", ".")); + if (!Number.isFinite(kg) || kg <= 0 || kg > 31.5) return fail("Bitte ein Gewicht zwischen 0,1 und 31,5 kg angeben.", { weight: "Ungültiges Gewicht" }); + const result = await createLabel(config, { ...order, shippingAddress: order.shippingAddress as AddressData }, kg * 1000); + if (!result.ok) return fail(result.error); + const shipped = order.status === "PENDING" || order.status === "PAID" || order.status === "PROCESSING"; + await db.order.update({ + where: { id }, + data: { + trackingNumber: result.shipmentNo, + labelFile: result.labelFile, + ...(shipped ? { status: "SHIPPED" } : {}), + events: { + create: { + message: `DHL-Label erstellt (${String(kg).replace(".", ",")} kg), Sendungsnummer ${result.shipmentNo}${shipped ? ". Status: Versendet" : ""}${config.sandbox ? " (Sandbox)" : ""}`, + author: authorName(user), + }, + }, + }, + }); + await audit(user, "DHL-Label erstellt", `${order.number}: ${result.shipmentNo}`); + revalidatePath(`/admin/bestellungen/${id}`); + return ok("Label erstellt."); +} + +export async function cancelDhlLabel(fd: FormData) { + const user = await assertPermission("orders.edit"); + const id = String(fd.get("id")); + const order = await db.order.findUnique({ where: { id } }); + if (!order?.labelFile || !order.trackingNumber) return; + const result = await cancelLabel(await getDhlConfig(), order.trackingNumber, order.labelFile); + if (!result.ok) { + await db.orderEvent.create({ data: { orderId: id, message: result.error, author: authorName(user) } }); + } else { + await db.order.update({ + where: { id }, + data: { + trackingNumber: "", + labelFile: "", + ...(order.status === "SHIPPED" ? { status: "PROCESSING" } : {}), + events: { create: { message: `DHL-Label ${order.trackingNumber} storniert${order.status === "SHIPPED" ? ". Status: In Bearbeitung" : ""}`, author: authorName(user) } }, + }, + }); + await audit(user, "DHL-Label storniert", `${order.number}: ${order.trackingNumber}`); + } + revalidatePath(`/admin/bestellungen/${id}`); +} diff --git a/src/app/admin/(panel)/dhl/actions.ts b/src/app/admin/(panel)/dhl/actions.ts new file mode 100644 index 0000000..c2f76a2 --- /dev/null +++ b/src/app/admin/(panel)/dhl/actions.ts @@ -0,0 +1,62 @@ +"use server"; +import { revalidatePath } from "next/cache"; +import { assertPermission, audit } from "@/lib/auth"; +import { fail, ok, type ActionResult } from "@/lib/action-result"; +import { getDhlConfig, saveDhlConfig, testConnection, type DhlConfig } from "@/lib/dhl"; + +const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); +const grams = (fd: FormData, k: string, fallback: number) => { + const kg = Number(str(fd, k).replace(",", ".")); + return Number.isFinite(kg) && kg > 0 ? Math.round(kg * 1000) : fallback; +}; + +export async function saveDhl(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("shipping.edit"); + const current = await getDhlConfig(); + // Leere Geheimfelder behalten den gespeicherten Wert + const keep = (v: string, old: string) => (v ? v : old); + const next: DhlConfig = { + enabled: fd.get("enabled") === "on", + sandbox: fd.get("sandbox") === "on", + apiKey: keep(str(fd, "apiKey"), current.apiKey), + username: str(fd, "username"), + password: keep(str(fd, "password"), current.password), + billingNational: str(fd, "billingNational").replace(/\s/g, ""), + billingInternational: str(fd, "billingInternational").replace(/\s/g, ""), + shipperName: str(fd, "shipperName"), + shipperStreet: str(fd, "shipperStreet"), + shipperHouse: str(fd, "shipperHouse"), + shipperZip: str(fd, "shipperZip"), + shipperCity: str(fd, "shipperCity"), + shipperEmail: str(fd, "shipperEmail"), + shipperPhone: str(fd, "shipperPhone"), + defaultWeight: grams(fd, "defaultWeight", current.defaultWeight), + packagingWeight: grams(fd, "packagingWeight", 0), + shareEmail: fd.get("shareEmail") === "on", + autoComplete: fd.get("autoComplete") === "on", + }; + if (fd.get("clear") === "on") { + next.apiKey = ""; + next.password = ""; + } + const errors: Record = {}; + for (const k of ["billingNational", "billingInternational"] as const) { + if (next[k] && !/^\d{14}$/.test(next[k])) errors[k] = "14 Ziffern, z. B. 22222222220101"; + } + if (next.shipperZip && !/^\d{5}$/.test(next.shipperZip)) errors.shipperZip = "5 Ziffern"; + if (Object.keys(errors).length) return fail("Bitte prüfe die markierten Felder.", errors); + if (next.enabled && !next.apiKey) return fail("Zum Einschalten braucht DHL einen API-Schlüssel.", { apiKey: "Bitte eintragen" }); + if (next.enabled && !next.sandbox && (!next.username || !next.password || !next.billingNational)) { + return fail("Für den Live-Betrieb fehlen Benutzername, Passwort oder Abrechnungsnummer."); + } + await saveDhlConfig(next); + await audit(user, "DHL-Einstellungen geändert", `${next.enabled ? "an" : "aus"}, ${next.sandbox ? "Sandbox" : "Live"}`); + revalidatePath("/admin/dhl"); + return ok("Gespeichert."); +} + +export async function testDhl(_prev: ActionResult): Promise { + await assertPermission("shipping.edit"); + const r = await testConnection(await getDhlConfig()); + return r.ok ? ok(r.message) : fail(r.message); +} diff --git a/src/app/admin/(panel)/dhl/page.tsx b/src/app/admin/(panel)/dhl/page.tsx new file mode 100644 index 0000000..9302229 --- /dev/null +++ b/src/app/admin/(panel)/dhl/page.tsx @@ -0,0 +1,71 @@ +import { requireAdmin } from "@/lib/auth"; +import { getSettings } from "@/lib/settings"; +import { canCreateLabels, getDhlConfig, splitStreet } from "@/lib/dhl"; +import { mask } from "@/lib/payments/credentials"; +import { Field } from "@/components/Field"; +import { AdminForm } from "@/components/admin/AdminForm"; +import { TestButton } from "@/components/admin/TestButton"; +import { Card, PageHead, Pill, Switch } from "@/components/admin/ui"; +import { saveDhl, testDhl } from "./actions"; + +const kg = (g: number) => (g ? String(g / 1000).replace(".", ",") : ""); + +export default async function DhlPage() { + await requireAdmin("shipping.edit"); + const [c, s] = await Promise.all([getDhlConfig(), getSettings()]); + // Absender beim ersten Einrichten aus den Shop-Angaben vorschlagen + const [street, house] = c.shipperStreet ? [c.shipperStreet, c.shipperHouse] : splitStreet(s.general.street); + const [zip, ...city] = s.general.zipCity.split(" "); + const ready = canCreateLabels(c); + return ( +
+ + + Nicht eingerichtet : {c.sandbox ? "Sandbox" : "Live"}} + > + + + +
+ + +
+
+ + +
+ {(c.apiKey || c.password) && } +
+ + +
+ + +
+
+ + +
+
+ + +
+
+ +
+ + +
+ + +
+
+
+ +
+
+ ); +} diff --git a/src/app/admin/(panel)/produkte/[id]/page.tsx b/src/app/admin/(panel)/produkte/[id]/page.tsx index faa462d..da6a75c 100644 --- a/src/app/admin/(panel)/produkte/[id]/page.tsx +++ b/src/app/admin/(panel)/produkte/[id]/page.tsx @@ -38,6 +38,7 @@ export default async function EditProduct({ params, searchParams }: { params: Pr description: p.description, details: p.details, sku: p.sku, + weight: p.weight ? String(p.weight / 1000).replace(".", ",") : "", price: centsToInput(p.price), compareAtPrice: centsToInput(p.compareAtPrice), taxRate: p.taxRate, diff --git a/src/app/admin/(panel)/produkte/actions.ts b/src/app/admin/(panel)/produkte/actions.ts index b6835de..07191b3 100644 --- a/src/app/admin/(panel)/produkte/actions.ts +++ b/src/app/admin/(panel)/produkte/actions.ts @@ -46,6 +46,7 @@ export async function saveProduct(_prev: ActionResult, fd: FormData): Promise
); diff --git a/src/components/admin/DhlCard.tsx b/src/components/admin/DhlCard.tsx new file mode 100644 index 0000000..a383580 --- /dev/null +++ b/src/components/admin/DhlCard.tsx @@ -0,0 +1,69 @@ +import Link from "next/link"; +import type { DhlConfig, TrackingInfo } from "@/lib/dhl"; +import { canCreateLabels, formatDhlTime, trackingUrl } from "@/lib/dhl"; +import { Field } from "../Field"; +import { AdminForm, ConfirmButton } from "./AdminForm"; +import { Card, Pill } from "./ui"; +import { cancelDhlLabel, createDhlLabel } from "@/app/admin/(panel)/bestellungen/actions"; + +const TONE: Record = { "pre-transit": "gold", transit: "gold", delivered: "success", failure: "danger" }; +const when = formatDhlTime; + +export function DhlCard({ + order, + config, + tracking, + weightGrams, + canEdit, + canSetup, +}: { + order: { id: string; status: string; trackingNumber: string; labelFile: string }; + config: DhlConfig; + tracking: TrackingInfo | null; + weightGrams: number; + canEdit: boolean; + canSetup: boolean; +}) { + const closed = order.status === "CANCELLED" || order.status === "REFUNDED"; + const ready = canCreateLabels(config); + return ( + {tracking.statusCode === "delivered" ? "Zugestellt" : tracking.statusCode === "failure" ? "Problem" : "Unterwegs"} : undefined}> + {order.trackingNumber ? ( +
+
Sendung
+
{order.trackingNumber}
+ {tracking && (<>
Status
{tracking.text}{tracking.location &&
{tracking.location} · {when(tracking.time)}
}
)} +
+ ) : ( + !ready &&

Noch keine Sendung. {canSetup && DHL einrichten}{canSetup ? ", um Labels direkt hier zu erstellen." : ""}

+ )} + + {order.labelFile && ( +
+ Label öffnen (PDF) + {canEdit && order.status !== "COMPLETED" && ( + + )} +
+ )} + + {!order.labelFile && !order.trackingNumber && ready && canEdit && !closed && ( + + + + + )} + + {tracking && tracking.events.length > 0 && ( +
+ Sendungsverlauf ({tracking.events.length}) +
    + {tracking.events.map((e, i) => ( +
  • {e.text}{[when(e.time), e.location].filter(Boolean).join(" · ")}
  • + ))} +
+
+ )} +
+ ); +} diff --git a/src/components/admin/ProductForm.tsx b/src/components/admin/ProductForm.tsx index 3a55168..44fc58f 100644 --- a/src/components/admin/ProductForm.tsx +++ b/src/components/admin/ProductForm.tsx @@ -15,6 +15,7 @@ export type ProductFormValues = { description: string; details: string; sku: string; + weight: string; price: string; compareAtPrice: string; taxRate: number; @@ -97,7 +98,10 @@ export function ProductForm({ values, categories, canStock }: { values: ProductF

Lager

- +
+ + +
diff --git a/src/components/admin/nav.ts b/src/components/admin/nav.ts index f28cdaa..b338ece 100644 --- a/src/components/admin/nav.ts +++ b/src/components/admin/nav.ts @@ -37,6 +37,7 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [ { href: "/admin/einstellungen", label: "Allgemein & Kasse", icon: "settings", permission: "settings.edit" }, { href: "/admin/zahlung", label: "Zahlungsarten", icon: "card", permission: "payments.edit" }, { href: "/admin/versand", label: "Versand", icon: "truck", permission: "shipping.edit" }, + { href: "/admin/dhl", label: "DHL-Versand", icon: "box", permission: "shipping.edit" }, { href: "/admin/anmeldung", label: "Anmeldung", icon: "lock", permission: "settings.edit" }, { href: "/admin/team", label: "Team", icon: "users", permission: "users.manage" }, { href: "/admin/rollen", label: "Rollen & Rechte", icon: "shield", permission: "roles.manage" }, diff --git a/src/components/shop/DhlTracking.tsx b/src/components/shop/DhlTracking.tsx new file mode 100644 index 0000000..69a408d --- /dev/null +++ b/src/components/shop/DhlTracking.tsx @@ -0,0 +1,27 @@ +import type { TrackingInfo } from "@/lib/dhl"; +import { formatDhlTime, trackingUrl } from "@/lib/dhl"; + +const when = formatDhlTime; + +/** Sendungsstatus für Kunden: aktueller Stand, Verlauf und Link zu DHL. */ +export function DhlTracking({ trackingNumber, tracking }: { trackingNumber: string; tracking: TrackingInfo | null }) { + const delivered = tracking?.statusCode === "delivered"; + return ( +
+

Sendung mit DHL

+

+ {tracking ? {tracking.text} : "Dein Paket ist auf dem Weg zu DHL."} + {tracking?.time && · {[tracking.location, when(tracking.time)].filter(Boolean).join(", ")}} +

+

Sendungsnummer {trackingNumber}

+ {tracking && tracking.events.length > 1 && ( +
    + {tracking.events.slice(0, 6).map((e, i) => ( +
  1. {e.text}{[when(e.time), e.location].filter(Boolean).join(" · ")}
  2. + ))} +
+ )} + Sendung bei DHL verfolgen +
+ ); +} diff --git a/src/lib/dhl.ts b/src/lib/dhl.ts new file mode 100644 index 0000000..11cae0f --- /dev/null +++ b/src/lib/dhl.ts @@ -0,0 +1,298 @@ +import "server-only"; +import { mkdir, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { db } from "./db"; +import type { AddressData } from "./checkout"; + +export type DhlConfig = { + enabled: boolean; + sandbox: boolean; + apiKey: string; + username: string; + password: string; + // Abrechnungsnummern (14-stellig) je Produkt aus dem DHL-Geschäftskundenportal + billingNational: string; + billingInternational: string; + shipperName: string; + shipperStreet: string; + shipperHouse: string; + shipperZip: string; + shipperCity: string; + shipperEmail: string; + shipperPhone: string; + // Gramm + defaultWeight: number; + packagingWeight: number; + shareEmail: boolean; + autoComplete: boolean; +}; + +export const DHL_DEFAULTS: DhlConfig = { + enabled: false, + sandbox: true, + apiKey: "", + username: "", + password: "", + billingNational: "", + billingInternational: "", + shipperName: "", + shipperStreet: "", + shipperHouse: "", + shipperZip: "", + shipperCity: "", + shipperEmail: "", + shipperPhone: "", + defaultWeight: 1000, + packagingWeight: 300, + shareEmail: false, + autoComplete: true, +}; + +// Öffentliche Testzugänge der DHL-Sandbox (developer.dhl.com, Parcel DE Shipping) +const SANDBOX = { username: "user-valid", password: "SandboxPasswort2023!", billingNational: "33333333330102", billingInternational: "33333333335301" }; + +const SETTING_KEY = "dhl"; + +export async function getDhlConfig(): Promise { + const row = await db.setting.findUnique({ where: { key: SETTING_KEY } }); + return { ...DHL_DEFAULTS, ...((row?.value ?? {}) as Partial) }; +} + +export async function saveDhlConfig(value: DhlConfig) { + await db.setting.upsert({ where: { key: SETTING_KEY }, create: { key: SETTING_KEY, value }, update: { value } }); +} + +/** Zugangsdaten, die tatsächlich verwendet werden: in der Sandbox ergänzt um die DHL-Testzugänge. */ +function effective(c: DhlConfig) { + if (!c.sandbox) return c; + return { + ...c, + username: c.username || SANDBOX.username, + password: c.password || SANDBOX.password, + billingNational: c.billingNational || SANDBOX.billingNational, + billingInternational: c.billingInternational || SANDBOX.billingInternational, + }; +} + +/** Labels können erstellt werden: eingeschaltet, API-Schlüssel, Zugang und Absender vorhanden. */ +export function canCreateLabels(c: DhlConfig) { + const e = effective(c); + return Boolean(c.enabled && c.apiKey && e.username && e.password && e.billingNational && c.shipperName && c.shipperStreet && c.shipperZip && c.shipperCity); +} + +export const trackingUrl = (trackingNumber: string) => + `https://www.dhl.de/de/privatkunden/pakete-empfangen/verfolgen.html?piececode=${encodeURIComponent(trackingNumber)}`; + +const shippingBase = (c: DhlConfig) => (c.sandbox ? "https://api-sandbox.dhl.com/parcel/de/shipping/v2" : "https://api-eu.dhl.com/parcel/de/shipping/v2"); +const trackingBase = (c: DhlConfig) => (c.sandbox ? "https://api-test.dhl.com/track/shipments" : "https://api-eu.dhl.com/track/shipments"); + +function headers(c: DhlConfig) { + const e = effective(c); + return { + "dhl-api-key": c.apiKey, + Authorization: "Basic " + Buffer.from(`${e.username}:${e.password}`).toString("base64"), + "Content-Type": "application/json", + Accept: "application/json", + "Accept-Language": "de-DE", + }; +} + +const ISO3: Record = { DE: "DEU", AT: "AUT", CH: "CHE", NL: "NLD", BE: "BEL", LU: "LUX", FR: "FRA", DK: "DNK", PL: "POL", IT: "ITA", ES: "ESP" }; +// Länder außerhalb der EU brauchen eine Zollinhaltserklärung, die wir (noch) nicht erzeugen +const NEEDS_CUSTOMS = ["CH"]; + +/** "Musterstraße 12a" → ["Musterstraße", "12a"] */ +export function splitStreet(street: string): [string, string] { + const m = street.trim().match(/^(.+?)\s+(\d+[\w\s\-/]*)$/); + return m ? [m[1].trim(), m[2].trim()] : [street.trim(), ""]; +} + +type DhlMessage = { property?: string; validationMessage?: string }; +type DhlItem = { shipmentNo?: string; sstatus?: { title?: string; detail?: string; statusCode?: number }; label?: { b64?: string }; validationMessages?: DhlMessage[] }; +type DhlResponse = { status?: { title?: string; detail?: string; statusCode?: number }; items?: DhlItem[]; detail?: string; title?: string }; + +function errorText(data: DhlResponse, httpStatus: number) { + const item = data.items?.[0]; + const messages = (item?.validationMessages ?? []).map((m) => (m.property ? `${m.property}: ${m.validationMessage}` : m.validationMessage)).filter(Boolean); + if (messages.length) return messages.join(" · "); + return item?.sstatus?.detail || data.status?.detail || data.detail || data.title || `HTTP ${httpStatus}`; +} + +export function labelDir() { + return path.join(path.resolve(process.env.UPLOAD_DIR ?? "./uploads"), "labels"); +} + +export function labelPath(file: string) { + return path.join(labelDir(), path.basename(file)); +} + +export type LabelResult = { ok: true; shipmentNo: string; labelFile: string } | { ok: false; error: string }; + +export async function createLabel(c: DhlConfig, order: { id: string; number: string; email: string; phone: string; shippingAddress: AddressData }, weightGrams: number): Promise { + const e = effective(c); + const a = order.shippingAddress; + const country = (a.country || "DE").toUpperCase(); + if (NEEDS_CUSTOMS.includes(country)) return { ok: false, error: "Für Sendungen in die Schweiz braucht DHL eine Zollinhaltserklärung. Bitte das Label im DHL-Geschäftskundenportal erstellen." }; + const iso3 = ISO3[country]; + if (!iso3) return { ok: false, error: `Für das Land ${country} kann noch kein Label erstellt werden.` }; + const national = country === "DE"; + if (!national && !e.billingInternational) return { ok: false, error: "Für Auslandssendungen fehlt die Abrechnungsnummer „DHL Paket International“." }; + + const [street, house] = splitStreet(a.street); + const fullName = [a.firstName, a.lastName].filter(Boolean).join(" "); + const consignee: Record = { + name1: (a.company || fullName).slice(0, 50), + addressStreet: street.slice(0, 50), + postalCode: a.zip, + city: a.city.slice(0, 40), + country: iso3, + }; + if (house) consignee.addressHouse = house.slice(0, 10); + if (a.company && fullName) consignee.name2 = fullName.slice(0, 50); + if (a.extra) consignee.additionalAddressInformation1 = a.extra.slice(0, 60); + if (c.shareEmail && order.email) consignee.email = order.email; + if (c.shareEmail && order.phone) consignee.phone = order.phone; + + const shipper: Record = { + name1: c.shipperName.slice(0, 50), + addressStreet: c.shipperStreet, + addressHouse: c.shipperHouse, + postalCode: c.shipperZip, + city: c.shipperCity, + country: "DEU", + }; + if (c.shipperEmail) shipper.email = c.shipperEmail; + if (c.shipperPhone) shipper.phone = c.shipperPhone; + + const shipment: Record = { + product: national ? "V01PAK" : "V53WPAK", + billingNumber: national ? e.billingNational : e.billingInternational, + shipper, + consignee, + details: { weight: { uom: "g", value: Math.max(100, Math.round(weightGrams)) } }, + }; + // Referenz muss 8–35 Zeichen lang sein + if (order.number.length >= 8 && order.number.length <= 35) shipment.refNo = order.number; + + let res: Response; + try { + res = await fetch(`${shippingBase(c)}/orders?includeDocs=include&docFormat=PDF`, { + method: "POST", + headers: headers(c), + body: JSON.stringify({ profile: "STANDARD_GRUPPENPROFIL", shipments: [shipment] }), + cache: "no-store", + }); + } catch (err) { + return { ok: false, error: `DHL ist nicht erreichbar: ${err instanceof Error ? err.message : err}` }; + } + const data = (await res.json().catch(() => ({}))) as DhlResponse; + const item = data.items?.[0]; + if (!res.ok || !item?.shipmentNo || !item.label?.b64) return { ok: false, error: `DHL lehnt ab: ${errorText(data, res.status)}` }; + + const labelFile = `${order.id}-${item.shipmentNo}.pdf`; + await mkdir(labelDir(), { recursive: true }); + await writeFile(labelPath(labelFile), Buffer.from(item.label.b64, "base64")); + return { ok: true, shipmentNo: item.shipmentNo, labelFile }; +} + +export async function cancelLabel(c: DhlConfig, shipmentNo: string, labelFile: string): Promise<{ ok: true } | { ok: false; error: string }> { + try { + const res = await fetch(`${shippingBase(c)}/orders?profile=STANDARD_GRUPPENPROFIL&shipment=${encodeURIComponent(shipmentNo)}`, { + method: "DELETE", + headers: headers(c), + cache: "no-store", + }); + const data = (await res.json().catch(() => ({}))) as DhlResponse; + if (!res.ok) return { ok: false, error: `DHL lehnt die Stornierung ab: ${errorText(data, res.status)}` }; + } catch (err) { + return { ok: false, error: `DHL ist nicht erreichbar: ${err instanceof Error ? err.message : err}` }; + } + if (labelFile) await rm(labelPath(labelFile), { force: true }); + return { ok: true }; +} + +/** Prüft API-Schlüssel, Zugang und Abrechnungsnummer mit einer Probesendung an den Absender (validate=true, es entsteht kein Label). */ +export async function testConnection(c: DhlConfig): Promise<{ ok: boolean; message: string }> { + const e = effective(c); + if (!c.apiKey) return { ok: false, message: "Es ist noch kein API-Schlüssel gespeichert." }; + if (!c.shipperName || !c.shipperStreet || !c.shipperZip || !c.shipperCity) return { ok: false, message: "Bitte zuerst die Absenderadresse speichern." }; + const address = { name1: c.shipperName, addressStreet: c.shipperStreet, addressHouse: c.shipperHouse, postalCode: c.shipperZip, city: c.shipperCity, country: "DEU" }; + try { + const res = await fetch(`${shippingBase(c)}/orders?validate=true`, { + method: "POST", + headers: headers(c), + body: JSON.stringify({ + profile: "STANDARD_GRUPPENPROFIL", + shipments: [{ product: "V01PAK", billingNumber: e.billingNational, shipper: address, consignee: address, details: { weight: { uom: "g", value: 1000 } } }], + }), + cache: "no-store", + }); + const data = (await res.json().catch(() => ({}))) as DhlResponse; + if (res.status === 401) return { ok: false, message: "DHL lehnt Benutzername oder Passwort ab." }; + if (res.status === 403) return { ok: false, message: "DHL lehnt den API-Schlüssel ab." }; + if (!res.ok) return { ok: false, message: `DHL meldet: ${errorText(data, res.status)}` }; + } catch (err) { + return { ok: false, message: `DHL ist nicht erreichbar: ${err instanceof Error ? err.message : err}` }; + } + return { ok: true, message: `DHL verbunden (${c.sandbox ? "Sandbox" : "Live"}), Absender und Abrechnungsnummer sind gültig.` }; +} + +export type TrackingEvent = { time: string; text: string; location: string }; +export type TrackingInfo = { statusCode: string; text: string; time: string; location: string; events: TrackingEvent[] }; + +type DhlTrackEvent = { timestamp?: string; status?: string; description?: string; statusCode?: string; location?: { address?: { addressLocality?: string } } }; + +/** Aktueller Sendungsstatus über die DHL-Sendungsverfolgung. 15 Minuten zwischengespeichert. */ +export async function fetchTracking(c: DhlConfig, trackingNumber: string): Promise { + if (!c.apiKey || !trackingNumber) return null; + try { + const res = await fetch(`${trackingBase(c)}?trackingNumber=${encodeURIComponent(trackingNumber)}&language=de`, { + headers: { "DHL-API-Key": c.apiKey, Accept: "application/json" }, + next: { revalidate: 900 }, + }); + if (!res.ok) return null; + const data = (await res.json()) as { shipments?: { status?: DhlTrackEvent; events?: DhlTrackEvent[] }[] }; + const s = data.shipments?.[0]; + if (!s?.status) return null; + const toEvent = (e: DhlTrackEvent): TrackingEvent => ({ + time: e.timestamp ?? "", + text: e.description || e.status || "", + location: e.location?.address?.addressLocality ?? "", + }); + const current = toEvent(s.status); + return { statusCode: s.status.statusCode ?? "unknown", text: current.text, time: current.time, location: current.location, events: (s.events ?? []).map(toEvent) }; + } catch { + return null; + } +} + +/** Setzt eine versendete Bestellung auf „Abgeschlossen“, sobald DHL die Zustellung meldet. */ +export async function syncDelivered(c: DhlConfig, order: { id: string; status: string; number: string }, tracking: TrackingInfo | null) { + if (!c.autoComplete || order.status !== "SHIPPED" || tracking?.statusCode !== "delivered") return false; + const updated = await db.order.updateMany({ + where: { id: order.id, status: "SHIPPED" }, + data: { status: "COMPLETED" }, + }); + if (updated.count) { + await db.orderEvent.create({ data: { orderId: order.id, message: "Laut DHL zugestellt, Status auf Abgeschlossen gesetzt.", author: "DHL" } }); + } + return updated.count > 0; +} + +/** Versandgewicht aus den Artikelgewichten plus Verpackung, sonst das Standardgewicht. */ +export function estimateWeight(c: DhlConfig, items: { quantity: number; product: { weight: number } | null }[]) { + const sum = items.reduce((n, i) => n + (i.product?.weight ?? 0) * i.quantity, 0); + return sum > 0 ? sum + c.packagingWeight : c.defaultWeight; +} + +const utcFmt = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" }); +const berlinFmt = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeStyle: "short", timeZone: "Europe/Berlin" }); + +/** DHL liefert Zeiten meist als Ortszeit ohne Zeitzone; die werden unverändert angezeigt. */ +export function formatDhlTime(ts: string) { + if (!ts) return ""; + const hasZone = /(Z|[+-]\d\d:?\d\d)$/.test(ts); + const d = new Date(hasZone ? ts : `${ts}Z`); + if (Number.isNaN(d.getTime())) return ""; + return (hasZone ? berlinFmt : utcFmt).format(d); +} diff --git a/src/styles/shop.css b/src/styles/shop.css index f637d46..04adbac 100644 --- a/src/styles/shop.css +++ b/src/styles/shop.css @@ -93,3 +93,14 @@ h1, h2, h3 { margin: 0; } .sm-social__btn--apple:hover { background: #1f1f1f; border-color: #1f1f1f; } .sm-social__or { display: flex; align-items: center; gap: var(--space-3); margin-top: var(--space-2); color: var(--ink-muted); font-size: 14px; } .sm-social__or::before, .sm-social__or::after { content: ""; flex: 1; border-top: var(--hairline) solid var(--line); } + +/* DHL-Sendungsverfolgung im Kundenkonto */ +.sm-tracking { margin-top: var(--space-5); } +.sm-tracking p { margin: 0 0 var(--space-2); } +.sm-tracking__meta { color: var(--ink-muted); } +.sm-tracking__done { color: var(--success, var(--ink)); } +.sm-tracking__events { list-style: none; margin: var(--space-4) 0; padding: 0; border-left: 1px solid var(--line); } +.sm-tracking__events li { position: relative; padding: 0 0 var(--space-3) var(--space-4); font-size: 14px; line-height: 20px; } +.sm-tracking__events li::before { content: ""; position: absolute; left: -4px; top: 6px; width: 7px; height: 7px; border-radius: 50%; background: var(--gold); } +.sm-tracking__events li:first-child::before { background: var(--ink); } +.sm-tracking__events small { display: block; color: var(--ink-muted); font-size: 12px; }