import { prisma } from "@/lib/prisma"; import { sendMail } from "@/lib/mail"; import { backInStockEmail } from "@/lib/email-templates"; import { isLocale, defaultLocale } from "@/i18n/config"; /** * Versendet die Wiederverfuegbarkeits-E-Mail an alle wartenden Anmeldungen * fuer ein Produkt und markiert sie als benachrichtigt. Wird vom Admin-Bereich * aufgerufen, wenn der Lagerbestand eines zuvor ausverkauften Produkts wieder * auf > 0 gesetzt wird (siehe updateProductAction in admin/actions.ts). */ export async function notifyStockAvailable(productId: string): Promise { const pending = await prisma.stockNotification.findMany({ where: { productId, notifiedAt: null }, }); if (pending.length === 0) return; const product = await prisma.product.findUnique({ where: { id: productId }, select: { name: true, slug: true }, }); if (!product) return; // E-Mail-Fehler duerfen den Bestands-Update selbst nicht scheitern lassen — // sendMail wirft nie (siehe lib/mail.ts). Jede Anmeldung wird in der bei // der Anmeldung gespeicherten Sprache benachrichtigt (koennen unterschiedliche sein). for (const notification of pending) { const locale = isLocale(notification.locale) ? notification.locale : defaultLocale; const { subject, html, text } = await backInStockEmail({ locale, ...product }); await sendMail({ to: notification.email, subject, html, text }); } await prisma.stockNotification.updateMany({ where: { id: { in: pending.map((n) => n.id) } }, data: { notifiedAt: new Date() }, }); }