sanamare/src/app/(shop)/kasse/actions.ts
Claude 6e717435a6 Mail-Dienst: Versand über eigenes Postfach, frei bearbeitbare Vorlagen
- SMTP-Versand ohne Zusatzpaket, Einrichtung unter Verbindungen mit Anbieter-Voreinstellungen und Testmail
- 10 Vorlagen im Sanamare-Design: Bestellung, Zahlung, Versand, Rechnung, Storno, Team-Benachrichtigung, Willkommen, Passwort vergessen, Newsletter-Bestätigung, Team-Einladung
- Admin unter E-Mails: Betreff und Text mit Platzhaltern, an/aus, Live-Vorschau, Testversand, Zurücksetzen, Versandprotokoll
- Passwort vergessen für Kunden und Team, Double-Opt-in für den Newsletter, Team-Einladung per Link
- Rechnungslink für Gäste per Zugangsschlüssel; Mails erscheinen im Verlauf der Bestellung

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
2026-10-19 21:26:45 +02:00

136 lines
7 KiB
TypeScript

"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { z } from "zod";
import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { getCart } from "@/lib/cart";
import { finishCheckoutSession } from "@/lib/checkout-finish";
import { availablePayments, availableShipping, createOrder, readCheckout, writeCheckout } from "@/lib/checkout";
import { computeTotals } from "@/lib/pricing";
import { getSettings } from "@/lib/settings";
import { autoInvoice } from "@/lib/invoices";
import { mailOrderPlaced, sendLater } from "@/lib/mail/send";
import { getDefinition } from "@/lib/payments/catalog";
import { getCredentials } from "@/lib/payments/credentials";
import { createCheckoutSession } from "@/lib/payments/stripe";
import { createPaypalOrder } from "@/lib/payments/paypal";
export type FormState = { errors?: Record<string, string>; message?: string } | null;
const addressSchema = z.object({
firstName: z.string().trim().min(1, "Bitte gib deinen Vornamen ein."),
lastName: z.string().trim().min(1, "Bitte gib deinen Nachnamen ein."),
company: z.string().trim().default(""),
street: z.string().trim().min(3, "Bitte gib Straße und Hausnummer ein."),
extra: z.string().trim().default(""),
zip: z.string().trim().regex(/^[0-9A-Za-z -]{4,10}$/, "Bitte gib eine gültige Postleitzahl ein."),
city: z.string().trim().min(2, "Bitte gib deinen Ort ein."),
country: z.string().trim().length(2, "Bitte wähle ein Land."),
});
function pick(formData: FormData, prefix = "") {
const o: Record<string, string> = {};
for (const k of ["firstName", "lastName", "company", "street", "extra", "zip", "city", "country"]) o[k] = String(formData.get(prefix + k) ?? "");
return o;
}
export async function saveAddress(_prev: FormState, formData: FormData): Promise<FormState> {
const settings = await getSettings();
const errors: Record<string, string> = {};
const email = z.email().safeParse(String(formData.get("email") ?? "").trim().toLowerCase());
if (!email.success) errors.email = "Bitte gib eine gültige E-Mail-Adresse ein.";
const phone = String(formData.get("phone") ?? "").trim();
if (settings.checkout.requirePhone && phone.length < 5) errors.phone = "Bitte gib deine Telefonnummer ein.";
const address = addressSchema.safeParse(pick(formData));
if (!address.success) for (const i of address.error.issues) errors[String(i.path[0])] ??= i.message;
if (address.success && !settings.checkout.countries.includes(address.data.country)) errors.country = "In dieses Land liefern wir leider nicht.";
const billingSame = formData.get("billingSame") === "on";
let billing;
if (!billingSame) {
const b = addressSchema.safeParse(pick(formData, "b_"));
if (!b.success) for (const i of b.error.issues) errors["b_" + String(i.path[0])] ??= i.message;
else billing = b.data;
}
if (Object.keys(errors).length) return { errors, message: "Bitte prüfe die markierten Felder." };
await writeCheckout({
email: email.data,
phone,
address: address.data,
billingSame,
billing,
newsletter: formData.get("newsletter") === "on",
});
redirect("/kasse/versand");
}
export async function saveShipping(_prev: FormState, formData: FormData): Promise<FormState> {
const id = String(formData.get("shippingMethodId") ?? "");
const state = await readCheckout();
const methods = await availableShipping(state.address?.country);
if (!methods.some((m) => m.id === id)) return { message: "Bitte wähle eine Versandart." };
await writeCheckout({ shippingMethodId: id });
redirect("/kasse/zahlung");
}
export async function savePayment(_prev: FormState, formData: FormData): Promise<FormState> {
const id = String(formData.get("paymentMethodId") ?? "");
const [lines, user, jar] = await Promise.all([getCart(), getCurrentUser(), cookies()]);
const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value });
const methods = await availablePayments(totals.total, Boolean(user));
if (!methods.some((m) => m.id === id)) return { message: "Bitte wähle eine Zahlungsart." };
await writeCheckout({ paymentMethodId: id });
redirect("/kasse/pruefen");
}
export async function placeOrder(_prev: FormState, formData: FormData): Promise<FormState> {
const settings = await getSettings();
if (settings.checkout.requireTerms && formData.get("terms") !== "on") {
return { errors: { terms: "Bitte bestätige die AGB und die Widerrufsbelehrung." } };
}
const [state, lines, user, jar] = await Promise.all([readCheckout(), getCart(), getCurrentUser(), cookies()]);
if (!lines.length) redirect("/warenkorb");
if (!state.email || !state.address) redirect("/kasse/adresse");
const shipping = state.shippingMethodId ? await db.shippingMethod.findUnique({ where: { id: state.shippingMethodId } }) : null;
if (!shipping?.enabled) redirect("/kasse/versand");
const payment = state.paymentMethodId ? await db.paymentMethod.findUnique({ where: { id: state.paymentMethodId } }) : null;
if (!payment?.enabled) redirect("/kasse/zahlung");
const totals = await computeTotals({ lines, couponCode: jar.get("sm_coupon")?.value, shipping, payment });
if (settings.checkout.minOrderValue > 0 && totals.subtotal < settings.checkout.minOrderValue) redirect("/warenkorb");
let order;
try {
order = await createOrder({ state, lines, totals, shippingName: shipping.name, payment, userId: user?.id ?? null, note: String(formData.get("note") ?? "").slice(0, 1000) });
} catch (e) {
return { message: e instanceof Error ? e.message : "Die Bestellung konnte nicht angelegt werden." };
}
await autoInvoice(order.id, "order");
const placedId = order.id;
sendLater(() => mailOrderPlaced(placedId, "placed"));
await writeCheckout({ lastOrderId: order.id });
jar.set("sm_last_order", order.id, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 30 });
const def = getDefinition(payment.code);
const appUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
let target: string;
try {
if (def?.provider === "stripe") {
const creds = await getCredentials();
const session = await createCheckoutSession({ secretKey: creds.stripe.secretKey, order, stripeType: def.stripeType!, appUrl });
await db.order.update({ where: { id: order.id }, data: { paymentRef: session.id } });
target = session.url;
} else if (def?.provider === "paypal") {
const creds = await getCredentials();
const pp = await createPaypalOrder(creds.paypal, order, appUrl);
await db.order.update({ where: { id: order.id }, data: { paymentRef: pp.id } });
target = pp.url;
} else {
await finishCheckoutSession();
target = `/kasse/danke/${order.id}`;
}
} catch (e) {
await db.orderEvent.create({ data: { orderId: order.id, message: `Zahlung konnte nicht gestartet werden: ${e instanceof Error ? e.message : e}` } });
return { message: "Die Zahlung konnte nicht gestartet werden. Bitte wähle eine andere Zahlungsart oder versuche es gleich noch einmal." };
}
redirect(target);
}