diff --git a/backend/apps/backend/src/admin/routes/statistik/page.tsx b/backend/apps/backend/src/admin/routes/statistik/page.tsx
new file mode 100644
index 0000000..215010e
--- /dev/null
+++ b/backend/apps/backend/src/admin/routes/statistik/page.tsx
@@ -0,0 +1,206 @@
+import { defineRouteConfig } from "@medusajs/admin-sdk";
+import { Button, Container, Heading, Select, Table, Text, toast } from "@medusajs/ui";
+import { useEffect, useState } from "react";
+
+type Daten = {
+ zeitraum: { tage: number };
+ gesamt: {
+ bestellungen: number;
+ umsatz: number;
+ bezahlt: number;
+ storniert: number;
+ durchschnitt: number;
+ };
+ verlauf: { tag: string; bestellungen: number; umsatz: number }[];
+ produkte: { titel: string; menge: number; umsatz: number }[];
+ zahlarten: { zahlart: string; bestellungen: number; summe: number }[];
+ orte: { ort: string; land: string; bestellungen: number }[];
+};
+
+const euro = (wert: number) =>
+ wert.toLocaleString("de-DE", { style: "currency", currency: "EUR" });
+
+/** Balken aus einem div: für den Verlauf reicht das, und es lädt nichts nach. */
+const Balken = ({ anteil }: { anteil: number }) => (
+
+
0 ? 2 : 0)}%` }}
+ />
+
+);
+
+const Kennzahl = ({ titel, wert, zusatz }: { titel: string; wert: string; zusatz?: string }) => (
+
+ {titel}
+ {wert}
+ {zusatz && {zusatz}}
+
+);
+
+const StatistikPage = () => {
+ const [daten, setDaten] = useState
(null);
+ const [tage, setTage] = useState("30");
+ const [laedt, setLaedt] = useState(true);
+
+ const laden = async (zeitraum: string) => {
+ setLaedt(true);
+ try {
+ const res = await fetch(`/admin/statistik?tage=${zeitraum}`, { credentials: "include" });
+ if (!res.ok) throw new Error(String(res.status));
+ setDaten(await res.json());
+ } catch (fehler: any) {
+ toast.error("Fehler", { description: `Zahlen nicht ladbar (${fehler.message}).` });
+ } finally {
+ setLaedt(false);
+ }
+ };
+
+ useEffect(() => {
+ laden(tage);
+ }, [tage]);
+
+ const hoechsterUmsatz = Math.max(1, ...(daten?.verlauf ?? []).map((t) => t.umsatz));
+ const bestellungenGesamt = daten?.gesamt.bestellungen ?? 0;
+
+ return (
+
+
+
Statistik
+
+
+ {/* Der Download läuft über einen normalen Link, damit der Browser
+ die Datei speichert, statt sie im Speicher zu halten. */}
+
+
+
+
+ {laedt && !daten ? (
+
+ Zahlen werden geladen…
+
+ ) : !daten ? null : (
+ <>
+
+
+
+
+
+
+
+
+
Verlauf
+ {daten.verlauf.length === 0 ? (
+
Keine Bestellungen in diesem Zeitraum.
+ ) : (
+
+ {daten.verlauf.map((tag) => (
+
+
+ {new Date(tag.tag).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit" })}
+
+
+
+ {euro(tag.umsatz)}
+
+
+ {tag.bestellungen} Best.
+
+
+ ))}
+
+ )}
+
+
+
+
Meistverkauft
+
+
+
+ Produkt
+ Menge
+ Umsatz
+
+
+
+ {daten.produkte.map((p) => (
+
+ {p.titel}
+ {p.menge}
+ {euro(p.umsatz)}
+
+ ))}
+
+
+
+
+
+
+
Zahlarten
+
+
+
+ Zahlart
+ Bestellungen
+ Anteil
+
+
+
+ {daten.zahlarten.map((z) => (
+
+ {z.zahlart}
+ {z.bestellungen}
+
+ {bestellungenGesamt ? Math.round((z.bestellungen / bestellungenGesamt) * 100) : 0} %
+
+
+ ))}
+
+
+
+
+
+
Wohin geliefert wird
+
+
+
+ Ort
+ Land
+ Bestellungen
+
+
+
+ {daten.orte.map((o) => (
+
+ {o.ort}
+ {o.land}
+ {o.bestellungen}
+
+ ))}
+
+
+
+
+ >
+ )}
+
+ );
+};
+
+export const config = defineRouteConfig({
+ label: "Statistik",
+});
+
+export default StatistikPage;
diff --git a/backend/apps/backend/src/api/admin/statistik/export/route.ts b/backend/apps/backend/src/api/admin/statistik/export/route.ts
new file mode 100644
index 0000000..5601c56
--- /dev/null
+++ b/backend/apps/backend/src/api/admin/statistik/export/route.ts
@@ -0,0 +1,86 @@
+import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils";
+
+/**
+ * Bestellungen als CSV, eine Zeile je Bestellung.
+ *
+ * GET /admin/statistik/export?tage=365
+ *
+ * Für Buchhaltung und eigene Auswertungen in Excel. Semikolon als Trenner und
+ * Komma als Dezimalzeichen, weil Excel in deutscher Einstellung sonst Spalten
+ * und Beträge zerlegt. Die Datei beginnt mit einer Byte-Order-Mark, sonst
+ * zeigt Excel aus Umlauten Buchstabensalat.
+ */
+export async function GET(req: MedusaRequest, res: MedusaResponse) {
+ const knex: any = req.scope.resolve(ContainerRegistrationKeys.PG_CONNECTION);
+
+ const tage = Math.min(Math.max(Number((req.query.tage as string) ?? 365) || 365, 1), 3650);
+ const von = new Date(Date.now() - tage * 24 * 60 * 60 * 1000).toISOString();
+
+ const { rows } = await knex.raw(
+ `select o.display_id,
+ o.created_at,
+ o.status,
+ o.canceled_at,
+ o.email,
+ o.currency_code,
+ (s.totals->>'current_order_total')::numeric as summe,
+ (s.totals->>'paid_total')::numeric as bezahlt,
+ a.city, a.postal_code, a.country_code,
+ (select string_agg(distinct p.provider_id, ' | ')
+ from order_payment_collection opc
+ join payment p on p.payment_collection_id = opc.payment_collection_id
+ and p.deleted_at is null
+ where opc.order_id = o.id and opc.deleted_at is null) as zahlarten,
+ (select string_agg(li.product_title || ' x' || oi.quantity, ' | ')
+ from order_item oi
+ join order_line_item li on li.id = oi.item_id
+ where oi.order_id = o.id and oi.deleted_at is null) as positionen
+ from "order" o
+ join lateral (
+ select totals from order_summary
+ where order_id = o.id and deleted_at is null
+ order by version desc limit 1
+ ) s on true
+ left join order_address a on a.id = o.shipping_address_id
+ where o.deleted_at is null and o.is_draft_order = false and o.created_at >= ?
+ order by o.created_at desc`,
+ [von]
+ );
+
+ const spalten = [
+ "Bestellnummer", "Datum", "Status", "Storniert", "E-Mail", "Währung",
+ "Summe", "Bezahlt", "Ort", "PLZ", "Land", "Zahlart", "Positionen",
+ ];
+
+ /** Semikolon, Anführungszeichen und Zeilenumbrüche müssen maskiert werden. */
+ const feld = (wert: any) => {
+ if (wert === null || wert === undefined) return "";
+ const text = String(wert);
+ return /[";\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
+ };
+ const betrag = (wert: any) => (wert === null ? "" : Number(wert).toFixed(2).replace(".", ","));
+
+ const zeilen = rows.map((r: any) =>
+ [
+ r.display_id,
+ new Date(r.created_at).toLocaleString("de-DE"),
+ r.status,
+ r.canceled_at ? "ja" : "nein",
+ r.email,
+ (r.currency_code ?? "").toUpperCase(),
+ betrag(r.summe),
+ betrag(r.bezahlt),
+ r.city,
+ r.postal_code,
+ (r.country_code ?? "").toUpperCase(),
+ r.zahlarten,
+ r.positionen,
+ ].map(feld).join(";")
+ );
+
+ const datum = new Date().toISOString().slice(0, 10);
+ res.setHeader("Content-Type", "text/csv; charset=utf-8");
+ res.setHeader("Content-Disposition", `attachment; filename="bestellungen-${datum}.csv"`);
+ res.send("" + [spalten.join(";"), ...zeilen].join("\r\n"));
+}
diff --git a/backend/apps/backend/src/api/admin/statistik/route.ts b/backend/apps/backend/src/api/admin/statistik/route.ts
new file mode 100644
index 0000000..315fd58
--- /dev/null
+++ b/backend/apps/backend/src/api/admin/statistik/route.ts
@@ -0,0 +1,120 @@
+import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils";
+
+/**
+ * Zahlen für die Auswertungsseite im Admin.
+ *
+ * GET /admin/statistik?tage=30
+ *
+ * Bewusst als eine SQL-Abfrage je Kennzahl statt über das Datenmodell:
+ * Summen und Gruppierungen macht die Datenbank in einem Zug, das Laden aller
+ * Bestellungen in den Speicher würde bei wachsendem Bestand nicht mehr taugen.
+ *
+ * Die Summen einer Bestellung liegen als JSON in `order_summary`, und zwar je
+ * Fassung einmal — Stornierungen und Änderungen erzeugen neue Fassungen.
+ * Gezählt wird deshalb immer nur die neueste.
+ */
+
+/** Die jeweils neueste Fassung der Summen je Bestellung. */
+const AKTUELLE_SUMME = `
+ join lateral (
+ select totals from order_summary
+ where order_id = o.id and deleted_at is null
+ order by version desc limit 1
+ ) s on true
+`;
+
+export async function GET(req: MedusaRequest, res: MedusaResponse) {
+ const knex: any = req.scope.resolve(ContainerRegistrationKeys.PG_CONNECTION);
+
+ const tage = Math.min(Math.max(Number((req.query.tage as string) ?? 30) || 30, 1), 730);
+ const von = new Date(Date.now() - tage * 24 * 60 * 60 * 1000).toISOString();
+
+ const nurEchte = `o.deleted_at is null and o.is_draft_order = false and o.created_at >= ?`;
+
+ const [summe, verlauf, produkte, zahlarten, orte] = await Promise.all([
+ knex.raw(
+ `select count(*)::int as bestellungen,
+ coalesce(sum((s.totals->>'current_order_total')::numeric), 0) as umsatz,
+ coalesce(sum((s.totals->>'paid_total')::numeric), 0) as bezahlt,
+ count(*) filter (where o.canceled_at is not null)::int as storniert
+ from "order" o ${AKTUELLE_SUMME} where ${nurEchte}`,
+ [von]
+ ),
+ knex.raw(
+ `select o.created_at::date as tag,
+ count(*)::int as bestellungen,
+ coalesce(sum((s.totals->>'current_order_total')::numeric), 0) as umsatz
+ from "order" o ${AKTUELLE_SUMME} where ${nurEchte}
+ group by tag order by tag`,
+ [von]
+ ),
+ knex.raw(
+ `select li.product_title as titel,
+ sum(oi.quantity)::int as menge,
+ coalesce(sum(oi.quantity * li.unit_price), 0) as umsatz
+ from "order" o
+ join order_item oi on oi.order_id = o.id and oi.deleted_at is null
+ join order_line_item li on li.id = oi.item_id
+ where ${nurEchte}
+ group by titel order by menge desc limit 10`,
+ [von]
+ ),
+ knex.raw(
+ `select p.provider_id as zahlart,
+ count(distinct o.id)::int as bestellungen,
+ coalesce(sum(p.amount), 0) as summe
+ from "order" o
+ join order_payment_collection opc on opc.order_id = o.id and opc.deleted_at is null
+ join payment p on p.payment_collection_id = opc.payment_collection_id and p.deleted_at is null
+ where ${nurEchte}
+ group by zahlart order by bestellungen desc`,
+ [von]
+ ),
+ knex.raw(
+ `select coalesce(nullif(a.city, ''), 'ohne Angabe') as ort,
+ upper(coalesce(nullif(a.country_code, ''), '--')) as land,
+ count(*)::int as bestellungen
+ from "order" o
+ left join order_address a on a.id = o.shipping_address_id
+ where ${nurEchte}
+ group by ort, land order by bestellungen desc limit 15`,
+ [von]
+ ),
+ ]);
+
+ const zahl = (wert: any) => Number(wert ?? 0);
+
+ res.json({
+ zeitraum: { tage, von },
+ gesamt: {
+ bestellungen: summe.rows[0].bestellungen,
+ umsatz: zahl(summe.rows[0].umsatz),
+ bezahlt: zahl(summe.rows[0].bezahlt),
+ storniert: summe.rows[0].storniert,
+ durchschnitt: summe.rows[0].bestellungen
+ ? zahl(summe.rows[0].umsatz) / summe.rows[0].bestellungen
+ : 0,
+ },
+ verlauf: verlauf.rows.map((r: any) => ({
+ tag: r.tag instanceof Date ? r.tag.toISOString().slice(0, 10) : String(r.tag).slice(0, 10),
+ bestellungen: r.bestellungen,
+ umsatz: zahl(r.umsatz),
+ })),
+ produkte: produkte.rows.map((r: any) => ({
+ titel: r.titel ?? "ohne Titel",
+ menge: r.menge,
+ umsatz: zahl(r.umsatz),
+ })),
+ zahlarten: zahlarten.rows.map((r: any) => ({
+ zahlart: r.zahlart,
+ bestellungen: r.bestellungen,
+ summe: zahl(r.summe),
+ })),
+ orte: orte.rows.map((r: any) => ({
+ ort: r.ort,
+ land: r.land,
+ bestellungen: r.bestellungen,
+ })),
+ });
+}