feat(crm): end_customers table, RLS, wizard customer selector, /my-customers CRUD, GDPR anonymization
This commit is contained in:
@@ -9,7 +9,7 @@ const defaultUrl = process.env.VERCEL_URL
|
|||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
metadataBase: new URL(defaultUrl),
|
metadataBase: new URL(defaultUrl),
|
||||||
title: "CASPOSShop | Modulare Software-Lösungen",
|
title: "CASPOS-Shop | Die Kasse",
|
||||||
description: "Konfigurieren und bestellen Sie Ihre maßgeschneiderte Business-Software in Minuten.",
|
description: "Konfigurieren und bestellen Sie Ihre maßgeschneiderte Business-Software in Minuten.",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
213
shop/app/my-customers/[id]/page.tsx
Normal file
213
shop/app/my-customers/[id]/page.tsx
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { ArrowLeft, Save, AlertTriangle, Loader2, Building2, ShoppingBag, Trash2 } from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import { getEndCustomer, updateEndCustomer, anonymizeEndCustomer } from '@/lib/actions/end-customers'
|
||||||
|
import type { EndCustomer } from '@/lib/types'
|
||||||
|
|
||||||
|
export default function CustomerDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const router = useRouter()
|
||||||
|
const [customer, setCustomer] = useState<EndCustomer | null>(null)
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [anonymizing, setAnonymizing] = useState(false)
|
||||||
|
const [showGdprConfirm, setShowGdprConfirm] = useState(false)
|
||||||
|
const [form, setForm] = useState({
|
||||||
|
company_name: '', vat_id: '', first_name: '', last_name: '', street: '', zip: '', city: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
params.then(({ id }) => {
|
||||||
|
getEndCustomer(id).then(c => {
|
||||||
|
if (!c) { router.push('/my-customers'); return }
|
||||||
|
setCustomer(c)
|
||||||
|
setForm({
|
||||||
|
company_name: c.company_name ?? '',
|
||||||
|
vat_id: c.vat_id ?? '',
|
||||||
|
first_name: c.first_name ?? '',
|
||||||
|
last_name: c.last_name ?? '',
|
||||||
|
street: c.street ?? '',
|
||||||
|
zip: c.zip ?? '',
|
||||||
|
city: c.city ?? '',
|
||||||
|
})
|
||||||
|
setLoading(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}, [params, router])
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!customer || !form.company_name.trim()) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
await updateEndCustomer(customer.id, form)
|
||||||
|
setCustomer(prev => prev ? { ...prev, ...form } : prev)
|
||||||
|
alert('Kundendaten gespeichert.')
|
||||||
|
} catch (e) {
|
||||||
|
alert('Fehler beim Speichern.')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAnonymize = async () => {
|
||||||
|
if (!customer) return
|
||||||
|
setAnonymizing(true)
|
||||||
|
try {
|
||||||
|
await anonymizeEndCustomer(customer.id)
|
||||||
|
router.push('/my-customers')
|
||||||
|
} catch (e) {
|
||||||
|
alert('Fehler bei der Anonymisierung.')
|
||||||
|
setAnonymizing(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-[#020617] flex items-center justify-center">
|
||||||
|
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!customer) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-[#020617] text-white px-4 py-12">
|
||||||
|
<div className="max-w-3xl mx-auto space-y-6">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<Link href="/my-customers">
|
||||||
|
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-white">
|
||||||
|
<ArrowLeft className="w-4 h-4 mr-2" /> Meine Kunden
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-extrabold tracking-tight flex items-center gap-2">
|
||||||
|
<Building2 className="w-6 h-6 text-primary" />
|
||||||
|
{customer.is_anonymized ? '[Anonymisiert]' : customer.company_name}
|
||||||
|
</h1>
|
||||||
|
<p className="text-slate-400 text-xs mt-0.5">
|
||||||
|
Kunden-ID: <span className="font-mono">{customer.id.slice(0, 8)}…</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{customer.is_anonymized && (
|
||||||
|
<Badge className="bg-red-500/10 text-red-400 border-red-500/20 gap-1 ml-auto">
|
||||||
|
<AlertTriangle className="w-3 h-3" /> Anonymisiert
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bearbeitungsformular */}
|
||||||
|
{!customer.is_anonymized && (
|
||||||
|
<Card className="glass-dark border-white/10">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white">Stammdaten bearbeiten</CardTitle>
|
||||||
|
<CardDescription className="text-slate-400">
|
||||||
|
Änderungen wirken sich nur auf zukünftige Bestellungen aus. Bestehende Snapshots bleiben unverändert.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
|
{([
|
||||||
|
{ label: 'Firmenname *', key: 'company_name', span: true },
|
||||||
|
{ label: 'USt-IdNr.', key: 'vat_id', span: false },
|
||||||
|
{ label: 'Vorname', key: 'first_name', span: false },
|
||||||
|
{ label: 'Nachname', key: 'last_name', span: false },
|
||||||
|
{ label: 'Straße & Hausnummer', key: 'street', span: true },
|
||||||
|
{ label: 'PLZ', key: 'zip', span: false },
|
||||||
|
{ label: 'Ort', key: 'city', span: false },
|
||||||
|
] as const).map(({ label, key, span }) => (
|
||||||
|
<div key={key} className={`space-y-1.5 ${span ? 'md:col-span-2' : ''}`}>
|
||||||
|
<Label className="text-slate-300 text-sm">{label}</Label>
|
||||||
|
<Input
|
||||||
|
value={form[key]}
|
||||||
|
onChange={e => setForm(prev => ({ ...prev, [key]: e.target.value }))}
|
||||||
|
className="bg-white/5 border-white/10 text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3 pt-2">
|
||||||
|
<Button onClick={handleSave} disabled={saving || !form.company_name.trim()} className="gap-2">
|
||||||
|
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||||
|
Speichern
|
||||||
|
</Button>
|
||||||
|
<Link href={`/my-orders`}>
|
||||||
|
<Button variant="outline" className="border-white/10 hover:bg-white/5 gap-2">
|
||||||
|
<ShoppingBag className="w-4 h-4" /> Bestellungen ansehen
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* DSGVO Anonymisierung */}
|
||||||
|
{!customer.is_anonymized && (
|
||||||
|
<Card className="glass-dark border-red-500/20 bg-red-500/5">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-red-400 flex items-center gap-2">
|
||||||
|
<Trash2 className="w-5 h-5" />
|
||||||
|
Recht auf Vergessenwerden (DSGVO)
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-slate-400">
|
||||||
|
Auf Wunsch des Endkunden können Sie dessen personenbezogene Daten unwiderruflich anonymisieren.
|
||||||
|
Bestehende Bestelldaten (PDF-Rechnungen, Snapshots) werden aus steuerrechtlichen Gründen
|
||||||
|
<strong className="text-white"> nicht </strong> gelöscht.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{!showGdprConfirm ? (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="border-red-500/30 text-red-400 hover:bg-red-500/10 gap-2"
|
||||||
|
onClick={() => setShowGdprConfirm(true)}
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4" /> Kundendaten anonymisieren
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3 p-4 rounded-lg bg-red-500/10 border border-red-500/30">
|
||||||
|
<p className="text-sm text-red-300 font-semibold">
|
||||||
|
⚠️ Diese Aktion ist unwiderruflich. Alle personenbezogenen Daten werden überschrieben.
|
||||||
|
</p>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button
|
||||||
|
onClick={handleAnonymize}
|
||||||
|
disabled={anonymizing}
|
||||||
|
className="bg-red-600 hover:bg-red-700 gap-2"
|
||||||
|
>
|
||||||
|
{anonymizing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
|
||||||
|
Ja, unwiderruflich anonymisieren
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" onClick={() => setShowGdprConfirm(false)}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Bereits anonymisiert */}
|
||||||
|
{customer.is_anonymized && (
|
||||||
|
<Card className="glass-dark border-white/10">
|
||||||
|
<CardContent className="py-8 text-center space-y-2">
|
||||||
|
<AlertTriangle className="w-10 h-10 text-amber-400 mx-auto" />
|
||||||
|
<p className="text-slate-300">Dieser Endkunde wurde bereits anonymisiert.</p>
|
||||||
|
<p className="text-slate-500 text-sm">Die Daten können nicht wiederhergestellt werden.</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
94
shop/app/my-customers/new/page.tsx
Normal file
94
shop/app/my-customers/new/page.tsx
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { ArrowLeft, UserPlus, Loader2 } from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { createEndCustomer } from '@/lib/actions/end-customers'
|
||||||
|
|
||||||
|
export default function NewCustomerPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [form, setForm] = useState({
|
||||||
|
company_name: '', vat_id: '', first_name: '', last_name: '', street: '', zip: '', city: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!form.company_name.trim()) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
await createEndCustomer(form)
|
||||||
|
router.push('/my-customers')
|
||||||
|
} catch (e) {
|
||||||
|
alert('Fehler beim Anlegen des Kunden.')
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-[#020617] text-white px-4 py-12">
|
||||||
|
<div className="max-w-2xl mx-auto space-y-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<Link href="/my-customers">
|
||||||
|
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-white">
|
||||||
|
<ArrowLeft className="w-4 h-4 mr-2" /> Zurück
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<h1 className="text-2xl font-extrabold tracking-tight flex items-center gap-2">
|
||||||
|
<UserPlus className="w-6 h-6 text-primary" />
|
||||||
|
Neuen Endkunden anlegen
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card className="glass-dark border-white/10">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white">Stammdaten</CardTitle>
|
||||||
|
<CardDescription className="text-slate-400">
|
||||||
|
Legen Sie einen neuen Endkunden an. Diese Daten stehen sofort im Bestellwizard zur Auswahl.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
|
{([
|
||||||
|
{ label: 'Firmenname *', key: 'company_name', span: true, placeholder: 'GmbH / KG / Einzelunternehmen' },
|
||||||
|
{ label: 'USt-IdNr.', key: 'vat_id', span: false, placeholder: 'DE123456789' },
|
||||||
|
{ label: 'Vorname', key: 'first_name', span: false, placeholder: '' },
|
||||||
|
{ label: 'Nachname', key: 'last_name', span: false, placeholder: '' },
|
||||||
|
{ label: 'Straße & Hausnummer', key: 'street', span: true, placeholder: 'Musterstraße 1' },
|
||||||
|
{ label: 'PLZ', key: 'zip', span: false, placeholder: '12345' },
|
||||||
|
{ label: 'Ort', key: 'city', span: false, placeholder: 'Musterstadt' },
|
||||||
|
] as const).map(({ label, key, span, placeholder }) => (
|
||||||
|
<div key={key} className={`space-y-1.5 ${span ? 'md:col-span-2' : ''}`}>
|
||||||
|
<Label className="text-slate-300 text-sm">{label}</Label>
|
||||||
|
<Input
|
||||||
|
value={form[key]}
|
||||||
|
onChange={e => setForm(prev => ({ ...prev, [key]: e.target.value }))}
|
||||||
|
placeholder={placeholder}
|
||||||
|
className="bg-white/5 border-white/10 text-white placeholder:text-slate-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3 pt-2">
|
||||||
|
<Button
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={saving || !form.company_name.trim()}
|
||||||
|
className="gap-2"
|
||||||
|
>
|
||||||
|
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <UserPlus className="w-4 h-4" />}
|
||||||
|
Kunden anlegen
|
||||||
|
</Button>
|
||||||
|
<Link href="/my-customers">
|
||||||
|
<Button variant="ghost">Abbrechen</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
151
shop/app/my-customers/page.tsx
Normal file
151
shop/app/my-customers/page.tsx
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
import { createClient } from '@/lib/supabase/server'
|
||||||
|
import { redirect } from 'next/navigation'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { getEndCustomers } from '@/lib/actions/end-customers'
|
||||||
|
import { ArrowLeft, Building2, Plus, Edit2, AlertTriangle } from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
|
||||||
|
export default async function MyCustomersPage() {
|
||||||
|
const supabase = await createClient()
|
||||||
|
const { data: { user } } = await supabase.auth.getUser()
|
||||||
|
if (!user) redirect('/auth/login')
|
||||||
|
|
||||||
|
const customers = await getEndCustomers()
|
||||||
|
|
||||||
|
// Anzahl Bestellungen pro Endkunde
|
||||||
|
const { data: orderCounts } = await supabase
|
||||||
|
.from('orders')
|
||||||
|
.select('end_customer_id')
|
||||||
|
.not('end_customer_id', 'is', null)
|
||||||
|
|
||||||
|
const countMap: Record<string, number> = {}
|
||||||
|
;(orderCounts ?? []).forEach(o => {
|
||||||
|
if (o.end_customer_id) {
|
||||||
|
countMap[o.end_customer_id] = (countMap[o.end_customer_id] ?? 0) + 1
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-[#020617] text-white px-4 py-12">
|
||||||
|
<div className="max-w-5xl mx-auto space-y-8">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<Link href="/">
|
||||||
|
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-white">
|
||||||
|
<ArrowLeft className="w-4 h-4 mr-2" /> Startseite
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-extrabold tracking-tight flex items-center gap-3">
|
||||||
|
<Building2 className="w-8 h-8 text-primary" />
|
||||||
|
Meine Kunden
|
||||||
|
</h1>
|
||||||
|
<p className="text-slate-400 text-sm mt-1">
|
||||||
|
Verwalten Sie Ihre Endkunden – deren Daten werden für Bestellungen verwendet.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Link href="/my-customers/new">
|
||||||
|
<Button className="gap-2">
|
||||||
|
<Plus className="w-4 h-4" /> Kunde hinzufügen
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Keine Kunden */}
|
||||||
|
{customers.length === 0 && (
|
||||||
|
<Card className="glass-dark border-white/10">
|
||||||
|
<CardContent className="flex flex-col items-center justify-center py-16 gap-4">
|
||||||
|
<Building2 className="w-12 h-12 text-slate-600" />
|
||||||
|
<p className="text-slate-400 text-lg">Noch keine Endkunden angelegt.</p>
|
||||||
|
<Link href="/my-customers/new">
|
||||||
|
<Button><Plus className="w-4 h-4 mr-2" /> Ersten Kunden anlegen</Button>
|
||||||
|
</Link>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Kundenliste */}
|
||||||
|
{customers.length > 0 && (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-white/10 text-left">
|
||||||
|
<th className="pb-3 text-xs font-semibold text-slate-400 uppercase tracking-wider">Unternehmen</th>
|
||||||
|
<th className="pb-3 text-xs font-semibold text-slate-400 uppercase tracking-wider hidden sm:table-cell">Adresse</th>
|
||||||
|
<th className="pb-3 text-xs font-semibold text-slate-400 uppercase tracking-wider hidden md:table-cell">Bestellungen</th>
|
||||||
|
<th className="pb-3 text-xs font-semibold text-slate-400 uppercase tracking-wider">Status</th>
|
||||||
|
<th className="pb-3 text-xs font-semibold text-slate-400 uppercase tracking-wider text-right">Aktionen</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-white/5">
|
||||||
|
{customers.map(customer => (
|
||||||
|
<tr key={customer.id} className="hover:bg-white/3 transition-colors">
|
||||||
|
<td className="py-4 pr-4">
|
||||||
|
<p className="font-semibold text-white">{customer.company_name}</p>
|
||||||
|
{(customer.first_name || customer.last_name) && (
|
||||||
|
<p className="text-sm text-slate-400">
|
||||||
|
{[customer.first_name, customer.last_name].filter(Boolean).join(' ')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{customer.vat_id && (
|
||||||
|
<p className="text-xs text-slate-500">{customer.vat_id}</p>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="py-4 pr-4 hidden sm:table-cell">
|
||||||
|
<p className="text-sm text-slate-300">
|
||||||
|
{customer.street ?? '–'}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-slate-400">
|
||||||
|
{[customer.zip, customer.city].filter(Boolean).join(' ') || '–'}
|
||||||
|
</p>
|
||||||
|
</td>
|
||||||
|
<td className="py-4 pr-4 hidden md:table-cell">
|
||||||
|
<Link href={`/my-orders?customer=${customer.id}`} className="group">
|
||||||
|
<span className="text-primary font-bold group-hover:underline">
|
||||||
|
{countMap[customer.id] ?? 0}
|
||||||
|
</span>
|
||||||
|
<span className="text-slate-500 text-xs ml-1">Bestellung(en)</span>
|
||||||
|
</Link>
|
||||||
|
</td>
|
||||||
|
<td className="py-4 pr-4">
|
||||||
|
{customer.is_anonymized ? (
|
||||||
|
<Badge className="bg-red-500/10 text-red-400 border-red-500/20 gap-1">
|
||||||
|
<AlertTriangle className="w-3 h-3" /> Anonymisiert
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge className="bg-green-500/10 text-green-400 border-green-500/20">Aktiv</Badge>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="py-4 text-right">
|
||||||
|
{!customer.is_anonymized && (
|
||||||
|
<Link href={`/my-customers/${customer.id}`}>
|
||||||
|
<Button variant="ghost" size="sm" className="text-slate-400 hover:text-white gap-1">
|
||||||
|
<Edit2 className="w-3.5 h-3.5" /> Bearbeiten
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* DSGVO-Hinweis */}
|
||||||
|
<div className="p-4 rounded-xl bg-amber-500/5 border border-amber-500/20 text-xs text-amber-300/80 space-y-1">
|
||||||
|
<p className="font-semibold flex items-center gap-2"><AlertTriangle className="w-3.5 h-3.5" /> DSGVO-Hinweis</p>
|
||||||
|
<p>
|
||||||
|
Die hier gespeicherten Kundendaten unterliegen der DSGVO. Auf Wunsch Ihrer Endkunden können Sie deren Daten
|
||||||
|
über die Bearbeitungsmaske anonymisieren (Recht auf Vergessenwerden). Bestehende Bestellungen bleiben aus
|
||||||
|
steuerrechtlichen Gründen unverändert.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createClient } from '@/lib/supabase/server'
|
import { createClient } from '@/lib/supabase/server'
|
||||||
import { getProducts, getCategories } from '@/lib/actions/products'
|
import { getProducts, getCategories } from '@/lib/actions/products'
|
||||||
|
import { getEndCustomers } from '@/lib/actions/end-customers'
|
||||||
import { OrderWizard } from '@/components/order-wizard'
|
import { OrderWizard } from '@/components/order-wizard'
|
||||||
import { redirect } from 'next/navigation'
|
import { redirect } from 'next/navigation'
|
||||||
import { Suspense } from 'react'
|
import { Suspense } from 'react'
|
||||||
@@ -35,7 +36,8 @@ async function OrderDataWrapper() {
|
|||||||
|
|
||||||
const products = await getProducts()
|
const products = await getProducts()
|
||||||
const categories = await getCategories()
|
const categories = await getCategories()
|
||||||
|
const endCustomers = await getEndCustomers()
|
||||||
|
|
||||||
// Fetch profile if exists
|
// Fetch profile if exists
|
||||||
const { data: profile } = await supabase
|
const { data: profile } = await supabase
|
||||||
.from('profiles')
|
.from('profiles')
|
||||||
@@ -43,5 +45,5 @@ async function OrderDataWrapper() {
|
|||||||
.eq('id', user.id)
|
.eq('id', user.id)
|
||||||
.single()
|
.single()
|
||||||
|
|
||||||
return <OrderWizard products={products} categories={categories} initialProfile={profile} />
|
return <OrderWizard products={products} categories={categories} initialProfile={profile} initialEndCustomers={endCustomers} />
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ export default function Home() {
|
|||||||
<Link className="text-sm font-medium hover:text-primary transition-colors" href="/order">
|
<Link className="text-sm font-medium hover:text-primary transition-colors" href="/order">
|
||||||
Bestellen
|
Bestellen
|
||||||
</Link>
|
</Link>
|
||||||
|
<Link className="text-sm font-medium hover:text-primary transition-colors" href="/my-customers">
|
||||||
|
Meine Kunden
|
||||||
|
</Link>
|
||||||
<Link className="text-sm font-medium hover:text-primary transition-colors" href="/my-orders">
|
<Link className="text-sm font-medium hover:text-primary transition-colors" href="/my-orders">
|
||||||
Meine Bestellungen
|
Meine Bestellungen
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { useState, useMemo } from 'react'
|
import { useState, useMemo } from 'react'
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { motion, AnimatePresence } from 'framer-motion'
|
import { motion, AnimatePresence } from 'framer-motion'
|
||||||
import { Product, ProductModule, Profile } from '@/lib/types'
|
import { Product, ProductModule, Profile, EndCustomer } from '@/lib/types'
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card'
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Checkbox } from '@/components/ui/checkbox'
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
@@ -11,8 +11,9 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { Separator } from '@/components/ui/separator'
|
import { Separator } from '@/components/ui/separator'
|
||||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||||
import { Check, ChevronRight, ChevronLeft, ShoppingCart, User, ShieldCheck, Cloud, Utensils, HardDrive, Package, AlertCircle, Loader2 } from 'lucide-react'
|
import { Check, ChevronRight, ChevronLeft, ShoppingCart, User, ShieldCheck, Cloud, Utensils, HardDrive, Package, AlertCircle, Loader2, UserPlus, Building2 } from 'lucide-react'
|
||||||
import { submitOrder } from '@/lib/actions/orders'
|
import { submitOrder } from '@/lib/actions/orders'
|
||||||
|
import { createEndCustomer } from '@/lib/actions/end-customers'
|
||||||
import { Category } from '@/lib/types'
|
import { Category } from '@/lib/types'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
|
||||||
@@ -72,25 +73,33 @@ export function OrderWizard({
|
|||||||
products,
|
products,
|
||||||
categories,
|
categories,
|
||||||
initialProfile,
|
initialProfile,
|
||||||
|
initialEndCustomers,
|
||||||
}: {
|
}: {
|
||||||
products: Product[]
|
products: Product[]
|
||||||
categories: Category[]
|
categories: Category[]
|
||||||
initialProfile: Profile | null
|
initialProfile: Profile | null
|
||||||
|
initialEndCustomers: EndCustomer[]
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const [step, setStep] = useState(1)
|
const [step, setStep] = useState(1)
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
const [customerData, setCustomerData] = useState<Partial<Profile>>(
|
|
||||||
initialProfile || {
|
// Partner-Profil (Fallback)
|
||||||
company_name: '',
|
const [customerData] = useState<Partial<Profile>>(initialProfile || {})
|
||||||
vat_id: '',
|
|
||||||
first_name: '',
|
// Endkunden-State
|
||||||
last_name: '',
|
const [endCustomers, setEndCustomers] = useState<EndCustomer[]>(initialEndCustomers)
|
||||||
address: '',
|
const [selectedEndCustomerId, setSelectedEndCustomerId] = useState<string | null>(
|
||||||
city: '',
|
initialEndCustomers.length > 0 ? initialEndCustomers[0].id : null
|
||||||
zip_code: '',
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
const selectedEndCustomer = endCustomers.find(c => c.id === selectedEndCustomerId) ?? null
|
||||||
|
|
||||||
|
// Modus: 'select' = Bestandskunde wählen | 'create' = Neuen anlegen
|
||||||
|
const [customerMode, setCustomerMode] = useState<'select' | 'create'>('select')
|
||||||
|
const [isCreatingCustomer, setIsCreatingCustomer] = useState(false)
|
||||||
|
const [newCustomerForm, setNewCustomerForm] = useState({
|
||||||
|
company_name: '', vat_id: '', first_name: '', last_name: '', street: '', zip: '', city: '',
|
||||||
|
})
|
||||||
|
|
||||||
// Per-category selection map: categoryId -> { productId, moduleIds }
|
// Per-category selection map: categoryId -> { productId, moduleIds }
|
||||||
const [selections, setSelections] = useState<Record<string, CategorySelection>>(() => {
|
const [selections, setSelections] = useState<Record<string, CategorySelection>>(() => {
|
||||||
@@ -147,6 +156,23 @@ export function OrderWizard({
|
|||||||
const nextStep = () => setStep(s => s + 1)
|
const nextStep = () => setStep(s => s + 1)
|
||||||
const prevStep = () => setStep(s => s - 1)
|
const prevStep = () => setStep(s => s - 1)
|
||||||
|
|
||||||
|
// Neuen Endkunden inline anlegen
|
||||||
|
const handleCreateCustomer = async () => {
|
||||||
|
if (!newCustomerForm.company_name.trim()) return
|
||||||
|
setIsCreatingCustomer(true)
|
||||||
|
try {
|
||||||
|
const created = await createEndCustomer(newCustomerForm)
|
||||||
|
setEndCustomers(prev => [...prev, created])
|
||||||
|
setSelectedEndCustomerId(created.id)
|
||||||
|
setCustomerMode('select')
|
||||||
|
setNewCustomerForm({ company_name: '', vat_id: '', first_name: '', last_name: '', street: '', zip: '', city: '' })
|
||||||
|
} catch (e) {
|
||||||
|
alert('Fehler beim Anlegen des Kunden.')
|
||||||
|
} finally {
|
||||||
|
setIsCreatingCustomer(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
if (isSubmitting) return // Doppelklick-Guard
|
if (isSubmitting) return // Doppelklick-Guard
|
||||||
setIsSubmitting(true)
|
setIsSubmitting(true)
|
||||||
@@ -156,6 +182,8 @@ export function OrderWizard({
|
|||||||
products,
|
products,
|
||||||
categories,
|
categories,
|
||||||
customerProfile: customerData,
|
customerProfile: customerData,
|
||||||
|
endCustomerId: selectedEndCustomerId,
|
||||||
|
endCustomer: selectedEndCustomer,
|
||||||
})
|
})
|
||||||
router.push(`/order/success?id=${order.id}`)
|
router.push(`/order/success?id=${order.id}`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -425,7 +453,7 @@ export function OrderWizard({
|
|||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* ───── Step 2: Customer Data ───── */}
|
{/* ───── Step 2: Endkunde wählen / anlegen ───── */}
|
||||||
{step === 2 && (
|
{step === 2 && (
|
||||||
<motion.div
|
<motion.div
|
||||||
key="step2"
|
key="step2"
|
||||||
@@ -438,38 +466,127 @@ export function OrderWizard({
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-2xl flex items-center gap-2">
|
<CardTitle className="text-2xl flex items-center gap-2">
|
||||||
<User className="w-6 h-6 text-primary" />
|
<User className="w-6 h-6 text-primary" />
|
||||||
Kundendaten
|
Für wen bestellen Sie?
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription className="text-slate-300">
|
<CardDescription className="text-slate-300">
|
||||||
Wir benötigen Ihre Daten für die Rechnungsstellung.
|
Wählen Sie einen Endkunden aus Ihrem CRM oder legen Sie einen neuen an.
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="grid md:grid-cols-2 gap-6">
|
<CardContent className="space-y-6">
|
||||||
{[
|
{/* Modus-Toggle */}
|
||||||
{ label: 'Firmenname', key: 'company_name', placeholder: 'GmbH / Einzelunternehmen', span: false },
|
<div className="flex gap-2">
|
||||||
{ label: 'USt-IdNr.', key: 'vat_id', placeholder: 'DE123456789', span: false },
|
<Button
|
||||||
{ label: 'Vorname', key: 'first_name', placeholder: '', span: false },
|
variant={customerMode === 'select' ? 'default' : 'ghost'}
|
||||||
{ label: 'Nachname', key: 'last_name', placeholder: '', span: false },
|
size="sm"
|
||||||
{ label: 'Straße & Hausnummer', key: 'address', placeholder: '', span: true },
|
onClick={() => setCustomerMode('select')}
|
||||||
{ label: 'Postleitzahl', key: 'zip_code', placeholder: '', span: false },
|
className="gap-2"
|
||||||
{ label: 'Ort', key: 'city', placeholder: '', span: false },
|
>
|
||||||
].map(({ label, key, placeholder, span }) => (
|
<Building2 className="w-4 h-4" /> Bestandskunde wählen
|
||||||
<div key={key} className={`space-y-2 ${span ? 'md:col-span-2' : ''}`}>
|
</Button>
|
||||||
<Label className="text-white">{label}</Label>
|
<Button
|
||||||
<Input
|
variant={customerMode === 'create' ? 'default' : 'ghost'}
|
||||||
value={(customerData as any)[key] || ''}
|
size="sm"
|
||||||
onChange={e => setCustomerData({ ...customerData, [key]: e.target.value })}
|
onClick={() => setCustomerMode('create')}
|
||||||
placeholder={placeholder}
|
className="gap-2"
|
||||||
className="bg-white/5 border-white/10 text-white placeholder:text-slate-500"
|
>
|
||||||
/>
|
<UserPlus className="w-4 h-4" /> Neuen Kunden anlegen
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modus A: Bestandskunde wählen */}
|
||||||
|
{customerMode === 'select' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{endCustomers.length === 0 ? (
|
||||||
|
<div className="p-6 rounded-xl bg-white/5 border border-white/10 text-center space-y-3">
|
||||||
|
<Building2 className="w-10 h-10 text-slate-600 mx-auto" />
|
||||||
|
<p className="text-slate-400">Noch keine Endkunden angelegt.</p>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setCustomerMode('create')} className="border-white/10">
|
||||||
|
<UserPlus className="w-4 h-4 mr-2" /> Ersten Kunden anlegen
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{endCustomers.filter(c => !c.is_anonymized).map(customer => (
|
||||||
|
<label
|
||||||
|
key={customer.id}
|
||||||
|
className={`flex items-start p-4 rounded-xl border-2 cursor-pointer transition-all ${
|
||||||
|
selectedEndCustomerId === customer.id
|
||||||
|
? 'border-primary bg-primary/5'
|
||||||
|
: 'border-white/5 bg-white/5 hover:bg-white/10'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="end_customer"
|
||||||
|
value={customer.id}
|
||||||
|
checked={selectedEndCustomerId === customer.id}
|
||||||
|
onChange={() => setSelectedEndCustomerId(customer.id)}
|
||||||
|
className="sr-only"
|
||||||
|
/>
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className="font-semibold text-white">{customer.company_name}</p>
|
||||||
|
<p className="text-sm text-slate-400">
|
||||||
|
{[customer.first_name, customer.last_name].filter(Boolean).join(' ')}
|
||||||
|
{customer.first_name || customer.last_name ? ' · ' : ''}
|
||||||
|
{[customer.street, customer.zip, customer.city].filter(Boolean).join(', ')}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{selectedEndCustomerId === customer.id && (
|
||||||
|
<Check className="w-5 h-5 text-primary mt-0.5 shrink-0" />
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
)}
|
||||||
|
|
||||||
|
{/* Modus B: Neuen Kunden anlegen */}
|
||||||
|
{customerMode === 'create' && (
|
||||||
|
<div className="grid md:grid-cols-2 gap-4 p-4 rounded-xl bg-white/5 border border-white/10">
|
||||||
|
{([
|
||||||
|
{ label: 'Firmenname *', key: 'company_name', span: true, placeholder: 'GmbH / Einzelunternehmen' },
|
||||||
|
{ label: 'USt-IdNr.', key: 'vat_id', span: false, placeholder: 'DE123456789' },
|
||||||
|
{ label: 'Vorname', key: 'first_name', span: false, placeholder: '' },
|
||||||
|
{ label: 'Nachname', key: 'last_name', span: false, placeholder: '' },
|
||||||
|
{ label: 'Straße & Hausnummer', key: 'street', span: true, placeholder: '' },
|
||||||
|
{ label: 'PLZ', key: 'zip', span: false, placeholder: '' },
|
||||||
|
{ label: 'Ort', key: 'city', span: false, placeholder: '' },
|
||||||
|
] as const).map(({ label, key, span, placeholder }) => (
|
||||||
|
<div key={key} className={`space-y-1.5 ${span ? 'md:col-span-2' : ''}`}>
|
||||||
|
<Label className="text-slate-300 text-sm">{label}</Label>
|
||||||
|
<Input
|
||||||
|
value={newCustomerForm[key]}
|
||||||
|
onChange={e => setNewCustomerForm(prev => ({ ...prev, [key]: e.target.value }))}
|
||||||
|
placeholder={placeholder}
|
||||||
|
className="bg-white/5 border-white/10 text-white placeholder:text-slate-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="md:col-span-2 flex gap-2">
|
||||||
|
<Button
|
||||||
|
onClick={handleCreateCustomer}
|
||||||
|
disabled={isCreatingCustomer || !newCustomerForm.company_name.trim()}
|
||||||
|
className="gap-2"
|
||||||
|
>
|
||||||
|
{isCreatingCustomer ? <Loader2 className="w-4 h-4 animate-spin" /> : <UserPlus className="w-4 h-4" />}
|
||||||
|
Kunden speichern & auswählen
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" onClick={() => setCustomerMode('select')}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
</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" onClick={prevStep}>
|
<Button variant="ghost" onClick={prevStep}>
|
||||||
<ChevronLeft className="mr-2 w-4 h-4" /> Zurück
|
<ChevronLeft className="mr-2 w-4 h-4" /> Zurück
|
||||||
</Button>
|
</Button>
|
||||||
<Button onClick={nextStep}>
|
<Button
|
||||||
|
onClick={nextStep}
|
||||||
|
disabled={customerMode === 'select' && endCustomers.filter(c => !c.is_anonymized).length > 0 && !selectedEndCustomerId}
|
||||||
|
>
|
||||||
Prüfung & Abschluss <ChevronRight className="ml-2 w-4 h-4" />
|
Prüfung & Abschluss <ChevronRight className="ml-2 w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
@@ -533,13 +650,23 @@ export function OrderWizard({
|
|||||||
})}
|
})}
|
||||||
<Separator className="bg-white/10" />
|
<Separator className="bg-white/10" />
|
||||||
<div className="text-sm text-slate-300 space-y-1">
|
<div className="text-sm text-slate-300 space-y-1">
|
||||||
<p className="font-semibold text-white">{customerData.company_name}</p>
|
{selectedEndCustomer ? (
|
||||||
<p>
|
<>
|
||||||
{customerData.first_name} {customerData.last_name}
|
<p className="font-semibold text-white flex items-center gap-2">
|
||||||
</p>
|
<Building2 className="w-3.5 h-3.5 text-primary" />
|
||||||
<p>
|
{selectedEndCustomer.company_name}
|
||||||
{customerData.address}, {customerData.zip_code} {customerData.city}
|
</p>
|
||||||
</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>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<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>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between text-xl font-bold text-gradient">
|
<div className="flex justify-between text-xl font-bold text-gradient">
|
||||||
|
|||||||
145
shop/lib/actions/end-customers.ts
Normal file
145
shop/lib/actions/end-customers.ts
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
'use server'
|
||||||
|
|
||||||
|
import { createClient } from '@/lib/supabase/server'
|
||||||
|
import { revalidatePath } from 'next/cache'
|
||||||
|
import type { EndCustomer } from '@/lib/types'
|
||||||
|
|
||||||
|
// ─── Typen ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export type EndCustomerFormData = {
|
||||||
|
company_name: string
|
||||||
|
vat_id?: string
|
||||||
|
first_name?: string
|
||||||
|
last_name?: string
|
||||||
|
street?: string
|
||||||
|
zip?: string
|
||||||
|
city?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Lesen ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holt alle (nicht anonymisierten) Endkunden des eingeloggten Partners.
|
||||||
|
* RLS stellt sicher, dass nur eigene Kunden zurückgegeben werden.
|
||||||
|
*/
|
||||||
|
export async function getEndCustomers(): Promise<EndCustomer[]> {
|
||||||
|
const supabase = await createClient()
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('end_customers')
|
||||||
|
.select('*')
|
||||||
|
.order('company_name', { ascending: true })
|
||||||
|
|
||||||
|
if (error) throw error
|
||||||
|
return data as EndCustomer[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holt einen einzelnen Endkunden (Eigentümerprüfung via RLS).
|
||||||
|
*/
|
||||||
|
export async function getEndCustomer(id: string): Promise<EndCustomer | null> {
|
||||||
|
const supabase = await createClient()
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('end_customers')
|
||||||
|
.select('*')
|
||||||
|
.eq('id', id)
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (error) return null
|
||||||
|
return data as EndCustomer
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Erstellen ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Legt einen neuen Endkunden für den eingeloggten Partner an.
|
||||||
|
* partner_id wird serverseitig aus der Session gesetzt (kein Client-Trust).
|
||||||
|
*/
|
||||||
|
export async function createEndCustomer(formData: EndCustomerFormData): Promise<EndCustomer> {
|
||||||
|
const supabase = await createClient()
|
||||||
|
|
||||||
|
const { data: { user } } = await supabase.auth.getUser()
|
||||||
|
if (!user) throw new Error('Not authenticated')
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('end_customers')
|
||||||
|
.insert([{
|
||||||
|
partner_id: user.id,
|
||||||
|
company_name: formData.company_name,
|
||||||
|
vat_id: formData.vat_id || null,
|
||||||
|
first_name: formData.first_name || null,
|
||||||
|
last_name: formData.last_name || null,
|
||||||
|
street: formData.street || null,
|
||||||
|
zip: formData.zip || null,
|
||||||
|
city: formData.city || null,
|
||||||
|
}])
|
||||||
|
.select()
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (error) throw error
|
||||||
|
|
||||||
|
revalidatePath('/my-customers')
|
||||||
|
return data as EndCustomer
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Aktualisieren ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aktualisiert Adressdaten eines Endkunden.
|
||||||
|
* RLS verhindert Zugriff auf fremde Kunden.
|
||||||
|
*/
|
||||||
|
export async function updateEndCustomer(id: string, formData: EndCustomerFormData): Promise<void> {
|
||||||
|
const supabase = await createClient()
|
||||||
|
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('end_customers')
|
||||||
|
.update({
|
||||||
|
company_name: formData.company_name,
|
||||||
|
vat_id: formData.vat_id || null,
|
||||||
|
first_name: formData.first_name || null,
|
||||||
|
last_name: formData.last_name || null,
|
||||||
|
street: formData.street || null,
|
||||||
|
zip: formData.zip || null,
|
||||||
|
city: formData.city || null,
|
||||||
|
})
|
||||||
|
.eq('id', id)
|
||||||
|
|
||||||
|
if (error) throw error
|
||||||
|
|
||||||
|
revalidatePath('/my-customers')
|
||||||
|
revalidatePath(`/my-customers/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── DSGVO: Anonymisieren ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Anonymisiert einen Endkunden gemäß DSGVO „Recht auf Vergessenwerden".
|
||||||
|
*
|
||||||
|
* - Überschreibt alle personenbezogenen Felder mit [GELÖSCHT]
|
||||||
|
* - Setzt is_anonymized = true (verhindert weitere Bearbeitung)
|
||||||
|
* - LÖSCHT NICHT die Zeile (FK in orders bleibt erhalten)
|
||||||
|
* - Bestell-Snapshots in orders.customer_data werden NICHT verändert
|
||||||
|
* (steuerrechtliche Aufbewahrungspflicht)
|
||||||
|
*/
|
||||||
|
export async function anonymizeEndCustomer(id: string): Promise<void> {
|
||||||
|
const supabase = await createClient()
|
||||||
|
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('end_customers')
|
||||||
|
.update({
|
||||||
|
company_name: '[GELÖSCHT]',
|
||||||
|
vat_id: null,
|
||||||
|
first_name: '[GELÖSCHT]',
|
||||||
|
last_name: null,
|
||||||
|
street: null,
|
||||||
|
zip: null,
|
||||||
|
city: null,
|
||||||
|
is_anonymized: true,
|
||||||
|
})
|
||||||
|
.eq('id', id)
|
||||||
|
.eq('is_anonymized', false) // Keine doppelte Anonymisierung
|
||||||
|
|
||||||
|
if (error) throw error
|
||||||
|
|
||||||
|
revalidatePath('/my-customers')
|
||||||
|
revalidatePath(`/my-customers/${id}`)
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import { InvoicePDF } from '@/components/invoice-pdf'
|
|||||||
import { renderToBuffer } from '@react-pdf/renderer'
|
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, Order, Product, Profile, WizardSelections } from '@/lib/types'
|
import type { Category, EndCustomer, Order, Product, Profile, WizardSelections } from '@/lib/types'
|
||||||
|
|
||||||
// ─── Hilfsfunktionen ─────────────────────────────────────────────────────────
|
// ─── Hilfsfunktionen ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -51,15 +51,18 @@ export async function submitOrder(params: {
|
|||||||
products: Product[]
|
products: Product[]
|
||||||
categories: Category[]
|
categories: Category[]
|
||||||
customerProfile: Partial<Profile>
|
customerProfile: Partial<Profile>
|
||||||
|
endCustomerId?: string | null
|
||||||
|
endCustomer?: EndCustomer | null
|
||||||
}): Promise<Order> {
|
}): Promise<Order> {
|
||||||
const { selections, products, categories, customerProfile } = params
|
const { selections, products, categories, 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')
|
||||||
|
|
||||||
// 1. Snapshots aufbauen
|
// 1. Snapshots aufbauen
|
||||||
const customerSnapshot = buildCustomerSnapshot(customerProfile)
|
// Wenn Endkunde vorhanden: dessen Daten einfrieren; sonst Partner-Profil (Fallback)
|
||||||
|
const customerSnapshot = buildCustomerSnapshot(customerProfile, endCustomer ?? null)
|
||||||
const orderSnapshot = buildOrderSnapshot(selections, products, categories)
|
const orderSnapshot = buildOrderSnapshot(selections, products, categories)
|
||||||
|
|
||||||
// 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
|
||||||
@@ -102,6 +105,7 @@ export async function submitOrder(params: {
|
|||||||
user_id: user.id,
|
user_id: user.id,
|
||||||
order_number: orderNumber,
|
order_number: orderNumber,
|
||||||
order_hash: orderHash,
|
order_hash: orderHash,
|
||||||
|
end_customer_id: endCustomerId ?? null,
|
||||||
total_price: orderSnapshot.total,
|
total_price: orderSnapshot.total,
|
||||||
customer_data: customerSnapshot,
|
customer_data: customerSnapshot,
|
||||||
order_data: orderSnapshot,
|
order_data: orderSnapshot,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type {
|
|||||||
Category,
|
Category,
|
||||||
CategorySelection,
|
CategorySelection,
|
||||||
CustomerSnapshot,
|
CustomerSnapshot,
|
||||||
|
EndCustomer,
|
||||||
LicenseBundle,
|
LicenseBundle,
|
||||||
LicenseOption,
|
LicenseOption,
|
||||||
OrderItem,
|
OrderItem,
|
||||||
@@ -37,10 +38,28 @@ export function slugify(name: string): string {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Baut einen validen CustomerSnapshot aus einem Profil oder Formulardaten.
|
* Baut einen validen CustomerSnapshot aus einem Profil oder Formulardaten.
|
||||||
* Fehlende Pflichtfelder werden mit leerem String aufgefüllt (kein throw –
|
*
|
||||||
* Validierung findet im Wizard-UI statt).
|
* Wenn ein Endkunde übergeben wird, werden DESSEN Daten eingefroren (für die Rechnung).
|
||||||
|
* Ohne Endkunden-Übergabe: Partner-Profil als Fallback (Abwärtskompatibilität).
|
||||||
|
* Fehlende Pflichtfelder werden mit leerem String aufgefüllt (Validierung im Wizard).
|
||||||
*/
|
*/
|
||||||
export function buildCustomerSnapshot(profile: Partial<Profile>): CustomerSnapshot {
|
export function buildCustomerSnapshot(
|
||||||
|
profile: Partial<Profile>,
|
||||||
|
endCustomer?: EndCustomer | null
|
||||||
|
): CustomerSnapshot {
|
||||||
|
if (endCustomer) {
|
||||||
|
return {
|
||||||
|
schema_version: 1,
|
||||||
|
end_customer_id: endCustomer.id,
|
||||||
|
company_name: endCustomer.company_name ?? '',
|
||||||
|
vat_id: endCustomer.vat_id ?? '',
|
||||||
|
first_name: endCustomer.first_name ?? '',
|
||||||
|
last_name: endCustomer.last_name ?? '',
|
||||||
|
address: endCustomer.street ?? '',
|
||||||
|
zip_code: endCustomer.zip ?? '',
|
||||||
|
city: endCustomer.city ?? '',
|
||||||
|
}
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
schema_version: 1,
|
schema_version: 1,
|
||||||
company_name: profile.company_name ?? '',
|
company_name: profile.company_name ?? '',
|
||||||
|
|||||||
@@ -50,6 +50,22 @@ export type Profile = {
|
|||||||
updated_at: string
|
updated_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Endkunde (verwaltet vom Partner) ────────────────────────────────────────
|
||||||
|
|
||||||
|
export type EndCustomer = {
|
||||||
|
id: string
|
||||||
|
partner_id: string
|
||||||
|
company_name: string
|
||||||
|
vat_id: string | null
|
||||||
|
first_name: string | null
|
||||||
|
last_name: string | null
|
||||||
|
street: string | null
|
||||||
|
zip: string | null
|
||||||
|
city: string | null
|
||||||
|
is_anonymized: boolean
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Wizard-Zustand (flüchtig, im RAM) ───────────────────────────────────────
|
// ─── Wizard-Zustand (flüchtig, im RAM) ───────────────────────────────────────
|
||||||
|
|
||||||
export type CategorySelection = {
|
export type CategorySelection = {
|
||||||
@@ -68,6 +84,8 @@ export type WizardSelections = Record<string, CategorySelection>
|
|||||||
*/
|
*/
|
||||||
export type CustomerSnapshot = {
|
export type CustomerSnapshot = {
|
||||||
schema_version: 1
|
schema_version: 1
|
||||||
|
/** ID des Endkunden zum Zeitpunkt der Bestellung (für Audit-Trail) */
|
||||||
|
end_customer_id?: string
|
||||||
company_name: string
|
company_name: string
|
||||||
vat_id: string
|
vat_id: string
|
||||||
first_name: string
|
first_name: string
|
||||||
@@ -115,6 +133,7 @@ export type Order = {
|
|||||||
user_id: string | null
|
user_id: string | null
|
||||||
order_number: string
|
order_number: string
|
||||||
order_hash: string | null
|
order_hash: string | null
|
||||||
|
end_customer_id: string | null
|
||||||
customer_data: CustomerSnapshot
|
customer_data: CustomerSnapshot
|
||||||
order_data: OrderSnapshot
|
order_data: OrderSnapshot
|
||||||
total_price: number
|
total_price: number
|
||||||
|
|||||||
27
shop/supabase/migrations/20260617_end_customers.sql
Normal file
27
shop/supabase/migrations/20260617_end_customers.sql
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
-- Migration: end_customers table + RLS + orders.end_customer_id
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS end_customers (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
partner_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
company_name TEXT NOT NULL,
|
||||||
|
vat_id TEXT,
|
||||||
|
first_name TEXT,
|
||||||
|
last_name TEXT,
|
||||||
|
street TEXT,
|
||||||
|
zip TEXT,
|
||||||
|
city TEXT,
|
||||||
|
is_anonymized BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE end_customers ENABLE ROW LEVEL SECURITY;
|
||||||
|
|
||||||
|
DROP POLICY IF EXISTS "Partner sehen nur eigene Endkunden" ON end_customers;
|
||||||
|
|
||||||
|
CREATE POLICY "Partner sehen nur eigene Endkunden"
|
||||||
|
ON end_customers FOR ALL
|
||||||
|
USING (auth.uid() = partner_id)
|
||||||
|
WITH CHECK (auth.uid() = partner_id);
|
||||||
|
|
||||||
|
ALTER TABLE orders
|
||||||
|
ADD COLUMN IF NOT EXISTS end_customer_id UUID REFERENCES end_customers(id) ON DELETE SET NULL;
|
||||||
Reference in New Issue
Block a user