Video-Kurse: digitaler Produkttyp, Kapitel und Videos über Bunny Stream, Meine Kurse

- Produktart "Video-Kurs": kein Versand, kein Bestand, höchstens einmal im Warenkorb
- Admin: Kapitel und Einheiten anlegen, sortieren, Videos direkt aus dem Browser zu Bunny hochladen (TUS),
  Status wird automatisch nachgeladen; Zugänge ansehen, von Hand vergeben und entziehen
- Verbindungen: Assistent für Bunny Stream mit Prüfung beim Speichern, DRM als Option
- Kasse: Kurse nur mit Kundenkonto, reine Kurs-Warenkörbe ohne Versand-Schritt (Rechnungsadresse),
  Pflicht-Checkbox zum Widerrufsrecht bei digitalen Inhalten, Zustimmung im Bestellverlauf
- Freischaltung bei Zahlungseingang (Stripe, PayPal, Webhook, von Hand), Entzug bei Storno/Erstattung,
  reine Kurs-Bestellungen werden automatisch abgeschlossen; Mail "Kurs freigeschaltet" mit Widerrufsbestätigung
- Shop: Kurs-Produktseite mit Kursinhalt und kostenlosen Vorschau-Einheiten
- Konto: "Meine Kurse" mit Fortschritt, Player mit wanderndem Wasserzeichen (E-Mail), eigenem Vollbild,
  signierten kurzlebigen Links, Weiterschauen an der letzten Stelle, Einheiten als erledigt markieren
- Kurs mit Käufern wird beim Löschen nur ausgeblendet; Konto löschen entfernt Zugänge und Fortschritt

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Maaxxs 2026-10-20 21:50:55 +02:00
parent b83e21a21f
commit b3bc1ef596
47 changed files with 1686 additions and 93 deletions

View file

@ -0,0 +1,80 @@
-- AlterTable
ALTER TABLE "Product" ADD COLUMN "kind" TEXT NOT NULL DEFAULT 'physical';
-- CreateTable
CREATE TABLE "CourseChapter" (
"id" TEXT NOT NULL,
"productId" TEXT NOT NULL,
"title" TEXT NOT NULL,
"sort" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "CourseChapter_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CourseLesson" (
"id" TEXT NOT NULL,
"chapterId" TEXT NOT NULL,
"title" TEXT NOT NULL,
"description" TEXT NOT NULL DEFAULT '',
"videoId" TEXT NOT NULL DEFAULT '',
"videoStatus" TEXT NOT NULL DEFAULT 'none',
"duration" INTEGER NOT NULL DEFAULT 0,
"preview" BOOLEAN NOT NULL DEFAULT false,
"sort" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "CourseLesson_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CourseAccess" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"productId" TEXT NOT NULL,
"orderId" TEXT,
"expiresAt" TIMESTAMP(3),
"source" TEXT NOT NULL DEFAULT '',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "CourseAccess_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "LessonProgress" (
"userId" TEXT NOT NULL,
"lessonId" TEXT NOT NULL,
"position" INTEGER NOT NULL DEFAULT 0,
"completed" BOOLEAN NOT NULL DEFAULT false,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "LessonProgress_pkey" PRIMARY KEY ("userId","lessonId")
);
-- CreateIndex
CREATE INDEX "CourseAccess_orderId_idx" ON "CourseAccess"("orderId");
-- CreateIndex
CREATE UNIQUE INDEX "CourseAccess_userId_productId_key" ON "CourseAccess"("userId", "productId");
-- AddForeignKey
ALTER TABLE "CourseChapter" ADD CONSTRAINT "CourseChapter_productId_fkey" FOREIGN KEY ("productId") REFERENCES "Product"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CourseLesson" ADD CONSTRAINT "CourseLesson_chapterId_fkey" FOREIGN KEY ("chapterId") REFERENCES "CourseChapter"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CourseAccess" ADD CONSTRAINT "CourseAccess_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CourseAccess" ADD CONSTRAINT "CourseAccess_productId_fkey" FOREIGN KEY ("productId") REFERENCES "Product"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CourseAccess" ADD CONSTRAINT "CourseAccess_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "Order"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "LessonProgress" ADD CONSTRAINT "LessonProgress_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "LessonProgress" ADD CONSTRAINT "LessonProgress_lessonId_fkey" FOREIGN KEY ("lessonId") REFERENCES "CourseLesson"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View file

@ -40,6 +40,8 @@ model User {
resets PasswordReset[] resets PasswordReset[]
orders Order[] orders Order[]
addresses Address[] addresses Address[]
courseAccess CourseAccess[]
progress LessonProgress[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
} }
@ -123,6 +125,8 @@ model Product {
active Boolean @default(true) active Boolean @default(true)
featured Boolean @default(false) featured Boolean @default(false)
badge String @default("") // "", "new", "best" badge String @default("") // "", "new", "best"
// "physical" = Ware mit Versand, "course" = Video-Kurs (digital, ohne Versand und Bestand)
kind String @default("physical")
images String[] images String[]
sort Int @default(0) sort Int @default(0)
categoryId String? categoryId String?
@ -130,10 +134,74 @@ model Product {
variants ProductVariant[] variants ProductVariant[]
orderItems OrderItem[] orderItems OrderItem[]
stockAlerts StockAlert[] stockAlerts StockAlert[]
chapters CourseChapter[]
courseAccess CourseAccess[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
} }
// ---------- Video-Kurse ----------
model CourseChapter {
id String @id @default(cuid())
productId String
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
title String
sort Int @default(0)
lessons CourseLesson[]
}
model CourseLesson {
id String @id @default(cuid())
chapterId String
chapter CourseChapter @relation(fields: [chapterId], references: [id], onDelete: Cascade)
title String
description String @default("")
// Video bei Bunny Stream (GUID); leer, solange noch nichts hochgeladen ist
videoId String @default("")
// "none", "uploading", "processing", "ready", "error"
videoStatus String @default("none")
// Länge in Sekunden
duration Int @default(0)
// Kostenlose Vorschau auf der Produktseite
preview Boolean @default(false)
sort Int @default(0)
progress LessonProgress[]
createdAt DateTime @default(now())
}
// Wer welchen Kurs ansehen darf. Entsteht beim Zahlungseingang oder von Hand im Admin.
model CourseAccess {
id String @id @default(cuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
productId String
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
orderId String?
order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull)
// Leer = dauerhaft
expiresAt DateTime?
// Wer den Zugang vergeben hat ("Bestellung SM-10042" oder Name im Team)
source String @default("")
createdAt DateTime @default(now())
@@unique([userId, productId])
@@index([orderId])
}
model LessonProgress {
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
lessonId String
lesson CourseLesson @relation(fields: [lessonId], references: [id], onDelete: Cascade)
// Zuletzt gesehene Stelle in Sekunden
position Int @default(0)
completed Boolean @default(false)
updatedAt DateTime @updatedAt
@@id([userId, lessonId])
}
model ProductVariant { model ProductVariant {
id String @id @default(cuid()) id String @id @default(cuid())
productId String productId String
@ -212,6 +280,7 @@ model Order {
items OrderItem[] items OrderItem[]
events OrderEvent[] events OrderEvent[]
invoices Invoice[] invoices Invoice[]
courseAccess CourseAccess[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
} }

View file

@ -8,6 +8,8 @@ import { readCartCookie, writeCartCookie } from "@/lib/cart";
import { findCoupon } from "@/lib/pricing"; import { findCoupon } from "@/lib/pricing";
import { subscribe } from "@/lib/newsletter"; import { subscribe } from "@/lib/newsletter";
import { addStockAlert } from "@/lib/stock-alerts"; import { addStockAlert } from "@/lib/stock-alerts";
import { getCurrentUser } from "@/lib/auth";
import { hasCourseAccess, isCourse } from "@/lib/courses";
export async function subscribeNewsletter(_prev: unknown, formData: FormData) { export async function subscribeNewsletter(_prev: unknown, formData: FormData) {
const email = z.email().safeParse(String(formData.get("email") ?? "").trim().toLowerCase()); const email = z.email().safeParse(String(formData.get("email") ?? "").trim().toLowerCase());
@ -31,7 +33,9 @@ export async function addToCart(formData: FormData) {
const quantity = Math.max(1, Math.min(99, Number(formData.get("quantity") ?? 1) || 1)); const quantity = Math.max(1, Math.min(99, Number(formData.get("quantity") ?? 1) || 1));
const product = await db.product.findFirst({ where: { id: productId, active: true }, include: { variants: true } }); const product = await db.product.findFirst({ where: { id: productId, active: true }, include: { variants: true } });
if (!product) return; if (!product) return;
if (product.variants.length > 0 && !product.variants.some((v) => v.id === variantId)) { // Einen Kurs, den man schon hat, kauft man nicht noch einmal
if (isCourse(product) && (await hasCourseAccess((await getCurrentUser())?.id, product.id))) redirect(`/konto/kurse/${product.slug}`);
if (!isCourse(product) && product.variants.length > 0 && !product.variants.some((v) => v.id === variantId)) {
redirect(`/produkt/${product.slug}?variante=fehlt`); redirect(`/produkt/${product.slug}?variante=fehlt`);
} }
const entries = await readCartCookie(); const entries = await readCartCookie();

View file

@ -5,7 +5,7 @@ import { redirect } from "next/navigation";
import { z } from "zod"; import { z } from "zod";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth"; import { getCurrentUser } from "@/lib/auth";
import { getCart } from "@/lib/cart"; import { getCart, hasDigital, isDigitalOnly } from "@/lib/cart";
import { finishCheckoutSession } from "@/lib/checkout-finish"; import { finishCheckoutSession } from "@/lib/checkout-finish";
import { availablePayments, availableShipping, createOrder, readCheckout, writeCheckout } from "@/lib/checkout"; import { availablePayments, availableShipping, createOrder, readCheckout, writeCheckout } from "@/lib/checkout";
import { computeTotals } from "@/lib/pricing"; import { computeTotals } from "@/lib/pricing";
@ -62,7 +62,7 @@ export async function saveAddress(_prev: FormState, formData: FormData): Promise
billing, billing,
newsletter: formData.get("newsletter") === "on", newsletter: formData.get("newsletter") === "on",
}); });
redirect("/kasse/versand"); redirect(isDigitalOnly(await getCart()) ? "/kasse/zahlung" : "/kasse/versand");
} }
export async function saveShipping(_prev: FormState, formData: FormData): Promise<FormState> { export async function saveShipping(_prev: FormState, formData: FormData): Promise<FormState> {
@ -92,8 +92,15 @@ export async function placeOrder(_prev: FormState, formData: FormData): Promise<
const [state, lines, user, jar] = await Promise.all([readCheckout(), getCart(), getCurrentUser(), cookies()]); const [state, lines, user, jar] = await Promise.all([readCheckout(), getCart(), getCurrentUser(), cookies()]);
if (!lines.length) redirect("/warenkorb"); if (!lines.length) redirect("/warenkorb");
if (!state.email || !state.address) redirect("/kasse/adresse"); if (!state.email || !state.address) redirect("/kasse/adresse");
const shipping = state.shippingMethodId ? await db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : null; const digitalOnly = isDigitalOnly(lines);
if (!shipping?.enabled) redirect("/kasse/versand"); const withCourse = hasDigital(lines);
// Kurse gehören zu einem Konto und brauchen die ausdrückliche Zustimmung zum vorzeitigen Beginn (§ 356 Abs. 5 BGB)
if (withCourse && !user) redirect("/kasse/adresse");
if (withCourse && formData.get("digitalConsent") !== "on") {
return { errors: { digital: "Bitte bestätige die Zustimmung zum Widerrufsrecht bei digitalen Inhalten." } };
}
const shipping = digitalOnly ? null : state.shippingMethodId ? await db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : null;
if (!digitalOnly && !shipping?.enabled) redirect("/kasse/versand");
const payment = state.paymentMethodId ? await db.paymentMethod.findUnique({ where: { id: state.paymentMethodId } }) : null; const payment = state.paymentMethodId ? await db.paymentMethod.findUnique({ where: { id: state.paymentMethodId } }) : null;
if (!payment?.enabled) redirect("/kasse/zahlung"); if (!payment?.enabled) redirect("/kasse/zahlung");
const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value, shipping, payment }); const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value, shipping, payment });
@ -101,10 +108,13 @@ export async function placeOrder(_prev: FormState, formData: FormData): Promise<
let order; let order;
try { try {
order = await createOrder({ state, lines, totals, shippingName: shipping.name, payment, userId: user?.id ?? null, note: String(formData.get("note") ?? "").slice(0, 1000) }); order = await createOrder({ state, lines, totals, shippingName: shipping?.name ?? "Digital (kein Versand)", payment, userId: user?.id ?? null, note: String(formData.get("note") ?? "").slice(0, 1000) });
} catch (e) { } catch (e) {
return { message: e instanceof Error ? e.message : "Die Bestellung konnte nicht angelegt werden." }; return { message: e instanceof Error ? e.message : "Die Bestellung konnte nicht angelegt werden." };
} }
if (withCourse) {
await db.orderEvent.create({ data: { orderId: order.id, message: "Kunde hat der Bereitstellung der Video-Kurse vor Ablauf der Widerrufsfrist ausdrücklich zugestimmt und bestätigt, dass sein Widerrufsrecht damit erlischt.", author: "System" } });
}
await autoInvoice(order.id, "order"); await autoInvoice(order.id, "order");
const placedId = order.id; const placedId = order.id;
sendLater(() => mailOrderPlaced(placedId, "placed")); sendLater(() => mailOrderPlaced(placedId, "placed"));

View file

@ -9,11 +9,12 @@ export const metadata = { title: "Kasse – Adresse" };
export default async function AddressStep() { export default async function AddressStep() {
const [data, user, settings] = await Promise.all([loadCheckout(), getCurrentUser(), getSettings()]); const [data, user, settings] = await Promise.all([loadCheckout(), getCurrentUser(), getSettings()]);
if (!user && !settings.checkout.guestCheckout) { // Kurse landen im Kundenkonto, deshalb geht das nicht als Gast
if (!user && (!settings.checkout.guestCheckout || data.hasCourse)) {
return ( return (
<div className="sm-auth sm-box" style={{ textAlign: "center" }}> <div className="sm-auth sm-box" style={{ textAlign: "center" }}>
<h1 className="display-md" style={{ marginBottom: "var(--space-3)" }}>Bitte melde dich an</h1> <h1 className="display-md" style={{ marginBottom: "var(--space-3)" }}>Bitte melde dich an</h1>
<p className="body" style={{ color: "var(--ink-muted)" }}>Für eine Bestellung brauchst du ein Kundenkonto.</p> <p className="body" style={{ color: "var(--ink-muted)" }}>{data.hasCourse ? "Video-Kurse findest du nach dem Kauf in deinem Kundenkonto. Melde dich deshalb bitte an oder erstelle ein Konto." : "Für eine Bestellung brauchst du ein Kundenkonto."}</p>
<div className="sm-btn-row" style={{ justifyContent: "center" }}> <div className="sm-btn-row" style={{ justifyContent: "center" }}>
<Link className="sm-btn sm-btn--primary" href="/konto/anmelden?weiter=/kasse/adresse">Anmelden</Link> <Link className="sm-btn sm-btn--primary" href="/konto/anmelden?weiter=/kasse/adresse">Anmelden</Link>
<Link className="sm-btn sm-btn--secondary" href="/konto/registrieren?weiter=/kasse/adresse">Konto erstellen</Link> <Link className="sm-btn sm-btn--secondary" href="/konto/registrieren?weiter=/kasse/adresse">Konto erstellen</Link>
@ -42,6 +43,7 @@ export default async function AddressStep() {
newsletter={s.newsletter ?? false} newsletter={s.newsletter ?? false}
requirePhone={settings.checkout.requirePhone} requirePhone={settings.checkout.requirePhone}
countries={settings.checkout.countries.map((c) => [c, COUNTRIES[c] ?? c])} countries={settings.checkout.countries.map((c) => [c, COUNTRIES[c] ?? c])}
digital={data.digitalOnly}
/> />
</div> </div>
<CheckoutSummary data={data} /> <CheckoutSummary data={data} />

View file

@ -1,9 +1,11 @@
import { CheckoutSteps } from "@/components/shop/CheckoutSteps"; import { CheckoutSteps } from "@/components/shop/CheckoutSteps";
import { getCart, isDigitalOnly } from "@/lib/cart";
export default function CheckoutLayout({ children }: { children: React.ReactNode }) { export default async function CheckoutLayout({ children }: { children: React.ReactNode }) {
const digital = isDigitalOnly(await getCart());
return ( return (
<main className="sm-container sm-page"> <main className="sm-container sm-page">
<CheckoutSteps /> <CheckoutSteps digital={digital} />
{children} {children}
</main> </main>
); );

View file

@ -13,7 +13,7 @@ export default async function ReviewStep() {
const [data, settings] = await Promise.all([loadCheckout(), getSettings()]); const [data, settings] = await Promise.all([loadCheckout(), getSettings()]);
const { state, shipping, payment } = data; const { state, shipping, payment } = data;
if (!state.address || !state.email) redirect("/kasse/adresse"); if (!state.address || !state.email) redirect("/kasse/adresse");
if (!shipping) redirect("/kasse/versand"); if (!shipping && !data.digitalOnly) redirect("/kasse/versand");
if (!payment) redirect("/kasse/zahlung"); if (!payment) redirect("/kasse/zahlung");
const provider = getDefinition(payment.code)?.provider; const provider = getDefinition(payment.code)?.provider;
return ( return (
@ -22,17 +22,28 @@ export default async function ReviewStep() {
<h2 className="display-md" style={{ marginBottom: "var(--space-5)" }}>Alles richtig?</h2> <h2 className="display-md" style={{ marginBottom: "var(--space-5)" }}>Alles richtig?</h2>
<div className="sm-review"> <div className="sm-review">
<div className="sm-review__box"> <div className="sm-review__box">
<h3>Lieferadresse <Link href="/kasse/adresse">Ändern</Link></h3> <h3>{data.digitalOnly ? "Rechnungsadresse" : "Lieferadresse"} <Link href="/kasse/adresse">Ändern</Link></h3>
<AddressLines a={state.address} /> <AddressLines a={state.address} />
<p className="body-sm" style={{ color: "var(--ink-muted)", marginTop: "var(--space-2)" }}>{state.email}</p> <p className="body-sm" style={{ color: "var(--ink-muted)", marginTop: "var(--space-2)" }}>{state.email}</p>
</div> </div>
{!data.digitalOnly && (
<div className="sm-review__box"> <div className="sm-review__box">
<h3>Rechnungsadresse <Link href="/kasse/adresse">Ändern</Link></h3> <h3>Rechnungsadresse <Link href="/kasse/adresse">Ändern</Link></h3>
{state.billingSame === false && state.billing ? <AddressLines a={state.billing} /> : <p className="body">Wie Lieferadresse</p>} {state.billingSame === false && state.billing ? <AddressLines a={state.billing} /> : <p className="body">Wie Lieferadresse</p>}
</div> </div>
)}
<div className="sm-review__box"> <div className="sm-review__box">
{data.digitalOnly ? (
<>
<h3>Lieferung</h3>
<p className="body">Digital: Der Kurs erscheint nach dem Zahlungseingang unter „Meine Kurse“ in deinem Konto.</p>
</>
) : (
<>
<h3>Versand <Link href="/kasse/versand">Ändern</Link></h3> <h3>Versand <Link href="/kasse/versand">Ändern</Link></h3>
<p className="body">{shipping.name}</p> <p className="body">{shipping!.name}</p>
</>
)}
</div> </div>
<div className="sm-review__box"> <div className="sm-review__box">
<h3>Zahlung <Link href="/kasse/zahlung">Ändern</Link></h3> <h3>Zahlung <Link href="/kasse/zahlung">Ändern</Link></h3>
@ -40,7 +51,7 @@ export default async function ReviewStep() {
</div> </div>
</div> </div>
<div style={{ marginTop: "var(--space-6)" }}> <div style={{ marginTop: "var(--space-6)" }}>
<PlaceOrderForm requireTerms={settings.checkout.requireTerms} total={formatPrice(data.totals.total)} online={provider === "stripe" || provider === "paypal"} /> <PlaceOrderForm digital={data.hasCourse} requireTerms={settings.checkout.requireTerms} total={formatPrice(data.totals.total)} online={provider === "stripe" || provider === "paypal"} />
</div> </div>
</div> </div>
<CheckoutSummary data={data} /> <CheckoutSummary data={data} />

View file

@ -1,7 +1,7 @@
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getCart } from "@/lib/cart"; import { getCart, hasDigital, isDigitalOnly } from "@/lib/cart";
import { readCheckout } from "@/lib/checkout"; import { readCheckout } from "@/lib/checkout";
import { computeTotals } from "@/lib/pricing"; import { computeTotals } from "@/lib/pricing";
import { OrderSummary } from "@/components/shop/OrderSummary"; import { OrderSummary } from "@/components/shop/OrderSummary";
@ -15,7 +15,8 @@ export async function loadCheckout() {
state.paymentMethodId ? db.paymentMethod.findUnique({ where: { id: state.paymentMethodId } }) : null, state.paymentMethodId ? db.paymentMethod.findUnique({ where: { id: state.paymentMethodId } }) : null,
]); ]);
const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value, shipping, payment }); const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value, shipping, payment });
return { lines, state, shipping, payment, totals }; // Nur Kurse: kein Versand-Schritt; Kurse im Warenkorb: Konto und Widerrufs-Zustimmung nötig
return { lines, state, shipping, payment, totals, digitalOnly: isDigitalOnly(lines), hasCourse: hasDigital(lines) };
} }
export function CheckoutSummary({ data }: { data: Awaited<ReturnType<typeof loadCheckout>> }) { export function CheckoutSummary({ data }: { data: Awaited<ReturnType<typeof loadCheckout>> }) {
@ -23,7 +24,7 @@ export function CheckoutSummary({ data }: { data: Awaited<ReturnType<typeof load
<OrderSummary <OrderSummary
totals={data.totals} totals={data.totals}
lines={data.lines} lines={data.lines}
shippingLabel={data.shipping?.name} shippingLabel={data.digitalOnly ? "digital" : data.shipping?.name}
paymentLabel={data.payment?.name} paymentLabel={data.payment?.name}
/> />
); );

View file

@ -11,6 +11,7 @@ export const metadata = { title: "Kasse – Versand" };
export default async function ShippingStep() { export default async function ShippingStep() {
const data = await loadCheckout(); const data = await loadCheckout();
if (!data.state.address) redirect("/kasse/adresse"); if (!data.state.address) redirect("/kasse/adresse");
if (data.digitalOnly) redirect("/kasse/zahlung");
const methods = await availableShipping(data.state.address.country); const methods = await availableShipping(data.state.address.country);
const merchandise = data.totals.subtotal - data.totals.discount; const merchandise = data.totals.subtotal - data.totals.discount;
return ( return (

View file

@ -12,7 +12,7 @@ export const metadata = { title: "Kasse – Zahlung" };
export default async function PaymentStep({ searchParams }: { searchParams: Promise<{ abgebrochen?: string }> }) { export default async function PaymentStep({ searchParams }: { searchParams: Promise<{ abgebrochen?: string }> }) {
const [{ abgebrochen }, data, user] = await Promise.all([searchParams, loadCheckout(), getCurrentUser()]); const [{ abgebrochen }, data, user] = await Promise.all([searchParams, loadCheckout(), getCurrentUser()]);
if (!data.state.address) redirect("/kasse/adresse"); if (!data.state.address) redirect("/kasse/adresse");
if (!data.shipping) redirect("/kasse/versand"); if (!data.shipping && !data.digitalOnly) redirect("/kasse/versand");
const methods = await availablePayments(data.totals.total, Boolean(user)); const methods = await availablePayments(data.totals.total, Boolean(user));
return ( return (
<div className="sm-checkout"> <div className="sm-checkout">

View file

@ -0,0 +1,74 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { getCourseOutline, hasCourseAccess, isCourse } from "@/lib/courses";
import { embedUrl, getBunnyConfig, isBunnyReady } from "@/lib/bunny";
import { Alert } from "@/components/shop/Blocks";
import { CourseOutline } from "@/components/shop/CourseOutline";
import { LessonPlayer } from "@/components/shop/LessonPlayer";
export const metadata = { title: "Kurs", robots: { index: false } };
export default async function CoursePage({ params, searchParams }: { params: Promise<{ slug: string }>; searchParams: Promise<{ einheit?: string }> }) {
const [{ slug }, { einheit }, user] = await Promise.all([params, searchParams, getCurrentUser()]);
if (!user) redirect(`/konto/anmelden?weiter=/konto/kurse/${slug}`);
const product = await db.product.findUnique({ where: { slug } });
if (!product || !isCourse(product)) notFound();
if (!(await hasCourseAccess(user.id, product.id))) redirect(`/produkt/${slug}`);
const [outline, progress, bunny] = await Promise.all([
getCourseOutline(product.id),
db.lessonProgress.findMany({ where: { userId: user.id, lesson: { chapter: { productId: product.id } } } }),
getBunnyConfig(),
]);
const lessons = outline.flatMap((c) => c.lessons).filter((l) => l.videoStatus === "ready");
const byLesson = new Map(progress.map((p) => [p.lessonId, p]));
const done = new Set(progress.filter((p) => p.completed).map((p) => p.lessonId));
// Gewählte Einheit, sonst die zuletzt angefangene, sonst die erste noch offene
const lastStarted = [...progress].filter((p) => !p.completed && p.position > 0).sort((a, b) => +b.updatedAt - +a.updatedAt)[0];
const lesson = lessons.find((l) => l.id === einheit) ?? lessons.find((l) => l.id === lastStarted?.lessonId) ?? lessons.find((l) => !done.has(l.id)) ?? lessons[0];
const index = lesson ? lessons.indexOf(lesson) : -1;
const next = index >= 0 ? lessons[index + 1] : undefined;
const ready = isBunnyReady(bunny);
return (
<main className="sm-container sm-page sm-lesson">
<nav aria-label="Du bist hier">
<ol className="sm-crumbs">
<li><Link href="/konto">Mein Konto</Link></li>
<li><Link href="/konto/kurse">Meine Kurse</Link></li>
<li aria-current="page">{product.name}</li>
</ol>
</nav>
<div className="sm-lesson__grid">
<div>
{!lesson ? (
<Alert title="Hier kommen bald die Videos.">Dieser Kurs hat noch keine fertigen Einheiten. Schau bald wieder vorbei.</Alert>
) : !ready ? (
<Alert kind="danger" title="Die Videos sind gerade nicht erreichbar.">Bitte versuche es später noch einmal oder melde dich bei uns.</Alert>
) : (
<>
<LessonPlayer
lessonId={lesson.id}
src={embedUrl(bunny, lesson.videoId)}
title={lesson.title}
email={user.email}
startAt={byLesson.get(lesson.id)?.completed ? 0 : (byLesson.get(lesson.id)?.position ?? 0)}
done={done.has(lesson.id)}
nextHref={next ? `/konto/kurse/${slug}?einheit=${next.id}` : null}
/>
<h1 className="display-md" style={{ margin: "var(--space-5) 0 var(--space-2)" }}>{lesson.title}</h1>
{lesson.description && <p className="body" style={{ whiteSpace: "pre-line", color: "var(--ink-muted)" }}>{lesson.description}</p>}
</>
)}
</div>
<aside className="sm-lesson__side">
<span className="eyebrow">{product.name}</span>
<p className="caption sm-muted" style={{ margin: "var(--space-1) 0 var(--space-4)" }}>{done.size} von {lessons.length} Einheiten erledigt</p>
<CourseOutline chapters={outline} current={lesson?.id} done={done} hrefFor={(l) => `/konto/kurse/${slug}?einheit=${l.id}`} />
</aside>
</div>
</main>
);
}

View file

@ -0,0 +1,33 @@
"use server";
import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { hasCourseAccess } from "@/lib/courses";
/** Merkt sich, wie weit jemand eine Einheit gesehen hat. Ab 90 % oder am Ende gilt sie als erledigt. */
export async function saveLessonProgress(lessonId: string, seconds: number, duration: number, ended: boolean) {
const user = await getCurrentUser();
if (!user) return;
const lesson = await db.courseLesson.findUnique({ where: { id: lessonId }, include: { chapter: { select: { productId: true } } } });
if (!lesson || !(await hasCourseAccess(user.id, lesson.chapter.productId))) return;
const position = Math.max(0, Math.floor(Number(seconds) || 0));
const total = Math.floor(Number(duration) || lesson.duration || 0);
const completed = ended || (total > 0 && position >= total * 0.9);
await db.lessonProgress.upsert({
where: { userId_lessonId: { userId: user.id, lessonId } },
create: { userId: user.id, lessonId, position: completed ? 0 : position, completed },
// Einmal erledigt bleibt erledigt; die Stelle springt am Ende wieder auf den Anfang
update: { position: completed ? 0 : position, ...(completed ? { completed: true } : {}) },
});
}
export async function setLessonDone(lessonId: string, done: boolean) {
const user = await getCurrentUser();
if (!user) return;
const lesson = await db.courseLesson.findUnique({ where: { id: lessonId }, include: { chapter: { select: { productId: true } } } });
if (!lesson || !(await hasCourseAccess(user.id, lesson.chapter.productId))) return;
await db.lessonProgress.upsert({
where: { userId_lessonId: { userId: user.id, lessonId } },
create: { userId: user.id, lessonId, completed: done },
update: { completed: done },
});
}

View file

@ -0,0 +1,48 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { getCurrentUser } from "@/lib/auth";
import { getMyCourses } from "@/lib/courses";
import { Icon } from "@/components/Icon";
import { AccountShell } from "@/components/shop/account/AccountShell";
export const metadata = { title: "Meine Kurse" };
export default async function MyCoursesPage() {
const user = await getCurrentUser();
if (!user) redirect("/konto/anmelden?weiter=/konto/kurse");
const courses = await getMyCourses(user.id);
return (
<AccountShell user={user} title="Meine Kurse" lead="Deine Video-Kurse. Du kannst sie so oft ansehen, wie du möchtest.">
{courses.length === 0 ? (
<div className="sm-box sm-account__empty">
<Icon name="play" />
<p className="body">Du hast noch keinen Kurs. Gekaufte Kurse erscheinen hier, sobald die Zahlung angekommen ist.</p>
<Link className="sm-btn sm-btn--primary" href="/shop">Zum Shop</Link>
</div>
) : (
<div className="sm-mycourses">
{courses.map(({ product, lessons, completed }) => {
const pct = lessons ? Math.round((completed / lessons) * 100) : 0;
return (
<Link key={product.id} className="sm-box sm-mycourse" href={`/konto/kurse/${product.slug}`}>
{product.images[0] ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={product.images[0]} alt="" />
) : (
<span className="sm-mycourse__ph" aria-hidden="true"><Icon name="play" /></span>
)}
<div>
<strong>{product.name}</strong>
{product.subtitle && <span className="sm-muted">{product.subtitle}</span>}
<span className="sm-mycourse__bar" aria-hidden="true"><span style={{ width: `${pct}%` }} /></span>
<span className="caption sm-muted">{completed === 0 ? `${lessons} ${lessons === 1 ? "Einheit" : "Einheiten"}` : `${completed} von ${lessons} Einheiten erledigt`}</span>
</div>
<span className="sm-btn sm-btn--secondary sm-btn--sm">{completed === 0 ? "Starten" : completed === lessons ? "Ansehen" : "Weiter"}</span>
</Link>
);
})}
</div>
)}
</AccountShell>
);
}

View file

@ -31,7 +31,7 @@ export default async function ProfilePage() {
{!user.role && ( {!user.role && (
<section className="sm-box sm-account__panel"> <section className="sm-box sm-account__panel">
<h2 className="display-sm">Konto löschen</h2> <h2 className="display-sm">Konto löschen</h2>
<p className="body sm-muted">Dein Konto, dein Adressbuch und deine Newsletter-Anmeldung werden endgültig entfernt. Rechnungen zu deinen Bestellungen müssen wir gesetzlich aufbewahren, sie sind danach aber keinem Konto mehr zugeordnet.</p> <p className="body sm-muted">Dein Konto, dein Adressbuch und deine Newsletter-Anmeldung werden endgültig entfernt. Gekaufte Video-Kurse kannst du danach nicht mehr ansehen. Rechnungen zu deinen Bestellungen müssen wir gesetzlich aufbewahren, sie sind danach aber keinem Konto mehr zugeordnet.</p>
<DeleteAccountForm hasPassword={Boolean(user.passwordHash)} email={user.email} /> <DeleteAccountForm hasPassword={Boolean(user.passwordHash)} email={user.email} />
</section> </section>
)} )}

View file

@ -9,6 +9,11 @@ import { SectionHeading, TrustBar } from "@/components/shop/Blocks";
import { BuyBox } from "@/components/shop/BuyBox"; import { BuyBox } from "@/components/shop/BuyBox";
import { Gallery } from "@/components/shop/Gallery"; import { Gallery } from "@/components/shop/Gallery";
import { ProductCard } from "@/components/shop/ProductCard"; import { ProductCard } from "@/components/shop/ProductCard";
import { CourseBuyBox } from "@/components/shop/CourseBuyBox";
import { CourseOutline } from "@/components/shop/CourseOutline";
import { CoursePlayer } from "@/components/shop/CoursePlayer";
import { getCourseOutline, hasCourseAccess, isCourse } from "@/lib/courses";
import { embedUrl, getBunnyConfig, isBunnyReady } from "@/lib/bunny";
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) { export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params; const { slug } = await params;
@ -21,9 +26,9 @@ export default async function ProductPage({
searchParams, searchParams,
}: { }: {
params: Promise<{ slug: string }>; params: Promise<{ slug: string }>;
searchParams: Promise<{ variante?: string }>; searchParams: Promise<{ variante?: string; vorschau?: string }>;
}) { }) {
const [{ slug }, { variante }] = await Promise.all([params, searchParams]); const [{ slug }, { variante, vorschau }] = await Promise.all([params, searchParams]);
const raw = 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" } } },
@ -41,6 +46,12 @@ export default async function ProductPage({
}).then(withSales), }).then(withSales),
]); ]);
const shippingNote = settings.appearance.trustItems[0]; const shippingNote = settings.appearance.trustItems[0];
const course = isCourse(product);
const [outline, owned, bunny] = course ? await Promise.all([getCourseOutline(product.id), hasCourseAccess(user?.id, product.id), getBunnyConfig()]) : [[], false, null];
const allLessons = outline.flatMap((c) => c.lessons);
// Vorschau: nur Einheiten, die als Vorschau markiert und bei Bunny fertig sind
const previewLesson = vorschau ? allLessons.find((l) => l.id === vorschau && l.preview && l.videoStatus === "ready" && l.videoId) : undefined;
const previewSrc = previewLesson && bunny && isBunnyReady(bunny) ? embedUrl(bunny, previewLesson.videoId, 2) : null;
return ( return (
<main className="sm-container" style={{ paddingTop: "var(--space-5)", paddingBottom: "var(--space-9)" }}> <main className="sm-container" style={{ paddingTop: "var(--space-5)", paddingBottom: "var(--space-9)" }}>
@ -58,6 +69,18 @@ export default async function ProductPage({
{product.category && <span className="eyebrow">{product.category.name}</span>} {product.category && <span className="eyebrow">{product.category.name}</span>}
<h1 className="sm-pdp__title display-lg">{product.name}</h1> <h1 className="sm-pdp__title display-lg">{product.name}</h1>
{product.subtitle && <p className="body" style={{ margin: "0 0 var(--space-4)", color: "var(--ink-muted)" }}>{product.subtitle}</p>} {product.subtitle && <p className="body" style={{ margin: "0 0 var(--space-4)", color: "var(--ink-muted)" }}>{product.subtitle}</p>}
{course ? (
<CourseBuyBox
productId={product.id}
slug={product.slug}
price={product.price}
compareAt={product.compareAtPrice}
saleEndsAt={product.sale?.endsAt?.toISOString() ?? null}
owned={owned}
lessons={allLessons.length}
minutes={Math.round(allLessons.reduce((s, l) => s + l.duration, 0) / 60)}
/>
) : (
<BuyBox <BuyBox
productId={product.id} productId={product.id}
price={product.price} price={product.price}
@ -70,8 +93,9 @@ export default async function ProductPage({
missingVariant={variante === "fehlt"} missingVariant={variante === "fehlt"}
userEmail={user?.email} userEmail={user?.email}
/> />
)}
<ul className="sm-pdp__facts" style={{ marginTop: "var(--space-2)" }}> <ul className="sm-pdp__facts" style={{ marginTop: "var(--space-2)" }}>
{shippingNote && <li><Icon name={shippingNote.icon} /> {shippingNote.title}</li>} {shippingNote && !course && <li><Icon name={shippingNote.icon} /> {shippingNote.title}</li>}
{product.sku && <li className="caption">Art.-Nr. {product.sku}</li>} {product.sku && <li className="caption">Art.-Nr. {product.sku}</li>}
</ul> </ul>
<div style={{ marginTop: "var(--space-6)" }}> <div style={{ marginTop: "var(--space-6)" }}>
@ -81,18 +105,41 @@ export default async function ProductPage({
<div className="sm-acc__body" style={{ whiteSpace: "pre-line" }}>{product.description}</div> <div className="sm-acc__body" style={{ whiteSpace: "pre-line" }}>{product.description}</div>
</details> </details>
)} )}
{course && outline.length > 0 && (
<details className="sm-acc" open>
<summary>Inhalt des Kurses</summary>
<div className="sm-acc__body" id="inhalt">
{previewSrc && previewLesson && (
<div style={{ marginBottom: "var(--space-4)" }}>
<CoursePlayer src={previewSrc} title={`Vorschau: ${previewLesson.title}`} />
<p className="caption" style={{ color: "var(--ink-muted)", marginTop: "var(--space-2)" }}>Vorschau: {previewLesson.title}</p>
</div>
)}
<CourseOutline chapters={outline} current={previewLesson?.id} hrefFor={(l) => (owned ? `/konto/kurse/${product.slug}?einheit=${l.id}` : l.preview ? `/produkt/${product.slug}?vorschau=${l.id}#inhalt` : null)} />
</div>
</details>
)}
{product.details && ( {product.details && (
<details className="sm-acc"> <details className="sm-acc">
<summary>Material &amp; Pflege</summary> <summary>{course ? "Gut zu wissen" : <>Material &amp; Pflege</>}</summary>
<div className="sm-acc__body" style={{ whiteSpace: "pre-line" }}>{product.details}</div> <div className="sm-acc__body" style={{ whiteSpace: "pre-line" }}>{product.details}</div>
</details> </details>
)} )}
{course ? (
<details className="sm-acc">
<summary>Zugang &amp; Widerruf</summary>
<div className="sm-acc__body">
Nach dem Zahlungseingang findest du den Kurs in deinem Kundenkonto unter „Meine Kurse“. Du kannst ihn so oft ansehen, wie du möchtest. Für den Kauf brauchst du ein Kundenkonto. Bei digitalen Inhalten erlischt das Widerrufsrecht, sobald der Kurs freigeschaltet ist und du dem vorher ausdrücklich zugestimmt hast.
</div>
</details>
) : (
<details className="sm-acc"> <details className="sm-acc">
<summary>Versand &amp; Rückgabe</summary> <summary>Versand &amp; Rückgabe</summary>
<div className="sm-acc__body"> <div className="sm-acc__body">
{settings.appearance.trustItems.slice(0, 2).map((t) => `${t.title}. ${t.text}`).join(" ")} {settings.appearance.trustItems.slice(0, 2).map((t) => `${t.title}. ${t.text}`).join(" ")}
</div> </div>
</details> </details>
)}
</div> </div>
</div> </div>
</div> </div>

View file

@ -13,6 +13,7 @@ import type { AddressData } from "@/lib/checkout";
import { cancelLabel, canCreateLabels, createLabel, getDhlConfig } from "@/lib/dhl"; import { cancelLabel, canCreateLabels, createLabel, getDhlConfig } from "@/lib/dhl";
import { autoInvoice, cancelInvoice, createInvoice } from "@/lib/invoices"; import { autoInvoice, cancelInvoice, createInvoice } from "@/lib/invoices";
import { mailCancelled, mailPaymentReceived, mailShipped, sendLater } from "@/lib/mail/send"; import { mailCancelled, mailPaymentReceived, mailShipped, sendLater } from "@/lib/mail/send";
import { grantCourseAccess, isDigitalOrder, revokeCourseAccess } from "@/lib/courses";
const authorName = (u: { firstName: string; lastName: string; email: string }) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email; const authorName = (u: { firstName: string; lastName: string; email: string }) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email;
@ -48,7 +49,9 @@ export async function updateOrder(_prev: ActionResult, fd: FormData): Promise<Ac
if (events.length) await audit(user, "Bestellung geändert", `${order.number}: ${events.join(", ")}`); if (events.length) await audit(user, "Bestellung geändert", `${order.number}: ${events.join(", ")}`);
if (paymentStatus === "PAID" && order.paymentStatus !== "PAID") { if (paymentStatus === "PAID" && order.paymentStatus !== "PAID") {
await autoInvoice(id, "paid"); await autoInvoice(id, "paid");
sendLater(() => mailPaymentReceived(id)); // Reine Kurs-Bestellungen bekommen statt „Zahlung eingegangen, wir packen“ die Freischalt-Mail
if (!(await isDigitalOrder(id))) sendLater(() => mailPaymentReceived(id));
await grantCourseAccess(id);
} }
if (status === "SHIPPED" && order.status !== "SHIPPED") { if (status === "SHIPPED" && order.status !== "SHIPPED") {
await autoInvoice(id, "shipped"); await autoInvoice(id, "shipped");
@ -97,6 +100,7 @@ export async function cancelOrder(fd: FormData) {
}); });
}); });
await cancelInvoice(id, authorName(user)); await cancelInvoice(id, authorName(user));
await revokeCourseAccess(id);
sendLater(() => mailCancelled(id, wasPaid)); sendLater(() => mailCancelled(id, wasPaid));
await audit(user, wasPaid ? "Bestellung erstattet" : "Bestellung storniert", order.number); await audit(user, wasPaid ? "Bestellung erstattet" : "Bestellung storniert", order.number);
revalidatePath(`/admin/bestellungen/${id}`); revalidatePath(`/admin/bestellungen/${id}`);

View file

@ -12,7 +12,7 @@ import { deleteCustomer, saveCustomer } from "../actions";
export default async function CustomerDetail({ params }: { params: Promise<{ id: string }> }) { export default async function CustomerDetail({ params }: { params: Promise<{ id: string }> }) {
const user = await requireAdmin("customers.view"); const user = await requireAdmin("customers.view");
const { id } = await params; const { id } = await params;
const c = await db.user.findUnique({ where: { id }, include: { orders: { orderBy: { createdAt: "desc" } } } }); const c = await db.user.findUnique({ where: { id }, include: { orders: { orderBy: { createdAt: "desc" } }, courseAccess: { include: { product: { select: { name: true } } } } } });
if (!c || c.roleId) notFound(); if (!c || c.roleId) notFound();
return ( return (
<div className="ad-wrap"> <div className="ad-wrap">
@ -56,6 +56,7 @@ export default async function CustomerDetail({ params }: { params: Promise<{ id:
<p className="body-sm ad-muted" style={{ marginTop: 0 }}> <p className="body-sm ad-muted" style={{ marginTop: 0 }}>
Entfernt Konto, Anmeldedaten, Adressbuch und Newsletter-Anmeldung endgültig. Bestellungen und Rechnungen bleiben wegen der gesetzlichen Aufbewahrungspflicht erhalten, sind danach aber keinem Konto mehr zugeordnet. Entfernt Konto, Anmeldedaten, Adressbuch und Newsletter-Anmeldung endgültig. Bestellungen und Rechnungen bleiben wegen der gesetzlichen Aufbewahrungspflicht erhalten, sind danach aber keinem Konto mehr zugeordnet.
{open > 0 && <strong> Achtung: {open === 1 ? "1 Bestellung ist" : `${open} Bestellungen sind`} noch offen.</strong>} {open > 0 && <strong> Achtung: {open === 1 ? "1 Bestellung ist" : `${open} Bestellungen sind`} noch offen.</strong>}
{c.courseAccess.length > 0 && <strong> Die Person verliert den Zugang zu {c.courseAccess.length === 1 ? "einem Kurs" : `${c.courseAccess.length} Kursen`} ({c.courseAccess.map((a) => a.product.name).join(", ")}).</strong>}
</p> </p>
<ConfirmButton action={deleteCustomer} hidden={{ id: c.id }} confirm="Konto endgültig löschen?" className="sm-btn sm-btn--secondary sm-btn--sm">Kundenkonto löschen</ConfirmButton> <ConfirmButton action={deleteCustomer} hidden={{ id: c.id }} confirm="Konto endgültig löschen?" className="sm-btn sm-btn--secondary sm-btn--sm">Kundenkonto löschen</ConfirmButton>
</Card> </Card>

View file

@ -8,11 +8,12 @@ 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";
import { ProductForm } from "@/components/admin/ProductForm"; import { ProductForm } from "@/components/admin/ProductForm";
import { CourseEditor } from "@/components/admin/CourseEditor";
import { deleteProduct, duplicateProduct } from "../actions"; import { deleteProduct, duplicateProduct } from "../actions";
export default async function EditProduct({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ neu?: string }> }) { export default async function EditProduct({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ neu?: string; ausgeblendet?: string }> }) {
const user = await requireAdmin("products.view"); const user = await requireAdmin("products.view");
const [{ id }, { neu }] = await Promise.all([params, searchParams]); const [{ id }, { neu, ausgeblendet }] = await Promise.all([params, searchParams]);
const [p, categories] = await Promise.all([ const [p, categories] = await Promise.all([
db.product.findUnique({ where: { id }, include: { variants: { orderBy: { sort: "asc" } } } }), db.product.findUnique({ where: { id }, include: { variants: { orderBy: { sort: "asc" } } } }),
db.category.findMany({ orderBy: { sort: "asc" } }), db.category.findMany({ orderBy: { sort: "asc" } }),
@ -30,7 +31,8 @@ export default async function EditProduct({ params, searchParams }: { params: Pr
<ConfirmButton action={deleteProduct} hidden={{ id: p.id }} confirm="Produkt endgültig löschen?" className="sm-btn sm-btn--ghost">Löschen</ConfirmButton> <ConfirmButton action={deleteProduct} hidden={{ id: p.id }} confirm="Produkt endgültig löschen?" className="sm-btn sm-btn--ghost">Löschen</ConfirmButton>
)} )}
</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={p.kind === "course" ? "Kurs angelegt. Weiter unten legst du Kapitel und Einheiten an." : "Produkt angelegt."} /></div>}
{ausgeblendet && <div style={{ marginBottom: "var(--space-5)" }}><Alert title="Nicht gelöscht, nur ausgeblendet.">Diesen Kurs haben schon Kunden gekauft. Damit sie ihn weiter ansehen können, ist er nur aus dem Shop genommen.</Alert></div>}
{sale && ( {sale && (
<div style={{ marginBottom: "var(--space-5)" }}> <div style={{ marginBottom: "var(--space-5)" }}>
<Alert title={`Im Sale „${sale.name}“: im Shop ${formatPrice(reduce(p.price, sale))} statt ${formatPrice(p.price)}`}> <Alert title={`Im Sale „${sale.name}“: im Shop ${formatPrice(reduce(p.price, sale))} statt ${formatPrice(p.price)}`}>
@ -65,11 +67,13 @@ export default async function EditProduct({ params, searchParams }: { params: Pr
active: p.active, active: p.active,
featured: p.featured, featured: p.featured,
badge: p.badge, badge: p.badge,
kind: p.kind,
categoryId: p.categoryId ?? "", categoryId: p.categoryId ?? "",
images: p.images, images: p.images,
variants: p.variants.map((v) => ({ id: v.id, name: v.name, sku: v.sku, price: centsToInput(v.price), stock: String(v.stock) })), variants: p.variants.map((v) => ({ id: v.id, name: v.name, sku: v.sku, price: centsToInput(v.price), stock: String(v.stock) })),
}} }}
/> />
{p.kind === "course" && <CourseEditor productId={p.id} canEdit={can(user, "products.edit")} />}
</div> </div>
); );
} }

View file

@ -8,6 +8,13 @@ import { assertPermission, audit, can } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result"; import { fail, ok, type ActionResult } from "@/lib/action-result";
import { parsePrice } from "@/lib/money"; import { parsePrice } from "@/lib/money";
import { slugify } from "@/lib/slug"; import { slugify } from "@/lib/slug";
import { deleteBunnyVideo, getBunnyConfig } from "@/lib/bunny";
async function deleteVideos(ids: string[]) {
const c = await getBunnyConfig();
if (!c.libraryId || !c.apiKey) return;
for (const id of ids) await deleteBunnyVideo(c, id).catch(() => undefined);
}
type VariantInput = { id?: string; name: string; sku: string; price: string; stock: string }; type VariantInput = { id?: string; name: string; sku: string; price: string; stock: string };
@ -30,7 +37,9 @@ export async function saveProduct(_prev: ActionResult, fd: FormData): Promise<Ac
try { try {
variants = JSON.parse(String(fd.get("variants") ?? "[]")); variants = JSON.parse(String(fd.get("variants") ?? "[]"));
} catch {} } catch {}
variants = variants.filter((v) => v.name.trim()); const kind = fd.get("kind") === "course" ? "course" : "physical";
// Kurse haben keine Varianten und keinen Bestand
variants = kind === "course" ? [] : variants.filter((v) => v.name.trim());
for (const v of variants) { for (const v of variants) {
if (v.price.trim() && parsePrice(v.price) == null) errors.variants = `Preis der Variante „${v.name}“ ist ungültig.`; if (v.price.trim() && parsePrice(v.price) == null) errors.variants = `Preis der Variante „${v.name}“ ist ungültig.`;
} }
@ -48,11 +57,12 @@ export async function saveProduct(_prev: ActionResult, fd: FormData): Promise<Ac
description: String(fd.get("description") ?? ""), description: String(fd.get("description") ?? ""),
details: String(fd.get("details") ?? ""), details: String(fd.get("details") ?? ""),
sku: String(fd.get("sku") ?? "").trim(), sku: String(fd.get("sku") ?? "").trim(),
weight: Math.max(0, Math.round((Number(String(fd.get("weight") ?? "").replace(",", ".")) || 0) * 1000)), weight: kind === "course" ? 0 : Math.max(0, Math.round((Number(String(fd.get("weight") ?? "").replace(",", ".")) || 0) * 1000)),
price: price!, price: price!,
compareAtPrice, compareAtPrice,
taxRate: Number(fd.get("taxRate")) === 7 ? 7 : Number(fd.get("taxRate")) === 0 ? 0 : 19, taxRate: Number(fd.get("taxRate")) === 7 ? 7 : Number(fd.get("taxRate")) === 0 ? 0 : 19,
trackStock: fd.get("trackStock") === "on", kind,
trackStock: kind === "course" ? false : fd.get("trackStock") === "on",
active: fd.get("active") === "on", active: fd.get("active") === "on",
featured: fd.get("featured") === "on", featured: fd.get("featured") === "on",
badge: ["new", "best"].includes(String(fd.get("badge"))) ? String(fd.get("badge")) : "", badge: ["new", "best"].includes(String(fd.get("badge"))) ? String(fd.get("badge")) : "",
@ -89,7 +99,18 @@ export async function saveProduct(_prev: ActionResult, fd: FormData): Promise<Ac
export async function deleteProduct(fd: FormData) { export async function deleteProduct(fd: FormData) {
const user = await assertPermission("products.delete"); const user = await assertPermission("products.delete");
const id = String(fd.get("id")); const id = String(fd.get("id"));
// Ein Kurs, den schon jemand hat, wird nur ausgeblendet; sonst verlören Käufer ihren Zugang
const owners = await db.courseAccess.count({ where: { productId: id } });
if (owners > 0) {
const p = await db.product.update({ where: { id }, data: { active: false } });
await audit(user, "Kurs ausgeblendet statt gelöscht", `${p.name} (${owners} mit Zugang)`);
revalidatePath("/", "layout");
redirect(`/admin/produkte/${id}?ausgeblendet=1`);
}
const lessons = await db.courseLesson.findMany({ where: { chapter: { productId: id }, videoId: { not: "" } }, select: { videoId: true } });
const p = await db.product.delete({ where: { id } }); const p = await db.product.delete({ where: { id } });
// Videos bei Bunny mit löschen, damit keine Kosten weiterlaufen
if (lessons.length) sendLater(() => deleteVideos(lessons.map((l) => l.videoId)));
await audit(user, "Produkt gelöscht", p.name); await audit(user, "Produkt gelöscht", p.name);
revalidatePath("/", "layout"); revalidatePath("/", "layout");
redirect("/admin/produkte"); redirect("/admin/produkte");
@ -102,6 +123,7 @@ export async function duplicateProduct(fd: FormData) {
if (!p) return; if (!p) return;
let slug = `${p.slug}-kopie`; let slug = `${p.slug}-kopie`;
for (let i = 2; await db.product.findUnique({ where: { slug } }); i++) slug = `${p.slug}-kopie-${i}`; for (let i = 2; await db.product.findUnique({ where: { slug } }); i++) slug = `${p.slug}-kopie-${i}`;
// Kursinhalte (Kapitel, Videos) werden nicht mitkopiert
const { id: _id, createdAt: _c, updatedAt: _u, variants, ...rest } = p; const { id: _id, createdAt: _c, updatedAt: _u, variants, ...rest } = p;
const copy = await db.product.create({ const copy = await db.product.create({
data: { ...rest, name: `${p.name} (Kopie)`, slug, active: false, variants: { create: variants.map(({ id: _v, productId: _p, ...v }) => v) } }, data: { ...rest, name: `${p.name} (Kopie)`, slug, active: false, variants: { create: variants.map(({ id: _v, productId: _p, ...v }) => v) } },

View file

@ -0,0 +1,213 @@
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { db } from "@/lib/db";
import { assertPermission, audit } from "@/lib/auth";
import { fail, ok, type ActionResult } from "@/lib/action-result";
import { createBunnyVideo, deleteBunnyVideo, getBunnyConfig, getBunnyVideo, isBunnyReady, uploadSignature, videoStatus } from "@/lib/bunny";
// Kursinhalt im Admin: Kapitel, Einheiten, Video-Upload zu Bunny und Zugänge.
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
const who = (u: { firstName: string; lastName: string; email: string }) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email;
async function productOfChapter(chapterId: string) {
return (await db.courseChapter.findUnique({ where: { id: chapterId }, select: { productId: true } }))?.productId;
}
async function productOfLesson(lessonId: string) {
return (await db.courseLesson.findUnique({ where: { id: lessonId }, select: { chapter: { select: { productId: true } } } }))?.chapter.productId;
}
const refresh = (productId?: string | null) => {
if (!productId) return;
revalidatePath(`/admin/produkte/${productId}`);
revalidatePath("/", "layout");
};
async function dropVideo(videoId: string) {
if (!videoId) return;
const c = await getBunnyConfig();
if (c.libraryId && c.apiKey) await deleteBunnyVideo(c, videoId).catch(() => undefined);
}
// ---------- Kapitel ----------
export async function addChapter(fd: FormData) {
await assertPermission("products.edit");
const productId = str(fd, "productId");
const title = str(fd, "title") || "Neues Kapitel";
const last = await db.courseChapter.findFirst({ where: { productId }, orderBy: { sort: "desc" } });
await db.courseChapter.create({ data: { productId, title, sort: (last?.sort ?? -1) + 1 } });
refresh(productId);
}
export async function renameChapter(fd: FormData) {
await assertPermission("products.edit");
const id = str(fd, "id");
const title = str(fd, "title");
if (!title) return;
const c = await db.courseChapter.update({ where: { id }, data: { title } });
refresh(c.productId);
}
export async function moveChapter(fd: FormData) {
await assertPermission("products.edit");
const id = str(fd, "id");
const up = str(fd, "dir") === "up";
const c = await db.courseChapter.findUnique({ where: { id } });
if (!c) return;
const all = await db.courseChapter.findMany({ where: { productId: c.productId }, orderBy: { sort: "asc" } });
const i = all.findIndex((x) => x.id === id);
const j = up ? i - 1 : i + 1;
if (j < 0 || j >= all.length) return;
[all[i], all[j]] = [all[j], all[i]];
await db.$transaction(all.map((x, k) => db.courseChapter.update({ where: { id: x.id }, data: { sort: k } })));
refresh(c.productId);
}
export async function deleteChapter(fd: FormData) {
const user = await assertPermission("products.edit");
const id = str(fd, "id");
const c = await db.courseChapter.findUnique({ where: { id }, include: { lessons: true } });
if (!c) return;
await db.courseChapter.delete({ where: { id } });
for (const l of c.lessons) await dropVideo(l.videoId);
await audit(user, "Kurs-Kapitel gelöscht", c.title);
refresh(c.productId);
}
// ---------- Einheiten ----------
export async function addLesson(fd: FormData) {
await assertPermission("products.edit");
const chapterId = str(fd, "chapterId");
const title = str(fd, "title") || "Neue Einheit";
const last = await db.courseLesson.findFirst({ where: { chapterId }, orderBy: { sort: "desc" } });
await db.courseLesson.create({ data: { chapterId, title, sort: (last?.sort ?? -1) + 1 } });
refresh(await productOfChapter(chapterId));
}
export async function saveLesson(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
await assertPermission("products.edit");
const id = str(fd, "id");
const title = str(fd, "title");
if (!title) return fail("Bitte gib der Einheit einen Titel.", { title: "Bitte eintragen" });
const l = await db.courseLesson.update({
where: { id },
data: { title, description: String(fd.get("description") ?? "").trim(), preview: fd.get("preview") === "on" },
});
if (l.videoId) {
// Titel bei Bunny mitziehen, damit man die Videos dort wiederfindet (Fehler egal)
const c = await getBunnyConfig();
if (isBunnyReady(c)) void fetch(`https://video.bunnycdn.com/library/${c.libraryId}/videos/${l.videoId}`, { method: "POST", headers: { AccessKey: c.apiKey, "Content-Type": "application/json" }, body: JSON.stringify({ title }) }).catch(() => undefined);
}
refresh(await productOfLesson(id));
return ok();
}
export async function moveLesson(fd: FormData) {
await assertPermission("products.edit");
const id = str(fd, "id");
const up = str(fd, "dir") === "up";
const l = await db.courseLesson.findUnique({ where: { id } });
if (!l) return;
const all = await db.courseLesson.findMany({ where: { chapterId: l.chapterId }, orderBy: { sort: "asc" } });
const i = all.findIndex((x) => x.id === id);
const j = up ? i - 1 : i + 1;
if (j < 0 || j >= all.length) return;
[all[i], all[j]] = [all[j], all[i]];
await db.$transaction(all.map((x, k) => db.courseLesson.update({ where: { id: x.id }, data: { sort: k } })));
refresh(await productOfLesson(id));
}
export async function deleteLesson(fd: FormData) {
const user = await assertPermission("products.edit");
const id = str(fd, "id");
const productId = await productOfLesson(id);
const l = await db.courseLesson.delete({ where: { id } }).catch(() => null);
if (!l) return;
await dropVideo(l.videoId);
await audit(user, "Kurs-Einheit gelöscht", l.title);
refresh(productId);
}
// ---------- Video-Upload ----------
/** Legt das Video bei Bunny an und gibt die Signatur für den direkten Upload aus dem Browser zurück. Ein altes Video wird ersetzt. */
export async function startVideoUpload(lessonId: string) {
await assertPermission("products.edit");
const c = await getBunnyConfig();
if (!c.libraryId || !c.apiKey) return { ok: false as const, error: "Bunny Stream ist noch nicht eingerichtet (Verbindungen → Bunny Stream)." };
const l = await db.courseLesson.findUnique({ where: { id: lessonId }, include: { chapter: { include: { product: { select: { name: true } } } } } });
if (!l) return { ok: false as const, error: "Einheit nicht gefunden." };
try {
const video = await createBunnyVideo(c, `${l.chapter.product.name} · ${l.title}`);
const old = l.videoId;
await db.courseLesson.update({ where: { id: lessonId }, data: { videoId: video.guid, videoStatus: "uploading", duration: 0 } });
if (old) await dropVideo(old);
return { ok: true as const, ...uploadSignature(c, video.guid) };
} catch (e) {
return { ok: false as const, error: e instanceof Error ? e.message : String(e) };
}
}
export async function finishVideoUpload(lessonId: string, failed: boolean) {
await assertPermission("products.edit");
const l = await db.courseLesson.update({ where: { id: lessonId }, data: { videoStatus: failed ? "error" : "processing" } });
refresh(await productOfLesson(l.id));
}
/** Fragt bei Bunny nach, welche Videos fertig umgewandelt sind, und übernimmt die Länge. */
export async function refreshVideos(productId: string) {
await assertPermission("products.view");
const c = await getBunnyConfig();
if (!c.libraryId || !c.apiKey) return 0;
const pending = await db.courseLesson.findMany({ where: { chapter: { productId }, videoId: { not: "" }, videoStatus: { in: ["uploading", "processing"] } } });
let changed = 0;
for (const l of pending) {
try {
const v = await getBunnyVideo(c, l.videoId);
const status = l.videoStatus === "uploading" && v.status === 0 ? "uploading" : videoStatus(v.status);
if (status !== l.videoStatus || (v.length && v.length !== l.duration)) {
await db.courseLesson.update({ where: { id: l.id }, data: { videoStatus: status, duration: Math.round(v.length || 0) } });
changed++;
}
} catch {
// Video bei Bunny verschwunden: als Fehler markieren, damit es neu hochgeladen wird
await db.courseLesson.update({ where: { id: l.id }, data: { videoStatus: "error" } });
changed++;
}
}
if (changed) refresh(productId);
return changed;
}
// ---------- Zugänge ----------
export async function grantAccess(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("products.edit");
const productId = str(fd, "productId");
const email = z.email().safeParse(str(fd, "email").toLowerCase());
if (!email.success) return fail("Bitte gib eine gültige E-Mail-Adresse ein.", { email: "Ungültig" });
const customer = await db.user.findUnique({ where: { email: email.data } });
if (!customer) return fail("Zu dieser Adresse gibt es kein Kundenkonto. Die Person muss sich zuerst im Shop registrieren.", { email: "Kein Konto" });
const existing = await db.courseAccess.findUnique({ where: { userId_productId: { userId: customer.id, productId } } });
if (existing && (!existing.expiresAt || existing.expiresAt > new Date())) return fail("Diese Person hat schon Zugang.");
await db.courseAccess.upsert({
where: { userId_productId: { userId: customer.id, productId } },
create: { userId: customer.id, productId, source: `Von Hand: ${who(user)}` },
update: { expiresAt: null, orderId: null, source: `Von Hand: ${who(user)}` },
});
const p = await db.product.findUnique({ where: { id: productId }, select: { name: true } });
await audit(user, "Kurszugang vergeben", `${p?.name}: ${email.data}`);
refresh(productId);
return ok(`${email.data} hat jetzt Zugang. Der Kurs steht unter „Meine Kurse“ im Konto.`);
}
export async function revokeAccess(fd: FormData) {
const user = await assertPermission("products.edit");
const id = str(fd, "id");
const a = await db.courseAccess.delete({ where: { id }, include: { user: { select: { email: true } }, product: { select: { name: true } } } }).catch(() => null);
if (!a) return;
await audit(user, "Kurszugang entzogen", `${a.product.name}: ${a.user.email}`);
refresh(a.productId);
}

View file

@ -4,7 +4,8 @@ import { can, requireAdmin } from "@/lib/auth";
import { PageHead } from "@/components/admin/ui"; import { PageHead } from "@/components/admin/ui";
import { ProductForm } from "@/components/admin/ProductForm"; import { ProductForm } from "@/components/admin/ProductForm";
export default async function NewProduct() { export default async function NewProduct({ searchParams }: { searchParams: Promise<{ art?: string }> }) {
const course = (await searchParams).art === "kurs";
const user = await requireAdmin("products.edit"); const user = await requireAdmin("products.edit");
const categories = await db.category.findMany({ orderBy: { sort: "asc" } }); const categories = await db.category.findMany({ orderBy: { sort: "asc" } });
return ( return (
@ -13,7 +14,7 @@ export default async function NewProduct() {
<ProductForm <ProductForm
canStock={can(user, "stock.edit")} canStock={can(user, "stock.edit")}
categories={sortedForSelect(categories)} categories={sortedForSelect(categories)}
values={{ name: "", slug: "", subtitle: "", description: "", details: "", sku: "", weight: "", price: "", compareAtPrice: "", taxRate: 19, stock: 0, trackStock: true, active: true, featured: false, badge: "", categoryId: "", images: [], variants: [] }} values={{ name: "", slug: "", subtitle: "", description: "", details: "", sku: "", weight: "", price: "", compareAtPrice: "", taxRate: 19, stock: 0, trackStock: !course, active: true, featured: false, badge: "", kind: course ? "course" : "physical", categoryId: "", images: [], variants: [] }}
/> />
</div> </div>
); );

View file

@ -28,6 +28,7 @@ export default async function ProductsPage({ searchParams }: { searchParams: Pro
return ( return (
<div className="ad-wrap"> <div className="ad-wrap">
<PageHead title="Produkte" lead={`${products.length} Produkte`}> <PageHead title="Produkte" lead={`${products.length} Produkte`}>
{editable && <Link className="sm-btn sm-btn--secondary" href="/admin/produkte/neu?art=kurs"><Icon name="play" size="sm" /> Kurs anlegen</Link>}
{editable && <Link className="sm-btn sm-btn--primary" href="/admin/produkte/neu"><Icon name="plus" size="sm" /> Produkt anlegen</Link>} {editable && <Link className="sm-btn sm-btn--primary" href="/admin/produkte/neu"><Icon name="plus" size="sm" /> Produkt anlegen</Link>}
</PageHead> </PageHead>
<Card flush> <Card flush>

View file

@ -16,7 +16,8 @@ import { StatusPill } from "@/components/admin/IntegrationStatus";
import { MailServerFields } from "@/components/admin/MailServerFields"; import { MailServerFields } from "@/components/admin/MailServerFields";
import { MAIL_PRESETS, getMailConfig } from "@/lib/mail/config"; import { MAIL_PRESETS, getMailConfig } from "@/lib/mail/config";
import { getSettings } from "@/lib/settings"; import { getSettings } from "@/lib/settings";
import { disconnect, retest, saveApple, saveDhlConnection, saveGoogle, saveMail, savePaypal, saveStripe } from "../actions"; import { disconnect, retest, saveApple, saveBunny, saveDhlConnection, saveGoogle, saveMail, savePaypal, saveStripe } from "../actions";
import { getBunnyConfig } from "@/lib/bunny";
function LastTest({ t }: { t: TestResult | null }) { function LastTest({ t }: { t: TestResult | null }) {
if (!t) return null; if (!t) return null;
@ -299,6 +300,52 @@ async function MailWizard({ ok }: { ok: boolean }) {
); );
} }
// ---------- Bunny Stream ----------
async function BunnyWizard({ ok }: { ok: boolean }) {
const c = await getBunnyConfig();
const has = Boolean(c.libraryId && c.apiKey);
return (
<AdminForm action={saveBunny} submitLabel="Speichern und testen">
<Card>
<Steps>
<Step n={1} title="Bunny-Konto anlegen" done={ok && has}>
<p>Bunny speichert die Kursvideos und spielt sie in passender Qualität aus. Abgerechnet wird nach Verbrauch, für einen kleinen Shop meist nur wenige Euro im Monat. Die ersten 14 Tage sind kostenlos.</p>
<OpenLink href="https://dash.bunny.net/auth/register">Bei Bunny registrieren</OpenLink>
</Step>
<Step n={2} title="Video-Bibliothek anlegen" done={ok && has}>
<p>Links auf „Stream“ und dann „Add Video Library“ klicken. Name z. B. „Sanamare Kurse“, bei den Regionen nur <strong>Europa</strong> wählen (Datenschutz). In der neuen Bibliothek unter „API“ steht die <strong>Video Library ID</strong>, eine Zahl.</p>
<OpenLink href="https://dash.bunny.net/stream">Stream öffnen</OpenLink>
<Field label="Bibliotheks-ID" name="libraryId" defaultValue={c.libraryId} inputMode="numeric" placeholder="z. B. 123456" autoComplete="off" />
</Step>
<Step n={3} title="API-Schlüssel kopieren" done={ok && has}>
<p>Auf derselben Seite („API“) steht der <strong>API Key</strong> der Bibliothek. Damit lädt der Shop die Videos direkt aus dem Admin zu Bunny hoch.</p>
<Field label="API-Schlüssel" name="apiKey" type="password" autoComplete="off" placeholder={c.apiKey ? mask(c.apiKey) : ""} hint={c.apiKey ? "Gespeichert. Nur ausfüllen, wenn du ihn ersetzen willst." : undefined} />
</Step>
<Step n={4} title="Videos schützen" done={ok && Boolean(c.tokenKey)}>
<p>In der Bibliothek unter „Security“:</p>
<ol>
<li><strong>Embed view token authentication</strong> einschalten. Dann spielen die Videos nur über den Shop, mit einem Link, der nach wenigen Stunden abläuft.</li>
<li>Den <strong>Token authentication key</strong> kopieren und unten einfügen.</li>
<li>Unter „Allowed referrers“ deine Shop-Adressen eintragen:</li>
</ol>
{siteOrigins().map((o) => <CopyValue key={o} label="Erlaubte Domain" value={new URL(o).host} />)}
<p>Außerdem „Block direct url file access“ einschalten und unter „Player“ das Herunterladen ausschalten.</p>
<Field label="Token-Schlüssel" name="tokenKey" type="password" autoComplete="off" placeholder={c.tokenKey ? mask(c.tokenKey) : ""} hint={c.tokenKey ? "Gespeichert. Nur ausfüllen, wenn du ihn ersetzen willst." : undefined} />
</Step>
<Step n={5} title="Optional: DRM gegen Bildschirmaufnahmen">
<p>Mit „MediaCage Enterprise DRM“ (kostenpflichtig, unter „DRM“ in der Bibliothek) werden die Videos verschlüsselt. Bildschirmaufnahmen zeigen dann in Safari, Edge und auf den meisten Handys nur ein schwarzes Bild. Das Wasserzeichen mit der E-Mail des Kunden läuft immer, auch ohne DRM.</p>
<Switch name="drm" label="DRM ist bei Bunny gebucht und für die Bibliothek eingeschaltet" hint="Nur zur Anzeige im Admin. Verschlüsselt wird bei Bunny, sobald du DRM dort einschaltest." defaultChecked={c.drm} />
</Step>
<Step n={6} title="Speichern und testen">
<p>Ich prüfe Bibliothek und Schlüssel direkt bei Bunny. Danach legst du unter <a href="/admin/produkte/neu">Produkte</a> einen Kurs an (Art „Video-Kurs“) und lädst dort die Videos hoch.</p>
</Step>
</Steps>
</Card>
</AdminForm>
);
}
const WIZARDS: Record<IntegrationKey, (p: { ok: boolean }) => Promise<React.ReactElement>> = { const WIZARDS: Record<IntegrationKey, (p: { ok: boolean }) => Promise<React.ReactElement>> = {
stripe: StripeWizard, stripe: StripeWizard,
paypal: PaypalWizard, paypal: PaypalWizard,
@ -306,4 +353,5 @@ const WIZARDS: Record<IntegrationKey, (p: { ok: boolean }) => Promise<React.Reac
google: GoogleWizard, google: GoogleWizard,
apple: AppleWizard, apple: AppleWizard,
mail: MailWizard, mail: MailWizard,
bunny: BunnyWizard,
}; };

View file

@ -7,9 +7,10 @@ import { getDhlConfig, saveDhlConfig, splitStreet } from "@/lib/dhl";
import { getSettings } from "@/lib/settings"; import { getSettings } from "@/lib/settings";
import { getLoginProviders, saveLoginProviders } from "@/lib/social/config"; import { getLoginProviders, saveLoginProviders } from "@/lib/social/config";
import { isValidApplePrivateKey } from "@/lib/social/oauth"; import { isValidApplePrivateKey } from "@/lib/social/oauth";
import { createStripeWebhook, detectPaypalMode, forgetTest, saveDetectedPaypal, testDhlConnection, testLogin, testMail, testPaypal, testStripe, type IntegrationKey } from "@/lib/integrations"; import { createStripeWebhook, detectPaypalMode, forgetTest, saveDetectedPaypal, testBunny, testDhlConnection, testLogin, testMail, testPaypal, testStripe, type IntegrationKey } from "@/lib/integrations";
import { getMailConfig, saveMailConfig, type MailConfig } from "@/lib/mail/config"; import { getMailConfig, saveMailConfig, type MailConfig } from "@/lib/mail/config";
import { sendTestMail } from "@/lib/mail/send"; import { sendTestMail } from "@/lib/mail/send";
import { getBunnyConfig, isBunnyReady, saveBunnyConfig } from "@/lib/bunny";
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
// Leere Geheimfelder behalten den gespeicherten Wert // Leere Geheimfelder behalten den gespeicherten Wert
@ -195,7 +196,28 @@ export async function saveMail(_prev: ActionResult, fd: FormData): Promise<Actio
return done({ ok: true, message: `Testmail an ${user.email} verschickt. Schau in dein Postfach (auch im Spam-Ordner).${next.enabled ? "" : " Der Versand an Kunden ist noch ausgeschaltet."}` }); return done({ ok: true, message: `Testmail an ${user.email} verschickt. Schau in dein Postfach (auch im Spam-Ordner).${next.enabled ? "" : " Der Versand an Kunden ist noch ausgeschaltet."}` });
} }
const PERMS: Record<IntegrationKey, "payments.edit" | "shipping.edit" | "settings.edit" | "emails.edit"> = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit", mail: "emails.edit" }; export async function saveBunny(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
const user = await assertPermission("settings.edit");
const c = await getBunnyConfig();
const next = {
libraryId: str(fd, "libraryId").replace(/D/g, ""),
apiKey: keep(str(fd, "apiKey"), c.apiKey),
tokenKey: keep(str(fd, "tokenKey"), c.tokenKey),
drm: fd.get("drm") === "on",
};
if (!next.libraryId) return fail("Bitte trag die Bibliotheks-ID aus Schritt 2 ein (nur Ziffern).", { libraryId: "Bitte eintragen" });
if (!next.apiKey) return fail("Bitte füge den API-Schlüssel aus Schritt 3 ein.", { apiKey: "Bitte einfügen" });
const r = await testBunny(next);
// Eine funktionierende Verbindung nicht durch eine kaputte ersetzen, sonst laufen die Kurse nicht mehr.
// Bei der Ersteinrichtung trotzdem speichern, damit nichts neu eingetippt werden muss.
if (!r.ok && isBunnyReady(c)) return done({ ok: false, message: `${r.message} Nicht gespeichert, die bisherige Verbindung bleibt aktiv.` });
await saveBunnyConfig(next);
if (!r.ok) return done(r);
await audit(user, "Bunny Stream eingerichtet", `Bibliothek ${next.libraryId}${next.drm ? ", DRM" : ""}`);
return done(r);
}
const PERMS: Record<IntegrationKey, "payments.edit" | "shipping.edit" | "settings.edit" | "emails.edit"> = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit", mail: "emails.edit", bunny: "settings.edit" };
export async function disconnect(fd: FormData) { export async function disconnect(fd: FormData) {
const key = str(fd, "provider") as IntegrationKey; const key = str(fd, "provider") as IntegrationKey;
@ -212,6 +234,8 @@ export async function disconnect(fd: FormData) {
} else if (key === "mail") { } else if (key === "mail") {
const c = await getMailConfig(); const c = await getMailConfig();
await saveMailConfig({ ...c, host: "", user: "", password: "", enabled: false }); await saveMailConfig({ ...c, host: "", user: "", password: "", enabled: false });
} else if (key === "bunny") {
await saveBunnyConfig({ libraryId: "", apiKey: "", tokenKey: "", drm: false });
} else { } else {
const c = await getLoginProviders(); const c = await getLoginProviders();
if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" }; if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" };
@ -227,6 +251,6 @@ export async function retest(_prev: ActionResult, fd: FormData): Promise<ActionR
const key = str(fd, "provider") as IntegrationKey; const key = str(fd, "provider") as IntegrationKey;
if (!(key in PERMS)) return fail("Unbekannter Anbieter."); if (!(key in PERMS)) return fail("Unbekannter Anbieter.");
await assertPermission(PERMS[key]); await assertPermission(PERMS[key]);
const r = key === "stripe" ? await testStripe() : key === "paypal" ? await testPaypal() : key === "dhl" ? await testDhlConnection() : key === "mail" ? await testMail() : await testLogin(key); const r = key === "stripe" ? await testStripe() : key === "paypal" ? await testPaypal() : key === "dhl" ? await testDhlConnection() : key === "mail" ? await testMail() : key === "bunny" ? await testBunny() : await testLogin(key);
return done(r); return done(r);
} }

View file

@ -40,6 +40,7 @@ const PATHS = {
trash: (<><path d="M4 7h16M10 11v6M14 11v6" /><path d="M6 7l1 13h10l1-13M9 7V4h6v3" /></>), trash: (<><path d="M4 7h16M10 11v6M14 11v6" /><path d="M6 7l1 13h10l1-13M9 7V4h6v3" /></>),
edit: (<><path d="M4 20h4L19 9l-4-4L4 16z" /><path d="m13 7 4 4" /></>), edit: (<><path d="M4 20h4L19 9l-4-4L4 16z" /><path d="m13 7 4 4" /></>),
eye: (<><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" /><circle cx="12" cy="12" r="3" /></>), eye: (<><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" /><circle cx="12" cy="12" r="3" /></>),
play: (<><circle cx="12" cy="12" r="9" /><path d="m10 8.5 5.5 3.5-5.5 3.5z" /></>),
image: (<><rect x="3" y="4" width="18" height="16" rx="1" /><circle cx="9" cy="10" r="2" /><path d="m21 16-5-5-9 9" /></>), image: (<><rect x="3" y="4" width="18" height="16" rx="1" /><circle cx="9" cy="10" r="2" /><path d="m21 16-5-5-9 9" /></>),
grip: <path d="M9 6h.01M15 6h.01M9 12h.01M15 12h.01M9 18h.01M15 18h.01" />, grip: <path d="M9 6h.01M15 6h.01M9 12h.01M15 12h.01M9 18h.01M15 18h.01" />,
}; };

View file

@ -0,0 +1,151 @@
import Link from "next/link";
import { db } from "@/lib/db";
import { getBunnyConfig, isBunnyReady } from "@/lib/bunny";
import { formatDuration } from "@/lib/courses";
import { dateFmt } from "@/lib/status";
import { Alert } from "@/components/shop/Blocks";
import { Field } from "@/components/Field";
import { AdminForm, ConfirmButton } from "./AdminForm";
import { Card, Empty, Pill } from "./ui";
import { LessonForm } from "./LessonForm";
import { VideoStatusPoller, VideoUpload } from "./VideoUpload";
import { addChapter, addLesson, deleteChapter, deleteLesson, grantAccess, moveChapter, moveLesson, renameChapter, revokeAccess } from "@/app/admin/(panel)/produkte/kurs-actions";
const STATUS: Record<string, { tone: "neutral" | "gold" | "success" | "danger"; label: string }> = {
none: { tone: "neutral", label: "Kein Video" },
uploading: { tone: "gold", label: "Wird hochgeladen" },
processing: { tone: "gold", label: "Wird umgewandelt" },
ready: { tone: "success", label: "Bereit" },
error: { tone: "danger", label: "Fehler, bitte neu hochladen" },
};
function Move({ action, id, first, last }: { action: (fd: FormData) => Promise<void>; id: string; first: boolean; last: boolean }) {
return (
<span className="ad-move">
<form action={action}><input type="hidden" name="id" value={id} /><input type="hidden" name="dir" value="up" /><button type="submit" className="sm-btn sm-btn--ghost sm-btn--sm" disabled={first} aria-label="Nach oben">↑</button></form>
<form action={action}><input type="hidden" name="id" value={id} /><input type="hidden" name="dir" value="down" /><button type="submit" className="sm-btn sm-btn--ghost sm-btn--sm" disabled={last} aria-label="Nach unten">↓</button></form>
</span>
);
}
/** Kursinhalt (Kapitel, Einheiten, Videos) und Zugänge im Produkt. */
export async function CourseEditor({ productId, canEdit }: { productId: string; canEdit: boolean }) {
const [chapters, access, bunny] = await Promise.all([
db.courseChapter.findMany({ where: { productId }, orderBy: { sort: "asc" }, include: { lessons: { orderBy: { sort: "asc" } } } }),
db.courseAccess.findMany({ where: { productId }, orderBy: { createdAt: "desc" }, include: { user: { select: { email: true, firstName: true, lastName: true } }, order: { select: { id: true, number: true } } } }),
getBunnyConfig(),
]);
const ready = isBunnyReady(bunny);
const lessons = chapters.flatMap((c) => c.lessons);
const pending = lessons.some((l) => l.videoStatus === "uploading" || l.videoStatus === "processing");
const total = lessons.reduce((s, l) => s + l.duration, 0);
return (
<div style={{ marginTop: "var(--space-6)" }}>
<VideoStatusPoller productId={productId} active={pending} />
{!ready && (
<div style={{ marginBottom: "var(--space-5)" }}>
<Alert title="Für Videos fehlt noch Bunny Stream.">
Richte zuerst unter <Link href="/admin/verbindungen/bunny">Verbindungen → Bunny Stream</Link> die Video-Bibliothek ein. Kapitel und Einheiten kannst du schon anlegen.
</Alert>
</div>
)}
<Card title="Kursinhalt" lead={`${lessons.length} ${lessons.length === 1 ? "Einheit" : "Einheiten"}${total ? `, Gesamtlänge ${formatDuration(total)}` : ""}. Kunden sehen nur Einheiten mit fertigem Video.`}>
{chapters.length === 0 && <Empty title="Noch keine Kapitel" text="Lege ein erstes Kapitel an, z. B. „Grundlagen“, und darin die Einheiten mit je einem Video." />}
{chapters.map((c, ci) => (
<section key={c.id} className="ad-chapter">
<div className="ad-chapter__head">
{canEdit ? (
<form action={renameChapter} className="ad-chapter__title">
<input type="hidden" name="id" value={c.id} />
<input className="sm-input" name="title" defaultValue={c.title} aria-label="Titel des Kapitels" />
<button className="sm-btn sm-btn--ghost sm-btn--sm" type="submit">Umbenennen</button>
</form>
) : (
<h3>{c.title}</h3>
)}
{canEdit && (
<span className="ad-chapter__tools">
<Move action={moveChapter} id={c.id} first={ci === 0} last={ci === chapters.length - 1} />
<ConfirmButton action={deleteChapter} hidden={{ id: c.id }} confirm={`Kapitel mit ${c.lessons.length} ${c.lessons.length === 1 ? "Einheit" : "Einheiten"} und Videos löschen?`} className="sm-btn sm-btn--ghost sm-btn--sm">Löschen</ConfirmButton>
</span>
)}
</div>
{c.lessons.map((l, li) => {
const st = STATUS[l.videoStatus] ?? STATUS.none;
return (
<div key={l.id} className="ad-lesson">
<div className="ad-lesson__head">
<strong>{li + 1}. {l.title}</strong>
<span className="ad-lesson__meta">
<Pill tone={st.tone}>{st.label}</Pill>
{l.duration > 0 && <span className="caption ad-muted">{formatDuration(l.duration)}</span>}
{l.preview && <Pill tone="gold">Vorschau</Pill>}
</span>
{canEdit && (
<span className="ad-chapter__tools">
<Move action={moveLesson} id={l.id} first={li === 0} last={li === c.lessons.length - 1} />
<ConfirmButton action={deleteLesson} hidden={{ id: l.id }} confirm="Einheit und Video löschen?" className="sm-btn sm-btn--ghost sm-btn--sm">Löschen</ConfirmButton>
</span>
)}
</div>
{canEdit && (
<details className="ad-lesson__edit">
<summary>Bearbeiten und Video</summary>
<LessonForm id={l.id} title={l.title} description={l.description} preview={l.preview} />
{ready && <VideoUpload lessonId={l.id} hasVideo={Boolean(l.videoId)} />}
</details>
)}
</div>
);
})}
{canEdit && (
<form action={addLesson} className="ad-inline-add">
<input type="hidden" name="chapterId" value={c.id} />
<input className="sm-input" name="title" placeholder="Titel der neuen Einheit, z. B. „Atmung und Haltung“" aria-label="Titel der neuen Einheit" />
<button className="sm-btn sm-btn--secondary sm-btn--sm" type="submit">Einheit hinzufügen</button>
</form>
)}
</section>
))}
{canEdit && (
<form action={addChapter} className="ad-inline-add" style={{ marginTop: "var(--space-4)" }}>
<input type="hidden" name="productId" value={productId} />
<input className="sm-input" name="title" placeholder="Titel des neuen Kapitels, z. B. „Grundlagen“" aria-label="Titel des neuen Kapitels" />
<button className="sm-btn sm-btn--primary sm-btn--sm" type="submit">Kapitel hinzufügen</button>
</form>
)}
</Card>
<Card title="Zugänge" lead="Wer diesen Kurs ansehen darf. Nach dem Zahlungseingang kommt der Kunde automatisch dazu, bei Storno oder Erstattung fällt er wieder raus.">
{access.length === 0 ? (
<p className="body-sm ad-muted">Noch niemand.</p>
) : (
<div className="ad-table-wrap">
<table className="ad-table">
<thead><tr><th>Kunde</th><th>Seit</th><th>Über</th><th /></tr></thead>
<tbody>
{access.map((a) => (
<tr key={a.id}>
<td>{[a.user.firstName, a.user.lastName].filter(Boolean).join(" ") || a.user.email}<div className="body-sm ad-muted">{a.user.email}</div></td>
<td>{dateFmt.format(a.createdAt)}</td>
<td>{a.order ? <Link href={`/admin/bestellungen/${a.order.id}`}>Bestellung {a.order.number}</Link> : a.source || "–"}</td>
<td className="num">{canEdit && <ConfirmButton action={revokeAccess} hidden={{ id: a.id }} confirm="Zugang entziehen?" className="sm-btn sm-btn--ghost sm-btn--sm">Entziehen</ConfirmButton>}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{canEdit && (
<div style={{ marginTop: "var(--space-4)" }}>
<AdminForm action={grantAccess} submitLabel="Zugang geben">
<input type="hidden" name="productId" value={productId} />
<Field label="Zugang von Hand geben" name="email" type="email" placeholder="kundin@example.com" hint="Z. B. als Geschenk oder für Studio-Kunden. Die Person braucht ein Kundenkonto im Shop." />
</AdminForm>
</div>
)}
</Card>
</div>
);
}

View file

@ -0,0 +1,36 @@
"use client";
import { useActionState } from "react";
import { useFormStatus } from "react-dom";
import { saveLesson } from "@/app/admin/(panel)/produkte/kurs-actions";
import { Icon } from "../Icon";
function Save() {
const { pending } = useFormStatus();
return <button className="sm-btn sm-btn--secondary sm-btn--sm" type="submit" disabled={pending}>{pending ? "Speichert …" : "Speichern"}</button>;
}
/** Titel, Beschreibung und Vorschau-Schalter einer Einheit. */
export function LessonForm({ id, title, description, preview }: { id: string; title: string; description: string; preview: boolean }) {
const [state, action] = useActionState(saveLesson, null);
return (
<form action={action} className="ad-lesson__form">
<input type="hidden" name="id" value={id} />
<label className="sm-field">
<span className="sm-field__label">Titel</span>
<input className="sm-input" name="title" defaultValue={title} required />
</label>
<label className="sm-field">
<span className="sm-field__label">Beschreibung <small>optional</small></span>
<textarea className="sm-input" name="description" defaultValue={description} rows={2} />
</label>
<div className="ad-lesson__actions">
<label className="sm-check">
<input type="checkbox" name="preview" defaultChecked={preview} />
<span className="sm-check__text">Kostenlose Vorschau auf der Produktseite</span>
</label>
<Save />
{state?.message && <span className={state.ok ? "ad-ok" : "ad-err"}><Icon name={state.ok ? "check" : "alert"} size="sm" /> {state.message}</span>}
</div>
</form>
);
}

View file

@ -1,4 +1,5 @@
"use client"; "use client";
import { useState } from "react";
import type { Category } from "@prisma/client"; import type { Category } from "@prisma/client";
import { saveProduct } from "@/app/admin/(panel)/produkte/actions"; import { saveProduct } from "@/app/admin/(panel)/produkte/actions";
import { Field, SelectField, TextareaField } from "../Field"; import { Field, SelectField, TextareaField } from "../Field";
@ -24,12 +25,16 @@ export type ProductFormValues = {
active: boolean; active: boolean;
featured: boolean; featured: boolean;
badge: string; badge: string;
// "physical" oder "course"
kind: string;
categoryId: string; categoryId: string;
images: string[]; images: string[];
variants: VariantRow[]; variants: VariantRow[];
}; };
export function ProductForm({ values, categories, canStock }: { values: ProductFormValues; categories: (Pick<Category, "id" | "name"> & { label?: string })[]; canStock: boolean }) { export function ProductForm({ values, categories, canStock }: { values: ProductFormValues; categories: (Pick<Category, "id" | "name"> & { label?: string })[]; canStock: boolean }) {
const [kind, setKind] = useState(values.kind || "physical");
const course = kind === "course";
return ( return (
<AdminForm action={saveProduct} submitLabel={values.id ? "Änderungen speichern" : "Produkt anlegen"}> <AdminForm action={saveProduct} submitLabel={values.id ? "Änderungen speichern" : "Produkt anlegen"}>
{(state) => { {(state) => {
@ -41,10 +46,14 @@ export function ProductForm({ values, categories, canStock }: { values: ProductF
<section className="ad-card"> <section className="ad-card">
<div className="ad-card__head"><h2>Grunddaten</h2></div> <div className="ad-card__head"><h2>Grunddaten</h2></div>
<div className="ad-card__body"> <div className="ad-card__body">
<Field label="Name" name="name" defaultValue={values.name} error={e.name} placeholder="z. B. Reformer Matte Pro" required /> <SelectField label="Art" name="kind" value={kind} onChange={(ev) => setKind(ev.target.value)} hint={course ? (values.id ? "Kapitel und Videos bearbeitest du weiter unten." : "Nach dem Anlegen kannst du Kapitel und Videos hinzufügen.") : undefined}>
<option value="physical">Produkt mit Versand</option>
<option value="course">Video-Kurs (digital, kein Versand)</option>
</SelectField>
<Field label="Name" name="name" defaultValue={values.name} error={e.name} placeholder={course ? "z. B. Pilates Basics" : "z. B. Reformer Matte Pro"} required />
<Field label="Kurzbeschreibung" optional name="subtitle" defaultValue={values.subtitle} hint="Steht unter dem Namen, z. B. „Anthrazit · 8 mm“." /> <Field label="Kurzbeschreibung" optional name="subtitle" defaultValue={values.subtitle} hint="Steht unter dem Namen, z. B. „Anthrazit · 8 mm“." />
<TextareaField label="Beschreibung" name="description" defaultValue={values.description} rows={6} /> <TextareaField label="Beschreibung" name="description" defaultValue={values.description} rows={6} />
<TextareaField label="Material & Pflege" optional name="details" defaultValue={values.details} rows={3} /> <TextareaField label={course ? "Gut zu wissen (z. B. Level, was du brauchst)" : "Material & Pflege"} optional name="details" defaultValue={values.details} rows={3} />
</div> </div>
</section> </section>
<section className="ad-card"> <section className="ad-card">
@ -65,13 +74,13 @@ export function ProductForm({ values, categories, canStock }: { values: ProductF
</SelectField> </SelectField>
</div> </div>
</section> </section>
<section className="ad-card"> {!course && <section className="ad-card">
<div className="ad-card__head"><div><h2>Varianten</h2><p>Größen, Längen oder Farben – jede mit eigenem Bestand.</p></div></div> <div className="ad-card__head"><div><h2>Varianten</h2><p>Größen, Längen oder Farben – jede mit eigenem Bestand.</p></div></div>
<div className="ad-card__body"> <div className="ad-card__body">
<VariantEditor initial={values.variants} /> <VariantEditor initial={values.variants} />
{e.variants && <span className="sm-field__error"><Icon name="alert" /> {e.variants}</span>} {e.variants && <span className="sm-field__error"><Icon name="alert" /> {e.variants}</span>}
</div> </div>
</section> </section>}
</div> </div>
<div> <div>
<section className="ad-card"> <section className="ad-card">
@ -95,7 +104,7 @@ export function ProductForm({ values, categories, canStock }: { values: ProductF
</SelectField> </SelectField>
</div> </div>
</section> </section>
<section className="ad-card"> {!course && <section className="ad-card">
<div className="ad-card__head"><h2>Lager</h2></div> <div className="ad-card__head"><h2>Lager</h2></div>
<div className="ad-card__body"> <div className="ad-card__body">
<div className="sm-form-row"> <div className="sm-form-row">
@ -105,7 +114,7 @@ export function ProductForm({ values, categories, canStock }: { values: ProductF
<label className="ad-switch"><span className="ad-switch__text"><strong>Bestand verwalten</strong><small>Bei 0 wird das Produkt als ausverkauft gezeigt.</small></span><input type="checkbox" role="switch" name="trackStock" defaultChecked={values.trackStock} /></label> <label className="ad-switch"><span className="ad-switch__text"><strong>Bestand verwalten</strong><small>Bei 0 wird das Produkt als ausverkauft gezeigt.</small></span><input type="checkbox" role="switch" name="trackStock" defaultChecked={values.trackStock} /></label>
<Field label="Bestand" name="stock" type="number" min={0} defaultValue={values.stock} disabled={!canStock} hint={values.variants.length ? "Bei Varianten zählt der Bestand je Variante." : canStock ? undefined : "Dafür fehlt dir das Recht."} /> <Field label="Bestand" name="stock" type="number" min={0} defaultValue={values.stock} disabled={!canStock} hint={values.variants.length ? "Bei Varianten zählt der Bestand je Variante." : canStock ? undefined : "Dafür fehlt dir das Recht."} />
</div> </div>
</section> </section>}
<section className="ad-card"> <section className="ad-card">
<div className="ad-card__head"><h2>Web-Adresse</h2></div> <div className="ad-card__head"><h2>Web-Adresse</h2></div>
<div className="ad-card__body"> <div className="ad-card__body">

View file

@ -0,0 +1,132 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { finishVideoUpload, refreshVideos, startVideoUpload } from "@/app/admin/(panel)/produkte/kurs-actions";
// Lädt ein Video direkt aus dem Browser zu Bunny hoch (TUS-Protokoll, in Stücken, mit Wiederholung).
// So geht die große Datei nicht über unseren Server.
const CHUNK = 32 * 1024 * 1024;
const b64 = (s: string) => btoa(unescape(encodeURIComponent(s)));
type Sig = { endpoint: string; libraryId: string; videoId: string; expires: number; signature: string };
function send(method: string, url: string, headers: Record<string, string>, body: Blob | null, onProgress?: (loaded: number) => void) {
return new Promise<XMLHttpRequest>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);
if (onProgress) xhr.upload.onprogress = (e) => onProgress(e.loaded);
xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve(xhr) : reject(new Error(`HTTP ${xhr.status}`)));
xhr.onerror = () => reject(new Error("Netzwerkfehler"));
xhr.send(body);
});
}
async function tusUpload(file: File, sig: Sig, onProgress: (pct: number) => void) {
const auth = {
AuthorizationSignature: sig.signature,
AuthorizationExpire: String(sig.expires),
VideoId: sig.videoId,
LibraryId: sig.libraryId,
"Tus-Resumable": "1.0.0",
};
const created = await send("POST", sig.endpoint, { ...auth, "Upload-Length": String(file.size), "Upload-Metadata": `filetype ${b64(file.type || "video/mp4")},title ${b64(file.name)}` }, null);
const location = created.getResponseHeader("Location");
if (!location) throw new Error("Bunny hat keine Upload-Adresse geliefert.");
const url = new URL(location, sig.endpoint).toString();
let offset = 0;
let tries = 0;
while (offset < file.size) {
const chunk = file.slice(offset, offset + CHUNK);
try {
const res = await send("PATCH", url, { ...auth, "Upload-Offset": String(offset), "Content-Type": "application/offset+octet-stream" }, chunk, (loaded) => onProgress(((offset + loaded) / file.size) * 100));
offset = Number(res.getResponseHeader("Upload-Offset") ?? offset + chunk.size);
tries = 0;
} catch (e) {
if (++tries > 4) throw e;
await new Promise((r) => setTimeout(r, 1500 * tries));
// Nachfragen, wie viel schon angekommen ist, und dort weitermachen
const head = await send("HEAD", url, auth, null).catch(() => null);
offset = Number(head?.getResponseHeader("Upload-Offset") ?? offset);
}
onProgress((offset / file.size) * 100);
}
}
export function VideoUpload({ lessonId, hasVideo }: { lessonId: string; hasVideo: boolean }) {
const router = useRouter();
const input = useRef<HTMLInputElement>(null);
const [pct, setPct] = useState<number | null>(null);
const [error, setError] = useState("");
const upload = async (file: File) => {
setError("");
if (!file.type.startsWith("video/") && !/\.(mp4|mov|m4v|mkv|webm|avi)$/i.test(file.name)) {
setError("Bitte eine Videodatei wählen (z. B. MP4 oder MOV).");
return;
}
setPct(0);
const sig = await startVideoUpload(lessonId);
if (!sig.ok) {
setPct(null);
setError(sig.error);
return;
}
// Seite während des Uploads nicht versehentlich verlassen
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
window.addEventListener("beforeunload", warn);
try {
await tusUpload(file, sig, (p) => setPct(Math.min(99, Math.floor(p))));
await finishVideoUpload(lessonId, false);
setPct(null);
router.refresh();
} catch (e) {
await finishVideoUpload(lessonId, true);
setPct(null);
setError(`Upload abgebrochen: ${e instanceof Error ? e.message : e}. Bitte noch einmal versuchen.`);
router.refresh();
} finally {
window.removeEventListener("beforeunload", warn);
}
};
return (
<span className="ad-video-upload">
<input ref={input} type="file" accept="video/*" hidden onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])} />
{pct !== null ? (
<span className="ad-video-upload__progress" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
<span className="ad-video-upload__track"><span style={{ width: `${pct}%` }} /></span>
<small>Lädt hoch … {pct} %. Seite bitte offen lassen.</small>
</span>
) : (
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" onClick={() => input.current?.click()}>
{hasVideo ? "Video ersetzen" : "Video hochladen"}
</button>
)}
{error && <small className="ad-err" role="alert">{error}</small>}
</span>
);
}
/** Solange Videos bei Bunny umgewandelt werden: alle 15 Sekunden nachsehen. */
export function VideoStatusPoller({ productId, active }: { productId: string; active: boolean }) {
const router = useRouter();
useEffect(() => {
if (!active) return;
let stop = false;
let timer: ReturnType<typeof setTimeout>;
const tick = async () => {
const changed = await refreshVideos(productId).catch(() => 0);
if (stop) return;
if (changed) router.refresh();
timer = setTimeout(tick, 15000);
};
timer = setTimeout(tick, 5000);
return () => {
stop = true;
clearTimeout(timer);
};
}, [active, productId, router]);
return null;
}

View file

@ -37,6 +37,8 @@ export function AddressForm(props: {
requirePhone: boolean; requirePhone: boolean;
countries: [string, string][]; countries: [string, string][];
emailLocked: boolean; emailLocked: boolean;
// Nur Video-Kurse: keine Lieferung, die Adresse ist die Rechnungsadresse
digital?: boolean;
}) { }) {
const [state, action, pending] = useActionState(saveAddress, null); const [state, action, pending] = useActionState(saveAddress, null);
const [same, setSame] = useState(props.billingSame); const [same, setSame] = useState(props.billingSame);
@ -47,13 +49,18 @@ export function AddressForm(props: {
<h2 className="display-md" style={{ marginBottom: "var(--space-5)" }}>Kontakt</h2> <h2 className="display-md" style={{ marginBottom: "var(--space-5)" }}>Kontakt</h2>
<Field label="E-Mail-Adresse" name="email" type="email" autoComplete="email" defaultValue={props.email} readOnly={props.emailLocked} error={errors.email} hint="Hierhin schicken wir die Bestellbestätigung." required /> <Field label="E-Mail-Adresse" name="email" type="email" autoComplete="email" defaultValue={props.email} readOnly={props.emailLocked} error={errors.email} hint="Hierhin schicken wir die Bestellbestätigung." required />
<Field label="Telefon" optional={!props.requirePhone} name="phone" type="tel" autoComplete="tel" defaultValue={props.phone} error={errors.phone} hint="Nur für Rückfragen zur Lieferung." /> <Field label="Telefon" optional={!props.requirePhone} name="phone" type="tel" autoComplete="tel" defaultValue={props.phone} error={errors.phone} hint="Nur für Rückfragen zur Lieferung." />
<h2 className="display-md" style={{ margin: "var(--space-7) 0 var(--space-5)" }}>Lieferadresse</h2> <h2 className="display-md" style={{ margin: "var(--space-7) 0 var(--space-5)" }}>{props.digital ? "Rechnungsadresse" : "Lieferadresse"}</h2>
{props.digital && <p className="body-sm" style={{ color: "var(--ink-muted)", margin: "calc(var(--space-3) * -1) 0 var(--space-4)" }}>Für die Rechnung. Video-Kurse werden nicht verschickt, du findest sie nach dem Zahlungseingang in deinem Konto.</p>}
<AddressFields prefix="" values={props.address} errors={errors} countries={props.countries} /> <AddressFields prefix="" values={props.address} errors={errors} countries={props.countries} />
<div className="sm-field" style={{ marginTop: "var(--space-5)" }}> <div className="sm-field" style={{ marginTop: "var(--space-5)" }}>
{props.digital ? (
<input type="hidden" name="billingSame" value="on" />
) : (
<label className="sm-check"> <label className="sm-check">
<input type="checkbox" name="billingSame" checked={same} onChange={(e) => setSame(e.target.checked)} /> <input type="checkbox" name="billingSame" checked={same} onChange={(e) => setSame(e.target.checked)} />
<span className="sm-check__text">Rechnungsadresse ist Lieferadresse</span> <span className="sm-check__text">Rechnungsadresse ist Lieferadresse</span>
</label> </label>
)}
<label className="sm-check"> <label className="sm-check">
<input type="checkbox" name="newsletter" defaultChecked={props.newsletter} /> <input type="checkbox" name="newsletter" defaultChecked={props.newsletter} />
<span className="sm-check__text"> <span className="sm-check__text">
@ -61,14 +68,14 @@ export function AddressForm(props: {
</span> </span>
</label> </label>
</div> </div>
{!same && ( {!same && !props.digital && (
<> <>
<h2 className="display-md" style={{ margin: "var(--space-7) 0 var(--space-5)" }}>Rechnungsadresse</h2> <h2 className="display-md" style={{ margin: "var(--space-7) 0 var(--space-5)" }}>Rechnungsadresse</h2>
<AddressFields prefix="b_" values={props.billing} errors={errors} countries={props.countries} /> <AddressFields prefix="b_" values={props.billing} errors={errors} countries={props.countries} />
</> </>
)} )}
<div style={{ marginTop: "var(--space-7)" }}> <div style={{ marginTop: "var(--space-7)" }}>
<button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending}>Weiter zum Versand</button> <button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending}>{props.digital ? "Weiter zur Zahlung" : "Weiter zum Versand"}</button>
</div> </div>
</form> </form>
); );

View file

@ -9,13 +9,15 @@ const STEPS = [
{ href: "/kasse/pruefen", label: "Prüfen" }, { href: "/kasse/pruefen", label: "Prüfen" },
]; ];
export function CheckoutSteps() { /** Bei reinen Kurs-Bestellungen entfällt der Versand-Schritt. */
export function CheckoutSteps({ digital = false }: { digital?: boolean }) {
const pathname = usePathname(); const pathname = usePathname();
const current = STEPS.findIndex((s) => pathname.startsWith(s.href)); const steps = digital ? STEPS.filter((s) => s.href !== "/kasse/versand").map((s) => (s.href === "/kasse/adresse" ? { ...s, label: "Rechnung" } : s)) : STEPS;
const current = steps.findIndex((s) => pathname.startsWith(s.href));
if (current < 0) return null; if (current < 0) return null;
return ( return (
<ol className="sm-steps sm-checkout__steps" aria-label="Checkout-Fortschritt"> <ol className="sm-steps sm-checkout__steps" aria-label="Checkout-Fortschritt">
{STEPS.map((s, i) => ( {steps.map((s, i) => (
<li key={s.href} className={`sm-steps__item${i < current ? " is-done" : ""}${i === current ? " is-current" : ""}`} aria-current={i === current ? "step" : undefined}> <li key={s.href} className={`sm-steps__item${i < current ? " is-done" : ""}${i === current ? " is-current" : ""}`} aria-current={i === current ? "step" : undefined}>
{i < current ? <Link href={s.href}>{s.label}</Link> : <span>{s.label}</span>} {i < current ? <Link href={s.href}>{s.label}</Link> : <span>{s.label}</span>}
</li> </li>

View file

@ -0,0 +1,40 @@
import Link from "next/link";
import { addToCart } from "@/app/(shop)/actions";
import { formatPrice } from "@/lib/money";
import { Icon } from "../Icon";
/** Kaufbereich für Video-Kurse: keine Menge, kein Bestand. Wer den Kurs schon hat, kommt direkt hin. */
export function CourseBuyBox(props: { productId: string; slug: string; price: number; compareAt: number | null; saleEndsAt?: string | null; owned: boolean; lessons: number; minutes: number }) {
const compare = props.compareAt && props.compareAt > props.price ? props.compareAt : null;
return (
<div>
<div className="sm-price sm-price--lg">
{formatPrice(props.price)}
{compare && (
<>
<s className="sm-price__old">{formatPrice(compare)}</s>
<span className="sm-price__save">Du sparst {formatPrice(compare - props.price)}</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>
<span className="sm-price__note">inkl. MwSt. · digitaler Inhalt, kein Versand</span>
<div className="sm-pdp__cta">
{props.owned ? (
<Link className="sm-btn sm-btn--primary sm-btn--lg" href={`/konto/kurse/${props.slug}`}><Icon name="play" /> Zum Kurs</Link>
) : (
<form action={addToCart}>
<input type="hidden" name="productId" value={props.productId} />
<input type="hidden" name="quantity" value="1" />
<button className="sm-btn sm-btn--primary sm-btn--lg" type="submit">In den Warenkorb</button>
</form>
)}
</div>
<ul className="sm-pdp__facts">
{props.owned && <li><span className="sm-badge sm-badge--stock"><span className="sm-dot" aria-hidden="true" />Du hast diesen Kurs</span></li>}
{props.lessons > 0 && <li><Icon name="play" /> {props.lessons} {props.lessons === 1 ? "Einheit" : "Einheiten"}{props.minutes > 0 ? `, insgesamt etwa ${props.minutes} Minuten` : ""}</li>}
<li><Icon name="user" /> Zugang in deinem Kundenkonto, dauerhaft und auf all deinen Geräten</li>
</ul>
</div>
);
}

View file

@ -0,0 +1,45 @@
import Link from "next/link";
import { formatDuration } from "@/lib/courses";
import { Icon } from "../Icon";
type Lesson = { id: string; title: string; description: string; duration: number; preview: boolean; videoStatus: string };
type Chapter = { id: string; title: string; lessons: Lesson[] };
/**
* Kapitel und Einheiten eines Kurses. Auf der Produktseite mit Vorschau-Links,
* in „Meine Kurse“ mit Links zu allen Einheiten und Haken für erledigte.
*/
export function CourseOutline({ chapters, hrefFor, current, done }: { chapters: Chapter[]; hrefFor: (l: Lesson) => string | null; current?: string; done?: Set<string> }) {
if (!chapters.length) return null;
let n = 0;
return (
<div className="sm-course">
{chapters.map((c) => (
<section key={c.id} className="sm-course__chapter">
<h3>{c.title}</h3>
<ol>
{c.lessons.map((l) => {
n++;
const href = l.videoStatus === "ready" ? hrefFor(l) : null;
const body = (
<>
<span className="sm-course__num" aria-hidden="true">{done?.has(l.id) ? <Icon name="check" size="sm" /> : n}</span>
<span className="sm-course__title">
{l.title}
{l.preview && !done && <em>Vorschau</em>}
</span>
<span className="sm-course__time">{formatDuration(l.duration)}</span>
</>
);
return (
<li key={l.id} className={`${l.id === current ? "is-current" : ""}${done?.has(l.id) ? " is-done" : ""}`} aria-current={l.id === current ? "true" : undefined}>
{href ? <Link href={href} scroll={false}>{body}</Link> : <span className="sm-course__locked">{body}</span>}
</li>
);
})}
</ol>
</section>
))}
</div>
);
}

View file

@ -0,0 +1,105 @@
"use client";
import { useEffect, useRef, useState } from "react";
// Bunny-Player im iframe. Gesteuert über das player.js-Protokoll (postMessage), das der Bunny-Player spricht.
// Das Vollbild läuft über unseren Rahmen, damit das Wasserzeichen auch dort über dem Video liegt.
type Props = {
src: string;
title: string;
// E-Mail des Kunden als wanderndes Wasserzeichen; leer bei Vorschauvideos
watermark?: string;
startAt?: number;
onProgress?: (seconds: number, duration: number, ended: boolean) => void;
};
const SAVE_EVERY = 15;
export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }: Props) {
const frame = useRef<HTMLIFrameElement>(null);
const box = useRef<HTMLDivElement>(null);
const [pos, setPos] = useState({ x: 8, y: 10 });
const [full, setFull] = useState(false);
const lastSaved = useRef(0);
const report = useRef(onProgress);
report.current = onProgress;
// Wasserzeichen wandert alle paar Sekunden an eine andere Stelle
useEffect(() => {
if (!watermark) return;
const move = () => setPos({ x: 4 + Math.random() * 56, y: 6 + Math.random() * 76 });
move();
const id = setInterval(move, 7000);
return () => clearInterval(id);
}, [watermark]);
useEffect(() => {
const onFs = () => setFull(document.fullscreenElement === box.current);
document.addEventListener("fullscreenchange", onFs);
return () => document.removeEventListener("fullscreenchange", onFs);
}, []);
// player.js: auf "ready" warten, dann Zeit-Ereignisse abonnieren und ggf. an die letzte Stelle springen
useEffect(() => {
const target = () => frame.current?.contentWindow;
const send = (method: string, value?: unknown) => target()?.postMessage(JSON.stringify({ context: "player.js", version: "0.0.11", method, value }), "*");
let jumped = false;
const onMessage = (e: MessageEvent) => {
if (e.source !== target()) return;
let data: { context?: string; event?: string; value?: { seconds?: number; duration?: number } };
try {
data = typeof e.data === "string" ? JSON.parse(e.data) : e.data;
} catch {
return;
}
if (data?.context !== "player.js") return;
if (data.event === "ready") {
send("addEventListener", "timeupdate");
send("addEventListener", "ended");
if (startAt > 5 && !jumped) {
jumped = true;
send("setCurrentTime", startAt);
}
} else if (data.event === "timeupdate" && data.value?.seconds != null) {
const s = Math.floor(data.value.seconds);
if (Math.abs(s - lastSaved.current) >= SAVE_EVERY) {
lastSaved.current = s;
report.current?.(s, Math.floor(data.value.duration ?? 0), false);
}
} else if (data.event === "ended") {
report.current?.(0, 0, true);
}
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
}, [src, startAt]);
const toggleFull = () => {
if (document.fullscreenElement) void document.exitFullscreen();
else void box.current?.requestFullscreen?.();
};
return (
<div className={`sm-player${full ? " is-full" : ""}`} ref={box} onContextMenu={(e) => e.preventDefault()}>
<iframe
ref={frame}
src={src}
title={title}
loading="lazy"
// Kein allowFullScreen und kein Bild-im-Bild: sonst liefe das Video ohne Wasserzeichen
allow="accelerometer; gyroscope; autoplay; encrypted-media"
referrerPolicy="strict-origin-when-cross-origin"
/>
{watermark && (
<span className="sm-player__mark" style={{ left: `${pos.x}%`, top: `${pos.y}%` }} aria-hidden="true">
{watermark}
</span>
)}
<button type="button" className="sm-player__full" onClick={toggleFull} aria-label={full ? "Vollbild beenden" : "Vollbild"} title={full ? "Vollbild beenden" : "Vollbild"}>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
{full ? <path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5" /> : <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />}
</svg>
</button>
</div>
);
}

View file

@ -0,0 +1,43 @@
"use client";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { saveLessonProgress, setLessonDone } from "@/app/(shop)/konto/kurse/actions";
import { CoursePlayer } from "./CoursePlayer";
/** Player in „Meine Kurse“: speichert die Stelle und den Haken „erledigt“. */
export function LessonPlayer({ lessonId, src, title, email, startAt, done, nextHref }: { lessonId: string; src: string; title: string; email: string; startAt: number; done: boolean; nextHref: string | null }) {
const router = useRouter();
const [isDone, setDone] = useState(done);
const [pending, start] = useTransition();
const toggle = () =>
start(async () => {
await setLessonDone(lessonId, !isDone);
setDone(!isDone);
router.refresh();
});
return (
<>
<CoursePlayer
key={lessonId}
src={src}
title={title}
watermark={email}
startAt={startAt}
onProgress={(s, d, ended) => {
void saveLessonProgress(lessonId, s, d, ended).then(() => {
if (ended && !isDone) {
setDone(true);
router.refresh();
}
});
}}
/>
<div className="sm-lesson__bar">
<button type="button" className={`sm-btn sm-btn--sm ${isDone ? "sm-btn--secondary" : "sm-btn--ghost"}`} onClick={toggle} disabled={pending} aria-pressed={isDone}>
{isDone ? "✓ Erledigt" : "Als erledigt markieren"}
</button>
{nextHref && <a className="sm-btn sm-btn--primary sm-btn--sm" href={nextHref}>Nächste Einheit</a>}
</div>
</>
);
}

View file

@ -5,7 +5,7 @@ import { Icon } from "../Icon";
import { TextareaField } from "../Field"; import { TextareaField } from "../Field";
import { Alert } from "./Blocks"; import { Alert } from "./Blocks";
export function PlaceOrderForm({ requireTerms, total, online }: { requireTerms: boolean; total: string; online: boolean }) { export function PlaceOrderForm({ requireTerms, total, online, digital = false }: { requireTerms: boolean; total: string; online: boolean; digital?: boolean }) {
const [state, action, pending] = useActionState(placeOrder, null); const [state, action, pending] = useActionState(placeOrder, null);
return ( return (
<form action={action}> <form action={action}>
@ -22,6 +22,17 @@ export function PlaceOrderForm({ requireTerms, total, online }: { requireTerms:
{state?.errors?.terms && <span className="sm-field__error"><Icon name="alert" /> {state.errors.terms}</span>} {state?.errors?.terms && <span className="sm-field__error"><Icon name="alert" /> {state.errors.terms}</span>}
</div> </div>
)} )}
{digital && (
<div className={`sm-field${state?.errors?.digital ? " is-invalid" : ""}`} style={{ marginTop: "var(--space-4)" }}>
<label className="sm-check">
<input type="checkbox" name="digitalConsent" required />
<span className="sm-check__text">
Ich stimme ausdrücklich zu, dass ihr vor Ablauf der Widerrufsfrist mit der Bereitstellung der Video-Kurse beginnt. Mir ist bekannt, dass ich dadurch mein Widerrufsrecht für die Kurse verliere, sobald sie freigeschaltet sind.
</span>
</label>
{state?.errors?.digital && <span className="sm-field__error"><Icon name="alert" /> {state.errors.digital}</span>}
</div>
)}
<div style={{ marginTop: "var(--space-6)" }}> <div style={{ marginTop: "var(--space-6)" }}>
<button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending}> <button className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block" type="submit" disabled={pending}>
{pending ? "Einen Moment …" : `Zahlungspflichtig bestellen · ${total}`} {pending ? "Einen Moment …" : `Zahlungspflichtig bestellen · ${total}`}

View file

@ -6,6 +6,7 @@ import { Icon, type IconName } from "../../Icon";
const LINKS: { href: string; label: string; icon: IconName }[] = [ const LINKS: { href: string; label: string; icon: IconName }[] = [
{ href: "/konto", label: "Übersicht", icon: "dashboard" }, { href: "/konto", label: "Übersicht", icon: "dashboard" },
{ href: "/konto/bestellungen", label: "Bestellungen", icon: "box" }, { href: "/konto/bestellungen", label: "Bestellungen", icon: "box" },
{ href: "/konto/kurse", label: "Meine Kurse", icon: "play" },
{ href: "/konto/adressen", label: "Adressen", icon: "truck" }, { href: "/konto/adressen", label: "Adressen", icon: "truck" },
{ href: "/konto/profil", label: "Profil & Sicherheit", icon: "user" }, { href: "/konto/profil", label: "Profil & Sicherheit", icon: "user" },
]; ];

96
src/lib/bunny.ts Normal file
View file

@ -0,0 +1,96 @@
import "server-only";
import { createHash } from "node:crypto";
import { db } from "./db";
// Bunny Stream: Videos für die Kurse. Hochgeladen wird direkt aus dem Browser zu Bunny (TUS),
// abgespielt im Bunny-Player per iframe mit signiertem, kurzlebigem Link.
export type BunnyConfig = {
libraryId: string;
apiKey: string;
// "Token Authentication Key" der Bibliothek (Security → Embed view token authentication)
tokenKey: string;
// MediaCage Enterprise DRM ist bei Bunny gebucht und für die Bibliothek eingeschaltet
drm: boolean;
};
const DEFAULTS: BunnyConfig = { libraryId: "", apiKey: "", tokenKey: "", drm: false };
const KEY = "bunny_stream";
const API = "https://video.bunnycdn.com";
const EMBED = "https://iframe.mediadelivery.net/embed";
export async function getBunnyConfig(): Promise<BunnyConfig> {
const row = await db.setting.findUnique({ where: { key: KEY } });
return { ...DEFAULTS, ...((row?.value ?? {}) as Partial<BunnyConfig>) };
}
export async function saveBunnyConfig(value: BunnyConfig) {
await db.setting.upsert({ where: { key: KEY }, create: { key: KEY, value }, update: { value } });
}
export const isBunnyReady = (c: BunnyConfig) => Boolean(c.libraryId && c.apiKey && c.tokenKey);
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
async function api<T>(c: BunnyConfig, path: string, init?: { method?: string; body?: unknown }): Promise<T> {
const res = await fetch(`${API}/library/${encodeURIComponent(c.libraryId)}${path}`, {
method: init?.method ?? "GET",
headers: { AccessKey: c.apiKey, Accept: "application/json", ...(init?.body ? { "Content-Type": "application/json" } : {}) },
body: init?.body ? JSON.stringify(init.body) : undefined,
cache: "no-store",
});
if (!res.ok) {
const text = await res.text().catch(() => "");
if (res.status === 401) throw new Error("Bunny lehnt den API-Schlüssel ab (Bibliotheks-ID oder Schlüssel passen nicht zusammen).");
if (res.status === 404) throw new Error("Bunny kennt diese Bibliothek oder dieses Video nicht.");
throw new Error(`Bunny meldet HTTP ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
}
return (res.status === 204 ? null : await res.json()) as T;
}
/** Prüft Bibliotheks-ID und API-Schlüssel, ohne etwas zu verändern. */
export async function testBunnyApi(c: BunnyConfig) {
const data = await api<{ totalItems: number }>(c, "/videos?page=1&itemsPerPage=1");
return data.totalItems ?? 0;
}
type BunnyVideo = { guid: string; status: number; length: number; title: string };
export async function createBunnyVideo(c: BunnyConfig, title: string) {
return api<BunnyVideo>(c, "/videos", { method: "POST", body: { title } });
}
export async function getBunnyVideo(c: BunnyConfig, videoId: string) {
return api<BunnyVideo>(c, `/videos/${encodeURIComponent(videoId)}`);
}
export async function deleteBunnyVideo(c: BunnyConfig, videoId: string) {
await api(c, `/videos/${encodeURIComponent(videoId)}`, { method: "DELETE" });
}
/** Bunny-Status → unser Status. 4 = fertig, 5/6 = Fehler, alles andere läuft noch. */
export function videoStatus(bunnyStatus: number): "processing" | "ready" | "error" {
if (bunnyStatus === 4) return "ready";
if (bunnyStatus === 5 || bunnyStatus === 6) return "error";
return "processing";
}
/** Signatur für den direkten Upload aus dem Browser (TUS), gültig für 24 Stunden. */
export function uploadSignature(c: BunnyConfig, videoId: string) {
const expires = Math.floor(Date.now() / 1000) + 24 * 3600;
return {
endpoint: `${API}/tusupload`,
libraryId: c.libraryId,
videoId,
expires,
signature: sha256(c.libraryId + c.apiKey + expires + videoId),
};
}
/** Signierter Player-Link. Läuft nach `hours` Stunden ab; danach muss die Seite neu geladen werden. */
export function embedUrl(c: BunnyConfig, videoId: string, hours = 6) {
const expires = Math.floor(Date.now() / 1000) + hours * 3600;
const token = sha256(c.tokenKey + videoId + expires);
const q = new URLSearchParams({ token, expires: String(expires), autoplay: "false", preload: "true", responsive: "true" });
return `${EMBED}/${encodeURIComponent(c.libraryId)}/${encodeURIComponent(videoId)}?${q}`;
}

View file

@ -51,8 +51,14 @@ export type CartLine = {
maxQuantity: number; maxQuantity: number;
taxRate: number; taxRate: number;
total: number; total: number;
// Video-Kurs: kein Versand, kein Bestand, höchstens einmal im Warenkorb
digital: boolean;
}; };
/** Nur Kurse im Warenkorb: kein Versand, keine Lieferadresse nötig. */
export const isDigitalOnly = (lines: Pick<CartLine, "digital">[]) => lines.length > 0 && lines.every((l) => l.digital);
export const hasDigital = (lines: Pick<CartLine, "digital">[]) => lines.some((l) => l.digital);
/** Löst die Cookie-Einträge gegen die Datenbank auf; Preise kommen immer aus der DB. */ /** Löst die Cookie-Einträge gegen die Datenbank auf; Preise kommen immer aus der DB. */
export async function getCart(): Promise<CartLine[]> { export async function getCart(): Promise<CartLine[]> {
const entries = await readCartCookie(); const entries = await readCartCookie();
@ -71,7 +77,8 @@ export async function getCart(): Promise<CartLine[]> {
const basePrice = variant?.price ?? product.price; const basePrice = variant?.price ?? product.price;
const sale = sales.length ? bestSale(sales, product) : null; const sale = sales.length ? bestSale(sales, product) : null;
const unitPrice = sale ? reduce(basePrice, sale) : basePrice; const unitPrice = sale ? reduce(basePrice, sale) : basePrice;
const available = product.trackStock ? (variant ? variant.stock : product.stock) : 99; const digital = product.kind === "course";
const available = digital ? 1 : 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;
lines.push({ lines.push({
@ -91,6 +98,7 @@ export async function getCart(): Promise<CartLine[]> {
maxQuantity: Math.min(available, 99), maxQuantity: Math.min(available, 99),
taxRate: product.taxRate, taxRate: product.taxRate,
total: unitPrice * quantity, total: unitPrice * quantity,
digital,
}); });
} }
return lines; return lines;

View file

@ -10,6 +10,7 @@ import { getSettings } from "./settings";
import { autoInvoice } from "./invoices"; import { autoInvoice } from "./invoices";
import { mailOrderPlaced, sendLater } from "./mail/send"; import { mailOrderPlaced, sendLater } from "./mail/send";
import { subscribe } from "./newsletter"; import { subscribe } from "./newsletter";
import { grantCourseAccess } from "./courses";
export const CHECKOUT_COOKIE = "sm_checkout"; export const CHECKOUT_COOKIE = "sm_checkout";
@ -88,7 +89,7 @@ async function nextOrderNumber(tx: Prisma.TransactionClient) {
export async function restock(tx: Prisma.TransactionClient, orderId: string) { export async function restock(tx: Prisma.TransactionClient, orderId: string) {
const items = await tx.orderItem.findMany({ where: { orderId }, include: { product: true } }); const items = await tx.orderItem.findMany({ where: { orderId }, include: { product: true } });
for (const it of items) { for (const it of items) {
if (!it.product?.trackStock) continue; if (!it.product?.trackStock || it.product.kind === "course") continue;
if (it.variantId) await tx.productVariant.updateMany({ where: { id: it.variantId }, data: { stock: { increment: it.quantity } } }); if (it.variantId) await tx.productVariant.updateMany({ where: { id: it.variantId }, data: { stock: { increment: it.quantity } } });
else await tx.product.update({ where: { id: it.product.id }, data: { stock: { increment: it.quantity } } }); else await tx.product.update({ where: { id: it.product.id }, data: { stock: { increment: it.quantity } } });
} }
@ -117,7 +118,7 @@ export async function createOrder(opts: {
// Bestand prüfen und reservieren // Bestand prüfen und reservieren
for (const l of lines) { for (const l of lines) {
const product = await tx.product.findUnique({ where: { id: l.productId } }); const product = await tx.product.findUnique({ where: { id: l.productId } });
if (!product?.trackStock) continue; if (!product?.trackStock || product.kind === "course") continue;
if (l.variantId) { if (l.variantId) {
const r = await tx.productVariant.updateMany({ where: { id: l.variantId, stock: { gte: l.quantity } }, data: { stock: { decrement: l.quantity } } }); const r = await tx.productVariant.updateMany({ where: { id: l.variantId, stock: { gte: l.quantity } }, data: { stock: { decrement: l.quantity } } });
if (r.count === 0) throw new Error(`${l.name} – ${l.variantName} ist nicht mehr in dieser Menge verfügbar.`); if (r.count === 0) throw new Error(`${l.name} – ${l.variantName} ist nicht mehr in dieser Menge verfügbar.`);
@ -183,5 +184,6 @@ export async function markOrderPaid(orderId: string, reference: string, source:
}); });
await autoInvoice(orderId, "paid"); await autoInvoice(orderId, "paid");
sendLater(() => mailOrderPlaced(orderId, "paid")); sendLater(() => mailOrderPlaced(orderId, "paid"));
await grantCourseAccess(orderId);
return updated; return updated;
} }

98
src/lib/courses.ts Normal file
View file

@ -0,0 +1,98 @@
import "server-only";
import { db } from "./db";
import { appUrl } from "./social/config";
import { sendLater, sendTemplate } from "./mail/send";
export const COURSE = "course";
export const isCourse = (p: { kind: string }) => p.kind === COURSE;
/** Zugang gilt: vorhanden und nicht abgelaufen. */
export async function hasCourseAccess(userId: string | null | undefined, productId: string) {
if (!userId) return false;
const a = await db.courseAccess.findUnique({ where: { userId_productId: { userId, productId } } });
return Boolean(a && (!a.expiresAt || a.expiresAt > new Date()));
}
/** Alle Kurse eines Kunden mit Fortschritt, neueste zuerst. */
export async function getMyCourses(userId: string) {
const access = await db.courseAccess.findMany({
where: { userId, OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }] },
orderBy: { createdAt: "desc" },
include: { product: { include: { chapters: { include: { lessons: { select: { id: true } } } } } } },
});
const done = await db.lessonProgress.findMany({ where: { userId, completed: true }, select: { lessonId: true } });
const doneIds = new Set(done.map((d) => d.lessonId));
return access.map((a) => {
const ids = a.product.chapters.flatMap((c) => c.lessons.map((l) => l.id));
return { access: a, product: a.product, lessons: ids.length, completed: ids.filter((id) => doneIds.has(id)).length };
});
}
/** Kapitel und Lektionen in Reihenfolge. */
export async function getCourseOutline(productId: string) {
return db.courseChapter.findMany({
where: { productId },
orderBy: { sort: "asc" },
include: { lessons: { orderBy: { sort: "asc" } } },
});
}
export const formatDuration = (s: number) => {
if (!s) return "";
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
const sec = s % 60;
return h ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
};
/**
* Nach Zahlungseingang: Zugang zu allen Kursen der Bestellung freischalten und Mail schicken.
* Mehrfach aufrufbar, schon vorhandene Zugänge bleiben unverändert.
* Besteht die Bestellung nur aus Kursen, ist sie damit erledigt.
*/
export async function grantCourseAccess(orderId: string) {
const order = await db.order.findUnique({ where: { id: orderId }, include: { items: { include: { product: true } }, user: true } });
if (!order || order.paymentStatus !== "PAID" || ["CANCELLED", "REFUNDED"].includes(order.status)) return [];
const courses = order.items.map((i) => i.product).filter((p): p is NonNullable<typeof p> => Boolean(p && isCourse(p)));
if (!courses.length) return [];
// Kurse gehören zu einem Konto; Gäste können sie gar nicht kaufen (Kasse verlangt Anmeldung)
const user = order.user ?? (await db.user.findUnique({ where: { email: order.email.toLowerCase() } }));
if (!user) {
await db.orderEvent.create({ data: { orderId, message: "Kurs nicht freigeschaltet: Zur Bestellung gehört kein Kundenkonto. Bitte im Produkt unter „Zugänge“ von Hand freischalten.", author: "System" } });
return [];
}
const granted: string[] = [];
for (const p of courses) {
const existing = await db.courseAccess.findUnique({ where: { userId_productId: { userId: user.id, productId: p.id } } });
if (existing && (!existing.expiresAt || existing.expiresAt > new Date())) continue;
await db.courseAccess.upsert({
where: { userId_productId: { userId: user.id, productId: p.id } },
create: { userId: user.id, productId: p.id, orderId, source: `Bestellung ${order.number}` },
update: { orderId, expiresAt: null, source: `Bestellung ${order.number}` },
});
granted.push(p.name);
}
if (granted.length) {
await db.orderEvent.create({ data: { orderId, message: `Kurszugang freigeschaltet: ${granted.join(", ")}`, author: "System" } });
const onlyCourses = order.items.every((i) => i.product && isCourse(i.product));
if (onlyCourses && (order.status === "PAID" || order.status === "PENDING")) {
await db.order.update({ where: { id: orderId }, data: { status: "COMPLETED", events: { create: { message: "Abgeschlossen: Nur digitale Inhalte, kein Versand nötig.", author: "System" } } } });
}
const vars = { vorname: user.firstName, kurse: granted.join(", "), kurs_link: `${appUrl()}/konto/kurse`, bestellnummer: order.number };
sendLater(() => sendTemplate({ key: "course_access", to: user.email, orderId, vars }));
}
return granted;
}
/** Besteht die Bestellung nur aus Kursen? Dann gibt es nichts zu verpacken oder zu versenden. */
export async function isDigitalOrder(orderId: string) {
const items = await db.orderItem.findMany({ where: { orderId }, include: { product: { select: { kind: true } } } });
return items.length > 0 && items.every((i) => i.product?.kind === COURSE);
}
/** Bei Storno oder Erstattung: Zugänge aus dieser Bestellung wieder entziehen. */
export async function revokeCourseAccess(orderId: string) {
const r = await db.courseAccess.deleteMany({ where: { orderId } });
if (r.count) await db.orderEvent.create({ data: { orderId, message: `Kurszugang entzogen (${r.count})`, author: "System" } });
return r.count;
}

View file

@ -20,7 +20,7 @@ export async function deleteCustomerAccount(id: string) {
await db.emailLog.deleteMany({ where: { to: user.email, orderId: null } }); await db.emailLog.deleteMany({ where: { to: user.email, orderId: null } });
await db.newsletterRecipient.deleteMany({ where: { email: user.email } }); await db.newsletterRecipient.deleteMany({ where: { email: user.email } });
await db.stockAlert.deleteMany({ where: { email: user.email } }); await db.stockAlert.deleteMany({ where: { email: user.email } });
// Sitzungen, Social-Logins, Reset-Links und Adressen hängen per Cascade am Konto // Sitzungen, Social-Logins, Reset-Links, Adressen, Kurszugänge und Lernfortschritt hängen per Cascade am Konto
await db.user.delete({ where: { id } }); await db.user.delete({ where: { id } });
return { email: user.email }; return { email: user.email };
} }

View file

@ -8,8 +8,9 @@ import { appleClientSecret } from "./social/oauth";
import type { Permission } from "./permissions"; import type { Permission } from "./permissions";
import { getMailConfig, type MailConfig } from "./mail/config"; import { getMailConfig, type MailConfig } from "./mail/config";
import { verifySmtp } from "./mail/smtp"; import { verifySmtp } from "./mail/smtp";
import { getBunnyConfig, isBunnyReady, testBunnyApi, type BunnyConfig } from "./bunny";
export type IntegrationKey = "stripe" | "paypal" | "dhl" | "google" | "apple" | "mail"; export type IntegrationKey = "stripe" | "paypal" | "dhl" | "google" | "apple" | "mail" | "bunny";
export type TestResult = { ok: boolean; message: string; at: string }; export type TestResult = { ok: boolean; message: string; at: string };
export type IntegrationStatus = { key: IntegrationKey; configured: boolean; mode: string; active: boolean; lastTest: TestResult | null }; export type IntegrationStatus = { key: IntegrationKey; configured: boolean; mode: string; active: boolean; lastTest: TestResult | null };
@ -20,6 +21,7 @@ export const INTEGRATIONS: { key: IntegrationKey; name: string; purpose: string;
{ key: "google", name: "Google", purpose: "„Mit Google anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 10 Minuten, zwei Werte" }, { key: "google", name: "Google", purpose: "„Mit Google anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 10 Minuten, zwei Werte" },
{ key: "mail", name: "E-Mail-Versand", purpose: "Bestellbestätigungen, Rechnungen, Passwort vergessen und alle anderen Mails über dein Postfach", permission: "emails.edit", effort: "ca. 5 Minuten, Zugangsdaten deines Postfachs" }, { key: "mail", name: "E-Mail-Versand", purpose: "Bestellbestätigungen, Rechnungen, Passwort vergessen und alle anderen Mails über dein Postfach", permission: "emails.edit", effort: "ca. 5 Minuten, Zugangsdaten deines Postfachs" },
{ key: "apple", name: "Apple", purpose: "„Mit Apple anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 15 Minuten, Apple-Developer-Konto nötig" }, { key: "apple", name: "Apple", purpose: "„Mit Apple anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 15 Minuten, Apple-Developer-Konto nötig" },
{ key: "bunny", name: "Bunny Stream", purpose: "Videos für die Kurse: hochladen, geschützt abspielen, optional mit DRM", permission: "settings.edit", effort: "ca. 10 Minuten, Bunny-Konto nötig" },
]; ];
const TESTS_KEY = "integration_tests"; const TESTS_KEY = "integration_tests";
@ -42,7 +44,7 @@ export async function forgetTest(key: IntegrationKey) {
} }
export async function getStatuses(): Promise<Record<IntegrationKey, IntegrationStatus>> { export async function getStatuses(): Promise<Record<IntegrationKey, IntegrationStatus>> {
const [creds, dhl, login, mail, tests] = await Promise.all([getCredentials(), getDhlConfig(), getLoginProviders(), getMailConfig(), getLastTests()]); const [creds, dhl, login, mail, bunny, tests] = await Promise.all([getCredentials(), getDhlConfig(), getLoginProviders(), getMailConfig(), getBunnyConfig(), getLastTests()]);
const s = (key: IntegrationKey, configured: boolean, mode: string, active: boolean): IntegrationStatus => ({ key, configured, mode, active, lastTest: configured ? (tests[key] ?? null) : null }); const s = (key: IntegrationKey, configured: boolean, mode: string, active: boolean): IntegrationStatus => ({ key, configured, mode, active, lastTest: configured ? (tests[key] ?? null) : null });
return { return {
stripe: s("stripe", Boolean(creds.stripe.secretKey), creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live", Boolean(creds.stripe.secretKey)), stripe: s("stripe", Boolean(creds.stripe.secretKey), creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live", Boolean(creds.stripe.secretKey)),
@ -51,6 +53,7 @@ export async function getStatuses(): Promise<Record<IntegrationKey, IntegrationS
google: s("google", isConfigured("google", login), "", login.google.enabled), google: s("google", isConfigured("google", login), "", login.google.enabled),
apple: s("apple", isConfigured("apple", login), "", login.apple.enabled), apple: s("apple", isConfigured("apple", login), "", login.apple.enabled),
mail: s("mail", Boolean(mail.host && mail.fromEmail), mail.host, mail.enabled), mail: s("mail", Boolean(mail.host && mail.fromEmail), mail.host, mail.enabled),
bunny: s("bunny", Boolean(bunny.libraryId && bunny.apiKey), bunny.drm ? "mit DRM" : "", isBunnyReady(bunny)),
}; };
} }
@ -198,3 +201,24 @@ export async function testMail(c?: MailConfig) {
await remember("mail", r); await remember("mail", r);
return r; return r;
} }
// ---------- Bunny Stream ----------
/** Prüft Bibliothek und API-Schlüssel direkt bei Bunny. */
export async function testBunny(c?: BunnyConfig) {
const config = c ?? (await getBunnyConfig());
let r: { ok: boolean; message: string };
if (!config.libraryId || !config.apiKey) r = { ok: false, message: "Es sind noch keine Zugangsdaten gespeichert." };
else {
try {
const count = await testBunnyApi(config);
r = config.tokenKey
? { ok: true, message: `Bunny Stream verbunden (Bibliothek ${config.libraryId}, ${count} ${count === 1 ? "Video" : "Videos"}).${config.drm ? " DRM ist eingeschaltet." : ""}` }
: { ok: false, message: "Bibliothek und API-Schlüssel passen, aber der Token-Schlüssel aus Schritt 4 fehlt noch. Ohne ihn lassen sich die Videos nicht geschützt abspielen." };
} catch (e) {
r = { ok: false, message: e instanceof Error ? e.message : String(e) };
}
}
await remember("bunny", r);
return r;
}

View file

@ -85,6 +85,26 @@ Wir packen dein Paket und melden uns, sobald es unterwegs ist.
[Bestellung ansehen]({{bestellung_link}}) [Bestellung ansehen]({{bestellung_link}})
Herzliche Grüße Herzliche Grüße
dein {{shop_name}}-Team`,
},
{
key: "course_access",
name: "Kurs freigeschaltet",
description: "Sobald die Zahlung für einen Video-Kurs eingegangen ist. Bestätigt dem Kunden auch, dass sein Widerrufsrecht für den digitalen Inhalt erloschen ist (Pflicht nach § 312f BGB).",
recipient: "customer",
group: "Bestellung",
required: true,
placeholders: [P.vorname, P.bestellnummer, { key: "kurse", label: "Name der Kurse", sample: "Pilates Basics" }, { key: "kurs_link", label: "Link zu „Meine Kurse“", sample: "https://sanamare.de/konto/kurse" }],
subject: "Dein Kurs ist freigeschaltet: {{kurse}}",
body: `Hallo {{vorname}},
deine Zahlung ist angekommen, dein Kurs **{{kurse}}** ist ab sofort freigeschaltet. Du findest ihn in deinem Kundenkonto unter „Meine Kurse“.
[Zum Kurs]({{kurs_link}})
Bitte beachte: Du hast bei der Bestellung {{bestellnummer}} ausdrücklich zugestimmt, dass wir vor Ablauf der Widerrufsfrist mit der Bereitstellung der digitalen Inhalte beginnen, und bestätigt, dass dein Widerrufsrecht damit erlischt. Mit der Freischaltung ist das Widerrufsrecht für diesen Kurs erloschen.
Viel Freude beim Üben!
dein {{shop_name}}-Team`, dein {{shop_name}}-Team`,
}, },
{ {

View file

@ -43,8 +43,10 @@ export async function computeTotals(opts: {
if (coupon) discount = coupon.type === "percent" ? Math.round((subtotal * coupon.value) / 100) : Math.min(coupon.value, subtotal); if (coupon) discount = coupon.type === "percent" ? Math.round((subtotal * coupon.value) / 100) : Math.min(coupon.value, subtotal);
const merchandise = subtotal - discount; const merchandise = subtotal - discount;
let shipping = opts.shipping ?? null; // Nur Video-Kurse: nichts zu versenden
if (shipping === undefined || shipping === null) { const digitalOnly = opts.lines.length > 0 && opts.lines.every((l) => l.digital);
let shipping = digitalOnly ? null : (opts.shipping ?? null);
if (!digitalOnly && (shipping === undefined || shipping === null)) {
shipping = await db.shippingMethod.findFirst({ where: { enabled: true }, orderBy: { sort: "asc" } }); shipping = await db.shippingMethod.findFirst({ where: { enabled: true }, orderBy: { sort: "asc" } });
} }
const shippingCost = opts.lines.length ? shippingPrice(shipping, merchandise) : 0; const shippingCost = opts.lines.length ? shippingPrice(shipping, merchandise) : 0;

View file

@ -306,3 +306,26 @@ a.ad-kpi:hover { border-color: var(--line-strong); }
/* Unterkategorien eingerückt unter ihrer Oberkategorie */ /* Unterkategorien eingerückt unter ihrer Oberkategorie */
.ad-cat--sub { margin-left: var(--space-6); } .ad-cat--sub { margin-left: var(--space-6); }
@media (max-width: 640px) { .ad-cat--sub { margin-left: var(--space-4); } } @media (max-width: 640px) { .ad-cat--sub { margin-left: var(--space-4); } }
/* Kursinhalt */
.ad-chapter { border: var(--hairline) solid var(--line); border-radius: var(--radius-sm); padding: var(--space-4); margin-bottom: var(--space-4); }
.ad-chapter__head { display: flex; flex-wrap: wrap; gap: var(--space-3); align-items: center; justify-content: space-between; margin-bottom: var(--space-3); }
.ad-chapter__head h3 { margin: 0; font-size: 17px; font-weight: 500; }
.ad-chapter__title { display: flex; gap: var(--space-2); align-items: center; flex: 1 1 260px; }
.ad-chapter__title .sm-input { font-weight: 500; }
.ad-chapter__tools { display: inline-flex; gap: var(--space-1); align-items: center; }
.ad-move { display: inline-flex; }
.ad-lesson { border-top: var(--hairline) solid var(--line); padding: var(--space-3) 0; }
.ad-lesson__head { display: flex; flex-wrap: wrap; gap: var(--space-3); align-items: center; }
.ad-lesson__head strong { font-weight: 500; flex: 1 1 200px; }
.ad-lesson__meta { display: inline-flex; gap: var(--space-2); align-items: center; }
.ad-lesson__edit summary { cursor: pointer; font-size: 14px; color: var(--ink-muted); margin-top: var(--space-2); }
.ad-lesson__edit[open] { padding-bottom: var(--space-2); }
.ad-lesson__form { display: grid; gap: var(--space-3); margin: var(--space-3) 0; }
.ad-lesson__actions { display: flex; flex-wrap: wrap; gap: var(--space-3); align-items: center; }
.ad-inline-add { display: flex; gap: var(--space-2); align-items: center; margin-top: var(--space-3); }
.ad-inline-add .sm-input { flex: 1 1 auto; min-height: var(--control-height-sm); }
.ad-video-upload { display: inline-flex; flex-direction: column; gap: var(--space-2); }
.ad-video-upload__progress { display: grid; gap: 4px; min-width: 260px; }
.ad-video-upload__track { display: block; height: 6px; border-radius: 3px; background: var(--line); overflow: hidden; }
.ad-video-upload__track > span { display: block; height: 100%; background: var(--gold); transition: width 0.3s; }

View file

@ -273,3 +273,40 @@ button.sm-pdp__main { display: block; width: 100%; padding: 0; border: 0; cursor
@media (min-width: 1024px) { .sm-rubric-hero { padding: var(--space-7) 0; } } @media (min-width: 1024px) { .sm-rubric-hero { padding: var(--space-7) 0; } }
.sm-rubric-hero .sm-hero__media img { width: 100%; aspect-ratio: 16 / 10; max-height: 380px; object-fit: cover; display: block; } .sm-rubric-hero .sm-hero__media img { width: 100%; aspect-ratio: 16 / 10; max-height: 380px; object-fit: cover; display: block; }
.sm-rubric-hero .sm-crumbs a { color: inherit; } .sm-rubric-hero .sm-crumbs a { color: inherit; }
/* ---------- Video-Kurse ---------- */
.sm-player { position: relative; aspect-ratio: 16 / 9; background: #000; border-radius: var(--radius-md); overflow: hidden; user-select: none; -webkit-user-select: none; }
.sm-player iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
.sm-player.is-full { border-radius: 0; aspect-ratio: auto; }
.sm-player__mark { position: absolute; z-index: 2; pointer-events: none; font-size: 13px; line-height: 18px; color: rgb(255 255 255 / 0.42); text-shadow: 0 0 2px rgb(0 0 0 / 0.5); white-space: nowrap; transition: left 1.6s ease, top 1.6s ease; }
.sm-player.is-full .sm-player__mark { font-size: 18px; }
.sm-player__full { position: absolute; z-index: 3; top: 10px; right: 10px; display: grid; place-items: center; width: 36px; height: 36px; border: 0; border-radius: 50%; background: rgb(0 0 0 / 0.45); color: #fff; cursor: pointer; opacity: 0.75; }
.sm-player__full:hover, .sm-player__full:focus-visible { opacity: 1; }
@media (prefers-reduced-motion: reduce) { .sm-player__mark { transition: none; } }
.sm-course { display: grid; gap: var(--space-4); }
.sm-course__chapter h3 { margin: 0 0 var(--space-2); font-size: 13px; letter-spacing: 0.12em; text-transform: uppercase; font-weight: 500; color: var(--ink-muted); }
.sm-course ol { list-style: none; margin: 0; padding: 0; border-top: var(--hairline) solid var(--line); }
.sm-course li > a, .sm-course__locked { display: grid; grid-template-columns: 28px 1fr auto; gap: var(--space-3); align-items: center; padding: var(--space-3) var(--space-2); border-bottom: var(--hairline) solid var(--line); color: var(--ink); text-decoration: none; font-size: 15px; line-height: 22px; }
.sm-course li > a:hover { background: var(--surface-sunken); }
.sm-course__locked { color: var(--ink-muted); }
.sm-course li.is-current > a { background: var(--gold-soft); }
.sm-course__num { display: grid; place-items: center; width: 24px; height: 24px; border-radius: 50%; border: var(--hairline) solid var(--line-strong); font-size: 12px; color: var(--ink-muted); }
.sm-course li.is-done .sm-course__num { background: var(--success); border-color: var(--success); color: var(--surface-raised); }
.sm-course__title em { margin-left: var(--space-2); font-style: normal; font-size: 12px; color: var(--gold-deep); letter-spacing: 0.06em; text-transform: uppercase; }
.sm-course__time { font-size: 13px; color: var(--ink-muted); font-variant-numeric: tabular-nums; }
.sm-mycourses { display: grid; gap: var(--space-3); }
.sm-mycourse { display: grid; grid-template-columns: 96px 1fr auto; gap: var(--space-4); align-items: center; color: var(--ink); text-decoration: none; }
.sm-mycourse:hover { border-color: var(--line-strong); }
.sm-mycourse img, .sm-mycourse__ph { width: 96px; aspect-ratio: 4 / 3; object-fit: cover; border-radius: var(--radius-sm); background: var(--surface-sunken); }
.sm-mycourse__ph { display: grid; place-items: center; color: var(--gold-deep); }
.sm-mycourse > div { display: grid; gap: 4px; min-width: 0; }
.sm-mycourse__bar { display: block; height: 4px; border-radius: 2px; background: var(--line); overflow: hidden; margin-top: var(--space-1); }
.sm-mycourse__bar > span { display: block; height: 100%; background: var(--gold); }
@media (max-width: 560px) { .sm-mycourse { grid-template-columns: 72px 1fr; } .sm-mycourse img, .sm-mycourse__ph { width: 72px; } .sm-mycourse > .sm-btn { grid-column: 1 / -1; justify-self: start; } }
.sm-lesson__grid { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: var(--space-7); margin-top: var(--space-5); align-items: start; }
.sm-lesson__side { position: sticky; top: var(--space-5); }
.sm-lesson__bar { display: flex; gap: var(--space-3); justify-content: space-between; flex-wrap: wrap; margin-top: var(--space-3); }
@media (max-width: 900px) { .sm-lesson__grid { grid-template-columns: 1fr; gap: var(--space-5); } .sm-lesson__side { position: static; } }