feat: add company management and user-company assignment in admin panel
All checks were successful
Staging Build / build (push) Successful in 2m35s
All checks were successful
Staging Build / build (push) Successful in 2m35s
This commit is contained in:
186
shop/app/admin/companies/page.tsx
Normal file
186
shop/app/admin/companies/page.tsx
Normal file
@@ -0,0 +1,186 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Building2, Plus, Trash2, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { getCompanies, createCompany, deleteCompany } from '@/lib/actions/companies'
|
||||
|
||||
export default function CompaniesPage() {
|
||||
const [companies, setCompanies] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [isCreateOpen, setIsCreateOpen] = useState(false)
|
||||
const [name, setName] = useState('')
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [createError, setCreateError] = useState<string | null>(null)
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null)
|
||||
|
||||
const loadCompanies = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await getCompanies()
|
||||
setCompanies(data)
|
||||
} catch (err) {
|
||||
console.error('Fehler beim Laden der Firmen:', err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadCompanies()
|
||||
}, [])
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setCreating(true)
|
||||
setCreateError(null)
|
||||
try {
|
||||
await createCompany(name)
|
||||
setIsCreateOpen(false)
|
||||
setName('')
|
||||
loadCompanies()
|
||||
} catch (err: any) {
|
||||
setCreateError(err.message || 'Fehler beim Anlegen.')
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: string, firmName: string) => {
|
||||
if (!confirm(`Firma "${firmName}" wirklich löschen? Alle zugewiesenen Partner werden getrennt.`)) return
|
||||
setDeletingId(id)
|
||||
try {
|
||||
await deleteCompany(id)
|
||||
loadCompanies()
|
||||
} catch (err) {
|
||||
console.error('Fehler beim Löschen:', err)
|
||||
} finally {
|
||||
setDeletingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-4xl mx-auto text-slate-900 dark:text-white space-y-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-extrabold tracking-tight flex items-center gap-3">
|
||||
<Building2 className="w-8 h-8 text-blue-500" />
|
||||
Firmenverwaltung
|
||||
</h1>
|
||||
<p className="text-slate-500 dark:text-slate-400 text-sm mt-1">
|
||||
Verwalten Sie Firmen und weisen Sie Partner zu.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => setIsCreateOpen(true)}
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white font-semibold"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-2" /> Firma anlegen
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Firmen-Tabelle */}
|
||||
<div className="p-5 bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-white/10 shadow-sm">
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center py-16">
|
||||
<Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
|
||||
<span className="ml-3 text-slate-400 text-sm">Lade Firmen...</span>
|
||||
</div>
|
||||
) : companies.length === 0 ? (
|
||||
<div className="text-center py-16 border-2 border-dashed border-slate-200 dark:border-white/5 rounded-xl text-slate-500">
|
||||
<Building2 className="w-10 h-10 mx-auto mb-3 opacity-30" />
|
||||
Noch keine Firmen angelegt.
|
||||
</div>
|
||||
) : (
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 dark:border-white/10 text-slate-400 text-xs font-semibold uppercase">
|
||||
<th className="pb-3">Firmenname</th>
|
||||
<th className="pb-3">Erstellt am</th>
|
||||
<th className="pb-3 text-right">Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100 dark:divide-white/5">
|
||||
{companies.map((company) => (
|
||||
<tr key={company.id} className="hover:bg-slate-50 dark:hover:bg-white/3 transition-colors">
|
||||
<td className="py-4 font-semibold text-slate-900 dark:text-white">
|
||||
<div className="flex items-center gap-2">
|
||||
<Building2 className="w-4 h-4 text-blue-500 shrink-0" />
|
||||
{company.name}
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-4 text-sm text-slate-500 dark:text-slate-400">
|
||||
{company.created_at ? new Date(company.created_at).toLocaleDateString('de-DE') : '–'}
|
||||
</td>
|
||||
<td className="py-4 text-right">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={deletingId === company.id}
|
||||
onClick={() => handleDelete(company.id, company.name)}
|
||||
className="h-8 w-8 text-red-500 hover:text-red-400 hover:bg-red-500/10"
|
||||
title="Firma löschen"
|
||||
>
|
||||
{deletingId === company.id
|
||||
? <Loader2 className="h-4 w-4 animate-spin" />
|
||||
: <Trash2 className="h-4 w-4" />}
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Dialog: Neue Firma */}
|
||||
<Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
|
||||
<DialogContent className="bg-white dark:bg-slate-950 border-slate-200 dark:border-white/10 text-slate-900 dark:text-white shadow-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Neue Firma anlegen</DialogTitle>
|
||||
<DialogDescription className="text-slate-500 dark:text-slate-400">
|
||||
Geben Sie den Namen der Firma ein. Partner können danach zugewiesen werden.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleCreate} className="space-y-4 mt-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="company-name">Firmenname</Label>
|
||||
<Input
|
||||
id="company-name"
|
||||
type="text"
|
||||
required
|
||||
placeholder="Muster GmbH"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="bg-slate-50 dark:bg-white/5 border-slate-200 dark:border-white/10"
|
||||
/>
|
||||
</div>
|
||||
{createError && (
|
||||
<p className="text-sm text-red-600 dark:text-red-400">{createError}</p>
|
||||
)}
|
||||
<DialogFooter className="pt-2">
|
||||
<Button type="button" variant="outline" onClick={() => setIsCreateOpen(false)} disabled={creating}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={creating} className="bg-blue-600 hover:bg-blue-700 text-white font-semibold">
|
||||
{creating ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
|
||||
Anlegen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -169,6 +169,7 @@ export default function AdminSettings() {
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 dark:border-white/10 text-slate-400 text-xs font-semibold uppercase">
|
||||
<th className="pb-3">Partner E-Mail</th>
|
||||
<th className="pb-3">Firma</th>
|
||||
<th className="pb-3">Status</th>
|
||||
<th className="pb-3">Erstellt am</th>
|
||||
<th className="pb-3 text-right">Aktionen</th>
|
||||
@@ -186,6 +187,9 @@ export default function AdminSettings() {
|
||||
{partner.email}
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-4 text-sm text-slate-700 dark:text-slate-300">
|
||||
{partner.company_name || '–'}
|
||||
</td>
|
||||
<td className="py-4">
|
||||
{isGesperrt ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-700 dark:bg-red-500/10 dark:text-red-400 border border-red-200 dark:border-red-500/20">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Link from 'next/link'
|
||||
import { LayoutDashboard, Package, Settings, Users, LayoutGrid, ShoppingCart, Wrench, Database } from 'lucide-react'
|
||||
import { LayoutDashboard, Package, Settings, Users, LayoutGrid, ShoppingCart, Wrench, Database, Building2 } from 'lucide-react'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { AdminLogoutButton } from '@/components/admin/logout-menu-item'
|
||||
@@ -58,6 +58,10 @@ export default async function AdminLayout({
|
||||
<Users className="w-5 h-5" />
|
||||
Benutzer
|
||||
</Link>
|
||||
<Link href="/admin/companies" className="flex items-center gap-3 px-3 py-2 rounded-lg text-slate-400 hover:text-white hover:bg-white/5 transition-all">
|
||||
<Building2 className="w-5 h-5" />
|
||||
Firmen
|
||||
</Link>
|
||||
|
||||
<div className="pt-2 pb-1 px-3">
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-slate-600">Einstellungen</span>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getUsers } from '@/lib/actions/users'
|
||||
import { getCompanies } from '@/lib/actions/companies'
|
||||
import { UserList } from '@/components/admin/user-list'
|
||||
import { UserDialog } from '@/components/admin/user-dialog'
|
||||
import { Users } from 'lucide-react'
|
||||
@@ -32,8 +33,8 @@ export default async function AdminUsersPage() {
|
||||
|
||||
async function UserDataWrapper() {
|
||||
try {
|
||||
const users = await getUsers()
|
||||
return <UserList initialUsers={users} />
|
||||
const [users, companies] = await Promise.all([getUsers(), getCompanies()])
|
||||
return <UserList initialUsers={users} companies={companies} />
|
||||
} catch (error: any) {
|
||||
console.error('[UserDataWrapper] Error loading users:', error)
|
||||
return (
|
||||
|
||||
@@ -11,9 +11,10 @@ import {
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Key, Trash2, Mail, Loader2 } from 'lucide-react'
|
||||
import { Key, Trash2, Mail, Loader2, Building2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { deleteUser, resetPassword, updateUserRole } from '@/lib/actions/users'
|
||||
import { assignCompanyToUser } from '@/lib/actions/companies'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
|
||||
type Role = 'admin' | 'partner' | 'gesperrt'
|
||||
@@ -30,7 +31,12 @@ const ROLE_BADGE_CLASSES: Record<Role, string> = {
|
||||
gesperrt: 'bg-red-500/20 text-red-400 border border-red-500/30',
|
||||
}
|
||||
|
||||
export function UserList({ initialUsers }: { initialUsers: any[] }) {
|
||||
interface UserListProps {
|
||||
initialUsers: any[]
|
||||
companies: { id: string; name: string }[]
|
||||
}
|
||||
|
||||
export function UserList({ initialUsers, companies }: UserListProps) {
|
||||
const router = useRouter()
|
||||
const [loadingId, setLoadingId] = useState<string | null>(null)
|
||||
|
||||
@@ -55,6 +61,18 @@ export function UserList({ initialUsers }: { initialUsers: any[] }) {
|
||||
}
|
||||
}
|
||||
|
||||
const handleCompanyChange = async (userId: string, companyId: string) => {
|
||||
setLoadingId(userId + '-company')
|
||||
try {
|
||||
await assignCompanyToUser(userId, companyId === '' ? null : companyId)
|
||||
router.refresh()
|
||||
} catch (e) {
|
||||
console.error('Fehler beim Zuweisen der Firma:', e)
|
||||
} finally {
|
||||
setLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleResetPassword = async (email: string) => {
|
||||
try {
|
||||
await resetPassword(email)
|
||||
@@ -69,7 +87,7 @@ export function UserList({ initialUsers }: { initialUsers: any[] }) {
|
||||
<CardHeader>
|
||||
<CardTitle>Benutzerverwaltung</CardTitle>
|
||||
<CardDescription className="text-slate-400">
|
||||
Verwalten Sie Rollen, Passwörter und Benutzerkonten.
|
||||
Rollen, Firmenzuweisungen, Passwörter und Benutzerkonten verwalten.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -78,6 +96,7 @@ export function UserList({ initialUsers }: { initialUsers: any[] }) {
|
||||
<TableRow className="border-white/10 hover:bg-white/5">
|
||||
<TableHead className="text-slate-200">E-Mail</TableHead>
|
||||
<TableHead className="text-slate-200">Rolle</TableHead>
|
||||
<TableHead className="text-slate-200">Firma</TableHead>
|
||||
<TableHead className="text-slate-200">Zuletzt angemeldet</TableHead>
|
||||
<TableHead className="text-right text-slate-200">Aktionen</TableHead>
|
||||
</TableRow>
|
||||
@@ -86,6 +105,7 @@ export function UserList({ initialUsers }: { initialUsers: any[] }) {
|
||||
{initialUsers.map((user) => {
|
||||
const role: Role = (['admin', 'partner', 'gesperrt'].includes(user.role) ? user.role : 'partner') as Role
|
||||
const isLoadingRole = loadingId === user.id + '-role'
|
||||
const isLoadingCompany = loadingId === user.id + '-company'
|
||||
const isLoadingDelete = loadingId === user.id
|
||||
|
||||
return (
|
||||
@@ -116,6 +136,25 @@ export function UserList({ initialUsers }: { initialUsers: any[] }) {
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<Building2 className="w-4 h-4 text-slate-500 shrink-0" />
|
||||
{isLoadingCompany ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-slate-400" />
|
||||
) : (
|
||||
<select
|
||||
value={user.company_id || ''}
|
||||
onChange={(e) => handleCompanyChange(user.id, e.target.value)}
|
||||
className="text-xs bg-white/5 border border-white/10 rounded px-2 py-1 text-slate-300 hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/50 max-w-[150px]"
|
||||
>
|
||||
<option value="">Keine Firma</option>
|
||||
{companies.map((c) => (
|
||||
<option key={c.id} value={c.id}>{c.name}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-slate-400 text-sm">
|
||||
{user.last_sign_in_at ? new Date(user.last_sign_in_at).toLocaleString('de-DE') : 'Noch nie'}
|
||||
</TableCell>
|
||||
|
||||
49
shop/lib/actions/companies.ts
Normal file
49
shop/lib/actions/companies.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
'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('id, name, created_at')
|
||||
.order('name', { ascending: true })
|
||||
if (error) throw error
|
||||
return data || []
|
||||
}
|
||||
|
||||
export async function createCompany(name: string) {
|
||||
const admin = createAdminClient()
|
||||
const { data, error } = await admin
|
||||
.from('companies')
|
||||
.insert({ name: name.trim() })
|
||||
.select()
|
||||
.single()
|
||||
if (error) throw error
|
||||
revalidatePath('/admin/companies')
|
||||
revalidatePath('/admin/users')
|
||||
return data
|
||||
}
|
||||
|
||||
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')
|
||||
revalidatePath('/admin/users')
|
||||
}
|
||||
|
||||
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')
|
||||
revalidatePath('/admin/einstellungen')
|
||||
}
|
||||
@@ -10,18 +10,24 @@ export async function getUsers() {
|
||||
|
||||
const { data: dbUsers, error: dbError } = await admin
|
||||
.from('users')
|
||||
.select('id, role')
|
||||
.select('id, role, company_id, companies(id, name)')
|
||||
|
||||
const roleMap: Record<string, string> = {}
|
||||
const userMap: Record<string, { role: string; company_id: string | null; company_name: string | null }> = {}
|
||||
if (!dbError && dbUsers) {
|
||||
dbUsers.forEach(u => {
|
||||
roleMap[u.id] = u.role
|
||||
dbUsers.forEach((u: any) => {
|
||||
userMap[u.id] = {
|
||||
role: u.role,
|
||||
company_id: u.company_id || null,
|
||||
company_name: u.companies?.name || null,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return users.map(u => ({
|
||||
...u,
|
||||
role: roleMap[u.id] || 'partner'
|
||||
role: userMap[u.id]?.role || 'partner',
|
||||
company_id: userMap[u.id]?.company_id || null,
|
||||
company_name: userMap[u.id]?.company_name || null,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -90,15 +96,26 @@ export async function getPartners() {
|
||||
|
||||
const { data: dbUsers, error: dbError } = await admin
|
||||
.from('users')
|
||||
.select('id, role')
|
||||
.select('id, role, company_id, companies(id, name)')
|
||||
.in('role', ['partner', 'gesperrt'])
|
||||
if (dbError) throw dbError
|
||||
|
||||
const roleMap: Record<string, string> = {}
|
||||
dbUsers.forEach(u => { roleMap[u.id] = u.role })
|
||||
const userMap: Record<string, { role: string; company_id: string | null; company_name: string | null }> = {}
|
||||
dbUsers.forEach((u: any) => {
|
||||
userMap[u.id] = {
|
||||
role: u.role,
|
||||
company_id: u.company_id || null,
|
||||
company_name: u.companies?.name || null,
|
||||
}
|
||||
})
|
||||
|
||||
const partnerIds = new Set(dbUsers.map(u => u.id))
|
||||
return users
|
||||
.filter(u => partnerIds.has(u.id))
|
||||
.map(u => ({ ...u, role: roleMap[u.id] || 'partner' }))
|
||||
.map(u => ({
|
||||
...u,
|
||||
role: userMap[u.id]?.role || 'partner',
|
||||
company_id: userMap[u.id]?.company_id || null,
|
||||
company_name: userMap[u.id]?.company_name || null,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Migration: companies table + company_id in users
|
||||
|
||||
-- 1. Tabelle companies erstellen
|
||||
CREATE TABLE IF NOT EXISTS public.companies (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- RLS aktivieren
|
||||
ALTER TABLE public.companies ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Policies
|
||||
DROP POLICY IF EXISTS "Admins und Partner lesen Firmen" ON public.companies;
|
||||
DROP POLICY IF EXISTS "Service role kann alles" ON public.companies;
|
||||
|
||||
CREATE POLICY "Admins und Partner lesen Firmen"
|
||||
ON public.companies FOR SELECT
|
||||
USING (auth.role() = 'authenticated');
|
||||
|
||||
CREATE POLICY "Service role kann alles"
|
||||
ON public.companies FOR ALL
|
||||
USING (true)
|
||||
WITH CHECK (true);
|
||||
|
||||
-- 2. company_id zu public.users hinzufügen
|
||||
ALTER TABLE public.users
|
||||
ADD COLUMN IF NOT EXISTS company_id UUID REFERENCES public.companies(id) ON DELETE SET NULL;
|
||||
|
||||
-- Reload Schema Cache
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
Reference in New Issue
Block a user