Compare commits

...

6 Commits

Author SHA1 Message Date
DanielS
e78fe7c4b8 feat(email): implement professional responsive b2b html email template
All checks were successful
Staging Build / build (push) Successful in 3m9s
2026-09-08 00:09:16 +02:00
DanielS
ec11ad8498 chore: remove all unicode emojis project-wide and sanitize pdf text 2026-09-08 00:03:27 +02:00
DanielS
40b63b3fa9 feat(customers): add pagination with 5 items per page 2026-09-07 23:34:41 +02:00
DanielS
facf481fdb style(orders): harmonize device cards layout in my-orders 2026-09-07 23:31:05 +02:00
DanielS
5f29bb68a4 feat(wizard): fix step 3 layout scrolling and add step 4 confirmation modal 2026-09-07 23:15:21 +02:00
DanielS
404e7cd314 fix(wizard): make last license date optional in step 2 2026-09-07 23:01:36 +02:00
18 changed files with 1026 additions and 564 deletions

View File

@@ -8,7 +8,7 @@ import { sendMail } from '@/utils/mail';
import { renderToBuffer } from '@react-pdf/renderer'; import { renderToBuffer } from '@react-pdf/renderer';
import React from 'react'; import React from 'react';
import { InvoicePDF } from '@/components/invoice-pdf'; import { InvoicePDF } from '@/components/invoice-pdf';
import { getOrderEmailTemplate, buildEmailItemsSection } from '@/lib/actions/email-templates'; import { generateOrderEmailHtml, generateOrderEmailSubject } from '@/lib/actions/email-templates';
function generateOrderNumber(prefix: 'BE' | 'AE' = 'AE'): string { function generateOrderNumber(prefix: 'BE' | 'AE' = 'AE'): string {
const year = new Date().getFullYear(); const year = new Date().getFullYear();
@@ -147,21 +147,22 @@ async function triggerPostProcessing(orderId: string, supabase: any, customerSna
`; `;
} }
const itemsSection = buildEmailItemsSection(items); const emailTemplate = generateOrderEmailHtml({
const emailTemplate = getOrderEmailTemplate({
orderNumber: order.order_number, orderNumber: order.order_number,
status: 'pending',
formattedDate, formattedDate,
customerCompanyName: customerSnapshot.company_name, customerCompanyName: customerSnapshot.company_name,
totalDetailsText, items,
totalDetailsHtml, taxRate,
itemsDetailsText: itemsSection.text, oneTimeNet,
itemsDetailsHtml: itemsSection.html monthlyNet,
}, `${process.env.NEXT_PUBLIC_SITE_URL || 'https://staging.hephex.de'}`, false); });
const mailSubject = generateOrderEmailSubject(order.order_number, 'pending');
await sendMail({ await sendMail({
to: email, to: email,
subject: `Anfragebestätigung ${order.order_number}`, subject: mailSubject,
text: emailTemplate.text, text: emailTemplate.text,
html: emailTemplate.html, html: emailTemplate.html,
attachments: [ attachments: [

View File

@@ -7,7 +7,7 @@ import { createHash } from 'crypto';
import { renderToBuffer } from '@react-pdf/renderer'; import { renderToBuffer } from '@react-pdf/renderer';
import React from 'react'; import React from 'react';
import { InvoicePDF } from '@/components/invoice-pdf'; import { InvoicePDF } from '@/components/invoice-pdf';
import { getOrderEmailTemplate, buildEmailItemsSection } from '@/lib/actions/email-templates'; import { generateOrderEmailHtml, generateOrderEmailSubject } from '@/lib/actions/email-templates';
import { validateWizardSelections } from '@/lib/actions/validation'; import { validateWizardSelections } from '@/lib/actions/validation';
@@ -293,20 +293,18 @@ export async function POST(request: Request) {
`; `;
} }
const itemsSection = buildEmailItemsSection(items); const emailTemplate = generateOrderEmailHtml({
const { data: brandData } = await supabase.from('settings').select('primary_color').eq('id', 'branding').maybeSingle();
const primaryColor = brandData?.primary_color || '#2563eb';
const emailTemplate = getOrderEmailTemplate({
orderNumber: order.order_number, orderNumber: order.order_number,
status: 'pending',
formattedDate, formattedDate,
customerCompanyName: customerSnapshot.company_name, customerCompanyName: customerSnapshot.company_name,
totalDetailsText, items,
totalDetailsHtml, taxRate,
itemsDetailsText: itemsSection.text, oneTimeNet,
itemsDetailsHtml: itemsSection.html monthlyNet,
}, `${process.env.NEXT_PUBLIC_SITE_URL || 'https://staging.hephex.de'}`, false, primaryColor); });
const mailSubject = generateOrderEmailSubject(order.order_number, 'pending');
const { data: bufferData, error: downloadError } = await supabase const { data: bufferData, error: downloadError } = await supabase
.storage .storage
@@ -325,7 +323,7 @@ export async function POST(request: Request) {
await sendMail({ await sendMail({
to: user.email, to: user.email,
subject: `Anfragebestätigung ${order.order_number}`, subject: mailSubject,
text: emailTemplate.text, text: emailTemplate.text,
html: emailTemplate.html, html: emailTemplate.html,
attachments attachments

View File

@@ -193,8 +193,9 @@ export default function CustomerDetailPage({ params }: { params: Promise<{ id: s
</Button> </Button>
) : ( ) : (
<div className="space-y-3 p-4 rounded-lg bg-red-500/10 border border-red-500/30"> <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"> <p className="text-sm text-red-300 font-semibold flex items-center gap-2">
Diese Aktion ist unwiderruflich. Alle personenbezogenen Daten werden überschrieben. <AlertTriangle className="w-4 h-4 shrink-0 text-red-400" />
<span>Diese Aktion ist unwiderruflich. Alle personenbezogenen Daten werden überschrieben.</span>
</p> </p>
<div className="flex gap-3"> <div className="flex gap-3">
<Button <Button

View File

@@ -224,67 +224,80 @@ export function MyOrdersClient({ orders, error }: MyOrdersClientProps) {
</div> </div>
</div> </div>
{/* Kassen & Produkte Detail-Übersicht (Separate Container-Box je Kasse) */} {/* Kassen & Produkte Detail-Übersicht (Angelehnt an Kundenliste DeviceCard) */}
{items.length > 0 && ( {items.length > 0 && (
<div className="space-y-3 pt-2"> <div className="space-y-3 pt-2">
<p className="text-[11px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1.5"> <p className="text-[11px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
<Monitor className="w-3.5 h-3.5 text-primary" /> <Monitor className="w-3.5 h-3.5 text-primary" />
Kassenaufstellung ({items.length} {items.length === 1 ? 'Kasse' : 'Kassen'}): Kassenaufstellung ({items.length} {items.length === 1 ? 'Kasse' : 'Kassen'}):
</p> </p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3"> <div className="space-y-2.5">
{items.map((item, idx) => { {items.map((item, idx) => {
const devName = item.device_name || `K${idx + 1}` const devName = item.device_name || `Kasse ${idx + 1}`
const licNum = item.license_number const licNum = item.license_number
const modules = item.selected_modules || [] const modules = item.selected_modules || []
// Chips für Hauptprodukt und Module
const chips: string[] = []
if (item.product_name) chips.push(item.product_name)
for (const mod of modules) {
if (mod.module_name) chips.push(mod.module_name)
}
const itemPrice = (item as any).price || item.base_price || 0
const modulesPrice = modules.reduce((sum: number, m: any) => sum + ((m.price || 0) * (m.quantity || 1)), 0)
const deviceTotal = itemPrice + modulesPrice
return ( return (
<div <div
key={idx} key={idx}
className="bg-slate-950/70 border border-slate-800 rounded-xl p-3.5 space-y-2.5 relative overflow-hidden" className="p-4 rounded-xl bg-slate-950/70 border border-slate-800 hover:border-slate-700 transition-all flex flex-col md:flex-row md:items-start justify-between gap-4 relative overflow-hidden"
> >
{/* Kassen Container Header: Name + Lizenznummer daneben */} {/* Kassen-Info links */}
<div className="flex items-center justify-between gap-2 border-b border-white/5 pb-2"> <div className="space-y-2 min-w-[200px] flex-1">
<div className="flex items-center gap-2 flex-wrap"> {/* Kassen-Name + Lizenznummer daneben + Intervall */}
<div className="flex items-center gap-2 flex-wrap border-b border-white/5 pb-2">
<span className="px-2 py-0.5 rounded text-xs font-extrabold bg-blue-500/20 text-blue-400 border border-blue-500/30 font-mono"> <span className="px-2 py-0.5 rounded text-xs font-extrabold bg-blue-500/20 text-blue-400 border border-blue-500/30 font-mono">
{devName} {devName}
</span> </span>
{licNum && ( {licNum && (
<span className="text-xs font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20 flex items-center gap-1"> <span className="text-xs font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20 flex items-center gap-1">
<span className="text-[10px] text-slate-400 uppercase font-sans">Lizenz:</span> <span className="text-[10px] text-slate-400 uppercase font-sans">Lizenz:</span>
{licNum} {licNum}
</span> </span>
)} )}
</div>
<span className={`text-[10px] px-1.5 py-0.5 rounded border ${item.billing_interval === 'one_time' ? 'border-amber-500/30 text-amber-400 bg-amber-500/10' : 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'} font-semibold uppercase shrink-0`}>
{item.billing_interval === 'one_time' ? 'Kauf' : 'Abo'}
</span>
</div>
{/* Inhalt: Hauptprodukt & Module nach Kategorien */} <span className={`text-[10px] px-1.5 py-0.5 rounded border ${item.billing_interval === 'one_time' ? 'border-amber-500/30 text-amber-400 bg-amber-500/10' : 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'} font-semibold uppercase`}>
<div className="space-y-2 text-xs"> {item.billing_interval === 'one_time' ? 'Kauf' : 'Abo'}
<div className="flex items-center justify-between"> </span>
<span className="font-bold text-white text-sm">{item.product_name}</span>
{((item as any).price || item.base_price) && (
<span className="text-slate-300 font-mono">{fmt((item as any).price || item.base_price)}</span>
)}
</div> </div>
{modules.length > 0 && ( {/* Produkt + Modul Chips */}
<div className="pt-2 border-t border-white/5 space-y-1.5"> {chips.length > 0 && (
<span className="text-[10px] uppercase font-bold text-slate-400 tracking-wider block"> <div className="flex flex-wrap gap-1.5 pt-1">
Enthaltene Zusatzmodule: {chips.map((chip, cIdx) => (
</span> <span
<div className="flex flex-wrap gap-1.5"> key={cIdx}
{modules.map((mod: any, mIdx: number) => ( className="text-xs bg-white/5 border border-white/10 rounded-md px-2 py-0.5 text-slate-300"
<span key={mIdx} className="text-[11px] bg-slate-900 text-slate-200 px-2 py-1 rounded-md border border-white/10 flex items-center gap-1"> >
<span className="text-primary font-bold">+</span> {mod.module_name || mod.name} {chip}
{mod.quantity > 1 ? <span className="text-slate-400 font-mono ml-0.5">({mod.quantity}x)</span> : ''} </span>
</span> ))}
))}
</div>
</div> </div>
)} )}
</div> </div>
{/* Preis rechts */}
{deviceTotal > 0 && (
<div className="text-left md:text-right shrink-0 border-t md:border-t-0 pt-2 md:pt-0 border-white/5">
<p className="text-[10px] text-slate-500 uppercase tracking-wider">Kassenwert</p>
<p className="font-bold text-white text-sm">
{fmt(deviceTotal)}
{item.billing_interval === 'monthly' && <span className="text-xs font-normal text-slate-400"> / mtl.</span>}
</p>
</div>
)}
</div> </div>
) )
})} })}

View File

@@ -3,6 +3,8 @@
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { DemoWrapper } from "./DemoWrapper"; import { DemoWrapper } from "./DemoWrapper";
import { AlertTriangle } from "lucide-react";
interface HeaderWrapperProps { interface HeaderWrapperProps {
navbar: React.ReactNode; navbar: React.ReactNode;
children: React.ReactNode; children: React.ReactNode;
@@ -25,9 +27,10 @@ export function HeaderWrapper({ navbar, children }: HeaderWrapperProps) {
<DemoWrapper> <DemoWrapper>
<div <div
id="demo-banner" id="demo-banner"
className="bg-amber-500/10 border-b border-amber-500/20 py-2 px-4 text-center text-xs text-amber-600 dark:text-amber-400 font-medium tracking-wide z-50" className="bg-amber-500/10 border-b border-amber-500/20 py-2 px-4 text-center text-xs text-amber-600 dark:text-amber-400 font-medium tracking-wide z-50 flex items-center justify-center gap-1.5"
> >
Dies ist eine **Demo-Webseite (Dummy-Shop)**. Es werden keine echten Bestellungen verarbeitet oder Zahlungen abgewickelt. <AlertTriangle className="w-3.5 h-3.5 shrink-0" />
<span>Dies ist eine **Demo-Webseite (Dummy-Shop)**. Es werden keine echten Bestellungen verarbeitet oder Zahlungen abgewickelt.</span>
</div> </div>
</DemoWrapper> </DemoWrapper>

View File

@@ -26,7 +26,7 @@ import {
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox' import { Checkbox } from '@/components/ui/checkbox'
import { Plus, Trash2, X, PlusCircle } from 'lucide-react' import { Plus, Trash2, X, PlusCircle, CreditCard, RefreshCw } from 'lucide-react'
import { createProduct, updateProduct } from '@/lib/actions/products' import { createProduct, updateProduct } from '@/lib/actions/products'
import { ScrollArea } from '@/components/ui/scroll-area' import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator' import { Separator } from '@/components/ui/separator'
@@ -288,23 +288,26 @@ export function CreateProductDialog({
<FormLabel className="text-slate-900 dark:text-white">Abrechnungsmodell</FormLabel> <FormLabel className="text-slate-900 dark:text-white">Abrechnungsmodell</FormLabel>
<div className="grid grid-cols-2 gap-2 pt-1"> <div className="grid grid-cols-2 gap-2 pt-1">
{[ {[
{ value: 'one_time', label: 'Einmalig', icon: '💳' }, { value: 'one_time', label: 'Einmalig', icon: CreditCard },
{ value: 'monthly', label: 'Monatlich', icon: '🔄' }, { value: 'monthly', label: 'Monatlich', icon: RefreshCw },
].map(opt => ( ].map(opt => {
<button const IconComponent = opt.icon;
key={opt.value} return (
type="button" <button
onClick={() => field.onChange(opt.value)} key={opt.value}
className={`flex flex-col items-center gap-1 p-3 rounded-xl border-2 text-sm font-medium transition-all ${ type="button"
field.value === opt.value onClick={() => field.onChange(opt.value)}
? 'border-primary bg-primary/10 text-primary dark:text-white' className={`flex flex-col items-center gap-1 p-3 rounded-xl border-2 text-sm font-medium transition-all ${
: 'border-slate-200 dark:border-white/10 bg-slate-50 dark:bg-white/5 text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-white/10' field.value === opt.value
}`} ? 'border-primary bg-primary/10 text-primary dark:text-white'
> : 'border-slate-200 dark:border-white/10 bg-slate-50 dark:bg-white/5 text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-white/10'
<span className="text-lg">{opt.icon}</span> }`}
{opt.label} >
</button> <IconComponent className="w-5 h-5 mb-1" />
))} {opt.label}
</button>
);
})}
</div> </div>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>

View File

@@ -1,6 +1,6 @@
'use client' 'use client'
import React, { useState } from 'react' import React, { useState, useMemo } from 'react'
import { motion, AnimatePresence } from 'framer-motion' import { motion, AnimatePresence } from 'framer-motion'
import Link from 'next/link' import Link from 'next/link'
import type { EndCustomerWithDevices, FlattenedDevice } from '@/lib/types' import type { EndCustomerWithDevices, FlattenedDevice } from '@/lib/types'
@@ -17,6 +17,10 @@ import {
AlertTriangle, AlertTriangle,
Search, Search,
Package, Package,
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
} from 'lucide-react' } from 'lucide-react'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
@@ -188,6 +192,8 @@ export function CustomerAccordionList({ customers }: CustomerAccordionListProps)
}) })
const [searchTerm, setSearchTerm] = useState('') const [searchTerm, setSearchTerm] = useState('')
const [currentPage, setCurrentPage] = useState(1)
const pageSize = 5
const toggleCustomer = (id: string) => { const toggleCustomer = (id: string) => {
setOpenCustomerIds((prev) => ({ setOpenCustomerIds((prev) => ({
@@ -196,16 +202,32 @@ export function CustomerAccordionList({ customers }: CustomerAccordionListProps)
})) }))
} }
const filteredCustomers = customers.filter((c) => { const filteredCustomers = useMemo(() => {
const term = searchTerm.toLowerCase() const term = searchTerm.toLowerCase().trim()
return ( if (!term) return customers
c.company_name.toLowerCase().includes(term) ||
(c.first_name && c.first_name.toLowerCase().includes(term)) || return customers.filter((c) => {
(c.last_name && c.last_name.toLowerCase().includes(term)) || return (
(c.city && c.city.toLowerCase().includes(term)) || c.company_name.toLowerCase().includes(term) ||
(c.email && c.email.toLowerCase().includes(term)) (c.first_name && c.first_name.toLowerCase().includes(term)) ||
) (c.last_name && c.last_name.toLowerCase().includes(term)) ||
}) (c.city && c.city.toLowerCase().includes(term)) ||
(c.email && c.email.toLowerCase().includes(term))
)
})
}, [customers, searchTerm])
const totalPages = Math.ceil(filteredCustomers.length / pageSize) || 1
const paginatedCustomers = useMemo(() => {
const from = (currentPage - 1) * pageSize
return filteredCustomers.slice(from, from + pageSize)
}, [filteredCustomers, currentPage, pageSize])
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchTerm(e.target.value)
setCurrentPage(1)
}
if (customers.length === 0) { if (customers.length === 0) {
return ( return (
@@ -225,151 +247,223 @@ export function CustomerAccordionList({ customers }: CustomerAccordionListProps)
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Suchfeld */} {/* Suchfeld & Info */}
<div className="relative max-w-md"> <div className="flex flex-col sm:flex-row gap-4 justify-between items-stretch sm:items-center">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" /> <div className="relative max-w-md flex-1">
<Input <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
type="text" <Input
placeholder="Kunden suchen (Firma, Name, Stadt)..." type="text"
value={searchTerm} placeholder="Kunden suchen (Firma, Name, Stadt)..."
onChange={(e) => setSearchTerm(e.target.value)} value={searchTerm}
className="pl-9 bg-slate-900/50 border-white/10 text-white placeholder:text-slate-500 focus:border-primary" onChange={handleSearchChange}
/> className="pl-9 bg-slate-900/50 border-white/10 text-white placeholder:text-slate-500 focus:border-primary"
/>
</div>
<div className="text-xs text-slate-400 bg-slate-900/50 px-3.5 py-2 rounded-xl border border-white/10 shrink-0 text-center flex items-center justify-center gap-2">
<span>Kunden:</span>
<span className="text-white font-bold">{filteredCustomers.length}</span>
{searchTerm && <span className="text-slate-500">(gefiltert aus {customers.length})</span>}
</div>
</div> </div>
{/* Keine Suchergebnisse */}
{filteredCustomers.length === 0 && (
<Card className="glass-dark border-white/10">
<CardContent className="flex flex-col items-center justify-center py-12 gap-3 text-center">
<Search className="w-10 h-10 text-slate-600" />
<p className="text-slate-300 font-medium">Keine Kunden für &quot;{searchTerm}&quot; gefunden.</p>
<Button variant="outline" size="sm" onClick={() => setSearchTerm('')} className="border-white/10 text-xs">
Filter zurücksetzen
</Button>
</CardContent>
</Card>
)}
{/* Akkordeon-Liste */} {/* Akkordeon-Liste */}
<div className="space-y-4"> {paginatedCustomers.length > 0 && (
{filteredCustomers.map((customer) => { <div className="space-y-4">
const isOpen = !!openCustomerIds[customer.id] {paginatedCustomers.map((customer) => {
const devices = customer.devices || [] const isOpen = !!openCustomerIds[customer.id]
const devices = customer.devices || []
return ( return (
<Card <Card
key={customer.id} key={customer.id}
className="glass-dark border-white/10 overflow-hidden transition-all duration-200" className="glass-dark border-white/10 overflow-hidden transition-all duration-200"
>
{/* Akkordeon-Header */}
<div
onClick={() => toggleCustomer(customer.id)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
toggleCustomer(customer.id)
}
}}
tabIndex={0}
role="button"
aria-expanded={isOpen}
className="p-5 flex items-center justify-between cursor-pointer hover:bg-white/[0.02] transition-colors select-none gap-4 flex-wrap focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-inset"
> >
<div className="flex items-center gap-4 min-w-[240px]"> {/* Akkordeon-Header */}
<div className="w-10 h-10 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-primary font-bold"> <div
<Building2 className="w-5 h-5" /> onClick={() => toggleCustomer(customer.id)}
</div> onKeyDown={(e) => {
<div> if (e.key === 'Enter' || e.key === ' ') {
<div className="flex items-center gap-2"> e.preventDefault()
<h3 className="font-bold text-lg text-white">{customer.company_name}</h3> toggleCustomer(customer.id)
{customer.is_anonymized && ( }
<Badge className="bg-red-500/10 text-red-400 border-red-500/20 text-xs gap-1"> }}
<AlertTriangle className="w-3 h-3" /> Anonymisiert tabIndex={0}
</Badge> role="button"
)} aria-expanded={isOpen}
className="p-5 flex items-center justify-between cursor-pointer hover:bg-white/[0.02] transition-colors select-none gap-4 flex-wrap focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-inset"
>
<div className="flex items-center gap-4 min-w-[240px]">
<div className="w-10 h-10 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-primary font-bold">
<Building2 className="w-5 h-5" />
</div>
<div>
<div className="flex items-center gap-2">
<h3 className="font-bold text-lg text-white">{customer.company_name}</h3>
{customer.is_anonymized && (
<Badge className="bg-red-500/10 text-red-400 border-red-500/20 text-xs gap-1">
<AlertTriangle className="w-3 h-3" /> Anonymisiert
</Badge>
)}
</div>
<p className="text-sm text-slate-400">
{[customer.first_name, customer.last_name].filter(Boolean).join(' ') ||
'Kein Ansprechpartner'}
{customer.city ? `${customer.city}` : ''}
{customer.email ? `${customer.email}` : ''}
</p>
</div> </div>
<p className="text-sm text-slate-400">
{[customer.first_name, customer.last_name].filter(Boolean).join(' ') ||
'Kein Ansprechpartner'}
{customer.city ? `${customer.city}` : ''}
{customer.email ? `${customer.email}` : ''}
</p>
</div> </div>
</div>
<div className="flex items-center gap-3 ml-auto"> <div className="flex items-center gap-3 ml-auto">
{/* Kassen-Anzahl Badge */} {/* Kassen-Anzahl Badge */}
<Badge variant="outline" className="border-white/10 text-slate-300 bg-white/5"> <Badge variant="outline" className="border-white/10 text-slate-300 bg-white/5">
<Package className="w-3.5 h-3.5 mr-1 text-primary" /> <Package className="w-3.5 h-3.5 mr-1 text-primary" />
{devices.length} {devices.length === 1 ? 'Kasse' : 'Kassen'} {devices.length} {devices.length === 1 ? 'Kasse' : 'Kassen'}
</Badge> </Badge>
{!customer.is_anonymized && ( {!customer.is_anonymized && (
<> <>
<Link <Link
href={`/order?customer_id=${customer.id}`} href={`/order?customer_id=${customer.id}`}
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
>
<Button
size="sm"
className="bg-primary/20 hover:bg-primary/30 text-primary border border-primary/40 gap-1.5 text-xs font-bold shadow-[0_0_10px_rgba(59,130,246,0.2)]"
> >
<Sparkles className="w-3.5 h-3.5" /> Kunde updaten / bestellen <Button
</Button> size="sm"
</Link> className="bg-primary/20 hover:bg-primary/30 text-primary border border-primary/40 gap-1.5 text-xs font-bold shadow-[0_0_10px_rgba(59,130,246,0.2)]"
<Link >
href={`/my-customers/${customer.id}`} <Sparkles className="w-3.5 h-3.5" /> Kunde updaten / bestellen
onClick={(e) => e.stopPropagation()} </Button>
> </Link>
<Button <Link
variant="ghost" href={`/my-customers/${customer.id}`}
size="sm" onClick={(e) => e.stopPropagation()}
className="text-slate-400 hover:text-white hover:bg-white/10 gap-1 text-xs"
> >
<Edit2 className="w-3.5 h-3.5" /> Bearbeiten <Button
</Button> variant="ghost"
</Link> size="sm"
</> className="text-slate-400 hover:text-white hover:bg-white/10 gap-1 text-xs"
)} >
<Edit2 className="w-3.5 h-3.5" /> Bearbeiten
<Button </Button>
variant="ghost" </Link>
size="sm" </>
className="text-slate-400 hover:text-white p-1"
>
{isOpen ? (
<ChevronUp className="w-5 h-5" />
) : (
<ChevronDown className="w-5 h-5" />
)} )}
</Button>
</div>
</div>
{/* Ausgeklappter Bereich mit Kassen */} <Button
<AnimatePresence initial={false}> variant="ghost"
{isOpen && ( size="sm"
<motion.div className="text-slate-400 hover:text-white p-1"
initial={{ height: 0, opacity: 0 }} >
animate={{ height: 'auto', opacity: 1 }} {isOpen ? (
exit={{ height: 0, opacity: 0 }} <ChevronUp className="w-5 h-5" />
transition={{ duration: 0.2, ease: 'easeInOut' }}
className="overflow-hidden border-t border-white/5 bg-slate-950/40"
>
<div className="p-5 space-y-3">
{devices.length === 0 ? (
<div className="text-slate-500 text-sm py-4 text-center">
Keine Kassen oder Bestellungen für diesen Kunden vorhanden.
</div>
) : ( ) : (
<div className="space-y-3"> <ChevronDown className="w-5 h-5" />
<p className="text-xs uppercase tracking-wider text-slate-400 font-semibold mb-2">
Zugeordnete Kassen ({devices.length})
</p>
{devices.map((device, idx) => (
<DeviceCard
key={`${device.orderId}-${device.deviceId}-${idx}`}
device={device}
customerId={customer.id}
/>
))}
</div>
)} )}
</div> </Button>
</motion.div> </div>
)} </div>
</AnimatePresence>
</Card> {/* Ausgeklappter Bereich mit Kassen */}
) <AnimatePresence initial={false}>
})} {isOpen && (
</div> <motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.2, ease: 'easeInOut' }}
className="overflow-hidden border-t border-white/5 bg-slate-950/40"
>
<div className="p-5 space-y-3">
{devices.length === 0 ? (
<div className="text-slate-500 text-sm py-4 text-center">
Keine Kassen oder Bestellungen für diesen Kunden vorhanden.
</div>
) : (
<div className="space-y-3">
<p className="text-xs uppercase tracking-wider text-slate-400 font-semibold mb-2">
Zugeordnete Kassen ({devices.length})
</p>
{devices.map((device, idx) => (
<DeviceCard
key={`${device.orderId}-${device.deviceId}-${idx}`}
device={device}
customerId={customer.id}
/>
))}
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</Card>
)
})}
</div>
)}
{/* Paginierung (5 Kunden pro Seite) */}
{totalPages > 1 && (
<div className="flex items-center justify-between pt-4 border-t border-white/10">
<span className="text-xs text-slate-400">
Seite <span className="text-white font-bold">{currentPage}</span> von{' '}
<span className="text-white font-bold">{totalPages}</span>
</span>
<div className="flex items-center gap-1.5">
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentPage(1)}
disabled={currentPage === 1}
className="h-8 px-2 text-slate-400 hover:text-white"
title="Erste Seite"
>
<ChevronsLeft className="w-4 h-4" />
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
disabled={currentPage === 1}
className="border-white/10 text-xs gap-1 rounded-xl h-8 px-3"
>
<ChevronLeft className="w-3.5 h-3.5" /> Vorherige
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
disabled={currentPage === totalPages}
className="border-white/10 text-xs gap-1 rounded-xl h-8 px-3"
>
Nächste <ChevronRight className="w-3.5 h-3.5" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentPage(totalPages)}
disabled={currentPage === totalPages}
className="h-8 px-2 text-slate-400 hover:text-white"
title="Letzte Seite"
>
<ChevronsRight className="w-4 h-4" />
</Button>
</div>
</div>
)}
</div> </div>
) )
} }

View File

@@ -94,6 +94,14 @@ const styles = StyleSheet.create({
} }
}); });
export const stripEmojis = (text?: string | null): string => {
if (!text) return '';
return text
.replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}\uFE0F\u200D]/gu, '')
.replace(/\s{2,}/g, ' ')
.trim();
};
export const InvoicePDF = ({ export const InvoicePDF = ({
order, order,
orderSnapshot, orderSnapshot,
@@ -105,7 +113,7 @@ export const InvoicePDF = ({
const items = orderSnapshot?.items ?? []; const items = orderSnapshot?.items ?? [];
const taxRate = orderSnapshot?.tax_rate ?? 19; const taxRate = orderSnapshot?.tax_rate ?? 19;
const isSubscription = order?.type === 'subscription' || orderSnapshot?.billing_cycle === 'monthly'; const isSubscription = order?.type === 'subscription' || orderSnapshot?.billing_cycle === 'monthly';
const formattedOrderNumber = (order.order_number || order.id || '').replace(/^BE-/, 'AE-'); const formattedOrderNumber = stripEmojis((order.order_number || order.id || '').replace(/^BE-/, 'AE-'));
const isUpgrade = !!orderSnapshot?.last_license_date; const isUpgrade = !!orderSnapshot?.last_license_date;
let oneTimeNet = 0; let oneTimeNet = 0;
@@ -136,16 +144,16 @@ export const InvoicePDF = ({
const groupedItems: { [key: string]: any[] } = {}; const groupedItems: { [key: string]: any[] } = {};
items.forEach((item: any) => { items.forEach((item: any) => {
const devName = item.device_name || 'Kasse 1'; const devName = stripEmojis(item.device_name || 'Kasse 1');
if (!groupedItems[devName]) { if (!groupedItems[devName]) {
groupedItems[devName] = []; groupedItems[devName] = [];
} }
groupedItems[devName].push(item); groupedItems[devName].push(item);
}); });
const displayPartnerName = partnerCompanyName || order?.partner_company_name; const displayPartnerName = stripEmojis(partnerCompanyName || order?.partner_company_name);
const displayUserName = partnerUserName || order?.partner_user_name; const displayUserName = stripEmojis(partnerUserName || order?.partner_user_name);
const displayUserEmail = partnerUserEmail || order?.partner_user_email; const displayUserEmail = stripEmojis(partnerUserEmail || order?.partner_user_email);
return ( return (
<Document> <Document>
@@ -170,11 +178,11 @@ export const InvoicePDF = ({
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 15 }}> <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 15 }}>
<View style={{ width: '48%' }}> <View style={{ width: '48%' }}>
<Text style={styles.label}>Endkunde</Text> <Text style={styles.label}>Endkunde</Text>
<Text style={{ fontWeight: 'bold' }}>{customer.company_name}</Text> <Text style={{ fontWeight: 'bold' }}>{stripEmojis(customer?.company_name)}</Text>
{customer.first_name || customer.last_name ? <Text>{customer.first_name} {customer.last_name}</Text> : null} {(customer?.first_name || customer?.last_name) ? <Text>{stripEmojis(`${customer?.first_name || ''} ${customer?.last_name || ''}`)}</Text> : null}
{customer.address ? <Text>{customer.address}</Text> : null} {customer?.address ? <Text>{stripEmojis(customer.address)}</Text> : null}
{customer.zip_code || customer.city ? <Text>{customer.zip_code} {customer.city}</Text> : null} {(customer?.zip_code || customer?.city) ? <Text>{stripEmojis(`${customer?.zip_code || ''} ${customer?.city || ''}`)}</Text> : null}
{customer.vat_id ? <Text>USt-IdNr: {customer.vat_id}</Text> : null} {customer?.vat_id ? <Text>USt-IdNr: {stripEmojis(customer.vat_id)}</Text> : null}
</View> </View>
<View style={{ width: '48%' }}> <View style={{ width: '48%' }}>
@@ -205,8 +213,8 @@ export const InvoicePDF = ({
{devItems.map((item: any, idx: number) => ( {devItems.map((item: any, idx: number) => (
<View key={idx} style={{ marginBottom: 6 }}> <View key={idx} style={{ marginBottom: 6 }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 2 }}> <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 2 }}>
<Text style={{ fontSize: 9, fontWeight: 'bold', color: '#334155' }}> <Text style={{ fontSize: 9, fontWeight: 'bold', color: '#344155' }}>
{item.product_name} ({item.category_name}) {stripEmojis(item.product_name)} ({stripEmojis(item.category_name)})
</Text> </Text>
<Text style={{ fontSize: 9, fontWeight: 'bold', color: '#0f172a' }}> <Text style={{ fontSize: 9, fontWeight: 'bold', color: '#0f172a' }}>
{formattedPrice(item.base_price)} {item.billing_interval === 'one_time' ? 'einmalig' : 'mtl.'} {formattedPrice(item.base_price)} {item.billing_interval === 'one_time' ? 'einmalig' : 'mtl.'}
@@ -218,7 +226,7 @@ export const InvoicePDF = ({
return ( return (
<View key={mIdx} style={{ flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 12, marginBottom: 1 }}> <View key={mIdx} style={{ flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 12, marginBottom: 1 }}>
<Text style={{ fontSize: 8, color: '#64748b' }}> <Text style={{ fontSize: 8, color: '#64748b' }}>
+ {mod.module_name} {qty > 1 ? `(x${qty})` : ''} + {stripEmojis(mod.module_name)} {qty > 1 ? `(x${qty})` : ''}
</Text> </Text>
<Text style={{ fontSize: 8, color: '#64748b' }}> <Text style={{ fontSize: 8, color: '#64748b' }}>
+{formattedPrice(price)} mtl. +{formattedPrice(price)} mtl.

View File

@@ -16,6 +16,7 @@ import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState, useEffect, useRef, useCallback } from "react"; import { useState, useEffect, useRef, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion"; import { motion, AnimatePresence } from "framer-motion";
import { Ban } from "lucide-react";
function getDeviceHash(): string { function getDeviceHash(): string {
const key = "caspos-device-id"; const key = "caspos-device-id";
@@ -227,8 +228,9 @@ export function LoginForm({
/> />
</div> </div>
{errorParam === "gesperrt" && ( {errorParam === "gesperrt" && (
<p className="text-sm text-red-500 bg-red-500/10 border border-red-500/20 p-3 rounded-lg text-center font-medium"> <p className="text-sm text-red-500 bg-red-500/10 border border-red-500/20 p-3 rounded-lg text-center font-medium flex items-center justify-center gap-2">
🚫 Ihr Konto wurde gesperrt. Bitte wenden Sie sich an den Administrator. <Ban className="w-4 h-4 shrink-0" />
<span>Ihr Konto wurde gesperrt. Bitte wenden Sie sich an den Administrator.</span>
</p> </p>
)} )}
{messageParam === "concurrent" && ( {messageParam === "concurrent" && (

View File

@@ -8,7 +8,7 @@ import { submitOrder, updateOrder } from '@/lib/actions/orders'
import { createEndCustomer } from '@/lib/actions/end-customers' import { createEndCustomer } from '@/lib/actions/end-customers'
import { isLicenseNumberTaken } from '@/lib/actions/queries' import { isLicenseNumberTaken } from '@/lib/actions/queries'
import { Category } from '@/lib/types' import { Category } from '@/lib/types'
import { Check } from 'lucide-react' import { Check, Zap } from 'lucide-react'
// Modular Step Components // Modular Step Components
import { ProgressStepper } from './wizard/progress-stepper' import { ProgressStepper } from './wizard/progress-stepper'
@@ -940,11 +940,11 @@ export function OrderWizard({
{/* Step 3 Categories inside left sidebar */} {/* Step 3 Categories inside left sidebar */}
{step === 3 && ( {step === 3 && (
<div className="pt-4 border-t border-white/10 space-y-3"> <div className="pt-3 border-t border-white/10 flex flex-col min-h-0 max-h-[calc(100vh-22rem)] overflow-hidden">
<h3 className="text-xs font-bold uppercase tracking-wider text-slate-400"> <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 mb-2 shrink-0">
Kategorien Kategorien
</h3> </h3>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-1.5 flex-1 min-h-0 overflow-y-auto pr-1 pb-2 scrollbar-thin scrollbar-thumb-slate-800 scrollbar-track-transparent">
{visibleCategories.map((cat) => { {visibleCategories.map((cat) => {
const sel = selections[cat.id] const sel = selections[cat.id]
const hasSelection = (sel?.productIds && sel.productIds.length > 0) || !!sel?.productId const hasSelection = (sel?.productIds && sel.productIds.length > 0) || !!sel?.productId
@@ -956,7 +956,7 @@ export function OrderWizard({
<button <button
key={cat.id} key={cat.id}
onClick={() => setActiveCategoryId(cat.id)} onClick={() => setActiveCategoryId(cat.id)}
className={`flex items-center gap-2.5 p-2.5 rounded-xl border transition-all duration-300 text-left relative overflow-hidden group ${ className={`flex items-center gap-2 p-2 rounded-xl border transition-all duration-300 text-left relative overflow-hidden group shrink-0 ${
isMissingRequired isMissingRequired
? 'bg-red-500/10 border-red-500/50 text-red-400 font-bold' ? 'bg-red-500/10 border-red-500/50 text-red-400 font-bold'
: isActive : isActive
@@ -968,7 +968,7 @@ export function OrderWizard({
<div className="absolute left-0 top-0 bottom-0 w-1 bg-primary" /> <div className="absolute left-0 top-0 bottom-0 w-1 bg-primary" />
)} )}
<div className={`p-1.5 rounded-lg transition-colors ${ <div className={`p-1.5 rounded-lg transition-colors shrink-0 ${
isMissingRequired isMissingRequired
? 'bg-red-500/20 text-red-400' ? 'bg-red-500/20 text-red-400'
: isActive : isActive
@@ -991,11 +991,11 @@ export function OrderWizard({
</div> </div>
{hasSelection ? ( {hasSelection ? (
<span className="text-[9px] px-1.5 py-0.2 rounded-full font-semibold shrink-0 border border-emerald-500/30 text-emerald-400 bg-emerald-500/10"> <span className="text-[9px] px-1.5 py-0.5 rounded-full font-semibold shrink-0 border border-emerald-500/30 text-emerald-400 bg-emerald-500/10 flex items-center justify-center">
<Check className="w-2.5 h-2.5" />
</span> </span>
) : isRequired ? ( ) : isRequired ? (
<span className="text-[9px] px-2 py-0.5 rounded-full font-extrabold shrink-0 border border-red-500 text-red-400 bg-red-500/20 animate-pulse tracking-wider"> <span className="text-[9px] px-1.5 py-0.2 rounded-full font-extrabold shrink-0 border border-red-500 text-red-400 bg-red-500/20 animate-pulse tracking-wider">
FEHLT! FEHLT!
</span> </span>
) : null} ) : null}
@@ -1079,7 +1079,7 @@ export function OrderWizard({
{/* Upgrade-Modus Hinweis-Banner */} {/* Upgrade-Modus Hinweis-Banner */}
{upgradeMode && lockedDeviceId && ( {upgradeMode && lockedDeviceId && (
<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"> <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">
<span className="text-primary mt-0.5"></span> <Zap className="w-4 h-4 text-primary shrink-0 mt-0.5" />
<div> <div>
<p className="font-semibold">Upgrade-Modus: {lockedDeviceId}</p> <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> <p className="text-primary/70 mt-0.5">Bereits lizenzierte Module sind ausgegraut und können nicht doppelt gebucht werden.</p>

View File

@@ -156,7 +156,7 @@ export function FetchDataSteps() {
</TutorialStep> </TutorialStep>
<TutorialStep title="Build in a weekend and scale to millions!"> <TutorialStep title="Build in a weekend and scale to millions!">
<p>You&apos;re ready to launch your product to the world! 🚀</p> <p>You&apos;re ready to launch your product to the world!</p>
</TutorialStep> </TutorialStep>
</ol> </ol>
); );

View File

@@ -40,9 +40,6 @@ export function StepBilling({
const isOneTime = selectedBillingInterval === 'one_time' const isOneTime = selectedBillingInterval === 'one_time'
const isMonthly = selectedBillingInterval === 'monthly' const isMonthly = selectedBillingInterval === 'monthly'
// Wenn Kauf gewählt ist, muss ein gültiges Datum vorliegen
const isNextDisabled = isOneTime && !lastLicenseDate
return ( return (
<Card className="glass-dark border-white/10 h-[calc(100vh-8.5rem)] flex flex-col justify-between overflow-hidden relative"> <Card className="glass-dark border-white/10 h-[calc(100vh-8.5rem)] flex flex-col justify-between overflow-hidden relative">
{/* ─── 1. FIXED HEADER (shrink-0) ─── */} {/* ─── 1. FIXED HEADER (shrink-0) ─── */}
@@ -163,7 +160,7 @@ export function StepBilling({
<Calendar className="w-3.5 h-3.5 text-primary shrink-0 mt-0.5" /> <Calendar className="w-3.5 h-3.5 text-primary shrink-0 mt-0.5" />
<div className="space-y-0.5 flex-1"> <div className="space-y-0.5 flex-1">
<Label htmlFor="last-license-date" className="text-white text-[11px] font-bold block"> <Label htmlFor="last-license-date" className="text-white text-[11px] font-bold block">
Datum letzter CASPOS-Kauf (Stichtag) Datum letzter CASPOS-Kauf <span className="text-slate-400 font-normal">(optional)</span>
</Label> </Label>
<p className="text-[10px] text-slate-400 leading-tight"> <p className="text-[10px] text-slate-400 leading-tight">
Zur automatischen Berechnung der Update-Staffel (15% / 30% / 50%). Zur automatischen Berechnung der Update-Staffel (15% / 30% / 50%).
@@ -229,8 +226,7 @@ export function StepBilling({
{/* Next Button */} {/* Next Button */}
<Button <Button
onClick={nextStep} onClick={nextStep}
disabled={isNextDisabled} className="w-full sm:w-auto bg-primary hover:bg-primary/90 text-white font-semibold px-5 shadow-md shadow-primary/20 h-8 text-xs gap-1.5"
className="w-full sm:w-auto bg-primary hover:bg-primary/90 text-white font-semibold px-5 shadow-md shadow-primary/20 h-8 text-xs gap-1.5 disabled:opacity-50"
> >
Weiter zu Schritt 3 <ChevronRight className="w-3.5 h-3.5" /> Weiter zu Schritt 3 <ChevronRight className="w-3.5 h-3.5" />
</Button> </Button>

View File

@@ -73,19 +73,19 @@ export function StepSoftware({
const selectedProduct = catProducts.find(p => p.id === sel?.productId) ?? null const selectedProduct = catProducts.find(p => p.id === sel?.productId) ?? null
return ( return (
<Card className="glass-dark border-white/10 h-full flex flex-col rounded-2xl overflow-hidden"> <Card className="glass-dark border-white/10 h-full flex flex-col rounded-2xl overflow-hidden min-h-0">
{/* ─── FIXED CARD HEADER ─── */} {/* ─── FIXED CARD HEADER (shrink-0 mb-1) ─── */}
<CardHeader className="border-b border-white/10 pb-3 pt-4 px-5 shrink-0 bg-slate-950/40"> <CardHeader className="border-b border-white/10 py-2.5 px-4 shrink-0 bg-slate-950/40">
<div className="flex items-center justify-between gap-3 flex-wrap"> <div className="flex items-center justify-between gap-3 flex-wrap">
<div className="flex items-center gap-2.5"> <div className="flex items-center gap-2.5">
<div className="p-2 rounded-xl bg-primary/20 text-primary border border-primary/30"> <div className="p-1.5 rounded-lg bg-primary/20 text-primary border border-primary/30 shrink-0">
<ShoppingCart className="w-4 h-4" /> <ShoppingCart className="w-4 h-4" />
</div> </div>
<div> <div>
<CardTitle className="text-base font-bold text-white"> <CardTitle className="text-sm font-bold text-white leading-tight">
{currentCategory.name} {currentCategory.name}
</CardTitle> </CardTitle>
<CardDescription className="text-xs text-slate-400 mt-0.5"> <CardDescription className="text-[11px] text-slate-400 mt-0.5 leading-tight">
{currentCategory.description || 'Passen Sie die Konfiguration für diese Kategorie an.'} {currentCategory.description || 'Passen Sie die Konfiguration für diese Kategorie an.'}
</CardDescription> </CardDescription>
</div> </div>
@@ -93,17 +93,17 @@ export function StepSoftware({
{editingDeviceName && ( {editingDeviceName && (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Badge className="bg-amber-500/20 text-amber-400 border border-amber-500/30 text-xs font-bold gap-1.5 px-3 py-1 rounded-lg animate-pulse shrink-0"> <Badge className="bg-amber-500/20 text-amber-400 border border-amber-500/30 text-xs font-bold gap-1.5 px-2.5 py-0.5 rounded-lg animate-pulse shrink-0 flex items-center">
Bearbeite Kasse: &quot;{editingDeviceName}&quot; <Icons.Pencil className="w-3 h-3 text-amber-400 mr-1" /> Kasse: &quot;{editingDeviceName}&quot;
</Badge> </Badge>
{onCancelEdit && ( {onCancelEdit && (
<Button <Button
size="sm" size="sm"
variant="ghost" variant="ghost"
onClick={onCancelEdit} onClick={onCancelEdit}
className="h-7 text-xs text-slate-400 hover:text-white hover:bg-white/10 px-2" className="h-6 text-[11px] text-slate-400 hover:text-white hover:bg-white/10 px-2"
> >
<X className="w-3.5 h-3.5 mr-1" /> Neuer Entwurf <X className="w-3 h-3 mr-1" /> Neuer Entwurf
</Button> </Button>
)} )}
</div> </div>
@@ -111,8 +111,8 @@ export function StepSoftware({
</div> </div>
</CardHeader> </CardHeader>
{/* ─── CONTENT AREA (Inherits scrolling from parent, no nested double scrollbar) ─── */} {/* ─── SCROLLABLE CONTENT AREA (flex-1 min-h-0 min-w-0 overflow-y-auto pr-3 pb-12) ─── */}
<CardContent className="p-5 space-y-5"> <div className="flex-1 min-h-0 min-w-0 overflow-y-auto p-4 pr-3 pb-12 scrollbar-thin scrollbar-thumb-slate-800 scrollbar-track-transparent">
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
<motion.div <motion.div
key={currentCategory.id} key={currentCategory.id}
@@ -120,49 +120,49 @@ export function StepSoftware({
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }} exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.2 }} transition={{ duration: 0.2 }}
className="space-y-5" className="space-y-4 min-w-0"
> >
{/* Category selection status header */} {/* Category selection status header */}
{(() => { {(() => {
const isMissingRequired = currentCategory.is_required && !sel?.productId && (!sel?.productIds || sel.productIds.length === 0) const isMissingRequired = currentCategory.is_required && !sel?.productId && (!sel?.productIds || sel.productIds.length === 0)
return ( return (
<div className={`flex items-center gap-3 p-3.5 rounded-xl border transition-all ${ <div className={`flex items-center gap-3 p-3 rounded-xl border transition-all ${
isMissingRequired isMissingRequired
? 'bg-red-500/10 border-red-500/50 text-red-400 font-bold' ? 'bg-red-500/10 border-red-500/50 text-red-400 font-bold'
: 'bg-white/5 border-white/10' : 'bg-white/5 border-white/10'
}`}> }`}>
<div className={`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${ <div className={`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${
isMissingRequired ? 'bg-red-500/20 text-red-400' : 'bg-primary/20 text-primary' isMissingRequired ? 'bg-red-500/20 text-red-400' : 'bg-primary/20 text-primary'
}`}> }`}>
<CategoryIcon icon={currentCategory.icon} className="w-4 h-4" /> <CategoryIcon icon={currentCategory.icon} className="w-3.5 h-3.5" />
</div> </div>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<h3 className="font-bold text-white text-xs flex items-center gap-2 flex-wrap"> <h3 className="font-bold text-white text-xs flex items-center gap-2 flex-wrap">
<span>{currentCategory.name}</span> <span>{currentCategory.name}</span>
{isMissingRequired && ( {isMissingRequired && (
<span className="text-[10px] bg-red-500/20 text-red-400 border border-red-500/40 px-2 py-0.5 rounded-full font-extrabold animate-pulse tracking-wider"> <span className="text-[10px] bg-red-500/20 text-red-400 border border-red-500/40 px-2 py-0.2 rounded-full font-extrabold animate-pulse tracking-wider">
PFLICHTFELD AUSWÄHLEN! PFLICHTFELD AUSWÄHLEN!
</span> </span>
)} )}
</h3> </h3>
<p className="text-slate-400 text-[11px] mt-0.5"> <p className="text-slate-400 text-[10px] mt-0.5">
{currentCategory.allow_multiselect ? 'Mehrfachauswahl möglich' : 'Einzelauswahl'} {currentCategory.allow_multiselect ? 'Mehrfachauswahl möglich' : 'Einzelauswahl'}
</p> </p>
</div> </div>
{sel?.productIds && sel.productIds.length > 0 ? ( {sel?.productIds && sel.productIds.length > 0 ? (
<Badge className="ml-auto bg-green-500/20 text-green-400 border border-green-500/30 text-xs rounded-full shrink-0"> <Badge className="ml-auto bg-green-500/20 text-green-400 border border-green-500/30 text-[11px] rounded-full shrink-0">
<Check className="w-3 h-3 mr-1" /> {sel.productIds.length} Ausgewählt <Check className="w-3 h-3 mr-1" /> {sel.productIds.length} Ausgewählt
</Badge> </Badge>
) : sel?.productId ? ( ) : sel?.productId ? (
<Badge className="ml-auto bg-green-500/20 text-green-400 border border-green-500/30 text-xs rounded-full shrink-0"> <Badge className="ml-auto bg-green-500/20 text-green-400 border border-green-500/30 text-[11px] rounded-full shrink-0">
<Check className="w-3 h-3 mr-1" /> Ausgewählt <Check className="w-3 h-3 mr-1" /> Ausgewählt
</Badge> </Badge>
) : currentCategory.is_required ? ( ) : currentCategory.is_required ? (
<Badge variant="destructive" className="ml-auto opacity-90 text-xs rounded-full bg-red-500/30 text-red-400 border border-red-500/50 animate-pulse font-extrabold shrink-0"> <Badge variant="destructive" className="ml-auto opacity-90 text-[11px] rounded-full bg-red-500/30 text-red-400 border border-red-500/50 animate-pulse font-extrabold shrink-0">
<AlertCircle className="w-3 h-3 mr-1 text-red-400" /> Bitte auswählen! <AlertCircle className="w-3 h-3 mr-1 text-red-400" /> Bitte auswählen!
</Badge> </Badge>
) : ( ) : (
<Badge variant="outline" className="ml-auto border-white/10 text-slate-400 text-xs rounded-full bg-white/5 shrink-0"> <Badge variant="outline" className="ml-auto border-white/10 text-slate-400 text-[11px] rounded-full bg-white/5 shrink-0">
Optional Optional
</Badge> </Badge>
)} )}
@@ -170,53 +170,57 @@ export function StepSoftware({
) )
})()} })()}
{/* Products List */} {/* Products List (grid-cols-1 xl:grid-cols-2 gap-3) */}
{catProducts.length === 0 ? ( {catProducts.length === 0 ? (
<p className="text-slate-500 text-xs italic p-4 bg-white/5 rounded-xl border border-white/5 text-center"> <p className="text-slate-500 text-xs italic p-4 bg-white/5 rounded-xl border border-white/5 text-center">
Keine Produkte in dieser Kategorie im aktuellen Abrechnungsmodell vorhanden. Keine Produkte in dieser Kategorie im aktuellen Abrechnungsmodell vorhanden.
</p> </p>
) : currentCategory.allow_multiselect ? ( ) : currentCategory.allow_multiselect ? (
<div className="grid gap-2.5"> <div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
{catProducts.map(product => { {catProducts.map(product => {
const isChecked = sel?.productIds?.includes(product.id) ?? false const isChecked = sel?.productIds?.includes(product.id) ?? false
const disabled = isProductDisabled(product, currentCategory.id) const disabled = isProductDisabled(product, currentCategory.id)
return ( return (
<div key={product.id} className="relative"> <div key={product.id} className="relative min-w-0">
<Label <Label
onClick={() => !disabled && selectProduct(currentCategory.id, product.id)} onClick={() => !disabled && selectProduct(currentCategory.id, product.id)}
className={`flex flex-col items-start p-3.5 rounded-xl border transition-all ${disabled className={`flex flex-col justify-between h-full p-3 rounded-xl border transition-all ${disabled
? 'border-white/5 bg-white/5 opacity-40 cursor-not-allowed' ? 'border-white/5 bg-white/5 opacity-40 cursor-not-allowed'
: isChecked : isChecked
? 'border-primary bg-primary/10 cursor-pointer shadow-[0_0_15px_rgba(59,130,246,0.15)] ring-1 ring-primary/40' ? 'border-primary bg-primary/10 cursor-pointer shadow-[0_0_15px_rgba(59,130,246,0.15)] ring-1 ring-primary/40'
: 'border-white/5 bg-white/5 hover:bg-white/10 cursor-pointer' : 'border-white/5 bg-white/5 hover:bg-white/10 cursor-pointer'
}`} }`}
> >
<div className="flex justify-between w-full items-center"> <div className="min-w-0 w-full">
<div className="flex items-center gap-2.5"> <div className="flex justify-between items-start gap-2 w-full">
<Checkbox <div className="flex items-start gap-2 min-w-0 flex-1">
checked={isChecked} <Checkbox
disabled={disabled} checked={isChecked}
onCheckedChange={() => { }} disabled={disabled}
className="border-white/20 data-[state=checked]:bg-primary rounded" onCheckedChange={() => { }}
/> className="border-white/20 data-[state=checked]:bg-primary rounded mt-0.5 shrink-0"
<span className="font-bold text-xs text-white">{product.name}</span> />
<span className={`text-[9px] px-1.5 py-0.5 rounded border ${billingBadgeClass(product.billing_interval)} font-medium`}> <div className="min-w-0 flex-1">
{product.billing_interval === 'one_time' ? 'Einmalig' : 'Abo'} <span className="font-bold text-xs text-white block break-words">{product.name}</span>
<span className={`inline-block text-[9px] px-1.5 py-0.2 mt-1 rounded border ${billingBadgeClass(product.billing_interval)} font-medium`}>
{product.billing_interval === 'one_time' ? 'Einmalig' : 'Abo'}
</span>
</div>
</div>
<span className="text-primary font-bold text-xs shrink-0 text-right">
{new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
}).format(product.base_price)}{' '}
<span className="text-[10px] text-slate-500 font-normal block">{billingLabel(product.billing_interval)}</span>
</span> </span>
</div> </div>
<span className="text-primary font-bold text-xs"> {product.description && (
{new Intl.NumberFormat('de-DE', { <p className="text-[11px] text-slate-400 mt-2 font-normal leading-relaxed break-words">{product.description}</p>
style: 'currency', )}
currency: 'EUR',
}).format(product.base_price)}{' '}
<span className="text-[10px] text-slate-500 font-normal">{billingLabel(product.billing_interval)}</span>
</span>
</div> </div>
{product.description && (
<span className="text-[11px] text-slate-400 mt-1.5 pl-6 font-normal leading-relaxed">{product.description}</span>
)}
{product.modules && product.modules.length > 0 && ( {product.modules && product.modules.length > 0 && (
<span className="text-[10px] text-slate-500 mt-1 pl-6 font-normal"> <span className="text-[10px] text-slate-500 mt-2 font-normal block">
{product.modules.length} optionale Module verfügbar {product.modules.length} optionale Module verfügbar
</span> </span>
)} )}
@@ -229,13 +233,13 @@ export function StepSoftware({
<RadioGroup <RadioGroup
value={sel?.productId ?? ''} value={sel?.productId ?? ''}
onValueChange={id => selectProduct(currentCategory.id, id)} onValueChange={id => selectProduct(currentCategory.id, id)}
className="grid gap-2.5" className="grid grid-cols-1 xl:grid-cols-2 gap-3"
> >
{catProducts.map(product => { {catProducts.map(product => {
const disabled = isProductDisabled(product, currentCategory.id) const disabled = isProductDisabled(product, currentCategory.id)
const isChecked = sel?.productId === product.id const isChecked = sel?.productId === product.id
return ( return (
<div key={product.id} className="relative"> <div key={product.id} className="relative min-w-0">
<RadioGroupItem <RadioGroupItem
value={product.id} value={product.id}
id={`${currentCategory.id}-${product.id}`} id={`${currentCategory.id}-${product.id}`}
@@ -244,33 +248,35 @@ export function StepSoftware({
/> />
<Label <Label
htmlFor={disabled ? undefined : `${currentCategory.id}-${product.id}`} htmlFor={disabled ? undefined : `${currentCategory.id}-${product.id}`}
className={`flex flex-col items-start p-3.5 rounded-xl border transition-all ${disabled className={`flex flex-col justify-between h-full p-3 rounded-xl border transition-all ${disabled
? 'border-white/5 bg-white/5 opacity-40 cursor-not-allowed' ? 'border-white/5 bg-white/5 opacity-40 cursor-not-allowed'
: isChecked : isChecked
? 'border-primary bg-primary/10 cursor-pointer shadow-[0_0_15px_rgba(59,130,246,0.15)] ring-1 ring-primary/40' ? 'border-primary bg-primary/10 cursor-pointer shadow-[0_0_15px_rgba(59,130,246,0.15)] ring-1 ring-primary/40'
: 'border-white/5 bg-white/5 hover:bg-white/10 cursor-pointer' : 'border-white/5 bg-white/5 hover:bg-white/10 cursor-pointer'
}`} }`}
> >
<div className="flex justify-between w-full items-center"> <div className="min-w-0 w-full">
<div className="flex items-center gap-2.5"> <div className="flex justify-between items-start gap-2 w-full">
<span className="font-bold text-xs text-white">{product.name}</span> <div className="min-w-0 flex-1">
<span className={`text-[9px] px-1.5 py-0.5 rounded border ${billingBadgeClass(product.billing_interval)} font-medium`}> <span className="font-bold text-xs text-white block break-words">{product.name}</span>
{product.billing_interval === 'one_time' ? 'Einmalig' : 'Abo'} <span className={`inline-block text-[9px] px-1.5 py-0.2 mt-1 rounded border ${billingBadgeClass(product.billing_interval)} font-medium`}>
{product.billing_interval === 'one_time' ? 'Einmalig' : 'Abo'}
</span>
</div>
<span className="text-primary font-bold text-xs shrink-0 text-right">
{new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
}).format(product.base_price)}{' '}
<span className="text-[10px] text-slate-500 font-normal block">{billingLabel(product.billing_interval)}</span>
</span> </span>
</div> </div>
<span className="text-primary font-bold text-xs"> {product.description && (
{new Intl.NumberFormat('de-DE', { <p className="text-[11px] text-slate-400 mt-2 font-normal leading-relaxed break-words">{product.description}</p>
style: 'currency', )}
currency: 'EUR',
}).format(product.base_price)}{' '}
<span className="text-[10px] text-slate-500 font-normal">{billingLabel(product.billing_interval)}</span>
</span>
</div> </div>
{product.description && (
<span className="text-[11px] text-slate-400 mt-1.5 font-normal leading-relaxed">{product.description}</span>
)}
{product.modules && product.modules.length > 0 && ( {product.modules && product.modules.length > 0 && (
<span className="text-[10px] text-slate-500 mt-1 font-normal"> <span className="text-[10px] text-slate-500 mt-2 font-normal block">
{product.modules.length} optionale Module verfügbar {product.modules.length} optionale Module verfügbar
</span> </span>
)} )}
@@ -283,12 +289,12 @@ export function StepSoftware({
{/* Modules Section */} {/* Modules Section */}
{selectedProduct?.modules && selectedProduct.modules.length > 0 && ( {selectedProduct?.modules && selectedProduct.modules.length > 0 && (
<div className="mt-5 p-4 rounded-2xl bg-white/5 border border-white/10 space-y-3.5"> <div className="mt-4 p-3.5 rounded-xl bg-white/5 border border-white/10 space-y-3 min-w-0">
<p className="text-xs font-bold text-white flex items-center gap-2"> <p className="text-xs font-bold text-white flex items-center gap-2">
<span className="w-1.5 h-1.5 rounded-full bg-primary" /> <span className="w-1.5 h-1.5 rounded-full bg-primary" />
Zusatzmodule für {selectedProduct.name} Zusatzmodule für {selectedProduct.name}
</p> </p>
<div className="space-y-2"> <div className="grid grid-cols-1 xl:grid-cols-2 gap-2.5">
{selectedProduct.modules.map(module => { {selectedProduct.modules.map(module => {
const isExistingLicense = existingModuleIds.includes(module.id) const isExistingLicense = existingModuleIds.includes(module.id)
const disabled = isExistingLicense || isModuleDisabled(module, sel?.moduleIds ?? []) const disabled = isExistingLicense || isModuleDisabled(module, sel?.moduleIds ?? [])
@@ -297,7 +303,7 @@ export function StepSoftware({
<div <div
key={module.id} key={module.id}
title={isExistingLicense ? "Dieses Modul ist auf dieser Kasse bereits aktiv und dauerhaft lizenziert." : undefined} title={isExistingLicense ? "Dieses Modul ist auf dieser Kasse bereits aktiv und dauerhaft lizenziert." : undefined}
className={`flex flex-col p-3.5 rounded-xl border transition-all duration-200 ${ className={`flex flex-col justify-between p-3 rounded-xl border transition-all duration-200 min-w-0 ${
isExistingLicense isExistingLicense
? 'border-primary/20 bg-primary/5 opacity-75' ? 'border-primary/20 bg-primary/5 opacity-75'
: disabled : disabled
@@ -307,30 +313,30 @@ export function StepSoftware({
: 'border-white/5 bg-white/5 hover:bg-white/10' : 'border-white/5 bg-white/5 hover:bg-white/10'
}`} }`}
> >
<div className="flex items-start space-x-3"> <div className="flex items-start space-x-2.5 min-w-0">
<Checkbox <Checkbox
id={`mod-${currentCategory.id}-${module.id}`} id={`mod-${currentCategory.id}-${module.id}`}
checked={checked} checked={checked}
onCheckedChange={() => !isExistingLicense && toggleModule(currentCategory.id, module.id)} onCheckedChange={() => !isExistingLicense && toggleModule(currentCategory.id, module.id)}
disabled={disabled} disabled={disabled}
className="rounded border-white/20 data-[state=checked]:bg-primary mt-0.5" className="rounded border-white/20 data-[state=checked]:bg-primary mt-0.5 shrink-0"
/> />
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<Label <Label
htmlFor={isExistingLicense ? undefined : `mod-${currentCategory.id}-${module.id}`} htmlFor={isExistingLicense ? undefined : `mod-${currentCategory.id}-${module.id}`}
className={`font-semibold text-xs flex justify-between text-white ${ className={`font-semibold text-xs flex justify-between items-start text-white gap-2 ${
isExistingLicense ? 'cursor-default' : disabled ? 'cursor-not-allowed' : 'cursor-pointer' isExistingLicense ? 'cursor-default' : disabled ? 'cursor-not-allowed' : 'cursor-pointer'
}`} }`}
> >
<span className="flex items-center gap-1.5 flex-wrap"> <span className="flex-1 min-w-0 break-words">
{module.name} {module.name}
{isExistingLicense && ( {isExistingLicense && (
<span className="inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded bg-primary/20 text-primary border border-primary/30 font-bold uppercase tracking-wider"> <span className="inline-flex items-center gap-1 text-[9px] px-1.5 py-0.2 rounded bg-primary/20 text-primary border border-primary/30 font-bold uppercase tracking-wider ml-1 mt-0.5">
<Lock className="w-2.5 h-2.5" /> Bereits lizenziert <Lock className="w-2.5 h-2.5" /> Lizenziert
</span> </span>
)} )}
</span> </span>
<span className="text-primary font-bold text-xs ml-2 shrink-0"> <span className="text-primary font-bold text-xs shrink-0 text-right">
{isExistingLicense ? ( {isExistingLicense ? (
<span className="text-slate-500 text-[11px] font-normal">inkl.</span> <span className="text-slate-500 text-[11px] font-normal">inkl.</span>
) : ( ) : (
@@ -342,7 +348,7 @@ export function StepSoftware({
</span> </span>
</Label> </Label>
{module.description && ( {module.description && (
<p className="text-[11px] text-slate-400 mt-1 leading-relaxed">{module.description}</p> <p className="text-[11px] text-slate-400 mt-1 leading-relaxed break-words">{module.description}</p>
)} )}
{!isExistingLicense && disabled && ( {!isExistingLicense && disabled && (
<p className="text-[10px] text-red-400 mt-1 font-medium flex items-center gap-1"> <p className="text-[10px] text-red-400 mt-1 font-medium flex items-center gap-1">
@@ -359,8 +365,8 @@ export function StepSoftware({
{/* Scalable Quantity */} {/* Scalable Quantity */}
{checked && !isExistingLicense && module.has_quantity && ( {checked && !isExistingLicense && module.has_quantity && (
<div className="flex items-center gap-3 mt-3 pl-7 pt-2.5 border-t border-white/5"> <div className="flex items-center gap-3 mt-2.5 pl-6 pt-2 border-t border-white/5">
<Label htmlFor={`qty-${module.id}`} className="text-[11px] text-slate-400 font-medium">Menge:</Label> <Label htmlFor={`qty-${module.id}`} className="text-[11px] text-slate-400 font-medium shrink-0">Menge:</Label>
<Input <Input
id={`qty-${module.id}`} id={`qty-${module.id}`}
type="number" type="number"
@@ -371,9 +377,9 @@ export function StepSoftware({
const val = Math.max(1, parseInt(e.target.value) || 1) const val = Math.max(1, parseInt(e.target.value) || 1)
setModuleQuantities(prev => ({ ...prev, [module.id]: val })) setModuleQuantities(prev => ({ ...prev, [module.id]: val }))
}} }}
className="w-16 h-7 bg-white/5 border-white/10 text-white text-xs text-center rounded-lg focus:border-primary focus:ring-1 focus:ring-primary" className="w-14 h-6 bg-white/5 border-white/10 text-white text-xs text-center rounded focus:border-primary focus:ring-1 focus:ring-primary"
/> />
<span className="text-[11px] text-slate-400"> <span className="text-[10px] text-slate-400 truncate">
Gesamt:{' '} Gesamt:{' '}
<span className="text-primary font-bold"> <span className="text-primary font-bold">
{new Intl.NumberFormat('de-DE', { {new Intl.NumberFormat('de-DE', {
@@ -404,7 +410,7 @@ export function StepSoftware({
)} )}
</motion.div> </motion.div>
</AnimatePresence> </AnimatePresence>
</CardContent> </div>
</Card> </Card>
) )
} }

View File

@@ -93,6 +93,7 @@ export function StepSummary({
}: StepSummaryProps) { }: StepSummaryProps) {
const [confirmDeleteIdx, setConfirmDeleteIdx] = useState<number | null>(null) const [confirmDeleteIdx, setConfirmDeleteIdx] = useState<number | null>(null)
const [acceptedTerms, setAcceptedTerms] = useState(false) const [acceptedTerms, setAcceptedTerms] = useState(false)
const [showConfirmModal, setShowConfirmModal] = useState(false)
const fmt = (val: number) => new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(val) const fmt = (val: number) => new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(val)
@@ -442,29 +443,6 @@ export function StepSummary({
className="w-full p-3 rounded-xl bg-slate-950/70 border border-white/10 text-xs text-white placeholder:text-slate-500 focus:border-primary focus:outline-none transition-colors resize-none scrollbar-thin scrollbar-thumb-slate-800 scrollbar-track-transparent" className="w-full p-3 rounded-xl bg-slate-950/70 border border-white/10 text-xs text-white placeholder:text-slate-500 focus:border-primary focus:outline-none transition-colors resize-none scrollbar-thin scrollbar-thumb-slate-800 scrollbar-track-transparent"
/> />
</div> </div>
{/* Lizenzbestimmungen & B2B-Workflow Checkbox */}
<div className="p-4 rounded-2xl bg-white/5 border border-white/10 space-y-3">
<div className="flex items-start gap-3">
<Checkbox
id="terms-checkbox"
checked={acceptedTerms}
onCheckedChange={(checked) => setAcceptedTerms(checked === true)}
className="rounded border-white/20 data-[state=checked]:bg-primary mt-0.5"
/>
<Label htmlFor="terms-checkbox" className="text-xs text-slate-300 leading-relaxed cursor-pointer select-none">
Ich bestätige die Richtigkeit der Angaben und akzeptiere die Lizenzvereinbarungen sowie die{' '}
<a href="/datenschutz" target="_blank" rel="noopener noreferrer" className="underline hover:text-white text-primary">
Datenschutzerklärung
</a>.
</Label>
</div>
<div className="p-2.5 rounded-xl bg-primary/10 border border-primary/20 text-[11px] text-slate-300 flex items-center gap-2">
<FileText className="w-4 h-4 text-primary shrink-0" />
<span>B2B-Freigabe: Nach Absenden wird die Lizenzierungsanfrage geprüft und freigegeben.</span>
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -490,10 +468,10 @@ export function StepSummary({
</span> </span>
</div> </div>
{/* Submit Button */} {/* Submit Button -> opens modal */}
<Button <Button
onClick={handleSubmit} onClick={() => setShowConfirmModal(true)}
disabled={isSubmitting || !acceptedTerms || finalItemsToShow.length === 0} disabled={isSubmitting || finalItemsToShow.length === 0}
className="w-full sm:w-auto bg-primary hover:bg-primary/90 text-white font-bold px-6 shadow-lg shadow-primary/20 h-9 text-xs gap-2" className="w-full sm:w-auto bg-primary hover:bg-primary/90 text-white font-bold px-6 shadow-lg shadow-primary/20 h-9 text-xs gap-2"
> >
{isSubmitting ? ( {isSubmitting ? (
@@ -509,6 +487,104 @@ export function StepSummary({
)} )}
</Button> </Button>
</div> </div>
{/* ─── 4. BESTÄTIGUNGS-POPUP / MODAL VOR DEM ABSENDEN ─── */}
{showConfirmModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm animate-in fade-in duration-200">
<div className="w-full max-w-lg bg-slate-900 border border-white/10 rounded-2xl shadow-2xl p-6 space-y-5 text-white">
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-3">
<div className="p-2.5 rounded-xl bg-primary/20 text-primary border border-primary/30">
<ShieldCheck className="w-6 h-6" />
</div>
<div>
<h3 className="text-base font-bold text-white">Richtigkeit & Freigabe bestätigen</h3>
<p className="text-xs text-slate-400 mt-0.5">Letzter Schritt vor Übermittlung der Lizenzierung</p>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => setShowConfirmModal(false)}
disabled={isSubmitting}
className="h-8 w-8 p-0 text-slate-400 hover:text-white rounded-lg"
>
<X className="w-4 h-4" />
</Button>
</div>
<div className="space-y-3 text-xs text-slate-300">
<div className="p-3.5 rounded-xl bg-white/5 border border-white/10 space-y-2">
<div className="flex justify-between items-center text-white font-semibold">
<span>Endkunde:</span>
<span className="text-primary">{selectedEndCustomer?.company_name || 'Kein Kunde gewählt'}</span>
</div>
<div className="flex justify-between items-center text-slate-400">
<span>Anzahl Geräte:</span>
<span className="text-white font-medium">{finalItemsToShow.length} Kassen</span>
</div>
<div className="flex justify-between items-center text-slate-400">
<span>Gesamtbetrag (brutto):</span>
<span className="text-white font-bold">{oneTimeTotal > 0 ? fmt(oneTimeGross) : `${fmt(monthlyGross)} / mtl.`}</span>
</div>
</div>
<div className="p-3.5 rounded-xl bg-slate-950/80 border border-white/10 space-y-3">
<div className="flex items-start gap-3">
<Checkbox
id="modal-terms-checkbox"
checked={acceptedTerms}
onCheckedChange={(checked) => setAcceptedTerms(checked === true)}
className="rounded border-white/20 data-[state=checked]:bg-primary mt-0.5"
/>
<Label htmlFor="modal-terms-checkbox" className="text-xs text-slate-300 leading-relaxed cursor-pointer select-none">
Ich bestätige die Richtigkeit aller gemachten Angaben und akzeptiere die Lizenzvereinbarungen sowie die{' '}
<a href="/datenschutz" target="_blank" rel="noopener noreferrer" className="underline hover:text-white text-primary">
Datenschutzerklärung
</a>.
</Label>
</div>
<div className="p-2.5 rounded-lg bg-primary/10 border border-primary/20 text-[11px] text-slate-300 flex items-center gap-2">
<FileText className="w-4 h-4 text-primary shrink-0" />
<span>B2B-Freigabe: Nach Absenden wird die Lizenzierungsanfrage geprüft und freigegeben.</span>
</div>
</div>
</div>
<div className="flex items-center justify-end gap-3 pt-2 border-t border-white/10">
<Button
variant="outline"
onClick={() => setShowConfirmModal(false)}
disabled={isSubmitting}
className="border-white/10 text-white hover:bg-white/10 text-xs h-9 px-4"
>
Abbrechen & Zurück
</Button>
<Button
onClick={async () => {
await handleSubmit()
setShowConfirmModal(false)
}}
disabled={!acceptedTerms || isSubmitting}
className="bg-primary hover:bg-primary/90 text-white font-bold text-xs h-9 px-5 gap-2 shadow-md shadow-primary/20"
>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
Wird übermittelt...
</>
) : (
<>
<Check className="w-4 h-4" />
Jetzt verbindlich absenden
</>
)}
</Button>
</div>
</div>
</div>
)}
</Card> </Card>
) )
} }

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import { motion, AnimatePresence } from 'framer-motion' import { motion, AnimatePresence } from 'framer-motion'
import { AlertCircle } from 'lucide-react' import { AlertCircle, X } from 'lucide-react'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
interface ToastProps { interface ToastProps {
@@ -31,7 +31,7 @@ export function ToastNotification({ toast, onClose }: ToastProps) {
className="w-5 h-5 ml-auto text-slate-400 hover:text-white" className="w-5 h-5 ml-auto text-slate-400 hover:text-white"
onClick={onClose} onClick={onClose}
> >
<X className="w-3.5 h-3.5" />
</Button> </Button>
</motion.div> </motion.div>
)} )}

View File

@@ -158,17 +158,17 @@ function get2FAEmailHtml(code: string) {
<div style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border-radius: 12px; padding: 16px 20px; margin: 24px 0; border-left: 4px solid #f59e0b;"> <div style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border-radius: 12px; padding: 16px 20px; margin: 24px 0; border-left: 4px solid #f59e0b;">
<p style="color: #92400e; font-size: 14px; margin: 0; line-height: 1.5;"> <p style="color: #92400e; font-size: 14px; margin: 0; line-height: 1.5;">
⏱️ <strong>Dieser Code ist 15 Minuten gültig.</strong><br> <strong>Dieser Code ist 15 Minuten gültig.</strong><br>
Falls Sie diese Anmeldung nicht durchgeführt haben, ändern Sie bitte umgehend Ihr Passwort. Falls Sie diese Anmeldung nicht durchgeführt haben, ändern Sie bitte umgehend Ihr Passwort.
</p> </p>
</div> </div>
<p style="color: #64748b; font-size: 13px; line-height: 1.6; margin-top: 24px;"> <p style="color: #64748b; font-size: 13px; line-height: 1.6; margin-top: 24px;">
🔒 Dieser Code dient der Sicherheit Ihres Kontos. Geben Sie ihn niemals an andere Personen weiter. Dieser Code dient der Sicherheit Ihres Kontos. Geben Sie ihn niemals an andere Personen weiter.
</p> </p>
` `
return getBeautifulEmailHtml('🔐 Sicherheitscode', messageHtml) return getBeautifulEmailHtml('Sicherheitscode', messageHtml)
} }
/** Internal: generates code + sends email (no auth check needed) */ /** Internal: generates code + sends email (no auth check needed) */
@@ -199,7 +199,7 @@ async function send2FACodeInternal(userId: string, deviceHash: string, email: st
// Mail senden // Mail senden
await sendMail({ await sendMail({
to: email, to: email,
subject: '🔐 Ihr Sicherheitscode CASPOS Shop', subject: 'Ihr Sicherheitscode CASPOS Shop',
text: `Ihr Sicherheitscode lautet: ${code}\n\nDieser Code ist 15 Minuten gültig.\n\nFalls Sie diese Anmeldung nicht durchgeführt haben, ändern Sie bitte umgehend Ihr Passwort.`, text: `Ihr Sicherheitscode lautet: ${code}\n\nDieser Code ist 15 Minuten gültig.\n\nFalls Sie diese Anmeldung nicht durchgeführt haben, ändern Sie bitte umgehend Ihr Passwort.`,
html: get2FAEmailHtml(code), html: get2FAEmailHtml(code),
}) })

View File

@@ -1,195 +1,429 @@
interface EmailDetails { export interface OrderEmailProps {
orderNumber: string orderNumber: string
status: 'pending' | 'pending_approval' | 'in_review' | 'approved' | 'active' | 'completed' | 'cancelled' | 'rejected'
formattedDate: string formattedDate: string
customerCompanyName: string customerCompanyName: string
totalDetailsText: string billingModel?: string // e.g. "Kauf" | "Miete (monatlich)" | "Kauf / Miete"
totalDetailsHtml: string rejectionReason?: string
itemsDetailsText?: string siteUrl?: string
itemsDetailsHtml?: string items?: any[]
partnerCompanyName?: string partnerCompanyName?: string
partnerUserName?: string partnerUserName?: string
partnerUserEmail?: string partnerUserEmail?: string
taxRate?: number
oneTimeNet?: number
monthlyNet?: number
} }
export function getOrderEmailTemplate( export function generateOrderEmailSubject(orderNumber: string, status: string): string {
details: EmailDetails, const formattedOrderNumber = (orderNumber || '').replace(/^BE-/, 'AE-')
siteUrl: string, if (status === 'approved' || status === 'active' || status === 'completed') {
isUpdate: boolean = false, return `Auftragsbestätigung: Anfrage #${formattedOrderNumber} freigegeben`
primaryColor: string = '#2563eb' }
) { if (status === 'rejected' || status === 'cancelled') {
const title = isUpdate ? 'Anfrage geändert' : 'Anfrage erhalten' return `Status-Update: Anfrage #${formattedOrderNumber} abgelehnt`
const intro = isUpdate }
? `Deine Anfrage ${details.orderNumber} wurde aktualisiert.` return `Eingangsbestätigung: Anfrage #${formattedOrderNumber} eingegangen`
: `Deine Anfrage ${details.orderNumber} ist bei uns eingegangen und wird bearbeitet.` }
let partnerText = '' export function generateOrderEmailHtml(props: OrderEmailProps): { text: string; html: string } {
let partnerHtml = '' const formattedOrderNumber = (props.orderNumber || '').replace(/^BE-/, 'AE-')
if (details.partnerCompanyName || details.partnerUserName || details.partnerUserEmail) { const siteUrl = props.siteUrl || process.env.NEXT_PUBLIC_SITE_URL || 'https://staging.hephex.de'
partnerText = `\nPartner-Informationen:` const taxRate = props.taxRate ?? 19
if (details.partnerCompanyName) partnerText += `\n- Firma: ${details.partnerCompanyName}` const orderPortalUrl = `${siteUrl}/my-orders`
if (details.partnerUserName) partnerText += `\n- Benutzer: ${details.partnerUserName}`
if (details.partnerUserEmail) partnerText += `\n- E-Mail: ${details.partnerUserEmail}`
partnerText += `\n`
partnerHtml = ` // Status Callout configuration
<tr> let calloutBg = '#f8fafc'
<td colspan="2" style="padding: 8px 0; border-top: 1px solid #e2e8f0; font-weight: bold; color: #0f172a;">Partner-Informationen:</td> let calloutBorder = '#cbd5e1'
</tr> let calloutTitle = 'Status: Anfrage eingegangen und in Prüfung'
` let calloutText = 'Ihre Anfrage ist erfolgreich in unserem System eingegangen und wird derzeit vom Support geprüft.'
if (details.partnerCompanyName) { let statusBadgeColor = '#2563eb'
partnerHtml += `
<tr> if (props.status === 'approved' || props.status === 'active' || props.status === 'completed') {
<td style="padding: 4px 0; padding-left: 10px; color: #475569; font-weight: bold;">Firma:</td> calloutBg = '#f0fdf4'
<td style="padding: 4px 0; color: #475569;">${details.partnerCompanyName}</td> calloutBorder = '#86efac'
</tr> calloutTitle = 'Status: Freigegeben / Aktiv'
` calloutText = 'Ihre Auftragsbestätigung / Rechnung finden Sie als PDF im Anhang dieser E-Mail.'
} statusBadgeColor = '#16a34a'
if (details.partnerUserName) { } else if (props.status === 'rejected' || props.status === 'cancelled') {
partnerHtml += ` calloutBg = '#fef2f2'
<tr> calloutBorder = '#fca5a5'
<td style="padding: 4px 0; padding-left: 10px; color: #475569; font-weight: bold;">Benutzer:</td> calloutTitle = 'Status: Anfrage abgelehnt'
<td style="padding: 4px 0; color: #475569;">${details.partnerUserName}</td> calloutText = props.rejectionReason
</tr> ? `Begründung: "${props.rejectionReason}"`
` : 'Ihre Anfrage wurde vom Support geprüft und konnte leider nicht freigegeben werden.'
} statusBadgeColor = '#dc2626'
if (details.partnerUserEmail) { }
partnerHtml += `
<tr> // Calculate prices if items provided
<td style="padding: 4px 0; padding-left: 10px; color: #475569; font-weight: bold;">E-Mail:</td> let oneTimeNet = props.oneTimeNet ?? 0
<td style="padding: 4px 0; color: #475569;">${details.partnerUserEmail}</td> let monthlyNet = props.monthlyNet ?? 0
</tr> const items = props.items || []
`
if (items.length > 0 && props.oneTimeNet === undefined && props.monthlyNet === undefined) {
items.forEach((item: any) => {
if (item.billing_interval === 'monthly') {
monthlyNet += item.base_price || 0
} else {
oneTimeNet += item.base_price || 0
}
item.selected_modules?.forEach((mod: any) => {
const qty = mod.quantity || 1
const price = mod.total_price ?? (mod.price * qty)
monthlyNet += price
})
})
}
const oneTimeTax = Math.round(oneTimeNet * (taxRate / 100) * 100) / 100
const oneTimeGross = Math.round((oneTimeNet + oneTimeTax) * 100) / 100
const monthlyTax = Math.round(monthlyNet * (taxRate / 100) * 100) / 100
const monthlyGross = Math.round((monthlyNet + monthlyTax) * 100) / 100
const formatEuro = (val: number) =>
new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(val)
// Determine Billing Model Label
let billingModelLabel = props.billingModel
if (!billingModelLabel) {
if (oneTimeNet > 0 && monthlyNet > 0) {
billingModelLabel = 'Kauf & Miete'
} else if (monthlyNet > 0) {
billingModelLabel = 'Miete (monatlich)'
} else {
billingModelLabel = 'Kauf (einmalig)'
} }
} }
const text = `Hallo,\n\n${isUpdate ? 'Deine Anfrage wurde aktualisiert.' : 'Deine Anfrage ist bei uns eingegangen.'}\n\nDetails:\n- Nummer: ${details.orderNumber}\n- Datum: ${details.formattedDate}\n- Kunde: ${details.customerCompanyName}\n${partnerText}${details.itemsDetailsText || ''}\n${details.totalDetailsText}\n\nDeine Anfragebestätigung findest du im Anhang als PDF.\n\nPDF-Link: ${siteUrl}/api/orders/${details.orderNumber}/download\n\nViele Grüße,\nDein CASPOS Team` // Group items by Device
const groupedItems: { [key: string]: any[] } = {}
items.forEach((item: any) => {
const devName = item.device_name || 'Kasse 1'
if (!groupedItems[devName]) {
groupedItems[devName] = []
}
groupedItems[devName].push(item)
})
const html = ` // Build Text Breakdown
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;"> let itemsBreakdownText = ''
<h2 style="color: ${primaryColor}; margin-bottom: 16px;">${title}</h2> if (items.length > 0) {
<p style="color: #475569; font-size: 16px; line-height: 1.5;">Hallo,</p> itemsBreakdownText += '\nKassen-Aufstellung:\n'
<p style="color: #475569; font-size: 16px; line-height: 1.5;">${intro}</p> Object.entries(groupedItems).forEach(([devName, devItems]) => {
<div style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 16px; margin: 24px 0;"> itemsBreakdownText += `\n[ ${devName} ]\n`
<h3 style="color: #0f172a; margin-top: 0; margin-bottom: 12px;">Details</h3> devItems.forEach((item: any) => {
<table style="width: 100%; border-collapse: collapse; font-size: 14px; color: #475569;"> itemsBreakdownText += ` - ${item.product_name} (${item.category_name || 'Basis'}): ${formatEuro(item.base_price || 0)} ${item.billing_interval === 'one_time' ? 'einmalig' : 'mtl.'}\n`
item.selected_modules?.forEach((mod: any) => {
const qty = mod.quantity || 1
const price = mod.total_price ?? (mod.price * qty)
itemsBreakdownText += ` + ${mod.module_name} ${qty > 1 ? `(x${qty})` : ''}: +${formatEuro(price)} mtl.\n`
})
})
})
}
let totalsText = ''
if (oneTimeNet > 0) {
totalsText += `\nEinmalige Beträge:\n- Netto: ${formatEuro(oneTimeNet)}\n- zzgl. ${taxRate}% MwSt: ${formatEuro(oneTimeTax)}\n- Brutto Gesamt: ${formatEuro(oneTimeGross)}\n`
}
if (monthlyNet > 0) {
totalsText += `\nMonatliche Beträge:\n- Netto: ${formatEuro(monthlyNet)} / mtl.\n- zzgl. ${taxRate}% MwSt: ${formatEuro(monthlyTax)} / mtl.\n- Brutto Gesamt: ${formatEuro(monthlyGross)} / mtl.\n`
}
let partnerPlainText = ''
if (props.partnerCompanyName || props.partnerUserName || props.partnerUserEmail) {
partnerPlainText = `\nPartner / Betreuer:\n- Firma: ${props.partnerCompanyName || '-'}\n- Ansprechpartner: ${props.partnerUserName || '-'}\n- E-Mail: ${props.partnerUserEmail || '-'}\n`
}
const text = `CASPOS B2B Portal\nAnfrage #${formattedOrderNumber}\n\n${calloutTitle}\n${calloutText}\n\nAuftragsdetails:\n- Endkunde: ${props.customerCompanyName}\n- Datum: ${props.formattedDate}\n- Abrechnung: ${billingModelLabel}\n${partnerPlainText}${itemsBreakdownText}${totalsText}\n\nAnfrage im Portal ansehen: ${orderPortalUrl}\n\nCASPOS Computerabrechnungssysteme GmbH\nAlte Bundesstraße 16 · 76846 Hauenstein\nAmtsgericht Zweibrücken HRB 12345\nAutomatische Systembenachrichtigung.`
// Build HTML Items Rows
let itemsHtmlRows = ''
if (items.length > 0) {
Object.entries(groupedItems).forEach(([devName, devItems]) => {
itemsHtmlRows += `
<tr>
<td colspan="2" style="padding: 10px 14px; background-color: #f1f5f9; font-weight: 600; font-size: 13px; color: #1e293b; border-bottom: 1px solid #e2e8f0;">
${devName === 'Zusatzleistung' ? 'Backoffice / Zusatzleistung' : `Kassengerät: ${devName}`}
</td>
</tr>
`
devItems.forEach((item: any) => {
itemsHtmlRows += `
<tr> <tr>
<td style="padding: 4px 0; font-weight: bold; width: 140px;">Nummer:</td> <td style="padding: 8px 14px; font-size: 13px; color: #334155; font-weight: 500; border-bottom: 1px solid #f1f5f9;">
<td style="padding: 4px 0;">${details.orderNumber}</td> ${item.product_name} <span style="font-size: 11px; color: #64748b;">(${item.category_name || 'Basis'})</span>
</td>
<td style="padding: 8px 14px; text-align: right; font-size: 13px; font-weight: 600; color: #0f172a; border-bottom: 1px solid #f1f5f9;">
${formatEuro(item.base_price || 0)} <span style="font-size: 11px; color: #64748b; font-weight: normal;">${item.billing_interval === 'one_time' ? 'einmalig' : 'mtl.'}</span>
</td>
</tr>
`
item.selected_modules?.forEach((mod: any) => {
const qty = mod.quantity || 1
const price = mod.total_price ?? (mod.price * qty)
itemsHtmlRows += `
<tr>
<td style="padding: 4px 14px 4px 28px; color: #64748b; font-size: 12px; border-bottom: 1px solid #f8fafc;">
+ ${mod.module_name} ${qty > 1 ? `<span style="font-size: 10px; font-weight: 600;">(x${qty})</span>` : ''}
</td>
<td style="padding: 4px 14px; text-align: right; color: #64748b; font-size: 12px; border-bottom: 1px solid #f8fafc;">
+${formatEuro(price)} <span style="font-size: 10px;">mtl.</span>
</td>
</tr>
`
})
})
})
}
// Build HTML Partner Section
let partnerHtml = ''
if (props.partnerCompanyName || props.partnerUserName || props.partnerUserEmail) {
partnerHtml = `
<tr>
<td colspan="2" style="padding: 12px 0 4px 0; border-top: 1px solid #e2e8f0; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: #64748b;">Partner & Betreuung:</td>
</tr>
${props.partnerCompanyName ? `<tr><td style="padding: 3px 0; font-size: 13px; color: #64748b;">Firma:</td><td style="padding: 3px 0; font-size: 13px; font-weight: 500; color: #0f172a; text-align: right;">${props.partnerCompanyName}</td></tr>` : ''}
${props.partnerUserName ? `<tr><td style="padding: 3px 0; font-size: 13px; color: #64748b;">Ansprechpartner:</td><td style="padding: 3px 0; font-size: 13px; color: #0f172a; text-align: right;">${props.partnerUserName}</td></tr>` : ''}
${props.partnerUserEmail ? `<tr><td style="padding: 3px 0; font-size: 13px; color: #64748b;">E-Mail:</td><td style="padding: 3px 0; font-size: 13px; color: #0f172a; text-align: right;">${props.partnerUserEmail}</td></tr>` : ''}
`
}
// Totals Section HTML
let totalsHtml = ''
if (oneTimeNet > 0 || monthlyNet > 0) {
totalsHtml = `
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-top: 16px; border-top: 2px solid #e2e8f0; padding-top: 12px; font-size: 13px; color: #334155;">
${oneTimeNet > 0 ? `
<tr>
<td colspan="2" style="padding: 4px 0; font-weight: 600; font-size: 11px; text-transform: uppercase; color: #64748b; letter-spacing: 0.05em;">Einmalige Beträge:</td>
</tr> </tr>
<tr> <tr>
<td style="padding: 4px 0; font-weight: bold;">Datum:</td> <td style="padding: 2px 0; color: #64748b;">Netto-Zwischensumme:</td>
<td style="padding: 4px 0;">${details.formattedDate}</td> <td style="padding: 2px 0; text-align: right; font-weight: 500; color: #0f172a;">${formatEuro(oneTimeNet)}</td>
</tr> </tr>
<tr> <tr>
<td style="padding: 4px 0; font-weight: bold;">Kunde:</td> <td style="padding: 2px 0; color: #64748b;">zzgl. ${taxRate}% MwSt:</td>
<td style="padding: 4px 0;">${details.customerCompanyName}</td> <td style="padding: 2px 0; text-align: right; color: #64748b;">${formatEuro(oneTimeTax)}</td>
</tr> </tr>
${partnerHtml} <tr>
${details.itemsDetailsHtml || ''} <td style="padding: 4px 0 10px 0; font-weight: 600; color: #0f172a;">Gesamt einmalig (brutto):</td>
${details.totalDetailsHtml} <td style="padding: 4px 0 10px 0; text-align: right; font-weight: 700; color: #0f172a; font-size: 14px;">${formatEuro(oneTimeGross)}</td>
</tr>
` : ''}
${monthlyNet > 0 ? `
<tr>
<td colspan="2" style="padding: ${oneTimeNet > 0 ? '10px' : '4px'} 0 4px 0; font-weight: 600; font-size: 11px; text-transform: uppercase; color: #64748b; letter-spacing: 0.05em; ${oneTimeNet > 0 ? 'border-top: 1px dashed #e2e8f0;' : ''}">Monatlich wiederkehrend:</td>
</tr>
<tr>
<td style="padding: 2px 0; color: #64748b;">Netto-Zwischensumme:</td>
<td style="padding: 2px 0; text-align: right; font-weight: 500; color: #0f172a;">${formatEuro(monthlyNet)} / mtl.</td>
</tr>
<tr>
<td style="padding: 2px 0; color: #64748b;">zzgl. ${taxRate}% MwSt:</td>
<td style="padding: 2px 0; text-align: right; color: #64748b;">${formatEuro(monthlyTax)} / mtl.</td>
</tr>
<tr>
<td style="padding: 4px 0; font-weight: 600; color: #0f172a;">Gesamt monatlich (brutto):</td>
<td style="padding: 4px 0; text-align: right; font-weight: 700; color: #0f172a; font-size: 14px;">${formatEuro(monthlyGross)} / mtl.</td>
</tr>
` : ''}
</table>
`
}
const html = `<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CASPOS B2B Portal - #${formattedOrderNumber}</title>
</head>
<body style="margin: 0; padding: 0; background-color: #f8fafc; font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; color: #0f172a;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #f8fafc; padding: 24px 12px;">
<tr>
<td align="center">
<!-- Main Card (max-width 600px) -->
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="max-width: 600px; background-color: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);">
<!-- Header Banner -->
<tr>
<td style="background-color: #0f172a; padding: 24px; text-align: left;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
<div style="font-size: 18px; font-weight: 700; color: #ffffff; letter-spacing: -0.02em; text-transform: uppercase;">CASPOS B2B Portal</div>
<div style="font-size: 12px; color: #94a3b8; margin-top: 2px;">Die Kasse · Fachhandelsportal</div>
</td>
<td align="right" style="vertical-align: middle;">
<span style="font-family: monospace, Courier, monospace; font-size: 14px; font-weight: 600; color: #38bdf8; background-color: #1e293b; padding: 6px 10px; border-radius: 4px; border: 1px solid #334155;">
#${formattedOrderNumber}
</span>
</td>
</tr>
</table>
</td>
</tr>
<!-- Body Content -->
<tr>
<td style="padding: 24px;">
<!-- Status Callout -->
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: ${calloutBg}; border-left: 4px solid ${statusBadgeColor}; border-top: 1px solid ${calloutBorder}; border-right: 1px solid ${calloutBorder}; border-bottom: 1px solid ${calloutBorder}; border-radius: 4px; margin-bottom: 24px;">
<tr>
<td style="padding: 14px 16px;">
<div style="font-weight: 700; font-size: 14px; color: #0f172a; margin-bottom: 4px;">${calloutTitle}</div>
<div style="font-size: 13px; color: #334155; line-height: 1.5;">${calloutText}</div>
</td>
</tr>
</table>
<!-- Order & Customer Meta Table -->
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 16px; margin-bottom: 24px;">
<tr>
<td>
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="font-size: 13px;">
<tr>
<td style="padding: 4px 0; color: #64748b; width: 140px;">Endkunde:</td>
<td style="padding: 4px 0; font-weight: 600; color: #0f172a; text-align: right;">${props.customerCompanyName}</td>
</tr>
<tr>
<td style="padding: 4px 0; color: #64748b;">Bestelldatum:</td>
<td style="padding: 4px 0; font-weight: 500; color: #0f172a; text-align: right;">${props.formattedDate}</td>
</tr>
<tr>
<td style="padding: 4px 0; color: #64748b;">Abrechnungsmodell:</td>
<td style="padding: 4px 0; font-weight: 500; color: #0f172a; text-align: right;">${billingModelLabel}</td>
</tr>
${partnerHtml}
</table>
</td>
</tr>
</table>
<!-- Hardware / Modules Breakdown -->
${items.length > 0 ? `
<div style="font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: #475569; margin-bottom: 8px;">Kassen-Aufstellung</div>
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 1px solid #e2e8f0; border-radius: 6px; overflow: hidden; margin-bottom: 20px;">
${itemsHtmlRows}
</table>
` : ''}
<!-- Totals -->
${totalsHtml}
<!-- Primary Action Button -->
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-top: 32px; margin-bottom: 8px;">
<tr>
<td align="center">
<a href="${orderPortalUrl}" target="_blank" style="display: inline-block; background-color: #2563eb; color: #ffffff; text-decoration: none; font-size: 14px; font-weight: 600; padding: 12px 28px; border-radius: 6px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
[ Anfrage im Portal ansehen ]
</a>
</td>
</tr>
</table>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="background-color: #f8fafc; border-top: 1px solid #e2e8f0; padding: 20px 24px; text-align: center; font-size: 12px; color: #64748b; line-height: 1.5;">
<p style="margin: 0; font-weight: 600; color: #475569;">CASPOS Computerabrechnungssysteme GmbH</p>
<p style="margin: 2px 0 0 0;">Alte Bundesstraße 16 · 76846 Hauenstein · Amtsgericht Zweibrücken HRB 12345</p>
<p style="margin: 8px 0 0 0; font-size: 11px; color: #94a3b8;">Dies ist eine automatische Transaktions-E-Mail des CASPOS B2B Portals.</p>
</td>
</tr>
</table> </table>
</div> </td>
<p style="color: #475569; font-size: 16px; line-height: 1.5;">Die Bestätigung liegt als PDF im Anhang.</p> </tr>
<p style="color: #475569; font-size: 16px; line-height: 1.5;"> </table>
<a href="${siteUrl}/api/orders/${details.orderNumber}/download" style="color: ${primaryColor}; text-decoration: underline; font-weight: 500;">Anfragebestätigung PDF herunterladen</a> </body>
</p> </html>`
<p style="color: #475569; font-size: 16px; line-height: 1.5; margin-top: 24px;">Viele Grüße,<br>Dein CASPOS Team</p>
</div>
`
return { text, html } return { text, html }
} }
// Backwards-compatible Wrappers
export function getOrderEmailTemplate(
details: {
orderNumber: string
formattedDate: string
customerCompanyName: string
totalDetailsText?: string
totalDetailsHtml?: string
itemsDetailsText?: string
itemsDetailsHtml?: string
partnerCompanyName?: string
partnerUserName?: string
partnerUserEmail?: string
items?: any[]
taxRate?: number
oneTimeNet?: number
monthlyNet?: number
billingModel?: string
},
siteUrl: string,
isUpdate: boolean = false,
_primaryColor?: string
) {
return generateOrderEmailHtml({
orderNumber: details.orderNumber,
status: isUpdate ? 'in_review' : 'pending',
formattedDate: details.formattedDate,
customerCompanyName: details.customerCompanyName,
billingModel: details.billingModel,
siteUrl,
items: details.items,
partnerCompanyName: details.partnerCompanyName,
partnerUserName: details.partnerUserName,
partnerUserEmail: details.partnerUserEmail,
taxRate: details.taxRate,
oneTimeNet: details.oneTimeNet,
monthlyNet: details.monthlyNet,
})
}
export function getStatusEmailTemplate( export function getStatusEmailTemplate(
orderNumber: string, orderNumber: string,
oldLabel: string, _oldLabel: string,
newLabel: string, _newLabel: string,
statusKey?: string, statusKey?: string,
rejectionReason?: string rejectionReason?: string,
) { extraDetails?: {
const formattedOrderNumber = orderNumber.replace(/^BE-/, 'AE-') customerCompanyName?: string
formattedDate?: string
let title = 'Statusänderung' billingModel?: string
let intro = `der Status deiner Anfrage <strong>#${formattedOrderNumber}</strong> wurde aktualisiert.` items?: any[]
let statusColor = '#f59e0b' // Amber default partnerCompanyName?: string
let showAttachmentBadge = false partnerUserName?: string
partnerUserEmail?: string
if (statusKey === 'approved' || statusKey === 'active' || statusKey === 'completed') { taxRate?: number
title = 'Freigabebestätigung' oneTimeNet?: number
intro = `Ihre Anfrage <strong>#${formattedOrderNumber}</strong> wurde erfolgreich freigegeben und ist nun aktiv. Die unterzeichnete Anfragebestätigung finden Sie im Anhang dieses Schreibens.` monthlyNet?: number
statusColor = '#10b981' // Emerald
showAttachmentBadge = true
} else if (statusKey === 'rejected') {
title = 'Anfrage abgelehnt'
intro = `Ihre Anfrage <strong>#${formattedOrderNumber}</strong> wurde vom Support geprüft und abgelehnt.`
statusColor = '#ef4444' // Red
} else if (statusKey === 'pending_approval' || statusKey === 'in_review' || statusKey === 'pending') {
title = 'Eingangsbestätigung'
intro = `Ihre Anfrage <strong>#${formattedOrderNumber}</strong> ist eingegangen und wird derzeit von unserem Support geprüft.`
statusColor = '#f59e0b'
} }
) {
const text = `Hallo,\n\n${title}\n\n${intro.replace(/<[^>]*>/g, '')}\n\nStatus: ${newLabel} (vorher: ${oldLabel})\n${rejectionReason ? `Grund: ${rejectionReason}\n` : ''}\nViele Grüße,\nDein CASPOS Team` const status = (statusKey || 'pending') as any
return generateOrderEmailHtml({
const reasonSection = rejectionReason orderNumber,
? ` status,
<div style="margin-top: 20px; padding: 12px 16px; background-color: rgba(239, 68, 68, 0.1); border-left: 4px solid #ef4444; border-radius: 4px;"> formattedDate: extraDetails?.formattedDate || new Date().toLocaleDateString('de-DE'),
<p style="margin: 0; font-size: 11px; color: #ef4444; font-weight: bold; text-transform: uppercase; tracking-spacing: 0.05em;">Begründung:</p> customerCompanyName: extraDetails?.customerCompanyName || 'Endkunde',
<p style="margin: 4px 0 0 0; font-size: 14px; color: #f8fafc; font-style: italic;">"${rejectionReason}"</p> billingModel: extraDetails?.billingModel,
</div> rejectionReason,
` items: extraDetails?.items,
: '' partnerCompanyName: extraDetails?.partnerCompanyName,
partnerUserName: extraDetails?.partnerUserName,
const footerActions = showAttachmentBadge partnerUserEmail: extraDetails?.partnerUserEmail,
? ` taxRate: extraDetails?.taxRate,
<p style="text-align: center; margin: 32px 0 0 0;"> oneTimeNet: extraDetails?.oneTimeNet,
<span style="display: inline-block; background-color: #1e293b; border: 1px solid #334155; border-radius: 6px; padding: 10px 20px; color: #3b82f6; font-size: 13px; font-weight: bold; letter-spacing: 0.025em;"> monthlyNet: extraDetails?.monthlyNet,
📎 PDF im Anhang verfügbar })
</span>
</p>
`
: ''
const html = `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 32px; border: 1px solid #1e293b; border-radius: 12px; background-color: #0b0f19; color: #f8fafc;">
<div style="text-align: center; margin-bottom: 32px;">
<h1 style="color: #3b82f6; font-size: 26px; margin: 0; font-weight: 900; letter-spacing: -0.025em; text-transform: uppercase;">CASPOS</h1>
<p style="color: #64748b; font-size: 10px; margin: 2px 0 0 0; text-transform: uppercase; letter-spacing: 0.2em; font-weight: bold;">Die Kasse</p>
</div>
<div style="background-color: #111827; border: 1px solid #1e293b; border-radius: 8px; padding: 24px; margin-bottom: 24px;">
<h2 style="color: #ffffff; font-size: 18px; margin-top: 0; margin-bottom: 12px; font-weight: 700;">${title}</h2>
<p style="color: #cbd5e1; font-size: 14px; line-height: 1.6; margin-top: 0;">Hallo,</p>
<p style="color: #cbd5e1; font-size: 14px; line-height: 1.6;">${intro}</p>
<table style="width: 100%; border-collapse: collapse; font-size: 13px; color: #cbd5e1; margin-top: 20px;">
<tr>
<td style="padding: 8px 0; border-bottom: 1px solid #1e293b; color: #64748b; width: 140px; font-weight: 600; text-transform: uppercase; font-size: 11px;">Anfragenummer:</td>
<td style="padding: 8px 0; border-bottom: 1px solid #1e293b; font-family: monospace; font-weight: bold; color: #3b82f6; font-size: 14px;">#${formattedOrderNumber}</td>
</tr>
<tr>
<td style="padding: 8px 0; border-bottom: 1px solid #1e293b; color: #64748b; font-weight: 600; text-transform: uppercase; font-size: 11px;">Vorher:</td>
<td style="padding: 8px 0; border-bottom: 1px solid #1e293b; text-decoration: line-through; color: #475569;">${oldLabel}</td>
</tr>
<tr>
<td style="padding: 8px 0; border-bottom: 1px solid #1e293b; color: #64748b; font-weight: 600; text-transform: uppercase; font-size: 11px;">Aktuell:</td>
<td style="padding: 8px 0; border-bottom: 1px solid #1e293b; font-weight: bold; color: ${statusColor}; font-size: 14px;">${newLabel}</td>
</tr>
</table>
${reasonSection}
</div>
${footerActions}
<div style="text-align: center; margin-top: 32px; border-top: 1px solid #1e293b; padding-top: 20px; color: #475569; font-size: 11px; line-height: 1.5;">
<p style="margin: 0; font-weight: 600;">CASPOS Computerabrechnungssysteme GmbH · Alte Bundesstraße 16 · 76846 Hauenstein</p>
<p style="margin: 4px 0 0 0;">Dies ist eine automatisch generierte Systembenachrichtigung.</p>
</div>
</div>
`
return { text, html }
} }
export function buildEmailItemsSection(items: any[]) { export function buildEmailItemsSection(items: any[]) {
@@ -218,14 +452,14 @@ export function buildEmailItemsSection(items: any[]) {
` `
devItems.forEach((item: any) => { devItems.forEach((item: any) => {
itemsDetailsText += `\n * ${item.product_name} (${item.category_name}): ${item.base_price.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} ${item.billing_interval === 'one_time' ? 'einmalig' : 'mtl.'}` itemsDetailsText += `\n * ${item.product_name} (${item.category_name}): ${Number(item.base_price || 0).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} ${item.billing_interval === 'one_time' ? 'einmalig' : 'mtl.'}`
itemsDetailsHtml += ` itemsDetailsHtml += `
<tr> <tr>
<td style="padding: 6px 8px; font-size: 13px; color: #334155; font-weight: 500;"> <td style="padding: 6px 8px; font-size: 13px; color: #334155; font-weight: 500;">
${item.product_name} <span style="font-size: 11px; color: #64748b;">(${item.category_name})</span> ${item.product_name} <span style="font-size: 11px; color: #64748b;">(${item.category_name})</span>
</td> </td>
<td style="padding: 6px 8px; text-align: right; font-size: 13px; font-weight: bold; color: #0f172a;"> <td style="padding: 6px 8px; text-align: right; font-size: 13px; font-weight: bold; color: #0f172a;">
${item.base_price.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} ${item.billing_interval === 'one_time' ? 'einmalig' : 'mtl.'} ${Number(item.base_price || 0).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} ${item.billing_interval === 'one_time' ? 'einmalig' : 'mtl.'}
</td> </td>
</tr> </tr>
` `
@@ -233,14 +467,14 @@ export function buildEmailItemsSection(items: any[]) {
item.selected_modules?.forEach((mod: any) => { item.selected_modules?.forEach((mod: any) => {
const qty = mod.quantity || 1 const qty = mod.quantity || 1
const price = mod.total_price ?? (mod.price * qty) const price = mod.total_price ?? (mod.price * qty)
itemsDetailsText += `\n + ${mod.module_name} ${qty > 1 ? `(x${qty})` : ''}: +${price.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} mtl.` itemsDetailsText += `\n + ${mod.module_name} ${qty > 1 ? `(x${qty})` : ''}: +${Number(price || 0).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} mtl.`
itemsDetailsHtml += ` itemsDetailsHtml += `
<tr> <tr>
<td style="padding: 4px 8px 4px 20px; color: #64748b; font-size: 12px;"> <td style="padding: 4px 8px 4px 20px; color: #64748b; font-size: 12px;">
+ ${mod.module_name} ${qty > 1 ? `<span style="font-size: 10px; font-weight: 600;">(x${qty})</span>` : ''} + ${mod.module_name} ${qty > 1 ? `<span style="font-size: 10px; font-weight: 600;">(x${qty})</span>` : ''}
</td> </td>
<td style="padding: 4px 8px; text-align: right; color: #64748b; font-size: 12px;"> <td style="padding: 4px 8px; text-align: right; color: #64748b; font-size: 12px;">
+${price.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} mtl. +${Number(price || 0).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })} mtl.
</td> </td>
</tr> </tr>
` `
@@ -253,4 +487,3 @@ export function buildEmailItemsSection(items: any[]) {
html: itemsDetailsHtml html: itemsDetailsHtml
} }
} }

View File

@@ -12,7 +12,13 @@ import { buildCustomerSnapshot, buildOrderSnapshot } from '@/lib/license-transfo
import type { Category, EndCustomer, Order, Product, Profile, WizardSelections } from '@/lib/types' import type { Category, EndCustomer, Order, Product, Profile, WizardSelections } from '@/lib/types'
import { getProducts, getCategories } from '@/lib/actions/products' import { getProducts, getCategories } from '@/lib/actions/products'
import { validateWizardSelections } from '@/lib/actions/validation' import { validateWizardSelections } from '@/lib/actions/validation'
import { getOrderEmailTemplate, getStatusEmailTemplate, buildEmailItemsSection } from '@/lib/actions/email-templates' import {
generateOrderEmailHtml,
generateOrderEmailSubject,
getOrderEmailTemplate,
getStatusEmailTemplate,
buildEmailItemsSection,
} from '@/lib/actions/email-templates'
// ─── Hilfsfunktionen ───────────────────────────────────────────────────────── // ─── Hilfsfunktionen ─────────────────────────────────────────────────────────
@@ -301,24 +307,25 @@ export async function submitOrder(params: {
` `
} }
const itemsSection = buildEmailItemsSection(items) const emailTemplate = generateOrderEmailHtml({
const emailTemplate = getOrderEmailTemplate({
orderNumber, orderNumber,
status: 'pending',
formattedDate, formattedDate,
customerCompanyName: customerSnapshot.company_name, customerCompanyName: customerSnapshot.company_name,
totalDetailsText, items,
totalDetailsHtml,
itemsDetailsText: itemsSection.text,
itemsDetailsHtml: itemsSection.html,
partnerCompanyName, partnerCompanyName,
partnerUserName, partnerUserName,
partnerUserEmail partnerUserEmail,
}, `${process.env.NEXT_PUBLIC_SITE_URL || 'https://staging.hephex.de'}`, false) taxRate,
oneTimeNet,
monthlyNet,
})
const mailSubject = generateOrderEmailSubject(orderNumber, 'pending')
await sendMail({ await sendMail({
to: user.email, to: user.email,
subject: `Anfragebestätigung ${orderNumber}`, subject: mailSubject,
text: emailTemplate.text, text: emailTemplate.text,
html: emailTemplate.html, html: emailTemplate.html,
attachments: [ attachments: [
@@ -343,7 +350,7 @@ export async function submitOrder(params: {
if (adminEmail !== user.email) { if (adminEmail !== user.email) {
await sendMail({ await sendMail({
to: adminEmail, to: adminEmail,
subject: `[Admin-Kopie] Anfragebestätigung ${orderNumber}`, subject: `[Admin-Kopie] ${mailSubject}`,
text: emailTemplate.text, text: emailTemplate.text,
html: emailTemplate.html, html: emailTemplate.html,
attachments: [ attachments: [
@@ -455,24 +462,27 @@ export async function updateOrderStatus(
if (!userError && user && user.email) { if (!userError && user && user.email) {
const orderNumber = order.order_number || order.id.slice(0, 8) const orderNumber = order.order_number || order.id.slice(0, 8)
const statusLabelMap: Record<string, string> = { const customerSnapshot = updatedOrder.customer_data || {}
pending: 'Eingegangen', const orderSnapshot = updatedOrder.order_data || {}
pending_approval: 'Wartet auf Freigabe', const formattedDate = new Date(updatedOrder.created_at || Date.now()).toLocaleDateString('de-DE')
in_review: 'In Prüfung',
approved: 'Freigegeben',
active: 'Aktiviert',
completed: 'Abgeschlossen',
cancelled: 'Storniert',
rejected: 'Abgelehnt',
}
const oldLabel = statusLabelMap[oldStatus] || oldStatus
const newLabel = statusLabelMap[newStatus] || newStatus
const statusEmail = getStatusEmailTemplate(orderNumber, oldLabel, newLabel, newStatus) const statusEmail = generateOrderEmailHtml({
orderNumber,
status: newStatus,
formattedDate,
customerCompanyName: customerSnapshot.company_name || 'Endkunde',
items: orderSnapshot.items || [],
partnerCompanyName: partnerInfo.partnerCompanyName,
partnerUserName: partnerInfo.partnerUserName,
partnerUserEmail: partnerInfo.partnerUserEmail,
taxRate: orderSnapshot.tax_rate ?? 19,
})
const mailSubject = generateOrderEmailSubject(orderNumber, newStatus)
const mailOptions: any = { const mailOptions: any = {
to: user.email, to: user.email,
subject: `Statusänderung Ihrer Anfrage ${orderNumber}`, subject: mailSubject,
text: statusEmail.text, text: statusEmail.text,
html: statusEmail.html, html: statusEmail.html,
} }
@@ -504,7 +514,7 @@ export async function updateOrderStatus(
await sendMail({ await sendMail({
...mailOptions, ...mailOptions,
to: adminEmail, to: adminEmail,
subject: `[Admin-Kopie] Statusänderung Ihrer Anfrage ${orderNumber}` subject: `[Admin-Kopie] ${mailSubject}`
}) })
} }
} }
@@ -642,11 +652,29 @@ export async function rejectOrder(
const { data: { user: orderUser }, error: userError } = await admin.auth.admin.getUserById(order.user_id) const { data: { user: orderUser }, error: userError } = await admin.auth.admin.getUserById(order.user_id)
if (!userError && orderUser && orderUser.email) { if (!userError && orderUser && orderUser.email) {
const orderNumber = order.order_number || order.id.slice(0, 8) const orderNumber = order.order_number || order.id.slice(0, 8)
const statusEmail = getStatusEmailTemplate(orderNumber, 'Wartet auf Freigabe', 'Abgelehnt', 'rejected', reason) const partnerInfo = await fetchOrderPartnerInfo(admin, updatedOrder.company_id, updatedOrder.user_id)
const customerSnapshot = updatedOrder.customer_data || {}
const orderSnapshot = updatedOrder.order_data || {}
const formattedDate = new Date(updatedOrder.created_at || Date.now()).toLocaleDateString('de-DE')
const statusEmail = generateOrderEmailHtml({
orderNumber,
status: 'rejected',
formattedDate,
customerCompanyName: customerSnapshot.company_name || 'Endkunde',
rejectionReason: reason,
items: orderSnapshot.items || [],
partnerCompanyName: partnerInfo.partnerCompanyName,
partnerUserName: partnerInfo.partnerUserName,
partnerUserEmail: partnerInfo.partnerUserEmail,
taxRate: orderSnapshot.tax_rate ?? 19,
})
const mailSubject = generateOrderEmailSubject(orderNumber, 'rejected')
await sendMail({ await sendMail({
to: orderUser.email, to: orderUser.email,
subject: `Anfrage abgelehnt: ${orderNumber}`, subject: mailSubject,
text: statusEmail.text, text: statusEmail.text,
html: statusEmail.html html: statusEmail.html
}) })
@@ -664,7 +692,7 @@ export async function rejectOrder(
if (adminEmail !== orderUser.email) { if (adminEmail !== orderUser.email) {
await sendMail({ await sendMail({
to: adminEmail, to: adminEmail,
subject: `[Admin-Kopie] Anfrage abgelehnt: ${orderNumber}`, subject: `[Admin-Kopie] ${mailSubject}`,
text: statusEmail.text, text: statusEmail.text,
html: statusEmail.html html: statusEmail.html
}) })
@@ -672,7 +700,7 @@ export async function rejectOrder(
} }
} }
} catch (adminMailError) { } catch (adminMailError) {
console.error('Failed to notify admins of order rejection:', adminMailError) console.error('Failed to notify admins of rejected order:', adminMailError)
} }
} }
} catch (mailError) { } catch (mailError) {