Files
webshop/shop/lib/actions/companies.ts
DanielS ef9422908d
All checks were successful
Staging Build / build (push) Successful in 2m36s
feat: list end customers in companies admin and improve dark/light mode contrast across all admin components
2026-06-25 02:11:07 +02:00

79 lines
2.4 KiB
TypeScript

'use server'
import { createAdminClient } from '@/lib/supabase/admin'
import { revalidatePath } from 'next/cache'
export async function getCompanies() {
const admin = createAdminClient()
const { data, error } = await admin.from('companies').select('*')
if (error) throw error
return data
}
export async function createCompany(data: { name: string; street?: string; zip?: string; city?: string; email?: string }) {
const admin = createAdminClient()
const { data: dbData, error } = await admin.from('companies').insert({
name: data.name,
street: data.street || null,
zip: data.zip || null,
city: data.city || null,
email: data.email || null,
}).select().single()
if (error) throw error
revalidatePath('/admin/companies')
return dbData
}
export async function updateCompany(id: string, data: { name: string; street?: string; zip?: string; city?: string; email?: string }) {
const admin = createAdminClient()
const { data: dbData, error } = await admin.from('companies').update({
name: data.name,
street: data.street || null,
zip: data.zip || null,
city: data.city || null,
email: data.email || null,
}).eq('id', id).select().single()
if (error) throw error
revalidatePath('/admin/companies')
return dbData
}
export async function deleteCompany(id: string) {
const admin = createAdminClient()
const { error } = await admin.from('companies').delete().eq('id', id)
if (error) throw error
revalidatePath('/admin/companies')
return true
}
export async function assignCompanyToUser(userId: string, companyId: string | null) {
const admin = createAdminClient()
const { error } = await admin.from('users').update({ company_id: companyId }).eq('id', userId)
if (error) throw error
revalidatePath('/admin/users')
return true
}
export async function getEndCustomersByCompany(companyId: string) {
const admin = createAdminClient()
// 1. Get all partners of this company
const { data: partners, error: partnersError } = await admin
.from('users')
.select('id')
.eq('company_id', companyId)
if (partnersError) throw partnersError
if (!partners || partners.length === 0) return []
const partnerIds = partners.map((p) => p.id)
// 2. Get all end customers belonging to these partners
const { data: customers, error: customersError } = await admin
.from('end_customers')
.select('*')
.in('partner_id', partnerIds)
if (customersError) throw customersError
return customers || []
}