feat(crm): end_customers table, RLS, wizard customer selector, /my-customers CRUD, GDPR anonymization

This commit is contained in:
DanielS
2026-06-17 01:57:17 +02:00
parent d96be1ace9
commit fb124b549c
12 changed files with 855 additions and 51 deletions

View File

@@ -3,7 +3,7 @@
import { useState, useMemo } from 'react'
import { useRouter } from 'next/navigation'
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 { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
@@ -11,8 +11,9 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
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 { createEndCustomer } from '@/lib/actions/end-customers'
import { Category } from '@/lib/types'
import { Badge } from '@/components/ui/badge'
@@ -72,25 +73,33 @@ export function OrderWizard({
products,
categories,
initialProfile,
initialEndCustomers,
}: {
products: Product[]
categories: Category[]
initialProfile: Profile | null
initialEndCustomers: EndCustomer[]
}) {
const router = useRouter()
const [step, setStep] = useState(1)
const [isSubmitting, setIsSubmitting] = useState(false)
const [customerData, setCustomerData] = useState<Partial<Profile>>(
initialProfile || {
company_name: '',
vat_id: '',
first_name: '',
last_name: '',
address: '',
city: '',
zip_code: '',
}
// Partner-Profil (Fallback)
const [customerData] = useState<Partial<Profile>>(initialProfile || {})
// Endkunden-State
const [endCustomers, setEndCustomers] = useState<EndCustomer[]>(initialEndCustomers)
const [selectedEndCustomerId, setSelectedEndCustomerId] = useState<string | null>(
initialEndCustomers.length > 0 ? initialEndCustomers[0].id : null
)
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 }
const [selections, setSelections] = useState<Record<string, CategorySelection>>(() => {
@@ -147,6 +156,23 @@ export function OrderWizard({
const nextStep = () => 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 () => {
if (isSubmitting) return // Doppelklick-Guard
setIsSubmitting(true)
@@ -156,6 +182,8 @@ export function OrderWizard({
products,
categories,
customerProfile: customerData,
endCustomerId: selectedEndCustomerId,
endCustomer: selectedEndCustomer,
})
router.push(`/order/success?id=${order.id}`)
} catch (error) {
@@ -425,7 +453,7 @@ export function OrderWizard({
</motion.div>
)}
{/* ───── Step 2: Customer Data ───── */}
{/* ───── Step 2: Endkunde wählen / anlegen ───── */}
{step === 2 && (
<motion.div
key="step2"
@@ -438,38 +466,127 @@ export function OrderWizard({
<CardHeader>
<CardTitle className="text-2xl flex items-center gap-2">
<User className="w-6 h-6 text-primary" />
Kundendaten
Für wen bestellen Sie?
</CardTitle>
<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>
</CardHeader>
<CardContent className="grid md:grid-cols-2 gap-6">
{[
{ label: 'Firmenname', key: 'company_name', placeholder: 'GmbH / Einzelunternehmen', span: false },
{ label: 'USt-IdNr.', key: 'vat_id', placeholder: 'DE123456789', span: false },
{ label: 'Vorname', key: 'first_name', placeholder: '', span: false },
{ label: 'Nachname', key: 'last_name', placeholder: '', span: false },
{ label: 'Straße & Hausnummer', key: 'address', placeholder: '', span: true },
{ label: 'Postleitzahl', key: 'zip_code', placeholder: '', span: false },
{ label: 'Ort', key: 'city', placeholder: '', span: false },
].map(({ label, key, placeholder, span }) => (
<div key={key} className={`space-y-2 ${span ? 'md:col-span-2' : ''}`}>
<Label className="text-white">{label}</Label>
<Input
value={(customerData as any)[key] || ''}
onChange={e => setCustomerData({ ...customerData, [key]: e.target.value })}
placeholder={placeholder}
className="bg-white/5 border-white/10 text-white placeholder:text-slate-500"
/>
<CardContent className="space-y-6">
{/* Modus-Toggle */}
<div className="flex gap-2">
<Button
variant={customerMode === 'select' ? 'default' : 'ghost'}
size="sm"
onClick={() => setCustomerMode('select')}
className="gap-2"
>
<Building2 className="w-4 h-4" /> Bestandskunde wählen
</Button>
<Button
variant={customerMode === 'create' ? 'default' : 'ghost'}
size="sm"
onClick={() => setCustomerMode('create')}
className="gap-2"
>
<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>
))}
)}
{/* 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>
<CardFooter className="flex justify-between border-t border-white/10 pt-6">
<Button variant="ghost" onClick={prevStep}>
<ChevronLeft className="mr-2 w-4 h-4" /> Zurück
</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" />
</Button>
</CardFooter>
@@ -533,13 +650,23 @@ export function OrderWizard({
})}
<Separator className="bg-white/10" />
<div className="text-sm text-slate-300 space-y-1">
<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>
{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>
</>
) : (
<>
<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 className="flex justify-between text-xl font-bold text-gradient">