Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
181 lines
6.7 KiB
TypeScript
181 lines
6.7 KiB
TypeScript
import "server-only";
|
||
import { cookies } from "next/headers";
|
||
import type { PaymentMethod, Prisma } from "@prisma/client";
|
||
import { db } from "./db";
|
||
import type { CartLine } from "./cart";
|
||
import type { Totals } from "./pricing";
|
||
import { getDefinition } from "./payments/catalog";
|
||
import { getCredentials, isProviderReady } from "./payments/credentials";
|
||
import { getSettings } from "./settings";
|
||
|
||
export const CHECKOUT_COOKIE = "sm_checkout";
|
||
|
||
export type AddressData = {
|
||
firstName: string;
|
||
lastName: string;
|
||
company: string;
|
||
street: string;
|
||
extra: string;
|
||
zip: string;
|
||
city: string;
|
||
country: string;
|
||
};
|
||
|
||
export type CheckoutState = {
|
||
email?: string;
|
||
phone?: string;
|
||
address?: AddressData;
|
||
billingSame?: boolean;
|
||
billing?: AddressData;
|
||
newsletter?: boolean;
|
||
shippingMethodId?: string;
|
||
paymentMethodId?: string;
|
||
lastOrderId?: string;
|
||
};
|
||
|
||
export async function readCheckout(): Promise<CheckoutState> {
|
||
const raw = (await cookies()).get(CHECKOUT_COOKIE)?.value;
|
||
if (!raw) return {};
|
||
try {
|
||
return JSON.parse(raw) as CheckoutState;
|
||
} catch {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
export async function writeCheckout(patch: Partial<CheckoutState>) {
|
||
const next = { ...(await readCheckout()), ...patch };
|
||
(await cookies()).set(CHECKOUT_COOKIE, JSON.stringify(next), {
|
||
httpOnly: true,
|
||
sameSite: "lax",
|
||
path: "/",
|
||
maxAge: 60 * 60 * 24 * 7,
|
||
});
|
||
return next;
|
||
}
|
||
|
||
export async function availableShipping(country: string | undefined) {
|
||
const methods = await db.shippingMethod.findMany({ where: { enabled: true }, orderBy: { sort: "asc" } });
|
||
return methods.filter((m) => !country || m.countries.length === 0 || m.countries.includes(country));
|
||
}
|
||
|
||
export async function availablePayments(total: number, loggedIn: boolean): Promise<PaymentMethod[]> {
|
||
const [methods, creds] = await Promise.all([
|
||
db.paymentMethod.findMany({ where: { enabled: true }, orderBy: { sort: "asc" } }),
|
||
getCredentials(),
|
||
]);
|
||
return methods.filter((m) => {
|
||
const def = getDefinition(m.code);
|
||
if (!def || !isProviderReady(def.provider, creds)) return false;
|
||
if (m.loggedInOnly && !loggedIn) return false;
|
||
if (m.code === "prepayment" && !(m.config as Record<string, string>)?.iban) return false;
|
||
if (m.minTotal > 0 && total < m.minTotal) return false;
|
||
if (m.maxTotal > 0 && total > m.maxTotal) return false;
|
||
return true;
|
||
});
|
||
}
|
||
|
||
async function nextOrderNumber(tx: Prisma.TransactionClient) {
|
||
const settings = await getSettings();
|
||
const count = await tx.order.count();
|
||
return `${settings.general.orderPrefix || "SM"}-${10001 + count}`;
|
||
}
|
||
|
||
/** Bestand zurückbuchen, z. B. bei Storno */
|
||
export async function restock(tx: Prisma.TransactionClient, orderId: string) {
|
||
const items = await tx.orderItem.findMany({ where: { orderId }, include: { product: true } });
|
||
for (const it of items) {
|
||
if (!it.product?.trackStock) continue;
|
||
if (it.variantId) await tx.productVariant.updateMany({ where: { id: it.variantId }, data: { stock: { increment: it.quantity } } });
|
||
else await tx.product.update({ where: { id: it.product.id }, data: { stock: { increment: it.quantity } } });
|
||
}
|
||
}
|
||
|
||
export async function createOrder(opts: {
|
||
state: CheckoutState;
|
||
lines: CartLine[];
|
||
totals: Totals;
|
||
shippingName: string;
|
||
payment: PaymentMethod;
|
||
userId: string | null;
|
||
note: string;
|
||
}) {
|
||
const { state, lines, totals, payment } = opts;
|
||
return db.$transaction(async (tx) => {
|
||
// Eine noch offene, nie bezahlte Bestellung aus demselben Checkout wird ersetzt
|
||
if (state.lastOrderId) {
|
||
const prev = await tx.order.findUnique({ where: { id: state.lastOrderId } });
|
||
if (prev && prev.status === "PENDING" && prev.paymentStatus === "OPEN" && ["stripe", "paypal"].includes(getDefinition(prev.paymentMethod)?.provider ?? "")) {
|
||
await restock(tx, prev.id);
|
||
await tx.order.update({ where: { id: prev.id }, data: { status: "CANCELLED" } });
|
||
await tx.orderEvent.create({ data: { orderId: prev.id, message: "Automatisch storniert: Kunde hat neu bestellt, Zahlung wurde nie abgeschlossen." } });
|
||
}
|
||
}
|
||
// Bestand prüfen und reservieren
|
||
for (const l of lines) {
|
||
const product = await tx.product.findUnique({ where: { id: l.productId } });
|
||
if (!product?.trackStock) continue;
|
||
if (l.variantId) {
|
||
const r = await tx.productVariant.updateMany({ where: { id: l.variantId, stock: { gte: l.quantity } }, data: { stock: { decrement: l.quantity } } });
|
||
if (r.count === 0) throw new Error(`${l.name} – ${l.variantName} ist nicht mehr in dieser Menge verfügbar.`);
|
||
} else {
|
||
const r = await tx.product.updateMany({ where: { id: l.productId, stock: { gte: l.quantity } }, data: { stock: { decrement: l.quantity } } });
|
||
if (r.count === 0) throw new Error(`${l.name} ist nicht mehr in dieser Menge verfügbar.`);
|
||
}
|
||
}
|
||
if (totals.coupon) await tx.coupon.update({ where: { id: totals.coupon.id }, data: { usedCount: { increment: 1 } } });
|
||
const number = await nextOrderNumber(tx);
|
||
const order = await tx.order.create({
|
||
data: {
|
||
number,
|
||
userId: opts.userId,
|
||
email: state.email!,
|
||
phone: state.phone ?? "",
|
||
paymentMethod: payment.code,
|
||
shippingMethod: opts.shippingName,
|
||
shippingAddress: state.address!,
|
||
billingAddress: state.billingSame === false && state.billing ? state.billing : undefined,
|
||
subtotal: totals.subtotal,
|
||
shippingCost: totals.shippingCost,
|
||
paymentFee: totals.paymentFee,
|
||
discount: totals.discount,
|
||
couponCode: totals.coupon?.code ?? "",
|
||
taxAmount: totals.taxAmount,
|
||
total: totals.total,
|
||
note: opts.note,
|
||
items: {
|
||
create: lines.map((l) => ({
|
||
productId: l.productId,
|
||
variantId: l.variantId,
|
||
name: l.name,
|
||
variantName: l.variantName,
|
||
sku: l.sku,
|
||
unitPrice: l.unitPrice,
|
||
quantity: l.quantity,
|
||
taxRate: l.taxRate,
|
||
total: l.total,
|
||
})),
|
||
},
|
||
events: { create: { message: `Bestellung aufgegeben, Zahlungsart: ${payment.name}` } },
|
||
},
|
||
});
|
||
if (state.newsletter) {
|
||
await tx.newsletterSubscriber.upsert({ where: { email: order.email }, create: { email: order.email }, update: {} });
|
||
}
|
||
return order;
|
||
});
|
||
}
|
||
|
||
export async function markOrderPaid(orderId: string, reference: string, source: string) {
|
||
const order = await db.order.findUnique({ where: { id: orderId } });
|
||
if (!order || order.paymentStatus === "PAID") return order;
|
||
return db.order.update({
|
||
where: { id: orderId },
|
||
data: {
|
||
paymentStatus: "PAID",
|
||
paymentRef: reference,
|
||
status: order.status === "PENDING" ? "PAID" : order.status,
|
||
events: { create: { message: `Zahlung bestätigt (${source})` } },
|
||
},
|
||
});
|
||
}
|