Files
webshop/shop/app/admin/einstellungen/page.tsx

434 lines
17 KiB
TypeScript

/* Admin Settings with Bento Grid Layout & Motion Animations */
'use client';
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 { saveLicServerConfig, testLicServerConnection } from '@/lib/actions/licserver-config';
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() {
const [demoActive, setDemoActive] = useState(true);
const [exporting, setExporting] = useState(false);
const [importing, setImporting] = useState(false);
const [statusMsg, setStatusMsg] = useState('');
const [statusType, setStatusType] = useState<'success' | 'error' | 'info' | ''>('');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [loading, setLoading] = useState(true);
// LicServer Config State
const [licUrl, setLicUrl] = useState('');
const [licKey, setLicKey] = useState('');
const [showKey, setShowKey] = useState(false);
const [licSaving, setLicSaving] = useState(false);
const [licTesting, setLicTesting] = useState(false);
const [licStatus, setLicStatus] = useState<{ ok: boolean; message: string } | null>(null);
const [licMsg, setLicMsg] = useState('');
const [licMsgType, setLicMsgType] = useState<'success' | 'error' | ''>('');
const router = useRouter();
useEffect(() => {
async function checkAccess() {
try {
const supabase = createClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
router.push('/auth/login');
return;
}
// 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');
return;
}
const state = localStorage.getItem('demo_banner_disabled') !== 'true';
setDemoActive(state);
if (licRes.data) {
setLicUrl(licRes.data.licserver_base_url || '');
setLicKey(licRes.data.licserver_api_key || '');
}
} catch (err) {
console.error("Fehler bei checkAccess in Einstellungen:", err);
} finally {
setLoading(false);
}
}
checkAccess();
}, [router]);
const toggleDemo = (checked: boolean) => {
setDemoActive(checked);
localStorage.setItem('demo_banner_disabled', (!checked).toString());
window.dispatchEvent(new Event('storage_demo_changed'));
};
const handleExport = async () => {
setExporting(true);
setStatusMsg('Export läuft...');
setStatusType('info');
try {
const res = await fetch('/api/admin/db-backup');
if (!res.ok) throw new Error('Export fehlgeschlagen');
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `webshop_backup_${new Date().toISOString().split('T')[0]}.zip`;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
setStatusMsg('Export erfolgreich abgeschlossen.');
setStatusType('success');
} catch (err: any) {
console.error(err);
setStatusMsg(`Fehler beim Export: ${err.message}`);
setStatusType('error');
} finally {
setExporting(false);
}
};
const handleImport = async () => {
if (!selectedFile) return;
if (!confirm('ACHTUNG: Dies löscht und überschreibt alle aktuellen Datenbankinhalte in dieser Instanz. Möchten Sie wirklich fortfahren?')) {
return;
}
setImporting(true);
setStatusMsg('Import läuft...');
setStatusType('info');
try {
const formData = new FormData();
formData.append('file', selectedFile);
const res = await fetch('/api/admin/db-backup', {
method: 'POST',
body: formData,
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Import fehlgeschlagen');
setStatusMsg('Datenbank erfolgreich importiert!');
setStatusType('success');
setSelectedFile(null);
} catch (err: any) {
console.error(err);
setStatusMsg(`Fehler beim Import: ${err.message}`);
setStatusType('error');
} finally {
setImporting(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>;
}
return (
<div className="p-6 max-w-7xl mx-auto text-slate-900 dark:text-white space-y-6">
{/* Header */}
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="flex items-center justify-between"
>
<div>
<h1 className="text-3xl font-extrabold tracking-tight">Admin Einstellungen</h1>
<p className="text-slate-400 text-xs mt-1">
Zentrales Bento-Dashboard für System-, Backup- und Lizenz-Konfigurationen.
</p>
</div>
</motion.div>
{/* Dynamic Status Notification */}
{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' :
'bg-sky-500/10 border-sky-500/20 text-sky-400'
}`}
>
{statusMsg}
</motion.div>
)}
{/* Bento Grid Container */}
<motion.div
variants={containerVariants}
initial="hidden"
animate="visible"
className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-5"
>
{/* Bento Item 1: System Modus & Banner (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-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>
</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
onClick={handleImport}
disabled={!selectedFile || exporting || importing}
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"
>
{importing ? (
<><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Importiert...</>
) : (
<><Upload className="w-4 h-4 mr-2" /> ZIP Einspielen</>
)}
</Button>
</div>
</motion.div>
{/* Bento Item 4: LicServer Konfiguration (Breites Bento: 4 Spalten auf Large) */}
<motion.div
variants={cardVariants}
whileHover={{ y: -3 }}
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"
>
<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-center gap-3">
<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">
<KeyRound className="w-5 h-5" />
</div>
<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>
{/* LicServer Status Pill */}
{licStatus && (
<div className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-semibold border ${
licStatus.ok
? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400'
: 'bg-amber-500/10 border-amber-500/20 text-amber-400'
}`}>
{licStatus.ok ? <CheckCircle2 className="w-3.5 h-3.5" /> : <XCircle className="w-3.5 h-3.5" />}
{licStatus.message}
</div>
)}
</div>
{licMsg && (
<div className={`p-3 rounded-xl text-xs font-medium border ${
licMsgType === 'success' ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' : 'bg-destructive/10 border-destructive/20 text-destructive'
}`}>
{licMsg}
</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-bold text-slate-300 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 bg-slate-950/80 border-slate-800 text-white rounded-xl"
/>
</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>
{/* Action Buttons */}
<div className="flex items-center justify-end gap-3 pt-2">
<Button
id="lic-save-btn"
disabled={licSaving || licTesting}
onClick={async () => {
setLicSaving(true);
setLicMsg('');
setLicStatus(null);
const res = await saveLicServerConfig(licUrl, licKey);
setLicMsgType(res.success ? 'success' : 'error');
setLicMsg(res.success ? 'Konfiguration gespeichert.' : (res.error || 'Fehler beim Speichern'));
setLicSaving(false);
}}
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" />}
Speichern
</Button>
<Button
id="lic-test-btn"
variant="outline"
disabled={licSaving || licTesting}
onClick={async () => {
setLicTesting(true);
setLicStatus(null);
await saveLicServerConfig(licUrl, licKey);
const result = await testLicServerConnection();
setLicStatus(result);
setLicTesting(false);
}}
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" />}
Verbindung testen
</Button>
</div>
</motion.div>
</motion.div>
</div>
);
}