Creator-Programm Phase 1: persönliche Codes, Link /c/CODE, Provisionen, Admin und Creator-Bereich
- 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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HsJ4RG9iGFNcNnG8YcScYE
This commit is contained in:
parent
d9ffdec854
commit
d218ec5b8c
43 changed files with 1778 additions and 59 deletions
146
prisma/migrations/20261111040000_creators/migration.sql
Normal file
146
prisma/migrations/20261111040000_creators/migration.sql
Normal file
|
|
@ -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());
|
||||||
|
|
@ -44,6 +44,7 @@ model User {
|
||||||
progress LessonProgress[]
|
progress LessonProgress[]
|
||||||
advisor Advisor?
|
advisor Advisor?
|
||||||
appointments Appointment[] @relation("CustomerAppointments")
|
appointments Appointment[] @relation("CustomerAppointments")
|
||||||
|
creator Creator?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
}
|
}
|
||||||
|
|
@ -129,6 +130,8 @@ model Product {
|
||||||
badge String @default("") // "", "new", "best"
|
badge String @default("") // "", "new", "best"
|
||||||
// "physical" = Ware mit Versand, "course" = Video-Kurs (digital, ohne Versand und Bestand)
|
// "physical" = Ware mit Versand, "course" = Video-Kurs (digital, ohne Versand und Bestand)
|
||||||
kind String @default("physical")
|
kind String @default("physical")
|
||||||
|
// Creator-Codes geben auf dieses Produkt weder Rabatt noch Provision
|
||||||
|
noCreatorDiscount Boolean @default(false)
|
||||||
images String[]
|
images String[]
|
||||||
sort Int @default(0)
|
sort Int @default(0)
|
||||||
categoryId String?
|
categoryId String?
|
||||||
|
|
@ -273,6 +276,14 @@ model Order {
|
||||||
paymentFee Int @default(0)
|
paymentFee Int @default(0)
|
||||||
discount Int @default(0)
|
discount Int @default(0)
|
||||||
couponCode String @default("")
|
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
|
taxAmount Int
|
||||||
total Int
|
total Int
|
||||||
note String @default("")
|
note String @default("")
|
||||||
|
|
@ -303,6 +314,8 @@ model OrderItem {
|
||||||
quantity Int
|
quantity Int
|
||||||
taxRate Int
|
taxRate Int
|
||||||
total Int
|
total Int
|
||||||
|
// Anteil des Gutscheinrabatts an dieser Position (Cent, brutto)
|
||||||
|
discount Int @default(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rechnungen und Stornorechnungen. `data` ist eine unveränderliche Momentaufnahme
|
// Rechnungen und Stornorechnungen. `data` ist eine unveränderliche Momentaufnahme
|
||||||
|
|
@ -385,7 +398,12 @@ model Coupon {
|
||||||
usedCount Int @default(0)
|
usedCount Int @default(0)
|
||||||
active Boolean @default(true)
|
active Boolean @default(true)
|
||||||
validUntil DateTime?
|
validUntil DateTime?
|
||||||
|
// Gesetzt = Creator-Code dieses Creators
|
||||||
|
creatorId String?
|
||||||
|
creator Creator? @relation(fields: [creatorId], references: [id], onDelete: SetNull)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([creatorId])
|
||||||
}
|
}
|
||||||
|
|
||||||
model Page {
|
model Page {
|
||||||
|
|
@ -646,3 +664,112 @@ model AppointmentProposal {
|
||||||
startsAt DateTime
|
startsAt DateTime
|
||||||
endsAt 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())
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -103,7 +103,7 @@ export async function placeOrder(_prev: FormState, formData: FormData): Promise<
|
||||||
if (!digitalOnly && !shipping?.enabled) redirect("/kasse/versand");
|
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, email: state.email });
|
||||||
if (settings.checkout.minOrderValue > 0 && totals.subtotal < settings.checkout.minOrderValue) redirect("/warenkorb");
|
if (settings.checkout.minOrderValue > 0 && totals.subtotal < settings.checkout.minOrderValue) redirect("/warenkorb");
|
||||||
|
|
||||||
let order;
|
let order;
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ export async function loadCheckout() {
|
||||||
state.shippingMethodId ? db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : null,
|
state.shippingMethodId ? db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : null,
|
||||||
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, email: state.email });
|
||||||
// Nur Kurse: kein Versand-Schritt; Kurse im Warenkorb: Konto und Widerrufs-Zustimmung nötig
|
// 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) };
|
return { lines, state, shipping, payment, totals, digitalOnly: isDigitalOnly(lines), hasCourse: hasDigital(lines) };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
41
src/app/(shop)/konto/creator/actions.ts
Normal file
41
src/app/(shop)/konto/creator/actions.ts
Normal file
|
|
@ -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<AccountState> {
|
||||||
|
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<AccountState> {
|
||||||
|
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." };
|
||||||
|
}
|
||||||
144
src/app/(shop)/konto/creator/page.tsx
Normal file
144
src/app/(shop)/konto/creator/page.tsx
Normal file
|
|
@ -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 (
|
||||||
|
<AccountShell user={user} title="Creator-Bereich" lead={`Dein Code, deine Zahlen und deine Provisionen. Stufe: ${creator.tier.name}.`}>
|
||||||
|
{ended && (
|
||||||
|
<div className="sm-account__alert">
|
||||||
|
<Alert title={`Dein Creator-Status: ${CREATOR_STATUS[creator.status]?.label ?? creator.status}.`}>Dein Code ist gerade nicht aktiv. Bei Fragen schreib uns an {settings.general.email}.</Alert>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{(needsTerms || renew) && (
|
||||||
|
<section className="sm-creator__box">
|
||||||
|
<h2 className="display-sm">{renew ? "Neue Programmbedingungen" : "Programmbedingungen bestätigen"}</h2>
|
||||||
|
<p className="body">{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."}</p>
|
||||||
|
<TermsForm terms={s.terms} version={s.termsVersion} renew={renew} />
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{code && !needsTerms && (
|
||||||
|
<section className="sm-creator__box">
|
||||||
|
<h2 className="display-sm">Dein Code</h2>
|
||||||
|
<p className="body">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.</p>
|
||||||
|
<CopyLine value={code} />
|
||||||
|
<p className="body-sm" style={{ margin: "0 0 var(--space-2)" }}>Link, der den Code automatisch einträgt (auch für einzelne Seiten, z. B. {link}/produkt/…):</p>
|
||||||
|
<CopyLine value={link} />
|
||||||
|
<p className="body-sm" style={{ color: "var(--ink-muted)", margin: 0 }}>Bitte kennzeichne jedes Video und jeden Post mit deinem Code deutlich als „Werbung“ oder „Anzeige“. Reduzierte Artikel und Beratungstermine sind vom Code ausgenommen.</p>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="sm-creator__grid">
|
||||||
|
<div className="sm-creator__stat"><span>Vorgemerkt</span><strong>{formatPrice(b.pending)}</strong></div>
|
||||||
|
<div className="sm-creator__stat"><span>Freigegeben</span><strong>{formatPrice(Math.max(0, b.payable))}</strong></div>
|
||||||
|
<div className="sm-creator__stat"><span>Bisher ausgezahlt</span><strong>{formatPrice(creator.payouts.reduce((sum, p) => sum + p.amount, 0))}</strong></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="sm-creator__box">
|
||||||
|
<h2 className="display-sm">Zahlen je Monat</h2>
|
||||||
|
<div className="sm-creator__scroll">
|
||||||
|
<table className="sm-creator__table">
|
||||||
|
<thead><tr><th>Monat</th><th className="num">Klicks</th><th className="num">Bestellungen</th><th className="num">Umsatz</th><th className="num">Provision</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{stats.map((m) => (
|
||||||
|
<tr key={m.month}><td>{monthLabel(m.month)}</td><td className="num">{m.clicks}</td><td className="num">{m.orders}</td><td className="num">{formatPrice(m.revenue)}</td><td className="num">{formatPrice(m.commission)}</td></tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p className="body-sm" style={{ color: "var(--ink-muted)", marginBottom: 0 }}>Klicks werden nur gezählt, ohne IP-Adresse. Umsatz = Warenwert nach Rabatt, ohne Versand.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="sm-creator__box">
|
||||||
|
<h2 className="display-sm">Provisionen</h2>
|
||||||
|
<p className="body-sm" style={{ color: "var(--ink-muted)" }}>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.</p>
|
||||||
|
{creator.commissions.length === 0 ? (
|
||||||
|
<p className="body">Noch keine Bestellungen mit deinem Code.</p>
|
||||||
|
) : (
|
||||||
|
<div className="sm-creator__scroll">
|
||||||
|
<table className="sm-creator__table">
|
||||||
|
<thead><tr><th>Bestellung</th><th>Datum</th><th className="num">Warenwert</th><th className="num">Provision</th><th>Status</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{creator.commissions.map((c) => (
|
||||||
|
<tr key={c.id}>
|
||||||
|
<td>{c.order.number}</td>
|
||||||
|
<td>{dateFmt.format(c.createdAt)}</td>
|
||||||
|
<td className="num">{formatPrice(c.order.subtotal - c.order.discount)}</td>
|
||||||
|
<td className="num">{formatPrice(c.amount)}</td>
|
||||||
|
<td>{COMMISSION_STATUS[c.status]?.label ?? c.status}{c.status === "pending" && c.releaseAt ? ` · frei ab ${dateFmt.format(c.releaseAt)}` : ""}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="sm-creator__box">
|
||||||
|
<h2 className="display-sm">Auszahlung und Steuern</h2>
|
||||||
|
<p className="body-sm" style={{ color: "var(--ink-muted)" }}>Wir überweisen freigegebene Provisionen auf dieses Konto. Die Provision ist dein Einkommen; gib deinen Steuerstatus bitte korrekt an.</p>
|
||||||
|
<PayoutForm values={{ taxStatus: creator.taxStatus, vatId: creator.vatId, iban: creator.iban, accountHolder: creator.accountHolder }} taxOptions={Object.entries(TAX_STATUS)} />
|
||||||
|
{creator.payouts.length > 0 && (
|
||||||
|
<div className="sm-creator__scroll" style={{ marginTop: "var(--space-4)" }}>
|
||||||
|
<table className="sm-creator__table">
|
||||||
|
<thead><tr><th>Ausgezahlt am</th><th className="num">Betrag</th></tr></thead>
|
||||||
|
<tbody>{creator.payouts.map((p) => <tr key={p.id}><td>{dateFmt.format(p.paidAt)}</td><td className="num">{formatPrice(p.amount)}</td></tr>)}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</AccountShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { Header } from "@/components/shop/Header";
|
import { Header } from "@/components/shop/Header";
|
||||||
import { Footer } from "@/components/shop/Footer";
|
import { Footer } from "@/components/shop/Footer";
|
||||||
|
import { CreatorBar } from "@/components/shop/CreatorBar";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
import { can, getCurrentUser } from "@/lib/auth";
|
import { can, getCurrentUser } from "@/lib/auth";
|
||||||
|
|
||||||
|
|
@ -19,6 +20,7 @@ export default async function ShopLayout({ children }: { children: React.ReactNo
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<CreatorBar />
|
||||||
<Header />
|
<Header />
|
||||||
{children}
|
{children}
|
||||||
<Footer />
|
<Footer />
|
||||||
|
|
|
||||||
|
|
@ -49,13 +49,23 @@ export default async function CartPage({ searchParams }: { searchParams: Promise
|
||||||
)}
|
)}
|
||||||
{totals.coupon && (
|
{totals.coupon && (
|
||||||
<div style={{ marginBottom: "var(--space-4)" }}>
|
<div style={{ marginBottom: "var(--space-4)" }}>
|
||||||
<Alert kind="success" title={`Gutschein ${totals.coupon.code} eingelöst.`}>
|
<Alert kind="success" title={totals.creator ? `Code ${totals.coupon.code} eingelöst: ${totals.creator.label}.` : `Gutschein ${totals.coupon.code} eingelöst.`}>
|
||||||
|
{totals.couponNotice && <>{totals.couponNotice} </>}
|
||||||
<form action={removeCoupon} style={{ display: "inline" }}>
|
<form action={removeCoupon} style={{ display: "inline" }}>
|
||||||
<button type="submit" className="sm-cartline__remove" style={{ padding: 0 }}>Gutschein entfernen</button>
|
<button type="submit" className="sm-cartline__remove" style={{ padding: 0 }}>Gutschein entfernen</button>
|
||||||
</form>
|
</form>
|
||||||
</Alert>
|
</Alert>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{!totals.coupon && totals.couponError && jar.get("sm_coupon")?.value && (
|
||||||
|
<div style={{ marginBottom: "var(--space-4)" }}>
|
||||||
|
<Alert title={`Code ${jar.get("sm_coupon")?.value}: ${totals.couponError}`}>
|
||||||
|
<form action={removeCoupon} style={{ display: "inline" }}>
|
||||||
|
<button type="submit" className="sm-cartline__remove" style={{ padding: 0 }}>Code entfernen</button>
|
||||||
|
</form>
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{lines.map((l) => (
|
{lines.map((l) => (
|
||||||
<div className="sm-cartline" key={l.key}>
|
<div className="sm-cartline" key={l.key}>
|
||||||
<div className="sm-cartline__media"><ProductImage src={l.image} alt={l.name} /></div>
|
<div className="sm-cartline__media"><ProductImage src={l.image} alt={l.name} /></div>
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ export default async function OrderDetail({ params }: { params: Promise<{ id: st
|
||||||
return (
|
return (
|
||||||
<div className="ad-wrap">
|
<div className="ad-wrap">
|
||||||
<PageHead title={`Bestellung ${order.number}`} lead={`${dateFmt.format(order.createdAt)} · ${order.email}`} back={{ href: "/admin/bestellungen", label: "Bestellungen" }}>
|
<PageHead title={`Bestellung ${order.number}`} lead={`${dateFmt.format(order.createdAt)} · ${order.email}`} back={{ href: "/admin/bestellungen", label: "Bestellungen" }}>
|
||||||
|
{order.creatorId && <Link href={`/admin/creator/${order.creatorId}`} style={{ textDecoration: "none" }}><Pill tone="gold">Creator: {order.couponCode}</Pill></Link>}
|
||||||
<Pill tone={PAYMENT_STATUS[order.paymentStatus].tone}>{PAYMENT_STATUS[order.paymentStatus].label}</Pill>
|
<Pill tone={PAYMENT_STATUS[order.paymentStatus].tone}>{PAYMENT_STATUS[order.paymentStatus].label}</Pill>
|
||||||
<Pill tone={ORDER_STATUS[order.status].tone}>{ORDER_STATUS[order.status].label}</Pill>
|
<Pill tone={ORDER_STATUS[order.status].tone}>{ORDER_STATUS[order.status].label}</Pill>
|
||||||
</PageHead>
|
</PageHead>
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ import { mailCancelled, mailPaymentReceived, mailShipped, sendLater } from "@/li
|
||||||
import { grantCourseAccess, isDigitalOrder } from "@/lib/courses";
|
import { grantCourseAccess, isDigitalOrder } from "@/lib/courses";
|
||||||
import { cancelOrderById } from "@/lib/order-cancel";
|
import { cancelOrderById } from "@/lib/order-cancel";
|
||||||
import { bookAppointmentForOrder, cancelAppointmentForOrder } from "@/lib/consulting";
|
import { bookAppointmentForOrder, cancelAppointmentForOrder } from "@/lib/consulting";
|
||||||
|
import { syncCommission } from "@/lib/creators";
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
|
|
@ -60,6 +61,7 @@ export async function updateOrder(_prev: ActionResult, fd: FormData): Promise<Ac
|
||||||
await autoInvoice(id, "shipped");
|
await autoInvoice(id, "shipped");
|
||||||
sendLater(() => mailShipped(id));
|
sendLater(() => mailShipped(id));
|
||||||
}
|
}
|
||||||
|
await syncCommission(id);
|
||||||
revalidatePath(`/admin/bestellungen/${id}`);
|
revalidatePath(`/admin/bestellungen/${id}`);
|
||||||
return ok();
|
return ok();
|
||||||
}
|
}
|
||||||
|
|
@ -117,6 +119,7 @@ export async function createDhlLabel(_prev: ActionResult, fd: FormData): Promise
|
||||||
await autoInvoice(id, "shipped");
|
await autoInvoice(id, "shipped");
|
||||||
sendLater(() => mailShipped(id));
|
sendLater(() => mailShipped(id));
|
||||||
}
|
}
|
||||||
|
await syncCommission(id);
|
||||||
revalidatePath(`/admin/bestellungen/${id}`);
|
revalidatePath(`/admin/bestellungen/${id}`);
|
||||||
return ok("Label erstellt.");
|
return ok("Label erstellt.");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -60,7 +60,7 @@ export default async function OrdersPage({ searchParams }: { searchParams: Promi
|
||||||
const addr = o.shippingAddress as { firstName?: string; lastName?: string };
|
const addr = o.shippingAddress as { firstName?: string; lastName?: string };
|
||||||
return (
|
return (
|
||||||
<tr key={o.id}>
|
<tr key={o.id}>
|
||||||
<td><Link className="ad-rowlink" href={`/admin/bestellungen/${o.id}`}>{o.number}</Link><div className="body-sm ad-muted">{o._count.items} Positionen</div></td>
|
<td><Link className="ad-rowlink" href={`/admin/bestellungen/${o.id}`}>{o.number}</Link><div className="body-sm ad-muted">{o._count.items} Positionen</div>{o.creatorId && <Pill tone="gold">Creator: {o.couponCode}</Pill>}</td>
|
||||||
<td className="body-sm">{dateFmt.format(o.createdAt)}</td>
|
<td className="body-sm">{dateFmt.format(o.createdAt)}</td>
|
||||||
<td>{addr.firstName} {addr.lastName}<div className="body-sm ad-muted">{o.email}</div></td>
|
<td>{addr.firstName} {addr.lastName}<div className="body-sm ad-muted">{o.email}</div></td>
|
||||||
<td><Pill tone={PAYMENT_STATUS[o.paymentStatus].tone}>{PAYMENT_STATUS[o.paymentStatus].label}</Pill></td>
|
<td><Pill tone={PAYMENT_STATUS[o.paymentStatus].tone}>{PAYMENT_STATUS[o.paymentStatus].label}</Pill></td>
|
||||||
|
|
|
||||||
227
src/app/admin/(panel)/creator/[id]/page.tsx
Normal file
227
src/app/admin/(panel)/creator/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,227 @@
|
||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { can, requireAdmin } from "@/lib/auth";
|
||||||
|
import { centsToInput, formatPrice } from "@/lib/money";
|
||||||
|
import { dateFmt } from "@/lib/status";
|
||||||
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import {
|
||||||
|
COMMISSION_STATUS,
|
||||||
|
CREATOR_STATUS,
|
||||||
|
TAX_STATUS,
|
||||||
|
balance,
|
||||||
|
creatorLinkBase,
|
||||||
|
creatorName,
|
||||||
|
discountLabel,
|
||||||
|
effectiveTerms,
|
||||||
|
formatRate,
|
||||||
|
monthLabel,
|
||||||
|
monthlyStats,
|
||||||
|
refreshCommissions,
|
||||||
|
} from "@/lib/creators";
|
||||||
|
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
|
||||||
|
import { CopyValue } from "@/components/admin/CopyValue";
|
||||||
|
import { Card, PageHead, Pill } from "@/components/admin/ui";
|
||||||
|
import { Field, SelectField, TextareaField } from "@/components/Field";
|
||||||
|
import { payoutCreator, replaceCode, toggleCode, updateCreator } from "../actions";
|
||||||
|
|
||||||
|
export default async function CreatorDetail({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ neu?: string }> }) {
|
||||||
|
const user = await requireAdmin("creators.view");
|
||||||
|
const { id } = await params;
|
||||||
|
const sp = await searchParams;
|
||||||
|
await refreshCommissions(id);
|
||||||
|
const creator = await db.creator.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: {
|
||||||
|
user: true,
|
||||||
|
tier: true,
|
||||||
|
coupons: { orderBy: { createdAt: "desc" } },
|
||||||
|
commissions: { orderBy: { createdAt: "desc" }, include: { order: { select: { id: true, number: true, subtotal: true, discount: true, couponCode: true, status: true, createdAt: true } } } },
|
||||||
|
payouts: { orderBy: { paidAt: "desc" } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!creator) notFound();
|
||||||
|
const [tiers, stats, settings] = await Promise.all([db.creatorTier.findMany({ orderBy: { sort: "asc" } }), monthlyStats(id, 6), getSettings()]);
|
||||||
|
const canEdit = can(user, "creators.edit");
|
||||||
|
const canPay = can(user, "creators.payout");
|
||||||
|
const terms = effectiveTerms(creator);
|
||||||
|
const b = balance(creator.commissions);
|
||||||
|
const activeCode = creator.coupons.find((c) => c.active);
|
||||||
|
const base = creatorLinkBase();
|
||||||
|
const outdated = creator.termsAcceptedAt && creator.termsVersion !== settings.creator.termsVersion;
|
||||||
|
return (
|
||||||
|
<div className="ad-wrap">
|
||||||
|
<PageHead title={creatorName(creator)} lead={`${creator.user.email} · seit ${dateFmt.format(creator.createdAt)}`} back={{ href: "/admin/creator", label: "Creator" }}>
|
||||||
|
<Pill tone={CREATOR_STATUS[creator.status]?.tone ?? "neutral"}>{CREATOR_STATUS[creator.status]?.label ?? creator.status}</Pill>
|
||||||
|
<Pill tone={creator.termsAcceptedAt ? "success" : "gold"}>{creator.termsAcceptedAt ? `Bedingungen v${creator.termsVersion} bestätigt` : "Bedingungen offen"}</Pill>
|
||||||
|
</PageHead>
|
||||||
|
{sp.neu && (
|
||||||
|
<p className="ad-help" style={{ marginBottom: "var(--space-4)" }}>
|
||||||
|
Creator angelegt. Der Code wird aktiv, sobald die Programmbedingungen im Kundenkonto unter „Creator“ bestätigt sind.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="ad-grid ad-grid--2-1">
|
||||||
|
<div>
|
||||||
|
<Card title="Zahlen je Monat" flush>
|
||||||
|
<div className="ad-table-wrap">
|
||||||
|
<table className="ad-table">
|
||||||
|
<thead><tr><th>Monat</th><th className="num">Klicks</th><th className="num">Bestellungen</th><th className="num">Conversion</th><th className="num">Umsatz</th><th className="num">Provision</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{stats.map((m) => (
|
||||||
|
<tr key={m.month}>
|
||||||
|
<td>{monthLabel(m.month)}</td>
|
||||||
|
<td className="num">{m.clicks}</td>
|
||||||
|
<td className="num">{m.orders}{m.cancelled ? <span className="ad-muted"> (+{m.cancelled} storniert)</span> : ""}</td>
|
||||||
|
<td className="num">{m.clicks ? `${((m.orders / m.clicks) * 100).toLocaleString("de-DE", { maximumFractionDigits: 1 })} %` : "–"}</td>
|
||||||
|
<td className="num">{formatPrice(m.revenue)}</td>
|
||||||
|
<td className="num">{formatPrice(m.commission)}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title="Provisionen" lead={`Freigabe ${settings.creator.holdDays} Tage nach Versand (Kurse: nach Zahlung). Stornos werden automatisch abgezogen.`} flush>
|
||||||
|
{creator.commissions.length === 0 ? (
|
||||||
|
<div className="ad-card__body"><p className="body-sm ad-muted" style={{ margin: 0 }}>Noch keine Bestellungen mit diesem Code.</p></div>
|
||||||
|
) : (
|
||||||
|
<div className="ad-table-wrap">
|
||||||
|
<table className="ad-table">
|
||||||
|
<thead><tr><th>Bestellung</th><th>Datum</th><th className="num">Warenwert</th><th className="num">Basis netto</th><th className="num">Satz</th><th className="num">Provision</th><th>Status</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{creator.commissions.map((c) => (
|
||||||
|
<tr key={c.id}>
|
||||||
|
<td><Link className="ad-rowlink" href={`/admin/bestellungen/${c.order.id}`}>{c.order.number}</Link><div className="body-sm ad-muted">{c.order.couponCode}</div></td>
|
||||||
|
<td className="body-sm">{dateFmt.format(c.createdAt)}</td>
|
||||||
|
<td className="num">{formatPrice(c.order.subtotal - c.order.discount)}</td>
|
||||||
|
<td className="num">{formatPrice(c.base)}</td>
|
||||||
|
<td className="num">{formatRate(c.rate)}</td>
|
||||||
|
<td className="num">{formatPrice(c.amount)}</td>
|
||||||
|
<td>
|
||||||
|
<Pill tone={COMMISSION_STATUS[c.status]?.tone ?? "neutral"}>{COMMISSION_STATUS[c.status]?.label ?? c.status}</Pill>
|
||||||
|
{c.status === "pending" && <div className="body-sm ad-muted">{c.releaseAt ? `frei ab ${dateFmt.format(c.releaseAt)}` : "wartet auf Zahlung/Versand"}</div>}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title="Auszahlungen" lead="Phase 1: Überweisung von Hand, hier verbuchen. Gutschrift-PDF und CSV kommen mit Phase 2.">
|
||||||
|
<div className="ad-kv" style={{ marginBottom: "var(--space-4)" }}>
|
||||||
|
<p className="body-sm" style={{ margin: 0 }}>
|
||||||
|
Freigegeben: <strong>{formatPrice(b.approved)}</strong>
|
||||||
|
{b.reversed > 0 && <> · abzüglich nachträglicher Stornos: <strong>−{formatPrice(b.reversed)}</strong></>}
|
||||||
|
{" "}· auszahlbar: <strong>{formatPrice(b.payable)}</strong> · noch vorgemerkt: {formatPrice(b.pending)}
|
||||||
|
</p>
|
||||||
|
<p className="body-sm ad-muted" style={{ margin: "var(--space-2) 0 0" }}>
|
||||||
|
Bankverbindung: {creator.iban ? `${creator.accountHolder || creatorName(creator)} · ${creator.iban}` : "noch nicht hinterlegt"} · Steuerstatus: {TAX_STATUS[creator.taxStatus] ?? creator.taxStatus}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{canPay && b.payable > 0 && (
|
||||||
|
<AdminForm action={payoutCreator} submitLabel={`${formatPrice(b.payable)} als überwiesen verbuchen`}>
|
||||||
|
<input type="hidden" name="id" value={creator.id} />
|
||||||
|
<Field label="Notiz" name="note" optional placeholder="z. B. Überweisung vom 01.12." />
|
||||||
|
</AdminForm>
|
||||||
|
)}
|
||||||
|
{creator.payouts.length > 0 && (
|
||||||
|
<div className="ad-table-wrap" style={{ marginTop: "var(--space-4)" }}>
|
||||||
|
<table className="ad-table">
|
||||||
|
<thead><tr><th>Datum</th><th className="num">Betrag</th><th>Notiz</th><th>Von</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{creator.payouts.map((p) => (
|
||||||
|
<tr key={p.id}><td className="body-sm">{dateFmt.format(p.paidAt)}</td><td className="num">{formatPrice(p.amount)}</td><td className="body-sm">{p.note}</td><td className="body-sm">{p.author}</td></tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<Card title="Code und Link">
|
||||||
|
{activeCode ? (
|
||||||
|
<>
|
||||||
|
<CopyValue label="Code" value={activeCode.code} />
|
||||||
|
<CopyValue label="Link" value={`${base}/c/${activeCode.code}`} />
|
||||||
|
<p className="body-sm ad-muted">Kunden bekommen {discountLabel(terms)}{terms.discountCap ? ` (höchstens ${formatPrice(terms.discountCap)})` : ""}, Provision {formatRate(terms.commissionRate)}.</p>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<p className="body-sm">Kein aktiver Code.</p>
|
||||||
|
)}
|
||||||
|
{creator.coupons.length > 0 && (
|
||||||
|
<ul className="body-sm" style={{ paddingLeft: 18 }}>
|
||||||
|
{creator.coupons.map((c) => (
|
||||||
|
<li key={c.id} style={{ marginBottom: 6 }}>
|
||||||
|
<strong>{c.code}</strong> · {c.usedCount}× eingelöst · {c.active ? "aktiv" : "gesperrt"}{" "}
|
||||||
|
{canEdit && (
|
||||||
|
<ConfirmButton action={toggleCode} hidden={{ couponId: c.id }} confirm={c.active ? "Code sperren?" : "Code wieder freigeben?"} className="sm-btn sm-btn--ghost sm-btn--sm">
|
||||||
|
{c.active ? "Sperren" : "Freigeben"}
|
||||||
|
</ConfirmButton>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{canEdit && (
|
||||||
|
<AdminForm action={replaceCode} submitLabel="Neuen Code vergeben">
|
||||||
|
<>
|
||||||
|
<>
|
||||||
|
<input type="hidden" name="id" value={creator.id} />
|
||||||
|
<Field label="Neuer Code" name="code" hint="Der bisherige Code wird gesperrt, z. B. wenn er auf Gutscheinseiten aufgetaucht ist." style={{ textTransform: "uppercase" }} />
|
||||||
|
</>
|
||||||
|
</>
|
||||||
|
</AdminForm>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title="Stammdaten und Konditionen">
|
||||||
|
{outdated && <p className="body-sm" style={{ marginTop: 0 }}>Hat Version {creator.termsVersion} der Bedingungen bestätigt, aktuell ist Version {settings.creator.termsVersion}. Der Code bleibt aktiv, im Konto wird um neue Zustimmung gebeten.</p>}
|
||||||
|
{creator.termsAcceptedAt && <p className="body-sm ad-muted" style={{ marginTop: 0 }}>Bedingungen bestätigt am {dateFmt.format(creator.termsAcceptedAt)}.</p>}
|
||||||
|
<AdminForm action={updateCreator}>
|
||||||
|
<>
|
||||||
|
<fieldset disabled={!canEdit} style={{ border: 0, padding: 0, margin: 0 }}>
|
||||||
|
<input type="hidden" name="id" value={creator.id} />
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<SelectField label="Status" name="status" defaultValue={creator.status}>
|
||||||
|
{Object.entries(CREATOR_STATUS).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
|
||||||
|
</SelectField>
|
||||||
|
<SelectField label="Stufe" name="tierId" defaultValue={creator.tierId}>
|
||||||
|
{tiers.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||||
|
</SelectField>
|
||||||
|
</div>
|
||||||
|
<p className="body-sm ad-muted">Abweichende Werte nur für diesen Creator; leer = Wert der Stufe ({creator.tier.name}: {discountLabel(creator.tier)}, {formatRate(creator.tier.commissionRate)}).</p>
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<SelectField label="Rabatt-Art" name="discountType" defaultValue={creator.discountType ?? ""}>
|
||||||
|
<option value="">wie Stufe</option>
|
||||||
|
<option value="percent">Prozent</option>
|
||||||
|
<option value="fixed">Fester Betrag</option>
|
||||||
|
</SelectField>
|
||||||
|
<Field label="Rabatt" name="discountValue" inputMode="decimal" optional defaultValue={creator.discountValue == null ? "" : (creator.discountType ?? creator.tier.discountType) === "fixed" ? centsToInput(creator.discountValue) : String(creator.discountValue)} />
|
||||||
|
</div>
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="Höchstrabatt in €" name="discountCap" inputMode="decimal" optional defaultValue={creator.discountCap == null ? "" : centsToInput(creator.discountCap)} hint="0 = ohne Deckel" />
|
||||||
|
<Field label="Provision in %" name="commissionRate" inputMode="decimal" optional defaultValue={creator.commissionRate == null ? "" : String(creator.commissionRate / 100).replace(".", ",")} />
|
||||||
|
</div>
|
||||||
|
<TextareaField label="Kanäle" name="channels" rows={3} defaultValue={creator.channels} hint="Je Zeile ein Link" />
|
||||||
|
<Field label="Schwerpunkt" name="focus" optional defaultValue={creator.focus} placeholder="z. B. Pilates zu Hause, Tarot, Meditation" />
|
||||||
|
<SelectField label="Steuerstatus" name="taxStatus" defaultValue={creator.taxStatus}>
|
||||||
|
{Object.entries(TAX_STATUS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
|
||||||
|
</SelectField>
|
||||||
|
<Field label="USt-IdNr." name="vatId" optional defaultValue={creator.vatId} />
|
||||||
|
<Field label="Kontoinhaber" name="accountHolder" optional defaultValue={creator.accountHolder} />
|
||||||
|
<Field label="IBAN" name="iban" optional defaultValue={creator.iban} />
|
||||||
|
<TextareaField label="Interne Notiz" name="note" rows={3} defaultValue={creator.note} hint="Sieht nur das Team." />
|
||||||
|
</fieldset>
|
||||||
|
</>
|
||||||
|
</AdminForm>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
209
src/app/admin/(panel)/creator/actions.ts
Normal file
209
src/app/admin/(panel)/creator/actions.ts
Normal file
|
|
@ -0,0 +1,209 @@
|
||||||
|
"use server";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { assertPermission, audit, type CurrentUser } from "@/lib/auth";
|
||||||
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { parsePrice } from "@/lib/money";
|
||||||
|
import { CODE_PATTERN, TAX_STATUS, discountLabel, effectiveTerms, normalizeCode, parseRate, recordPayout } from "@/lib/creators";
|
||||||
|
import { getSettings, saveSettings } from "@/lib/settings";
|
||||||
|
import { getMailConfig, isMailReady } from "@/lib/mail/config";
|
||||||
|
import { sendLater, sendTemplate } from "@/lib/mail/send";
|
||||||
|
import { createResetLink } from "@/lib/password-reset";
|
||||||
|
import { appUrl } from "@/lib/social/config";
|
||||||
|
|
||||||
|
const authorName = (u: CurrentUser) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email;
|
||||||
|
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
||||||
|
|
||||||
|
async function codeProblem(code: string, ignoreCouponId?: string) {
|
||||||
|
if (!CODE_PATTERN.test(code)) return "Der Code braucht 3–32 Zeichen: Buchstaben, Ziffern, - oder _.";
|
||||||
|
const clash = await db.coupon.findFirst({ where: { code, NOT: ignoreCouponId ? { id: ignoreCouponId } : undefined } });
|
||||||
|
if (clash) return clash.creatorId ? "Diesen Code nutzt schon ein Creator (auch gesperrte Codes bleiben reserviert)." : "Diesen Code gibt es schon als Gutschein.";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Creator ----------
|
||||||
|
|
||||||
|
export async function createCreator(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const actor = await assertPermission("creators.edit");
|
||||||
|
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 code = normalizeCode(str(fd, "code"));
|
||||||
|
const problem = await codeProblem(code);
|
||||||
|
if (problem) return fail(problem, { code: "Bitte anderen Code wählen" });
|
||||||
|
const tier = await db.creatorTier.findUnique({ where: { id: str(fd, "tierId") } });
|
||||||
|
if (!tier) return fail("Bitte wähle eine Stufe.", { tierId: "Fehlt" });
|
||||||
|
let user = await db.user.findUnique({ where: { email: email.data }, include: { creator: true } });
|
||||||
|
if (user?.creator) return fail("Diese Person ist schon Creator.", { email: "Schon Creator" });
|
||||||
|
const isNew = !user;
|
||||||
|
if (!user) {
|
||||||
|
user = await db.user.create({ data: { email: email.data, passwordHash: "", firstName: str(fd, "firstName"), lastName: str(fd, "lastName") }, include: { creator: true } });
|
||||||
|
} else if (!user.firstName && str(fd, "firstName")) {
|
||||||
|
await db.user.update({ where: { id: user.id }, data: { firstName: str(fd, "firstName"), lastName: str(fd, "lastName") } });
|
||||||
|
}
|
||||||
|
const creator = await db.creator.create({
|
||||||
|
data: { userId: user.id, tierId: tier.id, status: "active", channels: str(fd, "channels"), coupons: { create: { code, type: "percent", value: 0 } } },
|
||||||
|
include: { tier: true },
|
||||||
|
});
|
||||||
|
await audit(actor, "Creator angelegt", `${user.email} · ${code}`);
|
||||||
|
if (fd.get("sendMail") === "on" && isMailReady(await getMailConfig())) {
|
||||||
|
const link = isNew || !user.passwordHash ? (await createResetLink(user.id, 24 * 7)).link : `${appUrl()}/konto/creator`;
|
||||||
|
const vars = { vorname: user.firstName || str(fd, "firstName"), code, vorteil: discountLabel(effectiveTerms(creator)), link };
|
||||||
|
const to = user.email;
|
||||||
|
sendLater(() => sendTemplate({ key: "creator_welcome", to, vars }));
|
||||||
|
}
|
||||||
|
revalidatePath("/admin/creator");
|
||||||
|
redirect(`/admin/creator/${creator.id}?neu=1`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateCreator(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const actor = await assertPermission("creators.edit");
|
||||||
|
const id = str(fd, "id");
|
||||||
|
const creator = await db.creator.findUnique({ where: { id }, include: { user: true } });
|
||||||
|
if (!creator) return fail("Creator nicht gefunden.");
|
||||||
|
const status = str(fd, "status");
|
||||||
|
if (!["applied", "active", "paused", "ended"].includes(status)) return fail("Ungültiger Status.");
|
||||||
|
const tier = await db.creatorTier.findUnique({ where: { id: str(fd, "tierId") } });
|
||||||
|
if (!tier) return fail("Bitte wähle eine Stufe.");
|
||||||
|
// Abweichende Werte: leer = Wert der Stufe
|
||||||
|
const discountType = str(fd, "discountType");
|
||||||
|
let discountValue: number | null = null;
|
||||||
|
if (str(fd, "discountValue")) {
|
||||||
|
const type = discountType || tier.discountType;
|
||||||
|
discountValue = type === "fixed" ? parsePrice(str(fd, "discountValue")) : Math.round(Number(str(fd, "discountValue").replace(",", ".")));
|
||||||
|
if (discountValue === null || !Number.isFinite(discountValue) || discountValue < 0 || (type === "percent" && discountValue > 100)) return fail("Bitte gib einen gültigen Rabatt ein.", { discountValue: "Ungültig" });
|
||||||
|
}
|
||||||
|
const discountCap = str(fd, "discountCap") ? parsePrice(str(fd, "discountCap")) : null;
|
||||||
|
const commissionRate = str(fd, "commissionRate") ? parseRate(str(fd, "commissionRate")) : null;
|
||||||
|
if (str(fd, "commissionRate") && commissionRate === null) return fail("Bitte gib einen gültigen Provisionssatz ein.", { commissionRate: "Ungültig" });
|
||||||
|
const taxStatus = str(fd, "taxStatus");
|
||||||
|
await db.creator.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status,
|
||||||
|
tierId: tier.id,
|
||||||
|
discountType: discountType === "percent" || discountType === "fixed" ? discountType : null,
|
||||||
|
discountValue,
|
||||||
|
discountCap,
|
||||||
|
commissionRate,
|
||||||
|
channels: str(fd, "channels"),
|
||||||
|
focus: str(fd, "focus"),
|
||||||
|
taxStatus: taxStatus in TAX_STATUS ? taxStatus : "",
|
||||||
|
vatId: str(fd, "vatId").toUpperCase(),
|
||||||
|
accountHolder: str(fd, "accountHolder"),
|
||||||
|
iban: str(fd, "iban").toUpperCase().replace(/\s+/g, ""),
|
||||||
|
note: String(fd.get("note") ?? ""),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await audit(actor, "Creator geändert", creator.user.email);
|
||||||
|
revalidatePath(`/admin/creator/${id}`);
|
||||||
|
return ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Neuen Code vergeben; der bisherige wird gesperrt (z. B. wenn er auf Gutscheinseiten aufgetaucht ist). */
|
||||||
|
export async function replaceCode(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const actor = await assertPermission("creators.edit");
|
||||||
|
const id = str(fd, "id");
|
||||||
|
const code = normalizeCode(str(fd, "code"));
|
||||||
|
const problem = await codeProblem(code);
|
||||||
|
if (problem) return fail(problem, { code: "Bitte anderen Code wählen" });
|
||||||
|
const creator = await db.creator.findUnique({ where: { id }, include: { user: true } });
|
||||||
|
if (!creator) return fail("Creator nicht gefunden.");
|
||||||
|
await db.$transaction([
|
||||||
|
db.coupon.updateMany({ where: { creatorId: id, active: true }, data: { active: false } }),
|
||||||
|
db.coupon.create({ data: { code, type: "percent", value: 0, creatorId: id } }),
|
||||||
|
]);
|
||||||
|
await audit(actor, "Creator-Code neu vergeben", `${creator.user.email} · ${code}`);
|
||||||
|
revalidatePath(`/admin/creator/${id}`);
|
||||||
|
return ok(`Neuer Code ${code} ist aktiv, der alte ist gesperrt.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function toggleCode(fd: FormData) {
|
||||||
|
const actor = await assertPermission("creators.edit");
|
||||||
|
const coupon = await db.coupon.findUnique({ where: { id: str(fd, "couponId") } });
|
||||||
|
if (!coupon?.creatorId) return;
|
||||||
|
await db.coupon.update({ where: { id: coupon.id }, data: { active: !coupon.active } });
|
||||||
|
await audit(actor, coupon.active ? "Creator-Code gesperrt" : "Creator-Code entsperrt", coupon.code);
|
||||||
|
revalidatePath(`/admin/creator/${coupon.creatorId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function payoutCreator(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const actor = await assertPermission("creators.payout");
|
||||||
|
const id = str(fd, "id");
|
||||||
|
const r = await recordPayout(id, authorName(actor), str(fd, "note"));
|
||||||
|
if (!r.ok) return fail(r.error);
|
||||||
|
await audit(actor, "Creator-Auszahlung verbucht", `${id} · ${(r.payout.amount / 100).toFixed(2)} €`);
|
||||||
|
revalidatePath(`/admin/creator/${id}`);
|
||||||
|
return ok("Auszahlung verbucht.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Stufen ----------
|
||||||
|
|
||||||
|
export async function saveTier(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const actor = await assertPermission("creators.edit");
|
||||||
|
const id = str(fd, "id");
|
||||||
|
const name = str(fd, "name");
|
||||||
|
if (!name) return fail("Bitte gib der Stufe einen Namen.", { name: "Fehlt" });
|
||||||
|
const discountType = fd.get("discountType") === "fixed" ? "fixed" : "percent";
|
||||||
|
const raw = str(fd, "discountValue") || "0";
|
||||||
|
const discountValue = discountType === "fixed" ? parsePrice(raw) : Math.round(Number(raw.replace(",", ".")));
|
||||||
|
if (discountValue === null || !Number.isFinite(discountValue) || discountValue < 0 || (discountType === "percent" && discountValue > 100)) return fail("Bitte gib einen gültigen Rabatt ein.", { discountValue: "Ungültig" });
|
||||||
|
const commissionRate = parseRate(str(fd, "commissionRate") || "0");
|
||||||
|
if (commissionRate === null) return fail("Bitte gib einen gültigen Provisionssatz ein.", { commissionRate: "Ungültig" });
|
||||||
|
const data = {
|
||||||
|
name,
|
||||||
|
sort: Math.round(Number(str(fd, "sort")) || 0),
|
||||||
|
discountType,
|
||||||
|
discountValue,
|
||||||
|
discountCap: parsePrice(str(fd, "discountCap")) ?? 0,
|
||||||
|
commissionRate,
|
||||||
|
minOrder: parsePrice(str(fd, "minOrder")) ?? 0,
|
||||||
|
upgradeFrom: parsePrice(str(fd, "upgradeFrom")) ?? 0,
|
||||||
|
extras: str(fd, "extras"),
|
||||||
|
excludedProductIds: fd.getAll("excludedProductIds").map(String),
|
||||||
|
excludedCategoryIds: fd.getAll("excludedCategoryIds").map(String),
|
||||||
|
};
|
||||||
|
if (id) await db.creatorTier.update({ where: { id }, data });
|
||||||
|
else await db.creatorTier.create({ data });
|
||||||
|
await audit(actor, id ? "Creator-Stufe geändert" : "Creator-Stufe angelegt", name);
|
||||||
|
revalidatePath("/admin/creator/stufen");
|
||||||
|
if (!id) redirect("/admin/creator/stufen");
|
||||||
|
return ok("Gespeichert. Gilt für alle neuen Bestellungen.");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteTier(fd: FormData) {
|
||||||
|
const actor = await assertPermission("creators.edit");
|
||||||
|
const id = str(fd, "id");
|
||||||
|
const used = await db.creator.count({ where: { tierId: id } });
|
||||||
|
if (used > 0) return;
|
||||||
|
const t = await db.creatorTier.delete({ where: { id } });
|
||||||
|
await audit(actor, "Creator-Stufe gelöscht", t.name);
|
||||||
|
revalidatePath("/admin/creator/stufen");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Einstellungen ----------
|
||||||
|
|
||||||
|
export async function saveCreatorSettings(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const actor = await assertPermission("creators.edit");
|
||||||
|
const current = (await getSettings()).creator;
|
||||||
|
const holdDays = Math.round(Number(str(fd, "holdDays")));
|
||||||
|
const linkDays = Math.round(Number(str(fd, "linkDays")));
|
||||||
|
if (!Number.isFinite(holdDays) || holdDays < 0 || holdDays > 365) return fail("Die Haltefrist muss zwischen 0 und 365 Tagen liegen.", { holdDays: "Ungültig" });
|
||||||
|
if (!Number.isFinite(linkDays) || linkDays < 1 || linkDays > 365) return fail("Die Merkdauer muss zwischen 1 und 365 Tagen liegen.", { linkDays: "Ungültig" });
|
||||||
|
const terms = String(fd.get("terms") ?? "").trim();
|
||||||
|
if (!terms) return fail("Die Programmbedingungen dürfen nicht leer sein.", { terms: "Fehlt" });
|
||||||
|
const newVersion = fd.get("newVersion") === "on" && terms !== current.terms;
|
||||||
|
const termsVersion = newVersion ? String((Number(current.termsVersion) || 1) + 1) : current.termsVersion;
|
||||||
|
await saveSettings("creator", {
|
||||||
|
holdDays,
|
||||||
|
linkDays,
|
||||||
|
defaultTierId: str(fd, "defaultTierId"),
|
||||||
|
excludedCategoryIds: fd.getAll("excludedCategoryIds").map(String),
|
||||||
|
terms,
|
||||||
|
termsVersion,
|
||||||
|
});
|
||||||
|
await audit(actor, "Creator-Programm eingestellt", newVersion ? `Neue Bedingungen, Version ${termsVersion}` : "");
|
||||||
|
revalidatePath("/admin/creator/einstellungen");
|
||||||
|
return ok(newVersion ? `Gespeichert. Bedingungen jetzt Version ${termsVersion}, Creator werden beim nächsten Besuch um Zustimmung gebeten.` : "Gespeichert.");
|
||||||
|
}
|
||||||
45
src/app/admin/(panel)/creator/einstellungen/page.tsx
Normal file
45
src/app/admin/(panel)/creator/einstellungen/page.tsx
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { requireAdmin } from "@/lib/auth";
|
||||||
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import { sortedForSelect } from "@/lib/categories";
|
||||||
|
import { AdminForm } from "@/components/admin/AdminForm";
|
||||||
|
import { Card, PageHead } from "@/components/admin/ui";
|
||||||
|
import { CreatorTabs } from "@/components/admin/CreatorTabs";
|
||||||
|
import { PickerField } from "@/components/admin/CreatorForms";
|
||||||
|
import { Field, SelectField, TextareaField } from "@/components/Field";
|
||||||
|
import { saveCreatorSettings } from "../actions";
|
||||||
|
|
||||||
|
export default async function CreatorSettingsPage() {
|
||||||
|
await requireAdmin("creators.edit");
|
||||||
|
const [settings, tiers, categories] = await Promise.all([getSettings(), db.creatorTier.findMany({ orderBy: { sort: "asc" } }), db.category.findMany({ orderBy: { sort: "asc" } })]);
|
||||||
|
const s = settings.creator;
|
||||||
|
const catOptions = sortedForSelect(categories).map((c) => ({ id: c.id, name: c.label, detail: categories.some((k) => k.parentId === c.id) ? "gilt auch für alle Unterkategorien" : "" }));
|
||||||
|
return (
|
||||||
|
<div className="ad-wrap ad-wrap--narrow">
|
||||||
|
<PageHead title="Creator-Programm einstellen" lead="Fristen, globale Ausschlüsse und die Programmbedingungen, denen Creator im Konto zustimmen." />
|
||||||
|
<CreatorTabs active="/admin/creator/einstellungen" />
|
||||||
|
<AdminForm action={saveCreatorSettings}>
|
||||||
|
<>
|
||||||
|
<>
|
||||||
|
<Card title="Fristen">
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="Haltefrist in Tagen" name="holdDays" type="number" min={0} defaultValue={s.holdDays} hint="Ab Versand (Kurse: ab Zahlung), danach ist die Provision freigegeben" />
|
||||||
|
<Field label="Code aus Link merken (Tage)" name="linkDays" type="number" min={1} defaultValue={s.linkDays} />
|
||||||
|
</div>
|
||||||
|
<SelectField label="Standard-Stufe für neue Creator" name="defaultTierId" defaultValue={s.defaultTierId}>
|
||||||
|
{tiers.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||||
|
</SelectField>
|
||||||
|
</Card>
|
||||||
|
<Card title="Global ausgenommene Kategorien" lead="Gilt für alle Stufen. Einzelne Produkte nimmst du am Produkt mit „Kein Creator-Rabatt“ aus.">
|
||||||
|
<PickerField name="excludedCategoryIds" options={catOptions} initial={s.excludedCategoryIds} />
|
||||||
|
</Card>
|
||||||
|
<Card title="Programmbedingungen" lead={`Aktuell Version ${s.termsVersion}. Entwurf, bitte einmal anwaltlich prüfen lassen.`}>
|
||||||
|
<TextareaField label="Text" name="terms" rows={16} defaultValue={s.terms} />
|
||||||
|
<label className="ad-switch"><span className="ad-switch__text"><strong>Als neue Version speichern</strong><small>Creator werden im Konto um erneute Zustimmung gebeten. Nur für inhaltliche Änderungen, nicht für Tippfehler.</small></span><input type="checkbox" role="switch" name="newVersion" /></label>
|
||||||
|
</Card>
|
||||||
|
</>
|
||||||
|
</>
|
||||||
|
</AdminForm>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
116
src/app/admin/(panel)/creator/page.tsx
Normal file
116
src/app/admin/(panel)/creator/page.tsx
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
import Link from "next/link";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { can, requireAdmin } from "@/lib/auth";
|
||||||
|
import { formatPrice } from "@/lib/money";
|
||||||
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import { CREATOR_STATUS, balance, creatorName, discountLabel, effectiveTerms, formatRate, refreshCommissions } from "@/lib/creators";
|
||||||
|
import { AdminForm } from "@/components/admin/AdminForm";
|
||||||
|
import { Card, Empty, PageHead, Pill } from "@/components/admin/ui";
|
||||||
|
import { CreatorTabs } from "@/components/admin/CreatorTabs";
|
||||||
|
import { Field, SelectField, TextareaField } from "@/components/Field";
|
||||||
|
import { createCreator } from "./actions";
|
||||||
|
|
||||||
|
const FILTERS = [
|
||||||
|
{ key: "aktiv", label: "Aktiv", status: ["active"] },
|
||||||
|
{ key: "beworben", label: "Beworben", status: ["applied"] },
|
||||||
|
{ key: "pausiert", label: "Pausiert & beendet", status: ["paused", "ended"] },
|
||||||
|
{ key: "alle", label: "Alle", status: ["applied", "active", "paused", "ended"] },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function CreatorsPage({ searchParams }: { searchParams: Promise<{ filter?: string }> }) {
|
||||||
|
const user = await requireAdmin("creators.view");
|
||||||
|
const sp = await searchParams;
|
||||||
|
const filter = FILTERS.find((f) => f.key === sp.filter) ?? FILTERS[0];
|
||||||
|
await refreshCommissions();
|
||||||
|
const [creators, tiers, settings, counts] = await Promise.all([
|
||||||
|
db.creator.findMany({
|
||||||
|
where: { status: { in: filter.status } },
|
||||||
|
include: { user: true, tier: true, coupons: { where: { active: true } }, commissions: { include: { order: { select: { subtotal: true, discount: true } } } } },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
}),
|
||||||
|
db.creatorTier.findMany({ orderBy: { sort: "asc" } }),
|
||||||
|
getSettings(),
|
||||||
|
Promise.all(FILTERS.map((f) => db.creator.count({ where: { status: { in: f.status } } }))),
|
||||||
|
]);
|
||||||
|
const canEdit = can(user, "creators.edit");
|
||||||
|
return (
|
||||||
|
<div className="ad-wrap">
|
||||||
|
<PageHead title="Creator-Programm" lead="Pilates-, Esoterik- und Wellness-Creator mit persönlichem Code. Kunden bekommen Rabatt, Creator Provision auf den Nettowarenwert." />
|
||||||
|
<CreatorTabs active="/admin/creator" />
|
||||||
|
<Card flush>
|
||||||
|
<div className="ad-toolbar">
|
||||||
|
<nav className="ad-tabs" aria-label="Filter">
|
||||||
|
{FILTERS.map((f, i) => (
|
||||||
|
<Link key={f.key} className={`ad-tab${f.key === filter.key ? " is-active" : ""}`} href={`/admin/creator?filter=${f.key}`}>
|
||||||
|
{f.label} <span>{counts[i]}</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
{creators.length === 0 ? (
|
||||||
|
<Empty title="Hier ist noch niemand" text={canEdit ? "Lege unten den ersten Creator an. Er bekommt eine E-Mail und bestätigt im Kundenkonto die Programmbedingungen, dann ist sein Code aktiv." : undefined} />
|
||||||
|
) : (
|
||||||
|
<div className="ad-table-wrap">
|
||||||
|
<table className="ad-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th>Creator</th><th>Code</th><th>Stufe</th><th>Status</th><th className="num">Bestellungen</th><th className="num">Umsatz</th><th className="num">Vorgemerkt</th><th className="num">Auszahlbar</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{creators.map((c) => {
|
||||||
|
const live = c.commissions.filter((k) => !["cancelled", "reversed", "offset"].includes(k.status));
|
||||||
|
const b = balance(c.commissions);
|
||||||
|
const terms = effectiveTerms(c);
|
||||||
|
return (
|
||||||
|
<tr key={c.id}>
|
||||||
|
<td><Link className="ad-rowlink" href={`/admin/creator/${c.id}`}>{creatorName(c)}</Link><div className="body-sm ad-muted">{c.user.email}</div></td>
|
||||||
|
<td>{c.coupons.map((k) => k.code).join(", ") || <span className="ad-muted">kein aktiver Code</span>}</td>
|
||||||
|
<td>{c.tier.name}<div className="body-sm ad-muted">{discountLabel(terms)} · {formatRate(terms.commissionRate)}</div></td>
|
||||||
|
<td>
|
||||||
|
<Pill tone={CREATOR_STATUS[c.status]?.tone ?? "neutral"}>{CREATOR_STATUS[c.status]?.label ?? c.status}</Pill>
|
||||||
|
{c.status === "active" && !c.termsAcceptedAt && <div className="body-sm ad-muted">Bedingungen noch nicht bestätigt</div>}
|
||||||
|
</td>
|
||||||
|
<td className="num">{live.length}</td>
|
||||||
|
<td className="num">{formatPrice(live.reduce((s, k) => s + k.order.subtotal - k.order.discount, 0))}</td>
|
||||||
|
<td className="num">{formatPrice(b.pending)}</td>
|
||||||
|
<td className="num">{formatPrice(b.payable)}</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{canEdit && (
|
||||||
|
<div style={{ marginTop: "var(--space-6)" }}>
|
||||||
|
<Card title="Creator anlegen" lead="Gibt es zur E-Mail noch kein Kundenkonto, wird eins angelegt; die Willkommens-Mail enthält dann einen Link zum Festlegen des Passworts.">
|
||||||
|
{tiers.length === 0 ? (
|
||||||
|
<p className="body-sm">Lege zuerst unter <Link href="/admin/creator/stufen">Stufen</Link> eine Stufe an.</p>
|
||||||
|
) : (
|
||||||
|
<AdminForm action={createCreator} submitLabel="Creator anlegen">
|
||||||
|
<>
|
||||||
|
<>
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="E-Mail" name="email" type="email" required />
|
||||||
|
<Field label="Code" name="code" required placeholder="z. B. LUNA5" hint="Wird auch der Link: sanamare.de/c/CODE" style={{ textTransform: "uppercase" }} />
|
||||||
|
</div>
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="Vorname" name="firstName" optional />
|
||||||
|
<Field label="Nachname" name="lastName" optional />
|
||||||
|
</div>
|
||||||
|
<SelectField label="Stufe" name="tierId" defaultValue={settings.creator.defaultTierId}>
|
||||||
|
{tiers.map((t) => <option key={t.id} value={t.id}>{t.name} · {discountLabel(t)} · {formatRate(t.commissionRate)} Provision</option>)}
|
||||||
|
</SelectField>
|
||||||
|
<TextareaField label="Kanäle" name="channels" optional rows={2} placeholder={"https://instagram.com/…\nhttps://youtube.com/@…"} hint="Je Zeile ein Link" />
|
||||||
|
<label className="ad-switch"><span className="ad-switch__text"><strong>Willkommens-Mail schicken</strong><small>Mit Code und Link in den Creator-Bereich. Vorlage unter E-Mails → „Willkommen im Creator-Programm“.</small></span><input type="checkbox" role="switch" name="sendMail" defaultChecked /></label>
|
||||||
|
</>
|
||||||
|
</>
|
||||||
|
</AdminForm>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
100
src/app/admin/(panel)/creator/stufen/page.tsx
Normal file
100
src/app/admin/(panel)/creator/stufen/page.tsx
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { can, requireAdmin } from "@/lib/auth";
|
||||||
|
import { centsToInput, formatPrice } from "@/lib/money";
|
||||||
|
import { sortedForSelect } from "@/lib/categories";
|
||||||
|
import { discountLabel, formatRate } from "@/lib/creators";
|
||||||
|
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
|
||||||
|
import { Card, PageHead, Pill } from "@/components/admin/ui";
|
||||||
|
import { CreatorTabs } from "@/components/admin/CreatorTabs";
|
||||||
|
import { PickerField } from "@/components/admin/CreatorForms";
|
||||||
|
import { Field, SelectField, TextareaField } from "@/components/Field";
|
||||||
|
import type { CreatorTier } from "@prisma/client";
|
||||||
|
import { deleteTier, saveTier } from "../actions";
|
||||||
|
|
||||||
|
type Option = { id: string; name: string; detail: string };
|
||||||
|
|
||||||
|
function TierFields({ t, categories, products, errors }: { t?: CreatorTier; categories: Option[]; products: Option[]; errors?: Record<string, string> }) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{t && <input type="hidden" name="id" value={t.id} />}
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="Name" name="name" defaultValue={t?.name} required error={errors?.name} />
|
||||||
|
<Field label="Reihenfolge" name="sort" type="number" defaultValue={t?.sort ?? 0} />
|
||||||
|
</div>
|
||||||
|
<h3 className="ad-subhead">Kundenvorteil</h3>
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<SelectField label="Rabatt-Art" name="discountType" defaultValue={t?.discountType ?? "percent"}>
|
||||||
|
<option value="percent">Prozent vom Warenwert</option>
|
||||||
|
<option value="fixed">Fester Betrag in €</option>
|
||||||
|
</SelectField>
|
||||||
|
<Field label="Rabatt" name="discountValue" inputMode="decimal" defaultValue={t ? (t.discountType === "fixed" ? centsToInput(t.discountValue) : String(t.discountValue)) : "5"} hint="z. B. 5 für 5 % oder 10,00 für 10 €; 0 = kein Rabatt" error={errors?.discountValue} />
|
||||||
|
</div>
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="Höchstrabatt je Bestellung in €" name="discountCap" inputMode="decimal" optional defaultValue={t?.discountCap ? centsToInput(t.discountCap) : ""} hint="Leer = ohne Deckel" />
|
||||||
|
<Field label="Mindestbestellwert in €" name="minOrder" inputMode="decimal" optional defaultValue={t?.minOrder ? centsToInput(t.minOrder) : ""} />
|
||||||
|
</div>
|
||||||
|
<h3 className="ad-subhead">Creator</h3>
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="Provision in %" name="commissionRate" inputMode="decimal" defaultValue={t ? String(t.commissionRate / 100).replace(".", ",") : "7"} hint="Vom Nettowarenwert nach Rabatt" error={errors?.commissionRate} />
|
||||||
|
<Field label="Aufstieg ab Umsatz im Quartal (€)" name="upgradeFrom" inputMode="decimal" optional defaultValue={t?.upgradeFrom ? centsToInput(t.upgradeFrom) : ""} hint="Phase 1: nur als Richtwert, Aufstieg von Hand" />
|
||||||
|
</div>
|
||||||
|
<TextareaField label="Extras" name="extras" optional rows={2} defaultValue={t?.extras} placeholder="z. B. Produkte zum Vorzugspreis, eigene Landingpage" />
|
||||||
|
<h3 className="ad-subhead">Ausgenommen (weder Rabatt noch Provision)</h3>
|
||||||
|
<p className="body-sm ad-muted">Gilt zusätzlich zu den globalen Ausschlüssen unter Einstellungen und dem Schalter „Kein Creator-Rabatt“ am Produkt. Artikel im Sale sind immer ausgenommen.</p>
|
||||||
|
<PickerField name="excludedCategoryIds" options={categories} initial={t?.excludedCategoryIds ?? []} />
|
||||||
|
<PickerField name="excludedProductIds" options={products} initial={t?.excludedProductIds ?? []} searchable />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function TiersPage() {
|
||||||
|
const user = await requireAdmin("creators.view");
|
||||||
|
const canEdit = can(user, "creators.edit");
|
||||||
|
const [tiers, categories, products] = await Promise.all([
|
||||||
|
db.creatorTier.findMany({ orderBy: { sort: "asc" }, include: { _count: { select: { creators: true } } } }),
|
||||||
|
db.category.findMany({ orderBy: { sort: "asc" } }),
|
||||||
|
db.product.findMany({ orderBy: { name: "asc" }, include: { category: { select: { name: true } } } }),
|
||||||
|
]);
|
||||||
|
const catOptions = sortedForSelect(categories).map((c) => ({ id: c.id, name: c.label, detail: categories.some((k) => k.parentId === c.id) ? "gilt auch für alle Unterkategorien" : "" }));
|
||||||
|
const prodOptions = products.map((p) => ({ id: p.id, name: p.name, detail: [formatPrice(p.price), p.kind === "course" ? "Video-Kurs" : p.category?.name].filter(Boolean).join(" · ") }));
|
||||||
|
return (
|
||||||
|
<div className="ad-wrap ad-wrap--narrow">
|
||||||
|
<PageHead title="Creator-Stufen" lead="Jeder Creator hängt an genau einer Stufe. Änderungen gelten für neue Bestellungen, bestehende behalten ihre Werte." />
|
||||||
|
<CreatorTabs active="/admin/creator/stufen" />
|
||||||
|
{tiers.map((t) => (
|
||||||
|
<details className="ad-card" key={t.id} style={{ marginBottom: "var(--space-3)" }}>
|
||||||
|
<summary className="ad-card__head" style={{ cursor: "pointer", listStyle: "none" }}>
|
||||||
|
<div>
|
||||||
|
<h2>{t.name}</h2>
|
||||||
|
<p>
|
||||||
|
{discountLabel(t)}{t.discountCap ? ` (max. ${formatPrice(t.discountCap)})` : ""} · {formatRate(t.commissionRate)} Provision
|
||||||
|
{t.minOrder ? ` · ab ${formatPrice(t.minOrder)}` : ""}
|
||||||
|
{t.excludedCategoryIds.length + t.excludedProductIds.length > 0 ? ` · ${t.excludedCategoryIds.length + t.excludedProductIds.length} Ausschlüsse` : ""}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Pill tone="neutral">{t._count.creators} Creator</Pill>
|
||||||
|
</summary>
|
||||||
|
<div className="ad-card__body">
|
||||||
|
{canEdit ? (
|
||||||
|
<AdminForm
|
||||||
|
action={saveTier}
|
||||||
|
extraActions={t._count.creators === 0 ? <ConfirmButton inForm action={deleteTier} confirm="Stufe löschen?">Löschen</ConfirmButton> : undefined}
|
||||||
|
>
|
||||||
|
<TierFields t={t} categories={catOptions} products={prodOptions} />
|
||||||
|
</AdminForm>
|
||||||
|
) : (
|
||||||
|
<p className="body-sm">{t.extras}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
))}
|
||||||
|
{canEdit && (
|
||||||
|
<Card title="Neue Stufe">
|
||||||
|
<AdminForm action={saveTier} submitLabel="Stufe anlegen">
|
||||||
|
<TierFields categories={catOptions} products={prodOptions} />
|
||||||
|
</AdminForm>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -11,7 +11,8 @@ export async function saveCoupon(_prev: ActionResult, fd: FormData): Promise<Act
|
||||||
const code = String(fd.get("code") ?? "").trim().toUpperCase().replace(/\s+/g, "");
|
const code = String(fd.get("code") ?? "").trim().toUpperCase().replace(/\s+/g, "");
|
||||||
if (!/^[A-Z0-9_-]{3,32}$/.test(code)) return fail("Der Code braucht 3–32 Zeichen: Buchstaben, Ziffern, - oder _.", { code: "Ungültiger Code." });
|
if (!/^[A-Z0-9_-]{3,32}$/.test(code)) return fail("Der Code braucht 3–32 Zeichen: Buchstaben, Ziffern, - oder _.", { code: "Ungültiger Code." });
|
||||||
const clash = await db.coupon.findFirst({ where: { code, NOT: id ? { id } : undefined } });
|
const clash = await db.coupon.findFirst({ where: { code, NOT: id ? { id } : undefined } });
|
||||||
if (clash) return fail("Diesen Code gibt es schon.", { code: "Schon vergeben." });
|
if (clash) return fail(clash.creatorId ? "Diesen Code nutzt schon ein Creator." : "Diesen Code gibt es schon.", { code: "Schon vergeben." });
|
||||||
|
if (id && (await db.coupon.findUnique({ where: { id } }))?.creatorId) return fail("Creator-Codes bearbeitest du unter Creator.");
|
||||||
const type = fd.get("type") === "fixed" ? "fixed" : "percent";
|
const type = fd.get("type") === "fixed" ? "fixed" : "percent";
|
||||||
const value = type === "percent" ? Math.round(Number(String(fd.get("value")).replace(",", "."))) : parsePrice(String(fd.get("value")));
|
const value = type === "percent" ? Math.round(Number(String(fd.get("value")).replace(",", "."))) : parsePrice(String(fd.get("value")));
|
||||||
if (!value || value <= 0 || (type === "percent" && value > 100)) return fail("Bitte gib einen gültigen Wert ein.", { value: "Ungültiger Wert." });
|
if (!value || value <= 0 || (type === "percent" && value > 100)) return fail("Bitte gib einen gültigen Wert ein.", { value: "Ungültiger Wert." });
|
||||||
|
|
@ -34,7 +35,9 @@ export async function saveCoupon(_prev: ActionResult, fd: FormData): Promise<Act
|
||||||
|
|
||||||
export async function deleteCoupon(fd: FormData) {
|
export async function deleteCoupon(fd: FormData) {
|
||||||
const user = await assertPermission("coupons.edit");
|
const user = await assertPermission("coupons.edit");
|
||||||
const c = await db.coupon.delete({ where: { id: String(fd.get("id")) } });
|
const id = String(fd.get("id"));
|
||||||
|
if ((await db.coupon.findUnique({ where: { id } }))?.creatorId) return;
|
||||||
|
const c = await db.coupon.delete({ where: { id } });
|
||||||
await audit(user, "Gutschein gelöscht", c.code);
|
await audit(user, "Gutschein gelöscht", c.code);
|
||||||
revalidatePath("/admin/gutscheine");
|
revalidatePath("/admin/gutscheine");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,10 @@ import { deleteCoupon, saveCoupon } from "./actions";
|
||||||
|
|
||||||
export default async function CouponsPage() {
|
export default async function CouponsPage() {
|
||||||
await requireAdmin("coupons.edit");
|
await requireAdmin("coupons.edit");
|
||||||
const coupons = await db.coupon.findMany({ orderBy: { createdAt: "desc" } });
|
const coupons = await db.coupon.findMany({ where: { creatorId: null }, orderBy: { createdAt: "desc" } });
|
||||||
return (
|
return (
|
||||||
<div className="ad-wrap ad-wrap--narrow">
|
<div className="ad-wrap ad-wrap--narrow">
|
||||||
<PageHead title="Gutscheine" lead="Rabattcodes, die Kunden im Warenkorb einlösen. Klick auf einen Gutschein, um ihn zu bearbeiten.">
|
<PageHead title="Gutscheine" lead="Rabattcodes, die Kunden im Warenkorb einlösen. Klick auf einen Gutschein, um ihn zu bearbeiten. Creator-Codes verwaltest du unter Creator.">
|
||||||
<NewCouponDialog />
|
<NewCouponDialog />
|
||||||
</PageHead>
|
</PageHead>
|
||||||
{coupons.length === 0 && (
|
{coupons.length === 0 && (
|
||||||
|
|
|
||||||
|
|
@ -66,6 +66,7 @@ export default async function EditProduct({ params, searchParams }: { params: Pr
|
||||||
trackStock: p.trackStock,
|
trackStock: p.trackStock,
|
||||||
active: p.active,
|
active: p.active,
|
||||||
featured: p.featured,
|
featured: p.featured,
|
||||||
|
noCreatorDiscount: p.noCreatorDiscount,
|
||||||
badge: p.badge,
|
badge: p.badge,
|
||||||
kind: p.kind,
|
kind: p.kind,
|
||||||
categoryId: p.categoryId ?? "",
|
categoryId: p.categoryId ?? "",
|
||||||
|
|
|
||||||
|
|
@ -59,6 +59,7 @@ export async function saveProduct(_prev: ActionResult, fd: FormData): Promise<Ac
|
||||||
trackStock: kind === "course" ? false : fd.get("trackStock") === "on",
|
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",
|
||||||
|
noCreatorDiscount: fd.get("noCreatorDiscount") === "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")) : "",
|
||||||
categoryId: String(fd.get("categoryId") ?? "") || null,
|
categoryId: String(fd.get("categoryId") ?? "") || null,
|
||||||
images,
|
images,
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ export default async function NewProduct({ searchParams }: { searchParams: Promi
|
||||||
<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: !course, active: true, featured: false, badge: "", kind: course ? "course" : "physical", categoryId: "", images: [], variants: [] }}
|
values={{ name: "", slug: "", subtitle: "", description: "", details: "", sku: "", weight: "", price: "", compareAtPrice: "", taxRate: 19, stock: 0, trackStock: !course, active: true, featured: false, noCreatorDiscount: false, badge: "", kind: course ? "course" : "physical", categoryId: "", images: [], variants: [] }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
29
src/app/c/[code]/[[...path]]/route.ts
Normal file
29
src/app/c/[code]/[[...path]]/route.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { countClick, isLive, loadCreatorCoupon } from "@/lib/creators";
|
||||||
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import { requestOrigin } from "@/lib/social/config";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creator-Link: sanamare.de/c/CODE oder /c/CODE/produkt/xyz.
|
||||||
|
* Trägt den Code in den Warenkorb ein (First-Party-Cookie, nur der Code), zählt den Klick ohne IP und leitet weiter.
|
||||||
|
*/
|
||||||
|
export async function GET(req: NextRequest, { params }: { params: Promise<{ code: string; path?: string[] }> }) {
|
||||||
|
const { code, path } = await params;
|
||||||
|
// Nur einfache Shop-Pfade als Ziel, keine fremden Adressen
|
||||||
|
const rest = (path ?? []).filter((p) => /^[a-zA-Z0-9._~-]+$/.test(p)).join("/");
|
||||||
|
const origin = await requestOrigin();
|
||||||
|
const res = NextResponse.redirect(new URL(`/${rest}`, origin), 302);
|
||||||
|
res.headers.set("Cache-Control", "no-store");
|
||||||
|
const coupon = await loadCreatorCoupon(decodeURIComponent(code));
|
||||||
|
if (!coupon?.active || !coupon.creator || !isLive(coupon.creator)) return res;
|
||||||
|
const { linkDays } = (await getSettings()).creator;
|
||||||
|
res.cookies.set("sm_coupon", coupon.code, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * Math.max(1, linkDays) });
|
||||||
|
// Vorschau-Abrufe (Link-Vorschau in Messengern) nicht mitzählen
|
||||||
|
const ua = req.headers.get("user-agent") ?? "";
|
||||||
|
if (!/bot|crawl|spider|preview|facebookexternalhit|whatsapp|telegram|slack|discord/i.test(ua) && req.headers.get("purpose") !== "prefetch") {
|
||||||
|
await countClick(coupon.creator.id);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
11
src/components/admin/CreatorForms.tsx
Normal file
11
src/components/admin/CreatorForms.tsx
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
"use client";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Picker } from "./SaleForm";
|
||||||
|
|
||||||
|
type Option = { id: string; name: string; detail: string };
|
||||||
|
|
||||||
|
/** Mehrfachauswahl (Produkte oder Kategorien) für normale Formulare. */
|
||||||
|
export function PickerField({ name, options, initial, searchable }: { name: string; options: Option[]; initial: string[]; searchable?: boolean }) {
|
||||||
|
const [selected, setSelected] = useState(initial);
|
||||||
|
return <Picker name={name} options={options} selected={selected} onChange={setSelected} searchable={searchable} />;
|
||||||
|
}
|
||||||
17
src/components/admin/CreatorTabs.tsx
Normal file
17
src/components/admin/CreatorTabs.tsx
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
const TABS = [
|
||||||
|
{ href: "/admin/creator", label: "Creator" },
|
||||||
|
{ href: "/admin/creator/stufen", label: "Stufen" },
|
||||||
|
{ href: "/admin/creator/einstellungen", label: "Einstellungen" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function CreatorTabs({ active }: { active: string }) {
|
||||||
|
return (
|
||||||
|
<nav className="ad-tabs" aria-label="Creator-Programm" style={{ marginBottom: "var(--space-5)" }}>
|
||||||
|
{TABS.map((t) => (
|
||||||
|
<Link key={t.href} className={`ad-tab${t.href === active ? " is-active" : ""}`} href={t.href}>{t.label}</Link>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -24,6 +24,7 @@ export type ProductFormValues = {
|
||||||
trackStock: boolean;
|
trackStock: boolean;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
featured: boolean;
|
featured: boolean;
|
||||||
|
noCreatorDiscount: boolean;
|
||||||
badge: string;
|
badge: string;
|
||||||
// "physical" oder "course"
|
// "physical" oder "course"
|
||||||
kind: string;
|
kind: string;
|
||||||
|
|
@ -88,6 +89,7 @@ export function ProductForm({ values, categories, canStock }: { values: ProductF
|
||||||
<div className="ad-card__body">
|
<div className="ad-card__body">
|
||||||
<label className="ad-switch"><span className="ad-switch__text"><strong>Im Shop sichtbar</strong><small>Ausgeschaltet sieht nur das Team das Produkt.</small></span><input type="checkbox" role="switch" name="active" defaultChecked={values.active} /></label>
|
<label className="ad-switch"><span className="ad-switch__text"><strong>Im Shop sichtbar</strong><small>Ausgeschaltet sieht nur das Team das Produkt.</small></span><input type="checkbox" role="switch" name="active" defaultChecked={values.active} /></label>
|
||||||
<label className="ad-switch"><span className="ad-switch__text"><strong>Auf der Startseite zeigen</strong><small>Im Abschnitt „Neu im Studio“.</small></span><input type="checkbox" role="switch" name="featured" defaultChecked={values.featured} /></label>
|
<label className="ad-switch"><span className="ad-switch__text"><strong>Auf der Startseite zeigen</strong><small>Im Abschnitt „Neu im Studio“.</small></span><input type="checkbox" role="switch" name="featured" defaultChecked={values.featured} /></label>
|
||||||
|
<label className="ad-switch"><span className="ad-switch__text"><strong>Kein Creator-Rabatt</strong><small>Creator-Codes geben auf dieses Produkt weder Rabatt noch Provision.</small></span><input type="checkbox" role="switch" name="noCreatorDiscount" defaultChecked={values.noCreatorDiscount} /></label>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<section className="ad-card">
|
<section className="ad-card">
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ export type SaleValues = {
|
||||||
active: boolean;
|
active: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function Picker({ name, options, selected, onChange, searchable }: { name: string; options: Option[]; selected: string[]; onChange: (ids: string[]) => void; searchable?: boolean }) {
|
export function Picker({ name, options, selected, onChange, searchable }: { name: string; options: Option[]; selected: string[]; onChange: (ids: string[]) => void; searchable?: boolean }) {
|
||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
const term = q.trim().toLowerCase();
|
const term = q.trim().toLowerCase();
|
||||||
const toggle = (id: string) => onChange(selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id]);
|
const toggle = (id: string) => onChange(selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id]);
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,7 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
|
||||||
{ href: "/admin/kunden", label: "Kunden", icon: "users", permission: "customers.view", badge: "newCustomers" },
|
{ href: "/admin/kunden", label: "Kunden", icon: "users", permission: "customers.view", badge: "newCustomers" },
|
||||||
{ href: "/admin/sales", label: "Sales", icon: "tag", permission: "coupons.edit" },
|
{ href: "/admin/sales", label: "Sales", icon: "tag", permission: "coupons.edit" },
|
||||||
{ href: "/admin/gutscheine", label: "Gutscheine", icon: "ticket", permission: "coupons.edit" },
|
{ href: "/admin/gutscheine", label: "Gutscheine", icon: "ticket", permission: "coupons.edit" },
|
||||||
|
{ href: "/admin/creator", label: "Creator", icon: "star", permission: "creators.view" },
|
||||||
{ href: "/admin/newsletter", label: "Newsletter", icon: "mail", permission: "newsletter.view", badge: "newSubscribers" },
|
{ href: "/admin/newsletter", label: "Newsletter", icon: "mail", permission: "newsletter.view", badge: "newSubscribers" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
|
||||||
17
src/components/shop/CreatorBar.tsx
Normal file
17
src/components/shop/CreatorBar.tsx
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { discountLabel, effectiveTerms, isLive, loadCreatorCoupon } from "@/lib/creators";
|
||||||
|
|
||||||
|
/** Hinweis oben im Shop, wenn ein Creator-Code (z. B. aus einem Link) im Warenkorb gemerkt ist. */
|
||||||
|
export async function CreatorBar() {
|
||||||
|
const code = (await cookies()).get("sm_coupon")?.value;
|
||||||
|
if (!code) return null;
|
||||||
|
const coupon = await loadCreatorCoupon(code);
|
||||||
|
if (!coupon?.active || !coupon.creator || !isLive(coupon.creator)) return null;
|
||||||
|
const terms = effectiveTerms(coupon.creator);
|
||||||
|
if (!terms.discountValue) return null;
|
||||||
|
return (
|
||||||
|
<div className="sm-creatorbar" role="status">
|
||||||
|
{discountLabel(terms)} von <strong>{coupon.code}</strong> aktiv · wird im Warenkorb automatisch abgezogen
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -12,12 +12,12 @@ const LINKS: { href: string; label: string; icon: IconName }[] = [
|
||||||
{ href: "/konto/profil", label: "Profil & Sicherheit", icon: "user" },
|
{ href: "/konto/profil", label: "Profil & Sicherheit", icon: "user" },
|
||||||
];
|
];
|
||||||
|
|
||||||
export function AccountNav() {
|
export function AccountNav({ creator }: { creator?: boolean }) {
|
||||||
const path = usePathname();
|
const path = usePathname();
|
||||||
const active = (href: string) => (href === "/konto" ? path === href : path.startsWith(href) || (href === "/konto/bestellungen" && path.startsWith("/konto/bestellung/")));
|
const active = (href: string) => (href === "/konto" ? path === href : path.startsWith(href) || (href === "/konto/bestellungen" && path.startsWith("/konto/bestellung/")));
|
||||||
return (
|
return (
|
||||||
<nav className="sm-account__nav" aria-label="Kontobereich">
|
<nav className="sm-account__nav" aria-label="Kontobereich">
|
||||||
{LINKS.map((l) => (
|
{(creator ? [...LINKS.slice(0, 4), { href: "/konto/creator", label: "Creator", icon: "star" as IconName }, ...LINKS.slice(4)] : LINKS).map((l) => (
|
||||||
<Link key={l.href} href={l.href} aria-current={active(l.href) ? "page" : undefined}>
|
<Link key={l.href} href={l.href} aria-current={active(l.href) ? "page" : undefined}>
|
||||||
<Icon name={l.icon} />
|
<Icon name={l.icon} />
|
||||||
<span>{l.label}</span>
|
<span>{l.label}</span>
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,10 @@ import type { CurrentUser } from "@/lib/auth";
|
||||||
import { logout } from "@/lib/auth-actions";
|
import { logout } from "@/lib/auth-actions";
|
||||||
import { Icon } from "../../Icon";
|
import { Icon } from "../../Icon";
|
||||||
import { AccountNav } from "./AccountNav";
|
import { AccountNav } from "./AccountNav";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
|
||||||
export function AccountShell({ user, title, lead, children }: { user: CurrentUser; title: string; lead?: React.ReactNode; children: React.ReactNode }) {
|
export async function AccountShell({ user, title, lead, children }: { user: CurrentUser; title: string; lead?: React.ReactNode; children: React.ReactNode }) {
|
||||||
|
const isCreator = (await db.creator.count({ where: { userId: user.id } })) > 0;
|
||||||
const name = [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email;
|
const name = [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email;
|
||||||
return (
|
return (
|
||||||
<main className="sm-container sm-page sm-account">
|
<main className="sm-container sm-page sm-account">
|
||||||
|
|
@ -16,7 +18,7 @@ export function AccountShell({ user, title, lead, children }: { user: CurrentUse
|
||||||
<span>{user.email}</span>
|
<span>{user.email}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<AccountNav />
|
<AccountNav creator={isCreator} />
|
||||||
<div className="sm-account__side-foot">
|
<div className="sm-account__side-foot">
|
||||||
{user.role && <Link href="/admin"><Icon name="settings" /> Zum Admin-Bereich</Link>}
|
{user.role && <Link href="/admin"><Icon name="settings" /> Zum Admin-Bereich</Link>}
|
||||||
<form action={logout}><button type="submit"><Icon name="logout" /> Abmelden</button></form>
|
<form action={logout}><button type="submit"><Icon name="logout" /> Abmelden</button></form>
|
||||||
|
|
|
||||||
77
src/components/shop/account/CreatorForms.tsx
Normal file
77
src/components/shop/account/CreatorForms.tsx
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
"use client";
|
||||||
|
import { useActionState, useState } from "react";
|
||||||
|
import { acceptCreatorTerms, saveCreatorPayout } from "@/app/(shop)/konto/creator/actions";
|
||||||
|
import { Field, SelectField } from "../../Field";
|
||||||
|
import { Alert } from "../Blocks";
|
||||||
|
|
||||||
|
export function CopyLine({ value }: { value: string }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const copy = async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(value);
|
||||||
|
} catch {
|
||||||
|
const t = document.createElement("textarea");
|
||||||
|
t.value = value;
|
||||||
|
document.body.appendChild(t);
|
||||||
|
t.select();
|
||||||
|
document.execCommand("copy");
|
||||||
|
t.remove();
|
||||||
|
}
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<div className="sm-creator__copy">
|
||||||
|
<code>{value}</code>
|
||||||
|
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" onClick={copy}>{copied ? "Kopiert" : "Kopieren"}</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TermsForm({ terms, version, renew }: { terms: string; version: string; renew: boolean }) {
|
||||||
|
const [state, action, pending] = useActionState(acceptCreatorTerms, null);
|
||||||
|
const e = state?.errors ?? {};
|
||||||
|
if (state?.ok) return <Alert kind="success" title={state.ok} />;
|
||||||
|
return (
|
||||||
|
<form action={action} noValidate>
|
||||||
|
{state?.error && <div className="sm-account__alert"><Alert kind="danger" title={state.error} /></div>}
|
||||||
|
<div className="sm-creator__terms">{terms}</div>
|
||||||
|
<label className="sm-check">
|
||||||
|
<input type="checkbox" name="accept" />
|
||||||
|
<span className="sm-check__text">Ich akzeptiere die Programmbedingungen (Version {version}) und kennzeichne jede Werbung mit meinem Code deutlich als „Werbung“ oder „Anzeige“.</span>
|
||||||
|
</label>
|
||||||
|
{e.accept && <p className="sm-field__error">{e.accept}</p>}
|
||||||
|
<label className="sm-check" style={{ marginTop: "var(--space-2)" }}>
|
||||||
|
<input type="checkbox" name="adult" />
|
||||||
|
<span className="sm-check__text">Ich bin mindestens 18 Jahre alt oder meine Eltern sind mit der Teilnahme einverstanden.</span>
|
||||||
|
</label>
|
||||||
|
{e.adult && <p className="sm-field__error">{e.adult}</p>}
|
||||||
|
<div className="sm-account__actions">
|
||||||
|
<button className="sm-btn sm-btn--primary" type="submit" disabled={pending}>{renew ? "Neuen Bedingungen zustimmen" : "Zustimmen und Code aktivieren"}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PayoutForm({ values: initial, taxOptions }: { values: { taxStatus: string; vatId: string; iban: string; accountHolder: string }; taxOptions: [string, string][] }) {
|
||||||
|
const [state, action, pending] = useActionState(saveCreatorPayout, null);
|
||||||
|
const e = state?.errors ?? {};
|
||||||
|
const v = { ...initial, ...state?.values };
|
||||||
|
return (
|
||||||
|
<form action={action} noValidate>
|
||||||
|
{state?.ok && <div className="sm-account__alert"><Alert kind="success" title={state.ok} /></div>}
|
||||||
|
{state?.error && <div className="sm-account__alert"><Alert kind="danger" title={state.error} /></div>}
|
||||||
|
<SelectField label="Steuerstatus" name="taxStatus" defaultValue={v.taxStatus} error={e.taxStatus}>
|
||||||
|
{taxOptions.map(([k, label]) => <option key={k} value={k}>{label}</option>)}
|
||||||
|
</SelectField>
|
||||||
|
<Field label="USt-IdNr." optional name="vatId" defaultValue={v.vatId} error={e.vatId} hint="Pflicht bei EU-Ausland (Reverse Charge)" />
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="Kontoinhaber" name="accountHolder" defaultValue={v.accountHolder} autoComplete="name" />
|
||||||
|
<Field label="IBAN" name="iban" defaultValue={v.iban} error={e.iban} />
|
||||||
|
</div>
|
||||||
|
<div className="sm-account__actions">
|
||||||
|
<button className="sm-btn sm-btn--secondary" type="submit" disabled={pending}>{pending ? "Speichert …" : "Speichern"}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -53,6 +53,9 @@ export type CartLine = {
|
||||||
total: number;
|
total: number;
|
||||||
// Video-Kurs: kein Versand, kein Bestand, höchstens einmal im Warenkorb
|
// Video-Kurs: kein Versand, kein Bestand, höchstens einmal im Warenkorb
|
||||||
digital: boolean;
|
digital: boolean;
|
||||||
|
// Für Creator-Codes (Ausschlüsse)
|
||||||
|
categoryId: string | null;
|
||||||
|
noCreatorDiscount: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Nur Kurse im Warenkorb: kein Versand, keine Lieferadresse nötig. */
|
/** Nur Kurse im Warenkorb: kein Versand, keine Lieferadresse nötig. */
|
||||||
|
|
@ -99,6 +102,8 @@ export async function getCart(): Promise<CartLine[]> {
|
||||||
taxRate: product.taxRate,
|
taxRate: product.taxRate,
|
||||||
total: unitPrice * quantity,
|
total: unitPrice * quantity,
|
||||||
digital,
|
digital,
|
||||||
|
categoryId: product.categoryId,
|
||||||
|
noCreatorDiscount: product.noCreatorDiscount,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return lines;
|
return lines;
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import { mailOrderPlaced, sendLater } from "./mail/send";
|
||||||
import { subscribe } from "./newsletter";
|
import { subscribe } from "./newsletter";
|
||||||
import { grantCourseAccess } from "./courses";
|
import { grantCourseAccess } from "./courses";
|
||||||
import { bookAppointmentForOrder } from "./consulting";
|
import { bookAppointmentForOrder } from "./consulting";
|
||||||
|
import { commissionAmount, syncCommission } from "./creators";
|
||||||
|
|
||||||
export const CHECKOUT_COOKIE = "sm_checkout";
|
export const CHECKOUT_COOKIE = "sm_checkout";
|
||||||
|
|
||||||
|
|
@ -145,11 +146,14 @@ export async function createOrder(opts: {
|
||||||
paymentFee: totals.paymentFee,
|
paymentFee: totals.paymentFee,
|
||||||
discount: totals.discount,
|
discount: totals.discount,
|
||||||
couponCode: totals.coupon?.code ?? "",
|
couponCode: totals.coupon?.code ?? "",
|
||||||
|
...(totals.creator
|
||||||
|
? { creatorId: totals.creator.id, creatorTier: totals.creator.tierName, commissionRate: totals.creator.commissionRate, commissionBase: totals.creator.commissionBase }
|
||||||
|
: {}),
|
||||||
taxAmount: totals.taxAmount,
|
taxAmount: totals.taxAmount,
|
||||||
total: totals.total,
|
total: totals.total,
|
||||||
note: opts.note,
|
note: opts.note,
|
||||||
items: {
|
items: {
|
||||||
create: lines.map((l) => ({
|
create: lines.map((l, i) => ({
|
||||||
productId: l.productId,
|
productId: l.productId,
|
||||||
variantId: l.variantId,
|
variantId: l.variantId,
|
||||||
name: l.name,
|
name: l.name,
|
||||||
|
|
@ -159,11 +163,16 @@ export async function createOrder(opts: {
|
||||||
quantity: l.quantity,
|
quantity: l.quantity,
|
||||||
taxRate: l.taxRate,
|
taxRate: l.taxRate,
|
||||||
total: l.total,
|
total: l.total,
|
||||||
|
discount: totals.itemDiscounts[i] ?? 0,
|
||||||
})),
|
})),
|
||||||
},
|
},
|
||||||
events: { create: { message: `Bestellung aufgegeben, Zahlungsart: ${payment.name}` } },
|
events: { create: { message: `Bestellung aufgegeben, Zahlungsart: ${payment.name}` } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
if (totals.creator) {
|
||||||
|
const c = totals.creator;
|
||||||
|
await tx.commission.create({ data: { creatorId: c.id, orderId: order.id, base: c.commissionBase, rate: c.commissionRate, amount: commissionAmount(c.commissionBase, c.commissionRate) } });
|
||||||
|
}
|
||||||
return order;
|
return order;
|
||||||
}).then(async (order) => {
|
}).then(async (order) => {
|
||||||
if (state.newsletter) await subscribe(order.email);
|
if (state.newsletter) await subscribe(order.email);
|
||||||
|
|
@ -187,5 +196,6 @@ export async function markOrderPaid(orderId: string, reference: string, source:
|
||||||
sendLater(() => mailOrderPlaced(orderId, "paid"));
|
sendLater(() => mailOrderPlaced(orderId, "paid"));
|
||||||
await grantCourseAccess(orderId);
|
await grantCourseAccess(orderId);
|
||||||
await bookAppointmentForOrder(orderId);
|
await bookAppointmentForOrder(orderId);
|
||||||
|
await syncCommission(orderId);
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
226
src/lib/creators.ts
Normal file
226
src/lib/creators.ts
Normal file
|
|
@ -0,0 +1,226 @@
|
||||||
|
import "server-only";
|
||||||
|
import type { Coupon, Creator, CreatorTier, Prisma } from "@prisma/client";
|
||||||
|
import { db } from "./db";
|
||||||
|
import { getSettings } from "./settings";
|
||||||
|
import { formatPrice } from "./money";
|
||||||
|
import { appUrl, siteOrigins } from "./social/config";
|
||||||
|
|
||||||
|
// ---------- Anzeige ----------
|
||||||
|
|
||||||
|
export const CREATOR_STATUS: Record<string, { label: string; tone: "neutral" | "gold" | "success" | "danger" }> = {
|
||||||
|
applied: { label: "Beworben", tone: "gold" },
|
||||||
|
active: { label: "Aktiv", tone: "success" },
|
||||||
|
paused: { label: "Pausiert", tone: "neutral" },
|
||||||
|
ended: { label: "Beendet", tone: "danger" },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const COMMISSION_STATUS: Record<string, { label: string; tone: "neutral" | "gold" | "success" | "danger"; hint: string }> = {
|
||||||
|
pending: { label: "Vorgemerkt", tone: "gold", hint: "Wartet auf Zahlung, Versand und Ablauf der Haltefrist" },
|
||||||
|
approved: { label: "Freigegeben", tone: "success", hint: "Wird mit der nächsten Auszahlung überwiesen" },
|
||||||
|
paid: { label: "Ausgezahlt", tone: "neutral", hint: "" },
|
||||||
|
cancelled: { label: "Storniert", tone: "danger", hint: "Bestellung storniert oder erstattet" },
|
||||||
|
reversed: { label: "Wird verrechnet", tone: "danger", hint: "Nach der Auszahlung storniert, wird mit der nächsten Auszahlung abgezogen" },
|
||||||
|
offset: { label: "Verrechnet", tone: "neutral", hint: "" },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TAX_STATUS: Record<string, string> = {
|
||||||
|
"": "Noch nicht angegeben",
|
||||||
|
small: "Kleinunternehmer (ohne USt)",
|
||||||
|
regular: "Regelbesteuert (zzgl. 19 % USt)",
|
||||||
|
eu: "EU-Ausland (Reverse Charge, USt-IdNr. nötig)",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Provisionssatz in Hundertstel-Prozent als Text, z. B. 750 → „7,5 %“ */
|
||||||
|
export function formatRate(rate: number) {
|
||||||
|
return `${(rate / 100).toLocaleString("de-DE", { maximumFractionDigits: 2 })} %`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** „7“, „7,5“ oder „7.5“ → 700 / 750; leer oder ungültig → null */
|
||||||
|
export function parseRate(raw: string): number | null {
|
||||||
|
const v = Number(raw.trim().replace("%", "").replace(",", "."));
|
||||||
|
if (!raw.trim() || !Number.isFinite(v) || v < 0 || v > 100) return null;
|
||||||
|
return Math.round(v * 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeCode(raw: string) {
|
||||||
|
return raw.trim().toUpperCase().replace(/\s+/g, "");
|
||||||
|
}
|
||||||
|
export const CODE_PATTERN = /^[A-Z0-9_-]{3,32}$/;
|
||||||
|
|
||||||
|
// ---------- Konditionen ----------
|
||||||
|
|
||||||
|
export type CreatorTerms = {
|
||||||
|
tierName: string;
|
||||||
|
discountType: "percent" | "fixed";
|
||||||
|
discountValue: number;
|
||||||
|
discountCap: number;
|
||||||
|
commissionRate: number;
|
||||||
|
minOrder: number;
|
||||||
|
excludedProductIds: string[];
|
||||||
|
excludedCategoryIds: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Werte der Stufe, überschrieben durch die eigenen Werte des Creators. */
|
||||||
|
export function effectiveTerms(creator: Creator & { tier: CreatorTier }): CreatorTerms {
|
||||||
|
const t = creator.tier;
|
||||||
|
return {
|
||||||
|
tierName: t.name,
|
||||||
|
discountType: (creator.discountType ?? t.discountType) === "fixed" ? "fixed" : "percent",
|
||||||
|
discountValue: creator.discountValue ?? t.discountValue,
|
||||||
|
discountCap: creator.discountCap ?? t.discountCap,
|
||||||
|
commissionRate: creator.commissionRate ?? t.commissionRate,
|
||||||
|
minOrder: t.minOrder,
|
||||||
|
excludedProductIds: t.excludedProductIds,
|
||||||
|
excludedCategoryIds: t.excludedCategoryIds,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function discountLabel(terms: { discountType: string; discountValue: number }) {
|
||||||
|
if (!terms.discountValue) return "ohne Rabatt";
|
||||||
|
return terms.discountType === "fixed" ? `${formatPrice(terms.discountValue)} Rabatt` : `${terms.discountValue} % Rabatt`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Code wirkt nur, wenn der Creator aktiv ist und den Bedingungen zugestimmt hat. */
|
||||||
|
export function isLive(creator: Pick<Creator, "status" | "termsAcceptedAt">) {
|
||||||
|
return creator.status === "active" && Boolean(creator.termsAcceptedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CreatorCoupon = Coupon & { creator: (Creator & { tier: CreatorTier; user: { id: string; email: string } }) | null };
|
||||||
|
|
||||||
|
export async function loadCreatorCoupon(code: string): Promise<CreatorCoupon | null> {
|
||||||
|
return db.coupon.findUnique({ where: { code: normalizeCode(code) }, include: { creator: { include: { tier: true, user: { select: { id: true, email: true } } } } } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ausgeschlossene Kategorien (global + Stufe), Oberkategorien schließen ihre Unterkategorien ein. */
|
||||||
|
export async function excludedCategorySet(tierCategoryIds: string[]) {
|
||||||
|
const settings = await getSettings();
|
||||||
|
const ids = new Set([...settings.creator.excludedCategoryIds, ...tierCategoryIds]);
|
||||||
|
if (ids.size === 0) return ids;
|
||||||
|
const subs = await db.category.findMany({ where: { parentId: { in: [...ids] } }, select: { id: true } });
|
||||||
|
for (const s of subs) ids.add(s.id);
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
type LineLike = { productId: string; categoryId: string | null; noCreatorDiscount: boolean; originalUnitPrice: number | null };
|
||||||
|
|
||||||
|
/** Für welche Positionen gilt der Code? Nicht für ausgeschlossene Produkte/Kategorien und nicht für Artikel im Sale. */
|
||||||
|
export async function eligibleLines(terms: CreatorTerms, lines: LineLike[]) {
|
||||||
|
const cats = await excludedCategorySet(terms.excludedCategoryIds);
|
||||||
|
return lines.map(
|
||||||
|
(l) => !l.noCreatorDiscount && l.originalUnitPrice === null && !terms.excludedProductIds.includes(l.productId) && !(l.categoryId && cats.has(l.categoryId)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const commissionAmount = (base: number, rate: number) => Math.round((base * rate) / 10000);
|
||||||
|
|
||||||
|
// ---------- Provisionen ----------
|
||||||
|
|
||||||
|
const DAY = 24 * 3600_000;
|
||||||
|
|
||||||
|
/** Bringt die Provision einer Bestellung auf den Stand der Bestellung (Freigabe, Storno). */
|
||||||
|
export async function syncCommission(orderId: string) {
|
||||||
|
const c = await db.commission.findUnique({
|
||||||
|
where: { orderId },
|
||||||
|
include: { order: { select: { status: true, paymentStatus: true, items: { select: { product: { select: { kind: true } } } } } } },
|
||||||
|
});
|
||||||
|
if (!c) return;
|
||||||
|
const o = c.order;
|
||||||
|
if (o.status === "CANCELLED" || o.status === "REFUNDED") {
|
||||||
|
if (c.status === "pending" || c.status === "approved") await db.commission.update({ where: { id: c.id }, data: { status: "cancelled" } });
|
||||||
|
else if (c.status === "paid") await db.commission.update({ where: { id: c.id }, data: { status: "reversed" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (c.status !== "pending") return;
|
||||||
|
const digital = o.items.length > 0 && o.items.every((i) => i.product?.kind === "course");
|
||||||
|
const ready = o.paymentStatus === "PAID" && (o.status === "SHIPPED" || o.status === "COMPLETED" || digital);
|
||||||
|
const { holdDays } = (await getSettings()).creator;
|
||||||
|
let releaseAt = c.releaseAt;
|
||||||
|
if (ready && !releaseAt) releaseAt = new Date(Date.now() + Math.max(0, holdDays) * DAY);
|
||||||
|
if (!ready) releaseAt = null;
|
||||||
|
const status = releaseAt && releaseAt <= new Date() ? "approved" : "pending";
|
||||||
|
if (status !== c.status || releaseAt?.getTime() !== c.releaseAt?.getTime()) {
|
||||||
|
await db.commission.update({ where: { id: c.id }, data: { status, releaseAt } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Offene Provisionen prüfen (beim Öffnen der Creator-Seiten). */
|
||||||
|
export async function refreshCommissions(creatorId?: string) {
|
||||||
|
const list = await db.commission.findMany({
|
||||||
|
where: {
|
||||||
|
...(creatorId ? { creatorId } : {}),
|
||||||
|
OR: [{ status: "pending" }, { status: { in: ["approved", "paid"] }, order: { status: { in: ["CANCELLED", "REFUNDED"] } } }],
|
||||||
|
},
|
||||||
|
select: { orderId: true },
|
||||||
|
});
|
||||||
|
for (const c of list) await syncCommission(c.orderId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Freigegebene Provisionen minus nach Auszahlung stornierte. */
|
||||||
|
export function balance(commissions: { status: string; amount: number; payoutId: string | null }[]) {
|
||||||
|
const approved = commissions.filter((c) => c.status === "approved" && !c.payoutId).reduce((s, c) => s + c.amount, 0);
|
||||||
|
const reversed = commissions.filter((c) => c.status === "reversed").reduce((s, c) => s + c.amount, 0);
|
||||||
|
const pending = commissions.filter((c) => c.status === "pending").reduce((s, c) => s + c.amount, 0);
|
||||||
|
return { approved, reversed, pending, payable: approved - reversed };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function recordPayout(creatorId: string, author: string, note: string) {
|
||||||
|
return db.$transaction(async (tx: Prisma.TransactionClient) => {
|
||||||
|
const creator = await tx.creator.findUnique({ where: { id: creatorId } });
|
||||||
|
if (!creator) return { ok: false as const, error: "Creator nicht gefunden." };
|
||||||
|
const open = await tx.commission.findMany({ where: { creatorId, OR: [{ status: "approved", payoutId: null }, { status: "reversed" }] } });
|
||||||
|
const b = balance(open);
|
||||||
|
if (b.payable <= 0) return { ok: false as const, error: b.reversed > 0 && b.approved > 0 ? "Die Abzüge sind höher als die freigegebenen Provisionen." : "Es gibt gerade nichts auszuzahlen." };
|
||||||
|
const payout = await tx.creatorPayout.create({ data: { creatorId, amount: b.payable, method: creator.payoutMethod, note, author } });
|
||||||
|
await tx.commission.updateMany({ where: { id: { in: open.filter((c) => c.status === "approved").map((c) => c.id) } }, data: { status: "paid", payoutId: payout.id } });
|
||||||
|
await tx.commission.updateMany({ where: { id: { in: open.filter((c) => c.status === "reversed").map((c) => c.id) } }, data: { status: "offset", offsetPayoutId: payout.id } });
|
||||||
|
return { ok: true as const, payout };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Klicks und Statistik ----------
|
||||||
|
|
||||||
|
export const berlinDay = (d = new Date()) => new Intl.DateTimeFormat("en-CA", { timeZone: "Europe/Berlin", year: "numeric", month: "2-digit", day: "2-digit" }).format(d);
|
||||||
|
|
||||||
|
export async function countClick(creatorId: string) {
|
||||||
|
const day = berlinDay();
|
||||||
|
await db.creatorClick.upsert({ where: { creatorId_day: { creatorId, day } }, create: { creatorId, day, count: 1 }, update: { count: { increment: 1 } } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MonthStats = { month: string; clicks: number; orders: number; revenue: number; commission: number; cancelled: number };
|
||||||
|
|
||||||
|
/** Zahlen je Monat (neueste zuerst). Umsatz = Warenwert nach Rabatt, ohne Versand. */
|
||||||
|
export async function monthlyStats(creatorId: string, months = 6): Promise<MonthStats[]> {
|
||||||
|
const now = new Date();
|
||||||
|
const keys: string[] = [];
|
||||||
|
for (let i = 0; i < months; i++) keys.push(berlinDay(new Date(now.getFullYear(), now.getMonth() - i, 15)).slice(0, 7));
|
||||||
|
const from = new Date(now.getFullYear(), now.getMonth() - months + 1, 1);
|
||||||
|
const [clicks, commissions] = await Promise.all([
|
||||||
|
db.creatorClick.findMany({ where: { creatorId, day: { gte: `${keys[keys.length - 1]}-01` } } }),
|
||||||
|
db.commission.findMany({ where: { creatorId, createdAt: { gte: from } }, include: { order: { select: { subtotal: true, discount: true } } } }),
|
||||||
|
]);
|
||||||
|
return keys.map((month) => {
|
||||||
|
const cs = commissions.filter((c) => berlinDay(c.createdAt).startsWith(month));
|
||||||
|
// Stornierte Bestellungen zählen nicht, auch nicht nach einer Auszahlung
|
||||||
|
const live = cs.filter((c) => !["cancelled", "reversed", "offset"].includes(c.status));
|
||||||
|
return {
|
||||||
|
month,
|
||||||
|
clicks: clicks.filter((c) => c.day.startsWith(month)).reduce((s, c) => s + c.count, 0),
|
||||||
|
orders: live.length,
|
||||||
|
revenue: live.reduce((s, c) => s + c.order.subtotal - c.order.discount, 0),
|
||||||
|
commission: live.reduce((s, c) => s + c.amount, 0),
|
||||||
|
cancelled: cs.length - live.length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export const monthLabel = (key: string) => new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" }).format(new Date(`${key}-15T12:00:00`));
|
||||||
|
|
||||||
|
export function creatorName(c: { user: { firstName: string; lastName: string; email: string } }) {
|
||||||
|
return [c.user.firstName, c.user.lastName].filter(Boolean).join(" ") || c.user.email;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adresse für Creator-Links: die Hauptdomain (z. B. sanamare.de) statt einer Test-Subdomain, wenn vorhanden. */
|
||||||
|
export function creatorLinkBase() {
|
||||||
|
const origins = siteOrigins();
|
||||||
|
return origins.find((o) => new URL(o).hostname.split(".").length === 2) ?? origins[0] ?? appUrl();
|
||||||
|
}
|
||||||
|
|
@ -60,8 +60,10 @@ function addressLines(a: AddressData) {
|
||||||
/** Steuern je Satz: Rabatt anteilig auf die Positionen, Versand und Gebühr zum überwiegenden Satz (wie im Checkout). */
|
/** Steuern je Satz: Rabatt anteilig auf die Positionen, Versand und Gebühr zum überwiegenden Satz (wie im Checkout). */
|
||||||
function taxBreakdown(order: Order & { items: OrderItem[] }): InvoiceTax[] {
|
function taxBreakdown(order: Order & { items: OrderItem[] }): InvoiceTax[] {
|
||||||
const ratio = order.subtotal > 0 ? (order.subtotal - order.discount) / order.subtotal : 0;
|
const ratio = order.subtotal > 0 ? (order.subtotal - order.discount) / order.subtotal : 0;
|
||||||
|
// Neuere Bestellungen kennen den Rabattanteil je Position (Creator-Codes gelten nicht für alle Artikel)
|
||||||
|
const perItem = order.discount > 0 && order.items.reduce((s, i) => s + i.discount, 0) === order.discount;
|
||||||
const byRate = new Map<number, number>();
|
const byRate = new Map<number, number>();
|
||||||
for (const i of order.items) byRate.set(i.taxRate, (byRate.get(i.taxRate) ?? 0) + i.total * ratio);
|
for (const i of order.items) byRate.set(i.taxRate, (byRate.get(i.taxRate) ?? 0) + (perItem ? i.total - i.discount : i.total * ratio));
|
||||||
const mainRate = [...byRate.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 19;
|
const mainRate = [...byRate.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 19;
|
||||||
byRate.set(mainRate, (byRate.get(mainRate) ?? 0) + order.shippingCost + order.paymentFee);
|
byRate.set(mainRate, (byRate.get(mainRate) ?? 0) + order.shippingCost + order.paymentFee);
|
||||||
const rows = [...byRate.entries()].sort((a, b) => b[0] - a[0]).map(([rate, g]) => {
|
const rows = [...byRate.entries()].sort((a, b) => b[0] - a[0]).map(([rate, g]) => {
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import { formatPrice } from "./money";
|
||||||
* zeigt der Admin bei den betroffenen Seiten „Neuere Vorlage verfügbar“.
|
* zeigt der Admin bei den betroffenen Seiten „Neuere Vorlage verfügbar“.
|
||||||
* Es sind Entwürfe: vor der Veröffentlichung rechtlich prüfen lassen.
|
* Es sind Entwürfe: vor der Veröffentlichung rechtlich prüfen lassen.
|
||||||
*/
|
*/
|
||||||
export const LEGAL_TEMPLATES_VERSION = "2026-10-19";
|
export const LEGAL_TEMPLATES_VERSION = "2026-11-11";
|
||||||
const VERSION_LABEL = "19. Oktober 2026";
|
const VERSION_LABEL = "19. Oktober 2026";
|
||||||
|
|
||||||
export type LegalTemplateKey = "impressum" | "datenschutz" | "agb" | "widerruf" | "versand";
|
export type LegalTemplateKey = "impressum" | "datenschutz" | "agb" | "widerruf" | "versand";
|
||||||
|
|
@ -112,11 +112,12 @@ function datenschutz(c: Ctx) {
|
||||||
"Wir verwenden ausschließlich Cookies, die für den Betrieb des Shops technisch notwendig sind (§ 25 Abs. 2 Nr. 2 TDDDG, Art. 6 Abs. 1 lit. b und f DSGVO). Eine Einwilligung ist dafür nicht erforderlich.",
|
"Wir verwenden ausschließlich Cookies, die für den Betrieb des Shops technisch notwendig sind (§ 25 Abs. 2 Nr. 2 TDDDG, Art. 6 Abs. 1 lit. b und f DSGVO). Eine Einwilligung ist dafür nicht erforderlich.",
|
||||||
[
|
[
|
||||||
"- **sm_cart:** merkt sich Ihren Warenkorb (30 Tage)",
|
"- **sm_cart:** merkt sich Ihren Warenkorb (30 Tage)",
|
||||||
"- **sm_checkout, sm_coupon:** speichern Angaben während des Bestellvorgangs und einen eingegebenen Gutscheincode",
|
"- **sm_checkout, sm_coupon:** speichern Angaben während des Bestellvorgangs und einen eingegebenen Gutscheincode bzw. den Code aus dem Link eines Creators (höchstens 30 Tage). Das Cookie enthält nur den Code, damit Ihnen der Rabatt gewährt werden kann.",
|
||||||
"- **sm_last_order:** ermöglicht den Aufruf Ihrer letzten Bestellung und Rechnung ohne Kundenkonto (30 Tage)",
|
"- **sm_last_order:** ermöglicht den Aufruf Ihrer letzten Bestellung und Rechnung ohne Kundenkonto (30 Tage)",
|
||||||
"- **sm_session:** hält Sie in Ihrem Kundenkonto angemeldet (bis zur Abmeldung, höchstens 30 Tage)",
|
"- **sm_session:** hält Sie in Ihrem Kundenkonto angemeldet (bis zur Abmeldung, höchstens 30 Tage)",
|
||||||
...(c.social.length ? ["- **sm_oauth:** schützt die Anmeldung über Google oder Apple vor Missbrauch (wenige Minuten)"] : []),
|
...(c.social.length ? ["- **sm_oauth:** schützt die Anmeldung über Google oder Apple vor Missbrauch (wenige Minuten)"] : []),
|
||||||
].join("\n"),
|
].join("\n"),
|
||||||
|
"Rufen Sie den Link eines Creators aus unserem Creator-Programm auf (z. B. /c/CODE), zählen wir diesen Aufruf ohne IP-Adresse und ohne weitere Angaben zu Ihrer Person, damit wir dem Creator die Anzahl der Klicks zeigen können. Bestellen Sie mit einem Creator-Code, erfährt der Creator nur Bestellnummer, Datum und Warenwert, nicht Ihren Namen oder Ihre Adresse (Art. 6 Abs. 1 lit. f DSGVO).",
|
||||||
"## 5. Kundenkonto",
|
"## 5. Kundenkonto",
|
||||||
"Sie können ein Kundenkonto anlegen. Dabei speichern wir Name, E-Mail-Adresse, ein verschlüsseltes Passwort sowie freiwillig Telefonnummer und Adressen. Im Konto sehen Sie Ihre Bestellungen und Rechnungen. Rechtsgrundlage ist Art. 6 Abs. 1 lit. b DSGVO. Sie können Ihr Konto jederzeit löschen lassen; Bestelldaten bewahren wir im Rahmen der gesetzlichen Pflichten weiter auf.",
|
"Sie können ein Kundenkonto anlegen. Dabei speichern wir Name, E-Mail-Adresse, ein verschlüsseltes Passwort sowie freiwillig Telefonnummer und Adressen. Im Konto sehen Sie Ihre Bestellungen und Rechnungen. Rechtsgrundlage ist Art. 6 Abs. 1 lit. b DSGVO. Sie können Ihr Konto jederzeit löschen lassen; Bestelldaten bewahren wir im Rahmen der gesetzlichen Pflichten weiter auf.",
|
||||||
);
|
);
|
||||||
|
|
@ -242,7 +243,7 @@ function agb(c: Ctx) {
|
||||||
"## § 10 Haftung",
|
"## § 10 Haftung",
|
||||||
"Wir haften unbeschränkt bei Vorsatz und grober Fahrlässigkeit, bei Verletzung von Leben, Körper oder Gesundheit sowie nach dem Produkthaftungsgesetz. Bei leicht fahrlässiger Verletzung einer wesentlichen Vertragspflicht ist die Haftung auf den vorhersehbaren, vertragstypischen Schaden begrenzt. Wesentliche Vertragspflichten sind solche, deren Erfüllung den Vertrag erst ermöglicht und auf deren Einhaltung Sie regelmäßig vertrauen dürfen. Im Übrigen ist die Haftung bei leichter Fahrlässigkeit ausgeschlossen.",
|
"Wir haften unbeschränkt bei Vorsatz und grober Fahrlässigkeit, bei Verletzung von Leben, Körper oder Gesundheit sowie nach dem Produkthaftungsgesetz. Bei leicht fahrlässiger Verletzung einer wesentlichen Vertragspflicht ist die Haftung auf den vorhersehbaren, vertragstypischen Schaden begrenzt. Wesentliche Vertragspflichten sind solche, deren Erfüllung den Vertrag erst ermöglicht und auf deren Einhaltung Sie regelmäßig vertrauen dürfen. Im Übrigen ist die Haftung bei leichter Fahrlässigkeit ausgeschlossen.",
|
||||||
"## § 11 Gutscheine",
|
"## § 11 Gutscheine",
|
||||||
"Aktionsgutscheine sind nur im angegebenen Zeitraum und nur einmal pro Bestellung einlösbar, nicht mit anderen Aktionen kombinierbar und nicht in bar auszahlbar. Wird eine Bestellung widerrufen, wird der mit dem Gutschein gewährte Rabatt nicht erstattet.",
|
"Aktionsgutscheine sind nur im angegebenen Zeitraum und nur einmal pro Bestellung einlösbar, nicht mit anderen Aktionen kombinierbar und nicht in bar auszahlbar. Wird eine Bestellung widerrufen, wird der mit dem Gutschein gewährte Rabatt nicht erstattet. Für Codes aus unserem Creator-Programm gilt zusätzlich: ein Code pro Bestellung, nicht mit anderen Gutscheinen kombinierbar, kein Rabatt auf bereits reduzierte und auf ausgenommene Artikel sowie auf Beratungstermine.",
|
||||||
"## § 12 Streitbeilegung",
|
"## § 12 Streitbeilegung",
|
||||||
"Wir sind nicht bereit und nicht verpflichtet, an Streitbeilegungsverfahren vor einer Verbraucherschlichtungsstelle teilzunehmen.",
|
"Wir sind nicht bereit und nicht verpflichtet, an Streitbeilegungsverfahren vor einer Verbraucherschlichtungsstelle teilzunehmen.",
|
||||||
"## § 13 Schlussbestimmungen",
|
"## § 13 Schlussbestimmungen",
|
||||||
|
|
|
||||||
|
|
@ -299,6 +299,25 @@ Lege jetzt dein Passwort fest. Der Link gilt sieben Tage.
|
||||||
[Passwort festlegen]({{link}})
|
[Passwort festlegen]({{link}})
|
||||||
|
|
||||||
Danach meldest du dich unter {{shop_link}}/admin an.`,
|
Danach meldest du dich unter {{shop_link}}/admin an.`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "creator_welcome",
|
||||||
|
name: "Willkommen im Creator-Programm",
|
||||||
|
description: "Wenn im Admin ein Creator angelegt wird. Bei neuen Konten führt der Link zuerst zum Festlegen des Passworts.",
|
||||||
|
recipient: "customer",
|
||||||
|
group: "Konto",
|
||||||
|
placeholders: [P.vorname, { key: "code", label: "Creator-Code", sample: "LUNA" }, { key: "vorteil", label: "Vorteil für Kunden", sample: "5 % Rabatt" }, { key: "link", label: "Link in den Creator-Bereich (bei neuen Konten: Passwort festlegen)", sample: "https://sanamare.de/konto/creator" }],
|
||||||
|
subject: "Willkommen im Creator-Programm von {{shop_name}}",
|
||||||
|
body: `Hallo {{vorname}},
|
||||||
|
|
||||||
|
schön, dass du dabei bist. Dein persönlicher Code ist **{{code}}**, deine Community bekommt damit {{vorteil}}.
|
||||||
|
|
||||||
|
Bevor der Code aktiv wird, bestätige bitte kurz die Programmbedingungen in deinem Creator-Bereich. Dort findest du auch deinen Link, deine Zahlen und deine Provisionen.
|
||||||
|
|
||||||
|
[Zum Creator-Bereich]({{link}})
|
||||||
|
|
||||||
|
Herzliche Grüße
|
||||||
|
dein {{shop_name}}-Team`,
|
||||||
},
|
},
|
||||||
// ---------- Beratung (Kartenlegen) ----------
|
// ---------- Beratung (Kartenlegen) ----------
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import { refundPayment } from "./payments/stripe";
|
||||||
import { cancelInvoice } from "./invoices";
|
import { cancelInvoice } from "./invoices";
|
||||||
import { mailCancelled, sendLater } from "./mail/send";
|
import { mailCancelled, sendLater } from "./mail/send";
|
||||||
import { revokeCourseAccess } from "./courses";
|
import { revokeCourseAccess } from "./courses";
|
||||||
|
import { syncCommission } from "./creators";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bestellung stornieren bzw. erstatten: Stripe-Zahlungen werden automatisch erstattet, sonst Hinweis im Verlauf.
|
* Bestellung stornieren bzw. erstatten: Stripe-Zahlungen werden automatisch erstattet, sonst Hinweis im Verlauf.
|
||||||
|
|
@ -41,6 +42,7 @@ export async function cancelOrderById(id: string, author: string, opts: { mail?:
|
||||||
});
|
});
|
||||||
await cancelInvoice(id, author);
|
await cancelInvoice(id, author);
|
||||||
await revokeCourseAccess(id);
|
await revokeCourseAccess(id);
|
||||||
|
await syncCommission(id);
|
||||||
if (opts.mail !== false) sendLater(() => mailCancelled(id, wasPaid));
|
if (opts.mail !== false) sendLater(() => mailCancelled(id, wasPaid));
|
||||||
return { order, wasPaid, refunded: refundNote.includes("erstattet."), refundNote };
|
return { order, wasPaid, refunded: refundNote.includes("erstattet."), refundNote };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,14 @@ export const PERMISSION_GROUPS = [
|
||||||
{ key: "newsletter.send", label: "Newsletter gestalten, versenden und Abonnenten entfernen" },
|
{ key: "newsletter.send", label: "Newsletter gestalten, versenden und Abonnenten entfernen" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
label: "Creator-Programm",
|
||||||
|
permissions: [
|
||||||
|
{ key: "creators.view", label: "Creator, Codes und Provisionen ansehen" },
|
||||||
|
{ key: "creators.edit", label: "Creator anlegen und bearbeiten, Stufen und Programm einstellen" },
|
||||||
|
{ key: "creators.payout", label: "Auszahlungen an Creator verbuchen" },
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
label: "Beratung (Kartenlegen)",
|
label: "Beratung (Kartenlegen)",
|
||||||
permissions: [
|
permissions: [
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,19 @@
|
||||||
import "server-only";
|
import "server-only";
|
||||||
import type { Coupon, PaymentMethod, ShippingMethod } from "@prisma/client";
|
import type { Coupon, PaymentMethod, ShippingMethod } from "@prisma/client";
|
||||||
|
import { formatPrice } from "./money";
|
||||||
import { db } from "./db";
|
import { db } from "./db";
|
||||||
import type { CartLine } from "./cart";
|
import type { CartLine } from "./cart";
|
||||||
|
import { getCurrentUser } from "./auth";
|
||||||
|
import { discountLabel, effectiveTerms, eligibleLines, isLive, loadCreatorCoupon, type CreatorTerms } from "./creators";
|
||||||
|
|
||||||
|
export type CreatorApplied = {
|
||||||
|
id: string;
|
||||||
|
tierName: string;
|
||||||
|
label: string;
|
||||||
|
commissionRate: number;
|
||||||
|
// Nettowarenwert der Artikel, auf die der Code wirkt, nach Rabatt (Cent)
|
||||||
|
commissionBase: number;
|
||||||
|
};
|
||||||
|
|
||||||
export type Totals = {
|
export type Totals = {
|
||||||
subtotal: number;
|
subtotal: number;
|
||||||
|
|
@ -13,16 +25,30 @@ export type Totals = {
|
||||||
freeShippingRemaining: number | null;
|
freeShippingRemaining: number | null;
|
||||||
coupon: Coupon | null;
|
coupon: Coupon | null;
|
||||||
couponError: string | null;
|
couponError: string | null;
|
||||||
|
// Hinweis zum eingelösten Code, z. B. dass er für einzelne Artikel nicht gilt
|
||||||
|
couponNotice: string | null;
|
||||||
|
// Rabattanteil je Position (gleiche Reihenfolge wie lines)
|
||||||
|
itemDiscounts: number[];
|
||||||
|
creator: CreatorApplied | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function findCoupon(code: string | null | undefined, subtotal: number) {
|
export async function findCoupon(code: string | null | undefined, subtotal: number) {
|
||||||
if (!code) return { coupon: null, error: null };
|
if (!code) return { coupon: null, error: null, terms: null };
|
||||||
const coupon = await db.coupon.findUnique({ where: { code: code.trim().toUpperCase() } });
|
const coupon = await loadCreatorCoupon(code);
|
||||||
if (!coupon || !coupon.active) return { coupon: null, error: "Diesen Gutscheincode kennen wir nicht." };
|
if (!coupon || !coupon.active) return { coupon: null, error: "Diesen Gutscheincode kennen wir nicht.", terms: null };
|
||||||
if (coupon.validUntil && coupon.validUntil < new Date()) return { coupon: null, error: "Dieser Gutschein ist abgelaufen." };
|
if (coupon.validUntil && coupon.validUntil < new Date()) return { coupon: null, error: "Dieser Gutschein ist abgelaufen.", terms: null };
|
||||||
if (coupon.maxUses > 0 && coupon.usedCount >= coupon.maxUses) return { coupon: null, error: "Dieser Gutschein wurde schon zu oft eingelöst." };
|
if (coupon.maxUses > 0 && coupon.usedCount >= coupon.maxUses) return { coupon: null, error: "Dieser Gutschein wurde schon zu oft eingelöst.", terms: null };
|
||||||
if (subtotal < coupon.minTotal) return { coupon: null, error: "Der Mindestbestellwert für diesen Gutschein ist noch nicht erreicht." };
|
let terms: CreatorTerms | null = null;
|
||||||
return { coupon, error: null };
|
if (coupon.creatorId) {
|
||||||
|
if (!coupon.creator || !isLive(coupon.creator)) return { coupon: null, error: "Dieser Code ist gerade nicht aktiv.", terms: null };
|
||||||
|
const user = await getCurrentUser();
|
||||||
|
if (user && user.id === coupon.creator.userId) return { coupon: null, error: "Deinen eigenen Creator-Code kannst du nicht selbst einlösen.", terms: null };
|
||||||
|
terms = effectiveTerms(coupon.creator);
|
||||||
|
if (subtotal < terms.minOrder) return { coupon: null, error: `Dieser Code gilt ab ${formatPrice(terms.minOrder)} Warenwert.`, terms: null };
|
||||||
|
} else if (subtotal < coupon.minTotal) {
|
||||||
|
return { coupon: null, error: "Der Mindestbestellwert für diesen Gutschein ist noch nicht erreicht.", terms: null };
|
||||||
|
}
|
||||||
|
return { coupon, error: null, terms };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function shippingPrice(method: ShippingMethod | null, merchandise: number) {
|
export function shippingPrice(method: ShippingMethod | null, merchandise: number) {
|
||||||
|
|
@ -36,12 +62,52 @@ export async function computeTotals(opts: {
|
||||||
couponCode?: string | null;
|
couponCode?: string | null;
|
||||||
shipping?: ShippingMethod | null;
|
shipping?: ShippingMethod | null;
|
||||||
payment?: PaymentMethod | null;
|
payment?: PaymentMethod | null;
|
||||||
|
// E-Mail aus der Kasse: eigene Creator-Codes gelten auch als Gast nicht
|
||||||
|
email?: string | null;
|
||||||
}): Promise<Totals> {
|
}): Promise<Totals> {
|
||||||
const subtotal = opts.lines.reduce((s, l) => s + l.total, 0);
|
const subtotal = opts.lines.reduce((s, l) => s + l.total, 0);
|
||||||
const { coupon, error } = await findCoupon(opts.couponCode, subtotal);
|
const found = await findCoupon(opts.couponCode, subtotal);
|
||||||
|
let coupon: Coupon | null = found.coupon;
|
||||||
|
let error = found.error;
|
||||||
|
let notice: string | null = null;
|
||||||
|
let eligible = opts.lines.map(() => true);
|
||||||
|
const terms = found.terms;
|
||||||
|
if (coupon && terms && opts.email && found.coupon?.creator?.user.email === opts.email.trim().toLowerCase()) {
|
||||||
|
coupon = null;
|
||||||
|
error = "Deinen eigenen Creator-Code kannst du nicht selbst einlösen.";
|
||||||
|
}
|
||||||
|
if (coupon && terms) {
|
||||||
|
eligible = await eligibleLines(terms, opts.lines);
|
||||||
|
if (eligible.some((e) => !e)) {
|
||||||
|
notice = eligible.every((e) => !e)
|
||||||
|
? "Der Code gilt nicht für die Artikel in deinem Warenkorb (reduzierte oder ausgenommene Artikel)."
|
||||||
|
: "Der Code gilt nicht für reduzierte oder ausgenommene Artikel.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const eligibleSubtotal = opts.lines.reduce((s, l, i) => s + (eligible[i] ? l.total : 0), 0);
|
||||||
let discount = 0;
|
let discount = 0;
|
||||||
if (coupon) discount = coupon.type === "percent" ? Math.round((subtotal * coupon.value) / 100) : Math.min(coupon.value, subtotal);
|
if (coupon && terms) {
|
||||||
|
discount = terms.discountType === "percent" ? Math.round((eligibleSubtotal * terms.discountValue) / 100) : Math.min(terms.discountValue, eligibleSubtotal);
|
||||||
|
if (terms.discountCap > 0) discount = Math.min(discount, terms.discountCap);
|
||||||
|
} else if (coupon) {
|
||||||
|
discount = coupon.type === "percent" ? Math.round((subtotal * coupon.value) / 100) : Math.min(coupon.value, subtotal);
|
||||||
|
}
|
||||||
|
// Rabatt anteilig auf die Positionen verteilen, Rundungsrest auf die größte
|
||||||
|
const itemDiscounts = opts.lines.map((l, i) => (eligible[i] && eligibleSubtotal > 0 ? Math.round((discount * l.total) / eligibleSubtotal) : 0));
|
||||||
|
const rest = discount - itemDiscounts.reduce((s, d) => s + d, 0);
|
||||||
|
if (rest && itemDiscounts.length) {
|
||||||
|
let big = -1;
|
||||||
|
opts.lines.forEach((l, i) => {
|
||||||
|
if (eligible[i] && (big < 0 || l.total > opts.lines[big].total)) big = i;
|
||||||
|
});
|
||||||
|
if (big >= 0) itemDiscounts[big] += rest;
|
||||||
|
}
|
||||||
const merchandise = subtotal - discount;
|
const merchandise = subtotal - discount;
|
||||||
|
let creator: CreatorApplied | null = null;
|
||||||
|
if (coupon && terms && found.coupon?.creator) {
|
||||||
|
const base = opts.lines.reduce((s, l, i) => (eligible[i] ? s + (l.total - itemDiscounts[i]) / (1 + l.taxRate / 100) : s), 0);
|
||||||
|
creator = { id: found.coupon.creator.id, tierName: terms.tierName, label: discountLabel(terms), commissionRate: terms.commissionRate, commissionBase: Math.round(base) };
|
||||||
|
}
|
||||||
|
|
||||||
// Nur Video-Kurse: nichts zu versenden
|
// Nur Video-Kurse: nichts zu versenden
|
||||||
const digitalOnly = opts.lines.length > 0 && opts.lines.every((l) => l.digital);
|
const digitalOnly = opts.lines.length > 0 && opts.lines.every((l) => l.digital);
|
||||||
|
|
@ -53,11 +119,10 @@ export async function computeTotals(opts: {
|
||||||
const paymentFee = opts.payment?.fee ?? 0;
|
const paymentFee = opts.payment?.fee ?? 0;
|
||||||
const total = merchandise + shippingCost + paymentFee;
|
const total = merchandise + shippingCost + paymentFee;
|
||||||
|
|
||||||
// MwSt.: anteilig je Steuersatz der Positionen, Versand/Gebühr mit dem überwiegenden Satz
|
// MwSt.: je Steuersatz der Positionen (nach ihrem Rabattanteil), Versand/Gebühr mit dem überwiegenden Satz
|
||||||
const ratio = subtotal > 0 ? merchandise / subtotal : 0;
|
|
||||||
let taxAmount = 0;
|
let taxAmount = 0;
|
||||||
const byRate = new Map<number, number>();
|
const byRate = new Map<number, number>();
|
||||||
for (const l of opts.lines) byRate.set(l.taxRate, (byRate.get(l.taxRate) ?? 0) + l.total * ratio);
|
opts.lines.forEach((l, i) => byRate.set(l.taxRate, (byRate.get(l.taxRate) ?? 0) + l.total - itemDiscounts[i]));
|
||||||
for (const [rate, gross] of byRate) taxAmount += gross - gross / (1 + rate / 100);
|
for (const [rate, gross] of byRate) taxAmount += gross - gross / (1 + rate / 100);
|
||||||
const mainRate = [...byRate.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 19;
|
const mainRate = [...byRate.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 19;
|
||||||
taxAmount += (shippingCost + paymentFee) - (shippingCost + paymentFee) / (1 + mainRate / 100);
|
taxAmount += (shippingCost + paymentFee) - (shippingCost + paymentFee) / (1 + mainRate / 100);
|
||||||
|
|
@ -75,5 +140,8 @@ export async function computeTotals(opts: {
|
||||||
freeShippingRemaining,
|
freeShippingRemaining,
|
||||||
coupon,
|
coupon,
|
||||||
couponError: error,
|
couponError: error,
|
||||||
|
couponNotice: notice,
|
||||||
|
itemDiscounts,
|
||||||
|
creator,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -71,6 +71,17 @@ export type ShopSettings = {
|
||||||
bank: string;
|
bank: string;
|
||||||
footer: string;
|
footer: string;
|
||||||
};
|
};
|
||||||
|
creator: {
|
||||||
|
// Tage nach Versand (bei Kursen: nach Zahlung), bis eine Provision freigegeben wird
|
||||||
|
holdDays: number;
|
||||||
|
// So lange merkt sich der Warenkorb einen Code aus einem Creator-Link
|
||||||
|
linkDays: number;
|
||||||
|
defaultTierId: string;
|
||||||
|
// Gilt für alle Stufen zusätzlich zu deren eigenen Ausschlüssen
|
||||||
|
excludedCategoryIds: string[];
|
||||||
|
termsVersion: string;
|
||||||
|
terms: string;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DEFAULT_SETTINGS: ShopSettings = {
|
export const DEFAULT_SETTINGS: ShopSettings = {
|
||||||
|
|
@ -146,6 +157,22 @@ export const DEFAULT_SETTINGS: ShopSettings = {
|
||||||
bank: "",
|
bank: "",
|
||||||
footer: "Vielen Dank für deinen Einkauf.",
|
footer: "Vielen Dank für deinen Einkauf.",
|
||||||
},
|
},
|
||||||
|
creator: {
|
||||||
|
holdDays: 30,
|
||||||
|
linkDays: 30,
|
||||||
|
defaultTierId: "tier_starter",
|
||||||
|
excludedCategoryIds: [],
|
||||||
|
termsVersion: "1",
|
||||||
|
terms: `Programmbedingungen für Creator (Entwurf, bitte rechtlich prüfen lassen)
|
||||||
|
|
||||||
|
1. Werbekennzeichnung: Wer den Code oder Link bewirbt, macht Werbung. Kennzeichne jedes Video und jeden Post deutlich am Anfang als „Werbung“ oder „Anzeige“ und nutze die Kennzeichnung der Plattform. Bei Verstößen sperren wir den Code.
|
||||||
|
2. Aussagen: Keine Heilversprechen oder gesundheitsbezogenen Wirkversprechen, keine Preis- oder Leistungsversprechen ohne unsere Freigabe und keine Vergleiche mit Preisen anderer Anbieter.
|
||||||
|
3. Code: Der Code ist persönlich. Er darf nicht auf Gutschein- oder Schnäppchenseiten veröffentlicht werden. Eigene Bestellungen mit dem eigenen Code sind ausgeschlossen.
|
||||||
|
4. Provision: Es gibt Provision auf den Nettowarenwert nach Rabatt (ohne Versand, Zahlungsgebühr und Steuer) der Artikel, auf die der Code wirkt. Freigabe nach Ablauf der Haltefrist; stornierte oder erstattete Bestellungen werden abgezogen, auch nach einer Auszahlung.
|
||||||
|
5. Steuern: Die Provision ist dein Einkommen. Gib deinen Steuerstatus im Konto korrekt an. Ausgezahlt wird per Überweisung.
|
||||||
|
6. Teilnahme ab 18 Jahren, sonst nur mit Zustimmung der Eltern.
|
||||||
|
7. Kündigung jederzeit von beiden Seiten. Offene, freigegebene Provisionen werden ausgezahlt.`,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SettingsSection = keyof ShopSettings;
|
export type SettingsSection = keyof ShopSettings;
|
||||||
|
|
|
||||||
|
|
@ -348,3 +348,4 @@ a.ad-kpi:hover { border-color: var(--line-strong); }
|
||||||
.ad-week__slot { display: inline-flex; gap: 6px; align-items: center; }
|
.ad-week__slot { display: inline-flex; gap: 6px; align-items: center; }
|
||||||
.ad-week__slot .sm-input { width: 110px; min-height: var(--control-height-sm); }
|
.ad-week__slot .sm-input { width: 110px; min-height: var(--control-height-sm); }
|
||||||
@media (max-width: 640px) { .ad-week__day { grid-template-columns: 1fr; gap: var(--space-1); } }
|
@media (max-width: 640px) { .ad-week__day { grid-template-columns: 1fr; gap: var(--space-1); } }
|
||||||
|
.ad-subhead { font-size: 15px; line-height: 22px; font-weight: 500; margin: var(--space-5) 0 var(--space-2); }
|
||||||
|
|
|
||||||
|
|
@ -395,3 +395,21 @@ button.sm-pdp__main { display: block; width: 100%; padding: 0; border: 0; cursor
|
||||||
.sm-room__send .sm-input { min-height: var(--control-height-sm); }
|
.sm-room__send .sm-input { min-height: var(--control-height-sm); }
|
||||||
@media (max-width: 1023px) { .sm-room { grid-template-columns: 1fr; } .sm-room__chat { max-height: 40vh; } }
|
@media (max-width: 1023px) { .sm-room { grid-template-columns: 1fr; } .sm-room__chat { max-height: 40vh; } }
|
||||||
@media (max-width: 640px) { .sm-room__remote { aspect-ratio: 3 / 4; } .sm-room__self { width: 34%; aspect-ratio: 3 / 4; } }
|
@media (max-width: 640px) { .sm-room__remote { aspect-ratio: 3 / 4; } .sm-room__self { width: 34%; aspect-ratio: 3 / 4; } }
|
||||||
|
|
||||||
|
/* ---------- Creator-Programm ---------- */
|
||||||
|
.sm-creatorbar { background: var(--gold-soft); color: var(--ink); text-align: center; font-size: 13px; line-height: 20px; padding: var(--space-2) var(--space-4); border-bottom: var(--hairline) solid var(--line); }
|
||||||
|
.sm-creatorbar strong { letter-spacing: 0.04em; }
|
||||||
|
.sm-creator__grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: var(--space-3); margin-bottom: var(--space-6); }
|
||||||
|
.sm-creator__stat { border: var(--hairline) solid var(--line); border-radius: var(--radius-md); padding: var(--space-4); background: var(--surface-raised); }
|
||||||
|
.sm-creator__stat span { display: block; font-size: 13px; color: var(--ink-muted); }
|
||||||
|
.sm-creator__stat strong { display: block; font-family: var(--font-serif); font-size: 28px; line-height: 1.2; margin-top: var(--space-1); }
|
||||||
|
.sm-creator__box { border: var(--hairline) solid var(--line); border-radius: var(--radius-md); padding: var(--space-5); background: var(--surface-raised); margin-bottom: var(--space-6); }
|
||||||
|
.sm-creator__box h2 { margin: 0 0 var(--space-3); }
|
||||||
|
.sm-creator__copy { display: flex; gap: var(--space-2); align-items: center; flex-wrap: wrap; margin-bottom: var(--space-3); }
|
||||||
|
.sm-creator__copy code { font-size: 15px; padding: var(--space-2) var(--space-3); background: var(--surface-sunken); border-radius: var(--radius-sm); word-break: break-all; }
|
||||||
|
.sm-creator__terms { white-space: pre-wrap; max-height: 360px; overflow: auto; font-size: 14px; line-height: 1.6; padding: var(--space-4); background: var(--surface-sunken); border-radius: var(--radius-sm); margin-bottom: var(--space-4); }
|
||||||
|
.sm-creator__table { width: 100%; border-collapse: collapse; font-size: 14px; }
|
||||||
|
.sm-creator__table th, .sm-creator__table td { text-align: left; padding: var(--space-2) var(--space-2); border-bottom: var(--hairline) solid var(--line); }
|
||||||
|
.sm-creator__table th { font-weight: 500; color: var(--ink-muted); }
|
||||||
|
.sm-creator__table .num { text-align: right; white-space: nowrap; }
|
||||||
|
.sm-creator__scroll { overflow-x: auto; }
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue