feat: add admin content module pages
Local Build and Deploy / deploy (push) Successful in 47s

This commit is contained in:
Simo committed 2026-07-12 15:27:07 +02:00
1 parent f422bb4a0b
commit 2606092337
24 files changed
+2892

No files matched your search

+253
View File
@@ -0,0 +1,253 @@
'use client'
import { Pencil, Plus, Trash2 } from 'lucide-react'
import { useState } from 'react'
import { createBanner, deleteBanner, updateBanner } from '@/actions/banners'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { DateTimePicker } from '@/components/ui/date-time-picker'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { useServerAction } from '@/hooks/use-server-action'
interface Banner {
id: number
title: string
subtitle: string
image: string
link: string
color: string
isActive: number
sortOrder: number
startDate: string | null
endDate: string | null
}
interface Props {
banners: Banner[]
}
export function BannersManager({ banners }: Props) {
const { run, isPending } = useServerAction()
const [showForm, setShowForm] = useState(false)
const [editingId, setEditingId] = useState<number | null>(null)
const [form, setForm] = useState({
title: '',
subtitle: '',
image: '',
link: '',
color: '',
isActive: 1,
sortOrder: 0,
startDate: '' as string | null,
endDate: '' as string | null,
})
function resetForm() {
setForm({
title: '',
subtitle: '',
image: '',
link: '',
color: '',
isActive: 1,
sortOrder: 0,
startDate: '',
endDate: '',
})
setEditingId(null)
setShowForm(false)
}
function handleEdit(b: Banner) {
setForm({
title: b.title,
subtitle: b.subtitle,
image: b.image,
link: b.link,
color: b.color,
isActive: b.isActive,
sortOrder: b.sortOrder,
startDate: b.startDate,
endDate: b.endDate,
})
setEditingId(b.id)
setShowForm(true)
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
const data = { ...form, startDate: form.startDate || null, endDate: form.endDate || null }
if (editingId) {
run(() => updateBanner({ id: editingId, ...data }), { successMessage: 'Banner updated!' })
} else {
run(() => createBanner(data), { successMessage: 'Banner created!' })
}
resetForm()
}
return (
<div className="space-y-4">
<div className="flex justify-end">
<Button
onClick={() => {
resetForm()
setShowForm(!showForm)
}}
>
<Plus className="h-4 w-4 mr-2" /> New Banner
</Button>
</div>
{showForm && (
<Card>
<CardHeader>
<CardTitle>{editingId ? 'Edit Banner' : 'New Banner'}</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Title</Label>
<Input
value={form.title}
onChange={(e) => setForm({ ...form, title: e.target.value })}
required
/>
</div>
<div className="space-y-2">
<Label>Subtitle</Label>
<Input
value={form.subtitle}
onChange={(e) => setForm({ ...form, subtitle: e.target.value })}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Image URL</Label>
<Input
value={form.image}
onChange={(e) => setForm({ ...form, image: e.target.value })}
required
/>
</div>
<div className="space-y-2">
<Label>Link URL</Label>
<Input
value={form.link}
onChange={(e) => setForm({ ...form, link: e.target.value })}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label>Color</Label>
<Input
type="color"
value={form.color || '#000000'}
onChange={(e) => setForm({ ...form, color: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label>Start Date</Label>
<DateTimePicker
value={form.startDate}
onChange={(d) => setForm({ ...form, startDate: d ? d.toISOString() : null })}
placeholder="Select start date"
/>
</div>
<div className="space-y-2">
<Label>End Date</Label>
<DateTimePicker
value={form.endDate}
onChange={(d) => setForm({ ...form, endDate: d ? d.toISOString() : null })}
placeholder="Select end date"
/>
</div>
</div>
<div className="flex gap-6">
<div className="flex items-center gap-2">
<Switch
checked={form.isActive === 1}
onCheckedChange={(v) => setForm({ ...form, isActive: v ? 1 : 0 })}
/>
<Label>Active</Label>
</div>
<div className="space-y-2 flex items-center gap-2">
<Label>Order</Label>
<Input
type="number"
className="w-20"
value={form.sortOrder}
onChange={(e) => setForm({ ...form, sortOrder: Number(e.target.value) })}
/>
</div>
</div>
<div className="flex gap-2 justify-end">
<Button type="button" variant="outline" onClick={resetForm}>
Cancel
</Button>
<Button type="submit" disabled={isPending}>
{editingId ? 'Update' : 'Create'}
</Button>
</div>
</form>
</CardContent>
</Card>
)}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{banners.length === 0 && (
<p className="text-muted-foreground col-span-full text-center py-8">No banners yet.</p>
)}
{banners.map((b) => (
<Card key={b.id} className="overflow-hidden">
{b.image && (
<div
className="h-32 bg-cover bg-center"
style={{ backgroundImage: `url(${b.image})` }}
/>
)}
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div>
<h3 className="font-medium">{b.title}</h3>
{b.subtitle && <p className="text-xs text-muted-foreground">{b.subtitle}</p>}
<div className="flex gap-1 mt-2">
<Badge variant={b.isActive ? 'default' : 'outline'}>
{b.isActive ? 'Active' : 'Inactive'}
</Badge>
{b.startDate && <Badge variant="secondary">Scheduled</Badge>}
</div>
</div>
<div className="flex gap-1">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => handleEdit(b)}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() =>
run(() => deleteBanner({ id: b.id }), { successMessage: 'Banner deleted' })
}
>
<Trash2 className="h-3.5 w-3.5 text-destructive" />
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</div>
)
}
+25
View File
@@ -0,0 +1,25 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { BannersManager } from './banners-manager'
export default async function BannersPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.BANNERS_VIEW, session.user.rank)) {
redirect('/admin')
}
const banners = await prisma.websiteBanner.findMany({
orderBy: { sortOrder: 'asc' },
})
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Banners</h1>
<p className="text-muted-foreground">Manage homepage banners and promotional slides</p>
</div>
<BannersManager banners={banners} />
</div>
)
}
+177
View File
@@ -0,0 +1,177 @@
'use client'
import { Plus, Trash2 } from 'lucide-react'
import { useState } from 'react'
import { addEventPrize, deleteEventPrize } from '@/actions/events'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useServerAction } from '@/hooks/use-server-action'
interface Prize {
id: number
position: number
prizeType: string
badgeCode: string | null
credits: number
pixels: number
points: number
itemId: number | null
description: string
}
interface Props {
eventId: number
prizes: Prize[]
}
export function EventPrizesManager({ eventId, prizes }: Props) {
const { run, isPending } = useServerAction()
const [showForm, setShowForm] = useState(false)
const [form, setForm] = useState({
position: prizes.length + 1,
prizeType: 'badge' as string,
badgeCode: '',
credits: 0,
pixels: 0,
points: 0,
description: '',
})
function handleAdd(e: React.FormEvent) {
e.preventDefault()
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
run(() => addEventPrize({ eventId, ...form } as any), {
successMessage: 'Prize added!',
onSuccess: () => {
setShowForm(false)
setForm({ ...form, position: form.position + 1, badgeCode: '', description: '' })
},
})
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Prizes</CardTitle>
<Button size="sm" onClick={() => setShowForm(!showForm)}>
<Plus className="h-4 w-4 mr-1" /> Add Prize
</Button>
</CardHeader>
<CardContent className="space-y-4">
{showForm && (
<form onSubmit={handleAdd} className="border rounded-lg p-4 space-y-3">
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<div className="space-y-1">
<Label>Position</Label>
<Input
type="number"
value={form.position}
onChange={(e) => setForm({ ...form, position: Number(e.target.value) })}
/>
</div>
<div className="space-y-1">
<Label>Type</Label>
<Select
value={form.prizeType}
onValueChange={(v) => setForm({ ...form, prizeType: v })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="badge">Badge</SelectItem>
<SelectItem value="credits">Credits</SelectItem>
<SelectItem value="pixels">Pixels</SelectItem>
<SelectItem value="points">Points</SelectItem>
<SelectItem value="item">Item</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label>Badge Code</Label>
<Input
value={form.badgeCode}
onChange={(e) => setForm({ ...form, badgeCode: e.target.value })}
placeholder="ACH_..."
/>
</div>
<div className="space-y-1">
<Label>Credits</Label>
<Input
type="number"
value={form.credits}
onChange={(e) => setForm({ ...form, credits: Number(e.target.value) })}
/>
</div>
</div>
<div className="space-y-1">
<Label>Description</Label>
<Input
value={form.description}
onChange={(e) => setForm({ ...form, description: e.target.value })}
/>
</div>
<div className="flex gap-2 justify-end">
<Button type="button" variant="outline" size="sm" onClick={() => setShowForm(false)}>
Cancel
</Button>
<Button type="submit" size="sm" disabled={isPending}>
Add
</Button>
</div>
</form>
)}
{prizes.length === 0 && !showForm && (
<p className="text-sm text-muted-foreground text-center py-4">
No prizes configured yet.
</p>
)}
{prizes.map((prize) => (
<div
key={prize.id}
className="flex items-center justify-between border rounded-lg px-4 py-3"
>
<div className="flex items-center gap-3">
<span className="flex h-8 w-8 items-center justify-center rounded-full bg-accent font-bold text-sm">
#{prize.position}
</span>
<div>
<div className="flex items-center gap-2">
<Badge variant="secondary">{prize.prizeType}</Badge>
{prize.badgeCode && <span className="text-sm font-mono">{prize.badgeCode}</span>}
{prize.credits > 0 && <span className="text-sm">{prize.credits} credits</span>}
{prize.pixels > 0 && <span className="text-sm">{prize.pixels} pixels</span>}
{prize.points > 0 && <span className="text-sm">{prize.points} points</span>}
</div>
{prize.description && (
<p className="text-xs text-muted-foreground">{prize.description}</p>
)}
</div>
</div>
<Button
variant="ghost"
size="icon"
onClick={() =>
run(() => deleteEventPrize({ id: prize.id }), { successMessage: 'Prize removed' })
}
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
))}
</CardContent>
</Card>
)
}
@@ -0,0 +1,40 @@
'use client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
interface Registration {
id: number
userId: number
username: string
createdAt: Date
}
interface Props {
registrations: Registration[]
}
export function EventRegistrations({ registrations }: Props) {
return (
<Card>
<CardHeader>
<CardTitle>Registrations ({registrations.length})</CardTitle>
</CardHeader>
<CardContent>
{registrations.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">No registrations yet.</p>
) : (
<div className="divide-y max-h-[400px] overflow-y-auto">
{registrations.map((r) => (
<div key={r.id} className="flex items-center justify-between py-2">
<span className="text-sm font-medium">{r.username}</span>
<span className="text-xs text-muted-foreground">
{new Date(r.createdAt).toLocaleString()}
</span>
</div>
))}
</div>
)}
</CardContent>
</Card>
)
}
@@ -0,0 +1,99 @@
'use client'
import { Plus } from 'lucide-react'
import { useState } from 'react'
import { addEventWinner } from '@/actions/events'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useServerAction } from '@/hooks/use-server-action'
interface Winner {
id: number
userId: number
position: number
username: string
createdAt: Date
}
interface Props {
eventId: number
winners: Winner[]
}
export function EventWinnersManager({ eventId, winners }: Props) {
const { run, isPending } = useServerAction()
const [showForm, setShowForm] = useState(false)
const [userId, setUserId] = useState('')
const [position, setPosition] = useState(winners.length + 1)
function handleAdd(e: React.FormEvent) {
e.preventDefault()
run(() => addEventWinner({ eventId, userId: Number(userId), position }), {
successMessage: 'Winner added!',
onSuccess: () => {
setShowForm(false)
setUserId('')
setPosition(position + 1)
},
})
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Winners</CardTitle>
<Button size="sm" onClick={() => setShowForm(!showForm)}>
<Plus className="h-4 w-4 mr-1" /> Add Winner
</Button>
</CardHeader>
<CardContent className="space-y-3">
{showForm && (
<form onSubmit={handleAdd} className="border rounded-lg p-4 flex gap-3 items-end">
<div className="space-y-1">
<Label>User ID</Label>
<Input
type="number"
value={userId}
onChange={(e) => setUserId(e.target.value)}
required
placeholder="12345"
/>
</div>
<div className="space-y-1">
<Label>Position</Label>
<Input
type="number"
value={position}
onChange={(e) => setPosition(Number(e.target.value))}
min={1}
/>
</div>
<Button type="submit" size="sm" disabled={isPending}>
Add
</Button>
</form>
)}
{winners.length === 0 && !showForm && (
<p className="text-sm text-muted-foreground text-center py-4">No winners yet.</p>
)}
<div className="divide-y">
{winners.map((w) => (
<div key={w.id} className="flex items-center gap-3 py-2.5">
<span className="flex h-7 w-7 items-center justify-center rounded-full bg-primary text-primary-foreground text-xs font-bold">
{w.position}
</span>
<span className="font-medium text-sm">{w.username}</span>
<span className="text-xs text-muted-foreground ml-auto">
{new Date(w.createdAt).toLocaleDateString()}
</span>
</div>
))}
</div>
</CardContent>
</Card>
)
}
+173
View File
@@ -0,0 +1,173 @@
import { CalendarDays, Gift, Trophy, Users } from 'lucide-react'
import { notFound, redirect } from 'next/navigation'
import { AdminBreadcrumb } from '@/components/admin/admin-breadcrumb'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { EventForm } from '../event-form'
import { EventPrizesManager } from './event-prizes'
import { EventRegistrations } from './event-registrations'
import { EventWinnersManager } from './event-winners'
export default async function EventDetailPage({
params,
}: {
params: Promise<{ locale: string; id: string }>
}) {
const { id } = await params
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.EVENTS_EDIT, session.user.rank)) {
redirect('/admin/events')
}
const eventId = parseInt(id, 10)
if (Number.isNaN(eventId)) notFound()
const event = await prisma.websiteEvent.findUnique({
where: { id: eventId },
include: {
type: true,
prizes: { orderBy: { position: 'asc' } },
winners: { orderBy: { position: 'asc' } },
registrations: { orderBy: { createdAt: 'desc' } },
},
})
if (!event) notFound()
const eventTypes = await prisma.websiteEventType.findMany({
where: { isActive: 1 },
orderBy: { name: 'asc' },
})
// Fetch usernames for registrations and winners
const userIds = [
...event.registrations.map((r) => r.userId),
...event.winners.map((w) => w.userId),
]
const users =
userIds.length > 0
? await prisma.user.findMany({
where: { id: { in: [...new Set(userIds)] } },
select: { id: true, username: true },
})
: []
const userMap = new Map(users.map((u) => [u.id, u.username]))
return (
<div className="space-y-6">
<div>
<AdminBreadcrumb
items={[{ label: 'Events', href: '/admin/events' }, { label: event.title }]}
/>
<div className="flex items-center gap-3">
<h1 className="text-3xl font-bold tracking-tight">{event.title}</h1>
<Badge
variant={
event.status === 'published'
? 'default'
: event.status === 'cancelled'
? 'destructive'
: 'secondary'
}
>
{event.status}
</Badge>
</div>
<p className="text-muted-foreground">
{event.type.name} &middot; {new Date(event.startsAt).toLocaleString()}
</p>
</div>
{/* Stats */}
<div className="grid gap-4 md:grid-cols-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Registrations</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{event.registrations.length}</div>
{event.maxPlayers && (
<p className="text-xs text-muted-foreground">Max: {event.maxPlayers}</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Prizes</CardTitle>
<Gift className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{event.prizes.length}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Winners</CardTitle>
<Trophy className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{event.winners.length}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Time</CardTitle>
<CalendarDays className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-sm font-medium">
{new Date(event.startsAt) > new Date() ? 'Upcoming' : 'Past'}
</div>
{event.endsAt && (
<p className="text-xs text-muted-foreground">
Ends: {new Date(event.endsAt).toLocaleString()}
</p>
)}
</CardContent>
</Card>
</div>
{/* Edit form */}
<EventForm
eventTypes={eventTypes}
defaultValues={{
id: event.id,
title: event.title,
description: event.description,
typeId: event.typeId,
roomId: event.roomId,
startsAt: event.startsAt,
endsAt: event.endsAt,
maxPlayers: event.maxPlayers,
isRecurring: event.isRecurring,
recurrenceRule: event.recurrenceRule,
status: event.status as 'draft' | 'published' | 'cancelled' | 'completed',
image: event.image,
}}
/>
{/* Prizes */}
<EventPrizesManager eventId={event.id} prizes={event.prizes} />
{/* Winners */}
<EventWinnersManager
eventId={event.id}
winners={event.winners.map((w) => ({
...w,
username: userMap.get(w.userId) ?? `User #${w.userId}`,
}))}
/>
{/* Registrations */}
<EventRegistrations
registrations={event.registrations.map((r) => ({
...r,
username: userMap.get(r.userId) ?? `User #${r.userId}`,
}))}
/>
</div>
)
}
+27
View File
@@ -0,0 +1,27 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { EventForm } from '../event-form'
export default async function CreateEventPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.EVENTS_EDIT, session.user.rank)) {
redirect('/admin/events')
}
const eventTypes = await prisma.websiteEventType.findMany({
where: { isActive: 1 },
orderBy: { name: 'asc' },
})
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Create Event</h1>
<p className="text-muted-foreground">Schedule a new hotel event</p>
</div>
<EventForm eventTypes={eventTypes} />
</div>
)
}
+181
View File
@@ -0,0 +1,181 @@
'use client'
import { useForm } from 'react-hook-form'
import { createEvent, updateEvent } from '@/actions/events'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { DateTimePicker } from '@/components/ui/date-time-picker'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
import type { CreateEventInput } from '@/lib/validators/event'
interface EventType {
id: number
name: string
slug: string
color: string
}
interface EventFormProps {
eventTypes: EventType[]
defaultValues?: Partial<CreateEventInput> & { id?: number }
}
export function EventForm({ eventTypes, defaultValues }: EventFormProps) {
const { run, isPending } = useServerAction()
const isEditing = !!defaultValues?.id
const form = useForm({
defaultValues: {
title: '',
description: '',
typeId: eventTypes[0]?.id,
status: 'draft',
isRecurring: 0,
...defaultValues,
},
})
// biome-ignore lint/suspicious/noExplicitAny: form values typed by useForm defaults; createEvent does its own zod validation
function onSubmit(data: any) {
if (isEditing && defaultValues?.id) {
run(() => updateEvent({ id: defaultValues.id!, ...data }), {
successMessage: 'Event updated!',
})
} else {
run(() => createEvent(data), {
successMessage: 'Event created!',
onSuccess: (result) => {
const data = result.data as Record<string, unknown> | undefined
if (data?.id) {
window.location.href = `/admin/events/${data.id}`
}
},
})
}
}
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
<Card>
<CardHeader>
<CardTitle>{isEditing ? 'Edit Event' : 'Event Details'}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="title">Title</Label>
<Input id="title" {...form.register('title')} />
{form.formState.errors.title && (
<p className="text-sm text-destructive">{form.formState.errors.title.message}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="typeId">Event Type</Label>
<Select
value={String(form.watch('typeId'))}
onValueChange={(v) => form.setValue('typeId', Number(v))}
>
<SelectTrigger>
<SelectValue placeholder="Select type" />
</SelectTrigger>
<SelectContent>
{eventTypes.map((t) => (
<SelectItem key={t.id} value={String(t.id)}>
{t.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea id="description" rows={4} {...form.register('description')} />
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label>Starts At</Label>
<DateTimePicker
value={form.watch('startsAt')}
// biome-ignore lint/suspicious/noExplicitAny: form value type inferred loose; runtime validated by zod on submit
onChange={(d) => form.setValue('startsAt', d as any, { shouldDirty: true })}
placeholder="Select start date"
/>
</div>
<div className="space-y-2">
<Label>Ends At</Label>
<DateTimePicker
value={form.watch('endsAt')}
// biome-ignore lint/suspicious/noExplicitAny: form value type inferred loose; runtime validated by zod on submit
onChange={(d) => form.setValue('endsAt', d as any, { shouldDirty: true })}
placeholder="Select end date"
/>
</div>
<div className="space-y-2">
<Label htmlFor="maxPlayers">Max Players</Label>
<Input
id="maxPlayers"
type="number"
{...form.register('maxPlayers')}
placeholder="Unlimited"
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="roomId">Room ID</Label>
<Input
id="roomId"
type="number"
{...form.register('roomId')}
placeholder="Optional"
/>
</div>
<div className="space-y-2">
<Label htmlFor="status">Status</Label>
<Select
value={form.watch('status')}
onValueChange={(v) => form.setValue('status', v as CreateEventInput['status'])}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Draft</SelectItem>
<SelectItem value="published">Published</SelectItem>
<SelectItem value="cancelled">Cancelled</SelectItem>
<SelectItem value="completed">Completed</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="image">Image URL</Label>
<Input id="image" {...form.register('image')} placeholder="https://..." />
</div>
<div className="flex justify-end">
<Button type="submit" disabled={isPending}>
{isPending ? 'Saving...' : isEditing ? 'Update Event' : 'Create Event'}
</Button>
</div>
</CardContent>
</Card>
</form>
)
}
+81
View File
@@ -0,0 +1,81 @@
'use client'
import { Pencil } from 'lucide-react'
import Link from 'next/link'
import { DataTable } from '@/components/admin/data-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface EventRow {
id: number
title: string
typeName: string
typeColor: string
startsAt: Date
endsAt: Date | null
status: string
hostUserId: number
}
const statusVariants: Record<string, 'default' | 'secondary' | 'outline' | 'destructive'> = {
published: 'default',
draft: 'secondary',
cancelled: 'destructive',
completed: 'outline',
}
function getColumns(): DataTableColumn<EventRow>[] {
return [
{ key: 'id', label: 'ID', sortable: true },
{
key: 'title',
label: 'Title',
sortable: true,
render: (value) => <span className="font-medium">{String(value)}</span>,
},
{
key: 'typeName',
label: 'Type',
sortable: false,
render: (_, row) => (
<Badge style={{ backgroundColor: row.typeColor, color: '#fff' }}>{row.typeName}</Badge>
),
},
{
key: 'startsAt',
label: 'Starts',
sortable: true,
render: (value) => (
<span className="text-sm">{new Date(value as unknown as string).toLocaleString()}</span>
),
},
{
key: 'status',
label: 'Status',
sortable: true,
render: (value) => (
<Badge variant={statusVariants[String(value)] ?? 'secondary'}>{String(value)}</Badge>
),
},
{
key: 'actions',
label: 'Actions',
render: (_, row) => (
<Button variant="ghost" size="icon" asChild>
<Link href={`/admin/events/${row.id}`}>
<Pencil className="h-4 w-4" />
</Link>
</Button>
),
},
]
}
interface EventsTableProps {
data: PaginatedResult<EventRow>
}
export function EventsTable({ data }: EventsTableProps) {
return <DataTable data={data} columns={getColumns()} searchPlaceholder="Search events..." />
}
+68
View File
@@ -0,0 +1,68 @@
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { fetchAdminList } from '@/lib/admin-list'
import { PERMS } from '@/lib/permissions'
import { EventsTable } from './events-table'
export default async function EventsPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
const result = await fetchAdminList(
{
permission: PERMS.EVENTS_VIEW,
model: 'websiteEvent',
searchFields: ['title'],
defaultSort: { startsAt: 'desc' },
include: { type: { select: { name: true, color: true } } },
mapRow: (e: {
id: number
title: string
type: { name: string; color: string }
startsAt: Date
endsAt: Date | null
status: string
hostUserId: number
_count?: { registrations: number }
}) => ({
id: e.id,
title: e.title,
typeName: e.type.name,
typeColor: e.type.color,
startsAt: e.startsAt,
endsAt: e.endsAt,
status: e.status,
hostUserId: e.hostUserId,
}),
},
paramsPromise,
searchParams,
)
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Events</h1>
<p className="text-muted-foreground">Manage hotel events, calendar and prizes</p>
</div>
<Button asChild>
<Link href="/admin/events/create">New Event</Link>
</Button>
</div>
<EventsTable
data={{
rows: result.rows,
total: result.total,
page: result.page,
perPage: result.perPage,
lastPage: result.lastPage,
}}
/>
</div>
)
}
@@ -0,0 +1,201 @@
'use client'
import { Pencil, Plus, Trash2 } from 'lucide-react'
import { useState } from 'react'
import { createEventType, deleteEventType, updateEventType } from '@/actions/events'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useServerAction } from '@/hooks/use-server-action'
interface EventType {
id: number
name: string
slug: string
description: string
color: string
icon: string
isActive: number
minRank: number
}
interface Props {
eventTypes: EventType[]
}
export function EventTypesManager({ eventTypes }: Props) {
const { run, isPending } = useServerAction()
const [showForm, setShowForm] = useState(false)
const [editingId, setEditingId] = useState<number | null>(null)
const [form, setForm] = useState({
name: '',
slug: '',
description: '',
color: '#3b82f6',
icon: 'calendar',
minRank: 0,
})
function resetForm() {
setForm({ name: '', slug: '', description: '', color: '#3b82f6', icon: 'calendar', minRank: 0 })
setEditingId(null)
setShowForm(false)
}
function handleEdit(et: EventType) {
setForm({
name: et.name,
slug: et.slug,
description: et.description,
color: et.color,
icon: et.icon,
minRank: et.minRank,
})
setEditingId(et.id)
setShowForm(true)
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (editingId) {
run(() => updateEventType({ id: editingId, ...form }), {
successMessage: 'Event type updated!',
onSuccess: resetForm,
})
} else {
run(() => createEventType(form), {
successMessage: 'Event type created!',
onSuccess: resetForm,
})
}
}
function handleDelete(id: number) {
run(() => deleteEventType({ id }), {
successMessage: 'Event type deleted!',
})
}
return (
<div className="space-y-4">
<div className="flex justify-end">
<Button onClick={() => setShowForm(!showForm)}>
<Plus className="h-4 w-4 mr-2" />
New Type
</Button>
</div>
{showForm && (
<Card>
<CardHeader>
<CardTitle>{editingId ? 'Edit Event Type' : 'New Event Type'}</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label>Name</Label>
<Input
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
/>
</div>
<div className="space-y-2">
<Label>Slug</Label>
<Input
value={form.slug}
onChange={(e) => setForm({ ...form, slug: e.target.value })}
required
placeholder="game-night"
/>
</div>
<div className="space-y-2">
<Label>Color</Label>
<Input
type="color"
value={form.color}
onChange={(e) => setForm({ ...form, color: e.target.value })}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Description</Label>
<Input
value={form.description}
onChange={(e) => setForm({ ...form, description: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label>Rank minimo (0 = tutti)</Label>
<Input
type="number"
min={0}
max={7}
value={form.minRank}
onChange={(e) =>
setForm({ ...form, minRank: parseInt(e.target.value, 10) || 0 })
}
/>
<p className="text-[10px] text-muted-foreground">
0=Tutti, 3=Mod+, 4=Staff+, 6=Admin+
</p>
</div>
</div>
<div className="flex gap-2 justify-end">
<Button type="button" variant="outline" onClick={resetForm}>
Cancel
</Button>
<Button type="submit" disabled={isPending}>
{isPending ? 'Saving...' : editingId ? 'Update' : 'Create'}
</Button>
</div>
</form>
</CardContent>
</Card>
)}
<Card>
<CardContent className="p-0">
<div className="divide-y">
{eventTypes.length === 0 && (
<div className="p-6 text-center text-muted-foreground">
No event types yet. Create your first one above.
</div>
)}
{eventTypes.map((et) => (
<div key={et.id} className="flex items-center justify-between px-4 py-3">
<div className="flex items-center gap-3">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: et.color }} />
<div>
<span className="font-medium">{et.name}</span>
<span className="ml-2 text-xs text-muted-foreground">{et.slug}</span>
</div>
<Badge variant={et.isActive ? 'default' : 'outline'}>
{et.isActive ? 'Active' : 'Inactive'}
</Badge>
{et.minRank > 0 && (
<Badge variant="secondary" className="text-[10px]">
Rank {et.minRank}+
</Badge>
)}
</div>
<div className="flex gap-1">
<Button variant="ghost" size="icon" onClick={() => handleEdit(et)}>
<Pencil className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" onClick={() => handleDelete(et.id)}>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</div>
)
}
+26
View File
@@ -0,0 +1,26 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { EventTypesManager } from './event-types-manager'
export default async function EventTypesPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.EVENTS_EDIT, session.user.rank)) {
redirect('/admin/events')
}
const eventTypes = await prisma.websiteEventType.findMany({
orderBy: { name: 'asc' },
})
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Event Types</h1>
<p className="text-muted-foreground">Manage event categories and types</p>
</div>
<EventTypesManager eventTypes={eventTypes} />
</div>
)
}
+4
View File
@@ -72,6 +72,10 @@ function getNavGroups(t: (key: string) => string) {
{ href: "/admin/writeable-boxes", label: t("writeableBoxes"), icon: <SquarePen size={16} /> },
{ href: "/admin/photos", label: t("photos"), icon: <Image size={16} /> },
{ href: "/admin/tickets", label: t("tickets"), icon: <MessageSquare size={16} /> },
{ href: "/admin/events", label: "Events", icon: <Calendar size={16} /> },
{ href: "/admin/polls", label: "Polls", icon: <ClipboardList size={16} /> },
{ href: "/admin/banners", label: "Banners", icon: <Image size={16} /> },
{ href: "/admin/prefixes", label: "Prefixes", icon: <Languages size={16} /> },
],
},
{
+133
View File
@@ -0,0 +1,133 @@
import { notFound, redirect } from 'next/navigation'
import { AdminBreadcrumb } from '@/components/admin/admin-breadcrumb'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { PollForm } from '../poll-form'
import { PollQuestionsManager } from './poll-questions'
import { PollResultsView } from './poll-results'
export default async function PollDetailPage({
params,
}: {
params: Promise<{ locale: string; id: string }>
}) {
const { id } = await params
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.POLLS_EDIT, session.user.rank)) {
redirect('/admin/polls')
}
const pollId = parseInt(id, 10)
if (Number.isNaN(pollId)) notFound()
const poll = await prisma.websitePoll.findUnique({
where: { id: pollId },
include: {
questions: {
orderBy: { sortOrder: 'asc' },
include: {
votes: true,
},
},
},
})
if (!poll) notFound()
const totalVoters = new Set(poll.questions.flatMap((q) => q.votes.map((v) => v.userId))).size
return (
<div className="space-y-6">
<div>
<AdminBreadcrumb
items={[{ label: 'Polls', href: '/admin/polls' }, { label: poll.title }]}
/>
<div className="flex items-center gap-3">
<h1 className="text-3xl font-bold tracking-tight">{poll.title}</h1>
<Badge
variant={
poll.status === 'active'
? 'default'
: poll.status === 'closed'
? 'outline'
: 'secondary'
}
>
{poll.status}
</Badge>
</div>
{poll.description && <p className="text-muted-foreground">{poll.description}</p>}
</div>
{/* Stats */}
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Total Voters</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalVoters}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Questions</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{poll.questions.length}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Total Votes</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{poll.questions.reduce((sum, q) => sum + q.votes.length, 0)}
</div>
</CardContent>
</Card>
</div>
{/* Edit form */}
<PollForm
defaultValues={{
id: poll.id,
title: poll.title,
description: poll.description,
status: poll.status as 'draft' | 'active' | 'closed',
showResults: poll.showResults,
multipleChoice: poll.multipleChoice,
startsAt: poll.startsAt,
endsAt: poll.endsAt,
}}
/>
{/* Questions */}
<PollQuestionsManager
pollId={poll.id}
questions={poll.questions.map((q) => ({
id: q.id,
question: q.question,
type: q.type,
sortOrder: q.sortOrder,
options: q.options,
}))}
/>
{/* Results */}
{poll.questions.length > 0 && (
<PollResultsView
questions={poll.questions.map((q) => ({
id: q.id,
question: q.question,
options: q.options,
votes: q.votes.map((v) => v.answer),
}))}
/>
)}
</div>
)
}
+199
View File
@@ -0,0 +1,199 @@
'use client'
import { GripVertical, Pencil, Plus, Trash2 } from 'lucide-react'
import { useState } from 'react'
import { addPollQuestion, deletePollQuestion, updatePollQuestion } from '@/actions/polls'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useServerAction } from '@/hooks/use-server-action'
interface Question {
id: number
question: string
type: string
sortOrder: number
options: string
}
interface Props {
pollId: number
questions: Question[]
}
export function PollQuestionsManager({ pollId, questions }: Props) {
const { run, isPending } = useServerAction()
const [showForm, setShowForm] = useState(false)
const [editingId, setEditingId] = useState<number | null>(null)
const [form, setForm] = useState({
question: '',
type: 'single',
sortOrder: questions.length,
options: '',
})
function resetForm() {
setForm({ question: '', type: 'single', sortOrder: questions.length, options: '' })
setEditingId(null)
setShowForm(false)
}
function handleEdit(q: Question) {
setForm({ question: q.question, type: q.type, sortOrder: q.sortOrder, options: q.options })
setEditingId(q.id)
setShowForm(true)
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (editingId) {
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
run(() => updatePollQuestion({ id: editingId, ...form } as any), {
successMessage: 'Question updated!',
})
} else {
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
run(() => addPollQuestion({ pollId, ...form } as any), {
successMessage: 'Question added!',
})
}
resetForm()
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Questions ({questions.length})</CardTitle>
<Button
size="sm"
onClick={() => {
resetForm()
setShowForm(!showForm)
}}
>
<Plus className="h-4 w-4 mr-1" /> Add Question
</Button>
</CardHeader>
<CardContent className="space-y-4">
{showForm && (
<form onSubmit={handleSubmit} className="border rounded-lg p-4 space-y-3">
<div className="space-y-1">
<Label>Question</Label>
<Input
value={form.question}
onChange={(e) => setForm({ ...form, question: e.target.value })}
required
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label>Type</Label>
<Select value={form.type} onValueChange={(v) => setForm({ ...form, type: v })}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="single">Single Choice</SelectItem>
<SelectItem value="multiple">Multiple Choice</SelectItem>
<SelectItem value="text">Free Text</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label>Sort Order</Label>
<Input
type="number"
value={form.sortOrder}
onChange={(e) => setForm({ ...form, sortOrder: Number(e.target.value) })}
/>
</div>
</div>
<div className="space-y-1">
<Label>Options (one per line)</Label>
<textarea
className="w-full rounded-md border bg-transparent px-3 py-2 text-sm min-h-[80px]"
value={form.options}
onChange={(e) => setForm({ ...form, options: e.target.value })}
placeholder={'Option A\nOption B\nOption C'}
/>
</div>
<div className="flex gap-2 justify-end">
<Button type="button" variant="outline" size="sm" onClick={resetForm}>
Cancel
</Button>
<Button type="submit" size="sm" disabled={isPending}>
{editingId ? 'Update' : 'Add'}
</Button>
</div>
</form>
)}
{questions.length === 0 && !showForm && (
<p className="text-sm text-muted-foreground text-center py-4">
No questions yet. Add your first question above.
</p>
)}
<div className="space-y-2">
{questions.map((q, i) => (
<div key={q.id} className="flex items-start gap-3 border rounded-lg px-4 py-3">
<GripVertical className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="text-xs text-muted-foreground">Q{i + 1}</span>
<span className="text-xs bg-muted px-1.5 py-0.5 rounded">{q.type}</span>
</div>
<p className="text-sm font-medium">{q.question}</p>
{q.options && (
<div className="mt-1 text-xs text-muted-foreground">
{q.options
.split('\n')
.filter(Boolean)
.map((opt) => (
<span
key={opt}
className="inline-block mr-2 bg-muted px-1.5 py-0.5 rounded mb-1"
>
{opt}
</span>
))}
</div>
)}
</div>
<div className="flex gap-1 shrink-0">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => handleEdit(q)}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() =>
run(() => deletePollQuestion({ id: q.id }), {
successMessage: 'Question deleted',
})
}
>
<Trash2 className="h-3.5 w-3.5 text-destructive" />
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)
}
+74
View File
@@ -0,0 +1,74 @@
'use client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
interface QuestionResult {
id: number
question: string
options: string
votes: string[] // array of answer strings
}
interface Props {
questions: QuestionResult[]
}
export function PollResultsView({ questions }: Props) {
return (
<Card>
<CardHeader>
<CardTitle>Results</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
{questions.map((q) => {
const options = q.options.split('\n').filter(Boolean)
const totalVotes = q.votes.length
// Count votes per option
const voteCounts = new Map<string, number>()
for (const opt of options) voteCounts.set(opt, 0)
for (const vote of q.votes) {
voteCounts.set(vote, (voteCounts.get(vote) ?? 0) + 1)
}
return (
<div key={q.id}>
<h4 className="text-sm font-medium mb-3">{q.question}</h4>
{options.length > 0 ? (
<div className="space-y-2">
{options.map((opt) => {
const count = voteCounts.get(opt) ?? 0
const pct = totalVotes > 0 ? Math.round((count / totalVotes) * 100) : 0
return (
<div key={opt}>
<div className="flex justify-between text-xs mb-1">
<span>{opt}</span>
<span className="text-muted-foreground">
{count} votes ({pct}%)
</span>
</div>
<div className="h-2 w-full rounded-full bg-muted overflow-hidden">
<div
className="h-full rounded-full bg-primary transition-all"
style={{ width: `${pct}%` }}
/>
</div>
</div>
)
})}
</div>
) : (
<div className="text-sm text-muted-foreground">
{totalVotes} free-text responses
</div>
)}
<p className="text-xs text-muted-foreground mt-2">
{totalVotes} total vote{totalVotes !== 1 ? 's' : ''}
</p>
</div>
)
})}
</CardContent>
</Card>
)
}
+21
View File
@@ -0,0 +1,21 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { PollForm } from '../poll-form'
export default async function CreatePollPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.POLLS_EDIT, session.user.rank)) {
redirect('/admin/polls')
}
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Create Poll</h1>
<p className="text-muted-foreground">Create a new community poll or survey</p>
</div>
<PollForm />
</div>
)
}
+67
View File
@@ -0,0 +1,67 @@
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { fetchAdminList } from '@/lib/admin-list'
import { PERMS } from '@/lib/permissions'
import { PollsTable } from './polls-table'
export default async function PollsPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
const result = await fetchAdminList(
{
permission: PERMS.POLLS_VIEW,
model: 'websitePoll',
searchFields: ['title'],
defaultSort: { createdAt: 'desc' },
mapRow: (p: {
id: number
title: string
status: string
showResults: number
multipleChoice: number
startsAt: Date | null
endsAt: Date | null
createdAt: Date
}) => ({
id: p.id,
title: p.title,
status: p.status,
showResults: p.showResults,
multipleChoice: p.multipleChoice,
startsAt: p.startsAt,
endsAt: p.endsAt,
createdAt: p.createdAt,
}),
},
paramsPromise,
searchParams,
)
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Polls</h1>
<p className="text-muted-foreground">Manage community polls and surveys</p>
</div>
<Button asChild>
<Link href="/admin/polls/create">New Poll</Link>
</Button>
</div>
<PollsTable
data={{
rows: result.rows,
total: result.total,
page: result.page,
perPage: result.perPage,
lastPage: result.lastPage,
}}
/>
</div>
)
}
+143
View File
@@ -0,0 +1,143 @@
'use client'
import { useForm } from 'react-hook-form'
import { createPoll, updatePoll } from '@/actions/polls'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { DateTimePicker } from '@/components/ui/date-time-picker'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
import type { CreatePollInput } from '@/lib/validators/poll'
interface PollFormProps {
defaultValues?: Partial<CreatePollInput> & { id?: number }
}
export function PollForm({ defaultValues }: PollFormProps) {
const { run, isPending } = useServerAction()
const isEditing = !!defaultValues?.id
const form = useForm({
defaultValues: {
title: '',
description: '',
status: 'draft',
showResults: 1,
multipleChoice: 0,
...defaultValues,
},
})
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
function onSubmit(data: any) {
if (isEditing) {
run(() => updatePoll({ id: defaultValues!.id!, ...data }), {
successMessage: 'Poll updated!',
})
} else {
run(() => createPoll(data), {
successMessage: 'Poll created!',
onSuccess: (result) => {
const data = result.data as Record<string, unknown> | undefined
if (data?.id) {
window.location.href = `/admin/polls/${data.id}`
}
},
})
}
}
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
<Card>
<CardHeader>
<CardTitle>{isEditing ? 'Edit Poll' : 'Poll Details'}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="title">Title</Label>
<Input id="title" {...form.register('title')} />
{form.formState.errors.title && (
<p className="text-sm text-destructive">{form.formState.errors.title.message}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea id="description" rows={3} {...form.register('description')} />
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="status">Status</Label>
<Select
value={form.watch('status')}
onValueChange={(v) => form.setValue('status', v as CreatePollInput['status'])}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Draft</SelectItem>
<SelectItem value="active">Active</SelectItem>
<SelectItem value="closed">Closed</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Starts At</Label>
<DateTimePicker
value={form.watch('startsAt')}
// biome-ignore lint/suspicious/noExplicitAny: form value type inferred loose; runtime validated by zod on submit
onChange={(d) => form.setValue('startsAt', d as any, { shouldDirty: true })}
placeholder="Select start date"
/>
</div>
<div className="space-y-2">
<Label>Ends At</Label>
<DateTimePicker
value={form.watch('endsAt')}
// biome-ignore lint/suspicious/noExplicitAny: form value type inferred loose; runtime validated by zod on submit
onChange={(d) => form.setValue('endsAt', d as any, { shouldDirty: true })}
placeholder="Select end date"
/>
</div>
</div>
<div className="flex gap-6">
<div className="flex items-center gap-2">
<Switch
checked={form.watch('showResults') === 1}
onCheckedChange={(v) => form.setValue('showResults', v ? 1 : 0)}
/>
<Label>Show results to voters</Label>
</div>
<div className="flex items-center gap-2">
<Switch
checked={form.watch('multipleChoice') === 1}
onCheckedChange={(v) => form.setValue('multipleChoice', v ? 1 : 0)}
/>
<Label>Allow multiple answers</Label>
</div>
</div>
<div className="flex justify-end">
<Button type="submit" disabled={isPending}>
{isPending ? 'Saving...' : isEditing ? 'Update Poll' : 'Create Poll'}
</Button>
</div>
</CardContent>
</Card>
</form>
)
}
+79
View File
@@ -0,0 +1,79 @@
'use client'
import { Pencil } from 'lucide-react'
import Link from 'next/link'
import { DataTable } from '@/components/admin/data-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface PollRow {
id: number
title: string
status: string
showResults: number
multipleChoice: number
startsAt: Date | null
endsAt: Date | null
createdAt: Date
}
const statusVariants: Record<string, 'default' | 'secondary' | 'outline'> = {
active: 'default',
draft: 'secondary',
closed: 'outline',
}
function getColumns(): DataTableColumn<PollRow>[] {
return [
{ key: 'id', label: 'ID', sortable: true },
{
key: 'title',
label: 'Title',
sortable: true,
render: (value) => <span className="font-medium">{String(value)}</span>,
},
{
key: 'status',
label: 'Status',
sortable: true,
render: (value) => (
<Badge variant={statusVariants[String(value)] ?? 'secondary'}>{String(value)}</Badge>
),
},
{
key: 'multipleChoice',
label: 'Type',
render: (value) => (
<span className="text-sm">{Number(value) ? 'Multiple choice' : 'Single choice'}</span>
),
},
{
key: 'createdAt',
label: 'Created',
sortable: true,
render: (value) => (
<span className="text-sm">{new Date(value as unknown as string).toLocaleDateString()}</span>
),
},
{
key: 'actions',
label: 'Actions',
render: (_, row) => (
<Button variant="ghost" size="icon" asChild>
<Link href={`/admin/polls/${row.id}`}>
<Pencil className="h-4 w-4" />
</Link>
</Button>
),
},
]
}
interface PollsTableProps {
data: PaginatedResult<PollRow>
}
export function PollsTable({ data }: PollsTableProps) {
return <DataTable data={data} columns={getColumns()} searchPlaceholder="Search polls..." />
}
+28
View File
@@ -0,0 +1,28 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function PrefixesLoading() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-9 w-40" />
<Skeleton className="h-5 w-64 mt-2" />
</div>
</div>
<div className="flex items-center gap-3">
<Skeleton className="h-10 w-64" />
<Skeleton className="h-10 w-24" />
</div>
<div className="rounded-md border">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex items-center gap-6 px-4 py-3 border-b last:border-0">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
))}
</div>
</div>
)
}
+25
View File
@@ -0,0 +1,25 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { PrefixesClient } from './prefixes-client'
export default async function PrefixesPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.PREFIXES_VIEW, session.user.rank)) {
redirect('/admin')
}
const canEdit = canAccess(permissions, PERMS.PREFIXES_EDIT, session.user.rank)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Custom Prefixes</h1>
<p className="text-muted-foreground">
Gestisci i prefissi degli utenti, la blacklist e le impostazioni
</p>
</div>
<PrefixesClient canEdit={canEdit} />
</div>
)
}
+728
View File
@@ -0,0 +1,728 @@
'use client'
import { Pencil, Plus, Save, Search, Trash2, X } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import {
addBlacklistWord as addBlacklistWordAction,
createPrefix,
deletePrefix as deletePrefixAction,
removeBlacklistWord as removeBlacklistWordAction,
updatePrefix,
updatePrefixSettings,
} from '@/actions/prefixes'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useServerAction } from '@/hooks/use-server-action'
interface UserPrefix {
id: number
user_id: number
text: string
color: string
icon: string
effect: string
active: boolean
created_at: string
username?: string
}
interface BlacklistWord {
id: number
word: string
created_at: string
}
interface PrefixSettings {
max_length: string
min_rank_to_buy: string
price_credits: string
price_points: string
points_type: string
}
interface PrefixFormData {
username: string
text: string
color: string
icon: string
effect: string
active: boolean
}
const PRESET_EFFECTS = [
{ id: '', label: 'Nessuno' },
{ id: 'glow', label: '✨ Bagliore' },
{ id: 'shadow', label: '🌑 Ombra' },
{ id: 'italic', label: '𝑰 Corsivo' },
{ id: 'outline', label: '🔲 Contorno' },
{ id: 'pulse', label: '💫 Pulsante' },
{ id: 'bold-glow', label: '💡 Neon' },
]
const PRESET_ICONS = [
{ emoji: '', label: 'Nessuna' },
{ emoji: '👑', label: 'Corona' },
{ emoji: '⭐', label: 'Stella' },
{ emoji: '❤️', label: 'Cuore' },
{ emoji: '💎', label: 'Diamante' },
{ emoji: '🔥', label: 'Fuoco' },
{ emoji: '⚡', label: 'Fulmine' },
{ emoji: '🛡️', label: 'Scudo' },
{ emoji: '💀', label: 'Teschio' },
{ emoji: '🎵', label: 'Musica' },
{ emoji: '💠', label: 'Gemma' },
{ emoji: '⚔️', label: 'Spade' },
{ emoji: '🏆', label: 'Trofeo' },
{ emoji: '🚀', label: 'Razzo' },
{ emoji: '👻', label: 'Fantasma' },
{ emoji: '🐾', label: 'Zampa' },
{ emoji: '🍃', label: 'Foglia' },
{ emoji: '😎', label: 'Cool' },
{ emoji: '🐺', label: 'Lupo' },
{ emoji: '🦁', label: 'Leone' },
{ emoji: '🐉', label: 'Drago' },
{ emoji: '🦄', label: 'Unicorno' },
{ emoji: '🌙', label: 'Luna' },
{ emoji: '☀️', label: 'Sole' },
{ emoji: '❄️', label: 'Neve' },
{ emoji: '🌹', label: 'Rosa' },
{ emoji: '🎮', label: 'Controller' },
{ emoji: '💰', label: 'Soldi' },
{ emoji: '🔮', label: 'Sfera' },
{ emoji: '🏴‍☠️', label: 'Pirata' },
]
function PrefixDialog({
isOpen,
onClose,
onSave,
editPrefix,
}: {
isOpen: boolean
onClose: () => void
onSave: (data: PrefixFormData, editId?: number) => Promise<void>
editPrefix: UserPrefix | null
}) {
const [form, setForm] = useState<PrefixFormData>({
username: '',
text: '',
color: '#FFFFFF',
icon: '',
effect: '',
active: false,
})
const [saving, setSaving] = useState(false)
// biome-ignore lint/correctness/useExhaustiveDependencies: explicitly chosen here, see surrounding code
useEffect(() => {
if (editPrefix) {
setForm({
username: editPrefix.username || '',
text: editPrefix.text,
color: editPrefix.color,
icon: editPrefix.icon || '',
effect: editPrefix.effect || '',
active: editPrefix.active,
})
} else {
setForm({ username: '', text: '', color: '#FFFFFF', icon: '', effect: '', active: false })
}
}, [editPrefix, isOpen])
if (!isOpen) return null
const handleSave = async () => {
setSaving(true)
try {
await onSave(form, editPrefix?.id)
onClose()
} finally {
setSaving(false)
}
}
// Parse multi-color for preview
const colors = form.color.split(',')
const hasMultiColor = colors.length > 1 && new Set(colors).size > 1
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div className="bg-background rounded-lg shadow-lg w-full max-w-md p-6 space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">
{editPrefix ? 'Modifica Prefisso' : 'Aggiungi Prefisso'}
</h3>
<button
type="button"
onClick={onClose}
className="text-muted-foreground hover:text-foreground"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Preview */}
<div className="flex items-center justify-center p-3 rounded-lg bg-muted min-h-[40px]">
<span className="text-lg font-bold">
{form.icon && <span className="mr-0.5">{form.icon}</span>}
{hasMultiColor ? (
<span>
{'{'}
{[...(form.text || '...')].map((char, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: char position drives color slot
<span key={i} style={{ color: colors[Math.min(i, colors.length - 1)] }}>
{char}
</span>
))}
{'}'}
</span>
) : (
<span style={{ color: colors[0] || '#FFFFFF' }}>
{'{'}
{form.text || '...'}
{'}'}
</span>
)}
</span>
<span className="ml-2 text-lg text-muted-foreground">{form.username || 'Username'}</span>
</div>
{!editPrefix && (
<div className="space-y-2">
<span className="text-sm font-medium">Username</span>
<Input
placeholder="Nome utente..."
value={form.username}
onChange={(e) => setForm({ ...form, username: e.target.value })}
/>
</div>
)}
<div className="space-y-2">
<span className="text-sm font-medium">Testo</span>
<Input
maxLength={15}
placeholder="Testo del prefix..."
value={form.text}
onChange={(e) => setForm({ ...form, text: e.target.value })}
/>
<span className="text-xs text-muted-foreground">{form.text.length}/15</span>
</div>
<div className="space-y-2">
<span className="text-sm font-medium">Colore (HEX o multi: #FF0000,#00FF00)</span>
<div className="flex items-center gap-2">
<Input
placeholder="#FFFFFF o #FF0000,#00FF00,..."
value={form.color}
onChange={(e) => setForm({ ...form, color: e.target.value })}
/>
<div
className="w-8 h-8 rounded border shrink-0"
style={{ backgroundColor: colors[0] || '#FFFFFF' }}
/>
</div>
</div>
<div className="space-y-2">
<span className="text-sm font-medium">Icona</span>
<select
className="w-full px-3 py-2 rounded border bg-background text-sm"
value={form.icon}
onChange={(e) => setForm({ ...form, icon: e.target.value })}
>
{PRESET_ICONS.map((icon) => (
<option key={icon.label} value={icon.emoji}>
{icon.emoji ? `${icon.emoji} ${icon.label}` : icon.label}
</option>
))}
</select>
</div>
<div className="space-y-2">
<span className="text-sm font-medium">Effetto</span>
<select
className="w-full px-3 py-2 rounded border bg-background text-sm"
value={form.effect}
onChange={(e) => setForm({ ...form, effect: e.target.value })}
>
{PRESET_EFFECTS.map((fx) => (
<option key={fx.id} value={fx.id}>
{fx.label}
</option>
))}
</select>
</div>
<div className="flex items-center gap-2">
<input
checked={form.active}
id="prefix-active"
type="checkbox"
onChange={(e) => setForm({ ...form, active: e.target.checked })}
/>
<label className="text-sm" htmlFor="prefix-active">
Attivo
</label>
</div>
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" onClick={onClose}>
Annulla
</Button>
<Button
disabled={saving || !form.text.trim() || (!editPrefix && !form.username.trim())}
onClick={handleSave}
>
<Save className="h-4 w-4 mr-1" />
{saving ? 'Salvando...' : 'Salva'}
</Button>
</div>
</div>
</div>
)
}
export function PrefixesClient({ canEdit }: { canEdit: boolean }) {
const { run, isPending } = useServerAction()
const [prefixes, setPrefixes] = useState<UserPrefix[]>([])
const [searchQuery, setSearchQuery] = useState('')
const [page, setPage] = useState(1)
const [totalPages, setTotalPages] = useState(1)
const [blacklist, setBlacklist] = useState<BlacklistWord[]>([])
const [newWord, setNewWord] = useState('')
const [settings, setSettings] = useState<PrefixSettings>({
max_length: '15',
min_rank_to_buy: '1',
price_credits: '5',
price_points: '0',
points_type: '0',
})
const [dialogOpen, setDialogOpen] = useState(false)
const [editPrefix, setEditPrefix] = useState<UserPrefix | null>(null)
const fetchPrefixes = useCallback(async () => {
const params = new URLSearchParams({ page: String(page) })
if (searchQuery) params.set('q', searchQuery)
const res = await fetch(`/api/admin/prefixes?${params}`)
const data = await res.json()
if (data.ok) {
setPrefixes(data.prefixes)
setTotalPages(data.pages)
}
}, [page, searchQuery])
const fetchBlacklist = useCallback(async () => {
const res = await fetch('/api/admin/prefixes/blacklist')
const data = await res.json()
if (data.ok) setBlacklist(data.words)
}, [])
const fetchSettings = useCallback(async () => {
const res = await fetch('/api/admin/prefixes/settings')
const data = await res.json()
if (data.ok) setSettings(data.settings)
}, [])
useEffect(() => {
fetchPrefixes()
}, [fetchPrefixes])
useEffect(() => {
fetchBlacklist()
fetchSettings()
}, [fetchBlacklist, fetchSettings])
const handleDeletePrefix = async (id: number) => {
if (!confirm('Sei sicuro di voler eliminare questo prefisso?')) return
run(() => deletePrefixAction({ id }), {
successMessage: 'Prefisso eliminato!',
onSuccess: () => {
fetchPrefixes()
},
})
}
const handleSavePrefix = async (data: PrefixFormData, editId?: number) => {
if (editId) {
run(
() =>
updatePrefix({
id: editId,
text: data.text,
color: data.color,
icon: data.icon,
effect: data.effect,
active: data.active ? 1 : 0,
}),
{
successMessage: 'Prefisso aggiornato!',
onSuccess: () => {
fetchPrefixes()
},
},
)
} else {
run(
() =>
createPrefix({
username: data.username,
text: data.text,
color: data.color,
icon: data.icon,
effect: data.effect,
active: data.active ? 1 : 0,
}),
{
successMessage: 'Prefisso creato!',
onSuccess: () => {
fetchPrefixes()
},
},
)
}
}
const openAddDialog = () => {
setEditPrefix(null)
setDialogOpen(true)
}
const openEditDialog = (prefix: UserPrefix) => {
setEditPrefix(prefix)
setDialogOpen(true)
}
const handleAddBlacklistWord = async () => {
if (!newWord.trim()) return
run(() => addBlacklistWordAction({ word: newWord.trim() }), {
successMessage: 'Parola aggiunta alla blacklist!',
onSuccess: () => {
setNewWord('')
fetchBlacklist()
},
})
}
const handleRemoveBlacklistWord = async (id: number) => {
run(() => removeBlacklistWordAction({ id }), {
successMessage: 'Parola rimossa dalla blacklist!',
onSuccess: () => {
fetchBlacklist()
},
})
}
const saveSettings = async () => {
run(() => updatePrefixSettings({ settings: settings as unknown as Record<string, string> }), {
successMessage: 'Impostazioni salvate!',
})
}
return (
<>
<PrefixDialog
editPrefix={editPrefix}
isOpen={dialogOpen}
onClose={() => setDialogOpen(false)}
onSave={handleSavePrefix}
/>
<Tabs defaultValue="prefixes">
<TabsList>
<TabsTrigger value="prefixes">Prefissi Utenti</TabsTrigger>
<TabsTrigger value="blacklist">Blacklist</TabsTrigger>
<TabsTrigger value="settings">Impostazioni</TabsTrigger>
</TabsList>
<TabsContent value="prefixes" className="space-y-4">
<div className="flex items-center gap-2">
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
className="pl-8"
placeholder="Cerca per utente o testo..."
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value)
setPage(1)
}}
/>
</div>
<Button variant="outline" onClick={fetchPrefixes}>
Cerca
</Button>
{canEdit && (
<Button onClick={openAddDialog}>
<Plus className="h-4 w-4 mr-1" />
Aggiungi
</Button>
)}
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Utente</TableHead>
<TableHead>Prefix</TableHead>
<TableHead>Colore</TableHead>
<TableHead>Icona</TableHead>
<TableHead>Effetto</TableHead>
<TableHead>Attivo</TableHead>
<TableHead>Data</TableHead>
{canEdit && <TableHead>Azioni</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{prefixes.map((prefix) => {
const colors = prefix.color.split(',')
const hasMultiColor = colors.length > 1 && new Set(colors).size > 1
const prefixIcon = prefix.icon || ''
return (
<TableRow key={prefix.id}>
<TableCell>{prefix.id}</TableCell>
<TableCell>{prefix.username || `#${prefix.user_id}`}</TableCell>
<TableCell>
<span style={{ fontWeight: 'bold' }}>
{hasMultiColor ? (
<>
{'{'}
{[...prefix.text].map((char, i) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: char position drives color slot
key={i}
style={{
color: colors[Math.min(i, colors.length - 1)],
}}
>
{char}
</span>
))}
{'}'}
</>
) : (
<span style={{ color: colors[0] || '#FFFFFF' }}>
{'{'}
{prefix.text}
{'}'}
</span>
)}
</span>
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
{colors.slice(0, 5).map((c, i) => (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: color preview slots, position is identity
key={i}
className="w-4 h-4 rounded border"
style={{ backgroundColor: c }}
title={c}
/>
))}
{colors.length > 5 && (
<span className="text-xs text-muted-foreground">
+{colors.length - 5}
</span>
)}
</div>
</TableCell>
<TableCell className="text-center text-lg">{prefixIcon || '-'}</TableCell>
<TableCell className="text-xs">
{prefix.effect
? PRESET_EFFECTS.find((fx) => fx.id === prefix.effect)?.label ||
prefix.effect
: '-'}
</TableCell>
<TableCell>{prefix.active ? 'Si' : 'No'}</TableCell>
<TableCell className="text-xs">
{new Date(prefix.created_at).toLocaleDateString()}
</TableCell>
{canEdit && (
<TableCell>
<div className="flex items-center gap-1">
<Button
size="icon"
variant="outline"
onClick={() => openEditDialog(prefix)}
>
<Pencil className="h-4 w-4" />
</Button>
<Button
size="icon"
variant="destructive"
disabled={isPending}
onClick={() => handleDeletePrefix(prefix.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
)}
</TableRow>
)
})}
{prefixes.length === 0 && (
<TableRow>
<TableCell className="text-center text-muted-foreground" colSpan={9}>
Nessun prefisso trovato
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2">
<Button
disabled={page <= 1}
size="sm"
variant="outline"
onClick={() => setPage(page - 1)}
>
Precedente
</Button>
<span className="text-sm">
Pagina {page} di {totalPages}
</span>
<Button
disabled={page >= totalPages}
size="sm"
variant="outline"
onClick={() => setPage(page + 1)}
>
Successiva
</Button>
</div>
)}
</TabsContent>
<TabsContent value="blacklist" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Parole Vietate</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{canEdit && (
<div className="flex items-center gap-2">
<Input
placeholder="Aggiungi parola..."
value={newWord}
onChange={(e) => setNewWord(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleAddBlacklistWord()}
/>
<Button disabled={isPending} onClick={handleAddBlacklistWord}>
<Plus className="h-4 w-4 mr-1" />
Aggiungi
</Button>
</div>
)}
<div className="flex flex-wrap gap-2">
{blacklist.map((word) => (
<div
key={word.id}
className="flex items-center gap-1 px-3 py-1 rounded-full bg-destructive/10 text-destructive text-sm"
>
<span>{word.word}</span>
{canEdit && (
<button
type="button"
className="ml-1 hover:text-destructive/80"
onClick={() => handleRemoveBlacklistWord(word.id)}
>
&times;
</button>
)}
</div>
))}
{blacklist.length === 0 && (
<p className="text-muted-foreground text-sm">Nessuna parola in blacklist</p>
)}
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="settings" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Impostazioni Prefissi</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<span className="text-sm font-medium">Lunghezza Massima</span>
<Input
disabled={!canEdit}
type="number"
value={settings.max_length}
onChange={(e) => setSettings({ ...settings, max_length: e.target.value })}
/>
</div>
<div className="space-y-2">
<span className="text-sm font-medium">Rank Minimo</span>
<Input
disabled={!canEdit}
type="number"
value={settings.min_rank_to_buy}
onChange={(e) => setSettings({ ...settings, min_rank_to_buy: e.target.value })}
/>
</div>
<div className="space-y-2">
<span className="text-sm font-medium">Prezzo (Crediti)</span>
<Input
disabled={!canEdit}
type="number"
value={settings.price_credits}
onChange={(e) => setSettings({ ...settings, price_credits: e.target.value })}
/>
</div>
<div className="space-y-2">
<span className="text-sm font-medium">Prezzo (Punti)</span>
<Input
disabled={!canEdit}
type="number"
value={settings.price_points}
onChange={(e) => setSettings({ ...settings, price_points: e.target.value })}
/>
</div>
<div className="space-y-2">
<span className="text-sm font-medium">Tipo Punti</span>
<Input
disabled={!canEdit}
type="number"
value={settings.points_type}
onChange={(e) => setSettings({ ...settings, points_type: e.target.value })}
/>
<p className="text-xs text-muted-foreground">0 = Duckets, 5 = Diamonds, ecc.</p>
</div>
</div>
{canEdit && (
<Button disabled={isPending} onClick={saveSettings}>
<Save className="h-4 w-4 mr-1" />
Salva Impostazioni
</Button>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</>
)
}
+40
View File
@@ -0,0 +1,40 @@
"use client";
import { cn } from "@/lib/utils";
interface DateTimePickerProps {
value?: Date | string | null;
onChange: (date: Date | null) => void;
placeholder?: string;
disabled?: boolean;
className?: string;
showTime?: boolean;
}
function inputValue(value: Date | string | null | undefined, showTime: boolean): string {
if (!value) return "";
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) return "";
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
return local.toISOString().slice(0, showTime ? 16 : 10);
}
export function DateTimePicker({
value,
onChange,
placeholder,
disabled = false,
className,
showTime = true,
}: DateTimePickerProps) {
return (
<input
aria-label={placeholder ?? (showTime ? "Date and time" : "Date")}
className={cn("w-full", className)}
disabled={disabled}
type={showTime ? "datetime-local" : "date"}
value={inputValue(value, showTime)}
onChange={(event) => onChange(event.target.value ? new Date(event.target.value) : null)}
/>
);
}