Compare commits

..

6 Commits

Author SHA1 Message Date
DanielS
b3ae720136 refactor(admin): optimize db tools with bento cockpit
Some checks failed
Staging Build / build (push) Failing after 32s
2026-08-06 17:49:42 +02:00
DanielS
d02703af8b refactor(admin): optimize smtp settings with bento grid 2026-08-06 17:49:37 +02:00
DanielS
abd8f54ef7 refactor(admin): redesign general settings into bento grid 2026-08-06 17:49:33 +02:00
DanielS
c08237aa73 refactor(wizard): redesign step summary layout with step indicator 2026-08-06 17:44:51 +02:00
DanielS
6a95896361 feat(wizard): add order notes field and scroll container 2026-08-06 17:42:05 +02:00
DanielS
b40f8018f7 refactor(wizard): hide legacy license date input 2026-08-06 17:42:01 +02:00
6 changed files with 870 additions and 769 deletions

View File

@@ -1,16 +1,43 @@
/* Admin Settings with Database Import / Export functionality */ /* Admin Settings with Bento Grid Layout & Motion Animations */
'use client'; 'use client';
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Switch } from '@/components/ui/switch'; import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { Download, Upload, Database, AlertTriangle, Loader2, KeyRound, Server, CheckCircle2, XCircle, Eye, EyeOff, Wifi } from 'lucide-react'; import {
Download, Upload, Database, AlertTriangle, Loader2, KeyRound,
Server, CheckCircle2, XCircle, Eye, EyeOff, Wifi, Sliders, ShieldAlert, FileArchive
} from 'lucide-react';
import { createClient } from '@/lib/supabase/client'; import { createClient } from '@/lib/supabase/client';
import { saveLicServerConfig, testLicServerConnection } from '@/lib/actions/licserver-config'; import { saveLicServerConfig, testLicServerConnection } from '@/lib/actions/licserver-config';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
staggerChildren: 0.1
}
}
};
const cardVariants = {
hidden: { opacity: 0, y: 20 },
visible: {
opacity: 1,
y: 0,
transition: {
type: 'spring' as const,
stiffness: 80,
damping: 15
}
}
};
export default function AdminSettings() { export default function AdminSettings() {
const [demoActive, setDemoActive] = useState(true); const [demoActive, setDemoActive] = useState(true);
const [exporting, setExporting] = useState(false); const [exporting, setExporting] = useState(false);
@@ -40,13 +67,14 @@ export default function AdminSettings() {
router.push('/auth/login'); router.push('/auth/login');
return; return;
} }
const { data: userData, error: userError } = await supabase
.from('users')
.select('role')
.eq('id', user.id)
.single();
if (userError || !userData || userData.role === 'verwaltung') { // Parallele Abfrage von User-Rolle & LicServer Settings
const [userRes, licRes] = await Promise.all([
supabase.from('users').select('role').eq('id', user.id).single(),
supabase.from('settings').select('licserver_base_url, licserver_api_key').eq('id', 'licserver').maybeSingle()
]);
if (userRes.error || !userRes.data || userRes.data.role === 'verwaltung') {
router.push('/admin'); router.push('/admin');
return; return;
} }
@@ -54,19 +82,9 @@ export default function AdminSettings() {
const state = localStorage.getItem('demo_banner_disabled') !== 'true'; const state = localStorage.getItem('demo_banner_disabled') !== 'true';
setDemoActive(state); setDemoActive(state);
// Load current LicServer config from DB if (licRes.data) {
try { setLicUrl(licRes.data.licserver_base_url || '');
const { data: licRow } = await supabase setLicKey(licRes.data.licserver_api_key || '');
.from('settings')
.select('licserver_base_url, licserver_api_key')
.eq('id', 'licserver')
.single();
if (licRow) {
setLicUrl(licRow.licserver_base_url || '');
setLicKey(licRow.licserver_api_key || '');
}
} catch (dbErr) {
console.error("Fehler beim Laden der LicServer-Einstellungen:", dbErr);
} }
} catch (err) { } catch (err) {
console.error("Fehler bei checkAccess in Einstellungen:", err); console.error("Fehler bei checkAccess in Einstellungen:", err);
@@ -148,204 +166,230 @@ export default function AdminSettings() {
} }
return ( return (
<div className="p-6 max-w-4xl mx-auto text-slate-900 dark:text-white space-y-8"> <div className="p-6 max-w-7xl mx-auto text-slate-900 dark:text-white space-y-6">
{/* Page Header */} {/* Header */}
<div> <motion.div
<h1 className="text-3xl font-extrabold tracking-tight">Admin Einstellungen</h1> initial={{ opacity: 0, y: -10 }}
<p className="text-slate-500 dark:text-slate-400 text-sm mt-1"> animate={{ opacity: 1, y: 0 }}
Verwalten Sie globale Shopeinstellungen. className="flex items-center justify-between"
</p> >
</div>
{/* Allgemeine Einstellungen */}
<div className="p-5 bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-white/10 shadow-sm space-y-4">
<h2 className="text-lg font-bold flex items-center gap-2">
Allgemeine Einstellungen
</h2>
<div className="flex items-center justify-between p-4 bg-slate-50 dark:bg-white/5 rounded-lg border border-slate-100 dark:border-white/5">
<div>
<p className="font-medium text-sm text-slate-900 dark:text-white">Demo-Warnmeldungen</p>
<p className="text-xs text-slate-500 dark:text-slate-400">Schaltet gelbe Banner ein oder aus.</p>
</div>
<Switch checked={demoActive} onCheckedChange={toggleDemo} />
</div>
</div>
{/* Datenimport & -export */}
<div className="p-5 bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-white/10 shadow-sm space-y-6">
<div> <div>
<h2 className="text-lg font-bold flex items-center gap-2"> <h1 className="text-3xl font-extrabold tracking-tight">Admin Einstellungen</h1>
<Database className="w-5 h-5 text-primary" /> <p className="text-slate-400 text-xs mt-1">
Datenimport & -export Zentrales Bento-Dashboard für System-, Backup- und Lizenz-Konfigurationen.
</h2>
<p className="text-slate-500 dark:text-slate-400 text-xs mt-1">
Sichern Sie Ihre gesamte Instanz oder stellen Sie Daten wieder her.
</p> </p>
</div> </div>
</motion.div>
{statusMsg && ( {/* Dynamic Status Notification */}
<div className={`p-4 rounded-lg text-sm border ${statusType === 'success' ? 'bg-green-500/10 border-green-500/20 text-green-600 dark:text-green-400' : {statusMsg && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
className={`p-3 rounded-xl text-sm border ${
statusType === 'success' ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' :
statusType === 'error' ? 'bg-destructive/10 border-destructive/20 text-destructive' : statusType === 'error' ? 'bg-destructive/10 border-destructive/20 text-destructive' :
'bg-blue-500/10 border-blue-500/20 text-blue-600 dark:text-blue-400' 'bg-sky-500/10 border-sky-500/20 text-sky-400'
}`}> }`}
{statusMsg} >
</div> {statusMsg}
)} </motion.div>
)}
<div className="grid md:grid-cols-2 gap-6"> {/* Bento Grid Container */}
{/* Export Card */} <motion.div
<div className="p-5 bg-slate-50 dark:bg-white/5 border border-slate-100 dark:border-white/5 rounded-xl flex flex-col justify-between space-y-4"> variants={containerVariants}
<div className="space-y-2"> initial="hidden"
<h3 className="font-bold text-sm flex items-center gap-2 text-slate-800 dark:text-white"> animate="visible"
<Download className="w-4 h-4 text-primary" /> className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-5"
Daten exportieren >
</h3> {/* Bento Item 1: System Modus & Banner (1 Spalte) */}
<p className="text-xs text-slate-500 dark:text-slate-400 leading-relaxed"> <motion.div
Lädt alle Kategorien, Produkte, Module, Firmen, Endkunden, Bestellungen und SMTP-Einstellungen als ZIP-Datei herunter. variants={cardVariants}
whileHover={{ y: -3 }}
className="p-5 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md flex flex-col justify-between space-y-4 hover:border-sky-500/30 transition-all duration-300 shadow-md"
>
<div className="space-y-3">
<div className="w-10 h-10 rounded-xl bg-sky-500/10 border border-sky-500/20 text-sky-400 flex items-center justify-center">
<Sliders className="w-5 h-5" />
</div>
<div>
<h3 className="font-bold text-base text-white">System Banner</h3>
<p className="text-xs text-slate-400 mt-1 leading-relaxed">
Gelbe Demo-Warnmeldungen im gesamten Shop aktivieren oder stummschalten.
</p> </p>
</div> </div>
</div>
<div className="flex items-center justify-between pt-3 border-t border-slate-800/80">
<span className="text-xs font-semibold text-slate-300">Banner aktiv</span>
<Switch checked={demoActive} onCheckedChange={toggleDemo} />
</div>
</motion.div>
{/* Bento Item 2: Daten Export (1 Spalte) */}
<motion.div
variants={cardVariants}
whileHover={{ y: -3 }}
className="p-5 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md flex flex-col justify-between space-y-4 hover:border-blue-500/30 transition-all duration-300 shadow-md"
>
<div className="space-y-3">
<div className="w-10 h-10 rounded-xl bg-blue-500/10 border border-blue-500/20 text-blue-400 flex items-center justify-center">
<Download className="w-5 h-5" />
</div>
<div>
<h3 className="font-bold text-base text-white">DB Backup</h3>
<p className="text-xs text-slate-400 mt-1 leading-relaxed">
Lädt alle Produkte, Firmen, Lizenzen & Einstellungen als ZIP-Archiv herunter.
</p>
</div>
</div>
<Button
onClick={handleExport}
disabled={exporting || importing}
className="w-full bg-blue-600 hover:bg-blue-500 text-white rounded-xl h-10 text-xs font-bold"
>
{exporting ? (
<><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Export läuft...</>
) : (
<><Download className="w-4 h-4 mr-2" /> ZIP Export</>
)}
</Button>
</motion.div>
{/* Bento Item 3: Daten Import (2 Spalten / Span 2 auf Desktop) */}
<motion.div
variants={cardVariants}
whileHover={{ y: -3 }}
className="md:col-span-1 lg:col-span-2 p-5 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md flex flex-col justify-between space-y-4 hover:border-amber-500/30 transition-all duration-300 shadow-md"
>
<div className="space-y-3">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-xl bg-amber-500/10 border border-amber-500/20 text-amber-400 flex items-center justify-center">
<Upload className="w-5 h-5" />
</div>
<span className="text-[10px] font-bold uppercase tracking-wider text-amber-400 bg-amber-500/10 px-2.5 py-1 rounded-full border border-amber-500/20 flex items-center gap-1">
<ShieldAlert className="w-3 h-3" /> Überschreibt DB
</span>
</div>
<div>
<h3 className="font-bold text-base text-white">Daten Wiederherstellung</h3>
<p className="text-xs text-slate-400 mt-1 leading-relaxed">
Spielen Sie eine gesicherte ZIP-Sicherungsdatei ein. Warnung: Überschreibt aktuelle Datenbankinhalte.
</p>
</div>
</div>
<div className="grid sm:grid-cols-2 gap-3 pt-2">
<div className="relative border border-dashed border-slate-700/80 rounded-xl p-3 hover:bg-slate-800/50 transition cursor-pointer flex items-center justify-center text-center">
<input
type="file"
accept=".zip"
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
disabled={exporting || importing}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
/>
<span className="text-xs font-medium text-slate-300 truncate px-2 flex items-center gap-1.5">
<FileArchive className="w-4 h-4 text-amber-400 shrink-0" />
{selectedFile ? selectedFile.name : 'ZIP-Datei auswählen'}
</span>
</div>
<Button <Button
onClick={handleExport} onClick={handleImport}
disabled={exporting || importing} disabled={!selectedFile || exporting || importing}
className="w-full bg-primary hover:bg-primary/90 text-white" variant="outline"
className="w-full border-amber-500/30 text-amber-300 hover:bg-amber-500/10 rounded-xl h-10 text-xs font-bold"
> >
{exporting ? ( {importing ? (
<><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Export läuft...</> <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Importiert...</>
) : ( ) : (
<><Download className="w-4 h-4 mr-2" /> ZIP-Backup herunterladen</> <><Upload className="w-4 h-4 mr-2" /> ZIP Einspielen</>
)} )}
</Button> </Button>
</div> </div>
</motion.div>
{/* Import Card */} {/* Bento Item 4: LicServer Konfiguration (Breites Bento: 4 Spalten auf Large) */}
<div className="p-5 bg-slate-50 dark:bg-white/5 border border-slate-100 dark:border-white/5 rounded-xl flex flex-col justify-between space-y-4"> <motion.div
<div className="space-y-2"> variants={cardVariants}
<h3 className="font-bold text-sm flex items-center gap-2 text-slate-800 dark:text-white"> whileHover={{ y: -3 }}
<Upload className="w-4 h-4 text-amber-500" /> className="md:col-span-3 lg:col-span-4 p-6 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md space-y-5 hover:border-violet-500/30 transition-all duration-300 shadow-md"
Daten importieren >
</h3> <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-800/80 pb-4">
<div className="flex items-start gap-2 bg-amber-500/10 border border-amber-500/20 p-2.5 rounded-lg text-amber-600 dark:text-amber-400 text-[11px] leading-snug"> <div className="flex items-center gap-3">
<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" /> <div className="w-10 h-10 rounded-xl bg-violet-500/10 border border-violet-500/20 text-violet-400 flex items-center justify-center">
<span> <KeyRound className="w-5 h-5" />
<strong>Warnung:</strong> Der Import überschreibt alle Daten dieser Instanz unwiderruflich! </div>
</span> <div>
<h3 className="font-bold text-lg text-white">CASPOS Lizenzserver (LicServer)</h3>
<p className="text-xs text-slate-400">REST API-Anbindung für automatisierte Lizenzierung</p>
</div> </div>
</div> </div>
<div className="space-y-3"> {/* LicServer Status Pill */}
<div className="relative border border-dashed border-slate-200 dark:border-white/10 rounded-lg p-3 hover:bg-slate-100/50 dark:hover:bg-white/5 transition"> {licStatus && (
<input <div className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-semibold border ${
type="file" licStatus.ok
accept=".zip" ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400'
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)} : 'bg-amber-500/10 border-amber-500/20 text-amber-400'
disabled={exporting || importing} }`}>
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed" {licStatus.ok ? <CheckCircle2 className="w-3.5 h-3.5" /> : <XCircle className="w-3.5 h-3.5" />}
/> {licStatus.message}
<div className="text-center text-xs text-slate-500 dark:text-slate-400">
{selectedFile ? (
<span className="text-primary font-semibold">{selectedFile.name}</span>
) : (
"ZIP-Datei auswählen oder hierher ziehen"
)}
</div>
</div> </div>
)}
</div>
<Button {licMsg && (
onClick={handleImport} <div className={`p-3 rounded-xl text-xs font-medium border ${
disabled={!selectedFile || exporting || importing} licMsgType === 'success' ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' : 'bg-destructive/10 border-destructive/20 text-destructive'
variant="secondary" }`}>
className="w-full border border-slate-200 dark:border-white/10" {licMsg}
>
{importing ? (
<><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Import läuft...</>
) : (
<><Upload className="w-4 h-4 mr-2" /> ZIP-Backup einspielen</>
)}
</Button>
</div> </div>
</div> )}
</div>
</div>
{/* LicServer Konfiguration */}
<div className="p-5 bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-white/10 shadow-sm space-y-5">
<div>
<h2 className="text-lg font-bold flex items-center gap-2">
<KeyRound className="w-5 h-5 text-violet-500" />
LicServer Konfiguration
</h2>
<p className="text-slate-500 dark:text-slate-400 text-xs mt-1">
Verbindungseinstellungen zum CASPOS Lizenzserver.
</p>
</div>
{/* Status Message */} <div className="grid md:grid-cols-2 gap-4">
{licMsg && ( {/* Base URL */}
<div className={`p-3 rounded-lg text-sm border ${licMsgType === 'success' <div className="space-y-1.5">
? 'bg-green-500/10 border-green-500/20 text-green-600 dark:text-green-400' <Label htmlFor="lic-url" className="text-xs font-bold text-slate-300 flex items-center gap-1.5">
: 'bg-destructive/10 border-destructive/20 text-destructive' <Server className="w-3.5 h-3.5 text-slate-400" /> Server URL
}`}> </Label>
{licMsg}
</div>
)}
{/* Connection Test Result */}
{licStatus && (
<div className={`flex items-center gap-2 p-3 rounded-lg text-sm border ${licStatus.ok
? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-600 dark:text-emerald-400'
: 'bg-amber-500/10 border-amber-500/20 text-amber-600 dark:text-amber-400'
}`}>
{licStatus.ok
? <CheckCircle2 className="w-4 h-4 shrink-0" />
: <XCircle className="w-4 h-4 shrink-0" />}
{licStatus.message}
</div>
)}
<div className="grid md:grid-cols-2 gap-4">
{/* Base URL */}
<div className="space-y-1.5">
<Label htmlFor="lic-url" className="text-xs font-medium flex items-center gap-1.5">
<Server className="w-3.5 h-3.5 text-slate-400" /> Server URL
</Label>
<Input
id="lic-url"
value={licUrl}
onChange={e => setLicUrl(e.target.value)}
placeholder="http://192.168.178.174:9980"
className="text-sm font-mono"
/>
<p className="text-[10px] text-slate-400">URL des CASPOS Lizenzservers</p>
</div>
{/* API Key */}
<div className="space-y-1.5">
<Label htmlFor="lic-key" className="text-xs font-medium flex items-center gap-1.5">
<KeyRound className="w-3.5 h-3.5 text-slate-400" /> API-Key
</Label>
<div className="relative">
<Input <Input
id="lic-key" id="lic-url"
type={showKey ? 'text' : 'password'} value={licUrl}
value={licKey} onChange={e => setLicUrl(e.target.value)}
onChange={e => setLicKey(e.target.value)} placeholder="http://192.168.178.174:9980"
placeholder="Ihr X-Api-Key" className="text-sm font-mono bg-slate-950/80 border-slate-800 text-white rounded-xl"
className="text-sm font-mono pr-10"
/> />
<button
type="button"
onClick={() => setShowKey(v => !v)}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white transition-colors"
aria-label={showKey ? 'Key verbergen' : 'Key anzeigen'}
>
{showKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div> </div>
{/* API Key */}
<div className="space-y-1.5">
<Label htmlFor="lic-key" className="text-xs font-bold text-slate-300 flex items-center gap-1.5">
<KeyRound className="w-3.5 h-3.5 text-slate-400" /> API-Key
</Label>
<div className="relative">
<Input
id="lic-key"
type={showKey ? 'text' : 'password'}
value={licKey}
onChange={e => setLicKey(e.target.value)}
placeholder="Ihr X-Api-Key"
className="text-sm font-mono pr-10 bg-slate-950/80 border-slate-800 text-white rounded-xl"
/>
<button
type="button"
onClick={() => setShowKey(v => !v)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white transition-colors"
aria-label={showKey ? 'Key verbergen' : 'Key anzeigen'}
>
{showKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div> </div>
</div> </div>
{/* Actions */} {/* Action Buttons */}
<div className="flex gap-3 pt-1"> <div className="flex items-center justify-end gap-3 pt-2">
<Button <Button
id="lic-save-btn" id="lic-save-btn"
disabled={licSaving || licTesting} disabled={licSaving || licTesting}
@@ -358,7 +402,7 @@ export default function AdminSettings() {
setLicMsg(res.success ? 'Konfiguration gespeichert.' : (res.error || 'Fehler beim Speichern')); setLicMsg(res.success ? 'Konfiguration gespeichert.' : (res.error || 'Fehler beim Speichern'));
setLicSaving(false); setLicSaving(false);
}} }}
className="bg-violet-600 hover:bg-violet-500 text-white" className="bg-violet-600 hover:bg-violet-500 text-white rounded-xl px-5 h-10 text-xs font-bold"
> >
{licSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <KeyRound className="w-4 h-4 mr-2" />} {licSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <KeyRound className="w-4 h-4 mr-2" />}
Speichern Speichern
@@ -371,20 +415,19 @@ export default function AdminSettings() {
onClick={async () => { onClick={async () => {
setLicTesting(true); setLicTesting(true);
setLicStatus(null); setLicStatus(null);
// Save first, then test
await saveLicServerConfig(licUrl, licKey); await saveLicServerConfig(licUrl, licKey);
const result = await testLicServerConnection(); const result = await testLicServerConnection();
setLicStatus(result); setLicStatus(result);
setLicTesting(false); setLicTesting(false);
}} }}
className="border-white/10" className="border-slate-700 text-slate-300 hover:text-white rounded-xl px-5 h-10 text-xs font-bold"
> >
{licTesting ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Wifi className="w-4 h-4 mr-2" />} {licTesting ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Wifi className="w-4 h-4 mr-2" />}
Verbindung testen Verbindung testen
</Button> </Button>
</div> </div>
</div> </motion.div>
</motion.div>
</div> </div>
); );
} }

View File

@@ -1,9 +1,13 @@
"use client"; 'use client';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { createClient } from '@/lib/supabase/client'; import { createClient } from '@/lib/supabase/client';
import { Loader2 } from 'lucide-react'; import { Loader2, Mail, Server, ShieldCheck, Key, Send, CheckCircle2, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
interface Settings { interface Settings {
host: string; host: string;
@@ -13,39 +17,60 @@ interface Settings {
pass: string; pass: string;
} }
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: { staggerChildren: 0.1 }
}
};
const itemVariants = {
hidden: { opacity: 0, y: 15 },
visible: { opacity: 1, y: 0, transition: { type: 'spring' as const, stiffness: 80, damping: 15 } }
};
export default function SettingsPage() { export default function SettingsPage() {
const [settings, setSettings] = useState<Settings | null>(null); const [settings, setSettings] = useState<Settings | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [message, setMessage] = useState(''); const [message, setMessage] = useState('');
const [msgType, setMsgType] = useState<'success' | 'error' | ''>('');
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const router = useRouter(); const router = useRouter();
// Load current settings and verify access
useEffect(() => { useEffect(() => {
async function checkAccessAndLoad() { async function checkAccessAndLoad() {
const supabase = createClient(); try {
const { data: { user } } = await supabase.auth.getUser(); const supabase = createClient();
if (!user) { const { data: { user } } = await supabase.auth.getUser();
router.push('/auth/login'); if (!user) {
return; router.push('/auth/login');
} return;
const { data: userData } = await supabase }
.from('users')
.select('role')
.eq('id', user.id)
.single();
if (!userData || userData.role === 'verwaltung') {
router.push('/admin');
return;
}
fetch('/api/admin/smtp-settings') const [userRes, smtpRes] = await Promise.all([
.then((res) => res.json()) supabase.from('users').select('role').eq('id', user.id).single(),
.then((data) => { fetch('/api/admin/smtp-settings').then(res => res.json())
if (data.settings) setSettings(data.settings as Settings); ]);
else setMessage('Failed to load settings');
}) if (!userRes.data || userRes.data.role === 'verwaltung') {
.catch(() => setMessage('Failed to load settings')) router.push('/admin');
.finally(() => setLoading(false)); return;
}
if (smtpRes.settings) {
setSettings(smtpRes.settings as Settings);
} else {
setMessage('Fehler beim Laden der SMTP-Einstellungen.');
setMsgType('error');
}
} catch (err) {
setMessage('Fehler beim Laden der Einstellungen.');
setMsgType('error');
} finally {
setLoading(false);
}
} }
checkAccessAndLoad(); checkAccessAndLoad();
}, [router]); }, [router]);
@@ -62,110 +87,195 @@ export default function SettingsPage() {
const handleSave = async (e: React.FormEvent) => { const handleSave = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
setSaving(true);
setMessage(''); setMessage('');
const res = await fetch('/api/admin/smtp-settings', { try {
method: 'POST', const res = await fetch('/api/admin/smtp-settings', {
headers: { 'Content-Type': 'application/json' }, method: 'POST',
body: JSON.stringify(settings), headers: { 'Content-Type': 'application/json' },
}); body: JSON.stringify(settings),
const data = await res.json(); });
if (res.ok) setMessage('Settings saved'); const data = await res.json();
else setMessage(data.error || 'Error saving settings'); if (res.ok) {
setMessage('SMTP-Einstellungen erfolgreich gespeichert.');
setMsgType('success');
} else {
setMessage(data.error || 'Fehler beim Speichern.');
setMsgType('error');
}
} catch {
setMessage('Verbindungsfehler beim Speichern.');
setMsgType('error');
} finally {
setSaving(false);
}
}; };
const handleTestEmail = async () => { const handleTestEmail = async () => {
setTesting(true);
setMessage(''); setMessage('');
const testPayload = { try {
to: settings?.user || '', // send to the configured user address const testPayload = {
subject: 'Test Email from Webshop Admin', to: settings?.user || '',
text: 'This is a test email to verify SMTP configuration.', subject: 'Test-E-Mail aus dem CASPOS Webshop Admin',
}; text: 'Dies ist eine automatische Test-E-Mail zur Bestätigung der SMTP-Konfiguration.',
const res = await fetch('/api/admin/send-test-email', { };
method: 'POST', const res = await fetch('/api/admin/send-test-email', {
headers: { 'Content-Type': 'application/json' }, method: 'POST',
body: JSON.stringify(testPayload), headers: { 'Content-Type': 'application/json' },
}); body: JSON.stringify(testPayload),
const data = await res.json(); });
if (res.ok) setMessage('Test email sent successfully'); const data = await res.json();
else setMessage(data.error || 'Failed to send test email'); if (res.ok) {
setMessage('Test-E-Mail erfolgreich versendet.');
setMsgType('success');
} else {
setMessage(data.error || 'Versand der Test-E-Mail fehlgeschlagen.');
setMsgType('error');
}
} catch {
setMessage('Fehler beim Senden der Test-E-Mail.');
setMsgType('error');
} finally {
setTesting(false);
}
}; };
if (loading) return <div className="p-8 text-white flex justify-center items-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>; if (loading) {
return <div className="p-8 text-white flex justify-center items-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>;
}
return ( return (
<div className="max-w-2xl mx-auto p-8 bg-black/30 backdrop-blur-xl rounded-lg text-white"> <div className="p-6 max-w-5xl mx-auto text-slate-900 dark:text-white space-y-6">
<h1 className="text-2xl font-bold mb-6">SMTPEinstellungen</h1> {/* Header */}
{message && <p className="mb-4 text-yellow-300">{message}</p>} <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="space-y-1">
<form onSubmit={handleSave} className="space-y-4"> <h1 className="text-3xl font-extrabold tracking-tight flex items-center gap-3">
<label className="flex flex-col"> <Mail className="w-8 h-8 text-sky-400" />
Host SMTP-Einstellungen
<input </h1>
name="host" <p className="text-slate-400 text-xs">
type="text" Konfigurieren Sie den E-Mail-Server für transaktionale Benachrichtigungen und Bestellbestätigungen.
required </p>
value={settings?.host ?? ''} </motion.div>
onChange={handleChange}
className="mt-1 p-2 rounded bg-black/20 border border-white/20" {/* Dynamic Status Message */}
/> {message && (
</label> <motion.div
<label className="flex flex-col"> initial={{ opacity: 0, height: 0 }}
Port animate={{ opacity: 1, height: 'auto' }}
<input className={`p-3.5 rounded-xl text-xs font-semibold border flex items-center gap-2 ${
name="port" msgType === 'success'
type="number" ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400'
required : 'bg-destructive/10 border-destructive/20 text-destructive'
value={settings?.port ?? ''} }`}
onChange={handleChange} >
className="mt-1 p-2 rounded bg-black/20 border border-white/20" {msgType === 'success' ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <AlertCircle className="w-4 h-4 shrink-0" />}
/> {message}
</label> </motion.div>
<label className="inline-flex items-center space-x-2"> )}
<input
name="secure" {/* Bento Grid layout for SMTP */}
type="checkbox" <form onSubmit={handleSave}>
checked={settings?.secure ?? false} <motion.div variants={containerVariants} initial="hidden" animate="visible" className="grid grid-cols-1 md:grid-cols-3 gap-5">
onChange={handleChange} {/* Bento Box 1: Server Connection Details (2 Spalten) */}
className="rounded" <motion.div variants={itemVariants} className="md:col-span-2 p-6 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md space-y-4 shadow-md">
/> <div className="flex items-center gap-2 text-sky-400 font-bold text-sm border-b border-slate-800 pb-3">
<span>SSL / TLS (secure)</span> <Server className="w-4 h-4" />
</label> <span>Server & Serververbindung</span>
<label className="flex flex-col"> </div>
Benutzer (SMTPUser)
<input <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
name="user" <div className="sm:col-span-2 space-y-1.5">
type="email" <Label htmlFor="host" className="text-xs font-bold text-slate-300">SMTP Host</Label>
required <Input
value={settings?.user ?? ''} id="host"
onChange={handleChange} name="host"
className="mt-1 p-2 rounded bg-black/20 border border-white/20" type="text"
/> required
</label> value={settings?.host ?? ''}
<label className="flex flex-col"> onChange={handleChange}
Passwort placeholder="smtp.beispiel.de"
<input className="bg-slate-950/80 border-slate-800 text-white rounded-xl font-mono text-sm"
name="pass" />
type="password" </div>
required
value={settings?.pass ?? ''} <div className="space-y-1.5">
onChange={handleChange} <Label htmlFor="port" className="text-xs font-bold text-slate-300">Port</Label>
className="mt-1 p-2 rounded bg-black/20 border border-white/20" <Input
/> id="port"
</label> name="port"
<div className="flex space-x-4 mt-4"> type="number"
<button required
type="submit" value={settings?.port ?? ''}
className="px-4 py-2 bg-primary rounded hover:bg-primary/80 transition" onChange={handleChange}
> placeholder="587"
Speichern className="bg-slate-950/80 border-slate-800 text-white rounded-xl font-mono text-sm"
</button> />
<button </div>
type="button" </div>
onClick={handleTestEmail}
className="px-4 py-2 bg-green-600 rounded hover:bg-green-500 transition" <div className="pt-2">
> <label className="inline-flex items-center gap-2 cursor-pointer p-3 rounded-xl bg-slate-950/50 border border-slate-800/80 hover:bg-slate-800/40 transition">
TestMail senden <input
</button> name="secure"
</div> type="checkbox"
checked={settings?.secure ?? false}
onChange={handleChange}
className="w-4 h-4 rounded text-sky-500 bg-slate-900 border-slate-700"
/>
<span className="text-xs font-semibold text-slate-200">SSL / TLS Verschlüsselung aktivieren</span>
</label>
</div>
</motion.div>
{/* Bento Box 2: Auth Credentials (1 Spalte) */}
<motion.div variants={itemVariants} className="p-6 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md space-y-4 shadow-md flex flex-col justify-between">
<div className="space-y-4">
<div className="flex items-center gap-2 text-sky-400 font-bold text-sm border-b border-slate-800 pb-3">
<Key className="w-4 h-4" />
<span>Zugangsdaten</span>
</div>
<div className="space-y-1.5">
<Label htmlFor="user" className="text-xs font-bold text-slate-300">SMTP Benutzer</Label>
<Input
id="user"
name="user"
type="email"
required
value={settings?.user ?? ''}
onChange={handleChange}
placeholder="absender@beispiel.de"
className="bg-slate-950/80 border-slate-800 text-white rounded-xl font-mono text-sm"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="pass" className="text-xs font-bold text-slate-300">Passwort</Label>
<Input
id="pass"
name="pass"
type="password"
required
value={settings?.pass ?? ''}
onChange={handleChange}
placeholder="••••••••••••"
className="bg-slate-950/80 border-slate-800 text-white rounded-xl font-mono text-sm"
/>
</div>
</div>
{/* Submit & Test Buttons */}
<div className="flex flex-col gap-2 pt-4 border-t border-slate-800">
<Button type="submit" disabled={saving || testing} className="w-full bg-sky-600 hover:bg-sky-500 text-white rounded-xl h-10 text-xs font-bold">
{saving ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Speichert...</> : 'Konfiguration speichern'}
</Button>
<Button type="button" onClick={handleTestEmail} disabled={saving || testing} variant="outline" className="w-full border-slate-700 text-slate-300 hover:text-white rounded-xl h-10 text-xs font-bold">
{testing ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Sendet...</> : <><Send className="w-3.5 h-3.5 mr-2 text-emerald-400" /> Test-Mail senden</>}
</Button>
</div>
</motion.div>
</motion.div>
</form> </form>
</div> </div>
); );

View File

@@ -1,16 +1,15 @@
"use client"; "use client";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { import { motion } from "framer-motion";
getDatabaseIntegrity, import {
repairDatabaseSchema, getDatabaseIntegrity,
optimizeDatabaseIndices repairDatabaseSchema,
optimizeDatabaseIndices
} from "@/lib/actions/admin"; } from "@/lib/actions/admin";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Loader2, RefreshCw, Wrench, Database, AlertTriangle, CheckCircle2, XCircle, Terminal, ArrowLeft } from "lucide-react"; import { Loader2, RefreshCw, Wrench, Database, CheckCircle2, XCircle, Terminal } from "lucide-react";
import Link from "next/link";
import { createClient } from "@/lib/supabase/client"; import { createClient } from "@/lib/supabase/client";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -26,6 +25,19 @@ interface IntegrityData {
}; };
} }
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: { staggerChildren: 0.1 }
}
};
const itemVariants = {
hidden: { opacity: 0, y: 15 },
visible: { opacity: 1, y: 0, transition: { type: 'spring' as const, stiffness: 80, damping: 15 } }
};
export default function AdminToolsPage() { export default function AdminToolsPage() {
const [integrity, setIntegrity] = useState<IntegrityData | null>(null); const [integrity, setIntegrity] = useState<IntegrityData | null>(null);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@@ -88,218 +100,145 @@ export default function AdminToolsPage() {
useEffect(() => { useEffect(() => {
async function checkAccess() { async function checkAccess() {
const supabase = createClient(); try {
const { data: { user } } = await supabase.auth.getUser(); const supabase = createClient();
if (!user) { const { data: { user } } = await supabase.auth.getUser();
router.push('/auth/login'); if (!user) {
return; router.push('/auth/login');
return;
}
const [userRes] = await Promise.all([
supabase.from('users').select('role').eq('id', user.id).single(),
loadStatus(true)
]);
if (!userRes.data || userRes.data.role === 'verwaltung') {
router.push('/admin');
return;
}
} catch (err) {
console.error("Fehler beim Laden von Admin Tools:", err);
} finally {
setLoading(false);
} }
const { data: userData } = await supabase
.from('users')
.select('role')
.eq('id', user.id)
.single();
if (!userData || userData.role === 'verwaltung') {
router.push('/admin');
return;
}
setLoading(false);
loadStatus();
} }
checkAccess(); checkAccess();
}, [router]); }, [router]);
if (loading) { if (loading) {
return <div className="min-h-screen bg-[#020617] text-white flex justify-center items-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>; return <div className="p-8 text-white flex justify-center items-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>;
} }
return ( return (
<div className="min-h-screen bg-[#020617] text-white px-4 py-12 relative overflow-hidden"> <div className="p-6 max-w-7xl mx-auto text-slate-900 dark:text-white space-y-6">
{/* Background decoration */} {/* Header */}
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-[1000px] h-[600px] bg-blue-600/10 blur-[120px] rounded-full -z-10 opacity-30" /> <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="space-y-1">
<h1 className="text-3xl font-extrabold tracking-tight flex items-center gap-3">
{/* Loading Overlay */} <Database className="w-8 h-8 text-primary" />
{isLoading && ( Datenbank Cockpit & Tools
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex flex-col items-center justify-center gap-4"> </h1>
<Loader2 className="w-12 h-12 text-primary animate-spin" /> <p className="text-slate-400 text-xs">
<p className="text-slate-200 text-lg font-medium"> Verwalten und reparieren Sie Systemtabellen, Sicherheitsrichtlinien (RLS) und Datenbank-Indizes.
{activeAction === "repair" </p>
? "Schema wird repariert..." </motion.div>
: activeAction === "optimize"
? "Datenbank wird indexiert..."
: "Verbindung zur Datenbank wird aufgebaut..."}
</p>
</div>
)}
<div className="max-w-5xl mx-auto space-y-8"> {/* Bento Grid layout */}
{/* Header */} <motion.div variants={containerVariants} initial="hidden" animate="visible" className="grid grid-cols-1 md:grid-cols-3 gap-5">
<div className="flex items-center gap-4"> {/* Bento Card 1: Integritätsscan */}
<Link href="/"> <motion.div variants={itemVariants} whileHover={{ y: -3 }} className="p-6 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md flex flex-col justify-between space-y-4 hover:border-blue-500/30 transition-all duration-300 shadow-md">
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-white"> <div className="space-y-3">
<ArrowLeft className="w-4 h-4 mr-2" /> Startseite <div className="w-10 h-10 rounded-xl bg-blue-500/10 border border-blue-500/20 text-blue-400 flex items-center justify-center">
</Button> <RefreshCw className="w-5 h-5" />
</Link> </div>
<div> <div>
<h1 className="text-3xl font-extrabold tracking-tight flex items-center gap-3"> <h3 className="font-bold text-base text-white">Integritätsscan</h3>
<Database className="w-8 h-8 text-primary" /> <p className="text-xs text-slate-400 mt-1 leading-relaxed">
Admin Datenbank-Cockpit
</h1>
<p className="text-slate-400 text-sm mt-1">
Verwalten und reparieren Sie Systemtabellen, Sicherheitsrichtlinien (RLS) und Datenbank-Indizes.
</p>
</div>
</div>
{/* Action Controls */}
<div className="grid md:grid-cols-3 gap-6">
<Card className="glass-dark border-white/10 flex flex-col justify-between">
<CardHeader>
<CardTitle className="text-white text-lg flex items-center gap-2">
<RefreshCw className="w-5 h-5 text-blue-400" />
Integritätsscan
</CardTitle>
<CardDescription className="text-slate-400">
Prüft die physische Existenz der Tabellen und zählt deren Zeilenanzahl. Prüft die physische Existenz der Tabellen und zählt deren Zeilenanzahl.
</CardDescription> </p>
</CardHeader>
<CardContent className="pt-0">
<Button
onClick={() => loadStatus()}
disabled={isLoading}
className="w-full bg-blue-600 hover:bg-blue-700 text-white"
>
Status aktualisieren
</Button>
</CardContent>
</Card>
<Card className="glass-dark border-white/10 flex flex-col justify-between">
<CardHeader>
<CardTitle className="text-white text-lg flex items-center gap-2">
<Wrench className="w-5 h-5 text-emerald-400" />
Schema reparieren
</CardTitle>
<CardDescription className="text-slate-400">
Erstellt fehlende Kerntabellen automatisch neu und konfiguriert die RLS-Rechte.
</CardDescription>
</CardHeader>
<CardContent className="pt-0">
<Button
onClick={handleRepair}
disabled={isLoading}
className="w-full bg-emerald-600 hover:bg-emerald-700 text-white"
>
Schema reparieren
</Button>
</CardContent>
</Card>
<Card className="glass-dark border-white/10 flex flex-col justify-between">
<CardHeader>
<CardTitle className="text-white text-lg flex items-center gap-2">
<Database className="w-5 h-5 text-amber-400" />
Index optimieren
</CardTitle>
<CardDescription className="text-slate-400">
Baut korrupte Suchindizes im Schema public mittels REINDEX neu auf.
</CardDescription>
</CardHeader>
<CardContent className="pt-0">
<Button
onClick={handleOptimize}
disabled={isLoading}
className="w-full bg-amber-600 hover:bg-amber-700 text-white"
>
Index optimieren
</Button>
</CardContent>
</Card>
</div>
{/* Tabellenstatus */}
<Card className="glass-dark border-white/10">
<CardHeader>
<CardTitle className="text-white text-xl">Tabellen-Status & Diagnose</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid sm:grid-cols-2 md:grid-cols-4 gap-4">
{integrity?.tables ? (
Object.entries(integrity.tables).map(([name, status]) => (
<div
key={name}
className="p-4 rounded-xl border bg-white/5 border-white/10 flex flex-col justify-between gap-2"
>
<span className="font-semibold text-slate-300 text-sm capitalize">
{name.replace("_", " ")}
</span>
<div className="flex items-center justify-between">
<span className="text-xs text-slate-500">Zeilen: {status.count}</span>
{status.exists ? (
<Badge className="bg-emerald-500/10 text-emerald-400 border-emerald-500/20 gap-1">
<CheckCircle2 className="w-3.5 h-3.5" /> OK
</Badge>
) : (
<Badge className="bg-red-500/10 text-red-400 border-red-500/20 gap-1">
<XCircle className="w-3.5 h-3.5" /> Fehlt
</Badge>
)}
</div>
</div>
))
) : (
<div className="col-span-4 py-8 text-center text-slate-500 text-sm">
Lade Diagnosedaten...
</div>
)}
</div> </div>
</div>
<Button onClick={() => loadStatus()} disabled={isLoading} className="w-full bg-blue-600 hover:bg-blue-500 text-white rounded-xl h-10 text-xs font-bold">
{isLoading && activeAction === null ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Prüft...</> : 'Status Scannen'}
</Button>
</motion.div>
{/* Foreign Key Errors */} {/* Bento Card 2: Schema Reparieren */}
{integrity && integrity.errors.foreign_keys > 0 && ( <motion.div variants={itemVariants} whileHover={{ y: -3 }} className="p-6 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md flex flex-col justify-between space-y-4 hover:border-emerald-500/30 transition-all duration-300 shadow-md">
<div className="p-4 rounded-xl bg-red-500/10 border border-red-500/20 flex gap-3 items-center"> <div className="space-y-3">
<AlertTriangle className="w-6 h-6 text-red-400 shrink-0" /> <div className="w-10 h-10 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 flex items-center justify-center">
<div> <Wrench className="w-5 h-5" />
<p className="font-bold text-red-200">Fremdschlüssel-Fehler gefunden!</p> </div>
<p className="text-red-300/80 text-sm"> <div>
Es wurden {integrity.errors.foreign_keys} verwaiste Lizenzen ohne zugeordneten Endkunden in der Tabelle `licenses` detektiert. <h3 className="font-bold text-base text-white">Schema Reparieren</h3>
</p> <p className="text-xs text-slate-400 mt-1 leading-relaxed">
Erstellt fehlende Kerntabellen automatisch neu und konfiguriert RLS-Rechte.
</p>
</div>
</div>
<Button onClick={handleRepair} disabled={isLoading} className="w-full bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl h-10 text-xs font-bold">
{isLoading && activeAction === 'repair' ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Repariert...</> : 'Schema Reparieren'}
</Button>
</motion.div>
{/* Bento Card 3: Index Optimieren */}
<motion.div variants={itemVariants} whileHover={{ y: -3 }} className="p-6 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md flex flex-col justify-between space-y-4 hover:border-amber-500/30 transition-all duration-300 shadow-md">
<div className="space-y-3">
<div className="w-10 h-10 rounded-xl bg-amber-500/10 border border-amber-500/20 text-amber-400 flex items-center justify-center">
<Database className="w-5 h-5" />
</div>
<div>
<h3 className="font-bold text-base text-white">Index Optimieren</h3>
<p className="text-xs text-slate-400 mt-1 leading-relaxed">
Baut Suchindizes im Schema public mittels REINDEX neu auf für maximale Performance.
</p>
</div>
</div>
<Button onClick={handleOptimize} disabled={isLoading} className="w-full bg-amber-600 hover:bg-amber-500 text-white rounded-xl h-10 text-xs font-bold">
{isLoading && activeAction === 'optimize' ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Indexiert...</> : 'Index Optimieren'}
</Button>
</motion.div>
{/* Bento Card 4: Tabellen-Diagnose (2 Spalten) */}
<motion.div variants={itemVariants} className="md:col-span-2 p-6 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md space-y-4 shadow-md">
<h3 className="font-bold text-base text-white border-b border-slate-800 pb-3">Tabellen-Status & Diagnose</h3>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{integrity?.tables ? (
Object.entries(integrity.tables).map(([name, status]) => (
<div key={name} className="p-3 rounded-xl border bg-slate-950/60 border-slate-800 flex items-center justify-between">
<div>
<span className="font-bold text-xs text-slate-200 capitalize block">{name.replace("_", " ")}</span>
<span className="text-[10px] text-slate-400">Zeilen: {status.count}</span>
</div>
{status.exists ? (
<Badge className="bg-emerald-500/10 text-emerald-400 border-emerald-500/20 text-[10px] py-0 px-1.5">OK</Badge>
) : (
<Badge className="bg-red-500/10 text-red-400 border-red-500/20 text-[10px] py-0 px-1.5">Fehlt</Badge>
)}
</div> </div>
</div> ))
) : (
<p className="text-xs text-slate-500 col-span-3">Keine Diagnose-Daten geladen.</p>
)} )}
</CardContent> </div>
</Card> </motion.div>
{/* Console / Output logs */} {/* Bento Card 5: Live Konsole / Logs (1 Spalte) */}
<Card className="glass-dark border-white/10"> <motion.div variants={itemVariants} className="p-6 rounded-2xl bg-slate-900/60 border border-slate-800 backdrop-blur-md space-y-3 shadow-md flex flex-col justify-between">
<CardHeader className="flex flex-row items-center justify-between"> <div className="space-y-2">
<CardTitle className="text-white text-lg flex items-center gap-2"> <h3 className="font-bold text-base text-white flex items-center gap-2 border-b border-slate-800 pb-3">
<Terminal className="w-5 h-5 text-primary" /> <Terminal className="w-4 h-4 text-sky-400" /> System-Konsole
Diagnose-Konsole </h3>
</CardTitle> <div className="bg-slate-950 p-3 rounded-xl border border-slate-800 font-mono text-[11px] text-slate-300 h-44 overflow-y-auto space-y-1 subpixel-antialiased">
<Button
variant="ghost"
size="sm"
onClick={() => setLogs([])}
className="text-slate-400 hover:text-white text-xs"
>
Konsole leeren
</Button>
</CardHeader>
<CardContent className="pt-0">
<div className="font-mono text-xs bg-black/50 p-4 rounded-xl border border-white/5 h-64 overflow-y-auto space-y-1.5 scrollbar-thin">
{logs.length === 0 ? ( {logs.length === 0 ? (
<span className="text-slate-600 italic">Konsole bereit. Führen Sie einen Scan aus.</span> <span className="text-slate-600 italic">Warte auf Aktionen...</span>
) : ( ) : (
logs.map((log, index) => ( logs.map((log, i) => <div key={i} className="leading-tight">{log}</div>)
<div key={index} className={log.includes("FEHLER") ? "text-red-400" : log.includes("Erfolgreich") ? "text-emerald-400" : "text-slate-300"}>
{log}
</div>
))
)} )}
</div> </div>
</CardContent> </div>
</Card> </motion.div>
</div> </motion.div>
</div> </div>
); );
} }

View File

@@ -166,6 +166,7 @@ export function OrderWizard({
return '' return ''
}) })
const [editingIdx, setEditingIdx] = useState<number | null>(null) const [editingIdx, setEditingIdx] = useState<number | null>(null)
const [orderNotes, setOrderNotes] = useState<string>('')
const [toast, setToast] = useState<{ message: string; type: 'error' | 'success' } | null>(null) const [toast, setToast] = useState<{ message: string; type: 'error' | 'success' } | null>(null)
useEffect(() => { useEffect(() => {
@@ -687,6 +688,7 @@ export function OrderWizard({
endCustomerId: selectedEndCustomerId, endCustomerId: selectedEndCustomerId,
endCustomer: selectedEndCustomer, endCustomer: selectedEndCustomer,
lastLicenseDate: lastLicenseDate || null, lastLicenseDate: lastLicenseDate || null,
notes: orderNotes || null,
}) })
}) })
@@ -859,40 +861,42 @@ export function OrderWizard({
</div> </div>
{/* CENTER: Sticky stepper + scrollable categories */} {/* CENTER: Sticky stepper + scrollable categories */}
<div className="lg:col-span-2 space-y-0"> <div className="lg:col-span-2 flex flex-col max-h-[calc(100vh-4rem)] overflow-hidden">
{/* Sticky stepper header — only covers center column */} {/* Sticky stepper header — only covers center column */}
<div className="sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md pb-4 pt-6 border-b border-white/5 mb-6"> <div className="shrink-0 bg-slate-950/80 backdrop-blur-md pb-4 pt-2 border-b border-white/5 mb-4">
<p className="text-center text-slate-400 text-sm mb-4">Schritt 3 von 4 Software konfigurieren</p> <p className="text-center text-slate-400 text-sm mb-4">Schritt 3 von 4 Software konfigurieren</p>
<ProgressStepper step={step} basketItemsCount={basketItems.length} /> <ProgressStepper step={step} basketItemsCount={basketItems.length} />
</div> </div>
{/* Upgrade-Modus Hinweis-Banner */} {/* Scrollable category content area */}
{upgradeMode && lockedDeviceId && ( <div className="flex-1 overflow-y-auto pr-2 subpixel-antialiased scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent">
<div className="mb-4 p-3 rounded-xl bg-primary/10 border border-primary/20 text-xs text-primary/90 flex items-start gap-2"> {/* Upgrade-Modus Hinweis-Banner */}
<span className="text-primary mt-0.5"></span> {upgradeMode && lockedDeviceId && (
<div> <div className="mb-4 p-3 rounded-xl bg-primary/10 border border-primary/20 text-xs text-primary/90 flex items-start gap-2">
<p className="font-semibold">Upgrade-Modus: {lockedDeviceId}</p> <span className="text-primary mt-0.5"></span>
<p className="text-primary/70 mt-0.5">Bereits lizenzierte Module sind ausgegraut und können nicht doppelt gebucht werden.</p> <div>
<p className="font-semibold">Upgrade-Modus: {lockedDeviceId}</p>
<p className="text-primary/70 mt-0.5">Bereits lizenzierte Module sind ausgegraut und können nicht doppelt gebucht werden.</p>
</div>
</div> </div>
</div> )}
)}
{/* Scrollable category content */} <StepSoftware
<StepSoftware visibleCategories={visibleCategories}
visibleCategories={visibleCategories} products={products}
products={products} selections={selections}
selections={selections} selectProduct={selectProduct}
selectProduct={selectProduct} isProductDisabled={isProductDisabled}
isProductDisabled={isProductDisabled} isModuleDisabled={isModuleDisabled}
isModuleDisabled={isModuleDisabled} toggleModule={toggleModule}
toggleModule={toggleModule} moduleQuantities={moduleQuantities}
moduleQuantities={moduleQuantities} setModuleQuantities={setModuleQuantities}
setModuleQuantities={setModuleQuantities} selectedBillingInterval={selectedBillingInterval}
selectedBillingInterval={selectedBillingInterval} billingLabel={billingLabel}
billingLabel={billingLabel} billingBadgeClass={billingBadgeClass}
billingBadgeClass={billingBadgeClass} existingModuleIds={existingModuleIds}
existingModuleIds={existingModuleIds} />
/> </div>
</div> </div>
{/* RIGHT: Summary sidebar (sticky) */} {/* RIGHT: Summary sidebar (sticky) */}
@@ -935,10 +939,10 @@ export function OrderWizard({
{step === 4 && ( {step === 4 && (
<motion.div <motion.div
key="step4" key="step4"
initial={{ opacity: 0, scale: 0.95 }} initial={{ opacity: 0, scale: 0.98 }}
animate={{ opacity: 1, scale: 1 }} animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }} exit={{ opacity: 0, scale: 0.98 }}
className="space-y-6 text-center" className="w-full"
> >
<StepSummary <StepSummary
finalItemsToShow={finalItemsToShow} finalItemsToShow={finalItemsToShow}
@@ -961,6 +965,8 @@ export function OrderWizard({
initialOrder={initialOrder} initialOrder={initialOrder}
prevStep={prevStep} prevStep={prevStep}
linkedFeeProducts={linkedFeeProducts} linkedFeeProducts={linkedFeeProducts}
orderNotes={orderNotes}
setOrderNotes={setOrderNotes}
/> />
</motion.div> </motion.div>
)} )}

View File

@@ -93,7 +93,8 @@ export function StepBilling({
)} )}
</div> </div>
</div> </div>
{selectedBillingInterval === 'one_time' && customerMode === 'select' && selectedEndCustomerId && ( {/* Alte Lizenznummereingabe / Datum vorerst ausgeblendet */}
{/* {selectedBillingInterval === 'one_time' && customerMode === 'select' && selectedEndCustomerId && (
<div className="p-4 rounded-xl bg-white/5 border border-white/10 space-y-3 mt-6 max-w-md animate-in fade-in slide-in-from-top-2 duration-300"> <div className="p-4 rounded-xl bg-white/5 border border-white/10 space-y-3 mt-6 max-w-md animate-in fade-in slide-in-from-top-2 duration-300">
<Label htmlFor="last-license-date" className="text-white font-medium flex items-center gap-2"> <Label htmlFor="last-license-date" className="text-white font-medium flex items-center gap-2">
<Calendar className="w-4 h-4 text-primary" /> <Calendar className="w-4 h-4 text-primary" />
@@ -110,7 +111,7 @@ export function StepBilling({
Falls dieser Kunde bereits Lizenzen besitzt, tragen Sie das Datum der letzten Lizenzierung ein. Damit werden die korrekten Update-Gebühren ermittelt. Falls dieser Kunde bereits Lizenzen besitzt, tragen Sie das Datum der letzten Lizenzierung ein. Damit werden die korrekten Update-Gebühren ermittelt.
</p> </p>
</div> </div>
)} )} */}
</CardContent> </CardContent>
<CardFooter className="flex justify-between border-t border-white/10 pt-6"> <CardFooter className="flex justify-between border-t border-white/10 pt-6">
<Button variant="ghost" className="text-white" onClick={prevStep}> <Button variant="ghost" className="text-white" onClick={prevStep}>

View File

@@ -4,7 +4,7 @@ import React from 'react'
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card' import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator' import { Separator } from '@/components/ui/separator'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { ShieldCheck, Building2, Calendar, Loader2 } from 'lucide-react' import { ShieldCheck, Building2, Calendar, Loader2, CheckCircle2 } from 'lucide-react'
import * as Icons from 'lucide-react' import * as Icons from 'lucide-react'
import { Category, Product, EndCustomer, Profile } from '@/lib/types' import { Category, Product, EndCustomer, Profile } from '@/lib/types'
@@ -29,6 +29,8 @@ interface StepSummaryProps {
initialOrder: any initialOrder: any
prevStep: () => void prevStep: () => void
linkedFeeProducts?: Product[] linkedFeeProducts?: Product[]
orderNotes: string
setOrderNotes: (notes: string) => void
} }
function CategoryIcon({ icon, className }: { icon?: string | null; className?: string }) { function CategoryIcon({ icon, className }: { icon?: string | null; className?: string }) {
@@ -58,238 +60,238 @@ export function StepSummary({
initialOrder, initialOrder,
prevStep, prevStep,
linkedFeeProducts = [], linkedFeeProducts = [],
orderNotes,
setOrderNotes,
}: StepSummaryProps) { }: StepSummaryProps) {
return ( return (
<Card className="glass-dark border-primary/30 max-w-2xl mx-auto shadow-primary/10 shadow-2xl"> <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start max-w-6xl mx-auto text-left">
<CardHeader> {/* LINKER BEREICH: Linksbündige Überschrift & Notizfeld */}
<div className="w-20 h-20 bg-primary/20 rounded-full flex items-center justify-center mx-auto mb-4 border border-primary/50"> <div className="lg:col-span-5 space-y-6">
<ShieldCheck className="w-10 h-10 text-primary" /> <div className="space-y-3">
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-primary/20 rounded-xl flex items-center justify-center border border-primary/50 shrink-0">
<ShieldCheck className="w-6 h-6 text-primary" />
</div>
<span className="text-xs font-bold uppercase tracking-widest text-sky-400 bg-sky-500/10 px-3 py-1 rounded-full border border-sky-500/20">
Schritt 4 von 4 Abschluss
</span>
</div>
<h2 className="text-3xl sm:text-4xl font-extrabold text-white tracking-tight">
Anfrage prüfen
</h2>
<p className="text-slate-300 text-base leading-relaxed">
Fast fertig! Bitte überprüfen Sie Ihre ausgewählte Konfiguration vor dem Absenden.
</p>
</div> </div>
<CardTitle className="text-3xl text-white">Anfrage prüfen</CardTitle>
<CardDescription className="text-slate-300">
Fast fertig! Bitte überprüfen Sie Ihre Auswahl.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6 text-left">
<div className="p-4 rounded-lg bg-white/5 space-y-6">
{finalItemsToShow.map((item, itemIdx) => (
<div key={itemIdx} className="space-y-3 border-b border-white/10 pb-4 last:border-0 last:pb-0">
<div className="flex justify-between items-center bg-white/5 p-2 rounded">
<span className="text-white font-bold text-sm">Kasse: {item.deviceName}</span>
<span className="text-xs text-slate-400 capitalize">{item.billingInterval === 'one_time' ? 'Kauf' : 'Abo'}</span>
</div>
{visibleCategories.map(cat => { {/* Kunden-Info Card */}
const sel = item.selections[cat.id] {selectedEndCustomer && (
const selectedProds: Product[] = [] <div className="p-5 rounded-2xl bg-slate-900/80 border border-slate-800 space-y-2">
if (cat.allow_multiselect && sel?.productIds) { <div className="flex items-center gap-2 text-sky-400 font-bold text-sm">
sel.productIds.forEach((pId: string) => { <Building2 className="w-4 h-4" />
const p = products.find(prod => prod.id === pId) <span>Ausgewählter Endkunde</span>
if (p) selectedProds.push(p)
})
} else if (sel?.productId) {
const p = products.find(prod => prod.id === sel.productId)
if (p) selectedProds.push(p)
}
if (selectedProds.length === 0) return null
const sortedProds = [...selectedProds].sort((a, b) => a.base_price - b.base_price)
const freeLimit = cat.allow_multiselect ? cat.free_items_limit : 0
return (
<div key={cat.id} className="space-y-1 pl-2">
<div className="text-slate-400 font-semibold text-xs flex items-center gap-1">
<CategoryIcon icon={cat.icon} className="w-3.5 h-3.5 text-primary" />
<span>{cat.name}</span>
</div>
{sortedProds.map((prod, idx) => {
const isFree = idx < freeLimit
const actualPrice = isFree ? 0 : prod.base_price
const catTotal =
Number(actualPrice) +
(sel?.moduleIds?.reduce((acc: number, mId: string) => {
const mod = prod.modules?.find(m => m.id === mId)
const qty = item.moduleQuantities[mId] || 1
return acc + (Number(mod?.price ?? 0) * qty)
}, 0) || 0)
return (
<div key={prod.id} className="pl-3">
<div className="flex justify-between font-semibold text-sm text-white">
<span>
{prod.name} {isFree && <span className="text-[10px] text-green-400 font-semibold">(Frei)</span>}
</span>
<span>
{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(catTotal)}
</span>
</div>
{sel?.moduleIds && sel.moduleIds.length > 0 && (
<p className="text-xs text-slate-400 mt-0.5">
Module: {sel.moduleIds
.map((id: string) => {
const mod = prod.modules?.find(m => m.id === id)
const qty = item.moduleQuantities[id] || 1
return mod ? `${mod.name}${mod.has_quantity ? ` (x${qty})` : ''}` : ''
})
.filter(Boolean)
.join(', ')}
</p>
)}
</div>
)
})}
</div>
)
})}
</div>
))}
{linkedFeeProducts && linkedFeeProducts.length > 0 && (
<div className="space-y-3 border-b border-white/10 pb-4 last:border-0 last:pb-0">
<div className="flex justify-between items-center bg-white/5 p-2 rounded">
<span className="text-white font-bold text-sm">Backoffice</span>
</div>
{linkedFeeProducts.map(p => (
<div key={p.id} className="pl-2 space-y-1">
<div className="flex justify-between font-semibold text-sm text-white pl-3">
<span>{p.name}</span>
<span>
{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(p.base_price)}
{' '}<span className="text-slate-400 text-[10px] font-normal">{p.billing_interval === 'monthly' ? '/ mtl.' : 'einmalig'}</span>
</span>
</div>
</div>
))}
</div>
)}
<Separator className="bg-white/10" />
<div className="text-sm text-slate-300 space-y-1">
{selectedEndCustomer ? (
<>
<p className="font-semibold text-white flex items-center gap-2">
<Building2 className="w-3.5 h-3.5 text-primary" />
{selectedEndCustomer.company_name}
</p>
<p>{[selectedEndCustomer.first_name, selectedEndCustomer.last_name].filter(Boolean).join(' ')}</p>
<p>{[selectedEndCustomer.street, selectedEndCustomer.zip, selectedEndCustomer.city].filter(Boolean).join(', ')}</p>
<p className="text-xs text-slate-500 mt-1">Endkunde Ihres Partners</p>
{lastLicenseDate && (
<p className="text-xs text-slate-400 flex items-center gap-1 mt-1 font-mono">
<Calendar className="w-3.5 h-3.5 text-primary" />
Letzte Lizenz vom: {new Date(lastLicenseDate).toLocaleDateString('de-DE')}
</p>
)}
</>
) : (
<>
<p className="font-semibold text-white">{customerData.company_name}</p>
<p>{customerData.first_name} {customerData.last_name}</p>
<p>{customerData.address}, {customerData.zip_code} {customerData.city}</p>
</>
)}
</div>
</div>
{oneTimeTotal > 0 && monthlyTotal > 0 ? (
<div className="space-y-4 border-t border-white/10 pt-4">
<div className="space-y-1">
<p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Einmaliger Betrag:</p>
<div className="flex justify-between text-sm text-slate-400">
<span>Netto:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeNet)}</span>
</div>
<div className="flex justify-between text-sm text-slate-400">
<span>zzgl. 19% MwSt.:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeTax)}</span>
</div>
<div className="flex justify-between text-base font-bold text-white">
<span>Brutto:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeGross)}</span>
</div>
</div>
{updatePriceModifier.label && (
<div className="text-sm text-green-400 font-semibold bg-green-500/10 p-2 rounded border border-green-500/20 my-1">
{updatePriceModifier.label}
</div>
)}
<div className="space-y-1 pt-2 border-t border-white/10">
<p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Monatlicher Betrag:</p>
<div className="flex justify-between text-sm text-slate-400">
<span>Netto:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyNet)} / mtl.</span>
</div>
<div className="flex justify-between text-sm text-slate-400">
<span>zzgl. 19% MwSt.:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyTax)} / mtl.</span>
</div>
<div className="flex justify-between text-base font-bold text-white">
<span>Brutto:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyGross)} / mtl.</span>
</div>
</div>
</div>
) : oneTimeTotal > 0 ? (
<div className="space-y-1 border-t border-white/10 pt-4">
<div className="flex justify-between text-sm text-slate-400">
<span>Netto-Gesamtbetrag:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeNet)}</span>
</div>
<div className="flex justify-between text-sm text-slate-400">
<span>zzgl. 19% MwSt.:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeTax)}</span>
</div>
{updatePriceModifier.label && (
<div className="text-sm text-green-400 font-semibold bg-green-500/10 p-2 rounded border border-green-500/20 my-1">
{updatePriceModifier.label}
</div>
)}
<div className="flex justify-between text-xl font-bold text-blue-500 dark:text-blue-400 pt-1 border-t border-white/5">
<span>Gesamtbetrag (brutto):</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeGross)}</span>
</div>
</div>
) : (
<div className="space-y-1 border-t border-white/10 pt-4">
<div className="flex justify-between text-sm text-slate-400">
<span>Netto-Gesamtbetrag:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyNet)} / mtl.</span>
</div>
<div className="flex justify-between text-sm text-slate-400">
<span>zzgl. 19% MwSt.:</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyTax)} / mtl.</span>
</div>
<div className="flex justify-between text-xl font-bold text-blue-500 dark:text-blue-400 pt-1 border-t border-white/5">
<span>Gesamtbetrag (brutto):</span>
<span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyGross)} / mtl.</span>
</div> </div>
<p className="text-white font-bold text-base">{selectedEndCustomer.company_name}</p>
<p className="text-slate-400 text-xs">{selectedEndCustomer.first_name} {selectedEndCustomer.last_name}</p>
<p className="text-slate-400 text-xs">{selectedEndCustomer.zip} {selectedEndCustomer.city}</p>
</div> </div>
)} )}
{/* Anmerkungen / Notizfeld (Links) */}
<div className="space-y-2 pt-2">
<label htmlFor="order-notes" className="block text-sm font-bold text-white">
Anmerkungen / Hinweise (optional)
</label>
<textarea
id="order-notes"
rows={4}
value={orderNotes}
onChange={e => setOrderNotes(e.target.value)}
placeholder="Besondere Hinweise, Ansprechpartner oder Terminwünsche hier eintragen..."
className="w-full p-4 rounded-xl bg-slate-900/90 border border-slate-800 text-sm text-white placeholder-slate-500 focus:border-sky-400 focus:outline-none transition-colors duration-200 resize-none shadow-inner"
/>
</div>
<p className="text-xs text-slate-500 italic"> <p className="text-xs text-slate-500 italic">
Mit dem Klick auf Kostenpflichtig bestellen" akzeptieren Sie unsere AGB und die{' '} Mit dem Klick auf {initialOrder ? 'Anfrage aktualisieren' : 'Kostenpflichtig bestellen'} akzeptieren Sie unsere AGB und die{' '}
<a href="/datenschutz" target="_blank" rel="noopener noreferrer" className="underline hover:text-slate-400"> <a href="/datenschutz" target="_blank" rel="noopener noreferrer" className="underline hover:text-slate-400">
Datenschutzerklärung Datenschutzerklärung
</a>. </a>.
</p> </p>
</CardContent>
<CardFooter className="flex flex-col gap-4"> {/* Aktions-Buttons Links */}
<Button <div className="space-y-3 pt-2">
className="w-full h-14 text-xl font-bold bg-primary hover:bg-primary/90" <Button
onClick={handleSubmit} className="w-full h-14 text-lg font-bold bg-primary hover:bg-primary/90 shadow-[0_0_20px_rgba(59,130,246,0.3)] rounded-xl"
disabled={isSubmitting} onClick={handleSubmit}
> disabled={isSubmitting}
{isSubmitting ? ( >
initialOrder ? ( {isSubmitting ? (
<><Loader2 className="mr-2 h-5 w-5 animate-spin" /> Anfrage wird aktualisiert...</> initialOrder ? (
<><Loader2 className="mr-2 h-5 w-5 animate-spin" /> Anfrage wird aktualisiert...</>
) : (
<><Loader2 className="mr-2 h-5 w-5 animate-spin" /> Anfrage wird versendet...</>
)
) : ( ) : (
<><Loader2 className="mr-2 h-5 w-5 animate-spin" /> Anfrage wird versendet...</> initialOrder ? 'Anfrage aktualisieren' : 'Kostenpflichtig bestellen'
) )}
) : ( </Button>
initialOrder ? 'Anfrage aktualisieren' : 'Anfrage versenden' <Button variant="ghost" className="w-full text-slate-400 hover:text-white" onClick={prevStep}>
)} Noch etwas ändern
</Button> </Button>
<Button variant="ghost" className="w-full text-white" onClick={prevStep}> </div>
Noch etwas ändern </div>
</Button>
</CardFooter> {/* RECHTER BEREICH: Eigenständig scrollbare Zusammenfassung der Anfrage */}
</Card> <div className="lg:col-span-7">
<Card className="glass-dark border-primary/30 shadow-primary/10 shadow-2xl overflow-hidden rounded-2xl flex flex-col max-h-[calc(100vh-6rem)]">
<CardHeader className="shrink-0 border-b border-white/10 pb-4">
<CardTitle className="text-xl text-white flex items-center justify-between">
<span>Zusammenfassung der Positionen</span>
<span className="text-xs font-normal text-sky-400 bg-sky-500/10 px-3 py-1 rounded-full border border-sky-500/20">
{finalItemsToShow.length} {finalItemsToShow.length === 1 ? 'Kasse' : 'Kassen'}
</span>
</CardTitle>
</CardHeader>
{/* Scrollbarer Content der Aufschlüsselung */}
<CardContent className="space-y-6 text-left flex-1 overflow-y-auto pt-6 subpixel-antialiased scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent pr-2">
<div className="p-4 rounded-xl bg-white/5 space-y-6">
{finalItemsToShow.map((item, itemIdx) => (
<div key={itemIdx} className="space-y-3 border-b border-white/10 pb-4 last:border-0 last:pb-0">
<div className="flex justify-between items-center bg-white/5 p-2.5 rounded-lg border border-white/5">
<span className="text-white font-bold text-sm">Kasse: {item.deviceName}</span>
<span className="text-xs text-sky-400 font-semibold uppercase px-2 py-0.5 rounded bg-sky-500/10 border border-sky-500/20">
{item.billingInterval === 'one_time' ? 'Kauf' : 'Abo'}
</span>
</div>
{visibleCategories.map(cat => {
const sel = item.selections[cat.id]
const selectedProds: Product[] = []
if (cat.allow_multiselect && sel?.productIds) {
sel.productIds.forEach((pId: string) => {
const p = products.find(prod => prod.id === pId)
if (p) selectedProds.push(p)
})
} else if (sel?.productId) {
const p = products.find(prod => prod.id === sel.productId)
if (p) selectedProds.push(p)
}
if (selectedProds.length === 0) return null
const sortedProds = [...selectedProds].sort((a, b) => a.base_price - b.base_price)
const freeLimit = cat.allow_multiselect ? cat.free_items_limit : 0
return (
<div key={cat.id} className="text-sm space-y-1.5 pl-2">
<span className="text-slate-400 text-xs font-semibold uppercase tracking-wider block">{cat.name}:</span>
{sortedProds.map((prod, idx) => {
const isFree = idx < freeLimit
const isAbo = item.billingInterval === 'monthly'
const displayPrice = isFree ? 0 : (isAbo ? (prod.monthly_price ?? prod.base_price) : prod.base_price)
return (
<div key={prod.id} className="flex justify-between text-slate-200">
<span className="flex items-center gap-1.5">
<CategoryIcon icon={cat.icon} className="w-3.5 h-3.5 text-primary shrink-0" />
{prod.name}
{isFree && <span className="text-[10px] bg-green-500/20 text-green-400 px-1.5 py-0.5 rounded border border-green-500/30">Inklusive</span>}
</span>
<span className="font-mono text-xs">
{isFree ? '0,00 €' : new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(displayPrice)}
</span>
</div>
)
})}
{/* Selected Modules */}
{sel?.moduleIds && sel.moduleIds.length > 0 && (
<div className="pl-4 space-y-1 pt-1">
{sel.moduleIds.map((mId: string) => {
let modObj: any = null
products.forEach(p => {
const found = p.modules?.find(m => m.id === mId)
if (found) modObj = found
})
if (!modObj) return null
const isAbo = item.billingInterval === 'monthly'
const qty = item.moduleQuantities?.[mId] || 1
const unitPrice = isAbo ? (modObj.monthly_price ?? modObj.price) : modObj.price
const totalPrice = unitPrice * qty
return (
<div key={mId} className="flex justify-between text-slate-400 text-xs">
<span>+ {modObj.name} {qty > 1 ? `(${qty}x)` : ''}</span>
<span className="font-mono">
{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(totalPrice)}
</span>
</div>
)
})}
</div>
)}
</div>
)
})}
</div>
))}
{/* Gebühren & Zusatz-Positionen */}
{linkedFeeProducts.length > 0 && (
<div className="border-t border-white/10 pt-3 space-y-2">
<span className="text-slate-400 text-xs font-semibold uppercase tracking-wider block">Service & Gebühren:</span>
{linkedFeeProducts.map(fp => (
<div key={fp.id} className="flex justify-between text-xs text-slate-300">
<span>{fp.name}</span>
<span className="font-mono">{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(fp.base_price)}</span>
</div>
))}
</div>
)}
</div>
{/* Summen-Berechnung */}
{oneTimeTotal > 0 ? (
<div className="space-y-1.5 border-t border-white/10 pt-4">
<div className="flex justify-between text-sm text-slate-400">
<span>Netto-Gesamtbetrag:</span>
<span className="font-mono">{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeNet)}</span>
</div>
<div className="flex justify-between text-sm text-slate-400">
<span>zzgl. 19% MwSt.:</span>
<span className="font-mono">{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeTax)}</span>
</div>
{updatePriceModifier.label && (
<div className="text-sm text-green-400 font-semibold bg-green-500/10 p-2 rounded border border-green-500/20 my-1">
{updatePriceModifier.label}
</div>
)}
<div className="flex justify-between text-lg font-bold text-sky-400 pt-2 border-t border-white/5">
<span>Gesamtbetrag (brutto):</span>
<span className="font-mono">{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(oneTimeGross)}</span>
</div>
</div>
) : (
<div className="space-y-1.5 border-t border-white/10 pt-4">
<div className="flex justify-between text-sm text-slate-400">
<span>Netto-Gesamtbetrag:</span>
<span className="font-mono">{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyNet)} / mtl.</span>
</div>
<div className="flex justify-between text-sm text-slate-400">
<span>zzgl. 19% MwSt.:</span>
<span className="font-mono">{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyTax)} / mtl.</span>
</div>
<div className="flex justify-between text-lg font-bold text-sky-400 pt-2 border-t border-white/5">
<span>Gesamtbetrag (brutto):</span>
<span className="font-mono">{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(monthlyGross)} / mtl.</span>
</div>
</div>
)}
</CardContent>
</Card>
</div>
</div>
) )
} }