diff --git a/prisma/migrations/20261019210000_sales/migration.sql b/prisma/migrations/20261019210000_sales/migration.sql new file mode 100644 index 0000000..7be2d52 --- /dev/null +++ b/prisma/migrations/20261019210000_sales/migration.sql @@ -0,0 +1,18 @@ +-- CreateTable +CREATE TABLE "Sale" ( + "id" TEXT NOT NULL, + "name" TEXT NOT NULL, + "type" TEXT NOT NULL DEFAULT 'percent', + "value" INTEGER NOT NULL, + "scope" TEXT NOT NULL DEFAULT 'shop', + "categoryIds" TEXT[], + "productIds" TEXT[], + "startsAt" TIMESTAMP(3), + "endsAt" TIMESTAMP(3), + "active" BOOLEAN NOT NULL DEFAULT true, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Sale_pkey" PRIMARY KEY ("id") +); + diff --git a/prisma/schema.prisma b/prisma/schema.prisma index f3e7ff4..3b71f75 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -360,3 +360,21 @@ model AuditLog { details String @default("") createdAt DateTime @default(now()) } + +// ---------- Sales ---------- + +// Preisnachlass auf Produkte, Kategorien oder den ganzen Shop. Gilt automatisch, ohne Code. +model Sale { + id String @id @default(cuid()) + name String // z. B. "Sommer-Sale", nur intern + type String @default("percent") // "percent" oder "fixed" (Cent pro Stück) + value Int + scope String @default("shop") // "shop", "categories" oder "products" + categoryIds String[] + productIds String[] + startsAt DateTime? + endsAt DateTime? + active Boolean @default(true) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} diff --git a/src/app/(shop)/page.tsx b/src/app/(shop)/page.tsx index eb4f209..cc96db4 100644 --- a/src/app/(shop)/page.tsx +++ b/src/app/(shop)/page.tsx @@ -1,5 +1,6 @@ import Link from "next/link"; import { db } from "@/lib/db"; +import { withSales } from "@/lib/sales"; import { getSettings } from "@/lib/settings"; import { Icon } from "@/components/Icon"; import { SectionHeading, TrustBar } from "@/components/shop/Blocks"; @@ -17,7 +18,7 @@ export default async function HomePage() { include: { variants: true }, orderBy: [{ sort: "asc" }, { createdAt: "desc" }], take: 8, - }) + }).then(withSales) : [], ]); diff --git a/src/app/(shop)/produkt/[slug]/page.tsx b/src/app/(shop)/produkt/[slug]/page.tsx index e4c11c3..e1064a4 100644 --- a/src/app/(shop)/produkt/[slug]/page.tsx +++ b/src/app/(shop)/produkt/[slug]/page.tsx @@ -2,6 +2,7 @@ import { notFound } from "next/navigation"; import Link from "next/link"; import { db } from "@/lib/db"; import { getSettings } from "@/lib/settings"; +import { withSale, withSales } from "@/lib/sales"; import { Icon } from "@/components/Icon"; import { SectionHeading, TrustBar } from "@/components/shop/Blocks"; import { BuyBox } from "@/components/shop/BuyBox"; @@ -22,11 +23,12 @@ export default async function ProductPage({ searchParams: Promise<{ variante?: string }>; }) { const [{ slug }, { variante }] = await Promise.all([params, searchParams]); - const product = await db.product.findUnique({ + const raw = await db.product.findUnique({ where: { slug }, include: { category: true, variants: { orderBy: { sort: "asc" } } }, }); - if (!product || !product.active) notFound(); + if (!raw || !raw.active) notFound(); + const product = await withSale(raw); const [settings, related] = await Promise.all([ getSettings(), db.product.findMany({ @@ -34,7 +36,7 @@ export default async function ProductPage({ include: { variants: true }, take: 4, orderBy: { featured: "desc" }, - }), + }).then(withSales), ]); const shippingNote = settings.appearance.trustItems[0]; @@ -60,7 +62,8 @@ export default async function ProductPage({ compareAt={product.compareAtPrice} stock={product.stock} trackStock={product.trackStock} - variants={product.variants.map((v) => ({ id: v.id, name: v.name, price: v.price ?? product.price, stock: v.stock }))} + variants={product.variants.map((v) => ({ id: v.id, name: v.name, price: v.price ?? product.price, compareAt: v.compareAtPrice, stock: v.stock }))} + saleEndsAt={product.sale?.endsAt?.toISOString() ?? null} variantLabel="Variante" missingVariant={variante === "fehlt"} /> diff --git a/src/app/(shop)/suche/page.tsx b/src/app/(shop)/suche/page.tsx index 2ad8740..e3784c9 100644 --- a/src/app/(shop)/suche/page.tsx +++ b/src/app/(shop)/suche/page.tsx @@ -1,4 +1,5 @@ import { db } from "@/lib/db"; +import { withSales } from "@/lib/sales"; import { ProductCard } from "@/components/shop/ProductCard"; export const metadata = { title: "Suche" }; @@ -19,7 +20,7 @@ export default async function SearchPage({ searchParams }: { searchParams: Promi }, include: { variants: true }, take: 48, - }) + }).then(withSales) : []; return (
diff --git a/src/app/(shop)/warenkorb/page.tsx b/src/app/(shop)/warenkorb/page.tsx index dc84b93..91ee421 100644 --- a/src/app/(shop)/warenkorb/page.tsx +++ b/src/app/(shop)/warenkorb/page.tsx @@ -77,7 +77,7 @@ export default async function CartPage({ searchParams }: { searchParams: Promise
- {l.quantity} × {formatPrice(l.unitPrice)} + {l.quantity} × {formatPrice(l.unitPrice)}{l.originalUnitPrice && <> {formatPrice(l.originalUnitPrice)}} {formatPrice(l.total)}
diff --git a/src/app/admin/(panel)/produkte/[id]/page.tsx b/src/app/admin/(panel)/produkte/[id]/page.tsx index da6a75c..0a014f3 100644 --- a/src/app/admin/(panel)/produkte/[id]/page.tsx +++ b/src/app/admin/(panel)/produkte/[id]/page.tsx @@ -1,7 +1,8 @@ import { notFound } from "next/navigation"; import { db } from "@/lib/db"; import { can, requireAdmin } from "@/lib/auth"; -import { centsToInput } from "@/lib/money"; +import { centsToInput, formatPrice } from "@/lib/money"; +import { bestSale, getRunningSales, reduce } from "@/lib/sales"; import { Alert } from "@/components/shop/Blocks"; import { ConfirmButton } from "@/components/admin/AdminForm"; import { PageHead } from "@/components/admin/ui"; @@ -16,6 +17,7 @@ export default async function EditProduct({ params, searchParams }: { params: Pr db.category.findMany({ orderBy: { sort: "asc" } }), ]); if (!p) notFound(); + const sale = bestSale(await getRunningSales(), p); return (
@@ -27,6 +29,13 @@ export default async function EditProduct({ params, searchParams }: { params: Pr )} {neu &&
} + {sale && ( +
+ + Der Preis unten bleibt der normale Preis. Sale ansehen + +
+ )} ; searchParams: Promise<{ neu?: string }> }) { + await requireAdmin("coupons.edit"); + const [{ id }, { neu }] = await Promise.all([params, searchParams]); + const isNew = id === "neu"; + const sale = isNew ? null : await db.sale.findUnique({ where: { id } }); + if (!isNew && !sale) notFound(); + const [categories, products] = await Promise.all([ + db.category.findMany({ orderBy: { sort: "asc" }, include: { _count: { select: { products: true } } } }), + db.product.findMany({ orderBy: [{ active: "desc" }, { name: "asc" }], select: { id: true, name: true, price: true, active: true, categoryId: true, category: { select: { name: true } } } }), + ]); + const initial: SaleValues = sale + ? { + id: sale.id, + name: sale.name, + type: sale.type === "fixed" ? "fixed" : "percent", + value: sale.type === "fixed" ? centsToInput(sale.value) : String(sale.value), + scope: sale.scope === "categories" || sale.scope === "products" ? sale.scope : "shop", + categoryIds: sale.categoryIds, + productIds: sale.productIds, + startsAt: toBerlinLocal(sale.startsAt), + endsAt: toBerlinLocal(sale.endsAt), + active: sale.active, + } + : { name: "", type: "percent", value: "", scope: "shop", categoryIds: [], productIds: [], startsAt: "", endsAt: "", active: true }; + const st = sale ? saleState(sale) : null; + return ( +
+ + {st && {STATE[st].label}} + {sale && } + + {neu &&
{st === "running" ? "Er gilt ab sofort im Shop." : st === "planned" ? "Er startet automatisch zum eingestellten Zeitpunkt." : "Er ist gespeichert, aber gerade nicht aktiv."}
} + + ({ id: c.id, name: c.name, detail: `${c._count.products} Produkte${c.active ? "" : " · ausgeblendet"}` }))} + products={products.map((p) => ({ id: p.id, name: p.name, detail: [formatPrice(p.price), p.category?.name, p.active ? "" : "inaktiv"].filter(Boolean).join(" · "), price: p.price, categoryId: p.categoryId }))} + /> + +
+ ); +} diff --git a/src/app/admin/(panel)/sales/actions.ts b/src/app/admin/(panel)/sales/actions.ts new file mode 100644 index 0000000..3034f68 --- /dev/null +++ b/src/app/admin/(panel)/sales/actions.ts @@ -0,0 +1,58 @@ +"use server"; +import { revalidatePath } from "next/cache"; +import { redirect } from "next/navigation"; +import { db } from "@/lib/db"; +import { assertPermission, audit } from "@/lib/auth"; +import { fail, ok, type ActionResult } from "@/lib/action-result"; +import { parsePrice } from "@/lib/money"; +import { parseBerlinLocal } from "@/lib/berlin-time"; + +const refresh = () => { + revalidatePath("/admin/sales", "layout"); + // Preise im ganzen Shop ändern sich + revalidatePath("/", "layout"); +}; + +export async function saveSale(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("coupons.edit"); + const id = String(fd.get("id") ?? ""); + const name = String(fd.get("name") ?? "").trim(); + if (!name) return fail("Gib dem Sale einen Namen, z. B. „Black Friday“.", { name: "Bitte eintragen" }); + const type = fd.get("type") === "fixed" ? "fixed" : "percent"; + const raw = String(fd.get("value") ?? ""); + const value = type === "percent" ? Math.round(Number(raw.replace(",", "."))) : parsePrice(raw); + if (!value || value <= 0 || (type === "percent" && value >= 100)) return fail(type === "percent" ? "Bitte gib einen Rabatt zwischen 1 und 99 % ein." : "Bitte gib einen Betrag ein.", { value: "Ungültig" }); + const scopeRaw = String(fd.get("scope")); + const scope = scopeRaw === "categories" || scopeRaw === "products" ? scopeRaw : "shop"; + const categoryIds = scope === "categories" ? fd.getAll("categoryIds").map(String) : []; + const productIds = scope === "products" ? fd.getAll("productIds").map(String) : []; + if (scope === "categories" && !categoryIds.length) return fail("Wähle mindestens eine Kategorie."); + if (scope === "products" && !productIds.length) return fail("Wähle mindestens ein Produkt."); + const startsAt = parseBerlinLocal(String(fd.get("startsAt") ?? "")); + const endsAt = parseBerlinLocal(String(fd.get("endsAt") ?? "")); + if (startsAt && endsAt && endsAt <= startsAt) return fail("Das Ende muss nach dem Start liegen.", { endsAt: "Vor dem Start" }); + const data = { name, type, value, scope, categoryIds, productIds, startsAt, endsAt, active: fd.get("active") === "on" }; + const sale = id ? await db.sale.update({ where: { id }, data }) : await db.sale.create({ data }); + await audit(user, id ? "Sale geändert" : "Sale angelegt", `${name}: ${type === "percent" ? `${value} %` : `${(value / 100).toFixed(2)} €`}`); + refresh(); + if (!id) redirect(`/admin/sales/${sale.id}?neu=1`); + return ok(); +} + +export async function deleteSale(fd: FormData) { + const user = await assertPermission("coupons.edit"); + const s = await db.sale.delete({ where: { id: String(fd.get("id")) } }); + await audit(user, "Sale gelöscht", s.name); + refresh(); + redirect("/admin/sales"); +} + +export async function toggleSale(fd: FormData) { + const user = await assertPermission("coupons.edit"); + const id = String(fd.get("id")); + const s = await db.sale.findUnique({ where: { id } }); + if (!s) return; + await db.sale.update({ where: { id }, data: { active: !s.active } }); + await audit(user, s.active ? "Sale beendet" : "Sale gestartet", s.name); + refresh(); +} diff --git a/src/app/admin/(panel)/sales/page.tsx b/src/app/admin/(panel)/sales/page.tsx new file mode 100644 index 0000000..a41cbea --- /dev/null +++ b/src/app/admin/(panel)/sales/page.tsx @@ -0,0 +1,58 @@ +import Link from "next/link"; +import { db } from "@/lib/db"; +import { requireAdmin } from "@/lib/auth"; +import { dateFmt } from "@/lib/status"; +import { formatPrice } from "@/lib/money"; +import { SALE_STATES as STATE, SCOPE_LABELS, saleState, type SaleScope, type SaleState } from "@/lib/sales"; +import { ConfirmButton } from "@/components/admin/AdminForm"; +import { Card, Empty, PageHead, Pill } from "@/components/admin/ui"; +import { toggleSale } from "./actions"; + +export default async function SalesPage() { + await requireAdmin("coupons.edit"); + const [sales, categories] = await Promise.all([db.sale.findMany({ orderBy: { createdAt: "desc" } }), db.category.findMany({ select: { id: true, name: true } })]); + const catName = new Map(categories.map((c) => [c.id, c.name])); + const order: SaleState[] = ["running", "planned", "off", "ended"]; + const sorted = [...sales].sort((a, b) => order.indexOf(saleState(a)) - order.indexOf(saleState(b))); + return ( +
+ + Neuer Sale + + + {sales.length === 0 ? ( + + Ersten Sale anlegen + + ) : ( +
+ + + + {sorted.map((s) => { + const st = saleState(s); + const target = s.scope === "categories" ? s.categoryIds.map((id) => catName.get(id) ?? "?").join(", ") : s.scope === "products" ? `${s.productIds.length} Produkt${s.productIds.length === 1 ? "" : "e"}` : SCOPE_LABELS.shop; + return ( + + + + + + + + + ); + })} + +
SaleRabattGilt fürZeitraumStatus
{s.name}{s.type === "percent" ? `−${s.value} %` : `−${formatPrice(s.value)}`}{SCOPE_LABELS[s.scope as SaleScope] && s.scope !== "shop" ? `${SCOPE_LABELS[s.scope as SaleScope]}: ` : ""}{target}{s.startsAt ? dateFmt.format(s.startsAt) : "sofort"} – {s.endsAt ? dateFmt.format(s.endsAt) : "offen"}{STATE[st].label} + {st !== "ended" && ( + + )} +
+
+ )} +
+

Gelten mehrere Sales für ein Produkt, zählt der günstigste. Gutscheine lassen sich zusätzlich einlösen.

+
+ ); +} diff --git a/src/components/admin/SaleForm.tsx b/src/components/admin/SaleForm.tsx new file mode 100644 index 0000000..4b8aa5f --- /dev/null +++ b/src/components/admin/SaleForm.tsx @@ -0,0 +1,126 @@ +"use client"; +import { useEffect, useMemo, useRef, useState } from "react"; +import type { ActionResult } from "@/lib/action-result"; +import { Field, SelectField } from "../Field"; +import { AdminForm } from "./AdminForm"; + +type Option = { id: string; name: string; detail: string; price?: number; categoryId?: string | null }; + +const fmt = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }); + +export type SaleValues = { + id?: string; + name: string; + type: "percent" | "fixed"; + value: string; + scope: "shop" | "categories" | "products"; + categoryIds: string[]; + productIds: string[]; + startsAt: string; + endsAt: string; + active: boolean; +}; + +function Picker({ name, options, selected, onChange, searchable }: { name: string; options: Option[]; selected: string[]; onChange: (ids: string[]) => void; searchable?: boolean }) { + const [q, setQ] = useState(""); + const term = q.trim().toLowerCase(); + const toggle = (id: string) => onChange(selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id]); + return ( +
+ {searchable && setQ(e.target.value)} aria-label="Produkt suchen" />} +
+ {options.map((o) => { + // Ausgefilterte Einträge nur verstecken, damit ihre Auswahl mitgeschickt wird + const hidden = term && !`${o.name} ${o.detail}`.toLowerCase().includes(term); + return ( + + ); + })} +
+ {selected.length} ausgewählt +
+ ); +} + +export function SaleForm({ action, initial, categories, products }: { action: (p: ActionResult, fd: FormData) => Promise; initial: SaleValues; categories: Option[]; products: Option[] }) { + const [type, setType] = useState(initial.type); + const [value, setValue] = useState(initial.value); + const [scope, setScope] = useState(initial.scope); + const [categoryIds, setCategoryIds] = useState(initial.categoryIds); + const [productIds, setProductIds] = useState(initial.productIds); + // Nach dem Speichern setzt React das Formular zurück; neu zeichnen stellt die gesteuerten Felder wieder her + const anchor = useRef(null); + const [, redraw] = useState(0); + useEffect(() => { + const form = anchor.current?.closest("form"); + const onReset = () => setTimeout(() => redraw((n) => n + 1)); + form?.addEventListener("reset", onReset); + return () => form?.removeEventListener("reset", onReset); + }, []); + + // Beispielrechnung mit einem passenden Produkt + const example = useMemo(() => { + const n = type === "percent" ? Math.round(Number(value.replace(",", "."))) : Math.round(Number(value.replace(/\./g, "").replace(",", ".")) * 100); + if (!n || n <= 0) return null; + const match = scope === "products" ? products.find((x) => productIds.includes(x.id)) : scope === "categories" ? products.find((x) => x.categoryId && categoryIds.includes(x.categoryId)) : null; + const p = match ?? products.find((x) => x.price); + if (!p?.price) return null; + const after = Math.max(0, p.price - (type === "percent" ? Math.round((p.price * n) / 100) : n)); + return `${p.name}: ${fmt.format(p.price / 100)} → ${fmt.format(after / 100)}`; + }, [type, value, scope, productIds, categoryIds, products]); + + return ( + + + ); +} diff --git a/src/components/admin/nav.ts b/src/components/admin/nav.ts index 612874c..ca09dd5 100644 --- a/src/components/admin/nav.ts +++ b/src/components/admin/nav.ts @@ -16,6 +16,7 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [ { href: "/admin/bestellungen", label: "Bestellungen", icon: "receipt", permission: "orders.view", badge: "openOrders" }, { href: "/admin/rechnungen", label: "Rechnungen", icon: "invoice", permission: "orders.view" }, { href: "/admin/kunden", label: "Kunden", icon: "users", permission: "customers.view", badge: "newCustomers" }, + { href: "/admin/sales", label: "Sales", icon: "tag", permission: "coupons.edit" }, { href: "/admin/gutscheine", label: "Gutscheine", icon: "ticket", permission: "coupons.edit" }, { href: "/admin/newsletter", label: "Newsletter", icon: "mail", permission: "newsletter.view", badge: "newSubscribers" }, ], diff --git a/src/components/shop/BuyBox.tsx b/src/components/shop/BuyBox.tsx index 45d81b4..6ebfae1 100644 --- a/src/components/shop/BuyBox.tsx +++ b/src/components/shop/BuyBox.tsx @@ -4,7 +4,7 @@ import { useFormStatus } from "react-dom"; import { addToCart } from "@/app/(shop)/actions"; import { Icon } from "../Icon"; -type Variant = { id: string; name: string; price: number; stock: number }; +type Variant = { id: string; name: string; price: number; compareAt?: number | null; stock: number }; const fmt = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }); @@ -26,6 +26,7 @@ export function BuyBox(props: { variants: Variant[]; variantLabel: string; missingVariant: boolean; + saleEndsAt?: string | null; }) { const firstAvailable = props.variants.find((v) => !props.trackStock || v.stock > 0); const [variantId, setVariantId] = useState(props.variants.length === 1 ? (firstAvailable?.id ?? null) : null); @@ -36,7 +37,8 @@ export function BuyBox(props: { const soldOut = props.variants.length ? props.trackStock && props.variants.every((v) => v.stock <= 0) : stock <= 0; const max = Math.min(Number.isFinite(stock) ? stock : 99, 99); const needsVariant = props.variants.length > 0 && !variant; - const compare = props.compareAt && props.compareAt > price ? props.compareAt : null; + const compareBase = variant ? (variant.compareAt ?? props.compareAt) : props.compareAt; + const compare = compareBase && compareBase > price ? compareBase : null; return (
@@ -48,6 +50,7 @@ export function BuyBox(props: { <> {fmt.format(compare / 100)} Du sparst {fmt.format((compare - price) / 100)} + {props.saleEndsAt && Angebot gilt bis {new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeStyle: "short", timeZone: "Europe/Berlin" }).format(new Date(props.saleEndsAt))} Uhr} )}
diff --git a/src/components/shop/ProductCard.tsx b/src/components/shop/ProductCard.tsx index c2382a9..6898edd 100644 --- a/src/components/shop/ProductCard.tsx +++ b/src/components/shop/ProductCard.tsx @@ -4,7 +4,7 @@ import { formatPrice } from "@/lib/money"; import { addToCart } from "@/app/(shop)/actions"; import { ProductImage } from "./ProductImage"; -type P = Product & { variants: ProductVariant[] }; +type P = Product & { variants: (ProductVariant & { compareAtPrice?: number | null })[] }; export function stockOf(p: P) { if (!p.trackStock) return 99; @@ -36,6 +36,8 @@ export function ProductCard({ product }: { product: P }) { const minPrice = product.variants.length ? Math.min(...product.variants.map((v) => v.price ?? product.price)) : product.price; + const cheapest = product.variants.find((v) => (v.price ?? product.price) === minPrice); + const compareAt = (cheapest?.compareAtPrice ?? product.compareAtPrice) || null; const hasVariants = product.variants.length > 0; return (
@@ -66,9 +68,7 @@ export function ProductCard({ product }: { product: P }) {
{hasVariants && product.variants.some((v) => (v.price ?? product.price) !== minPrice) ? "ab " : ""} {formatPrice(minPrice)} - {product.compareAtPrice && product.compareAtPrice > product.price && ( - {formatPrice(product.compareAtPrice)} - )} + {compareAt && compareAt > minPrice && {formatPrice(compareAt)}}
diff --git a/src/components/shop/ProductList.tsx b/src/components/shop/ProductList.tsx index 9794f62..019a35c 100644 --- a/src/components/shop/ProductList.tsx +++ b/src/components/shop/ProductList.tsx @@ -1,6 +1,7 @@ import Link from "next/link"; import type { Prisma } from "@prisma/client"; import { db } from "@/lib/db"; +import { withSales } from "@/lib/sales"; import { ProductCard } from "./ProductCard"; const SORTS: Record = { @@ -25,9 +26,12 @@ export async function ProductList({ }) { const s = SORTS[sort ?? ""] ? sort! : "empfohlen"; const [products, categories] = await Promise.all([ - db.product.findMany({ where: { active: true, ...where }, include: { variants: true }, orderBy: SORTS[s].orderBy }), + db.product.findMany({ where: { active: true, ...where }, include: { variants: true }, orderBy: SORTS[s].orderBy }).then(withSales), showCategoryChips ? db.category.findMany({ where: { active: true }, orderBy: { sort: "asc" } }) : [], ]); + // Nach Sale-Preis sortieren, nicht nach dem gespeicherten Preis + if (s === "preis-auf") products.sort((a, b) => a.price - b.price); + if (s === "preis-ab") products.sort((a, b) => b.price - a.price); return ( <>
diff --git a/src/lib/berlin-time.ts b/src/lib/berlin-time.ts new file mode 100644 index 0000000..2c31089 --- /dev/null +++ b/src/lib/berlin-time.ts @@ -0,0 +1,26 @@ +// Eingaben aus sind deutsche Ortszeit; der Server läuft in UTC. + +const ZONE = "Europe/Berlin"; + +function offsetMs(d: Date) { + const parts = Object.fromEntries( + new Intl.DateTimeFormat("en-US", { timeZone: ZONE, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }) + .formatToParts(d) + .map((p) => [p.type, p.value]), + ); + return Date.UTC(+parts.year, +parts.month - 1, +parts.day, +parts.hour, +parts.minute, +parts.second) - d.getTime(); +} + +/** "2026-11-27T00:00" (deutsche Zeit) → Date. Leer oder ungültig → null. */ +export function parseBerlinLocal(value: string): Date | null { + if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) return null; + const guess = Date.parse(`${value}:00Z`); + if (Number.isNaN(guess)) return null; + return new Date(guess - offsetMs(new Date(guess))); +} + +/** Date → Wert für in deutscher Zeit. */ +export function toBerlinLocal(d: Date | null | undefined) { + if (!d) return ""; + return new Date(d.getTime() + offsetMs(d)).toISOString().slice(0, 16); +} diff --git a/src/lib/cart.ts b/src/lib/cart.ts index e5474e8..283a45f 100644 --- a/src/lib/cart.ts +++ b/src/lib/cart.ts @@ -1,6 +1,7 @@ import "server-only"; import { cookies } from "next/headers"; import { db } from "./db"; +import { bestSale, getRunningSales, reduce } from "./sales"; export const CART_COOKIE = "sm_cart"; export type CartEntry = { p: string; v: string | null; q: number }; @@ -43,6 +44,9 @@ export type CartLine = { sku: string; image: string; unitPrice: number; + // Preis vor einem Sale, null wenn kein Sale gilt + originalUnitPrice: number | null; + saleName: string; quantity: number; maxQuantity: number; taxRate: number; @@ -57,13 +61,16 @@ export async function getCart(): Promise { where: { id: { in: entries.map((e) => e.p) }, active: true }, include: { variants: true }, }); + const sales = await getRunningSales(); const lines: CartLine[] = []; for (const e of entries) { const product = products.find((p) => p.id === e.p); if (!product) continue; const variant = e.v ? product.variants.find((v) => v.id === e.v) : null; if (e.v && !variant) continue; - const unitPrice = variant?.price ?? product.price; + const basePrice = variant?.price ?? product.price; + const sale = sales.length ? bestSale(sales, product) : null; + const unitPrice = sale ? reduce(basePrice, sale) : basePrice; const available = product.trackStock ? (variant ? variant.stock : product.stock) : 99; const quantity = Math.min(e.q, Math.max(available, 0)); if (quantity <= 0) continue; @@ -78,6 +85,8 @@ export async function getCart(): Promise { sku: variant?.sku || product.sku, image: product.images[0] ?? "", unitPrice, + originalUnitPrice: sale && unitPrice < basePrice ? basePrice : null, + saleName: sale?.name ?? "", quantity, maxQuantity: Math.min(available, 99), taxRate: product.taxRate, diff --git a/src/lib/permissions.ts b/src/lib/permissions.ts index 07178db..08cb6df 100644 --- a/src/lib/permissions.ts +++ b/src/lib/permissions.ts @@ -27,7 +27,7 @@ export const PERMISSION_GROUPS = [ permissions: [ { key: "customers.view", label: "Kunden ansehen" }, { key: "customers.edit", label: "Kunden bearbeiten" }, - { key: "coupons.edit", label: "Gutscheine verwalten" }, + { key: "coupons.edit", label: "Gutscheine und Sales verwalten" }, { key: "newsletter.view", label: "Newsletter-Anmeldungen ansehen" }, ], }, diff --git a/src/lib/sales.ts b/src/lib/sales.ts new file mode 100644 index 0000000..6bb01ed --- /dev/null +++ b/src/lib/sales.ts @@ -0,0 +1,93 @@ +import "server-only"; +import { cache } from "react"; +import type { Sale } from "@prisma/client"; +import { db } from "./db"; + +export type SaleScope = "shop" | "categories" | "products"; + +export const SCOPE_LABELS: Record = { + shop: "Ganzer Shop", + categories: "Kategorien", + products: "Einzelne Produkte", +}; + +export type SaleState = "running" | "planned" | "ended" | "off"; + +export const SALE_STATES: Record = { + running: { label: "Läuft", tone: "success" }, + planned: { label: "Geplant", tone: "gold" }, + ended: { label: "Beendet", tone: "neutral" }, + off: { label: "Aus", tone: "neutral" }, +}; + +export function saleState(s: Pick, now = new Date()): SaleState { + if (!s.active) return "off"; + if (s.endsAt && s.endsAt <= now) return "ended"; + if (s.startsAt && s.startsAt > now) return "planned"; + return "running"; +} + +/** Laufende Sales, einmal pro Anfrage geladen. */ +export const getRunningSales = cache(async () => { + const now = new Date(); + return db.sale.findMany({ + where: { + active: true, + AND: [{ OR: [{ startsAt: null }, { startsAt: { lte: now } }] }, { OR: [{ endsAt: null }, { endsAt: { gt: now } }] }], + }, + }); +}); + +function applies(s: Sale, product: { id: string; categoryId: string | null }) { + if (s.scope === "shop") return true; + if (s.scope === "categories") return Boolean(product.categoryId && s.categoryIds.includes(product.categoryId)); + return s.productIds.includes(product.id); +} + +/** Preis nach einem Sale. Nie unter 0 €. */ +export function reduce(price: number, s: Pick) { + const off = s.type === "fixed" ? s.value : Math.round((price * s.value) / 100); + return Math.max(0, price - off); +} + +/** Der Sale mit dem niedrigsten Preis für dieses Produkt. Sales werden nicht addiert. */ +export function bestSale(sales: Sale[], product: { id: string; categoryId: string | null; price: number }) { + let best: Sale | null = null; + for (const s of sales) { + if (!applies(s, product)) continue; + if (!best || reduce(product.price, s) < reduce(product.price, best)) best = s; + } + return best; +} + +type Priced = { id: string; categoryId: string | null; price: number; compareAtPrice: number | null; variants?: { price: number | null }[] }; + +export type WithSale = Omit & { sale: Sale | null } & (T extends { variants: (infer V)[] } ? { variants: (V & { compareAtPrice: number | null })[] } : unknown); + +/** + * Setzt bei Produkten mit laufendem Sale den reduzierten Preis ein. + * Der bisherige Preis wird zum Streichpreis (compareAtPrice), bei Varianten je Variante. + */ +export async function withSales(items: T[]): Promise[]> { + const sales = await getRunningSales(); + return items.map((p): WithSale => { + const sale = sales.length ? bestSale(sales, p) : null; + if (!sale) { + return { ...p, sale: null, variants: p.variants?.map((v) => ({ ...v, compareAtPrice: null })) } as unknown as WithSale; + } + return { + ...p, + sale, + price: reduce(p.price, sale), + compareAtPrice: p.price, + variants: p.variants?.map((v) => { + const base = v.price ?? p.price; + return { ...v, price: reduce(base, sale), compareAtPrice: base }; + }), + } as unknown as WithSale; + }); +} + +export async function withSale(item: T) { + return (await withSales([item]))[0]; +} diff --git a/src/styles/admin.css b/src/styles/admin.css index 1145e5f..80845db 100644 --- a/src/styles/admin.css +++ b/src/styles/admin.css @@ -233,3 +233,19 @@ a.ad-kpi:hover { border-color: var(--line-strong); } .ad-chip span { font-size: 12px; color: var(--ink-subtle); line-height: 16px; } .ad-mailedit__frame { background: #f7f4ee; padding: var(--space-3); display: flex; justify-content: center; } .ad-mailedit__frame iframe { height: 760px; border: 0; background: #f7f4ee; max-width: 100%; transition: width 0.2s; } + +/* Sales */ +.ad-scope { border: 0; padding: 0; margin: var(--space-5) 0 0; display: grid; gap: var(--space-2); grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); } +.ad-scope legend { margin-bottom: var(--space-2); } +.ad-scope__option { display: flex; gap: var(--space-3); align-items: flex-start; padding: var(--space-3) var(--space-4); border: 1px solid var(--line); border-radius: var(--radius-md); cursor: pointer; background: var(--surface-raised, #fff); } +.ad-scope__option.is-active { border-color: var(--gold); box-shadow: 0 0 0 1px var(--gold); } +.ad-scope__option input { margin-top: 3px; accent-color: var(--noir); } +.ad-scope__option span, .ad-picker__item span { display: grid; gap: 2px; } +.ad-scope__option small, .ad-picker__item small { font-size: 12px; color: var(--ink-subtle); line-height: 16px; } +.ad-picker { display: grid; gap: var(--space-2); margin-top: var(--space-4); } +.ad-picker__list { max-height: 320px; overflow-y: auto; border: 1px solid var(--line); border-radius: var(--radius-md); } +.ad-picker__item { display: flex; gap: var(--space-3); align-items: center; padding: var(--space-2) var(--space-4); border-bottom: 1px solid var(--line); cursor: pointer; } +.ad-picker__item:last-child { border-bottom: 0; } +.ad-picker__item:hover { background: var(--surface); } +.ad-picker__item input { accent-color: var(--noir); } +.ad-picker__item strong { font-weight: 500; font-size: 15px; }