diff --git a/prisma/migrations/20261020210000_courses/migration.sql b/prisma/migrations/20261020210000_courses/migration.sql new file mode 100644 index 0000000..9c3c084 --- /dev/null +++ b/prisma/migrations/20261020210000_courses/migration.sql @@ -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; + diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 221af4c..46814d7 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -23,25 +23,27 @@ model Role { } model User { - id String @id @default(cuid()) - email String @unique + id String @id @default(cuid()) + email String @unique passwordHash String - firstName String @default("") - lastName String @default("") - phone String @default("") + firstName String @default("") + lastName String @default("") + phone String @default("") // Ohne Rolle ist ein Benutzer ein Kunde ohne Admin-Zugang roleId String? - role Role? @relation(fields: [roleId], references: [id], onDelete: SetNull) - active Boolean @default(true) - newsletter Boolean @default(false) + role Role? @relation(fields: [roleId], references: [id], onDelete: SetNull) + active Boolean @default(true) + newsletter Boolean @default(false) lastLoginAt DateTime? sessions Session[] identities UserIdentity[] resets PasswordReset[] orders Order[] addresses Address[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + courseAccess CourseAccess[] + progress LessonProgress[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } // Verknüpfte Anmeldungen über Google oder Apple. Konten nur mit dieser Anmeldung haben passwordHash "". @@ -123,6 +125,8 @@ model Product { active Boolean @default(true) featured Boolean @default(false) badge String @default("") // "", "new", "best" + // "physical" = Ware mit Versand, "course" = Video-Kurs (digital, ohne Versand und Bestand) + kind String @default("physical") images String[] sort Int @default(0) categoryId String? @@ -130,10 +134,74 @@ model Product { variants ProductVariant[] orderItems OrderItem[] stockAlerts StockAlert[] + chapters CourseChapter[] + courseAccess CourseAccess[] createdAt DateTime @default(now()) 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 { id String @id @default(cuid()) productId String @@ -184,36 +252,37 @@ enum PaymentStatus { } model Order { - id String @id @default(cuid()) - number String @unique + id String @id @default(cuid()) + number String @unique userId String? - user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + user User? @relation(fields: [userId], references: [id], onDelete: SetNull) email String - phone String @default("") - status OrderStatus @default(PENDING) - paymentStatus PaymentStatus @default(OPEN) + phone String @default("") + status OrderStatus @default(PENDING) + paymentStatus PaymentStatus @default(OPEN) paymentMethod String - paymentRef String @default("") + paymentRef String @default("") shippingMethod String shippingAddress Json billingAddress Json? subtotal Int shippingCost Int - paymentFee Int @default(0) - discount Int @default(0) - couponCode String @default("") + paymentFee Int @default(0) + discount Int @default(0) + couponCode String @default("") taxAmount Int total Int - note String @default("") - internalNote String @default("") - trackingNumber String @default("") + note String @default("") + internalNote String @default("") + trackingNumber String @default("") // Über die DHL-Schnittstelle erzeugtes Versandlabel (Dateiname im Label-Ordner) - labelFile String @default("") + labelFile String @default("") items OrderItem[] events OrderEvent[] invoices Invoice[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + courseAccess CourseAccess[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } model OrderItem { diff --git a/src/app/(shop)/actions.ts b/src/app/(shop)/actions.ts index 96605b8..62ba64b 100644 --- a/src/app/(shop)/actions.ts +++ b/src/app/(shop)/actions.ts @@ -8,6 +8,8 @@ import { readCartCookie, writeCartCookie } from "@/lib/cart"; import { findCoupon } from "@/lib/pricing"; import { subscribe } from "@/lib/newsletter"; 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) { 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 product = await db.product.findFirst({ where: { id: productId, active: true }, include: { variants: true } }); 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`); } const entries = await readCartCookie(); diff --git a/src/app/(shop)/kasse/actions.ts b/src/app/(shop)/kasse/actions.ts index 0d7b151..81d9c36 100644 --- a/src/app/(shop)/kasse/actions.ts +++ b/src/app/(shop)/kasse/actions.ts @@ -5,7 +5,7 @@ import { redirect } from "next/navigation"; import { z } from "zod"; import { db } from "@/lib/db"; import { getCurrentUser } from "@/lib/auth"; -import { getCart } from "@/lib/cart"; +import { getCart, hasDigital, isDigitalOnly } from "@/lib/cart"; import { finishCheckoutSession } from "@/lib/checkout-finish"; import { availablePayments, availableShipping, createOrder, readCheckout, writeCheckout } from "@/lib/checkout"; import { computeTotals } from "@/lib/pricing"; @@ -62,7 +62,7 @@ export async function saveAddress(_prev: FormState, formData: FormData): Promise billing, 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 { @@ -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()]); if (!lines.length) redirect("/warenkorb"); if (!state.email || !state.address) redirect("/kasse/adresse"); - const shipping = state.shippingMethodId ? await db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : null; - if (!shipping?.enabled) redirect("/kasse/versand"); + const digitalOnly = isDigitalOnly(lines); + 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; if (!payment?.enabled) redirect("/kasse/zahlung"); 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; 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) { 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"); const placedId = order.id; sendLater(() => mailOrderPlaced(placedId, "placed")); diff --git a/src/app/(shop)/kasse/adresse/page.tsx b/src/app/(shop)/kasse/adresse/page.tsx index 72db436..8558ee2 100644 --- a/src/app/(shop)/kasse/adresse/page.tsx +++ b/src/app/(shop)/kasse/adresse/page.tsx @@ -9,11 +9,12 @@ export const metadata = { title: "Kasse – Adresse" }; export default async function AddressStep() { 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 (

Bitte melde dich an

-

Für eine Bestellung brauchst du ein Kundenkonto.

+

{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."}

Anmelden Konto erstellen @@ -42,6 +43,7 @@ export default async function AddressStep() { newsletter={s.newsletter ?? false} requirePhone={settings.checkout.requirePhone} countries={settings.checkout.countries.map((c) => [c, COUNTRIES[c] ?? c])} + digital={data.digitalOnly} />
diff --git a/src/app/(shop)/kasse/layout.tsx b/src/app/(shop)/kasse/layout.tsx index 271484e..128f4f5 100644 --- a/src/app/(shop)/kasse/layout.tsx +++ b/src/app/(shop)/kasse/layout.tsx @@ -1,9 +1,11 @@ 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 (
- + {children}
); diff --git a/src/app/(shop)/kasse/pruefen/page.tsx b/src/app/(shop)/kasse/pruefen/page.tsx index 50c46be..4d4d465 100644 --- a/src/app/(shop)/kasse/pruefen/page.tsx +++ b/src/app/(shop)/kasse/pruefen/page.tsx @@ -13,7 +13,7 @@ export default async function ReviewStep() { const [data, settings] = await Promise.all([loadCheckout(), getSettings()]); const { state, shipping, payment } = data; 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"); const provider = getDefinition(payment.code)?.provider; return ( @@ -22,17 +22,28 @@ export default async function ReviewStep() {

Alles richtig?

-

Lieferadresse Ändern

+

{data.digitalOnly ? "Rechnungsadresse" : "Lieferadresse"} Ändern

{state.email}

+ {!data.digitalOnly && ( +
+

Rechnungsadresse Ändern

+ {state.billingSame === false && state.billing ? :

Wie Lieferadresse

} +
+ )}
-

Rechnungsadresse Ändern

- {state.billingSame === false && state.billing ? :

Wie Lieferadresse

} -
-
-

Versand Ändern

-

{shipping.name}

+ {data.digitalOnly ? ( + <> +

Lieferung

+

Digital: Der Kurs erscheint nach dem Zahlungseingang unter „Meine Kurse“ in deinem Konto.

+ + ) : ( + <> +

Versand Ändern

+

{shipping!.name}

+ + )}

Zahlung Ändern

@@ -40,7 +51,7 @@ export default async function ReviewStep() {
- +
diff --git a/src/app/(shop)/kasse/shared.tsx b/src/app/(shop)/kasse/shared.tsx index fe72a7b..65f7639 100644 --- a/src/app/(shop)/kasse/shared.tsx +++ b/src/app/(shop)/kasse/shared.tsx @@ -1,7 +1,7 @@ import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { db } from "@/lib/db"; -import { getCart } from "@/lib/cart"; +import { getCart, hasDigital, isDigitalOnly } from "@/lib/cart"; import { readCheckout } from "@/lib/checkout"; import { computeTotals } from "@/lib/pricing"; import { OrderSummary } from "@/components/shop/OrderSummary"; @@ -15,7 +15,8 @@ export async function loadCheckout() { state.paymentMethodId ? db.paymentMethod.findUnique({ where: { id: state.paymentMethodId } }) : null, ]); 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> }) { @@ -23,7 +24,7 @@ export function CheckoutSummary({ data }: { data: Awaited ); diff --git a/src/app/(shop)/kasse/versand/page.tsx b/src/app/(shop)/kasse/versand/page.tsx index 12e5737..4206351 100644 --- a/src/app/(shop)/kasse/versand/page.tsx +++ b/src/app/(shop)/kasse/versand/page.tsx @@ -11,6 +11,7 @@ export const metadata = { title: "Kasse – Versand" }; export default async function ShippingStep() { const data = await loadCheckout(); if (!data.state.address) redirect("/kasse/adresse"); + if (data.digitalOnly) redirect("/kasse/zahlung"); const methods = await availableShipping(data.state.address.country); const merchandise = data.totals.subtotal - data.totals.discount; return ( diff --git a/src/app/(shop)/kasse/zahlung/page.tsx b/src/app/(shop)/kasse/zahlung/page.tsx index 67b38ad..c11461d 100644 --- a/src/app/(shop)/kasse/zahlung/page.tsx +++ b/src/app/(shop)/kasse/zahlung/page.tsx @@ -12,7 +12,7 @@ export const metadata = { title: "Kasse – Zahlung" }; export default async function PaymentStep({ searchParams }: { searchParams: Promise<{ abgebrochen?: string }> }) { const [{ abgebrochen }, data, user] = await Promise.all([searchParams, loadCheckout(), getCurrentUser()]); 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)); return (
diff --git a/src/app/(shop)/konto/kurse/[slug]/page.tsx b/src/app/(shop)/konto/kurse/[slug]/page.tsx new file mode 100644 index 0000000..51532b2 --- /dev/null +++ b/src/app/(shop)/konto/kurse/[slug]/page.tsx @@ -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 ( +
+ +
+
+ {!lesson ? ( + Dieser Kurs hat noch keine fertigen Einheiten. Schau bald wieder vorbei. + ) : !ready ? ( + Bitte versuche es später noch einmal oder melde dich bei uns. + ) : ( + <> + +

{lesson.title}

+ {lesson.description &&

{lesson.description}

} + + )} +
+ +
+
+ ); +} diff --git a/src/app/(shop)/konto/kurse/actions.ts b/src/app/(shop)/konto/kurse/actions.ts new file mode 100644 index 0000000..5eeeb37 --- /dev/null +++ b/src/app/(shop)/konto/kurse/actions.ts @@ -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 }, + }); +} diff --git a/src/app/(shop)/konto/kurse/page.tsx b/src/app/(shop)/konto/kurse/page.tsx new file mode 100644 index 0000000..cf6e197 --- /dev/null +++ b/src/app/(shop)/konto/kurse/page.tsx @@ -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 ( + + {courses.length === 0 ? ( +
+ +

Du hast noch keinen Kurs. Gekaufte Kurse erscheinen hier, sobald die Zahlung angekommen ist.

+ Zum Shop +
+ ) : ( +
+ {courses.map(({ product, lessons, completed }) => { + const pct = lessons ? Math.round((completed / lessons) * 100) : 0; + return ( + + {product.images[0] ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( + + )} +
+ {product.name} + {product.subtitle && {product.subtitle}} +
+ {completed === 0 ? "Starten" : completed === lessons ? "Ansehen" : "Weiter"} + + ); + })} +
+ )} +
+ ); +} diff --git a/src/app/(shop)/konto/profil/page.tsx b/src/app/(shop)/konto/profil/page.tsx index 78476d3..7cb9f48 100644 --- a/src/app/(shop)/konto/profil/page.tsx +++ b/src/app/(shop)/konto/profil/page.tsx @@ -31,7 +31,7 @@ export default async function ProfilePage() { {!user.role && (

Konto löschen

-

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.

+

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.

)} diff --git a/src/app/(shop)/produkt/[slug]/page.tsx b/src/app/(shop)/produkt/[slug]/page.tsx index 8188738..ba90c3b 100644 --- a/src/app/(shop)/produkt/[slug]/page.tsx +++ b/src/app/(shop)/produkt/[slug]/page.tsx @@ -9,6 +9,11 @@ import { SectionHeading, TrustBar } from "@/components/shop/Blocks"; import { BuyBox } from "@/components/shop/BuyBox"; import { Gallery } from "@/components/shop/Gallery"; 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 }> }) { const { slug } = await params; @@ -21,9 +26,9 @@ export default async function ProductPage({ searchParams, }: { 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({ where: { slug }, include: { category: true, variants: { orderBy: { sort: "asc" } } }, @@ -41,6 +46,12 @@ export default async function ProductPage({ }).then(withSales), ]); 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 (
@@ -58,6 +69,18 @@ export default async function ProductPage({ {product.category && {product.category.name}}

{product.name}

{product.subtitle &&

{product.subtitle}

} + {course ? ( + s + l.duration, 0) / 60)} + /> + ) : ( + )}
    - {shippingNote &&
  • {shippingNote.title}
  • } + {shippingNote && !course &&
  • {shippingNote.title}
  • } {product.sku &&
  • Art.-Nr. {product.sku}
  • }
@@ -81,18 +105,41 @@ export default async function ProductPage({
{product.description}
)} + {course && outline.length > 0 && ( +
+ Inhalt des Kurses +
+ {previewSrc && previewLesson && ( +
+ +

Vorschau: {previewLesson.title}

+
+ )} + (owned ? `/konto/kurse/${product.slug}?einheit=${l.id}` : l.preview ? `/produkt/${product.slug}?vorschau=${l.id}#inhalt` : null)} /> +
+
+ )} {product.details && (
- Material & Pflege + {course ? "Gut zu wissen" : <>Material & Pflege}
{product.details}
)} + {course ? ( +
+ Zugang & Widerruf +
+ 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. +
+
+ ) : (
Versand & Rückgabe
{settings.appearance.trustItems.slice(0, 2).map((t) => `${t.title}. ${t.text}`).join(" ")}
+ )}
diff --git a/src/app/admin/(panel)/bestellungen/actions.ts b/src/app/admin/(panel)/bestellungen/actions.ts index 2f2b584..cac2782 100644 --- a/src/app/admin/(panel)/bestellungen/actions.ts +++ b/src/app/admin/(panel)/bestellungen/actions.ts @@ -13,6 +13,7 @@ import type { AddressData } from "@/lib/checkout"; import { cancelLabel, canCreateLabels, createLabel, getDhlConfig } from "@/lib/dhl"; import { autoInvoice, cancelInvoice, createInvoice } from "@/lib/invoices"; 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; @@ -48,7 +49,9 @@ export async function updateOrder(_prev: ActionResult, fd: FormData): Promise 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") { await autoInvoice(id, "shipped"); @@ -97,6 +100,7 @@ export async function cancelOrder(fd: FormData) { }); }); await cancelInvoice(id, authorName(user)); + await revokeCourseAccess(id); sendLater(() => mailCancelled(id, wasPaid)); await audit(user, wasPaid ? "Bestellung erstattet" : "Bestellung storniert", order.number); revalidatePath(`/admin/bestellungen/${id}`); diff --git a/src/app/admin/(panel)/kunden/[id]/page.tsx b/src/app/admin/(panel)/kunden/[id]/page.tsx index 7206837..c4c0113 100644 --- a/src/app/admin/(panel)/kunden/[id]/page.tsx +++ b/src/app/admin/(panel)/kunden/[id]/page.tsx @@ -12,7 +12,7 @@ import { deleteCustomer, saveCustomer } from "../actions"; export default async function CustomerDetail({ params }: { params: Promise<{ id: string }> }) { const user = await requireAdmin("customers.view"); 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(); return (
@@ -56,6 +56,7 @@ export default async function CustomerDetail({ params }: { params: Promise<{ id:

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 && Achtung: {open === 1 ? "1 Bestellung ist" : `${open} Bestellungen sind`} noch offen.} + {c.courseAccess.length > 0 && Die Person verliert den Zugang zu {c.courseAccess.length === 1 ? "einem Kurs" : `${c.courseAccess.length} Kursen`} ({c.courseAccess.map((a) => a.product.name).join(", ")}).}

diff --git a/src/app/admin/(panel)/produkte/[id]/page.tsx b/src/app/admin/(panel)/produkte/[id]/page.tsx index b34e342..3b1f297 100644 --- a/src/app/admin/(panel)/produkte/[id]/page.tsx +++ b/src/app/admin/(panel)/produkte/[id]/page.tsx @@ -8,11 +8,12 @@ import { Alert } from "@/components/shop/Blocks"; import { ConfirmButton } from "@/components/admin/AdminForm"; import { PageHead } from "@/components/admin/ui"; import { ProductForm } from "@/components/admin/ProductForm"; +import { CourseEditor } from "@/components/admin/CourseEditor"; 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 [{ id }, { neu }] = await Promise.all([params, searchParams]); + const [{ id }, { neu, ausgeblendet }] = await Promise.all([params, searchParams]); const [p, categories] = await Promise.all([ db.product.findUnique({ where: { id }, include: { variants: { orderBy: { sort: "asc" } } } }), db.category.findMany({ orderBy: { sort: "asc" } }), @@ -30,7 +31,8 @@ export default async function EditProduct({ params, searchParams }: { params: Pr )} - {neu &&
} + {neu &&
} + {ausgeblendet &&
Diesen Kurs haben schon Kunden gekauft. Damit sie ihn weiter ansehen können, ist er nur aus dem Shop genommen.
} {sale && (
@@ -65,11 +67,13 @@ export default async function EditProduct({ params, searchParams }: { params: Pr active: p.active, featured: p.featured, badge: p.badge, + kind: p.kind, categoryId: p.categoryId ?? "", 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) })), }} /> + {p.kind === "course" && }
); } diff --git a/src/app/admin/(panel)/produkte/actions.ts b/src/app/admin/(panel)/produkte/actions.ts index 69d8252..c3fe201 100644 --- a/src/app/admin/(panel)/produkte/actions.ts +++ b/src/app/admin/(panel)/produkte/actions.ts @@ -8,6 +8,13 @@ import { assertPermission, audit, can } from "@/lib/auth"; import { fail, ok, type ActionResult } from "@/lib/action-result"; import { parsePrice } from "@/lib/money"; 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 }; @@ -30,7 +37,9 @@ export async function saveProduct(_prev: ActionResult, fd: FormData): Promise 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) { 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 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 } }); + // 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); revalidatePath("/", "layout"); redirect("/admin/produkte"); @@ -102,6 +123,7 @@ export async function duplicateProduct(fd: FormData) { if (!p) return; let slug = `${p.slug}-kopie`; 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 copy = await db.product.create({ data: { ...rest, name: `${p.name} (Kopie)`, slug, active: false, variants: { create: variants.map(({ id: _v, productId: _p, ...v }) => v) } }, diff --git a/src/app/admin/(panel)/produkte/kurs-actions.ts b/src/app/admin/(panel)/produkte/kurs-actions.ts new file mode 100644 index 0000000..e80adfe --- /dev/null +++ b/src/app/admin/(panel)/produkte/kurs-actions.ts @@ -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 { + 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 { + 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); +} diff --git a/src/app/admin/(panel)/produkte/neu/page.tsx b/src/app/admin/(panel)/produkte/neu/page.tsx index 906a2c9..6ee4978 100644 --- a/src/app/admin/(panel)/produkte/neu/page.tsx +++ b/src/app/admin/(panel)/produkte/neu/page.tsx @@ -4,7 +4,8 @@ import { can, requireAdmin } from "@/lib/auth"; import { PageHead } from "@/components/admin/ui"; 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 categories = await db.category.findMany({ orderBy: { sort: "asc" } }); return ( @@ -13,7 +14,7 @@ export default async function NewProduct() {
); diff --git a/src/app/admin/(panel)/produkte/page.tsx b/src/app/admin/(panel)/produkte/page.tsx index f10f2ca..5b3c5dc 100644 --- a/src/app/admin/(panel)/produkte/page.tsx +++ b/src/app/admin/(panel)/produkte/page.tsx @@ -28,6 +28,7 @@ export default async function ProductsPage({ searchParams }: { searchParams: Pro return (
+ {editable && Kurs anlegen} {editable && Produkt anlegen} diff --git a/src/app/admin/(panel)/verbindungen/[provider]/page.tsx b/src/app/admin/(panel)/verbindungen/[provider]/page.tsx index d5b191f..d723804 100644 --- a/src/app/admin/(panel)/verbindungen/[provider]/page.tsx +++ b/src/app/admin/(panel)/verbindungen/[provider]/page.tsx @@ -16,7 +16,8 @@ import { StatusPill } from "@/components/admin/IntegrationStatus"; import { MailServerFields } from "@/components/admin/MailServerFields"; import { MAIL_PRESETS, getMailConfig } from "@/lib/mail/config"; 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 }) { 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 ( + + + + +

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.

+ Bei Bunny registrieren +
+ +

Links auf „Stream“ und dann „Add Video Library“ klicken. Name z. B. „Sanamare Kurse“, bei den Regionen nur Europa wählen (Datenschutz). In der neuen Bibliothek unter „API“ steht die Video Library ID, eine Zahl.

+ Stream öffnen + +
+ +

Auf derselben Seite („API“) steht der API Key der Bibliothek. Damit lädt der Shop die Videos direkt aus dem Admin zu Bunny hoch.

+ +
+ +

In der Bibliothek unter „Security“:

+
    +
  1. Embed view token authentication einschalten. Dann spielen die Videos nur über den Shop, mit einem Link, der nach wenigen Stunden abläuft.
  2. +
  3. Den Token authentication key kopieren und unten einfügen.
  4. +
  5. Unter „Allowed referrers“ deine Shop-Adressen eintragen:
  6. +
+ {siteOrigins().map((o) => )} +

Außerdem „Block direct url file access“ einschalten und unter „Player“ das Herunterladen ausschalten.

+ +
+ +

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.

+ +
+ +

Ich prüfe Bibliothek und Schlüssel direkt bei Bunny. Danach legst du unter Produkte einen Kurs an (Art „Video-Kurs“) und lädst dort die Videos hoch.

+
+
+
+
+ ); +} + const WIZARDS: Record Promise> = { stripe: StripeWizard, paypal: PaypalWizard, @@ -306,4 +353,5 @@ const WIZARDS: Record Promise String(fd.get(k) ?? "").trim(); // Leere Geheimfelder behalten den gespeicherten Wert @@ -195,7 +196,28 @@ export async function saveMail(_prev: ActionResult, fd: FormData): Promise = { 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 { + 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 = { 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) { const key = str(fd, "provider") as IntegrationKey; @@ -212,6 +234,8 @@ export async function disconnect(fd: FormData) { } else if (key === "mail") { const c = await getMailConfig(); await saveMailConfig({ ...c, host: "", user: "", password: "", enabled: false }); + } else if (key === "bunny") { + await saveBunnyConfig({ libraryId: "", apiKey: "", tokenKey: "", drm: false }); } else { const c = await getLoginProviders(); if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" }; @@ -227,6 +251,6 @@ export async function retest(_prev: ActionResult, fd: FormData): Promise), edit: (<>), eye: (<>), + play: (<>), image: (<>), grip: , }; diff --git a/src/components/admin/CourseEditor.tsx b/src/components/admin/CourseEditor.tsx new file mode 100644 index 0000000..c82abbc --- /dev/null +++ b/src/components/admin/CourseEditor.tsx @@ -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 = { + 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; id: string; first: boolean; last: boolean }) { + return ( + +
+
+
+ ); +} + +/** 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 ( +
+ + {!ready && ( +
+ + Richte zuerst unter Verbindungen → Bunny Stream die Video-Bibliothek ein. Kapitel und Einheiten kannst du schon anlegen. + +
+ )} + + {chapters.length === 0 && } + {chapters.map((c, ci) => ( +
+
+ {canEdit ? ( +
+ + + +
+ ) : ( +

{c.title}

+ )} + {canEdit && ( + + + + + )} +
+ {c.lessons.map((l, li) => { + const st = STATUS[l.videoStatus] ?? STATUS.none; + return ( +
+
+ {li + 1}. {l.title} + + {st.label} + {l.duration > 0 && {formatDuration(l.duration)}} + {l.preview && Vorschau} + + {canEdit && ( + + + + + )} +
+ {canEdit && ( +
+ Bearbeiten und Video + + {ready && } +
+ )} +
+ ); + })} + {canEdit && ( +
+ + + +
+ )} +
+ ))} + {canEdit && ( +
+ + + +
+ )} +
+ + + {access.length === 0 ? ( +

Noch niemand.

+ ) : ( +
+ + + + {access.map((a) => ( + + + + + + + ))} + +
KundeSeitÜber
{[a.user.firstName, a.user.lastName].filter(Boolean).join(" ") || a.user.email}
{a.user.email}
{dateFmt.format(a.createdAt)}{a.order ? Bestellung {a.order.number} : a.source || "–"}{canEdit && }
+
+ )} + {canEdit && ( +
+ + + + +
+ )} +
+
+ ); +} diff --git a/src/components/admin/LessonForm.tsx b/src/components/admin/LessonForm.tsx new file mode 100644 index 0000000..9635612 --- /dev/null +++ b/src/components/admin/LessonForm.tsx @@ -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 ; +} + +/** 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 ( +
+ + +