feat(wizard): add partner filter and pagination to customer step
All checks were successful
Staging Build / build (push) Successful in 2m52s
All checks were successful
Staging Build / build (push) Successful in 2m52s
This commit is contained in:
@@ -87,7 +87,7 @@ export function OrderWizard({
|
||||
const [step, setStep] = useState(initialOrder ? 3 : 1)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [selectedCompanyId, setSelectedCompanyId] = useState<string | null>(
|
||||
initialOrder?.company_id ?? null
|
||||
initialOrder?.company_id ?? (isAdmin ? 'all' : null)
|
||||
)
|
||||
const [basketItems, setBasketItems] = useState<any[]>(() => {
|
||||
if (!initialOrder || !initialOrder.order_data?.items) return []
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import React, { useState, useMemo, useEffect } from 'react'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { User, Building2, UserPlus, Search, Check, Loader2, ChevronRight } from 'lucide-react'
|
||||
import { EndCustomer, Profile } from '@/lib/types'
|
||||
import {
|
||||
User,
|
||||
Building2,
|
||||
UserPlus,
|
||||
Search,
|
||||
Check,
|
||||
Loader2,
|
||||
ChevronRight,
|
||||
ChevronLeft,
|
||||
ChevronsLeft,
|
||||
ChevronsRight,
|
||||
} from 'lucide-react'
|
||||
import { EndCustomer } from '@/lib/types'
|
||||
|
||||
interface StepCustomerProps {
|
||||
isAdmin: boolean
|
||||
@@ -38,7 +49,6 @@ export function StepCustomer({
|
||||
endCustomers,
|
||||
searchTerm,
|
||||
setSearchTerm,
|
||||
filteredEndCustomers,
|
||||
selectedEndCustomerId,
|
||||
setSelectedEndCustomerId,
|
||||
newCustomerForm,
|
||||
@@ -47,6 +57,45 @@ export function StepCustomer({
|
||||
isCreatingCustomer,
|
||||
nextStep,
|
||||
}: StepCustomerProps) {
|
||||
const [pageSize, setPageSize] = useState<number>(10)
|
||||
const [currentPage, setCurrentPage] = useState<number>(1)
|
||||
|
||||
// Reset page to 1 when search or company filter or pageSize changes
|
||||
useEffect(() => {
|
||||
setCurrentPage(1)
|
||||
}, [searchTerm, selectedCompanyId, pageSize])
|
||||
|
||||
// Filter customers by selected company (if admin and selectedCompanyId != 'all')
|
||||
const customersByCompany = useMemo(() => {
|
||||
let list = endCustomers.filter((c) => !c.is_anonymized)
|
||||
if (isAdmin && selectedCompanyId && selectedCompanyId !== 'all') {
|
||||
list = list.filter((c) => c.partner_id === selectedCompanyId)
|
||||
}
|
||||
return list
|
||||
}, [endCustomers, isAdmin, selectedCompanyId])
|
||||
|
||||
// Search filter
|
||||
const filteredCustomers = useMemo(() => {
|
||||
const term = searchTerm.toLowerCase().trim()
|
||||
if (!term) return customersByCompany
|
||||
return customersByCompany.filter(
|
||||
(c) =>
|
||||
c.company_name?.toLowerCase().includes(term) ||
|
||||
c.first_name?.toLowerCase().includes(term) ||
|
||||
c.last_name?.toLowerCase().includes(term) ||
|
||||
c.city?.toLowerCase().includes(term) ||
|
||||
c.zip?.toLowerCase().includes(term)
|
||||
)
|
||||
}, [customersByCompany, searchTerm])
|
||||
|
||||
const totalCount = filteredCustomers.length
|
||||
const totalPages = Math.ceil(totalCount / pageSize) || 1
|
||||
|
||||
const paginatedCustomers = useMemo(() => {
|
||||
const from = (currentPage - 1) * pageSize
|
||||
return filteredCustomers.slice(from, from + pageSize)
|
||||
}, [filteredCustomers, currentPage, pageSize])
|
||||
|
||||
return (
|
||||
<Card className="glass-dark border-white/10">
|
||||
<CardHeader>
|
||||
@@ -59,20 +108,20 @@ export function StepCustomer({
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Admin Company Selector */}
|
||||
{/* Admin Partner Dropdown */}
|
||||
{isAdmin && (
|
||||
<div className="p-4 rounded-xl bg-white/5 border border-white/10 space-y-3">
|
||||
<Label htmlFor="order-company" className="text-white font-medium flex items-center gap-2">
|
||||
<Building2 className="w-4 h-4 text-primary" />
|
||||
Zugeordnetes Unternehmen (Admin-Option)
|
||||
Partner-Auswahl (Admin-Funktion)
|
||||
</Label>
|
||||
<select
|
||||
id="order-company"
|
||||
value={selectedCompanyId || ''}
|
||||
onChange={(e) => setSelectedCompanyId(e.target.value || null)}
|
||||
className="flex h-9 w-full rounded-md border border-white/10 bg-slate-900 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary text-white"
|
||||
value={selectedCompanyId || 'all'}
|
||||
onChange={(e) => setSelectedCompanyId(e.target.value)}
|
||||
className="flex h-10 w-full rounded-md border border-white/10 bg-slate-900 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary text-white"
|
||||
>
|
||||
<option value="">Keine Firma zugewiesen</option>
|
||||
<option value="all">Alle Partner (Firmenübergreifend)</option>
|
||||
{companies.map((c: any) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
@@ -105,35 +154,61 @@ export function StepCustomer({
|
||||
{/* Modus A: Bestandskunde wählen */}
|
||||
{customerMode === 'select' && (
|
||||
<div className="space-y-4">
|
||||
{endCustomers.filter(c => !c.is_anonymized).length === 0 ? (
|
||||
{customersByCompany.length === 0 ? (
|
||||
<div className="p-6 rounded-xl bg-white/5 border border-white/10 text-center space-y-3">
|
||||
<Building2 className="w-10 h-10 text-slate-600 mx-auto" />
|
||||
<p className="text-slate-400">Noch keine Endkunden angelegt.</p>
|
||||
<Button variant="outline" size="sm" onClick={() => setCustomerMode('create')} className="border-white/10 text-white">
|
||||
<p className="text-slate-400">Keine Endkunden vorhanden.</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCustomerMode('create')}
|
||||
className="border-white/10 text-white"
|
||||
>
|
||||
<UserPlus className="w-4 h-4 mr-2" /> Ersten Kunden anlegen
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="relative">
|
||||
{/* Search & Page Size Header */}
|
||||
<div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-center justify-between">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
|
||||
<Input
|
||||
placeholder="Kunden suchen nach Name, Ort, PLZ..."
|
||||
value={searchTerm}
|
||||
onChange={e => setSearchTerm(e.target.value)}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-9 bg-white/5 border-white/10 text-white placeholder:text-slate-500"
|
||||
/>
|
||||
</div>
|
||||
{filteredEndCustomers.length === 0 ? (
|
||||
|
||||
{/* Page Size Selector */}
|
||||
<div className="flex items-center gap-2 self-end sm:self-auto">
|
||||
<span className="text-xs text-slate-400 whitespace-nowrap">Einträge pro Seite:</span>
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => setPageSize(Number(e.target.value))}
|
||||
className="h-9 rounded-md border border-white/10 bg-slate-900 px-2 py-1 text-xs text-white shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
|
||||
>
|
||||
<option value={10}>10</option>
|
||||
<option value={20}>20</option>
|
||||
<option value={50}>50</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{filteredCustomers.length === 0 ? (
|
||||
<div className="p-6 rounded-xl bg-white/5 border border-white/10 text-center">
|
||||
<p className="text-slate-400">Keine passenden Kunden gefunden.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 max-h-72 overflow-y-auto pr-1">
|
||||
{filteredEndCustomers.map(customer => (
|
||||
<>
|
||||
{/* Kundenliste */}
|
||||
<div className="space-y-2 max-h-80 overflow-y-auto pr-1">
|
||||
{paginatedCustomers.map((customer) => (
|
||||
<label
|
||||
key={customer.id}
|
||||
className={`flex items-start p-4 rounded-xl border-2 cursor-pointer transition-all ${selectedEndCustomerId === customer.id
|
||||
className={`flex items-start p-4 rounded-xl border-2 cursor-pointer transition-all ${
|
||||
selectedEndCustomerId === customer.id
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-white/5 bg-white/5 hover:bg-white/10'
|
||||
}`}
|
||||
@@ -160,6 +235,61 @@ export function StepCustomer({
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Pagination Footer */}
|
||||
<div className="flex items-center justify-between border-t border-white/10 pt-3 text-xs text-slate-400 flex-wrap gap-2">
|
||||
<div>
|
||||
Zeige {(currentPage - 1) * pageSize + 1} bis{' '}
|
||||
{Math.min(currentPage * pageSize, totalCount)} von {totalCount} Kunden
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<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="h-8 px-2.5 border-white/10 text-white"
|
||||
>
|
||||
<ChevronLeft className="w-3.5 h-3.5 mr-1" /> Vorherige
|
||||
</Button>
|
||||
|
||||
<span className="px-2 font-medium text-slate-300">
|
||||
Seite {currentPage} von {totalPages}
|
||||
</span>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
|
||||
disabled={currentPage === totalPages}
|
||||
className="h-8 px-2.5 border-white/10 text-white"
|
||||
>
|
||||
Nächste <ChevronRight className="w-3.5 h-3.5 ml-1" />
|
||||
</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>
|
||||
)}
|
||||
@@ -169,7 +299,8 @@ export function StepCustomer({
|
||||
{/* Modus B: Neuen Kunden anlegen */}
|
||||
{customerMode === 'create' && (
|
||||
<div className="grid md:grid-cols-2 gap-4 p-4 rounded-xl bg-white/5 border border-white/10">
|
||||
{([
|
||||
{(
|
||||
[
|
||||
{ label: 'Firmenname *', key: 'company_name', span: true, placeholder: 'GmbH / Einzelunternehmen' },
|
||||
{ label: 'USt-IdNr.', key: 'vat_id', span: false, placeholder: 'DE123456789' },
|
||||
{ label: 'Vorname', key: 'first_name', span: false, placeholder: '' },
|
||||
@@ -181,12 +312,15 @@ export function StepCustomer({
|
||||
{ label: 'IBAN', key: 'bank_iban', span: false, placeholder: 'DE89370400440532013000' },
|
||||
{ label: 'BIC', key: 'bank_bic', span: false, placeholder: 'SOLADE21XXX' },
|
||||
{ label: 'Bankname', key: 'bank_name', span: false, placeholder: 'Musterbank' },
|
||||
] as const).map(({ label, key, span, placeholder }) => (
|
||||
] as const
|
||||
).map(({ label, key, span, placeholder }) => (
|
||||
<div key={key} className={`space-y-1.5 ${span ? 'md:col-span-2' : ''}`}>
|
||||
<Label className="text-slate-300 text-sm">{label}</Label>
|
||||
<Input
|
||||
value={newCustomerForm[key] || ''}
|
||||
onChange={e => setNewCustomerForm((prev: any) => ({ ...prev, [key]: e.target.value }))}
|
||||
onChange={(e) =>
|
||||
setNewCustomerForm((prev: any) => ({ ...prev, [key]: e.target.value }))
|
||||
}
|
||||
placeholder={placeholder}
|
||||
className="bg-white/5 border-white/10 text-white placeholder:text-slate-500"
|
||||
/>
|
||||
@@ -198,10 +332,18 @@ export function StepCustomer({
|
||||
disabled={isCreatingCustomer || !newCustomerForm.company_name?.trim()}
|
||||
className="gap-2"
|
||||
>
|
||||
{isCreatingCustomer ? <Loader2 className="w-4 h-4 animate-spin" /> : <UserPlus className="w-4 h-4" />}
|
||||
{isCreatingCustomer ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<UserPlus className="w-4 h-4" />
|
||||
)}
|
||||
Kunden speichern & auswählen
|
||||
</Button>
|
||||
<Button variant="ghost" className="text-white" onClick={() => setCustomerMode('select')}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="text-white"
|
||||
onClick={() => setCustomerMode('select')}
|
||||
>
|
||||
Abbrechen
|
||||
</Button>
|
||||
</div>
|
||||
@@ -213,7 +355,9 @@ export function StepCustomer({
|
||||
onClick={nextStep}
|
||||
disabled={
|
||||
customerMode === 'create' ||
|
||||
(customerMode === 'select' && endCustomers.filter(c => !c.is_anonymized).length > 0 && !selectedEndCustomerId)
|
||||
(customerMode === 'select' &&
|
||||
customersByCompany.length > 0 &&
|
||||
!selectedEndCustomerId)
|
||||
}
|
||||
>
|
||||
Weiter zum Abrechnungsmodell <ChevronRight className="ml-2 w-4 h-4" />
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use server'
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { createAdminClient } from '@/lib/supabase/admin'
|
||||
import type { Order, EndCustomer, EndCustomerWithOrders, OrderWithRegisterName } from '@/lib/types'
|
||||
|
||||
/**
|
||||
@@ -73,3 +74,105 @@ export async function getPartnerCustomersWithOrders(): Promise<EndCustomerWithOr
|
||||
})
|
||||
}
|
||||
|
||||
export interface GetCustomersForWizardParams {
|
||||
partnerCompanyId?: string
|
||||
page?: number
|
||||
pageSize?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export interface GetCustomersForWizardResult {
|
||||
customers: EndCustomer[]
|
||||
totalCount: number
|
||||
totalPages: number
|
||||
page: number
|
||||
pageSize: number
|
||||
isAdmin: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Server Action für den Neubestellung-Wizard:
|
||||
* Holt Endkunden rollenbasiert mit Partner-Filter (für Admins) und Pagination.
|
||||
*/
|
||||
export async function getCustomersForWizard(
|
||||
params: GetCustomersForWizardParams = {}
|
||||
): Promise<GetCustomersForWizardResult> {
|
||||
const { partnerCompanyId, page = 1, pageSize = 10, search = '' } = params
|
||||
const supabase = await createClient()
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
throw new Error('Nicht authentifiziert')
|
||||
}
|
||||
|
||||
const { data: dbUser } = await supabase
|
||||
.from('users')
|
||||
.select('role, company_id')
|
||||
.eq('id', user.id)
|
||||
.single()
|
||||
|
||||
const isAdmin = dbUser?.role === 'admin'
|
||||
|
||||
let client = supabase
|
||||
if (isAdmin) {
|
||||
try {
|
||||
client = createAdminClient() as any
|
||||
} catch {
|
||||
client = supabase
|
||||
}
|
||||
}
|
||||
|
||||
let query = client
|
||||
.from('end_customers')
|
||||
.select('*', { count: 'exact' })
|
||||
.eq('is_anonymized', false)
|
||||
|
||||
if (isAdmin) {
|
||||
if (partnerCompanyId && partnerCompanyId !== 'all' && partnerCompanyId !== '') {
|
||||
query = query.eq('partner_id', partnerCompanyId)
|
||||
}
|
||||
} else {
|
||||
if (dbUser?.company_id) {
|
||||
query = query.eq('partner_id', dbUser.company_id)
|
||||
}
|
||||
}
|
||||
|
||||
if (search && search.trim() !== '') {
|
||||
const term = `%${search.trim()}%`
|
||||
query = query.or(
|
||||
`company_name.ilike.${term},first_name.ilike.${term},last_name.ilike.${term},city.ilike.${term},zip.ilike.${term}`
|
||||
)
|
||||
}
|
||||
|
||||
query = query.order('company_name', { ascending: true })
|
||||
|
||||
const validPageSize = [10, 20, 50].includes(pageSize) ? pageSize : 10
|
||||
const validPage = Math.max(1, page)
|
||||
const from = (validPage - 1) * validPageSize
|
||||
const to = from + validPageSize - 1
|
||||
|
||||
query = query.range(from, to)
|
||||
|
||||
const { data, error, count } = await query
|
||||
|
||||
if (error) {
|
||||
throw error
|
||||
}
|
||||
|
||||
const totalCount = count ?? 0
|
||||
const totalPages = Math.ceil(totalCount / validPageSize) || 1
|
||||
|
||||
return {
|
||||
customers: (data as EndCustomer[]) || [],
|
||||
totalCount,
|
||||
totalPages,
|
||||
page: validPage,
|
||||
pageSize: validPageSize,
|
||||
isAdmin,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Migration: Rollenbasierte Endkunden-RLS für Wizard und Partner-Dashboard
|
||||
-- Stellt sicher, dass Admins alle Endkunden sehen/filtern können und Partner strikt ihre eigenen.
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.is_admin(user_id UUID)
|
||||
RETURNS BOOLEAN AS $$
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM public.users
|
||||
WHERE id = user_id AND role = 'admin'
|
||||
);
|
||||
$$ LANGUAGE sql STABLE SECURITY DEFINER;
|
||||
|
||||
-- SELECT Policy auf end_customers
|
||||
DROP POLICY IF EXISTS "Partner sehen nur eigene Endkunden" ON public.end_customers;
|
||||
CREATE POLICY "Partner sehen nur eigene Endkunden" ON public.end_customers
|
||||
FOR SELECT USING (partner_id = public.get_auth_company_id() OR public.is_admin(auth.uid()));
|
||||
|
||||
-- ALL/INSERT/UPDATE Policy auf end_customers
|
||||
DROP POLICY IF EXISTS "Partner verwalten eigene Endkunden" ON public.end_customers;
|
||||
CREATE POLICY "Partner verwalten eigene Endkunden" ON public.end_customers
|
||||
FOR ALL USING (partner_id = public.get_auth_company_id() OR public.is_admin(auth.uid()))
|
||||
WITH CHECK (partner_id = public.get_auth_company_id() OR public.is_admin(auth.uid()));
|
||||
Reference in New Issue
Block a user