Sales: Preisnachlass auf Produkte, Kategorien oder den ganzen Shop
- Neues Modell Sale (Prozent oder fester Betrag, Ziel, Start/Ende in deutscher Zeit, an/aus) - Admin unter Verkauf → Sales: Liste mit Status (läuft, geplant, beendet, aus), anlegen, bearbeiten, beenden, löschen; Beispielrechnung im Formular - Shop: Sale-Preis mit Streichpreis in Listen, Suche, Startseite, Produktseite (je Variante, mit „gilt bis“), Warenkorb; Kasse und Bestellung rechnen mit dem Sale-Preis - Mehrere Sales: der günstigste zählt, keine Addition; Gutscheine weiterhin zusätzlich - Produktseite im Admin zeigt, wenn ein Sale läuft Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
This commit is contained in:
parent
4c26d2f083
commit
21aa679504
20 changed files with 516 additions and 17 deletions
18
prisma/migrations/20261019210000_sales/migration.sql
Normal file
18
prisma/migrations/20261019210000_sales/migration.sql
Normal file
|
|
@ -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")
|
||||||
|
);
|
||||||
|
|
||||||
|
|
@ -360,3 +360,21 @@ model AuditLog {
|
||||||
details String @default("")
|
details String @default("")
|
||||||
createdAt DateTime @default(now())
|
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
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { withSales } from "@/lib/sales";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
import { Icon } from "@/components/Icon";
|
import { Icon } from "@/components/Icon";
|
||||||
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
|
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
|
||||||
|
|
@ -17,7 +18,7 @@ export default async function HomePage() {
|
||||||
include: { variants: true },
|
include: { variants: true },
|
||||||
orderBy: [{ sort: "asc" }, { createdAt: "desc" }],
|
orderBy: [{ sort: "asc" }, { createdAt: "desc" }],
|
||||||
take: 8,
|
take: 8,
|
||||||
})
|
}).then(withSales)
|
||||||
: [],
|
: [],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import { withSale, withSales } from "@/lib/sales";
|
||||||
import { Icon } from "@/components/Icon";
|
import { Icon } from "@/components/Icon";
|
||||||
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
|
import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
|
||||||
import { BuyBox } from "@/components/shop/BuyBox";
|
import { BuyBox } from "@/components/shop/BuyBox";
|
||||||
|
|
@ -22,11 +23,12 @@ export default async function ProductPage({
|
||||||
searchParams: Promise<{ variante?: string }>;
|
searchParams: Promise<{ variante?: string }>;
|
||||||
}) {
|
}) {
|
||||||
const [{ slug }, { variante }] = await Promise.all([params, searchParams]);
|
const [{ slug }, { variante }] = await Promise.all([params, searchParams]);
|
||||||
const product = await db.product.findUnique({
|
const raw = await db.product.findUnique({
|
||||||
where: { slug },
|
where: { slug },
|
||||||
include: { category: true, variants: { orderBy: { sort: "asc" } } },
|
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([
|
const [settings, related] = await Promise.all([
|
||||||
getSettings(),
|
getSettings(),
|
||||||
db.product.findMany({
|
db.product.findMany({
|
||||||
|
|
@ -34,7 +36,7 @@ export default async function ProductPage({
|
||||||
include: { variants: true },
|
include: { variants: true },
|
||||||
take: 4,
|
take: 4,
|
||||||
orderBy: { featured: "desc" },
|
orderBy: { featured: "desc" },
|
||||||
}),
|
}).then(withSales),
|
||||||
]);
|
]);
|
||||||
const shippingNote = settings.appearance.trustItems[0];
|
const shippingNote = settings.appearance.trustItems[0];
|
||||||
|
|
||||||
|
|
@ -60,7 +62,8 @@ export default async function ProductPage({
|
||||||
compareAt={product.compareAtPrice}
|
compareAt={product.compareAtPrice}
|
||||||
stock={product.stock}
|
stock={product.stock}
|
||||||
trackStock={product.trackStock}
|
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"
|
variantLabel="Variante"
|
||||||
missingVariant={variante === "fehlt"}
|
missingVariant={variante === "fehlt"}
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { withSales } from "@/lib/sales";
|
||||||
import { ProductCard } from "@/components/shop/ProductCard";
|
import { ProductCard } from "@/components/shop/ProductCard";
|
||||||
|
|
||||||
export const metadata = { title: "Suche" };
|
export const metadata = { title: "Suche" };
|
||||||
|
|
@ -19,7 +20,7 @@ export default async function SearchPage({ searchParams }: { searchParams: Promi
|
||||||
},
|
},
|
||||||
include: { variants: true },
|
include: { variants: true },
|
||||||
take: 48,
|
take: 48,
|
||||||
})
|
}).then(withSales)
|
||||||
: [];
|
: [];
|
||||||
return (
|
return (
|
||||||
<main className="sm-container sm-page">
|
<main className="sm-container sm-page">
|
||||||
|
|
|
||||||
|
|
@ -77,7 +77,7 @@ export default async function CartPage({ searchParams }: { searchParams: Promise
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
<div className="sm-cartline__price">
|
<div className="sm-cartline__price">
|
||||||
<span className="sm-cartline__unit">{l.quantity} × {formatPrice(l.unitPrice)}</span>
|
<span className="sm-cartline__unit">{l.quantity} × {formatPrice(l.unitPrice)}{l.originalUnitPrice && <> <s className="sm-price__old">{formatPrice(l.originalUnitPrice)}</s></>}</span>
|
||||||
<span className="sm-price">{formatPrice(l.total)}</span>
|
<span className="sm-price">{formatPrice(l.total)}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { can, requireAdmin } from "@/lib/auth";
|
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 { Alert } from "@/components/shop/Blocks";
|
||||||
import { ConfirmButton } from "@/components/admin/AdminForm";
|
import { ConfirmButton } from "@/components/admin/AdminForm";
|
||||||
import { PageHead } from "@/components/admin/ui";
|
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" } }),
|
db.category.findMany({ orderBy: { sort: "asc" } }),
|
||||||
]);
|
]);
|
||||||
if (!p) notFound();
|
if (!p) notFound();
|
||||||
|
const sale = bestSale(await getRunningSales(), p);
|
||||||
return (
|
return (
|
||||||
<div className="ad-wrap">
|
<div className="ad-wrap">
|
||||||
<PageHead title={p.name} back={{ href: "/admin/produkte", label: "Produkte" }}>
|
<PageHead title={p.name} back={{ href: "/admin/produkte", label: "Produkte" }}>
|
||||||
|
|
@ -27,6 +29,13 @@ export default async function EditProduct({ params, searchParams }: { params: Pr
|
||||||
)}
|
)}
|
||||||
</PageHead>
|
</PageHead>
|
||||||
{neu && <div style={{ marginBottom: "var(--space-5)" }}><Alert kind="success" title="Produkt angelegt." /></div>}
|
{neu && <div style={{ marginBottom: "var(--space-5)" }}><Alert kind="success" title="Produkt angelegt." /></div>}
|
||||||
|
{sale && (
|
||||||
|
<div style={{ marginBottom: "var(--space-5)" }}>
|
||||||
|
<Alert title={`Im Sale „${sale.name}“: im Shop ${formatPrice(reduce(p.price, sale))} statt ${formatPrice(p.price)}`}>
|
||||||
|
Der Preis unten bleibt der normale Preis. <a href={`/admin/sales/${sale.id}`}>Sale ansehen</a>
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<ProductForm
|
<ProductForm
|
||||||
canStock={can(user, "stock.edit")}
|
canStock={can(user, "stock.edit")}
|
||||||
categories={categories}
|
categories={categories}
|
||||||
|
|
|
||||||
55
src/app/admin/(panel)/sales/[id]/page.tsx
Normal file
55
src/app/admin/(panel)/sales/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { requireAdmin } from "@/lib/auth";
|
||||||
|
import { centsToInput, formatPrice } from "@/lib/money";
|
||||||
|
import { toBerlinLocal } from "@/lib/berlin-time";
|
||||||
|
import { SALE_STATES as STATE, saleState } from "@/lib/sales";
|
||||||
|
import { Alert } from "@/components/shop/Blocks";
|
||||||
|
import { ConfirmButton } from "@/components/admin/AdminForm";
|
||||||
|
import { Card, PageHead, Pill } from "@/components/admin/ui";
|
||||||
|
import { SaleForm, type SaleValues } from "@/components/admin/SaleForm";
|
||||||
|
import { deleteSale, saveSale } from "../actions";
|
||||||
|
|
||||||
|
export default async function SalePage({ params, searchParams }: { params: Promise<{ id: string }>; 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 (
|
||||||
|
<div className="ad-wrap ad-wrap--narrow">
|
||||||
|
<PageHead title={sale ? sale.name : "Neuer Sale"} back={{ href: "/admin/sales", label: "Sales" }}>
|
||||||
|
{st && <Pill tone={STATE[st].tone}>{STATE[st].label}</Pill>}
|
||||||
|
{sale && <ConfirmButton action={deleteSale} hidden={{ id: sale.id }} confirm="Sale löschen?" className="sm-btn sm-btn--ghost sm-btn--sm">Löschen</ConfirmButton>}
|
||||||
|
</PageHead>
|
||||||
|
{neu && <div style={{ marginBottom: "var(--space-5)" }}><Alert kind="success" title="Sale angelegt.">{st === "running" ? "Er gilt ab sofort im Shop." : st === "planned" ? "Er startet automatisch zum eingestellten Zeitpunkt." : "Er ist gespeichert, aber gerade nicht aktiv."}</Alert></div>}
|
||||||
|
<Card>
|
||||||
|
<SaleForm
|
||||||
|
action={saveSale}
|
||||||
|
initial={initial}
|
||||||
|
categories={categories.map((c) => ({ 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 }))}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
58
src/app/admin/(panel)/sales/actions.ts
Normal file
58
src/app/admin/(panel)/sales/actions.ts
Normal file
|
|
@ -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<ActionResult> {
|
||||||
|
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();
|
||||||
|
}
|
||||||
58
src/app/admin/(panel)/sales/page.tsx
Normal file
58
src/app/admin/(panel)/sales/page.tsx
Normal file
|
|
@ -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 (
|
||||||
|
<div className="ad-wrap">
|
||||||
|
<PageHead title="Sales" lead="Preisnachlässe auf einzelne Produkte, ganze Kategorien oder den ganzen Shop. Sie gelten automatisch, Kunden sehen den alten Preis durchgestrichen.">
|
||||||
|
<Link className="sm-btn sm-btn--primary" href="/admin/sales/neu">Neuer Sale</Link>
|
||||||
|
</PageHead>
|
||||||
|
<Card flush>
|
||||||
|
{sales.length === 0 ? (
|
||||||
|
<Empty title="Noch keine Sales" text="Lege z. B. 20 % auf eine Kategorie an, mit Start und Ende.">
|
||||||
|
<Link className="sm-btn sm-btn--secondary" href="/admin/sales/neu">Ersten Sale anlegen</Link>
|
||||||
|
</Empty>
|
||||||
|
) : (
|
||||||
|
<div className="ad-table-wrap">
|
||||||
|
<table className="ad-table">
|
||||||
|
<thead><tr><th>Sale</th><th>Rabatt</th><th>Gilt für</th><th>Zeitraum</th><th>Status</th><th /></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{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 (
|
||||||
|
<tr key={s.id}>
|
||||||
|
<td><Link className="ad-rowlink" href={`/admin/sales/${s.id}`}>{s.name}</Link></td>
|
||||||
|
<td style={{ whiteSpace: "nowrap" }}>{s.type === "percent" ? `−${s.value} %` : `−${formatPrice(s.value)}`}</td>
|
||||||
|
<td className="body-sm">{SCOPE_LABELS[s.scope as SaleScope] && s.scope !== "shop" ? `${SCOPE_LABELS[s.scope as SaleScope]}: ` : ""}{target}</td>
|
||||||
|
<td className="body-sm" style={{ whiteSpace: "nowrap" }}>{s.startsAt ? dateFmt.format(s.startsAt) : "sofort"} – {s.endsAt ? dateFmt.format(s.endsAt) : "offen"}</td>
|
||||||
|
<td><Pill tone={STATE[st].tone}>{STATE[st].label}</Pill></td>
|
||||||
|
<td className="num">
|
||||||
|
{st !== "ended" && (
|
||||||
|
<ConfirmButton action={toggleSale} hidden={{ id: s.id }} confirm={s.active ? "Sale beenden?" : "Sale starten?"} className="sm-btn sm-btn--ghost sm-btn--sm">{s.active ? "Beenden" : "Starten"}</ConfirmButton>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
<p className="ad-help" style={{ marginTop: "var(--space-4)" }}>Gelten mehrere Sales für ein Produkt, zählt der günstigste. Gutscheine lassen sich zusätzlich einlösen.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
126
src/components/admin/SaleForm.tsx
Normal file
126
src/components/admin/SaleForm.tsx
Normal file
|
|
@ -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 (
|
||||||
|
<div className="ad-picker">
|
||||||
|
{searchable && <input className="sm-input" type="search" placeholder="Produkt suchen …" value={q} onChange={(e) => setQ(e.target.value)} aria-label="Produkt suchen" />}
|
||||||
|
<div className="ad-picker__list">
|
||||||
|
{options.map((o) => {
|
||||||
|
// Ausgefilterte Einträge nur verstecken, damit ihre Auswahl mitgeschickt wird
|
||||||
|
const hidden = term && !`${o.name} ${o.detail}`.toLowerCase().includes(term);
|
||||||
|
return (
|
||||||
|
<label key={o.id} className="ad-picker__item" style={hidden ? { display: "none" } : undefined}>
|
||||||
|
<input type="checkbox" name={name} value={o.id} checked={selected.includes(o.id)} onChange={() => toggle(o.id)} />
|
||||||
|
<span>
|
||||||
|
<strong>{o.name}</strong>
|
||||||
|
<small>{o.detail}</small>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<small className="ad-muted">{selected.length} ausgewählt</small>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SaleForm({ action, initial, categories, products }: { action: (p: ActionResult, fd: FormData) => Promise<ActionResult>; 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<HTMLSpanElement>(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 (
|
||||||
|
<AdminForm action={action} submitLabel={initial.id ? "Speichern" : "Sale anlegen"}>
|
||||||
|
<span ref={anchor} hidden />
|
||||||
|
{initial.id && <input type="hidden" name="id" value={initial.id} />}
|
||||||
|
<Field label="Name" name="name" defaultValue={initial.name} placeholder="z. B. Black Friday" hint="Nur für dich, Kunden sehen den durchgestrichenen Preis." />
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<SelectField label="Rabatt" name="type" value={type} onChange={(e) => setType(e.target.value as SaleValues["type"])}>
|
||||||
|
<option value="percent">Prozent</option>
|
||||||
|
<option value="fixed">Fester Betrag pro Stück</option>
|
||||||
|
</SelectField>
|
||||||
|
<Field label={type === "percent" ? "Wie viel Prozent?" : "Wie viel Euro?"} name="value" inputMode="decimal" value={value} onChange={(e) => setValue(e.target.value)} placeholder={type === "percent" ? "20" : "10,00"} />
|
||||||
|
</div>
|
||||||
|
{example && <p className="ad-help" style={{ margin: "var(--space-2) 0 0" }}>Beispiel: {example}</p>}
|
||||||
|
|
||||||
|
<fieldset className="ad-scope">
|
||||||
|
<legend className="sm-field__label">Wofür gilt der Sale?</legend>
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
["shop", "Ganzer Shop", "Alle Produkte"],
|
||||||
|
["categories", "Kategorien", "Alle Produkte der gewählten Kategorien"],
|
||||||
|
["products", "Einzelne Produkte", "Nur die Produkte, die du auswählst"],
|
||||||
|
] as const
|
||||||
|
).map(([key, title, text]) => (
|
||||||
|
<label key={key} className={`ad-scope__option${scope === key ? " is-active" : ""}`}>
|
||||||
|
<input type="radio" name="scope" value={key} checked={scope === key} onChange={() => setScope(key)} />
|
||||||
|
<span>
|
||||||
|
<strong>{title}</strong>
|
||||||
|
<small>{text}</small>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</fieldset>
|
||||||
|
{scope === "categories" && <Picker name="categoryIds" options={categories} selected={categoryIds} onChange={setCategoryIds} />}
|
||||||
|
{scope === "products" && <Picker name="productIds" options={products} selected={productIds} onChange={setProductIds} searchable />}
|
||||||
|
|
||||||
|
<div className="sm-form-row" style={{ marginTop: "var(--space-5)" }}>
|
||||||
|
<Field label="Start" optional name="startsAt" type="datetime-local" defaultValue={initial.startsAt} hint="Leer = sofort" />
|
||||||
|
<Field label="Ende" optional name="endsAt" type="datetime-local" defaultValue={initial.endsAt} hint="Leer = bis du ihn beendest" />
|
||||||
|
</div>
|
||||||
|
<label className="ad-switch" style={{ marginTop: "var(--space-4)" }}>
|
||||||
|
<span className="ad-switch__text">
|
||||||
|
<strong>Sale aktiv</strong>
|
||||||
|
<small>Gilt automatisch im Zeitraum, ohne Gutscheincode. Gelten mehrere Sales für ein Produkt, zählt der günstigste.</small>
|
||||||
|
</span>
|
||||||
|
<input type="checkbox" role="switch" name="active" defaultChecked={initial.active} />
|
||||||
|
</label>
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -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/bestellungen", label: "Bestellungen", icon: "receipt", permission: "orders.view", badge: "openOrders" },
|
||||||
{ href: "/admin/rechnungen", label: "Rechnungen", icon: "invoice", permission: "orders.view" },
|
{ href: "/admin/rechnungen", label: "Rechnungen", icon: "invoice", permission: "orders.view" },
|
||||||
{ href: "/admin/kunden", label: "Kunden", icon: "users", permission: "customers.view", badge: "newCustomers" },
|
{ 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/gutscheine", label: "Gutscheine", icon: "ticket", permission: "coupons.edit" },
|
||||||
{ href: "/admin/newsletter", label: "Newsletter", icon: "mail", permission: "newsletter.view", badge: "newSubscribers" },
|
{ href: "/admin/newsletter", label: "Newsletter", icon: "mail", permission: "newsletter.view", badge: "newSubscribers" },
|
||||||
],
|
],
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { useFormStatus } from "react-dom";
|
||||||
import { addToCart } from "@/app/(shop)/actions";
|
import { addToCart } from "@/app/(shop)/actions";
|
||||||
import { Icon } from "../Icon";
|
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" });
|
const fmt = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||||
|
|
||||||
|
|
@ -26,6 +26,7 @@ export function BuyBox(props: {
|
||||||
variants: Variant[];
|
variants: Variant[];
|
||||||
variantLabel: string;
|
variantLabel: string;
|
||||||
missingVariant: boolean;
|
missingVariant: boolean;
|
||||||
|
saleEndsAt?: string | null;
|
||||||
}) {
|
}) {
|
||||||
const firstAvailable = props.variants.find((v) => !props.trackStock || v.stock > 0);
|
const firstAvailable = props.variants.find((v) => !props.trackStock || v.stock > 0);
|
||||||
const [variantId, setVariantId] = useState<string | null>(props.variants.length === 1 ? (firstAvailable?.id ?? null) : null);
|
const [variantId, setVariantId] = useState<string | null>(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 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 max = Math.min(Number.isFinite(stock) ? stock : 99, 99);
|
||||||
const needsVariant = props.variants.length > 0 && !variant;
|
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 (
|
return (
|
||||||
<form action={addToCart}>
|
<form action={addToCart}>
|
||||||
|
|
@ -48,6 +50,7 @@ export function BuyBox(props: {
|
||||||
<>
|
<>
|
||||||
<s className="sm-price__old">{fmt.format(compare / 100)}</s>
|
<s className="sm-price__old">{fmt.format(compare / 100)}</s>
|
||||||
<span className="sm-price__save">Du sparst {fmt.format((compare - price) / 100)}</span>
|
<span className="sm-price__save">Du sparst {fmt.format((compare - price) / 100)}</span>
|
||||||
|
{props.saleEndsAt && <span className="sm-price__note" style={{ display: "block" }}>Angebot gilt bis {new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeStyle: "short", timeZone: "Europe/Berlin" }).format(new Date(props.saleEndsAt))} Uhr</span>}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { formatPrice } from "@/lib/money";
|
||||||
import { addToCart } from "@/app/(shop)/actions";
|
import { addToCart } from "@/app/(shop)/actions";
|
||||||
import { ProductImage } from "./ProductImage";
|
import { ProductImage } from "./ProductImage";
|
||||||
|
|
||||||
type P = Product & { variants: ProductVariant[] };
|
type P = Product & { variants: (ProductVariant & { compareAtPrice?: number | null })[] };
|
||||||
|
|
||||||
export function stockOf(p: P) {
|
export function stockOf(p: P) {
|
||||||
if (!p.trackStock) return 99;
|
if (!p.trackStock) return 99;
|
||||||
|
|
@ -36,6 +36,8 @@ export function ProductCard({ product }: { product: P }) {
|
||||||
const minPrice = product.variants.length
|
const minPrice = product.variants.length
|
||||||
? Math.min(...product.variants.map((v) => v.price ?? product.price))
|
? Math.min(...product.variants.map((v) => v.price ?? product.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;
|
const hasVariants = product.variants.length > 0;
|
||||||
return (
|
return (
|
||||||
<article className="sm-card">
|
<article className="sm-card">
|
||||||
|
|
@ -66,9 +68,7 @@ export function ProductCard({ product }: { product: P }) {
|
||||||
<div className="sm-price">
|
<div className="sm-price">
|
||||||
{hasVariants && product.variants.some((v) => (v.price ?? product.price) !== minPrice) ? "ab " : ""}
|
{hasVariants && product.variants.some((v) => (v.price ?? product.price) !== minPrice) ? "ab " : ""}
|
||||||
{formatPrice(minPrice)}
|
{formatPrice(minPrice)}
|
||||||
{product.compareAtPrice && product.compareAtPrice > product.price && (
|
{compareAt && compareAt > minPrice && <s className="sm-price__old">{formatPrice(compareAt)}</s>}
|
||||||
<s className="sm-price__old">{formatPrice(product.compareAtPrice)}</s>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import type { Prisma } from "@prisma/client";
|
import type { Prisma } from "@prisma/client";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { withSales } from "@/lib/sales";
|
||||||
import { ProductCard } from "./ProductCard";
|
import { ProductCard } from "./ProductCard";
|
||||||
|
|
||||||
const SORTS: Record<string, { label: string; orderBy: Prisma.ProductOrderByWithRelationInput[] }> = {
|
const SORTS: Record<string, { label: string; orderBy: Prisma.ProductOrderByWithRelationInput[] }> = {
|
||||||
|
|
@ -25,9 +26,12 @@ export async function ProductList({
|
||||||
}) {
|
}) {
|
||||||
const s = SORTS[sort ?? ""] ? sort! : "empfohlen";
|
const s = SORTS[sort ?? ""] ? sort! : "empfohlen";
|
||||||
const [products, categories] = await Promise.all([
|
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" } }) : [],
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="sm-shop-toolbar">
|
<div className="sm-shop-toolbar">
|
||||||
|
|
|
||||||
26
src/lib/berlin-time.ts
Normal file
26
src/lib/berlin-time.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
// Eingaben aus <input type="datetime-local"> 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 <input type="datetime-local"> in deutscher Zeit. */
|
||||||
|
export function toBerlinLocal(d: Date | null | undefined) {
|
||||||
|
if (!d) return "";
|
||||||
|
return new Date(d.getTime() + offsetMs(d)).toISOString().slice(0, 16);
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import "server-only";
|
import "server-only";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import { db } from "./db";
|
import { db } from "./db";
|
||||||
|
import { bestSale, getRunningSales, reduce } from "./sales";
|
||||||
|
|
||||||
export const CART_COOKIE = "sm_cart";
|
export const CART_COOKIE = "sm_cart";
|
||||||
export type CartEntry = { p: string; v: string | null; q: number };
|
export type CartEntry = { p: string; v: string | null; q: number };
|
||||||
|
|
@ -43,6 +44,9 @@ export type CartLine = {
|
||||||
sku: string;
|
sku: string;
|
||||||
image: string;
|
image: string;
|
||||||
unitPrice: number;
|
unitPrice: number;
|
||||||
|
// Preis vor einem Sale, null wenn kein Sale gilt
|
||||||
|
originalUnitPrice: number | null;
|
||||||
|
saleName: string;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
maxQuantity: number;
|
maxQuantity: number;
|
||||||
taxRate: number;
|
taxRate: number;
|
||||||
|
|
@ -57,13 +61,16 @@ export async function getCart(): Promise<CartLine[]> {
|
||||||
where: { id: { in: entries.map((e) => e.p) }, active: true },
|
where: { id: { in: entries.map((e) => e.p) }, active: true },
|
||||||
include: { variants: true },
|
include: { variants: true },
|
||||||
});
|
});
|
||||||
|
const sales = await getRunningSales();
|
||||||
const lines: CartLine[] = [];
|
const lines: CartLine[] = [];
|
||||||
for (const e of entries) {
|
for (const e of entries) {
|
||||||
const product = products.find((p) => p.id === e.p);
|
const product = products.find((p) => p.id === e.p);
|
||||||
if (!product) continue;
|
if (!product) continue;
|
||||||
const variant = e.v ? product.variants.find((v) => v.id === e.v) : null;
|
const variant = e.v ? product.variants.find((v) => v.id === e.v) : null;
|
||||||
if (e.v && !variant) continue;
|
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 available = product.trackStock ? (variant ? variant.stock : product.stock) : 99;
|
||||||
const quantity = Math.min(e.q, Math.max(available, 0));
|
const quantity = Math.min(e.q, Math.max(available, 0));
|
||||||
if (quantity <= 0) continue;
|
if (quantity <= 0) continue;
|
||||||
|
|
@ -78,6 +85,8 @@ export async function getCart(): Promise<CartLine[]> {
|
||||||
sku: variant?.sku || product.sku,
|
sku: variant?.sku || product.sku,
|
||||||
image: product.images[0] ?? "",
|
image: product.images[0] ?? "",
|
||||||
unitPrice,
|
unitPrice,
|
||||||
|
originalUnitPrice: sale && unitPrice < basePrice ? basePrice : null,
|
||||||
|
saleName: sale?.name ?? "",
|
||||||
quantity,
|
quantity,
|
||||||
maxQuantity: Math.min(available, 99),
|
maxQuantity: Math.min(available, 99),
|
||||||
taxRate: product.taxRate,
|
taxRate: product.taxRate,
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ export const PERMISSION_GROUPS = [
|
||||||
permissions: [
|
permissions: [
|
||||||
{ key: "customers.view", label: "Kunden ansehen" },
|
{ key: "customers.view", label: "Kunden ansehen" },
|
||||||
{ key: "customers.edit", label: "Kunden bearbeiten" },
|
{ 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" },
|
{ key: "newsletter.view", label: "Newsletter-Anmeldungen ansehen" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
|
||||||
93
src/lib/sales.ts
Normal file
93
src/lib/sales.ts
Normal file
|
|
@ -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<SaleScope, string> = {
|
||||||
|
shop: "Ganzer Shop",
|
||||||
|
categories: "Kategorien",
|
||||||
|
products: "Einzelne Produkte",
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SaleState = "running" | "planned" | "ended" | "off";
|
||||||
|
|
||||||
|
export const SALE_STATES: Record<SaleState, { label: string; tone: "success" | "gold" | "neutral" }> = {
|
||||||
|
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<Sale, "active" | "startsAt" | "endsAt">, 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<Sale, "type" | "value">) {
|
||||||
|
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<T> = Omit<T, "variants"> & { 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<T extends Priced>(items: T[]): Promise<WithSale<T>[]> {
|
||||||
|
const sales = await getRunningSales();
|
||||||
|
return items.map((p): WithSale<T> => {
|
||||||
|
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<T>;
|
||||||
|
}
|
||||||
|
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<T>;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function withSale<T extends Priced>(item: T) {
|
||||||
|
return (await withSales([item]))[0];
|
||||||
|
}
|
||||||
|
|
@ -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-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 { 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; }
|
.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; }
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue