Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
77 lines
3.6 KiB
TypeScript
77 lines
3.6 KiB
TypeScript
import "server-only";
|
|
import { db } from "./db";
|
|
import { appUrl } from "./social/config";
|
|
import { sendTemplate } from "./mail/send";
|
|
|
|
const MAX_PER_EMAIL = 30;
|
|
|
|
/** Kunde möchte benachrichtigt werden. Doppelte Einträge für dasselbe Produkt werden ignoriert. */
|
|
export async function addStockAlert(productId: string, variantId: string | null, email: string) {
|
|
const product = await db.product.findFirst({ where: { id: productId, active: true }, include: { variants: true } });
|
|
if (!product) return { ok: false as const, error: "Produkt nicht gefunden." };
|
|
if (variantId && !product.variants.some((v) => v.id === variantId)) return { ok: false as const, error: "Variante nicht gefunden." };
|
|
const existing = await db.stockAlert.findFirst({ where: { productId, variantId, email, notifiedAt: null } });
|
|
if (!existing) {
|
|
// Schutz vor Missbrauch: nicht beliebig viele Einträge für eine Adresse
|
|
if ((await db.stockAlert.count({ where: { email, notifiedAt: null } })) >= MAX_PER_EMAIL) return { ok: false as const, error: "Du hast schon sehr viele Erinnerungen eingetragen." };
|
|
await db.stockAlert.create({ data: { productId, variantId, email } });
|
|
}
|
|
return { ok: true as const };
|
|
}
|
|
|
|
type ProductWithVariants = { trackStock: boolean; stock: number; active: boolean; variants: { id: string; stock: number }[] };
|
|
|
|
function available(p: ProductWithVariants, variantId: string | null) {
|
|
if (!p.active) return false;
|
|
if (!p.trackStock) return true;
|
|
if (variantId) return (p.variants.find((v) => v.id === variantId)?.stock ?? 0) > 0;
|
|
return p.variants.length ? p.variants.some((v) => v.stock > 0) : p.stock > 0;
|
|
}
|
|
|
|
/**
|
|
* Verschickt „wieder da“ an alle wartenden Kunden, deren Produkt (oder Variante) wieder lieferbar ist.
|
|
* Ohne productId werden alle wartenden Einträge geprüft (läuft jede Minute mit, z. B. nach Stornos).
|
|
* Nach dem Versand wird die Adresse gelöscht, sie wird für nichts anderes gebraucht.
|
|
*/
|
|
export async function notifyBackInStock(productId?: string) {
|
|
const alerts = await db.stockAlert.findMany({
|
|
where: { notifiedAt: null, ...(productId ? { productId } : {}) },
|
|
include: { product: { include: { variants: { select: { id: true, stock: true, name: true } } } }, variant: { select: { name: true } } },
|
|
take: 200,
|
|
orderBy: { createdAt: "asc" },
|
|
});
|
|
let sent = 0;
|
|
for (const a of alerts) {
|
|
if (!available(a.product, a.variantId)) continue;
|
|
const r = await sendTemplate({
|
|
key: "back_in_stock",
|
|
to: a.email,
|
|
vars: { produkt: a.product.name, variante: a.variant?.name ?? "", variante_hinweis: a.variant ? `Gewählte Variante: ${a.variant.name}` : "", produkt_link: `${appUrl()}/produkt/${a.product.slug}` },
|
|
});
|
|
// Ausgeschaltete Vorlage oder fehlender Mailserver: Eintrag bleibt und wird später erneut versucht
|
|
if (r.ok) {
|
|
await db.stockAlert.update({ where: { id: a.id }, data: { notifiedAt: new Date(), email: "" } });
|
|
sent++;
|
|
}
|
|
}
|
|
return sent;
|
|
}
|
|
|
|
const timer = globalThis as unknown as { stockAlertTimer?: NodeJS.Timeout; stockAlertBusy?: boolean };
|
|
|
|
/** Prüft jede Minute, ob Wartende benachrichtigt werden können (fängt auch Stornos und andere Bestandsänderungen ab). */
|
|
export function startStockAlertTimer() {
|
|
if (timer.stockAlertTimer) return;
|
|
timer.stockAlertTimer = setInterval(async () => {
|
|
if (timer.stockAlertBusy) return;
|
|
timer.stockAlertBusy = true;
|
|
try {
|
|
if (await db.stockAlert.count({ where: { notifiedAt: null } })) await notifyBackInStock();
|
|
} catch (e) {
|
|
console.error("Wieder-da-Erinnerungen fehlgeschlagen", e);
|
|
} finally {
|
|
timer.stockAlertBusy = false;
|
|
}
|
|
}, 60_000);
|
|
timer.stockAlertTimer.unref?.();
|
|
}
|