feat(wizard): add partner filter and pagination to customer step
All checks were successful
Staging Build / build (push) Successful in 2m52s

This commit is contained in:
DanielS
2026-07-21 10:43:21 +02:00
parent 8b4fd5f02e
commit 07208fcad0
4 changed files with 338 additions and 70 deletions

View File

@@ -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,
}
}