From d218ec5b8c3b50bede336ca8a1e4936d32247363 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 03:36:49 +0000 Subject: [PATCH] =?UTF-8?q?Creator-Programm=20Phase=201:=20pers=C3=B6nlich?= =?UTF-8?q?e=20Codes,=20Link=20/c/CODE,=20Provisionen,=20Admin=20und=20Cre?= =?UTF-8?q?ator-Bereich?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Creator-Code = Gutschein mit Creator; Stufen mit Rabatt (Prozent/Festbetrag, Deckel, Mindestwert) und Provision, Werte je Creator überschreibbar - Ausschlüsse: global je Kategorie, je Stufe (Produkte/Kategorien), Schalter am Produkt; Artikel im Sale ausgenommen - Link /c/CODE[/pfad] merkt den Code (Cookie, 30 Tage), zählt Klicks ohne IP, Hinweis oben im Shop - Bestellung friert Creator, Stufe, Satz und Netto-Basis ein; Rabattanteil je Position (auch für Rechnungs-Steuern) - Provision: vorgemerkt, Freigabe nach Haltefrist ab Versand (Kurse: ab Zahlung), Storno vor/nach Auszahlung, Auszahlung verbuchen - Admin /admin/creator (Liste, Detail, Stufen, Einstellungen), Rechte creators.*, Badge in Bestellungen - Kundenkonto /konto/creator: Bedingungen bestätigen, Code/Link, Zahlen je Monat, Provisionen, IBAN und Steuerstatus - Kein Rabatt auf eigene Bestellungen, Willkommens-Mail, Datenschutz-/AGB-Vorlagen ergänzt Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HsJ4RG9iGFNcNnG8YcScYE --- .../20261111040000_creators/migration.sql | 146 +++++++++++ prisma/schema.prisma | 183 +++++++++++--- src/app/(shop)/kasse/actions.ts | 2 +- src/app/(shop)/kasse/shared.tsx | 2 +- src/app/(shop)/konto/creator/actions.ts | 41 ++++ src/app/(shop)/konto/creator/page.tsx | 144 +++++++++++ src/app/(shop)/layout.tsx | 2 + src/app/(shop)/warenkorb/page.tsx | 12 +- .../admin/(panel)/bestellungen/[id]/page.tsx | 1 + src/app/admin/(panel)/bestellungen/actions.ts | 3 + src/app/admin/(panel)/bestellungen/page.tsx | 2 +- src/app/admin/(panel)/creator/[id]/page.tsx | 227 ++++++++++++++++++ src/app/admin/(panel)/creator/actions.ts | 209 ++++++++++++++++ .../(panel)/creator/einstellungen/page.tsx | 45 ++++ src/app/admin/(panel)/creator/page.tsx | 116 +++++++++ src/app/admin/(panel)/creator/stufen/page.tsx | 100 ++++++++ src/app/admin/(panel)/gutscheine/actions.ts | 7 +- src/app/admin/(panel)/gutscheine/page.tsx | 4 +- src/app/admin/(panel)/produkte/[id]/page.tsx | 1 + src/app/admin/(panel)/produkte/actions.ts | 1 + src/app/admin/(panel)/produkte/neu/page.tsx | 2 +- src/app/c/[code]/[[...path]]/route.ts | 29 +++ src/components/admin/CreatorForms.tsx | 11 + src/components/admin/CreatorTabs.tsx | 17 ++ src/components/admin/ProductForm.tsx | 2 + src/components/admin/SaleForm.tsx | 2 +- src/components/admin/nav.ts | 1 + src/components/shop/CreatorBar.tsx | 17 ++ src/components/shop/account/AccountNav.tsx | 4 +- src/components/shop/account/AccountShell.tsx | 6 +- src/components/shop/account/CreatorForms.tsx | 77 ++++++ src/lib/cart.ts | 5 + src/lib/checkout.ts | 12 +- src/lib/creators.ts | 226 +++++++++++++++++ src/lib/invoices.ts | 4 +- src/lib/legal-templates.ts | 7 +- src/lib/mail/templates.ts | 19 ++ src/lib/order-cancel.ts | 2 + src/lib/permissions.ts | 8 + src/lib/pricing.ts | 92 ++++++- src/lib/settings.ts | 27 +++ src/styles/admin.css | 1 + src/styles/shop.css | 18 ++ 43 files changed, 1778 insertions(+), 59 deletions(-) create mode 100644 prisma/migrations/20261111040000_creators/migration.sql create mode 100644 src/app/(shop)/konto/creator/actions.ts create mode 100644 src/app/(shop)/konto/creator/page.tsx create mode 100644 src/app/admin/(panel)/creator/[id]/page.tsx create mode 100644 src/app/admin/(panel)/creator/actions.ts create mode 100644 src/app/admin/(panel)/creator/einstellungen/page.tsx create mode 100644 src/app/admin/(panel)/creator/page.tsx create mode 100644 src/app/admin/(panel)/creator/stufen/page.tsx create mode 100644 src/app/c/[code]/[[...path]]/route.ts create mode 100644 src/components/admin/CreatorForms.tsx create mode 100644 src/components/admin/CreatorTabs.tsx create mode 100644 src/components/shop/CreatorBar.tsx create mode 100644 src/components/shop/account/CreatorForms.tsx create mode 100644 src/lib/creators.ts diff --git a/prisma/migrations/20261111040000_creators/migration.sql b/prisma/migrations/20261111040000_creators/migration.sql new file mode 100644 index 0000000..5d6025c --- /dev/null +++ b/prisma/migrations/20261111040000_creators/migration.sql @@ -0,0 +1,146 @@ +-- AlterTable +ALTER TABLE "Coupon" ADD COLUMN "creatorId" TEXT; + +-- AlterTable +ALTER TABLE "Order" ADD COLUMN "commissionBase" INTEGER NOT NULL DEFAULT 0, +ADD COLUMN "commissionRate" INTEGER NOT NULL DEFAULT 0, +ADD COLUMN "creatorId" TEXT, +ADD COLUMN "creatorTier" TEXT NOT NULL DEFAULT ''; + +-- AlterTable +ALTER TABLE "OrderItem" ADD COLUMN "discount" INTEGER NOT NULL DEFAULT 0; + +-- AlterTable +ALTER TABLE "Product" ADD COLUMN "noCreatorDiscount" BOOLEAN NOT NULL DEFAULT false; + +-- CreateTable +CREATE TABLE "CreatorTier" ( + "id" TEXT NOT NULL, + "name" TEXT NOT NULL, + "sort" INTEGER NOT NULL DEFAULT 0, + "discountType" TEXT NOT NULL DEFAULT 'percent', + "discountValue" INTEGER NOT NULL DEFAULT 5, + "discountCap" INTEGER NOT NULL DEFAULT 0, + "commissionRate" INTEGER NOT NULL DEFAULT 700, + "minOrder" INTEGER NOT NULL DEFAULT 0, + "upgradeFrom" INTEGER NOT NULL DEFAULT 0, + "extras" TEXT NOT NULL DEFAULT '', + "excludedProductIds" TEXT[], + "excludedCategoryIds" TEXT[], + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "CreatorTier_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Creator" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "status" TEXT NOT NULL DEFAULT 'active', + "tierId" TEXT NOT NULL, + "discountType" TEXT, + "discountValue" INTEGER, + "discountCap" INTEGER, + "commissionRate" INTEGER, + "channels" TEXT NOT NULL DEFAULT '', + "focus" TEXT NOT NULL DEFAULT '', + "taxStatus" TEXT NOT NULL DEFAULT '', + "vatId" TEXT NOT NULL DEFAULT '', + "accountHolder" TEXT NOT NULL DEFAULT '', + "iban" TEXT NOT NULL DEFAULT '', + "payoutMethod" TEXT NOT NULL DEFAULT 'transfer', + "termsAcceptedAt" TIMESTAMP(3), + "termsVersion" TEXT NOT NULL DEFAULT '', + "note" TEXT NOT NULL DEFAULT '', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Creator_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "CreatorClick" ( + "creatorId" TEXT NOT NULL, + "day" TEXT NOT NULL, + "count" INTEGER NOT NULL DEFAULT 0, + + CONSTRAINT "CreatorClick_pkey" PRIMARY KEY ("creatorId","day") +); + +-- CreateTable +CREATE TABLE "Commission" ( + "id" TEXT NOT NULL, + "creatorId" TEXT NOT NULL, + "orderId" TEXT NOT NULL, + "amount" INTEGER NOT NULL, + "base" INTEGER NOT NULL, + "rate" INTEGER NOT NULL, + "status" TEXT NOT NULL DEFAULT 'pending', + "releaseAt" TIMESTAMP(3), + "payoutId" TEXT, + "offsetPayoutId" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Commission_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "CreatorPayout" ( + "id" TEXT NOT NULL, + "creatorId" TEXT NOT NULL, + "amount" INTEGER NOT NULL, + "method" TEXT NOT NULL DEFAULT 'transfer', + "note" TEXT NOT NULL DEFAULT '', + "author" TEXT NOT NULL DEFAULT '', + "paidAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "CreatorPayout_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Creator_userId_key" ON "Creator"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "Commission_orderId_key" ON "Commission"("orderId"); + +-- CreateIndex +CREATE INDEX "Commission_creatorId_status_idx" ON "Commission"("creatorId", "status"); + +-- CreateIndex +CREATE INDEX "Coupon_creatorId_idx" ON "Coupon"("creatorId"); + +-- AddForeignKey +ALTER TABLE "Order" ADD CONSTRAINT "Order_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "Creator"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Coupon" ADD CONSTRAINT "Coupon_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "Creator"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Creator" ADD CONSTRAINT "Creator_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Creator" ADD CONSTRAINT "Creator_tierId_fkey" FOREIGN KEY ("tierId") REFERENCES "CreatorTier"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "CreatorClick" ADD CONSTRAINT "CreatorClick_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "Creator"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Commission" ADD CONSTRAINT "Commission_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "Creator"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Commission" ADD CONSTRAINT "Commission_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "Order"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Commission" ADD CONSTRAINT "Commission_payoutId_fkey" FOREIGN KEY ("payoutId") REFERENCES "CreatorPayout"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "CreatorPayout" ADD CONSTRAINT "CreatorPayout_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "Creator"("id") ON DELETE CASCADE ON UPDATE CASCADE; + + +-- Startvorlage der Stufen (frei änderbar unter Creator › Stufen) +INSERT INTO "CreatorTier" ("id", "name", "sort", "discountType", "discountValue", "discountCap", "commissionRate", "minOrder", "upgradeFrom", "extras", "excludedProductIds", "excludedCategoryIds", "updatedAt") VALUES + ('tier_starter', 'Starter', 0, 'percent', 5, 0, 700, 0, 0, 'Creator-Bereich mit Statistik', '{}', '{}', NOW()), + ('tier_partner', 'Partner', 1, 'percent', 5, 0, 1000, 0, 300000, 'Produkte zum Vorzugspreis, eigene Landingpage', '{}', '{}', NOW()), + ('tier_botschafter', 'Botschafterin', 2, 'percent', 5, 0, 1000, 0, 0, 'Wenige Ausgewählte per Vertrag: Werte je Creator individuell, Gratis-Produkte, Fixbetrag pro Video möglich', '{}', '{}', NOW()); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 8a0c5d4..7707b9f 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -44,6 +44,7 @@ model User { progress LessonProgress[] advisor Advisor? appointments Appointment[] @relation("CustomerAppointments") + creator Creator? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } @@ -109,37 +110,39 @@ model Category { } model Product { - id String @id @default(cuid()) - name String - slug String @unique - subtitle String @default("") // z. B. "Anthrazit · 8 mm" - description String @default("") - details String @default("") // Material & Pflege - sku String @default("") + id String @id @default(cuid()) + name String + slug String @unique + subtitle String @default("") // z. B. "Anthrazit · 8 mm" + description String @default("") + details String @default("") // Material & Pflege + sku String @default("") // Versandgewicht in Gramm, für DHL-Labels (0 = unbekannt) - weight Int @default(0) + weight Int @default(0) // Preise in Cent, brutto - price Int - compareAtPrice Int? - taxRate Int @default(19) - stock Int @default(0) - trackStock Boolean @default(true) - active Boolean @default(true) - featured Boolean @default(false) - badge String @default("") // "", "new", "best" + price Int + compareAtPrice Int? + taxRate Int @default(19) + stock Int @default(0) + trackStock Boolean @default(true) + 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? - category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull) - variants ProductVariant[] - orderItems OrderItem[] - stockAlerts StockAlert[] - chapters CourseChapter[] - courseAccess CourseAccess[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + kind String @default("physical") + // Creator-Codes geben auf dieses Produkt weder Rabatt noch Provision + noCreatorDiscount Boolean @default(false) + images String[] + sort Int @default(0) + categoryId String? + category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull) + variants ProductVariant[] + orderItems OrderItem[] + stockAlerts StockAlert[] + chapters CourseChapter[] + courseAccess CourseAccess[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } // ---------- Video-Kurse ---------- @@ -273,6 +276,14 @@ model Order { paymentFee Int @default(0) discount Int @default(0) couponCode String @default("") + // Creator-Code: zum Bestellzeitpunkt eingefroren + creatorId String? + creator Creator? @relation(fields: [creatorId], references: [id], onDelete: SetNull) + creatorTier String @default("") + // Provisionssatz in Hundertstel-Prozent (700 = 7 %), Basis = Nettowarenwert der Artikel, auf die der Code wirkt + commissionRate Int @default(0) + commissionBase Int @default(0) + commission Commission? taxAmount Int total Int note String @default("") @@ -303,6 +314,8 @@ model OrderItem { quantity Int taxRate Int total Int + // Anteil des Gutscheinrabatts an dieser Position (Cent, brutto) + discount Int @default(0) } // Rechnungen und Stornorechnungen. `data` ist eine unveränderliche Momentaufnahme @@ -385,7 +398,12 @@ model Coupon { usedCount Int @default(0) active Boolean @default(true) validUntil DateTime? + // Gesetzt = Creator-Code dieses Creators + creatorId String? + creator Creator? @relation(fields: [creatorId], references: [id], onDelete: SetNull) createdAt DateTime @default(now()) + + @@index([creatorId]) } model Page { @@ -646,3 +664,112 @@ model AppointmentProposal { startsAt DateTime endsAt DateTime } + +// ---------- Creator-Programm ---------- + +// Stufe mit Kundenvorteil und Provision. Änderungen gelten nur für neue Bestellungen. +model CreatorTier { + id String @id @default(cuid()) + name String + sort Int @default(0) + // Kundenrabatt: "percent" (Wert in Prozent) oder "fixed" (Wert in Cent) + discountType String @default("percent") + discountValue Int @default(5) + // Höchstrabatt je Bestellung in Cent (0 = ohne Deckel) + discountCap Int @default(0) + // Provision in Hundertstel-Prozent (700 = 7 %) + commissionRate Int @default(700) + // Mindestbestellwert für den Code in Cent + minOrder Int @default(0) + // Umsatz im Quartal für den Aufstieg in Cent (0 = nur von Hand) + upgradeFrom Int @default(0) + extras String @default("") + // Für diese Produkte und Kategorien gibt es mit Codes dieser Stufe weder Rabatt noch Provision + excludedProductIds String[] + excludedCategoryIds String[] + creators Creator[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + +model Creator { + id String @id @default(cuid()) + userId String @unique + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + // "applied" (beworben), "active", "paused", "ended" + status String @default("active") + tierId String + tier CreatorTier @relation(fields: [tierId], references: [id], onDelete: Restrict) + // Abweichende Werte für diesen Creator; leer = Wert der Stufe + discountType String? + discountValue Int? + discountCap Int? + commissionRate Int? + // Kanäle, je Zeile ein Link + channels String @default("") + focus String @default("") + // "small" (Kleinunternehmer), "regular" (+19 % USt), "eu" (Reverse Charge), "" = noch offen + taxStatus String @default("") + vatId String @default("") + accountHolder String @default("") + iban String @default("") + payoutMethod String @default("transfer") + termsAcceptedAt DateTime? + termsVersion String @default("") + note String @default("") + coupons Coupon[] + orders Order[] + commissions Commission[] + payouts CreatorPayout[] + clicks CreatorClick[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + +// Klicks auf den Creator-Link, nur gezählt (ohne IP), je Tag (YYYY-MM-DD, deutsche Zeit) +model CreatorClick { + creatorId String + creator Creator @relation(fields: [creatorId], references: [id], onDelete: Cascade) + day String + count Int @default(0) + + @@id([creatorId, day]) +} + +model Commission { + id String @id @default(cuid()) + creatorId String + creator Creator @relation(fields: [creatorId], references: [id], onDelete: Cascade) + orderId String @unique + order Order @relation(fields: [orderId], references: [id], onDelete: Cascade) + // Cent + amount Int + base Int + rate Int + // "pending" (vorgemerkt), "approved" (freigegeben), "paid" (ausgezahlt), "cancelled" (storniert), + // "reversed" (nach Auszahlung storniert, wird mit der nächsten Auszahlung verrechnet), "offset" (verrechnet) + status String @default("pending") + // Ab wann die Provision freigegeben wird (Versand bzw. Zahlung + Haltefrist) + releaseAt DateTime? + payoutId String? + payout CreatorPayout? @relation("PayoutCommissions", fields: [payoutId], references: [id], onDelete: SetNull) + // Bei "offset": die Auszahlung, mit der verrechnet wurde + offsetPayoutId String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([creatorId, status]) +} + +model CreatorPayout { + id String @id @default(cuid()) + creatorId String + creator Creator @relation(fields: [creatorId], references: [id], onDelete: Cascade) + // Cent, nach Verrechnung + amount Int + method String @default("transfer") + note String @default("") + author String @default("") + commissions Commission[] @relation("PayoutCommissions") + paidAt DateTime @default(now()) +} diff --git a/src/app/(shop)/kasse/actions.ts b/src/app/(shop)/kasse/actions.ts index 81d9c36..0061194 100644 --- a/src/app/(shop)/kasse/actions.ts +++ b/src/app/(shop)/kasse/actions.ts @@ -103,7 +103,7 @@ export async function placeOrder(_prev: FormState, formData: FormData): Promise< 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 }); + const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value, shipping, payment, email: state.email }); if (settings.checkout.minOrderValue > 0 && totals.subtotal < settings.checkout.minOrderValue) redirect("/warenkorb"); let order; diff --git a/src/app/(shop)/kasse/shared.tsx b/src/app/(shop)/kasse/shared.tsx index 65f7639..3492a47 100644 --- a/src/app/(shop)/kasse/shared.tsx +++ b/src/app/(shop)/kasse/shared.tsx @@ -14,7 +14,7 @@ export async function loadCheckout() { state.shippingMethodId ? db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : 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, email: state.email }); // 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) }; } diff --git a/src/app/(shop)/konto/creator/actions.ts b/src/app/(shop)/konto/creator/actions.ts new file mode 100644 index 0000000..dfdd4fc --- /dev/null +++ b/src/app/(shop)/konto/creator/actions.ts @@ -0,0 +1,41 @@ +"use server"; +import { revalidatePath } from "next/cache"; +import { db } from "@/lib/db"; +import { audit, getCurrentUser } from "@/lib/auth"; +import { getSettings } from "@/lib/settings"; +import { TAX_STATUS } from "@/lib/creators"; +import type { AccountState } from "../actions"; + +async function myCreator() { + const user = await getCurrentUser(); + if (!user) return null; + const creator = await db.creator.findUnique({ where: { userId: user.id } }); + return creator ? { user, creator } : null; +} + +export async function acceptCreatorTerms(_prev: AccountState, fd: FormData): Promise { + const me = await myCreator(); + if (!me) return { error: "Bitte melde dich erneut an." }; + if (fd.get("accept") !== "on") return { errors: { accept: "Bitte bestätige die Programmbedingungen." } }; + if (fd.get("adult") !== "on") return { errors: { adult: "Bitte bestätige, dass du volljährig bist oder deine Eltern zustimmen." } }; + const { termsVersion } = (await getSettings()).creator; + await db.creator.update({ where: { id: me.creator.id }, data: { termsAcceptedAt: new Date(), termsVersion } }); + await audit(me.user, "Creator-Bedingungen bestätigt", `Version ${termsVersion}`); + revalidatePath("/konto/creator"); + return { ok: "Danke! Dein Code ist jetzt aktiv." }; +} + +export async function saveCreatorPayout(_prev: AccountState, fd: FormData): Promise { + const me = await myCreator(); + if (!me) return { error: "Bitte melde dich erneut an." }; + const taxStatus = String(fd.get("taxStatus") ?? ""); + const vatId = String(fd.get("vatId") ?? "").trim().toUpperCase().replace(/\s+/g, ""); + const iban = String(fd.get("iban") ?? "").toUpperCase().replace(/\s+/g, ""); + const values = { taxStatus, vatId, iban, accountHolder: String(fd.get("accountHolder") ?? "").trim() }; + if (!(taxStatus in TAX_STATUS)) return { errors: { taxStatus: "Bitte wähle deinen Steuerstatus." }, values }; + if (taxStatus === "eu" && !/^[A-Z]{2}[0-9A-Z]{6,12}$/.test(vatId)) return { errors: { vatId: "Für Reverse Charge brauchen wir deine USt-IdNr." }, values }; + if (iban && !/^[A-Z]{2}[0-9]{2}[A-Z0-9]{10,30}$/.test(iban)) return { errors: { iban: "Diese IBAN sieht nicht richtig aus." }, values }; + await db.creator.update({ where: { id: me.creator.id }, data: { taxStatus, vatId, iban, accountHolder: values.accountHolder } }); + revalidatePath("/konto/creator"); + return { ok: "Gespeichert." }; +} diff --git a/src/app/(shop)/konto/creator/page.tsx b/src/app/(shop)/konto/creator/page.tsx new file mode 100644 index 0000000..3975b3e --- /dev/null +++ b/src/app/(shop)/konto/creator/page.tsx @@ -0,0 +1,144 @@ +import { redirect } from "next/navigation"; +import { db } from "@/lib/db"; +import { getCurrentUser } from "@/lib/auth"; +import { formatPrice } from "@/lib/money"; +import { getSettings } from "@/lib/settings"; +import { dateFmt } from "@/lib/status"; +import { + COMMISSION_STATUS, + CREATOR_STATUS, + TAX_STATUS, + balance, + creatorLinkBase, + discountLabel, + effectiveTerms, + formatRate, + monthLabel, + monthlyStats, + refreshCommissions, +} from "@/lib/creators"; +import { Alert } from "@/components/shop/Blocks"; +import { AccountShell } from "@/components/shop/account/AccountShell"; +import { CopyLine, PayoutForm, TermsForm } from "@/components/shop/account/CreatorForms"; + +export const metadata = { title: "Creator-Bereich" }; + +export default async function CreatorArea() { + const user = await getCurrentUser(); + if (!user) redirect("/konto/anmelden?weiter=/konto/creator"); + const me = await db.creator.findUnique({ where: { userId: user.id }, select: { id: true } }); + if (!me) redirect("/konto"); + await refreshCommissions(me.id); + const creator = await db.creator.findUnique({ + where: { userId: user.id }, + include: { + tier: true, + coupons: { where: { active: true }, orderBy: { createdAt: "desc" } }, + commissions: { orderBy: { createdAt: "desc" }, take: 100, include: { order: { select: { number: true, subtotal: true, discount: true } } } }, + payouts: { orderBy: { paidAt: "desc" } }, + }, + }); + if (!creator) redirect("/konto"); + const [settings, stats, fresh] = await Promise.all([ + getSettings(), + monthlyStats(creator.id, 6), + db.commission.findMany({ where: { creatorId: creator.id }, select: { status: true, amount: true, payoutId: true } }), + ]); + const s = settings.creator; + const terms = effectiveTerms(creator); + const b = balance(fresh); + const code = creator.coupons[0]?.code; + const link = code ? `${creatorLinkBase()}/c/${code}` : ""; + const needsTerms = !creator.termsAcceptedAt; + const renew = Boolean(creator.termsAcceptedAt) && creator.termsVersion !== s.termsVersion; + const ended = creator.status !== "active"; + + return ( + + {ended && ( +
+ Dein Code ist gerade nicht aktiv. Bei Fragen schreib uns an {settings.general.email}. +
+ )} + + {(needsTerms || renew) && ( +
+

{renew ? "Neue Programmbedingungen" : "Programmbedingungen bestätigen"}

+

{renew ? "Wir haben die Bedingungen geändert. Dein Code bleibt aktiv; bitte lies die neue Fassung und stimme zu." : "Bevor dein Code aktiv wird, lies bitte die Bedingungen und stimme zu."}

+ +
+ )} + + {code && !needsTerms && ( +
+

Dein Code

+

Deine Community bekommt {discountLabel(terms)}{terms.discountCap ? ` (höchstens ${formatPrice(terms.discountCap)})` : ""}{terms.minOrder ? ` ab ${formatPrice(terms.minOrder)} Warenwert` : ""}. Du bekommst {formatRate(terms.commissionRate)} vom Nettowarenwert nach Rabatt.

+ +

Link, der den Code automatisch einträgt (auch für einzelne Seiten, z. B. {link}/produkt/…):

+ +

Bitte kennzeichne jedes Video und jeden Post mit deinem Code deutlich als „Werbung“ oder „Anzeige“. Reduzierte Artikel und Beratungstermine sind vom Code ausgenommen.

+
+ )} + +
+
Vorgemerkt{formatPrice(b.pending)}
+
Freigegeben{formatPrice(Math.max(0, b.payable))}
+
Bisher ausgezahlt{formatPrice(creator.payouts.reduce((sum, p) => sum + p.amount, 0))}
+
+ +
+

Zahlen je Monat

+
+ + + + {stats.map((m) => ( + + ))} + +
MonatKlicksBestellungenUmsatzProvision
{monthLabel(m.month)}{m.clicks}{m.orders}{formatPrice(m.revenue)}{formatPrice(m.commission)}
+
+

Klicks werden nur gezählt, ohne IP-Adresse. Umsatz = Warenwert nach Rabatt, ohne Versand.

+
+ +
+

Provisionen

+

Eine Provision wird {s.holdDays} Tage nach dem Versand freigegeben (bei Video-Kursen nach der Zahlung), damit Rücksendungen schon erfasst sind. Danach überweisen wir sie.

+ {creator.commissions.length === 0 ? ( +

Noch keine Bestellungen mit deinem Code.

+ ) : ( +
+ + + + {creator.commissions.map((c) => ( + + + + + + + + ))} + +
BestellungDatumWarenwertProvisionStatus
{c.order.number}{dateFmt.format(c.createdAt)}{formatPrice(c.order.subtotal - c.order.discount)}{formatPrice(c.amount)}{COMMISSION_STATUS[c.status]?.label ?? c.status}{c.status === "pending" && c.releaseAt ? ` · frei ab ${dateFmt.format(c.releaseAt)}` : ""}
+
+ )} +
+ +
+

Auszahlung und Steuern

+

Wir überweisen freigegebene Provisionen auf dieses Konto. Die Provision ist dein Einkommen; gib deinen Steuerstatus bitte korrekt an.

+ + {creator.payouts.length > 0 && ( +
+ + + {creator.payouts.map((p) => )} +
Ausgezahlt amBetrag
{dateFmt.format(p.paidAt)}{formatPrice(p.amount)}
+
+ )} +
+
+ ); +} diff --git a/src/app/(shop)/layout.tsx b/src/app/(shop)/layout.tsx index c8d1f67..49bd9e6 100644 --- a/src/app/(shop)/layout.tsx +++ b/src/app/(shop)/layout.tsx @@ -1,5 +1,6 @@ import { Header } from "@/components/shop/Header"; import { Footer } from "@/components/shop/Footer"; +import { CreatorBar } from "@/components/shop/CreatorBar"; import { getSettings } from "@/lib/settings"; import { can, getCurrentUser } from "@/lib/auth"; @@ -19,6 +20,7 @@ export default async function ShopLayout({ children }: { children: React.ReactNo } return ( <> +
{children}