Implement dynamic SMTP setting loader, admin product dependency matrix UI, recursive deselect cascade, and backend catalog validation
All checks were successful
Staging Build / build (push) Successful in 2m19s

This commit is contained in:
DanielS
2026-06-23 04:42:50 +02:00
parent de1d228fb2
commit 0729dd21be
5 changed files with 286 additions and 122 deletions

View File

@@ -40,12 +40,13 @@ import {
} from "@/components/ui/select" } from "@/components/ui/select"
const moduleSchema = z.object({ const moduleSchema = z.object({
id: z.string().optional(),
name: z.string().min(2, 'Name muss mindestens 2 Zeichen lang sein'), name: z.string().min(2, 'Name muss mindestens 2 Zeichen lang sein'),
description: z.string().optional(), description: z.string().optional(),
price: z.coerce.number().min(0, 'Preis darf nicht negativ sein'), price: z.coerce.number().min(0, 'Preis darf nicht negativ sein'),
is_required: z.boolean().default(false), is_required: z.boolean().default(false),
requirements: z.string().optional().default(''), // Will be converted to array requirements: z.array(z.string()).default([]),
exclusions: z.string().optional().default(''), // Will be converted to array exclusions: z.array(z.string()).default([]),
}) })
const productSchema = z.object({ const productSchema = z.object({
@@ -72,12 +73,13 @@ export function CreateProductDialog({ children, categories, product }: { childre
category_id: product?.category_id || '', category_id: product?.category_id || '',
billing_interval: product?.billing_interval || 'monthly', billing_interval: product?.billing_interval || 'monthly',
modules: product?.modules?.map(m => ({ modules: product?.modules?.map(m => ({
id: m.id,
name: m.name, name: m.name,
description: m.description || '', description: m.description || '',
price: m.price, price: m.price,
is_required: false, is_required: false,
requirements: m.requirements?.join(', ') || '', requirements: m.requirements || [],
exclusions: m.exclusions?.join(', ') || '', exclusions: m.exclusions || [],
})) || [], })) || [],
}, },
}) })
@@ -92,8 +94,7 @@ export function CreateProductDialog({ children, categories, product }: { childre
const { modules, ...productData } = values const { modules, ...productData } = values
const formattedModules = modules.map(m => ({ const formattedModules = modules.map(m => ({
...m, ...m,
requirements: m.requirements ? m.requirements.split(',').map(s => s.trim()).filter(Boolean) : [], id: m.id || (typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).substring(2, 15)),
exclusions: m.exclusions ? m.exclusions.split(',').map(s => s.trim()).filter(Boolean) : [],
})) }))
if (product) { if (product) {
@@ -243,103 +244,184 @@ export function CreateProductDialog({ children, categories, product }: { childre
variant="outline" variant="outline"
size="sm" size="sm"
className="border-primary/50 text-primary hover:bg-primary/10" className="border-primary/50 text-primary hover:bg-primary/10"
onClick={() => append({ name: '', price: 0, is_required: false, description: '', requirements: '', exclusions: '' })} onClick={() => append({
id: typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).substring(2, 15),
name: '',
price: 0,
is_required: false,
description: '',
requirements: [],
exclusions: []
})}
> >
<Plus className="w-4 h-4 mr-2" /> Modul hinzufügen <Plus className="w-4 h-4 mr-2" /> Modul hinzufügen
</Button> </Button>
</div> </div>
{fields.map((field, index) => ( {fields.map((field, index) => {
<div key={field.id} className="p-4 rounded-lg bg-white/5 border border-white/10 space-y-4 relative group"> const allModules = form.watch('modules') || []
<Button const otherModules = allModules
type="button" .map((m, idx) => ({
variant="ghost" id: m.id || field.id,
size="icon" name: m.name || `Modul ${idx + 1}`,
className="absolute top-2 right-2 h-8 w-8 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity" }))
onClick={() => remove(index)} .filter((_, idx) => idx !== index)
>
<X className="h-4 w-4" />
</Button>
<div className="grid grid-cols-2 gap-4"> return (
<FormField <div key={field.id} className="p-4 rounded-lg bg-white/5 border border-white/10 space-y-4 relative group">
control={form.control} <Button
name={`modules.${index}.name`} type="button"
render={({ field }) => ( variant="ghost"
<FormItem> size="icon"
<FormLabel className="text-white">Modulname</FormLabel> className="absolute top-2 right-2 h-8 w-8 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
<FormControl> onClick={() => remove(index)}
<Input placeholder="z.B. Cloud Storage" className="bg-white/10 border-white/10 text-white placeholder:text-slate-400" {...field} /> >
</FormControl> <X className="h-4 w-4" />
<FormMessage /> </Button>
</FormItem>
)}
/>
<FormField
control={form.control}
name={`modules.${index}.price`}
render={({ field }) => (
<FormItem>
<FormLabel className="text-white">Aufpreis ()</FormLabel>
<FormControl>
<Input type="number" step="0.01" className="bg-white/10 border-white/10 text-white" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<FormField <FormField
control={form.control} control={form.control}
name={`modules.${index}.requirements`} name={`modules.${index}.name`}
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel className="text-white">Benötigt (IDs, kommagetrennt)</FormLabel> <FormLabel className="text-white">Modulname</FormLabel>
<FormControl> <FormControl>
<Input placeholder="UUIDs..." className="bg-white/10 border-white/10 text-xs text-white" {...field} /> <Input placeholder="z.B. Cloud Storage" className="bg-white/10 border-white/10 text-white placeholder:text-slate-400" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}
/> />
<FormField <FormField
control={form.control} control={form.control}
name={`modules.${index}.exclusions`} name={`modules.${index}.price`}
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel className="text-white">Schließt aus (IDs, kommagetrennt)</FormLabel> <FormLabel className="text-white">Aufpreis ()</FormLabel>
<FormControl> <FormControl>
<Input placeholder="UUIDs..." className="bg-white/10 border-white/10 text-xs text-white" {...field} /> <Input type="number" step="0.01" className="bg-white/10 border-white/10 text-white" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}
/> />
</div> </div>
<div className="flex items-center space-x-2"> <div className="grid grid-cols-2 gap-4 border border-white/10 rounded-lg p-3 bg-black/20">
<FormField {/* Requirements Selection Matrix */}
control={form.control} <FormField
name={`modules.${index}.is_required`} control={form.control}
render={({ field }) => ( name={`modules.${index}.requirements`}
<FormItem className="flex flex-row items-start space-x-3 space-y-0"> render={({ field: reqField }) => (
<FormControl> <div className="space-y-2">
<Checkbox <FormLabel className="text-white text-xs font-semibold">Benötigt Module</FormLabel>
checked={field.value} <ScrollArea className="h-28 border border-white/5 rounded p-2 bg-white/5">
onCheckedChange={field.onChange} {otherModules.length === 0 ? (
/> <p className="text-[10px] text-slate-500 italic">Keine anderen Module vorhanden.</p>
</FormControl> ) : (
<div className="space-y-1 leading-none"> <div className="space-y-1.5">
<FormLabel className="text-white">Erforderlich</FormLabel> {otherModules.map(other => {
const checked = (reqField.value || []).includes(other.id)
return (
<div key={other.id} className="flex items-center space-x-2">
<Checkbox
id={`req-${index}-${other.id}`}
checked={checked}
onCheckedChange={(checkedState) => {
const currentVal = reqField.value || []
if (checkedState) {
reqField.onChange([...currentVal, other.id])
} else {
reqField.onChange(currentVal.filter(id => id !== other.id))
}
}}
/>
<label
htmlFor={`req-${index}-${other.id}`}
className="text-xs text-slate-300 cursor-pointer select-none truncate block max-w-[180px]"
title={other.name}
>
{other.name}
</label>
</div>
)
})}
</div>
)}
</ScrollArea>
</div> </div>
</FormItem> )}
)} />
/>
{/* Exclusions Selection Matrix */}
<FormField
control={form.control}
name={`modules.${index}.exclusions`}
render={({ field: exclField }) => (
<div className="space-y-2">
<FormLabel className="text-white text-xs font-semibold">Schließt aus</FormLabel>
<ScrollArea className="h-28 border border-white/5 rounded p-2 bg-white/5">
{otherModules.length === 0 ? (
<p className="text-[10px] text-slate-500 italic">Keine anderen Module vorhanden.</p>
) : (
<div className="space-y-1.5">
{otherModules.map(other => {
const checked = (exclField.value || []).includes(other.id)
return (
<div key={other.id} className="flex items-center space-x-2">
<Checkbox
id={`excl-${index}-${other.id}`}
checked={checked}
onCheckedChange={(checkedState) => {
const currentVal = exclField.value || []
if (checkedState) {
exclField.onChange([...currentVal, other.id])
} else {
exclField.onChange(currentVal.filter(id => id !== other.id))
}
}}
/>
<label
htmlFor={`excl-${index}-${other.id}`}
className="text-xs text-slate-300 cursor-pointer select-none truncate block max-w-[180px]"
title={other.name}
>
{other.name}
</label>
</div>
)
})}
</div>
)}
</ScrollArea>
</div>
)}
/>
</div>
<div className="flex items-center space-x-2">
<FormField
control={form.control}
name={`modules.${index}.is_required`}
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel className="text-white">Erforderlich</FormLabel>
</div>
</FormItem>
)}
/>
</div>
</div> </div>
</div> )
))} })}
{fields.length === 0 && ( {fields.length === 0 && (
<div className="text-center py-6 border-2 border-dashed border-white/5 rounded-lg text-slate-400 text-sm"> <div className="text-center py-6 border-2 border-dashed border-white/5 rounded-lg text-slate-400 text-sm">

View File

@@ -48,12 +48,18 @@ function toggleModuleInList(
): string[] { ): string[] {
const isSelected = currentIds.includes(toggleId) const isSelected = currentIds.includes(toggleId)
if (isSelected) { if (isSelected) {
const next = currentIds.filter(id => id !== toggleId) // Recursive removal: repeatedly filter until no more dependent modules are removed
// cascade: remove modules that required this one let next = currentIds.filter(id => id !== toggleId)
return next.filter(mId => { let changed = true
const m = modules.find(mod => mod.id === mId) while (changed) {
return !m?.requirements || m.requirements.every(reqId => next.includes(reqId) || reqId === toggleId) const beforeLength = next.length
}).filter(id => id !== toggleId) next = next.filter(mId => {
const m = modules.find(mod => mod.id === mId)
return !m?.requirements || m.requirements.every(reqId => next.includes(reqId))
})
changed = next.length !== beforeLength
}
return next
} else { } else {
const module = modules.find(m => m.id === toggleId) const module = modules.find(m => m.id === toggleId)
if (module?.exclusions?.some(exId => currentIds.includes(exId))) return currentIds if (module?.exclusions?.some(exId => currentIds.includes(exId))) return currentIds

View File

@@ -7,6 +7,7 @@ import { renderToBuffer } from '@react-pdf/renderer'
import React from 'react' import React from 'react'
import { buildCustomerSnapshot, buildOrderSnapshot } from '@/lib/license-transform' import { buildCustomerSnapshot, buildOrderSnapshot } from '@/lib/license-transform'
import type { Category, EndCustomer, Order, Product, Profile, WizardSelections } from '@/lib/types' import type { Category, EndCustomer, Order, Product, Profile, WizardSelections } from '@/lib/types'
import { getProducts, getCategories } from '@/lib/actions/products'
// ─── Hilfsfunktionen ───────────────────────────────────────────────────────── // ─── Hilfsfunktionen ─────────────────────────────────────────────────────────
@@ -48,22 +49,62 @@ function hashOrderSnapshot(snapshot: object): string {
*/ */
export async function submitOrder(params: { export async function submitOrder(params: {
selections: WizardSelections selections: WizardSelections
products: Product[] products?: Product[]
categories: Category[] categories?: Category[]
customerProfile: Partial<Profile> customerProfile: Partial<Profile>
endCustomerId?: string | null endCustomerId?: string | null
endCustomer?: EndCustomer | null endCustomer?: EndCustomer | null
}): Promise<Order> { }): Promise<Order> {
const { selections, products, categories, customerProfile, endCustomerId, endCustomer } = params const { selections, customerProfile, endCustomerId, endCustomer } = params
const supabase = await createClient() const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser() const { data: { user } } = await supabase.auth.getUser()
if (!user) throw new Error('Not authenticated') if (!user) throw new Error('Not authenticated')
// Fetch catalog directly from DB to prevent client tampering
const dbProducts = await getProducts()
const dbCategories = await getCategories()
// ─── Constraint Validation ──────────────────────────────────────────────────
for (const cat of dbCategories) {
const sel = selections[cat.id]
if (cat.is_required && (!sel || !sel.productId)) {
throw new Error(`Die Kategorie "${cat.name}" ist ein Pflichtfeld, wurde aber nicht ausgewählt.`)
}
if (sel?.productId) {
const prod = dbProducts.find(p => p.id === sel.productId)
if (!prod) {
throw new Error(`Das ausgewählte Produkt für Kategorie "${cat.name}" wurde nicht gefunden.`)
}
// Validate selected modules
for (const mId of sel.moduleIds) {
const mod = prod.modules?.find(m => m.id === mId)
if (!mod) {
throw new Error(`Das Modul mit ID "${mId}" gehört nicht zum Produkt "${prod.name}".`)
}
// Requirements check
if (mod.requirements && mod.requirements.length > 0) {
const missing = mod.requirements.filter(reqId => !sel.moduleIds.includes(reqId))
if (missing.length > 0) {
throw new Error(`Das Modul "${mod.name}" setzt die Aktivierung anderer Module voraus.`)
}
}
// Exclusions check
if (mod.exclusions && mod.exclusions.length > 0) {
const conflicting = mod.exclusions.filter(exId => sel.moduleIds.includes(exId))
if (conflicting.length > 0) {
throw new Error(`Das Modul "${mod.name}" schließt die Kombination mit anderen gewählten Modulen aus.`)
}
}
}
}
}
// 1. Snapshots aufbauen // 1. Snapshots aufbauen
// Wenn Endkunde vorhanden: dessen Daten einfrieren; sonst Partner-Profil (Fallback) // Wenn Endkunde vorhanden: dessen Daten einfrieren; sonst Partner-Profil (Fallback)
const customerSnapshot = buildCustomerSnapshot(customerProfile, endCustomer ?? null) const customerSnapshot = buildCustomerSnapshot(customerProfile, endCustomer ?? null)
const orderSnapshot = buildOrderSnapshot(selections, products, categories) const orderSnapshot = buildOrderSnapshot(selections, dbProducts, dbCategories)
// 2. Idempotenz-Guard: Prüfen ob identische Bestellung in den letzten 30s existiert // 2. Idempotenz-Guard: Prüfen ob identische Bestellung in den letzten 30s existiert
const orderHash = hashOrderSnapshot(orderSnapshot) const orderHash = hashOrderSnapshot(orderSnapshot)

View File

@@ -3,6 +3,7 @@
import { createClient } from '@/lib/supabase/server' import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { Category, Product, ProductModule } from '../types' import { Category, Product, ProductModule } from '../types'
import { randomUUID } from 'crypto'
export async function getProducts() { export async function getProducts() {
const supabase = await createClient() const supabase = await createClient()
@@ -64,7 +65,10 @@ export async function deleteCategory(id: string) {
revalidatePath('/order') revalidatePath('/order')
} }
export async function createProduct(product: Omit<Product, 'id' | 'created_at' | 'updated_at'>, modules: Omit<ProductModule, 'id' | 'product_id' | 'created_at'>[]) { export async function createProduct(
product: Omit<Product, 'id' | 'created_at' | 'updated_at'>,
modules: Omit<ProductModule, 'product_id' | 'created_at'>[]
) {
const supabase = await createClient() const supabase = await createClient()
// Start a transaction-like approach (Supabase doesn't have cross-table transactions easily in one call via JS client without RPC) // Start a transaction-like approach (Supabase doesn't have cross-table transactions easily in one call via JS client without RPC)
@@ -77,7 +81,15 @@ export async function createProduct(product: Omit<Product, 'id' | 'created_at' |
if (productError) throw productError if (productError) throw productError
if (modules.length > 0) { if (modules.length > 0) {
const modulesWithId = modules.map(m => ({ ...m, product_id: newProduct.id })) const modulesWithId = modules.map(m => ({
id: m.id || randomUUID(),
product_id: newProduct.id,
name: m.name,
description: m.description || null,
price: m.price,
requirements: m.requirements || [],
exclusions: m.exclusions || [],
}))
const { error: modulesError } = await supabase const { error: modulesError } = await supabase
.from('product_modules') .from('product_modules')
.insert(modulesWithId) .insert(modulesWithId)
@@ -106,12 +118,13 @@ export async function updateProduct(id: string, product: Partial<Product>, modul
if (modules.length > 0) { if (modules.length > 0) {
const modulesWithId = modules.map(m => ({ const modulesWithId = modules.map(m => ({
id: m.id || randomUUID(),
product_id: id,
name: m.name, name: m.name,
description: m.description || null, description: m.description || null,
price: m.price, price: m.price,
requirements: m.requirements || [], requirements: m.requirements || [],
exclusions: m.exclusions || [], exclusions: m.exclusions || [],
product_id: id
})) }))
const { error: modulesError } = await supabase const { error: modulesError } = await supabase
.from('product_modules') .from('product_modules')
@@ -120,6 +133,7 @@ export async function updateProduct(id: string, product: Partial<Product>, modul
if (modulesError) throw modulesError if (modulesError) throw modulesError
} }
revalidatePath('/admin/products') revalidatePath('/admin/products')
revalidatePath('/order') revalidatePath('/order')
} }

View File

@@ -1,22 +1,9 @@
// utils/mail.ts simple wrapper around nodemailer // utils/mail.ts simple wrapper around nodemailer
import nodemailer from 'nodemailer'; import nodemailer from 'nodemailer';
import { createAdminClient } from '@/lib/supabase/admin';
// Load SMTP configuration from environment variables
const smtpConfig = {
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
secure: process.env.SMTP_SECURE === 'true' || process.env.SMTP_SECURE === '1', // true for 465, false for other ports
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
};
// Create a reusable transporter. If any required var is missing, nodemailer will throw on send.
const transporter = nodemailer.createTransport(smtpConfig);
/** /**
* Send an email. * Send an email using database-configured SMTP settings (or environment variable fallback).
* @param to Recipient address * @param to Recipient address
* @param subject Subject line * @param subject Subject line
* @param text Plaintext body * @param text Plaintext body
@@ -33,12 +20,46 @@ export async function sendMail({
text: string; text: string;
html?: string; html?: string;
}) { }) {
// Query custom SMTP settings from database
const supabase = createAdminClient();
const { data: dbSettings } = await supabase
.from('settings')
.select('*')
.eq('id', 'smtp')
.maybeSingle();
// Resolve config from DB or environment variables
const host = dbSettings?.host || process.env.SMTP_HOST;
const port = dbSettings?.port ? Number(dbSettings.port) : Number(process.env.SMTP_PORT);
const secure = dbSettings
? !!dbSettings.secure
: (process.env.SMTP_SECURE === 'true' || process.env.SMTP_SECURE === '1');
const user = dbSettings?.user || process.env.SMTP_USER;
const pass = dbSettings?.pass || process.env.SMTP_PASS;
if (!host || !user) {
throw new Error('SMTP host and user must be configured (either in settings database table or environment variables).');
}
// Create transporter dynamically on send request
const transporter = nodemailer.createTransport({
host,
port,
secure,
auth: {
user,
pass,
},
});
const info = await transporter.sendMail({ const info = await transporter.sendMail({
from: smtpConfig.auth.user, from: user,
to, to,
subject, subject,
text, text,
html, html,
}); });
return info; return info;
} }