Reapply "Add missing admin action files and navigation links"

This reverts commit 4d515bc400.
This commit is contained in:
Simo committed 2026-07-11 20:52:56 +02:00
1 parent 96ed768f14
commit 5b4228261a
338 files changed
+28143 -5948

No files matched your search

+6 -2
View File
@@ -53,7 +53,9 @@ export default async function AdminAchievements() {
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle", { rows: achievements.length, categories: groups.size })}</p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
{t("subtitle", { rows: achievements.length, categories: groups.size })}
</p>
</div>
</div>
@@ -70,7 +72,9 @@ export default async function AdminAchievements() {
<section key={category} className="mt-6">
<h2 className="admin-section-title">
{category}{" "}
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{rows.length}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{rows.length}
</span>
</h2>
<div className="admin-card p-0 overflow-x-auto">
<table>
+4 -6
View File
@@ -6,11 +6,7 @@ import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
export default async function EditAd({
params,
}: {
params: Promise<{ id: string }>;
}) {
export default async function EditAd({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
let ad: Awaited<ReturnType<typeof prisma.websiteAds.findUnique>> = null;
try {
@@ -28,7 +24,9 @@ export default async function EditAd({
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">Edit advertisement</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/ads">← Advertisements</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/ads">← Advertisements</Link>
</p>
</div>
</div>
<form action={updateAd} className="admin-card">
+3 -1
View File
@@ -11,7 +11,9 @@ export default function NewAd() {
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">New advertisement</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/ads">← Advertisements</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/ads">← Advertisements</Link>
</p>
</div>
</div>
<form action={createAd} className="admin-card">
+1 -3
View File
@@ -18,9 +18,7 @@ export default async function AdminAds() {
ads = [];
}
const latest = ads[0]?.createdAt
? ads[0].createdAt.toISOString().slice(0, 10)
: "—";
const latest = ads[0]?.createdAt ? ads[0].createdAt.toISOString().slice(0, 10) : "—";
return (
<main>
+2 -12
View File
@@ -84,24 +84,14 @@ export default async function AdminAlerts() {
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("alertsShown")} value={alerts.length} icon="🔔" />
<StatusCard
label={t("critical")}
value={critical}
state={critical > 0 ? "danger" : "ok"}
icon="🚨"
/>
<StatusCard label={t("critical")} value={critical} state={critical > 0 ? "danger" : "ok"} icon="🚨" />
<StatusCard
label={t("warnings")}
value={warnings}
state={warnings > 0 ? "warn" : "neutral"}
icon="⚠️"
/>
<StatusCard
label={t("unread")}
value={unread}
state={unread > 0 ? "warn" : "ok"}
icon="📨"
/>
<StatusCard label={t("unread")} value={unread} state={unread > 0 ? "warn" : "ok"} icon="📨" />
</div>
<form action={sendHotelAlert} className="admin-card mb-6">
+3 -1
View File
@@ -85,7 +85,9 @@ export default async function AdminApplications() {
<>{t("userNumber", { id: a.userId })}</>
)}
</h3>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{t("rankLabel", { rank: a.rankId })}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{t("rankLabel", { rank: a.rankId })}
</span>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0 mb-2">
{formatDate(a.createdAt)}
+13 -11
View File
@@ -18,10 +18,12 @@ export default async function EditArticle({
const { id } = await params;
const { error } = await searchParams;
const t = await getTranslations("pages.admin.articles");
const article = await prisma.websiteArticles.findUnique({
where: { id: BigInt(id) },
select: { id: true, slug: true, title: true, shortStory: true, fullStory: true, image: true },
}).catch(() => null);
const article = await prisma.websiteArticles
.findUnique({
where: { id: BigInt(id) },
select: { id: true, slug: true, title: true, shortStory: true, fullStory: true, image: true },
})
.catch(() => null);
if (!article) notFound();
return (
@@ -32,14 +34,12 @@ export default async function EditArticle({
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("form.title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/articles">← {t("title")}</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/articles">← {t("title")}</Link>
</p>
</div>
</div>
{error ? (
<p className="text-xs text-red-600 dark:text-red-400 mb-4">
Error: {error}
</p>
) : null}
{error ? <p className="text-xs text-red-600 dark:text-red-400 mb-4">Error: {error}</p> : null}
<ArticleForm
action={async (fd) => {
"use server";
@@ -55,7 +55,9 @@ export default async function EditArticle({
/>
<form action={deleteArticle} style={{ marginTop: "1rem" }}>
<input type="hidden" name="id" value={String(article.id)} />
<button type="submit" className="btn btn-primary">{t("form.deleteArticle")}</button>
<button type="submit" className="btn btn-primary">
{t("form.deleteArticle")}
</button>
</form>
</main>
);
+5 -11
View File
@@ -4,11 +4,7 @@ import { Newspaper } from "lucide-react";
import { createArticle } from "@/actions/admin-articles";
import { ArticleForm } from "@/components/admin/article-form";
export default async function NewArticle({
searchParams,
}: {
searchParams: Promise<{ error?: string }>;
}) {
export default async function NewArticle({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const { error } = await searchParams;
const t = await getTranslations("pages.admin.articles");
@@ -20,14 +16,12 @@ export default async function NewArticle({
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("form.title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/articles">← {t("title")}</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/articles">← {t("title")}</Link>
</p>
</div>
</div>
{error ? (
<p className="text-xs text-red-600 dark:text-red-400 mb-4">
Error: {error}
</p>
) : null}
{error ? <p className="text-xs text-red-600 dark:text-red-400 mb-4">Error: {error}</p> : null}
<ArticleForm action={createArticle} />
</main>
);
+6 -21
View File
@@ -7,11 +7,7 @@ import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
export default async function AdminArticles({
searchParams,
}: {
searchParams: Promise<{ error?: string }>;
}) {
export default async function AdminArticles({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const { error } = await searchParams;
const t = await getTranslations("pages.admin.articles");
const articles = await prisma.websiteArticles
@@ -22,9 +18,7 @@ export default async function AdminArticles({
})
.catch(() => []);
const latest = articles[0]?.createdAt
? articles[0].createdAt.toISOString().slice(0, 10)
: "—";
const latest = articles[0]?.createdAt ? articles[0].createdAt.toISOString().slice(0, 10) : "—";
return (
<main>
@@ -41,11 +35,7 @@ export default async function AdminArticles({
</Link>
</div>
{error ? (
<p className="text-xs text-red-600 dark:text-red-400 mb-4">
Error: {error}
</p>
) : null}
{error ? <p className="text-xs text-red-600 dark:text-red-400 mb-4">Error: {error}</p> : null}
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("articlesShown")} value={articles.length} icon="📰" />
@@ -70,9 +60,7 @@ export default async function AdminArticles({
{articles.map((a) => (
<tr key={String(a.id)}>
<td>
<Link href={`/admin/articles/${a.id}`}>
{a.title}
</Link>
<Link href={`/admin/articles/${a.id}`}>{a.title}</Link>
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
<code>{a.slug}</code>
@@ -87,10 +75,7 @@ export default async function AdminArticles({
</Link>
<form action={deleteArticle} className="m-0">
<input type="hidden" name="id" value={String(a.id)} />
<button
type="submit"
className="btn btn-danger"
>
<button type="submit" className="btn btn-danger">
{t("delete")}
</button>
</form>
@@ -104,4 +89,4 @@ export default async function AdminArticles({
</section>
</main>
);
}
}
+5 -8
View File
@@ -51,9 +51,7 @@ export default async function AdminBadges({
<section className="mt-6">
<h2 className="admin-section-title">{t("uploadTitle")}</h2>
<p className="text-xs text-[var(--color-text-muted)] -mt-2 mb-3">
{t("uploadSubtitle")}
</p>
<p className="text-xs text-[var(--color-text-muted)] -mt-2 mb-3">{t("uploadSubtitle")}</p>
<form action={uploadBadge} className="admin-card">
<div className="flex gap-2 flex-wrap items-center">
<input type="file" name="file" accept=".gif,.png" required />
@@ -100,7 +98,9 @@ export default async function AdminBadges({
</section>
<section className="mt-6">
<h2 className="admin-section-title">{t("catalogueTitle")} ({badges.length})</h2>
<h2 className="admin-section-title">
{t("catalogueTitle")} ({badges.length})
</h2>
{badges.length === 0 ? (
<div className="admin-empty">{t("noBadges")}</div>
) : (
@@ -123,10 +123,7 @@ export default async function AdminBadges({
<td>{b.badgeName}</td>
<td className="text-sm text-gray-500 dark:text-gray-400">{b.badgeDescription}</td>
<td>
<form
action={giveBadge}
className="flex gap-2 items-center"
>
<form action={giveBadge} className="flex gap-2 items-center">
<input type="hidden" name="code" value={b.badgeKey} />
<input
name="userId"
+9 -3
View File
@@ -75,7 +75,9 @@ export default async function AdminBans() {
</form>
<section className="mt-6">
<h2 className="admin-section-title">{t("activeBans")} ({bans.length})</h2>
<h2 className="admin-section-title">
{t("activeBans")} ({bans.length})
</h2>
{bans.length === 0 ? (
<div className="admin-empty">{t("noBans")}</div>
) : (
@@ -95,12 +97,16 @@ export default async function AdminBans() {
<tr key={b.id}>
<td>{b.userId}</td>
<td>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{b.type}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{b.type}
</span>
</td>
<td>{b.banReason || "—"}</td>
<td>
{b.banExpire === 0 ? (
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-red-500/22 text-[var(--color-text)]">{t("permanent")}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-red-500/22 text-[var(--color-text)]">
{t("permanent")}
</span>
) : (
<span className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{fromUnix(b.banExpire)}
+31 -19
View File
@@ -35,11 +35,7 @@ function fmtDate(ts: number): string {
return new Date(ts * 1000).toISOString().slice(0, 10);
}
export default async function AdminCalendarCampaign({
params,
}: {
params: Promise<{ id: string }>;
}) {
export default async function AdminCalendarCampaign({ params }: { params: Promise<{ id: string }> }) {
const t = await getTranslations("pages.admin.calendar");
const { id } = await params;
@@ -101,16 +97,16 @@ export default async function AdminCalendarCampaign({
<div className="admin-card flex items-center gap-5 mb-6">
{campaign.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img
className="w-24 h-24 object-cover"
src={campaign.image}
alt={campaign.name}
/>
<img className="w-24 h-24 object-cover" src={campaign.image} alt={campaign.name} />
) : null}
<div>
<h1 className="m-0 mb-1">{campaign.name || `#${campaign.id}`}</h1>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">
{t("detail.campaignMeta", { id: campaign.id, days: campaign.totalDays, date: fmtDate(campaign.startTimestamp) })}
{t("detail.campaignMeta", {
id: campaign.id,
days: campaign.totalDays,
date: fmtDate(campaign.startTimestamp),
})}
{disabled ? ` · ${t("detail.disabled")}` : ` · ${t("detail.enabled")}`}
{campaign.lockExpired === "1" ? ` · ${t("detail.locksExpired")}` : ""}
</p>
@@ -138,10 +134,26 @@ export default async function AdminCalendarCampaign({
{rewards.map((r) => (
<tr key={r.id} className="border-t border-[var(--border-subtle)]">
<td>{r.id}</td>
<td>{r.productName || <span className="text-sm text-gray-500 dark:text-gray-400">—</span>}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{r.itemId > 0 ? r.itemId : "—"}</td>
<td>{r.credits > 0 ? r.credits : <span className="text-sm text-gray-500 dark:text-gray-400">—</span>}</td>
<td>{r.pixels > 0 ? r.pixels : <span className="text-sm text-gray-500 dark:text-gray-400">—</span>}</td>
<td>
{r.productName || <span className="text-sm text-gray-500 dark:text-gray-400">—</span>}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{r.itemId > 0 ? r.itemId : "—"}
</td>
<td>
{r.credits > 0 ? (
r.credits
) : (
<span className="text-sm text-gray-500 dark:text-gray-400">—</span>
)}
</td>
<td>
{r.pixels > 0 ? (
r.pixels
) : (
<span className="text-sm text-gray-500 dark:text-gray-400">—</span>
)}
</td>
<td>
{r.points > 0 ? (
`${r.points} (${t("detail.typeLabel", { type: r.pointsType })})`
@@ -149,11 +161,11 @@ export default async function AdminCalendarCampaign({
<span className="text-sm text-gray-500 dark:text-gray-400">—</span>
)}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{r.badge || "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{r.subscriptionType
? `${r.subscriptionType} · ${r.subscriptionDays}d`
: "—"}
{r.badge || "—"}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{r.subscriptionType ? `${r.subscriptionType} · ${r.subscriptionDays}d` : "—"}
</td>
</tr>
))}
+8 -9
View File
@@ -52,8 +52,7 @@ export default async function AdminCalendar() {
for (const r of rewards) {
rewardCounts.set(r.campaignId, (rewardCounts.get(r.campaignId) ?? 0) + 1);
}
} catch {
}
} catch {}
const enabledCount = campaigns.filter((c) => c.enabled === "1").length;
@@ -65,7 +64,9 @@ export default async function AdminCalendar() {
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle", { count: campaigns.length })}</p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
{t("subtitle", { count: campaigns.length })}
</p>
</div>
</div>
@@ -88,11 +89,7 @@ export default async function AdminCalendar() {
const enabled = c.enabled === "1";
const count = rewardCounts.get(c.id) ?? 0;
return (
<Link
key={c.id}
href={`/admin/calendar/${c.id}`}
className="admin-card hover article"
>
<Link key={c.id} href={`/admin/calendar/${c.id}`} className="admin-card hover article">
{c.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img className="article-img" src={c.image} alt={c.name} />
@@ -102,7 +99,9 @@ export default async function AdminCalendar() {
<div className="body">
<div className="flex items-center justify-between gap-2 mb-1">
<h3 className="m-0">{c.name || `#${c.id}`}</h3>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${enabled ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${enabled ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}
>
{enabled ? t("statusEnabled") : t("statusDisabled")}
</span>
</div>
@@ -0,0 +1,126 @@
'use client'
import { Languages, Package, Settings } from 'lucide-react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import type { CatalogItemData } from './catalog-items-table'
import { CatalogItemsTable } from './catalog-items-table'
import { CatalogPageForm } from './catalog-page-form'
import { CatalogTranslateTab } from './catalog-translate-tab'
interface CatalogPageData {
id: number
caption: string
parentId: number
pageLayout: string
enabled: string
visible: string
minRank: number
clubOnly: string
orderNum: number
iconImage: number
iconColor: number
pageHeadline: string
pageTeaser: string
pageSpecial: string | null
pageText1: string | null
pageText2: string | null
pageTextDetails: string | null
pageTextTeaser: string | null
}
interface BaseItemData {
id: number
publicName: string
itemName: string
spriteId: number
type: string
}
interface CatalogDetailTabsProps {
catalogPage: CatalogPageData
items: CatalogItemData[]
baseItems: BaseItemData[]
catalogNameMap: Record<number, string>
childPages: { id: number; caption: string; enabled: string }[]
pageId: number
canEdit: boolean
furniDataIdList: number[]
furniDescriptionMap: Record<number, string>
furniRevisionMap: Record<number, { classname: string; revision: number }>
allPages: { id: number; caption: string }[]
interactionTypes: string[]
}
export function CatalogDetailTabs({
catalogPage,
items,
baseItems,
catalogNameMap,
childPages,
pageId,
canEdit,
furniDataIdList,
furniDescriptionMap,
furniRevisionMap,
allPages,
interactionTypes,
}: CatalogDetailTabsProps) {
return (
<Tabs defaultValue="settings">
<TabsList>
<TabsTrigger value="settings" className="gap-2">
<Settings className="h-4 w-4" />
Settings
</TabsTrigger>
<TabsTrigger value="items" className="gap-2">
<Package className="h-4 w-4" />
Items ({items.length})
</TabsTrigger>
<TabsTrigger value="translate" className="gap-2">
<Languages className="h-4 w-4" />
Translate ({baseItems.length}){(() => {
const furniSet = new Set(furniDataIdList)
const missing = baseItems.filter((b) => !furniSet.has(b.id)).length
return missing > 0 ? (
<span className="ml-1 rounded-full bg-orange-500 text-white text-[10px] px-1.5 py-0.5 leading-none font-medium">
{missing}
</span>
) : null
})()}
</TabsTrigger>
</TabsList>
<TabsContent value="settings" className="mt-4">
<CatalogPageForm
catalogPage={catalogPage}
childPages={childPages}
canEdit={canEdit}
allPages={allPages}
/>
</TabsContent>
<TabsContent value="items" className="mt-4">
<CatalogItemsTable
items={items}
pageId={pageId}
pageLayout={catalogPage.pageLayout}
canEdit={canEdit}
interactionTypes={interactionTypes}
furniRevisionMap={furniRevisionMap}
allPages={allPages}
/>
</TabsContent>
<TabsContent value="translate" className="mt-4">
<CatalogTranslateTab
baseItems={baseItems}
catalogNameMap={catalogNameMap}
canEdit={canEdit}
furniDataIdList={furniDataIdList}
furniDescriptionMap={furniDescriptionMap}
furniRevisionMap={furniRevisionMap}
/>
</TabsContent>
</Tabs>
)
}
@@ -0,0 +1,7 @@
/**
* Re-export barrel for backward compatibility.
* Implementation moved to ./catalog-items-table/ directory.
*/
export { CatalogItemsTable } from './catalog-items-table/catalog-items-table'
export { FurniIcon } from './catalog-items-table/furni-icon'
export type { BaseItemData, CatalogItemData } from './catalog-items-table/types'
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,250 @@
'use client'
import { Check, ChevronsUpDown, Star } from 'lucide-react'
import { useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Switch } from '@/components/ui/switch'
import { cn } from '@/lib/utils'
// ── Toggle field ──────────────────────────────────────────────
export function ToggleField({
label,
checked,
value,
onChange,
disabled,
}: {
label: string
/** Boolean checked state */
checked?: boolean
/** Number or string (0/1 or '0'/'1') — converted to boolean automatically */
value?: number | string
onChange: (v: boolean) => void
disabled?: boolean
}) {
const isChecked = checked ?? (value === 1 || value === '1')
return (
<div className="flex items-center justify-between gap-2">
<Label className="text-xs">{label}</Label>
<Switch checked={isChecked} onCheckedChange={onChange} disabled={disabled} size="sm" />
</div>
)
}
// ── Interaction Type Combobox ──────────────────────────────────
export function InteractionTypeCombobox({
value,
onChange,
types,
disabled,
}: {
value: string
onChange: (v: string) => void
types: string[]
disabled?: boolean
}) {
const [open, setOpen] = useState(false)
const [inputValue, setInputValue] = useState('')
const filtered = useMemo(() => {
if (!inputValue.trim()) return types.slice(0, 50)
const q = inputValue.toLowerCase()
return types.filter((t) => t.toLowerCase().includes(q)).slice(0, 50)
}, [types, inputValue])
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
disabled={disabled}
className="w-full justify-between font-normal h-8 text-sm"
>
<span className="truncate">{value || 'Select type...'}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
<Command shouldFilter={false}>
<CommandInput
placeholder="Search or type custom..."
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
<CommandEmpty>
{inputValue.trim() ? (
<button
type="button"
className="w-full px-2 py-1.5 text-left text-sm hover:bg-accent rounded"
onClick={() => {
onChange(inputValue.trim())
setOpen(false)
setInputValue('')
}}
>
Use &quot;{inputValue.trim()}&quot;
</button>
) : (
'No types found.'
)}
</CommandEmpty>
<CommandGroup>
{filtered.map((t) => (
<CommandItem
key={t}
value={t}
onSelect={() => {
onChange(t)
setOpen(false)
setInputValue('')
}}
>
<Check
className={cn('mr-2 h-4 w-4', value === t ? 'opacity-100' : 'opacity-0')}
/>
<span className="truncate">{t}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
// ── Move Page Combobox with smart suggestions ─────────────────
export function MovePageCombobox({
value,
onChange,
pages,
currentPageId,
suggestedPageIds,
}: {
value: number | null
onChange: (id: number | null) => void
pages: { id: number; caption: string }[]
currentPageId: number
/** Page IDs to show first as suggestions (from move-suggestions.ts) */
suggestedPageIds?: number[]
}) {
const [open, setOpen] = useState(false)
const options = useMemo(() => pages.filter((p) => p.id !== currentPageId), [pages, currentPageId])
const selectedPage = value ? pages.find((p) => p.id === value) : null
// Build suggested pages list
const suggested = useMemo(() => {
if (!suggestedPageIds?.length) return []
const pageMap = new Map(options.map((p) => [p.id, p]))
return suggestedPageIds.map((id) => pageMap.get(id)).filter(Boolean) as {
id: number
caption: string
}[]
}, [suggestedPageIds, options])
// Non-suggested pages (exclude those already in suggestions)
const suggestedSet = useMemo(() => new Set(suggested.map((s) => s.id)), [suggested])
const remaining = useMemo(
() => options.filter((p) => !suggestedSet.has(p.id)),
[options, suggestedSet],
)
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="w-full justify-between font-normal"
>
{selectedPage ? (
<span className="truncate">
<span className="text-muted-foreground font-mono text-xs mr-1.5">
#{selectedPage.id}
</span>
{selectedPage.caption}
</span>
) : (
<span className="text-muted-foreground">Select target page...</span>
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
<Command>
<CommandInput placeholder="Search pages..." />
<CommandList>
<CommandEmpty>No page found.</CommandEmpty>
{/* Suggested pages */}
{suggested.length > 0 && (
<CommandGroup heading="Suggested">
{suggested.map((page) => (
<CommandItem
key={`s-${page.id}`}
value={`${page.id} ${page.caption}`}
onSelect={() => {
onChange(page.id)
setOpen(false)
}}
>
<Check
className={cn(
'mr-2 h-4 w-4',
value === page.id ? 'opacity-100' : 'opacity-0',
)}
/>
<Star className="mr-1.5 h-3 w-3 text-amber-500" />
<span className="text-muted-foreground font-mono text-xs mr-1.5">
#{page.id}
</span>
<span className="truncate">{page.caption}</span>
</CommandItem>
))}
</CommandGroup>
)}
{/* All pages */}
<CommandGroup heading={suggested.length > 0 ? 'All pages' : undefined}>
{remaining.map((page) => (
<CommandItem
key={page.id}
value={`${page.id} ${page.caption}`}
onSelect={() => {
onChange(page.id)
setOpen(false)
}}
>
<Check
className={cn('mr-2 h-4 w-4', value === page.id ? 'opacity-100' : 'opacity-0')}
/>
<span className="text-muted-foreground font-mono text-xs mr-1.5">#{page.id}</span>
<span className="truncate">{page.caption}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,42 @@
'use client'
import { Image as ImageIcon } from 'lucide-react'
import { getHabboCdnIconUrl, getLocalIconUrl } from '@/lib/furni/classname'
export function FurniIcon({ classname, revision }: { classname: string; revision: number }) {
if (!classname) {
return (
<div className="w-10 h-10 rounded bg-muted flex items-center justify-center">
<ImageIcon className="h-4 w-4 text-muted-foreground" />
</div>
)
}
const localUrl = getLocalIconUrl(classname)
function handleError(e: React.SyntheticEvent<HTMLImageElement>) {
const img = e.target as HTMLImageElement
const stage = img.dataset.fallback
if (!stage && revision > 0) {
img.dataset.fallback = 'cdn'
img.src = getHabboCdnIconUrl(classname, revision)
} else {
img.dataset.fallback = 'none'
img.style.opacity = '0'
}
}
return (
<div className="w-10 h-10 rounded bg-muted/50 flex items-center justify-center overflow-hidden">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={localUrl}
alt={classname}
className="max-w-full max-h-full object-contain"
style={{ imageRendering: 'pixelated' }}
onError={handleError}
loading="lazy"
/>
</div>
)
}
@@ -0,0 +1,4 @@
export { CatalogItemsTable } from './catalog-items-table'
export { FurniIcon } from './furni-icon'
export type { BaseItemData, CatalogItemData, InlineEdit } from './types'
export { DEFAULT_NEW_ITEM, getPointsLabel, POINTS_TYPES } from './types'
@@ -0,0 +1,94 @@
'use client'
import { Loader2, Music } from 'lucide-react'
import { useEffect, useState } from 'react'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
getCachedSongPickerOptions,
loadSongPickerOptions,
type SoundtrackOption,
} from '@/lib/client-cache/song-picker-cache'
// Re-export so existing `import { invalidateSongPickerCache } from '.../song-picker'`
// callsites keep working. New code should import from the lib module directly.
export { invalidateSongPickerCache } from '@/lib/client-cache/song-picker-cache'
interface Props {
value: number
onChange: (id: number) => void
disabled?: boolean
}
function formatLength(seconds: number): string {
if (!seconds || seconds <= 0) return ''
const m = Math.floor(seconds / 60)
const s = seconds % 60
return `${m}:${String(s).padStart(2, '0')}`
}
export function SongPicker({ value, onChange, disabled }: Props) {
const initial = getCachedSongPickerOptions()
const [options, setOptions] = useState<SoundtrackOption[]>(initial ?? [])
const [loading, setLoading] = useState(!initial)
useEffect(() => {
if (getCachedSongPickerOptions()) return
let cancelled = false
loadSongPickerOptions()
.then((items) => {
if (!cancelled) setOptions(items)
})
.catch(() => {
if (!cancelled) setOptions([])
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [])
return (
<Select
value={String(value)}
onValueChange={(v) => onChange(parseInt(v, 10) || 0)}
disabled={disabled || loading}
>
<SelectTrigger>
{loading ? (
<span className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" /> Loading…
</span>
) : (
<SelectValue placeholder="No song" />
)}
</SelectTrigger>
<SelectContent>
<SelectItem value="0">
<span className="text-muted-foreground">— No song —</span>
</SelectItem>
{options.map((opt) => (
<SelectItem key={opt.id} value={String(opt.id)}>
<span className="inline-flex items-center gap-2">
<Music className="h-3 w-3 text-muted-foreground" />
<span className="font-medium">{opt.name}</span>
{opt.author && <span className="text-xs text-muted-foreground">— {opt.author}</span>}
{opt.length > 0 && (
<span className="text-xs text-muted-foreground font-mono">
{formatLength(opt.length)}
</span>
)}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
)
}
@@ -0,0 +1,85 @@
export interface BaseItemData {
id: number
spriteId: number
publicName: string
itemName: string
type: string
width: number
length: number
stackHeight: number
allowStack: number
allowSit: number
allowLay: number
allowWalk: number
allowGift: number
allowTrade: number
allowRecycle: number
allowMarketplaceSell: number
allowInventoryStack: number
interactionType: string
interactionModesCount: number
vendingIds: string
customparams: string
effectIdMale: number
effectIdFemale: number
clothingOnWalk: string
}
export interface CatalogItemData {
id: number
catalogName: string
itemIds: string
costCredits: number
costPoints: number
pointsType: number
amount: number
limitedSells: number
limitedStack: number
orderNumber: number
offerId: number
songId: number
haveOffer: string
clubOnly: string
extradata: string
baseName: string
baseItemName: string
spriteId: number
baseItem: BaseItemData | null
}
export interface InlineEdit {
costCredits: number
costPoints: number
pointsType: number
amount: number
}
export const POINTS_TYPES: Record<number, { label: string; color: string }> = {
0: { label: 'Duckets', color: 'text-blue-500' },
5: { label: 'Diamonds', color: 'text-purple-500' },
101: { label: 'Snowflakes', color: 'text-cyan-400' },
103: { label: 'Hearts', color: 'text-pink-500' },
104: { label: 'Stars', color: 'text-amber-400' },
105: { label: 'Shells', color: 'text-orange-400' },
}
export const DEFAULT_NEW_ITEM = {
catalogName: '',
itemIds: '0',
costCredits: 0,
costPoints: 0,
pointsType: 0,
amount: 1,
limitedSells: 0,
limitedStack: 0,
orderNumber: 1,
offerId: -1,
songId: 0,
haveOffer: '1',
clubOnly: '0',
extradata: '',
}
export function getPointsLabel(type: number) {
return POINTS_TYPES[type] || { label: `Type ${type}`, color: 'text-gray-500' }
}
@@ -0,0 +1,700 @@
'use client'
import {
Check,
ChevronsUpDown,
FileText,
FolderTree,
Loader2,
Package,
Palette,
Save,
Settings,
Trash2,
} from 'lucide-react'
import Link from 'next/link'
import { useEffect, useRef, useState } from 'react'
import { deleteCatalogPage, updateCatalogPage } from '@/actions/catalog'
import { CatalogImagePicker } from '@/components/admin/catalog/catalog-image-picker'
import { IconPicker } from '@/components/admin/catalog/icon-picker'
import { ImagePreview } from '@/components/admin/catalog-manager/image-preview'
import { CatalogIcon, LAYOUT_COLORS } from '@/components/admin/catalog-tree'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
import { CATALOG_LAYOUTS, type CatalogLayout, LAYOUT_DESCRIPTIONS } from '@/lib/catalog-layouts'
import { cn } from '@/lib/utils'
interface CatalogPageData {
id: number
caption: string
parentId: number
pageLayout: string
enabled: string
visible: string
minRank: number
clubOnly: string
orderNum: number
iconImage: number
iconColor: number
pageHeadline: string
pageTeaser: string
pageSpecial: string | null
pageText1: string | null
pageText2: string | null
pageTextDetails: string | null
pageTextTeaser: string | null
}
interface CatalogPageFormProps {
catalogPage: CatalogPageData
childPages: { id: number; caption: string; enabled: string }[]
canEdit: boolean
allPages: { id: number; caption: string }[]
}
export function CatalogPageForm({
catalogPage,
childPages,
canEdit,
allPages,
}: CatalogPageFormProps) {
const { isPending, run } = useServerAction()
const formRef = useRef<HTMLFormElement>(null)
const [form, setForm] = useState({
caption: catalogPage.caption,
parentId: catalogPage.parentId,
pageLayout: catalogPage.pageLayout,
enabled: catalogPage.enabled as '0' | '1',
visible: catalogPage.visible as '0' | '1',
minRank: catalogPage.minRank,
clubOnly: catalogPage.clubOnly as '0' | '1',
orderNum: catalogPage.orderNum,
iconImage: catalogPage.iconImage,
iconColor: catalogPage.iconColor,
pageHeadline: catalogPage.pageHeadline,
pageTeaser: catalogPage.pageTeaser,
pageSpecial: catalogPage.pageSpecial || '',
pageText1: catalogPage.pageText1 || '',
pageText2: catalogPage.pageText2 || '',
pageTextDetails: catalogPage.pageTextDetails || '',
pageTextTeaser: catalogPage.pageTextTeaser || '',
})
// Ctrl+S / Cmd+S to save
useEffect(() => {
if (!canEdit) return
function onKeyDown(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
formRef.current?.requestSubmit()
}
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [canEdit])
function update<K extends keyof typeof form>(key: K, value: (typeof form)[K]) {
setForm((prev) => ({ ...prev, [key]: value }))
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
run(() => updateCatalogPage({ id: catalogPage.id, ...form }), {
successMessage: 'Page updated and catalog synced.',
errorMessage: 'Failed to update.',
})
}
function handleDelete() {
const childCount = childPages.length
const msg =
childCount > 0
? `Delete this catalog page? Its ${childCount} child page(s) will be moved to root. All items in this page will be deleted.`
: 'Delete this catalog page and all its items?'
if (!confirm(msg)) return
run(() => deleteCatalogPage({ id: catalogPage.id }), {
successMessage: 'Page deleted.',
redirectTo: '/admin/catalog',
})
}
const layoutColorClass = LAYOUT_COLORS[form.pageLayout] || 'bg-muted text-muted-foreground'
return (
<form ref={formRef} onSubmit={handleSubmit}>
<div className="grid gap-4 lg:grid-cols-3">
{/* ── Left column (2/3): tabs ─────────────────────────── */}
<div className="lg:col-span-2 space-y-4">
<Card>
<CardContent className="pt-4">
<Tabs defaultValue="general">
<TabsList className="mb-4">
<TabsTrigger value="general" className="gap-2">
<Settings className="h-4 w-4" />
General
</TabsTrigger>
<TabsTrigger value="texts" className="gap-2">
<FileText className="h-4 w-4" />
Texts
</TabsTrigger>
<TabsTrigger value="appearance" className="gap-2">
<Palette className="h-4 w-4" />
Appearance
</TabsTrigger>
</TabsList>
{/* ── General ──────────────────────────────────── */}
<TabsContent value="general" className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="caption">Caption</Label>
<Input
id="caption"
value={form.caption}
onChange={(e) => update('caption', e.target.value)}
disabled={!canEdit}
/>
</div>
<div className="space-y-2">
<Label>Parent Page</Label>
<ParentCombobox
value={form.parentId}
onChange={(id) => update('parentId', id)}
pages={allPages}
currentPageId={catalogPage.id}
disabled={!canEdit}
/>
</div>
</div>
<div className="space-y-2">
<Label>Layout</Label>
<LayoutSelect
value={form.pageLayout}
onChange={(v) => update('pageLayout', v)}
disabled={!canEdit}
/>
<p className="text-xs text-muted-foreground">
{LAYOUT_DESCRIPTIONS[form.pageLayout as CatalogLayout] ?? 'Custom layout'}
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="orderNum">Order</Label>
<Input
id="orderNum"
type="number"
value={form.orderNum}
onChange={(e) => update('orderNum', parseInt(e.target.value, 10) || 0)}
disabled={!canEdit}
/>
</div>
<div className="space-y-2">
<Label htmlFor="minRank">Min Rank</Label>
<Input
id="minRank"
type="number"
min={1}
max={100}
value={form.minRank}
onChange={(e) => update('minRank', parseInt(e.target.value, 10) || 1)}
disabled={!canEdit}
/>
</div>
</div>
</TabsContent>
{/* ── Texts ────────────────────────────────────── */}
<TabsContent value="texts" className="space-y-4">
<div className="space-y-1.5">
<Label>Headline</Label>
<CatalogImagePicker
value={form.pageHeadline}
onChange={(v) => update('pageHeadline', v)}
type="header"
label="Headline image"
disabled={!canEdit}
/>
<ImagePreview value={form.pageHeadline} height={50} />
</div>
<div className="space-y-1.5">
<Label>Teaser</Label>
<CatalogImagePicker
value={form.pageTeaser}
onChange={(v) => update('pageTeaser', v)}
type="teaser"
label="Teaser image"
disabled={!canEdit}
/>
<ImagePreview value={form.pageTeaser} height={50} />
</div>
<div className="grid gap-4 sm:grid-cols-2">
<TextareaField
id="pageText1"
label="Text 1"
value={form.pageText1}
onChange={(v) => update('pageText1', v)}
disabled={!canEdit}
rows={4}
max={5000}
/>
<TextareaField
id="pageText2"
label="Text 2"
value={form.pageText2}
onChange={(v) => update('pageText2', v)}
disabled={!canEdit}
rows={4}
max={5000}
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<TextareaField
id="pageTextDetails"
label="Details"
value={form.pageTextDetails}
onChange={(v) => update('pageTextDetails', v)}
disabled={!canEdit}
rows={3}
max={5000}
/>
<TextareaField
id="pageTextTeaser"
label="Text Teaser"
value={form.pageTextTeaser}
onChange={(v) => update('pageTextTeaser', v)}
disabled={!canEdit}
rows={3}
max={5000}
/>
</div>
<TextareaField
id="pageSpecial"
label="Special"
value={form.pageSpecial}
onChange={(v) => update('pageSpecial', v)}
disabled={!canEdit}
rows={2}
max={2048}
/>
</TabsContent>
{/* ── Appearance ───────────────────────────────── */}
<TabsContent value="appearance" className="space-y-4">
<div className="space-y-2">
<Label>Icon</Label>
<div className="flex items-center gap-3">
<IconPicker
value={form.iconImage}
onChange={(id) => update('iconImage', id)}
disabled={!canEdit}
/>
<p className="text-xs text-muted-foreground">
Icon shown in the catalog tree navigation.
</p>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="iconColor">Icon Color</Label>
<div className="flex items-center gap-2">
<Input
id="iconColor"
type="number"
min={0}
className="w-32"
value={form.iconColor}
onChange={(e) => update('iconColor', parseInt(e.target.value, 10) || 0)}
disabled={!canEdit}
/>
<p className="text-xs text-muted-foreground">
Legacy tint value. Leave at default unless you need to match a specific
theme.
</p>
</div>
</div>
</TabsContent>
</Tabs>
</CardContent>
</Card>
{/* Child pages list */}
{childPages.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<FolderTree className="h-4 w-4" />
Child Pages ({childPages.length})
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-1">
{childPages.map((child) => (
<Link
key={child.id}
href={`/admin/catalog/${child.id}`}
className="flex items-center justify-between rounded-md px-3 py-2 hover:bg-accent text-sm"
>
<span>
{child.caption}
<span className="ml-2 text-muted-foreground font-mono text-xs">
#{child.id}
</span>
</span>
<Badge variant={child.enabled === '1' ? 'default' : 'outline'}>
{child.enabled === '1' ? 'Enabled' : 'Disabled'}
</Badge>
</Link>
))}
</div>
</CardContent>
</Card>
)}
</div>
{/* ── Right column (1/3): status sticky ────────────────── */}
<div className="lg:col-span-1">
<Card className="lg:sticky lg:top-4">
<CardHeader className="pb-3">
<CardTitle className="text-base">Status & Preview</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Preview */}
<div className="flex items-center gap-3 rounded-md border bg-muted/30 p-3">
<div className="flex h-12 w-12 items-center justify-center rounded bg-background shrink-0">
<CatalogIcon iconImage={form.iconImage} size={36} />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium">{form.caption || 'Untitled'}</p>
<Badge
className={cn(
'mt-1 h-5 px-1.5 text-[10px] font-mono border-0',
layoutColorClass,
)}
>
{form.pageLayout}
</Badge>
</div>
</div>
{/* Toggles */}
<div className="space-y-3">
<ToggleRow
id="tg-enabled"
label="Enabled"
description="Active in the catalog"
checked={form.enabled === '1'}
onChange={(v) => update('enabled', v ? '1' : '0')}
disabled={!canEdit}
/>
<ToggleRow
id="tg-visible"
label="Visible"
description="Shown in navigation"
checked={form.visible === '1'}
onChange={(v) => update('visible', v ? '1' : '0')}
disabled={!canEdit}
/>
<ToggleRow
id="tg-club"
label="Club Only"
description="Requires HC subscription"
checked={form.clubOnly === '1'}
onChange={(v) => update('clubOnly', v ? '1' : '0')}
disabled={!canEdit}
/>
</div>
{/* Stats */}
<div className="flex items-center gap-4 border-t pt-3 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<FolderTree className="h-3.5 w-3.5" />
{childPages.length} sub
</span>
<span className="flex items-center gap-1">
<Package className="h-3.5 w-3.5" />#{catalogPage.id}
</span>
</div>
{/* Actions */}
{canEdit && (
<div className="space-y-2 border-t pt-3">
<Button type="submit" disabled={isPending} className="w-full">
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save & Sync
</Button>
<Button
type="button"
variant="destructive"
onClick={handleDelete}
disabled={isPending}
className="w-full"
>
<Trash2 className="mr-2 h-4 w-4" />
Delete Page
</Button>
<p className="text-center text-[10px] text-muted-foreground">
Press <kbd className="rounded border px-1">Ctrl+S</kbd> to save
</p>
</div>
)}
</CardContent>
</Card>
</div>
</div>
</form>
)
}
// ── Toggle row ─────────────────────────────────────────────────
function ToggleRow({
id,
label,
description,
checked,
onChange,
disabled,
}: {
id: string
label: string
description: string
checked: boolean
onChange: (v: boolean) => void
disabled?: boolean
}) {
return (
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<Label htmlFor={id} className="text-sm font-medium cursor-pointer">
{label}
</Label>
<p className="text-[11px] text-muted-foreground">{description}</p>
</div>
<Switch id={id} checked={checked} onCheckedChange={onChange} disabled={disabled} />
</div>
)
}
// ── Text field with counter ────────────────────────────────────
function _TextField({
id,
label,
value,
onChange,
disabled,
max,
}: {
id: string
label: string
value: string
onChange: (v: string) => void
disabled?: boolean
max?: number
}) {
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label htmlFor={id}>{label}</Label>
{max && (
<span className="text-[10px] tabular-nums text-muted-foreground">
{value.length}/{max}
</span>
)}
</div>
<Input
id={id}
value={value}
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
maxLength={max}
/>
</div>
)
}
function TextareaField({
id,
label,
value,
onChange,
disabled,
rows = 3,
max,
}: {
id: string
label: string
value: string
onChange: (v: string) => void
disabled?: boolean
rows?: number
max?: number
}) {
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label htmlFor={id}>{label}</Label>
{max && (
<span className="text-[10px] tabular-nums text-muted-foreground">
{value.length}/{max}
</span>
)}
</div>
<Textarea
id={id}
rows={rows}
value={value}
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
maxLength={max}
/>
</div>
)
}
// ── Layout select with color swatch ────────────────────────────
function LayoutSelect({
value,
onChange,
disabled,
}: {
value: string
onChange: (v: string) => void
disabled?: boolean
}) {
return (
<Select value={value} onValueChange={onChange} disabled={disabled}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{CATALOG_LAYOUTS.map((layout) => {
const colorClass = LAYOUT_COLORS[layout] || 'bg-muted text-muted-foreground'
return (
<SelectItem key={layout} value={layout}>
<span className="flex items-center gap-2">
<span className={cn('inline-block h-2 w-2 rounded-full', colorClass)} />
{layout}
</span>
</SelectItem>
)
})}
</SelectContent>
</Select>
)
}
// ── Parent page combobox with search ────────────────────────────
function ParentCombobox({
value,
onChange,
pages,
currentPageId,
disabled,
}: {
value: number
onChange: (id: number) => void
pages: { id: number; caption: string }[]
currentPageId: number
disabled?: boolean
}) {
const [open, setOpen] = useState(false)
const options = pages.filter((p) => p.id !== currentPageId)
const selected = value === -1 ? { id: -1, caption: 'Root' } : pages.find((p) => p.id === value)
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
role="combobox"
aria-expanded={open}
disabled={disabled}
className="w-full justify-between font-normal"
>
{selected ? (
<span className="truncate">
<span className="text-muted-foreground font-mono text-xs mr-1.5">
{selected.id === -1 ? '—' : `#${selected.id}`}
</span>
{selected.caption}
</span>
) : (
<span className="text-muted-foreground">Select parent...</span>
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
<Command>
<CommandInput placeholder="Search pages..." />
<CommandList>
<CommandEmpty>No page found.</CommandEmpty>
<CommandGroup>
<CommandItem
value="root"
onSelect={() => {
onChange(-1)
setOpen(false)
}}
>
<Check className={cn('mr-2 h-4 w-4', value === -1 ? 'opacity-100' : 'opacity-0')} />
<span className="text-muted-foreground font-mono text-xs mr-1.5">—</span>
Root
</CommandItem>
{options.map((page) => (
<CommandItem
key={page.id}
value={`${page.id} ${page.caption}`}
onSelect={() => {
onChange(page.id)
setOpen(false)
}}
>
<Check
className={cn('mr-2 h-4 w-4', value === page.id ? 'opacity-100' : 'opacity-0')}
/>
<span className="text-muted-foreground font-mono text-xs mr-1.5">#{page.id}</span>
<span className="truncate">{page.caption}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,507 @@
'use client'
import {
AlertTriangle,
CheckCircle2,
Database,
FileJson,
Filter,
Loader2,
RotateCcw,
Save,
ShoppingCart,
Sparkles,
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { useCallback, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { translateCatalogItems } from '@/actions/catalog-items'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { useServerAction } from '@/hooks/use-server-action'
import { FurniIcon } from './catalog-items-table'
interface BaseItemForTranslation {
id: number
publicName: string
itemName: string
spriteId: number
type: string
}
interface CatalogTranslateTabProps {
baseItems: BaseItemForTranslation[]
catalogNameMap: Record<number, string>
canEdit: boolean
furniDataIdList: number[]
furniDescriptionMap: Record<number, string>
furniRevisionMap?: Record<number, { classname: string; revision: number }>
}
type FilterMode = 'all' | 'missing' | 'modified'
export function CatalogTranslateTab({
baseItems,
catalogNameMap,
canEdit,
furniDataIdList,
furniDescriptionMap,
furniRevisionMap = {},
}: CatalogTranslateTabProps) {
const router = useRouter()
const { run, isPending } = useServerAction()
const [isSuggesting, setIsSuggesting] = useState(false)
const [filterMode, setFilterMode] = useState<FilterMode>('all')
const furniDataIdSet = useMemo(() => new Set(furniDataIdList), [furniDataIdList])
const [selected, setSelected] = useState<Set<number>>(new Set())
// ── Editable state: names + descriptions ─────────────────────────
const [editedNames, setEditedNames] = useState<Record<number, string>>(
Object.fromEntries(baseItems.map((item) => [item.id, item.publicName])),
)
const [editedDescs, setEditedDescs] = useState<Record<number, string>>(
Object.fromEntries(baseItems.map((item) => [item.id, furniDescriptionMap[item.id] ?? ''])),
)
// Track which items have name or description changes
const isNameChanged = useCallback(
(item: BaseItemForTranslation) => editedNames[item.id] !== item.publicName,
[editedNames],
)
const isDescChanged = useCallback(
(item: BaseItemForTranslation) => editedDescs[item.id] !== (furniDescriptionMap[item.id] ?? ''),
[editedDescs, furniDescriptionMap],
)
const changedItems = useMemo(
() => baseItems.filter((item) => isNameChanged(item) || isDescChanged(item)),
[baseItems, isNameChanged, isDescChanged],
)
const missingItems = useMemo(
() => baseItems.filter((item) => !furniDataIdSet.has(item.id)),
[baseItems, furniDataIdSet],
)
const filteredItems = useMemo(() => {
switch (filterMode) {
case 'missing':
return baseItems.filter((item) => !furniDataIdSet.has(item.id))
case 'modified':
return baseItems.filter((item) => isNameChanged(item) || isDescChanged(item))
default:
return baseItems
}
}, [baseItems, filterMode, furniDataIdSet, isNameChanged, isDescChanged])
const toggleOne = useCallback((id: number) => {
setSelected((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}, [])
const toggleAll = useCallback(() => {
setSelected((prev) =>
prev.size === filteredItems.length ? new Set() : new Set(filteredItems.map((i) => i.id)),
)
}, [filteredItems])
// Items to act on: selected ones if any, otherwise all
const targetItems = useMemo(() => {
if (selected.size === 0) return baseItems
return baseItems.filter((i) => selected.has(i.id))
}, [baseItems, selected])
function handleNameChange(id: number, value: string) {
setEditedNames((prev) => ({ ...prev, [id]: value }))
}
function handleDescChange(id: number, value: string) {
setEditedDescs((prev) => ({ ...prev, [id]: value }))
}
function handleReset() {
setEditedNames(Object.fromEntries(baseItems.map((item) => [item.id, item.publicName])))
setEditedDescs(
Object.fromEntries(baseItems.map((item) => [item.id, furniDescriptionMap[item.id] ?? ''])),
)
}
async function handleSuggestFromHabboFurni() {
if (targetItems.length === 0) return
setIsSuggesting(true)
try {
// Collect classnames from selected items (or all if none selected)
const classnames = targetItems.map((item) => item.itemName).filter(Boolean)
if (classnames.length === 0) {
toast.info('No classnames found to look up.')
setIsSuggesting(false)
return
}
// Batch in chunks of 50 to avoid too-long URLs
const CHUNK_SIZE = 50
const allSuggestions: Record<string, { name: string; description: string }> = {}
for (let i = 0; i < classnames.length; i += CHUNK_SIZE) {
const chunk = classnames.slice(i, i + CHUNK_SIZE)
const res = await fetch(
`/api/admin/catalog/suggest?classnames=${encodeURIComponent(chunk.join(','))}`,
)
if (res.ok) {
const data = await res.json()
Object.assign(allSuggestions, data.suggestions || {})
}
}
// Apply suggestions to items that have a match (names + descriptions)
let nameCount = 0
let descCount = 0
const newNames = { ...editedNames }
const newDescs = { ...editedDescs }
for (const item of targetItems) {
const suggestion = allSuggestions[item.itemName]
if (!suggestion) continue
if (suggestion.name && suggestion.name !== item.publicName) {
newNames[item.id] = suggestion.name
nameCount++
}
const currentDesc = furniDescriptionMap[item.id] ?? ''
if (suggestion.description && suggestion.description !== currentDesc) {
newDescs[item.id] = suggestion.description
descCount++
}
}
setEditedNames(newNames)
setEditedDescs(newDescs)
const total = nameCount + descCount
if (total > 0) {
const parts = []
if (nameCount > 0) parts.push(`${nameCount} name(s)`)
if (descCount > 0) parts.push(`${descCount} description(s)`)
toast.success(`HabboFurni: ${parts.join(' + ')} suggested from habbo.it. Review and save.`)
} else {
toast.info(
`HabboFurni: No new suggestions found (${Object.keys(allSuggestions).length} looked up, all already match).`,
)
}
} catch (err) {
toast.error(`HabboFurni error: ${(err as Error).message}`)
} finally {
setIsSuggesting(false)
}
}
async function handleSaveAll() {
if (changedItems.length === 0) return
run(
() =>
translateCatalogItems({
items: changedItems.map((item) => ({
id: item.id,
publicName: editedNames[item.id],
description: editedDescs[item.id],
})),
}),
{
successMessage: 'Translations saved.',
errorMessage: 'Failed to save translations.',
onSuccess: (data) => {
const d = data as Record<string, number | boolean>
const parts = []
if (d.namesUpdated && (d.namesUpdated as number) > 0)
parts.push(`${d.namesUpdated} name(s) updated`)
if (d.descriptionsUpdated && (d.descriptionsUpdated as number) > 0)
parts.push(`${d.descriptionsUpdated} description(s) updated`)
if (parts.length === 0) parts.push(`${d.updated ?? 0} item(s) processed`)
if (d.furniDataUpdated) parts.push('FurnitureData.json synced')
if (d.furniDataInserted && (d.furniDataInserted as number) > 0) {
parts.push(`${d.furniDataInserted} new item(s) added to FurnitureData.json`)
}
parts.push('emulator cache refreshed')
toast.success(`${parts.join(' · ')}.`)
router.refresh()
},
},
)
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div className="min-w-0">
<CardTitle>Translate Item Names</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
Edit the public name and description of furniture items. Saving will update:
</p>
<div className="flex gap-3 mt-2 flex-wrap">
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
<Database className="h-3 w-3" /> items_base (name)
</span>
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
<ShoppingCart className="h-3 w-3" /> catalog_name (auto)
</span>
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
<FileJson className="h-3 w-3" /> FurnitureData.json (name + desc)
</span>
</div>
{missingItems.length > 0 && (
<div className="flex items-center gap-1.5 mt-2 text-xs text-orange-600 dark:text-orange-400">
<AlertTriangle className="h-3.5 w-3.5" />
<span>
{missingItems.length} item(s) missing from FurnitureData.json — will be
auto-inserted on save
</span>
</div>
)}
</div>
{canEdit && (
<div className="flex gap-2 flex-shrink-0 flex-wrap justify-end">
<Button
variant="outline"
size="sm"
onClick={handleSuggestFromHabboFurni}
disabled={isSuggesting || isPending || targetItems.length === 0}
title="Suggest Italian names + descriptions from HabboFurni API (habbo.it)"
>
{isSuggesting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Sparkles className="mr-2 h-4 w-4" />
)}
Suggest IT{selected.size > 0 ? ` (${selected.size})` : ''}
</Button>
<Button
variant="outline"
size="sm"
onClick={handleReset}
disabled={changedItems.length === 0 || isPending}
>
<RotateCcw className="mr-2 h-4 w-4" />
Reset
</Button>
<Button
size="sm"
onClick={handleSaveAll}
disabled={isPending || changedItems.length === 0}
>
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save All ({changedItems.length})
</Button>
</div>
)}
</CardHeader>
<CardContent>
{/* Filter bar */}
{baseItems.length > 0 && (
<div className="flex items-center gap-2 mb-4">
<Filter className="h-4 w-4 text-muted-foreground" />
<div className="flex gap-1">
<Button
variant={filterMode === 'all' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode('all')}
>
All ({baseItems.length})
</Button>
<Button
variant={filterMode === 'missing' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode('missing')}
disabled={missingItems.length === 0}
>
<AlertTriangle className="mr-1 h-3 w-3" />
Missing ({missingItems.length})
</Button>
<Button
variant={filterMode === 'modified' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode('modified')}
disabled={changedItems.length === 0}
>
Modified ({changedItems.length})
</Button>
</div>
</div>
)}
{baseItems.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">
No items to translate in this page.
</p>
) : filteredItems.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">
No items match the current filter.
</p>
) : (
<TooltipProvider>
<div className="rounded-md border overflow-auto max-h-[600px]">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[40px] px-2">
<Checkbox
checked={filteredItems.length > 0 && selected.size === filteredItems.length}
onCheckedChange={toggleAll}
aria-label="Select all"
/>
</TableHead>
<TableHead className="w-[50px]"></TableHead>
<TableHead className="w-[60px]">ID</TableHead>
<TableHead className="w-[80px]">Type</TableHead>
<TableHead>Item Name</TableHead>
<TableHead className="min-w-[200px]">Public Name</TableHead>
<TableHead className="min-w-[200px]">Description</TableHead>
<TableHead className="w-[100px]">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredItems.map((item) => {
const nameChanged = isNameChanged(item)
const descChanged = isDescChanged(item)
const isChanged = nameChanged || descChanged
const isMissing = !furniDataIdSet.has(item.id)
const currentCatalogName = catalogNameMap[item.id]
return (
<TableRow
key={item.id}
className={
isChanged
? 'bg-yellow-50 dark:bg-yellow-950/20'
: isMissing
? 'bg-orange-50/50 dark:bg-orange-950/10'
: undefined
}
>
<TableCell className="px-2">
<Checkbox
checked={selected.has(item.id)}
onCheckedChange={() => toggleOne(item.id)}
aria-label={`Select ${item.itemName}`}
/>
</TableCell>
<TableCell className="px-1">
{(() => {
const revInfo = furniRevisionMap[item.id]
return revInfo ? (
<FurniIcon
classname={revInfo.classname}
revision={revInfo.revision}
/>
) : (
<FurniIcon classname={item.itemName} revision={0} />
)
})()}
</TableCell>
<TableCell className="font-mono text-xs">{item.id}</TableCell>
<TableCell>
<Badge
variant={item.type === 's' ? 'default' : 'secondary'}
className="text-xs"
>
{item.type === 's' ? 'Floor' : item.type === 'i' ? 'Wall' : item.type}
</Badge>
</TableCell>
<TableCell className="text-xs text-muted-foreground font-mono">
{item.itemName}
</TableCell>
<TableCell>
<Input
value={editedNames[item.id] || ''}
onChange={(e) => handleNameChange(item.id, e.target.value)}
disabled={!canEdit}
className={`h-8 text-sm ${nameChanged ? 'border-yellow-400 dark:border-yellow-600' : ''}`}
/>
{currentCatalogName && currentCatalogName !== item.publicName && (
<p className="text-[11px] text-muted-foreground mt-0.5 truncate">
catalog: {currentCatalogName}
</p>
)}
</TableCell>
<TableCell>
<Input
value={editedDescs[item.id] || ''}
onChange={(e) => handleDescChange(item.id, e.target.value)}
disabled={!canEdit}
placeholder="No description"
className={`h-8 text-sm ${descChanged ? 'border-yellow-400 dark:border-yellow-600' : ''}`}
/>
</TableCell>
<TableCell>
<div className="flex items-center gap-1.5">
{isChanged ? (
<Badge
variant="secondary"
className="text-xs bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
>
Modified
</Badge>
) : (
<span className="text-xs text-muted-foreground">—</span>
)}
{isMissing ? (
<Tooltip>
<TooltipTrigger asChild>
<AlertTriangle className="h-3.5 w-3.5 text-orange-500 flex-shrink-0" />
</TooltipTrigger>
<TooltipContent>
<p>Missing from FurnitureData.json</p>
<p className="text-xs text-muted-foreground">
Will be auto-inserted on save
</p>
</TooltipContent>
</Tooltip>
) : (
<Tooltip>
<TooltipTrigger asChild>
<CheckCircle2 className="h-3.5 w-3.5 text-green-500 flex-shrink-0" />
</TooltipTrigger>
<TooltipContent>In FurnitureData.json</TooltipContent>
</Tooltip>
)}
</div>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
</TooltipProvider>
)}
</CardContent>
</Card>
)
}
+41
View File
@@ -0,0 +1,41 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function CatalogDetailLoading() {
return (
<div className="space-y-6">
{/* Breadcrumb */}
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-16" />
<Skeleton className="h-4 w-4" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-4" />
<Skeleton className="h-4 w-20" />
</div>
{/* Title */}
<div>
<Skeleton className="h-9 w-64" />
<Skeleton className="h-5 w-40 mt-2" />
</div>
{/* Tabs */}
<div className="space-y-4">
<div className="flex gap-2 border-b pb-2">
{Array.from({ length: 4 }).map((_, i) => (
<Skeleton key={i} className="h-9 w-24 rounded-md" />
))}
</div>
{/* Tab content */}
<div className="rounded-lg border bg-card p-6 space-y-4">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-10 w-full" />
</div>
))}
</div>
</div>
</div>
)
}
+114 -153
View File
@@ -1,164 +1,125 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { ChevronRight } from 'lucide-react'
import Link from 'next/link'
import { notFound, redirect } from 'next/navigation'
import { Fragment } from 'react'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { loadCatalogItemsData } from '@/lib/services/catalog-items-loader'
import { getAncestors } from '@/lib/services/catalog-tree'
import { CatalogDetailTabs } from './catalog-detail-tabs'
export const dynamic = "force-dynamic";
type CatalogPageRow = {
id: number;
caption: string;
parentId: number;
pageLayout: string;
minRank: number;
visible: string;
enabled: string;
clubOnly: string;
vipOnly: string;
};
type CatalogItemRow = {
id: number;
catalogName: string;
itemIds: string;
amount: number;
costCredits: number;
costPoints: number;
pointsType: number;
limitedStack: number;
limitedSells: number;
orderNumber: number;
clubOnly: string;
};
export default async function AdminCatalogPage({
export default async function CatalogEditPage({
params,
}: {
params: Promise<{ id: string }>;
params: Promise<{ locale: string; id: string }>
}) {
const t = await getTranslations("pages.admin.catalog");
const { id } = await params;
const pageId = Number(id);
if (!Number.isInteger(pageId)) notFound();
let page: CatalogPageRow | null = null;
try {
page = await prisma.catalogPages.findUnique({
where: { id: pageId },
select: {
id: true,
caption: true,
parentId: true,
pageLayout: true,
minRank: true,
visible: true,
enabled: true,
clubOnly: true,
vipOnly: true,
},
});
} catch {
page = null;
}
if (!page) notFound();
let items: CatalogItemRow[] = [];
try {
items = await prisma.catalogItems.findMany({
where: { pageId },
select: {
id: true,
catalogName: true,
itemIds: true,
amount: true,
costCredits: true,
costPoints: true,
pointsType: true,
limitedStack: true,
limitedSells: true,
orderNumber: true,
clubOnly: true,
},
orderBy: [{ orderNumber: "asc" }, { id: "asc" }],
take: 500,
});
} catch {
items = [];
const { id } = await params
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect('/admin')
}
const hidden = page.visible !== "1" || page.enabled !== "1";
const pageId = parseInt(id, 10)
if (Number.isNaN(pageId)) notFound()
const catalogPage = await prisma.catalogPage.findUnique({
where: { id: pageId },
})
if (!catalogPage) notFound()
const [children, itemsData, ancestors] = await Promise.all([
prisma.catalogPage.findMany({
where: { parentId: pageId },
orderBy: { orderNum: 'asc' },
select: { id: true, caption: true, enabled: true },
}),
loadCatalogItemsData(pageId),
getAncestors(catalogPage.parentId),
])
const {
items: catalogItems,
baseItems,
catalogNameMap,
furniDataIdList,
furniDescriptionMap,
furniRevisionMap,
interactionTypes,
allPages,
} = itemsData
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
return (
<main>
<p className="muted">
<Link href="/admin/catalog">← {t("title")}</Link>
</p>
<h1>{page.caption}</h1>
<p className="muted">
{t("pageLabel", { id: page.id })} · {t("layoutLabel", { layout: page.pageLayout })} · {t("minRankLabel", { rank: page.minRank })} ·{" "}
{hidden ? t("statusHidden") : t("statusVisible")}
{page.parentId > 0 ? ` · ${t("parentLabel", { id: page.parentId })}` : ""}
{page.clubOnly === "1" ? ` · ${t("hcOnly")}` : ""}
{page.vipOnly === "1" ? ` · ${t("vipOnly")}` : ""}
</p>
<div className="space-y-6">
{/* Breadcrumb */}
<nav className="flex items-center gap-1 text-sm text-muted-foreground">
<Link href={'/admin/catalog'} className="hover:text-foreground transition-colors">
Catalog
</Link>
{ancestors.map((bc) => (
<Fragment key={bc.id}>
<ChevronRight className="h-3 w-3 flex-shrink-0" />
<Link
href={`/admin/catalog/${bc.id}`}
className="hover:text-foreground transition-colors"
>
{bc.caption}
</Link>
</Fragment>
))}
<ChevronRight className="h-3 w-3 flex-shrink-0" />
<span className="text-foreground font-medium">{catalogPage.caption}</span>
</nav>
<h2 style={{ marginTop: "1.5rem" }}>{t("items")}</h2>
{items.length === 0 ? (
<p className="muted">{t("noItems")}</p>
) : (
<table style={{ width: "100%", borderCollapse: "collapse" }}>
<thead>
<tr style={{ textAlign: "left", color: "var(--muted)" }}>
<th>{t("colId")}</th>
<th>{t("catalogName")}</th>
<th>{t("itemIds")}</th>
<th>{t("amount")}</th>
<th>{t("colCostCredits")}</th>
<th>{t("colCostPoints")}</th>
<th>{t("colLimited")}</th>
<th>{t("colOrder")}</th>
</tr>
</thead>
<tbody>
{items.map((it) => (
<tr key={it.id} style={{ borderTop: "1px solid var(--border-subtle)" }}>
<td>{it.id}</td>
<td>
{it.catalogName}
{it.clubOnly === "1" ? (
<span className="muted"> · {t("hc")}</span>
) : null}
</td>
<td className="muted">{it.itemIds}</td>
<td>{it.amount}</td>
<td>
{it.costCredits > 0 ? (
<span className="currency">{it.costCredits}</span>
) : (
<span className="muted">—</span>
)}
</td>
<td className="muted">
{it.costPoints > 0
? `${it.costPoints} (${t("typeLabel", { type: it.pointsType })})`
: "—"}
</td>
<td className="muted">
{it.limitedStack > 0
? `${it.limitedSells}/${it.limitedStack}`
: "—"}
</td>
<td>{it.orderNumber}</td>
</tr>
))}
</tbody>
</table>
)}
{/* Title */}
<div>
<h1 className="text-3xl font-bold tracking-tight">
{catalogPage.caption}
<span className="ml-2 text-base font-normal text-muted-foreground">
#{catalogPage.id}
</span>
</h1>
<p className="text-muted-foreground">
Layout: {catalogPage.pageLayout} &middot; {catalogItems.length} items
</p>
</div>
<p className="muted" style={{ marginTop: "1rem" }}>
{t("itemCount", { count: items.length })}
</p>
</main>
);
{/* Tabs */}
<CatalogDetailTabs
catalogPage={{
id: catalogPage.id,
caption: catalogPage.caption,
parentId: catalogPage.parentId,
pageLayout: catalogPage.pageLayout,
enabled: catalogPage.enabled,
visible: catalogPage.visible,
minRank: catalogPage.minRank,
clubOnly: catalogPage.clubOnly,
orderNum: catalogPage.orderNum,
iconImage: catalogPage.iconImage,
iconColor: catalogPage.iconColor,
pageHeadline: catalogPage.pageHeadline,
pageTeaser: catalogPage.pageTeaser,
pageSpecial: catalogPage.pageSpecial,
pageText1: catalogPage.pageText1,
pageText2: catalogPage.pageText2,
pageTextDetails: catalogPage.pageTextDetails,
pageTextTeaser: catalogPage.pageTextTeaser,
}}
items={catalogItems}
baseItems={baseItems}
catalogNameMap={catalogNameMap}
childPages={children}
pageId={catalogPage.id}
canEdit={canEdit}
furniDataIdList={furniDataIdList}
furniDescriptionMap={furniDescriptionMap}
furniRevisionMap={furniRevisionMap}
allPages={allPages}
interactionTypes={interactionTypes}
/>
</div>
)
}
@@ -0,0 +1,61 @@
import { notFound, redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { BcPageDetail } from '../bc-manager'
export default async function BcPageDetailPage({
params: paramsPromise,
}: {
params: Promise<{ locale: string; id: string }>
}) {
const { id: idStr } = await paramsPromise
const id = parseInt(idStr, 10)
if (Number.isNaN(id)) notFound()
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect('/admin')
}
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
const bcPage = await prisma.catalog_pages_bc.findUnique({ where: { id } })
if (!bcPage) notFound()
const bcItems = await prisma.catalog_items_bc.findMany({
where: { page_id: id },
orderBy: { order_number: 'asc' },
})
return (
<BcPageDetail
page={{
id: bcPage.id,
parentId: bcPage.parent_id,
caption: bcPage.caption,
pageLayout: bcPage.page_layout,
iconColor: bcPage.icon_color,
iconImage: bcPage.icon_image,
orderNum: bcPage.order_num,
visible: bcPage.visible,
enabled: bcPage.enabled,
pageHeadline: bcPage.page_headline,
pageTeaser: bcPage.page_teaser,
pageSpecial: bcPage.page_special ?? '',
pageText1: bcPage.page_text1 ?? '',
pageText2: bcPage.page_text2 ?? '',
pageTextDetails: bcPage.page_text_details ?? '',
pageTextTeaser: bcPage.page_text_teaser ?? '',
}}
items={bcItems.map((i) => ({
id: i.id,
pageId: i.page_id,
itemIds: i.item_ids,
catalogName: i.catalog_name,
orderNumber: i.order_number,
extradata: i.extradata,
}))}
canEdit={canEdit}
/>
)
}
@@ -0,0 +1,548 @@
'use client'
import { ArrowLeft, HardHat, Loader2, Package, Pencil, Plus, Save, Trash2 } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useRef, useState } from 'react'
import { createBcItem, deleteBcItem, updateBcItem, updateBcPage } from '@/actions/catalog-bc'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
// ── Types ────────────────────────────────────────────────────────────
export interface BcPageData {
id: number
parentId: number
caption: string
pageLayout: string
iconColor: number
iconImage: number
orderNum: number
visible: string
enabled: string
pageHeadline: string
pageTeaser: string
pageSpecial: string
pageText1: string
pageText2: string
pageTextDetails: string
pageTextTeaser: string
}
export interface BcItemData {
id: number
pageId: number
itemIds: string
catalogName: string
orderNumber: number
extradata: string
}
interface BcPageDetailProps {
page: BcPageData
items: BcItemData[]
canEdit: boolean
}
// ── Main Component ───────────────────────────────────────────────────
export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
const { isPending, run } = useServerAction()
const formRef = useRef<HTMLFormElement>(null)
const [editingItem, setEditingItem] = useState<BcItemData | null>(null)
const [addingItem, setAddingItem] = useState(false)
const [form, setForm] = useState({
caption: page.caption,
orderNum: page.orderNum,
enabled: page.enabled as '0' | '1',
visible: page.visible as '0' | '1',
pageHeadline: page.pageHeadline,
pageTeaser: page.pageTeaser,
pageSpecial: page.pageSpecial,
pageText1: page.pageText1,
pageText2: page.pageText2,
pageTextDetails: page.pageTextDetails,
pageTextTeaser: page.pageTextTeaser,
})
// Ctrl+S / Cmd+S to save
useEffect(() => {
if (!canEdit) return
function onKeyDown(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
formRef.current?.requestSubmit()
}
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [canEdit])
function update<K extends keyof typeof form>(key: K, value: (typeof form)[K]) {
setForm((prev) => ({ ...prev, [key]: value }))
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
run(() => updateBcPage({ id: page.id, ...form }), {
successMessage: 'BC page updated and catalog synced.',
errorMessage: 'Failed to update.',
})
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center gap-3">
<Link
href="/admin/catalog?catalog=bc"
className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4" />
BC Catalog
</Link>
<span className="text-muted-foreground">/</span>
<div className="flex items-center gap-2">
<HardHat className="h-5 w-5 text-amber-500" />
<h1 className="text-2xl font-bold tracking-tight">{page.caption}</h1>
<Badge variant="outline" className="font-mono text-xs">
#{page.id}
</Badge>
<Badge variant="secondary" className="font-mono text-xs">
{page.pageLayout}
</Badge>
</div>
</div>
<form ref={formRef} onSubmit={handleSubmit}>
<div className="grid gap-4 lg:grid-cols-3">
{/* ── Left column: form fields ─────────────── */}
<div className="lg:col-span-2 space-y-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Page Settings</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="caption">Caption</Label>
<Input
id="caption"
value={form.caption}
onChange={(e) => update('caption', e.target.value)}
disabled={!canEdit}
/>
</div>
<div className="space-y-2">
<Label htmlFor="orderNum">Order</Label>
<Input
id="orderNum"
type="number"
value={form.orderNum}
onChange={(e) => update('orderNum', parseInt(e.target.value, 10) || 0)}
disabled={!canEdit}
/>
</div>
</div>
<div className="space-y-2">
<Label>Headline</Label>
<Input
value={form.pageHeadline}
onChange={(e) => update('pageHeadline', e.target.value)}
disabled={!canEdit}
placeholder="Headline image path"
/>
</div>
<div className="space-y-2">
<Label>Teaser</Label>
<Input
value={form.pageTeaser}
onChange={(e) => update('pageTeaser', e.target.value)}
disabled={!canEdit}
placeholder="Teaser image path"
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label>Text 1</Label>
<Textarea
value={form.pageText1}
onChange={(e) => update('pageText1', e.target.value)}
disabled={!canEdit}
rows={3}
/>
</div>
<div className="space-y-2">
<Label>Text 2</Label>
<Textarea
value={form.pageText2}
onChange={(e) => update('pageText2', e.target.value)}
disabled={!canEdit}
rows={3}
/>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label>Details</Label>
<Textarea
value={form.pageTextDetails}
onChange={(e) => update('pageTextDetails', e.target.value)}
disabled={!canEdit}
rows={3}
/>
</div>
<div className="space-y-2">
<Label>Text Teaser</Label>
<Textarea
value={form.pageTextTeaser}
onChange={(e) => update('pageTextTeaser', e.target.value)}
disabled={!canEdit}
rows={3}
/>
</div>
</div>
<div className="space-y-2">
<Label>Special</Label>
<Textarea
value={form.pageSpecial}
onChange={(e) => update('pageSpecial', e.target.value)}
disabled={!canEdit}
rows={2}
/>
</div>
</CardContent>
</Card>
{/* Items */}
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base flex items-center gap-2">
<Package className="h-4 w-4" />
Items ({items.length})
</CardTitle>
{canEdit && (
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={() => setAddingItem(true)}
>
<Plus className="h-3 w-3 mr-1" />
Add Item
</Button>
)}
</div>
</CardHeader>
<CardContent>
{items.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">
No items in this page.
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="text-xs">ID</TableHead>
<TableHead className="text-xs">Name</TableHead>
<TableHead className="text-xs">Item IDs</TableHead>
<TableHead className="text-xs">Order</TableHead>
<TableHead className="text-xs">Extra Data</TableHead>
{canEdit && <TableHead className="text-xs w-20">Actions</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{items.map((item) => (
<TableRow key={item.id}>
<TableCell className="text-xs font-mono">{item.id}</TableCell>
<TableCell className="text-xs font-medium">{item.catalogName}</TableCell>
<TableCell className="text-xs font-mono text-muted-foreground">
{item.itemIds}
</TableCell>
<TableCell className="text-xs">{item.orderNumber}</TableCell>
<TableCell className="text-xs text-muted-foreground max-w-32 truncate">
{item.extradata || '\u2014'}
</TableCell>
{canEdit && (
<TableCell>
<div className="flex gap-1">
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 w-6 p-0"
onClick={() => setEditingItem(item)}
>
<Pencil className="h-3 w-3" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-red-500 hover:text-red-600"
onClick={() => {
if (!confirm(`Delete item "${item.catalogName}"?`)) return
run(() => deleteBcItem({ id: item.id }), {
successMessage: 'Item deleted.',
})
}}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
{/* ── Right column: status ─────────────────── */}
<div className="lg:col-span-1">
<Card className="lg:sticky lg:top-4">
<CardHeader className="pb-3">
<CardTitle className="text-base">Status</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-3">
<ToggleRow
id="tg-enabled"
label="Enabled"
description="Active in the BC catalog"
checked={form.enabled === '1'}
onChange={(v) => update('enabled', v ? '1' : '0')}
disabled={!canEdit}
/>
<ToggleRow
id="tg-visible"
label="Visible"
description="Shown in BC navigation"
checked={form.visible === '1'}
onChange={(v) => update('visible', v ? '1' : '0')}
disabled={!canEdit}
/>
</div>
{/* Stats */}
<div className="flex items-center gap-4 border-t pt-3 text-xs text-muted-foreground">
<span>
Layout: <span className="font-mono">{page.pageLayout}</span>
</span>
<span>
Parent:{' '}
<span className="font-mono">
{page.parentId <= 0 ? 'Root' : `#${page.parentId}`}
</span>
</span>
</div>
{/* Actions */}
{canEdit && (
<div className="space-y-2 border-t pt-3">
<Button type="submit" disabled={isPending} className="w-full">
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save & Sync
</Button>
<p className="text-center text-[10px] text-muted-foreground">
Press <kbd className="rounded border px-1">Ctrl+S</kbd> to save
</p>
</div>
)}
</CardContent>
</Card>
</div>
</div>
</form>
{/* Edit Item Dialog */}
{editingItem && (
<ItemDialog
item={editingItem}
mode="edit"
isPending={isPending}
onClose={() => setEditingItem(null)}
onSubmit={(data) => {
run(() => updateBcItem({ id: editingItem.id, ...data }), {
successMessage: 'Item updated.',
onSuccess: () => setEditingItem(null),
})
}}
/>
)}
{/* Add Item Dialog */}
{addingItem && (
<ItemDialog
item={{
id: 0,
pageId: page.id,
itemIds: '',
catalogName: '',
orderNumber: 1,
extradata: '',
}}
mode="add"
isPending={isPending}
onClose={() => setAddingItem(false)}
onSubmit={(data) => {
run(() => createBcItem({ pageId: page.id, ...data }), {
successMessage: 'Item created.',
onSuccess: () => setAddingItem(false),
})
}}
/>
)}
</div>
)
}
// ── Toggle row ───────────────────────────────────────────────────────
function ToggleRow({
id,
label,
description,
checked,
onChange,
disabled,
}: {
id: string
label: string
description: string
checked: boolean
onChange: (v: boolean) => void
disabled?: boolean
}) {
return (
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<Label htmlFor={id} className="text-sm font-medium cursor-pointer">
{label}
</Label>
<p className="text-[11px] text-muted-foreground">{description}</p>
</div>
<Switch id={id} checked={checked} onCheckedChange={onChange} disabled={disabled} />
</div>
)
}
// ── Item Dialog ──────────────────────────────────────────────────────
function ItemDialog({
item,
mode,
isPending,
onClose,
onSubmit,
}: {
item: BcItemData
mode: 'add' | 'edit'
isPending: boolean
onClose: () => void
onSubmit: (data: {
itemIds: string
catalogName: string
orderNumber: number
extradata: string
}) => void
}) {
const [form, setForm] = useState({
itemIds: item.itemIds,
catalogName: item.catalogName,
orderNumber: item.orderNumber,
extradata: item.extradata,
})
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{mode === 'add' ? 'Add BC Item' : `Edit Item #${item.id}`}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label>Catalog Name</Label>
<Input
value={form.catalogName}
onChange={(e) => setForm((f) => ({ ...f, catalogName: e.target.value }))}
/>
</div>
<div className="space-y-2">
<Label>Item IDs (semicolon-separated)</Label>
<Input
value={form.itemIds}
onChange={(e) => setForm((f) => ({ ...f, itemIds: e.target.value }))}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Order</Label>
<Input
type="number"
value={form.orderNumber}
onChange={(e) =>
setForm((f) => ({ ...f, orderNumber: parseInt(e.target.value, 10) || 0 }))
}
/>
</div>
<div className="space-y-2">
<Label>Extra Data</Label>
<Input
value={form.extradata}
onChange={(e) => setForm((f) => ({ ...f, extradata: e.target.value }))}
placeholder="Optional"
/>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={isPending}>
Cancel
</Button>
<Button
onClick={() => onSubmit(form)}
disabled={isPending || !form.catalogName || !form.itemIds}
>
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{mode === 'add' ? 'Add Item' : 'Save'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,5 @@
import { redirect } from 'next/navigation'
export default function BuilderClubPage() {
redirect('/admin/catalog?catalog=bc')
}
+128
View File
@@ -0,0 +1,128 @@
'use client'
import { Loader2, Plus } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { createCatalogPage } from '@/actions/catalog'
import { createBcPage } from '@/actions/catalog-bc'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
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'
import { CATALOG_LAYOUTS } from '@/lib/catalog-layouts'
interface CatalogActionsProps {
catalogType?: 'normal' | 'bc'
}
export function CatalogActions({ catalogType = 'normal' }: CatalogActionsProps) {
const { run, isPending } = useServerAction()
const [open, setOpen] = useState(false)
const [caption, setCaption] = useState('')
const [parentId, setParentId] = useState('-1')
const [pageLayout, setPageLayout] = useState('default_3x3')
const isBc = catalogType === 'bc'
function handleCreate() {
if (!caption.trim()) {
toast.error('Caption is required')
return
}
const input = {
caption: caption.trim(),
parentId: parseInt(parentId, 10),
pageLayout,
}
const fn = isBc ? () => createBcPage(input) : () => createCatalogPage(input)
run(fn, {
successMessage: `Catalog page "${caption.trim()}" created.`,
onSuccess: (data) => {
setOpen(false)
setCaption('')
setParentId('-1')
if (data.id) {
window.location.href = isBc
? `/admin/catalog/builder-club/${data.id}`
: `/admin/catalog/${data.id}`
}
},
})
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="mr-2 h-4 w-4" />
New Page
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{isBc ? 'Create Builder Club Page' : 'Create Catalog Page'}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="caption">Caption</Label>
<Input
id="caption"
value={caption}
onChange={(e) => setCaption(e.target.value)}
placeholder="Page name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="parentId">Parent ID (-1 = root)</Label>
<Input
id="parentId"
type="number"
value={parentId}
onChange={(e) => setParentId(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>Layout</Label>
<Select value={pageLayout} onValueChange={setPageLayout}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{CATALOG_LAYOUTS.map((layout) => (
<SelectItem key={layout} value={layout}>
{layout}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button onClick={handleCreate} disabled={isPending} className="w-full">
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
Create Page
</Button>
</div>
</DialogContent>
</Dialog>
)
}
+178
View File
@@ -0,0 +1,178 @@
'use client'
import { Pencil } from 'lucide-react'
import Link from 'next/link'
import { toggleCatalogPage } from '@/actions/catalog'
import { toggleBcPage } from '@/actions/catalog-bc'
import { DataTable } from '@/components/admin/data-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { useServerAction } from '@/hooks/use-server-action'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface CatalogPageRow {
id: number
caption: string
parentId: number
parentCaption: string
pageLayout: string
enabled: string
visible: string
minRank: number
orderNum: number
itemCount: number
childCount: number
}
interface CatalogTableProps {
data: PaginatedResult<CatalogPageRow>
canEdit: boolean
catalogType?: 'normal' | 'bc'
}
export function CatalogTable({ data, canEdit, catalogType = 'normal' }: CatalogTableProps) {
const { run, isPending } = useServerAction()
const isBc = catalogType === 'bc'
// Parent URLs stay in the same catalog; root takes you to the catalog index.
const detailHref = (id: number) =>
isBc ? `/admin/catalog/builder-club/${id}` : `/admin/catalog/${id}`
function handleToggle(id: number, action: 'toggleEnabled' | 'toggleVisible') {
if (isBc) {
const field = action === 'toggleEnabled' ? 'enabled' : 'visible'
run(() => toggleBcPage({ id, field }), { successMessage: 'Updated.' })
} else {
run(() => toggleCatalogPage({ id, action }), { successMessage: 'Updated.' })
}
}
const columns: DataTableColumn<CatalogPageRow>[] = [
{ key: 'id', label: 'ID', sortable: true },
{
key: 'caption',
label: 'Caption',
sortable: true,
render: (value, row) => (
<Link href={detailHref(row.id)} className="font-medium text-primary hover:underline">
{String(value)}
</Link>
),
},
{
key: 'parentId',
label: 'Parent',
sortable: true,
render: (_, row) =>
row.parentId === -1 ? (
<span className="text-xs text-muted-foreground">Root</span>
) : (
<Link href={detailHref(row.parentId)} className="text-xs hover:underline">
{row.parentCaption}
</Link>
),
},
{
key: 'pageLayout',
label: 'Layout',
render: (value) => <Badge variant="secondary">{String(value)}</Badge>,
},
{
key: 'enabled',
label: 'Enabled',
sortable: true,
filterKey: 'filter_enabled',
filterOptions: [
{ label: 'Enabled', value: '1' },
{ label: 'Disabled', value: '0' },
],
render: (value, row) =>
canEdit ? (
<button
type="button"
onClick={() => handleToggle(row.id, 'toggleEnabled')}
disabled={isPending}
className="cursor-pointer disabled:opacity-50"
>
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
</button>
) : (
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
),
},
{
key: 'visible',
label: 'Visible',
sortable: true,
filterKey: 'filter_visible',
filterOptions: [
{ label: 'Visible', value: '1' },
{ label: 'Hidden', value: '0' },
],
render: (value, row) =>
canEdit ? (
<button
type="button"
onClick={() => handleToggle(row.id, 'toggleVisible')}
disabled={isPending}
className="cursor-pointer disabled:opacity-50"
>
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
</button>
) : (
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
),
},
...(isBc
? []
: [
{
key: 'minRank' as const,
label: 'Min Rank',
sortable: true,
} satisfies DataTableColumn<CatalogPageRow>,
]),
{
key: 'itemCount',
label: 'Items',
render: (value) => <span>{String(value)}</span>,
},
{
key: 'childCount',
label: 'Children',
render: (value) => <span>{String(value)}</span>,
},
{
key: 'actions',
label: 'Actions',
render: (_, row) => (
<Button variant="ghost" size="icon" asChild>
<Link href={detailHref(row.id)}>
<Pencil className="h-4 w-4" />
</Link>
</Button>
),
},
]
return (
<DataTable
data={data}
columns={columns}
searchPlaceholder="Search by caption, layout or item..."
bulkActions={
canEdit
? [{ label: 'Delete Selected', value: 'delete', variant: 'destructive' }]
: undefined
}
/>
)
}
@@ -0,0 +1,85 @@
'use client'
import { FolderTree, HardHat, List, Package } from 'lucide-react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
interface CatalogViewToggleProps {
currentView: string
catalogType?: string
}
export function CatalogViewToggle({ currentView, catalogType = 'normal' }: CatalogViewToggleProps) {
const router = useRouter()
const searchParams = useSearchParams()
function setView(view: string) {
const params = new URLSearchParams(searchParams.toString())
if (view === 'tree') {
params.delete('view')
} else {
params.set('view', view)
}
router.push(`?${params.toString()}`)
}
function setCatalog(type: string) {
const params = new URLSearchParams(searchParams.toString())
if (type === 'normal') {
params.delete('catalog')
} else {
params.set('catalog', type)
}
params.delete('view') // reset to tree when switching
router.push(`?${params.toString()}`)
}
return (
<div className="flex items-center gap-2">
{/* Catalog type selector */}
<div className="flex items-center rounded-md border bg-card">
<Button
variant="ghost"
size="sm"
className={cn('h-8 rounded-r-none', catalogType === 'normal' && 'bg-accent')}
onClick={() => setCatalog('normal')}
>
<Package className="mr-1.5 h-4 w-4" />
Catalog
</Button>
<Button
variant="ghost"
size="sm"
className={cn('h-8 rounded-l-none', catalogType === 'bc' && 'bg-accent')}
onClick={() => setCatalog('bc')}
>
<HardHat className="mr-1.5 h-4 w-4" />
Builder Club
</Button>
</div>
{/* View mode selector */}
<div className="flex items-center rounded-md border bg-card">
<Button
variant="ghost"
size="sm"
className={cn('h-8 rounded-r-none', currentView === 'tree' && 'bg-accent')}
onClick={() => setView('tree')}
>
<FolderTree className="mr-1.5 h-4 w-4" />
Tree
</Button>
<Button
variant="ghost"
size="sm"
className={cn('h-8 rounded-l-none', currentView === 'table' && 'bg-accent')}
onClick={() => setView('table')}
>
<List className="mr-1.5 h-4 w-4" />
Table
</Button>
</div>
</div>
)
}
+44
View File
@@ -0,0 +1,44 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function CatalogLoading() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-9 w-48" />
<Skeleton className="h-5 w-64 mt-2" />
</div>
<div className="flex items-center gap-2">
<Skeleton className="h-10 w-24" />
<Skeleton className="h-10 w-28" />
</div>
</div>
{/* Tree skeleton */}
<div className="rounded-lg border bg-card">
<div className="border-b px-4 py-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
<Skeleton className="h-8 w-56" />
</div>
<div className="p-2 space-y-1">
{Array.from({ length: 12 }).map((_, i) => (
<div
key={i}
className="flex items-center gap-2 px-2 py-1.5"
style={{ paddingLeft: `${(i % 3) * 20 + 8}px` }}
>
<Skeleton className="h-5 w-5 shrink-0" />
<Skeleton className="h-5 w-5 shrink-0" />
<Skeleton className="h-4 flex-1 max-w-48" />
<Skeleton className="h-5 w-8 rounded-full" />
</div>
))}
</div>
</div>
</div>
)
}
+380 -119
View File
@@ -1,130 +1,391 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
import { Package } from "lucide-react";
import dynamic from 'next/dynamic'
import { redirect } from 'next/navigation'
import { CatalogTree } from '@/components/admin/catalog-tree'
import { Prisma } from '@/generated/prisma/client'
import { calcPagination, parseListParams } from '@/lib/admin-helpers'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { CatalogActions } from './catalog-actions'
import { CatalogTable } from './catalog-table'
import { CatalogViewToggle } from './catalog-view-toggle'
export const dynamic = "force-dynamic";
type CatalogPageRow = {
id: number;
caption: string;
parentId: number;
pageLayout: string;
minRank: number;
orderNum: number;
visible: string;
enabled: string;
};
export default async function AdminCatalog() {
const t = await getTranslations("pages.admin.catalog");
let pages: CatalogPageRow[] = [];
try {
pages = await prisma.catalogPages.findMany({
select: {
id: true,
caption: true,
parentId: true,
pageLayout: true,
minRank: true,
orderNum: true,
visible: true,
enabled: true,
},
orderBy: [{ parentId: "asc" }, { orderNum: "asc" }, { id: "asc" }],
take: 500,
});
} catch {
pages = [];
const CatalogManagerDialog = dynamic(() =>
import('@/components/admin/catalog-manager/catalog-manager-dialog').then((m) => ({
default: m.CatalogManagerDialog,
})),
)
export default async function CatalogPagesPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
await paramsPromise
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect('/admin')
}
const captionById = new Map<number, string>();
for (const p of pages) captionById.set(p.id, p.caption);
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
const visibleCount = pages.filter(
(p) => p.visible === "1" && p.enabled === "1",
).length;
const hiddenCount = pages.length - visibleCount;
const rootCount = pages.filter((p) => p.parentId <= 0).length;
const params = await searchParams
const sp = new URLSearchParams(params)
const { search, perPage, page, sort, order } = parseListParams(sp)
const viewMode = sp.get('view') || 'tree'
const catalogType = sp.get('catalog') || 'normal'
// ── Builder Club mode ──────────────────────────────────────────
type TreeNodeShape = {
id: number
caption: string
parentId: number
enabled: string
visible: string
iconImage: number
iconColor: number
pageLayout: string
childCount: number
itemCount: number
}
if (catalogType === 'bc') {
const [totalBcPages, totalBcItems, enabledBcPages] = await Promise.all([
prisma.catalog_pages_bc.count(),
prisma.catalog_items_bc.count(),
prisma.catalog_pages_bc.count({ where: { enabled: '1' } }),
])
// ── BC tree view ──────────────────────────────────────────────
let bcRootPages: TreeNodeShape[] = []
if (viewMode === 'tree') {
const bcRootRaw = await prisma.catalog_pages_bc.findMany({
where: { OR: [{ parent_id: -1 }, { parent_id: 0 }] },
orderBy: { order_num: 'asc' },
})
const bcRootIds = bcRootRaw.map((p) => p.id)
const [bcChildCounts, bcItemCounts] = await Promise.all([
bcRootIds.length > 0
? prisma.catalog_pages_bc.groupBy({
by: ['parent_id'],
where: { parent_id: { in: bcRootIds } },
_count: true,
})
: [],
bcRootIds.length > 0
? prisma.catalog_items_bc.groupBy({
by: ['page_id'],
where: { page_id: { in: bcRootIds } },
_count: true,
})
: [],
])
const bcChildMap = Object.fromEntries(bcChildCounts.map((c) => [c.parent_id, c._count]))
const bcItemMap = Object.fromEntries(bcItemCounts.map((c) => [c.page_id, c._count]))
bcRootPages = bcRootRaw.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parent_id,
enabled: String(p.enabled),
visible: String(p.visible),
iconImage: p.icon_image,
iconColor: p.icon_color,
pageLayout: p.page_layout,
childCount: bcChildMap[p.id] ?? 0,
itemCount: bcItemMap[p.id] ?? 0,
}))
}
// ── BC table view ─────────────────────────────────────────────
let bcRows: {
id: number
caption: string
parentId: number
parentCaption: string
pageLayout: string
enabled: string
visible: string
minRank: number
orderNum: number
itemCount: number
childCount: number
}[] = []
let bcPagination = { total: 0, page: 1, perPage, lastPage: 0 }
if (viewMode === 'table') {
const parentFilter = sp.get('parent')
const parentId = parentFilter !== null ? parseInt(parentFilter, 10) : undefined
const where: Record<string, unknown> = {}
const hasParent = parentId !== undefined && !Number.isNaN(parentId)
if (search) {
const pattern = { contains: search }
where.OR = [{ caption: pattern }]
}
if (hasParent) where.parent_id = parentId
// Prisma sort key is snake_case for BC model. Translate known keys.
const sortKeyMap: Record<string, string> = {
parentId: 'parent_id',
pageLayout: 'page_layout',
orderNum: 'order_num',
}
const sortKey = sort ? (sortKeyMap[sort] ?? sort) : 'order_num'
const orderBy = { [sortKey]: sort ? order : 'asc' }
const [pages, total] = await Promise.all([
prisma.catalog_pages_bc.findMany({
where,
orderBy,
skip: (page - 1) * perPage,
take: perPage,
}),
prisma.catalog_pages_bc.count({ where }),
])
bcPagination = calcPagination(total, page, perPage)
const pageIds = pages.map((p) => p.id)
const parentIds = [...new Set(pages.map((p) => p.parent_id).filter((id) => id > 0))]
const [childCounts, itemCounts, parentPages] = await Promise.all([
pageIds.length > 0
? prisma.catalog_pages_bc.groupBy({
by: ['parent_id'],
where: { parent_id: { in: pageIds } },
_count: true,
})
: [],
pageIds.length > 0
? prisma.catalog_items_bc.groupBy({
by: ['page_id'],
where: { page_id: { in: pageIds } },
_count: true,
})
: [],
parentIds.length > 0
? prisma.catalog_pages_bc.findMany({
where: { id: { in: parentIds } },
select: { id: true, caption: true },
})
: [],
])
const childCountMap = Object.fromEntries(childCounts.map((c) => [c.parent_id, c._count]))
const itemCountMap = Object.fromEntries(itemCounts.map((c) => [c.page_id, c._count]))
const parentNameMap = Object.fromEntries(parentPages.map((p) => [p.id, p.caption]))
bcRows = pages.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parent_id,
parentCaption:
p.parent_id === -1 ? 'Root' : (parentNameMap[p.parent_id] ?? `#${p.parent_id}`),
pageLayout: String(p.page_layout),
enabled: String(p.enabled),
visible: String(p.visible),
minRank: 0, // BC pages have no min rank column
orderNum: p.order_num,
itemCount: itemCountMap[p.id] ?? 0,
childCount: childCountMap[p.id] ?? 0,
}))
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Catalog Pages</h1>
<p className="text-muted-foreground">
{totalBcPages} BC pages ({enabledBcPages} enabled) &middot; {totalBcItems} items
</p>
</div>
<div className="flex items-center gap-2">
<CatalogViewToggle currentView={viewMode} catalogType="bc" />
{canEdit && <CatalogActions catalogType="bc" />}
</div>
</div>
{viewMode === 'tree' ? (
<CatalogTree rootPages={bcRootPages} catalogType="bc" />
) : (
<CatalogTable
data={{ rows: bcRows, ...bcPagination }}
canEdit={canEdit}
catalogType="bc"
/>
)}
</div>
)
}
// ── Normal catalog mode ────────────────────────────────────────
// Global stats (lightweight counts)
const [totalPages, totalItems, enabledPages] = await Promise.all([
prisma.catalogPage.count(),
prisma.catalogItem.count(),
prisma.catalogPage.count({ where: { enabled: '1' } }),
])
// ── Tree view data ──────────────────────────────────────────────
let rootPages: TreeNodeShape[] = []
if (viewMode === 'tree') {
const rootPagesRaw = await prisma.catalogPage.findMany({
where: { parentId: -1 },
orderBy: { orderNum: 'asc' },
})
const rootIds = rootPagesRaw.map((p) => p.id)
const [rootChildCounts, rootItemCounts] = await Promise.all([
rootIds.length > 0
? prisma.catalogPage.groupBy({
by: ['parentId'],
where: { parentId: { in: rootIds } },
_count: true,
})
: [],
rootIds.length > 0
? prisma.catalogItem.groupBy({
by: ['pageId'],
where: { pageId: { in: rootIds } },
_count: true,
})
: [],
])
const rootChildMap = Object.fromEntries(rootChildCounts.map((c) => [c.parentId, c._count]))
const rootItemMap = Object.fromEntries(rootItemCounts.map((c) => [c.pageId, c._count]))
rootPages = rootPagesRaw.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parentId,
enabled: String(p.enabled),
visible: String(p.visible),
iconImage: p.iconImage,
iconColor: p.iconColor,
pageLayout: p.pageLayout,
childCount: rootChildMap[p.id] ?? 0,
itemCount: rootItemMap[p.id] ?? 0,
}))
}
// ── Table view data (skip if tree) ────────────────────────────
let rows: {
id: number
caption: string
parentId: number
parentCaption: string
pageLayout: string
enabled: string
visible: string
minRank: number
orderNum: number
itemCount: number
childCount: number
}[] = []
let pagination = { total: 0, page: 1, perPage, lastPage: 0 }
if (viewMode === 'table') {
const parentFilter = sp.get('parent')
const parentId = parentFilter !== null ? parseInt(parentFilter, 10) : undefined
const where: Record<string, unknown> = {}
const hasParent = parentId !== undefined && !Number.isNaN(parentId)
if (search) {
const searchPattern = `%${search}%`
const parentClause = hasParent ? Prisma.sql`AND cp.parent_id = ${parentId}` : Prisma.empty
const matchedIds = await prisma.$queryRaw<{ id: number }[]>(Prisma.sql`
SELECT DISTINCT cp.id FROM catalog_pages cp
LEFT JOIN catalog_items ci ON ci.page_id = cp.id
LEFT JOIN items_base ib ON FIND_IN_SET(ib.id, REPLACE(ci.item_ids, ';', ','))
WHERE (cp.caption LIKE ${searchPattern}
OR cp.page_layout LIKE ${searchPattern}
OR ci.catalog_name LIKE ${searchPattern}
OR ib.public_name LIKE ${searchPattern}
OR ib.item_name LIKE ${searchPattern})
${parentClause}
`)
where.id = { in: matchedIds.map((r) => r.id) }
} else if (hasParent) {
where.parentId = parentId
}
const orderBy = sort ? { [sort]: order } : { orderNum: 'asc' as const }
const [pages, total] = await Promise.all([
prisma.catalogPage.findMany({
where,
orderBy,
skip: (page - 1) * perPage,
take: perPage,
}),
prisma.catalogPage.count({ where }),
])
pagination = calcPagination(total, page, perPage)
// Count children and items per page, and resolve parent names in parallel
const pageIds = pages.map((p) => p.id)
const parentIds = [...new Set(pages.map((p) => p.parentId).filter((id) => id > 0))]
const [childCounts, itemCounts, parentPages] = await Promise.all([
pageIds.length > 0
? prisma.catalogPage.groupBy({
by: ['parentId'],
where: { parentId: { in: pageIds } },
_count: true,
})
: [],
pageIds.length > 0
? prisma.catalogItem.groupBy({
by: ['pageId'],
where: { pageId: { in: pageIds } },
_count: true,
})
: [],
parentIds.length > 0
? prisma.catalogPage.findMany({
where: { id: { in: parentIds } },
select: { id: true, caption: true },
})
: [],
])
const childCountMap = Object.fromEntries(childCounts.map((c) => [c.parentId, c._count]))
const itemCountMap = Object.fromEntries(itemCounts.map((c) => [c.pageId, c._count]))
const parentNameMap = Object.fromEntries(parentPages.map((p) => [p.id, p.caption]))
rows = pages.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parentId,
parentCaption: p.parentId === -1 ? 'Root' : (parentNameMap[p.parentId] ?? `#${p.parentId}`),
pageLayout: p.pageLayout,
enabled: p.enabled,
visible: p.visible,
minRank: p.minRank,
orderNum: p.orderNum,
itemCount: itemCountMap[p.id] ?? 0,
childCount: childCountMap[p.id] ?? 0,
}))
}
return (
<main>
<div className="flex items-center gap-3 mb-6">
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-[var(--color-primary)]/20 to-[var(--color-primary)]/5 grid place-items-center">
<Package size={20} className="text-[var(--color-primary)]" />
</div>
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle")}</p>
<h1 className="text-3xl font-bold tracking-tight">Catalog Pages</h1>
<p className="text-muted-foreground">
{totalPages} pages ({enabledPages} enabled) &middot; {totalItems} items
</p>
</div>
<div className="flex items-center gap-2">
<CatalogViewToggle currentView={viewMode} catalogType="normal" />
{canEdit && <CatalogManagerDialog />}
{canEdit && <CatalogActions />}
</div>
</div>
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("pages")} value={pages.length} icon="📚" />
<StatusCard label={t("visible")} value={visibleCount} state="ok" icon="👁️" />
<StatusCard
label={t("hidden")}
value={hiddenCount}
state={hiddenCount > 0 ? "warn" : "neutral"}
icon="🚫"
/>
<StatusCard label={t("rootPages")} value={rootCount} icon="🗂️" />
</div>
<section className="mt-6">
<h2>{t("pages")} ({pages.length})</h2>
{pages.length === 0 ? (
<p className="muted">{t("noPages")}</p>
) : (
<div style={{ overflowX: "auto" }}>
<table>
<thead>
<tr>
<th>{t("colId")}</th>
<th>{t("caption")}</th>
<th>{t("colParent")}</th>
<th>{t("colLayout")}</th>
<th>{t("colMinRank")}</th>
<th>{t("colOrder")}</th>
<th>{t("colStatus")}</th>
</tr>
</thead>
<tbody>
{pages.map((p) => {
const parentName =
p.parentId > 0 ? captionById.get(p.parentId) : null;
const hidden = p.visible !== "1" || p.enabled !== "1";
return (
<tr key={p.id}>
<td className="muted">{p.id}</td>
<td>
<Link href={`/admin/catalog/${p.id}`}>{p.caption}</Link>
</td>
<td className="muted">
{p.parentId <= 0
? "—"
: parentName
? `${parentName} (#${p.parentId})`
: `#${p.parentId}`}
</td>
<td className="muted">{p.pageLayout}</td>
<td>{p.minRank}</td>
<td>{p.orderNum}</td>
<td>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${hidden ? "bg-red-500/22 text-[var(--color-text)]" : "bg-green-600/20 text-[var(--color-text)]"}`}>
{hidden ? t("statusHidden") : t("statusVisible")}
</span>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</section>
</main>
);
{viewMode === 'tree' ? (
<CatalogTree rootPages={rootPages} catalogType="normal" />
) : (
<CatalogTable data={{ rows, ...pagination }} canEdit={canEdit} />
)}
</div>
)
}
+246 -72
View File
@@ -1,6 +1,6 @@
import os from "node:os";
import { getTranslations } from "next-intl/server";
import { Activity } from 'lucide-react';
import { Activity } from "lucide-react";
import {
hotelAlert,
updateCatalog,
@@ -58,21 +58,20 @@ function uptime(seconds: number): string {
export default async function CommandoCentrum() {
const t = await getTranslations("pages.admin.commandocentrum");
const [onlineCount, totalUsers, errors, dbOk, emulatorOnline, maintenance, activity] =
await Promise.all([
prisma.user.count({ where: { online: "1" } }).catch(() => 0),
prisma.user.count().catch(() => -1),
prisma.emulatorErrors.findMany({ orderBy: { timestamp: "desc" }, take: 50 }).catch(() => []),
prisma.websiteSetting
.count()
.then(() => true)
.catch(() => false),
rcon.send("ping", null).catch(() => false),
siteSettings.getBool("maintenance_enabled", false),
prisma.staffActivities
.findMany({ orderBy: { createdAt: "desc" }, take: 12 })
.catch(() => [] as Awaited<ReturnType<typeof prisma.staffActivities.findMany>>),
]);
const [onlineCount, totalUsers, errors, dbOk, emulatorOnline, maintenance, activity] = await Promise.all([
prisma.user.count({ where: { online: "1" } }).catch(() => 0),
prisma.user.count().catch(() => -1),
prisma.emulatorErrors.findMany({ orderBy: { timestamp: "desc" }, take: 50 }).catch(() => []),
prisma.websiteSetting
.count()
.then(() => true)
.catch(() => false),
rcon.send("ping", null).catch(() => false),
siteSettings.getBool("maintenance_enabled", false),
prisma.staffActivities
.findMany({ orderBy: { createdAt: "desc" }, take: 12 })
.catch(() => [] as Awaited<ReturnType<typeof prisma.staffActivities.findMany>>),
]);
const staffIds = Array.from(new Set(activity.map((a) => Number(a.userId)))).filter((n) => n > 0);
let nameById = new Map<number, string>();
@@ -100,7 +99,10 @@ export default async function CommandoCentrum() {
</div>
{/* ── Live status ────────────────────────────────────────── */}
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6" style={{ marginTop: "1.1rem" }}>
<div
className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6"
style={{ marginTop: "1.1rem" }}
>
<StatusCard
label={t("playersOnline")}
value={onlineCount}
@@ -134,10 +136,7 @@ export default async function CommandoCentrum() {
{/* ── Online users widget ───────────────────────────────── */}
<section className="admin-card mb-6">
<h2 className="admin-section-title">{t("onlineUsers")}</h2>
<OnlineUsersWidget
users={[]}
isLoading={false}
/>
<OnlineUsersWidget users={[]} isLoading={false} />
</section>
{/* ── Server info + diagnostics ──────────────────────────── */}
@@ -198,9 +197,7 @@ export default async function CommandoCentrum() {
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<form action={updateCatalog} className="admin-card">
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("updateCatalog")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-4">
{t("updateCatalogDesc")}
</p>
<p className="text-xs text-[var(--color-text-muted)] mb-4">{t("updateCatalogDesc")}</p>
<button type="submit" className="btn btn-primary">
{t("updateCatalog")}
</button>
@@ -208,9 +205,7 @@ export default async function CommandoCentrum() {
<form action={updateWordFilter} className="admin-card">
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("updateWordFilter")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-4">
{t("updateWordFilterDesc")}
</p>
<p className="text-xs text-[var(--color-text-muted)] mb-4">{t("updateWordFilterDesc")}</p>
<button type="submit" className="btn btn-primary">
{t("updateWordFilter")}
</button>
@@ -218,9 +213,7 @@ export default async function CommandoCentrum() {
<form action={updateNavigator} className="admin-card">
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("updateNavigator")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-4">
{t("updateNavigatorDesc")}
</p>
<p className="text-xs text-[var(--color-text-muted)] mb-4">{t("updateNavigatorDesc")}</p>
<button type="submit" className="btn btn-primary">
{t("updateNavigator")}
</button>
@@ -229,9 +222,7 @@ export default async function CommandoCentrum() {
<form action={hotelAlert} className="admin-card mt-6">
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("hotelAlert")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">
{t("hotelAlertDesc")}
</p>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("hotelAlertDesc")}</p>
<div className="flex gap-2">
<input
name="message"
@@ -250,18 +241,31 @@ export default async function CommandoCentrum() {
{/* ── User RCON actions ──────────────────────────────────── */}
<section className="mt-6">
<h2 className="admin-section-title">{t("userActions")}</h2>
<p className="text-xs text-[var(--color-text-muted)] mb-4">
{t("userActionsDesc")}
</p>
<p className="text-xs text-[var(--color-text-muted)] mb-4">{t("userActionsDesc")}</p>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<form action={disconnectUser} className="admin-card">
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("actions.disconnect")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("disconnectDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="username" type="text" placeholder={t("usernameRequired")} required className="w-full" />
<button type="submit" className="btn btn-danger w-full">{t("actions.disconnect")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="username"
type="text"
placeholder={t("usernameRequired")}
required
className="w-full"
/>
<button type="submit" className="btn btn-danger w-full">
{t("actions.disconnect")}
</button>
</div>
</form>
@@ -269,9 +273,25 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("actions.alert")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("alertDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="message" type="text" placeholder={t("alertMessage")} required maxLength={512} className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("actions.alert")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="message"
type="text"
placeholder={t("alertMessage")}
required
maxLength={512}
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("actions.alert")}
</button>
</div>
</form>
@@ -279,9 +299,25 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("forwardToRoom")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("forwardDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="roomId" type="number" min={1} placeholder={t("roomId")} required className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("forwardUser")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="roomId"
type="number"
min={1}
placeholder={t("roomId")}
required
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("forwardUser")}
</button>
</div>
</form>
</div>
@@ -291,9 +327,25 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("giveCredits")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("giveCreditsDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="credits" type="number" min={1} placeholder={t("amount")} required className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("giveCredits")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="credits"
type="number"
min={1}
placeholder={t("amount")}
required
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("giveCredits")}
</button>
</div>
</form>
@@ -301,9 +353,25 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("giveDuckets")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("giveDucketsDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="amount" type="number" min={1} placeholder={t("amount")} required className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("giveDuckets")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="amount"
type="number"
min={1}
placeholder={t("amount")}
required
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("giveDuckets")}
</button>
</div>
</form>
@@ -311,9 +379,25 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("giveDiamonds")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("giveDiamondsDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="amount" type="number" min={1} placeholder={t("amount")} required className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("giveDiamonds")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="amount"
type="number"
min={1}
placeholder={t("amount")}
required
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("giveDiamonds")}
</button>
</div>
</form>
</div>
@@ -323,9 +407,25 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("giveBadge")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("giveBadgeDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="badge" type="text" placeholder={t("badgeCode")} required maxLength={32} className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("giveBadge")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="badge"
type="text"
placeholder={t("badgeCode")}
required
maxLength={32}
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("giveBadge")}
</button>
</div>
</form>
@@ -333,9 +433,25 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("setMotto")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("setMottoDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="motto" type="text" placeholder={t("newMotto")} required maxLength={127} className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("setMotto")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="motto"
type="text"
placeholder={t("newMotto")}
required
maxLength={127}
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("setMotto")}
</button>
</div>
</form>
@@ -343,9 +459,26 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("setRank")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("setRankDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="rank" type="number" min={0} max={10} placeholder={t("rankPlaceholder")} required className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("setRank")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="rank"
type="number"
min={0}
max={10}
placeholder={t("rankPlaceholder")}
required
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("setRank")}
</button>
</div>
</form>
</div>
@@ -355,9 +488,25 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("executeCommand")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("executeCommandDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="command" type="text" placeholder={t("commandPlaceholder")} required maxLength={100} className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("execute")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="command"
type="text"
placeholder={t("commandPlaceholder")}
required
maxLength={100}
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("execute")}
</button>
</div>
</form>
@@ -365,10 +514,33 @@ export default async function CommandoCentrum() {
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("sendGift")}</h3>
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("sendGiftDesc")}</p>
<div className="space-y-2">
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
<input name="itemId" type="number" min={1} placeholder={t("furniId")} required className="w-full" />
<input name="message" type="text" placeholder={t("giftMessage")} maxLength={255} defaultValue={t("defaultGiftMessage")} className="w-full" />
<button type="submit" className="btn btn-primary w-full">{t("sendGift")}</button>
<input
name="userId"
type="number"
min={1}
placeholder={t("userId")}
required
className="w-full"
/>
<input
name="itemId"
type="number"
min={1}
placeholder={t("furniId")}
required
className="w-full"
/>
<input
name="message"
type="text"
placeholder={t("giftMessage")}
maxLength={255}
defaultValue={t("defaultGiftMessage")}
className="w-full"
/>
<button type="submit" className="btn btn-primary w-full">
{t("sendGift")}
</button>
</div>
</form>
</div>
@@ -398,7 +570,9 @@ export default async function CommandoCentrum() {
</td>
<td>{nameById.get(Number(a.userId)) ?? `#${a.userId}`}</td>
<td>
<span className="inline-block text-[0.6rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{a.action}</span>
<span className="inline-block text-[0.6rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{a.action}
</span>
</td>
<td className="text-sm text-gray-500 dark:text-gray-400">{a.description}</td>
</tr>
@@ -426,7 +600,7 @@ export default async function CommandoCentrum() {
</tr>
</thead>
<tbody>
{errors.map((e) => {
{errors.map((e) => {
const trace = decodeStacktrace(e.stacktrace);
const snippet = trace
? trace.split("\n").slice(0, 20).join("\n") +
+10 -6
View File
@@ -32,13 +32,15 @@ export default async function AdminEmailTemplates() {
</div>
</div>
<form
action={createEmailTemplate}
className="admin-card mb-6"
>
<form action={createEmailTemplate} className="admin-card mb-6">
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("newTemplate")}</h3>
<div className="flex gap-2 flex-wrap items-center mb-3">
<input name="name" placeholder={t("form.namePlaceholder")} required className="flex-1 min-w-[180px]" />
<input
name="name"
placeholder={t("form.namePlaceholder")}
required
className="flex-1 min-w-[180px]"
/>
<input
name="subject"
placeholder={t("form.subjectPlaceholder")}
@@ -108,7 +110,9 @@ export default async function AdminEmailTemplates() {
</button>
{template.updatedAt ? (
<span className="text-xs text-gray-500 dark:text-gray-400">
{t("updated", { date: new Date(template.updatedAt).toISOString().slice(0, 16).replace("T", " ") })}
{t("updated", {
date: new Date(template.updatedAt).toISOString().slice(0, 16).replace("T", " "),
})}
</span>
) : null}
</div>
+77 -113
View File
@@ -55,62 +55,46 @@ export default async function AdminEmulator() {
{t("keysCount", { count: settings.length })}
</p>
<form
action={updateEmulatorSetting}
className="admin-card mb-6"
>
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addOverwriteSetting")}</h3>
<div className="flex gap-2 flex-wrap">
<input name="key" placeholder={t("key")} maxLength={100} required />
<input
name="value"
placeholder={t("value")}
maxLength={512}
className="flex-1 min-w-[200px]"
/>
<button type="submit" className="btn btn-primary">
{t("save")}
</button>
</div>
</form>
<form action={updateEmulatorSetting} className="admin-card mb-6">
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addOverwriteSetting")}</h3>
<div className="flex gap-2 flex-wrap">
<input name="key" placeholder={t("key")} maxLength={100} required />
<input name="value" placeholder={t("value")} maxLength={512} className="flex-1 min-w-[200px]" />
<button type="submit" className="btn btn-primary">
{t("save")}
</button>
</div>
</form>
<table>
<thead>
<tr>
<th className="w-[320px]">{t("colKey")}</th>
<th>{t("colValue")}</th>
</tr>
</thead>
<tbody>
{settings.map((s) => (
<tr key={s.key}>
<td>
<strong>{s.key}</strong>
</td>
<td>
<form
action={updateEmulatorSetting}
className="flex gap-2"
>
<input type="hidden" name="key" value={s.key} />
<input
name="value"
defaultValue={s.value}
maxLength={512}
className="flex-1"
/>
<button type="submit" className="btn btn-outline">
{t("save")}
</button>
</form>
</td>
<table>
<thead>
<tr>
<th className="w-[320px]">{t("colKey")}</th>
<th>{t("colValue")}</th>
</tr>
))}
</tbody>
</table>
{settings.length === 0 ? (
<p className="text-xs text-gray-500 dark:text-gray-400">{t("noSettings")}</p>
) : null}
</thead>
<tbody>
{settings.map((s) => (
<tr key={s.key}>
<td>
<strong>{s.key}</strong>
</td>
<td>
<form action={updateEmulatorSetting} className="flex gap-2">
<input type="hidden" name="key" value={s.key} />
<input name="value" defaultValue={s.value} maxLength={512} className="flex-1" />
<button type="submit" className="btn btn-outline">
{t("save")}
</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
{settings.length === 0 ? (
<p className="text-xs text-gray-500 dark:text-gray-400">{t("noSettings")}</p>
) : null}
</section>
<section className="mt-6">
@@ -120,67 +104,47 @@ export default async function AdminEmulator() {
{textsTruncated ? ` (${t("showingFirst", { count: texts.length })})` : ""}.
</p>
<form
action={updateEmulatorText}
className="admin-card mb-6"
>
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addOverwriteText")}</h3>
<div className="flex gap-2 flex-wrap">
<input name="key" placeholder={t("key")} maxLength={100} required />
<input
name="value"
placeholder={t("value")}
maxLength={4096}
className="flex-1 min-w-[200px]"
/>
<button type="submit" className="btn btn-primary">
{t("save")}
</button>
</div>
</form>
<form action={updateEmulatorText} className="admin-card mb-6">
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addOverwriteText")}</h3>
<div className="flex gap-2 flex-wrap">
<input name="key" placeholder={t("key")} maxLength={100} required />
<input name="value" placeholder={t("value")} maxLength={4096} className="flex-1 min-w-[200px]" />
<button type="submit" className="btn btn-primary">
{t("save")}
</button>
</div>
</form>
<table>
<thead>
<tr>
<th className="w-[320px]">{t("colKey")}</th>
<th>{t("colValue")}</th>
</tr>
</thead>
<tbody>
{texts.map((txt) => (
<tr key={txt.key}>
<td>
<strong>{txt.key}</strong>
</td>
<td>
<form
action={updateEmulatorText}
className="flex gap-2"
>
<input type="hidden" name="key" value={txt.key} />
<input
name="value"
defaultValue={txt.value}
maxLength={4096}
className="flex-1"
/>
<button type="submit" className="btn btn-outline">
{t("save")}
</button>
</form>
</td>
<table>
<thead>
<tr>
<th className="w-[320px]">{t("colKey")}</th>
<th>{t("colValue")}</th>
</tr>
))}
</tbody>
</table>
{texts.length === 0 ? (
<div className="admin-empty">{t("noTexts")}</div>
) : null}
{textsTruncated ? (
<p className="muted">
{t("truncatedHint", { shown: texts.length, total: textsCount })}
</p>
) : null}
</thead>
<tbody>
{texts.map((txt) => (
<tr key={txt.key}>
<td>
<strong>{txt.key}</strong>
</td>
<td>
<form action={updateEmulatorText} className="flex gap-2">
<input type="hidden" name="key" value={txt.key} />
<input name="value" defaultValue={txt.value} maxLength={4096} className="flex-1" />
<button type="submit" className="btn btn-outline">
{t("save")}
</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
{texts.length === 0 ? <div className="admin-empty">{t("noTexts")}</div> : null}
{textsTruncated ? (
<p className="muted">{t("truncatedHint", { shown: texts.length, total: textsCount })}</p>
) : null}
</section>
</main>
);
+12 -3
View File
@@ -71,9 +71,18 @@ export function FaviconGenerator({ onSave }: Props) {
}
const swatches = [
"#6366f1", "#3b82f6", "#06b6d4", "#10b981",
"#f59e0b", "#ef4444", "#ec4899", "#8b5cf6",
"#1e1b4b", "#1f2937", "#000000", "#ffffff",
"#6366f1",
"#3b82f6",
"#06b6d4",
"#10b981",
"#f59e0b",
"#ef4444",
"#ec4899",
"#8b5cf6",
"#1e1b4b",
"#1f2937",
"#000000",
"#ffffff",
];
return (
+5 -11
View File
@@ -15,9 +15,7 @@ export default async function EditHelpQuestion({
}) {
const { id } = await params;
const { error } = await searchParams;
let entry: Awaited<
ReturnType<typeof prisma.websiteHelpCenterCategories.findUnique>
> = null;
let entry: Awaited<ReturnType<typeof prisma.websiteHelpCenterCategories.findUnique>> = null;
try {
entry = await prisma.websiteHelpCenterCategories.findUnique({
where: { id: BigInt(id) },
@@ -35,7 +33,9 @@ export default async function EditHelpQuestion({
</div>
<div className="flex-1">
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">Edit help-center entry</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/help-questions">← Help Center</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/help-questions">← Help Center</Link>
</p>
</div>
</div>
{error ? (
@@ -47,13 +47,7 @@ export default async function EditHelpQuestion({
<input type="hidden" name="id" value={String(entry.id)} />
<input name="name" defaultValue={entry.name} placeholder="Name / title" required maxLength={255} />
<textarea name="content" defaultValue={entry.content} placeholder="Content" rows={6} required />
<input
name="position"
type="number"
min={1}
defaultValue={entry.position}
placeholder="Position"
/>
<input name="position" type="number" min={1} defaultValue={entry.position} placeholder="Position" />
<input
name="imageUrl"
defaultValue={entry.imageUrl ?? ""}
+3 -1
View File
@@ -17,7 +17,9 @@ export default async function NewHelpQuestion({
</div>
<div className="flex-1">
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">New help-center entry</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/help-questions">← Help Center</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/help-questions">← Help Center</Link>
</p>
</div>
</div>
{error ? (
+7 -5
View File
@@ -8,9 +8,7 @@ export const dynamic = "force-dynamic";
export default async function AdminHelpQuestions() {
const t = await getTranslations("pages.admin.helpCenter");
let entries: Awaited<
ReturnType<typeof prisma.websiteHelpCenterCategories.findMany>
> = [];
let entries: Awaited<ReturnType<typeof prisma.websiteHelpCenterCategories.findMany>> = [];
try {
entries = await prisma.websiteHelpCenterCategories.findMany({
orderBy: [{ position: "asc" }, { id: "asc" }],
@@ -66,9 +64,13 @@ export default async function AdminHelpQuestions() {
<td>
<Link href={`/admin/help-questions/${e.id}`}>{e.name}</Link>
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{e.buttonText || "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{e.buttonText || "—"}
</td>
<td>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${e.smallBox ? "bg-green-600/20 text-[var(--color-text)]" : "bg-[var(--color-primary)]/18 text-[var(--color-text)]"}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${e.smallBox ? "bg-green-600/20 text-[var(--color-text)]" : "bg-[var(--color-primary)]/18 text-[var(--color-text)]"}`}
>
{e.smallBox ? "Yes" : "No"}
</span>
</td>
+56 -18
View File
@@ -16,9 +16,7 @@ export default async function AdminHousekeeping({
const q = (sp.q ?? "").trim();
const mode = sp.mode === "import" ? "import" : "manage";
let permissions: Awaited<
ReturnType<typeof prisma.websiteHousekeepingPermissions.findMany>
> = [];
let permissions: Awaited<ReturnType<typeof prisma.websiteHousekeepingPermissions.findMany>> = [];
try {
permissions = await prisma.websiteHousekeepingPermissions.findMany({
orderBy: [{ permission: "asc" }],
@@ -39,7 +37,10 @@ export default async function AdminHousekeeping({
if (mode === "import") {
const importRaw = String(sp.q ?? "");
if (importRaw) {
const importIds = importRaw.split(",").map((i) => Number(i.trim())).filter((i) => !isNaN(i));
const importIds = importRaw
.split(",")
.map((i) => Number(i.trim()))
.filter((i) => !isNaN(i));
importIds.forEach((id) => selectedIds.add(id));
}
}
@@ -64,11 +65,22 @@ export default async function AdminHousekeeping({
<div className="admin-filter-bar">
<form className="flex gap-2 flex-1">
<input name="q" defaultValue={q} placeholder={t("searchPermission")} className="flex-1 min-w-[200px]" />
<button type="submit" className="btn btn-primary">{t("search")}</button>
<input
name="q"
defaultValue={q}
placeholder={t("searchPermission")}
className="flex-1 min-w-[200px]"
/>
<button type="submit" className="btn btn-primary">
{t("search")}
</button>
</form>
<Link href="/admin/housekeeping?mode=manage" className="btn btn-outline">{t("manage")}</Link>
<Link href="/admin/housekeeping?mode=import&form=selected_ids" className="btn btn-outline">{t("importSelection")}</Link>
<Link href="/admin/housekeeping?mode=manage" className="btn btn-outline">
{t("manage")}
</Link>
<Link href="/admin/housekeeping?mode=import&form=selected_ids" className="btn btn-outline">
{t("importSelection")}
</Link>
</div>
{mode === "manage" ? (
@@ -77,22 +89,36 @@ export default async function AdminHousekeeping({
<form action={upsertPermission} className="admin-card">
<div className="flex gap-2 flex-wrap">
<input name="permission" placeholder={t("permissionKey")} required className="min-w-[200px]" />
<input name="minRank" type="number" min={0} placeholder={t("minRank")} required className="w-[110px]" />
<input
name="minRank"
type="number"
min={0}
placeholder={t("minRank")}
required
className="w-[110px]"
/>
<input name="description" placeholder={t("description")} className="flex-1 min-w-[160px]" />
<button type="submit" className="btn btn-primary">{t("save")}</button>
<button type="submit" className="btn btn-primary">
{t("save")}
</button>
</div>
</form>
</section>
) : (
<section>
<h2 className="admin-section-title">{t("importPermissions")}</h2>
<p className="text-xs text-[var(--color-text-muted)] -mt-2 mb-3">
{t("importHint")}
</p>
<p className="text-xs text-[var(--color-text-muted)] -mt-2 mb-3">{t("importHint")}</p>
<form action={upsertPermission} className="admin-card">
<div className="flex gap-2 flex-wrap">
<input name="q" placeholder={t("importPlaceholder")} required className="flex-1 min-w-[200px]" />
<button type="submit" className="btn btn-primary">{t("import")}</button>
<input
name="q"
placeholder={t("importPlaceholder")}
required
className="flex-1 min-w-[200px]"
/>
<button type="submit" className="btn btn-primary">
{t("import")}
</button>
</div>
</form>
</section>
@@ -100,7 +126,10 @@ export default async function AdminHousekeeping({
<section>
<h2 className="admin-section-title">
{t("permissions")} <span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{filtered.length}</span>
{t("permissions")}{" "}
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{filtered.length}
</span>
</h2>
{filtered.length === 0 ? (
<div className="admin-empty">{t("noPermissions")}</div>
@@ -118,8 +147,17 @@ export default async function AdminHousekeeping({
</thead>
<tbody>
{filtered.map((p, i) => (
<tr key={String(p.id)} style={mode === "import" && selectedIds.has(i) ? { backgroundColor: "color-mix(in srgb, var(--color-primary) 5%, transparent)" } : {}}>
<td className="muted" style={{ width: "40px" }}>{i + 1}</td>
<tr
key={String(p.id)}
style={
mode === "import" && selectedIds.has(i)
? { backgroundColor: "color-mix(in srgb, var(--color-primary) 5%, transparent)" }
: {}
}
>
<td className="muted" style={{ width: "40px" }}>
{i + 1}
</td>
<td>
<strong>{p.permission}</strong>
</td>
@@ -0,0 +1,108 @@
'use client'
import { Loader2 } from 'lucide-react'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { getBadgeData, updateBadge } from '@/actions/badges'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useServerAction } from '@/hooks/use-server-action'
interface BadgeEditorDialogProps {
code: string
open: boolean
onOpenChange: (open: boolean) => void
/** Called after a successful save so the parent can refresh state */
onSaved?: () => void
}
export function BadgeEditorDialog({ code, open, onOpenChange, onSaved }: BadgeEditorDialogProps) {
const [name, setName] = useState('')
const [desc, setDesc] = useState('')
const [loading, setLoading] = useState(false)
const { run, isPending: saving } = useServerAction()
// Fetch current values when dialog opens
useEffect(() => {
if (!open || !code) return
setLoading(true)
getBadgeData({ code })
.then((result) => {
if (result.ok) {
const data = result.data as { name: string; desc: string }
setName(data.name ?? '')
setDesc(data.desc ?? '')
}
})
.catch(() => {
toast.error('Failed to load badge data')
})
.finally(() => setLoading(false))
}, [open, code])
function handleSave() {
run(() => updateBadge({ code, name, desc }), {
successMessage: `Badge ${code} updated`,
errorMessage: 'Save failed',
onSuccess: () => {
onSaved?.()
onOpenChange(false)
},
})
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">Edit Badge — {code}</DialogTitle>
</DialogHeader>
{loading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="badge-name">Name</Label>
<Input
id="badge-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Badge name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="badge-desc">Description</Label>
<Input
id="badge-desc"
value={desc}
onChange={(e) => setDesc(e.target.value)}
placeholder="Badge description"
/>
</div>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
Cancel
</Button>
<Button onClick={handleSave} disabled={loading || saving}>
{saving && <Loader2 className="w-4 h-4 animate-spin mr-1" />}
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,496 @@
'use client'
import {
AlertCircle,
BadgeCheck,
Check,
CheckCircle2,
Download,
Globe,
Loader2,
Package,
Pencil,
Search,
X,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import { importBadgeFromRemote } from '@/actions/import-badges'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
import { BadgeEditorDialog } from './badge-editor-dialog'
interface BadgeItem {
id: number
code: string
name: string
description: string
hotel: string
url_habbo: string
url_habboassets: string
alreadyImported: boolean
}
const PAGE_SIZE = 100
export function ImportBadgesClient() {
const [searchTerm, setSearchTerm] = useState('')
const [activeSearch, setActiveSearch] = useState('')
const [badges, setBadges] = useState<BadgeItem[]>([])
const [offset, setOffset] = useState(0)
const [hasMore, setHasMore] = useState(false)
const [loading, setLoading] = useState(false)
const [importingCode, setImportingCode] = useState<string | null>(null)
const [error, setError] = useState('')
const [allHotels, setAllHotels] = useState(true)
const [editingCode, setEditingCode] = useState<string | null>(null)
const [selected, setSelected] = useState<Set<string>>(new Set())
const [batchImporting, setBatchImporting] = useState(false)
const searchRef = useRef<HTMLInputElement>(null)
const fetchBadges = useCallback(async (search: string, off: number, all: boolean) => {
setLoading(true)
setError('')
try {
const params = new URLSearchParams({ offset: String(off) })
if (search) params.set('search', search)
if (all) params.set('allHotels', '1')
const res = await fetch(`/api/admin/import/badges?${params}`)
const data = await res.json()
if (!res.ok) {
setError(data.error || 'Failed to load')
return
}
const list = data.badges || []
setBadges(list)
setHasMore(list.length >= PAGE_SIZE)
setSelected(new Set())
} catch {
setError('Network error')
} finally {
setLoading(false)
}
}, [])
// Auto-load on mount and when allHotels changes
// biome-ignore lint/correctness/useExhaustiveDependencies: explicitly chosen here, see surrounding code
useEffect(() => {
setOffset(0)
fetchBadges(activeSearch, 0, allHotels)
}, [fetchBadges, allHotels])
// "/" keyboard shortcut to focus search
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
if (e.key === '/' && !e.metaKey && !e.ctrlKey && !e.altKey) {
const tag = (e.target as HTMLElement)?.tagName
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return
e.preventDefault()
searchRef.current?.focus()
}
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [])
function doSearch() {
setActiveSearch(searchTerm)
setOffset(0)
fetchBadges(searchTerm, 0, allHotels)
}
function goPage(direction: 'prev' | 'next') {
const newOffset = direction === 'next' ? offset + PAGE_SIZE : Math.max(0, offset - PAGE_SIZE)
setOffset(newOffset)
fetchBadges(activeSearch, newOffset, allHotels)
}
async function doImport(badge: BadgeItem) {
setImportingCode(badge.code)
try {
const result = await importBadgeFromRemote({
code: badge.code,
name: badge.name,
description: badge.description,
})
if (result.ok) {
toast.success(`${badge.code} imported`)
setBadges((prev) =>
prev.map((b) => (b.code === badge.code ? { ...b, alreadyImported: true } : b)),
)
setSelected((prev) => {
const n = new Set(prev)
n.delete(badge.code)
return n
})
} else {
toast.error(result.error || `Failed to import ${badge.code}`)
}
} catch {
toast.error(`Network error importing ${badge.code}`)
} finally {
setImportingCode(null)
}
}
async function doBatchImport() {
const toImport = badges.filter((b) => selected.has(b.code) && !b.alreadyImported)
if (toImport.length === 0) return
setBatchImporting(true)
let ok = 0,
fail = 0
for (const badge of toImport) {
try {
const result = await importBadgeFromRemote({
code: badge.code,
name: badge.name,
description: badge.description,
})
if (result.ok) {
ok++
setBadges((prev) =>
prev.map((b) => (b.code === badge.code ? { ...b, alreadyImported: true } : b)),
)
} else {
fail++
}
} catch {
fail++
}
}
setBatchImporting(false)
setSelected(new Set())
if (ok > 0) toast.success(`${ok} badge(s) imported`)
if (fail > 0) toast.error(`${fail} failed`)
}
function toggleSelect(code: string) {
setSelected((prev) => {
const next = new Set(prev)
if (next.has(code)) next.delete(code)
else next.add(code)
return next
})
}
const importableBadges = useMemo(() => badges.filter((b) => !b.alreadyImported), [badges])
function toggleSelectAll() {
if (selected.size === importableBadges.length) {
setSelected(new Set())
} else {
setSelected(new Set(importableBadges.map((b) => b.code)))
}
}
// Stats
const importedCount = useMemo(() => badges.filter((b) => b.alreadyImported).length, [badges])
const currentPage = Math.floor(offset / PAGE_SIZE) + 1
return (
<TooltipProvider delayDuration={300}>
<div className="space-y-4">
{/* Stats bar */}
{badges.length > 0 && (
<div className="flex items-center gap-3 flex-wrap">
<div className="flex items-center gap-1.5 text-sm">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{badges.length}</span>
<span className="text-muted-foreground">results</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
<span className="font-medium text-emerald-600">{importedCount}</span>
<span className="text-muted-foreground">imported</span>
</div>
{importableBadges.length > 0 && (
<div className="flex items-center gap-1.5 text-sm">
<Download className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{importableBadges.length}</span>
<span className="text-muted-foreground">available</span>
</div>
)}
</div>
)}
{/* Search bar */}
<div className="flex gap-2">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
ref={searchRef}
placeholder="Search badges by name... /"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') doSearch()
if (e.key === 'Escape') {
setSearchTerm('')
searchRef.current?.blur()
}
}}
className="pl-9 pr-8"
/>
{searchTerm && (
<button
type="button"
onClick={() => {
setSearchTerm('')
setActiveSearch('')
fetchBadges('', 0, allHotels)
}}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
<Button onClick={doSearch} size="sm" disabled={loading}>
{loading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Search className="w-4 h-4" />
)}
</Button>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant={allHotels ? 'default' : 'outline'}
size="sm"
onClick={() => setAllHotels((v) => !v)}
>
<Globe className="w-4 h-4 mr-1" />
{allHotels ? 'All' : 'IT'}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>
{allHotels
? 'Showing all hotels — click for Italian only'
: 'Showing Italian only — click for all hotels'}
</p>
</TooltipContent>
</Tooltip>
</div>
{/* Bulk actions */}
{importableBadges.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<Button
variant="outline"
size="sm"
onClick={toggleSelectAll}
className="text-xs h-8"
disabled={batchImporting}
>
{selected.size === importableBadges.length
? 'Deselect All'
: `Select All (${importableBadges.length})`}
</Button>
{selected.size > 0 && (
<Button size="sm" className="h-8" onClick={doBatchImport} disabled={batchImporting}>
{batchImporting ? (
<Loader2 className="w-4 h-4 animate-spin mr-1" />
) : (
<Download className="w-4 h-4 mr-1" />
)}
Import {selected.size} selected
</Button>
)}
</div>
)}
{/* Error */}
{error && (
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
<AlertCircle className="w-4 h-4 shrink-0" />
{error}
</div>
)}
{/* Loading skeleton */}
{loading && badges.length === 0 && (
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
{Array.from({ length: 18 }).map((_, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: static skeleton placeholders
<div key={i} className="rounded-lg border bg-card p-3 animate-pulse">
<div className="h-12 w-12 bg-muted rounded mx-auto mb-2" />
<div className="h-4 bg-muted rounded w-3/4 mx-auto mb-1" />
<div className="h-3 bg-muted rounded w-1/2 mx-auto mb-2" />
<div className="h-7 bg-muted rounded" />
</div>
))}
</div>
)}
{/* Empty state */}
{!loading && badges.length === 0 && !error && (
<div className="text-center py-12 text-muted-foreground">
<BadgeCheck className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p className="text-sm">No badges found{activeSearch ? ` for "${activeSearch}"` : ''}</p>
{!activeSearch && <p className="text-xs mt-1">Try searching by badge name or code</p>}
</div>
)}
{/* Badge grid */}
{badges.length > 0 && (
<div
className={cn(
'grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3',
loading && 'opacity-50',
)}
>
{badges.map((badge) => {
const isSelected = selected.has(badge.code)
return (
<div
key={badge.code}
className={cn(
'rounded-lg border overflow-hidden bg-card group relative hover:border-border transition-all',
badge.alreadyImported && 'shadow-[0_0_6px_rgba(34,197,94,0.15)]',
isSelected && 'ring-2 ring-primary border-primary',
)}
>
{/* Checkbox for non-imported */}
{!badge.alreadyImported && (
<button
type="button"
onClick={() => toggleSelect(badge.code)}
className={cn(
'absolute top-1.5 left-1.5 z-10 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors',
isSelected
? 'bg-primary border-primary text-primary-foreground'
: 'bg-background/80 border-muted-foreground/30 hover:border-muted-foreground',
)}
>
{isSelected && <Check className="w-3 h-3" />}
</button>
)}
{/* Badge image area */}
<div className="flex items-center justify-center h-20 bg-accent/20">
<img
src={badge.url_habbo}
alt={badge.code}
className="image-pixelated drop-shadow-sm"
style={{ maxHeight: 48, maxWidth: 48 }}
onError={(e) => {
const img = e.target as HTMLImageElement
if (!img.dataset.fallback) {
img.dataset.fallback = '1'
img.src = badge.url_habboassets
} else {
img.style.opacity = '0.3'
}
}}
/>
</div>
{/* Info */}
<div className="px-2.5 py-2 border-t space-y-1">
<div className="text-xs font-bold truncate">{badge.code}</div>
{badge.name && (
<Tooltip>
<TooltipTrigger asChild>
<div className="text-[11px] text-muted-foreground truncate cursor-default">
{badge.name}
</div>
</TooltipTrigger>
<TooltipContent side="bottom" className="max-w-64">
<p className="font-medium">{badge.name}</p>
{badge.description && (
<p className="text-muted-foreground text-xs mt-1">
{badge.description}
</p>
)}
</TooltipContent>
</Tooltip>
)}
{allHotels && badge.hotel && (
<Badge variant="outline" className="text-[9px] px-1 h-4">
{badge.hotel.toUpperCase()}
</Badge>
)}
{/* Action */}
<div className="pt-1">
{badge.alreadyImported ? (
<div className="flex items-center gap-1">
<Badge className="text-[10px] px-1.5 py-0 bg-emerald-500/15 text-emerald-500 border-0 gap-0.5 flex-1 justify-center">
<Check className="w-2.5 h-2.5" />
Imported
</Badge>
<Button
variant="ghost"
size="sm"
className="h-5 w-5 p-0 shrink-0"
title="Edit badge name/description"
onClick={() => setEditingCode(badge.code)}
>
<Pencil className="w-3 h-3" />
</Button>
</div>
) : (
<Button
size="sm"
variant="outline"
className="w-full text-xs h-7"
onClick={() => doImport(badge)}
disabled={importingCode === badge.code || batchImporting}
>
{importingCode === badge.code ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
Import
</Button>
)}
</div>
</div>
</div>
)
})}
</div>
)}
{/* Pagination */}
{(offset > 0 || hasMore) && (
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Page {currentPage}</span>
<div className="flex gap-1">
<Button
variant="outline"
size="sm"
disabled={offset <= 0 || loading}
onClick={() => goPage('prev')}
>
&larr; Prev
</Button>
<Button
variant="outline"
size="sm"
disabled={!hasMore || loading}
onClick={() => goPage('next')}
>
Next &rarr;
</Button>
</div>
</div>
)}
{/* Badge Editor Dialog */}
<BadgeEditorDialog
code={editingCode ?? ''}
open={!!editingCode}
onOpenChange={(open) => {
if (!open) setEditingCode(null)
}}
/>
</div>
</TooltipProvider>
)
}
+21
View File
@@ -0,0 +1,21 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function ImportBadgesLoading() {
return (
<div className="space-y-6">
<div>
<Skeleton className="h-9 w-48" />
<Skeleton className="h-5 w-72 mt-2" />
</div>
<div className="rounded-lg border bg-card p-6 space-y-4">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-10 w-full" />
</div>
))}
<Skeleton className="h-10 w-24 mt-4" />
</div>
</div>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { ImportBadgesClient } from './import-badges-client'
export default async function ImportBadgesPage(_props: { params: Promise<{ locale: string }> }) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.SETTINGS_EDIT, session.user.rank)) {
redirect('/admin')
}
return <ImportBadgesClient />
}
@@ -0,0 +1,887 @@
'use client'
import {
AlertCircle,
Check,
CloudDownload,
Download,
Loader2,
Package,
Pencil,
Plus,
Search,
Trash2,
X,
} from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
// ── Types ─────────────────────────────────────────────────────────────────────
interface CloneSource {
id: string
name: string
furnidataUrl: string
nitroBaseUrl: string
iconBaseUrl: string
}
interface FurniItem {
classname: string
name: string
description?: string
revision?: number
category?: string
itemType: 's' | 'i'
xdim: number
ydim: number
present: boolean
}
interface CloneStats {
total: number
present: number
clonable: number
}
interface PageMeta {
page: number
perPage: number
total: number
}
// ── Shared SSE reader (mirrors import-clothing-client.tsx) ────────────────────
async function runSseImport(
url: string,
body: unknown,
onDone: (classname: string) => void,
onComplete: (succeeded: number, failed: number) => void,
): Promise<void> {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.body) {
toast.error('No response stream')
return
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buf = ''
let succeeded = 0
let failed = 0
while (true) {
const { value, done: streamDone } = await reader.read()
if (streamDone) break
buf += decoder.decode(value, { stream: true })
const parts = buf.split('\n\n')
buf = parts.pop() ?? ''
for (const part of parts) {
if (!part.startsWith('data: ')) continue
const evt = JSON.parse(part.slice(6))
if (evt.type === 'item_progress' && (evt.status === 'done' || evt.status === 'failed')) {
onDone(evt.classname)
}
if (evt.type === 'batch_complete') {
succeeded = evt.succeeded
failed = evt.failed
}
}
}
onComplete(succeeded, failed)
}
// ── Source form ───────────────────────────────────────────────────────────────
interface SourceFormProps {
initial?: Partial<CloneSource>
onSave: (src: Partial<CloneSource>) => Promise<void>
onCancel: () => void
saving: boolean
}
function SourceForm({ initial, onSave, onCancel, saving }: SourceFormProps) {
const [name, setName] = useState(initial?.name ?? '')
const [furnidataUrl, setFurnidataUrl] = useState(initial?.furnidataUrl ?? '')
const [nitroBaseUrl, setNitroBaseUrl] = useState(initial?.nitroBaseUrl ?? '')
const [iconBaseUrl, setIconBaseUrl] = useState(initial?.iconBaseUrl ?? '')
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
await onSave({ id: initial?.id, name, furnidataUrl, nitroBaseUrl, iconBaseUrl })
}
return (
<form onSubmit={handleSubmit} className="space-y-3 rounded-lg border p-4 bg-card">
<div className="text-sm font-medium">{initial?.id ? 'Edit Source' : 'Add Source'}</div>
<div className="grid gap-2">
<Input
placeholder="Name (e.g. HotelX)"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<Input
placeholder="FurnitureData URL (e.g. https://x/FurnitureData.json)"
value={furnidataUrl}
onChange={(e) => setFurnidataUrl(e.target.value)}
required
/>
<Input
placeholder="Nitro base URL (e.g. https://x/bundled/furniture)"
value={nitroBaseUrl}
onChange={(e) => setNitroBaseUrl(e.target.value)}
required
/>
<Input
placeholder="Icon base URL (e.g. https://x/icons)"
value={iconBaseUrl}
onChange={(e) => setIconBaseUrl(e.target.value)}
required
/>
</div>
<div className="flex gap-2">
<Button type="submit" size="sm" disabled={saving}>
{saving ? <Loader2 className="w-3 h-3 animate-spin mr-1" /> : null}
Save
</Button>
<Button type="button" variant="outline" size="sm" onClick={onCancel} disabled={saving}>
Cancel
</Button>
</div>
</form>
)
}
// ── Sources manager ───────────────────────────────────────────────────────────
interface SourcesManagerProps {
sources: CloneSource[]
activeSourceId: string | null
onSelect: (src: CloneSource) => void
onRefresh: () => Promise<void>
}
function SourcesManager({ sources, activeSourceId, onSelect, onRefresh }: SourcesManagerProps) {
const [showForm, setShowForm] = useState(false)
const [editSrc, setEditSrc] = useState<CloneSource | null>(null)
const [saving, setSaving] = useState(false)
const [deletingId, setDeletingId] = useState<string | null>(null)
async function handleSave(src: Partial<CloneSource>) {
setSaving(true)
try {
const res = await fetch('/api/admin/import/clone', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(src),
})
const data = await res.json()
if (!res.ok) {
toast.error(data.error || 'Save failed')
return
}
toast.success(src.id ? 'Source updated' : 'Source added')
setShowForm(false)
setEditSrc(null)
await onRefresh()
} finally {
setSaving(false)
}
}
async function handleDelete(src: CloneSource) {
setDeletingId(src.id)
try {
const res = await fetch(`/api/admin/import/clone?id=${encodeURIComponent(src.id)}`, {
method: 'DELETE',
})
const data = await res.json()
if (!res.ok) {
toast.error(data.error || 'Delete failed')
return
}
toast.success(`${src.name} removed`)
await onRefresh()
} finally {
setDeletingId(null)
}
}
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-muted-foreground">Clone Sources</span>
<Button
size="sm"
variant="outline"
className="h-7 text-xs"
onClick={() => {
setEditSrc(null)
setShowForm(true)
}}
>
<Plus className="w-3 h-3 mr-1" />
Add Source
</Button>
</div>
{showForm && !editSrc && (
<SourceForm onSave={handleSave} onCancel={() => setShowForm(false)} saving={saving} />
)}
{sources.length === 0 && !showForm && (
<div className="text-center py-6 text-muted-foreground text-sm">
<CloudDownload className="w-8 h-8 mx-auto mb-2 opacity-40" />
No sources yet. Add one to start cloning furni from another hotel.
</div>
)}
{sources.map((src) => (
<div key={src.id}>
{editSrc?.id === src.id ? (
<SourceForm
initial={src}
onSave={handleSave}
onCancel={() => setEditSrc(null)}
saving={saving}
/>
) : (
<div
className={cn(
'w-full rounded-lg border px-3 py-2.5 flex items-center gap-2 transition-colors hover:border-border',
activeSourceId === src.id && 'border-primary ring-1 ring-primary bg-primary/5',
)}
>
<button
type="button"
className="flex-1 min-w-0 flex items-center gap-2 text-left cursor-pointer"
onClick={() => onSelect(src)}
>
<CloudDownload className="w-4 h-4 text-muted-foreground shrink-0" />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium truncate">{src.name}</div>
<div className="text-xs text-muted-foreground truncate">{src.furnidataUrl}</div>
</div>
</button>
<div className="flex items-center gap-1 shrink-0">
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0"
title="Edit source"
onClick={() => {
setEditSrc(src)
setShowForm(false)
}}
>
<Pencil className="w-3 h-3" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-destructive hover:text-destructive"
title="Delete source"
disabled={deletingId === src.id}
onClick={() => handleDelete(src)}
>
{deletingId === src.id ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
<Trash2 className="w-3 h-3" />
)}
</Button>
</div>
</div>
)}
</div>
))}
</div>
)
}
// ── Furni icon with fallback ──────────────────────────────────────────────────
function FurniIcon({
sourceId,
iconBaseUrl,
classname,
}: {
sourceId: string
iconBaseUrl: string
classname: string
}) {
// 0 = source's standalone icon, 1 = icon extracted from the .nitro (our
// endpoint), 2 = give up and show a placeholder.
const [stage, setStage] = useState(0)
if (stage >= 2) {
return <Package className="w-8 h-8 text-muted-foreground/50" />
}
const src =
stage === 0
? `${iconBaseUrl}/${classname}_icon.png`
: `/api/admin/import/clone/icon?source=${encodeURIComponent(sourceId)}&classname=${encodeURIComponent(classname)}`
return (
// biome-ignore lint/performance/noImgElement: remote icon from clone source, not a Next asset
<img
key={stage}
src={src}
alt={classname}
className="max-h-full max-w-full object-contain image-pixelated"
onError={() => setStage((s) => s + 1)}
/>
)
}
// ── Furni grid view ───────────────────────────────────────────────────────────
interface FurniGridProps {
source: CloneSource
}
const PER_PAGE = 50
function FurniGrid({ source }: FurniGridProps) {
const [searchTerm, setSearchTerm] = useState('')
const [activeSearch, setActiveSearch] = useState('')
const [items, setItems] = useState<FurniItem[]>([])
const [stats, setStats] = useState<CloneStats | null>(null)
const [meta, setMeta] = useState<PageMeta | null>(null)
const [page, setPage] = useState(1)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [selected, setSelected] = useState<Set<string>>(new Set())
const [batchProgress, setBatchProgress] = useState<{ done: number; total: number } | null>(null)
const [busyClassname, setBusyClassname] = useState<string | null>(null)
const [filter, setFilter] = useState<'all' | 'missing' | 'present'>('all')
const fetchItems = useCallback(
async (search: string, pageNum: number, filterVal: 'all' | 'missing' | 'present' = 'all') => {
setLoading(true)
setError('')
try {
const params = new URLSearchParams({
source: source.id,
page: String(pageNum),
perPage: String(PER_PAGE),
})
if (search) params.set('search', search)
if (filterVal !== 'all') params.set('filter', filterVal)
const res = await fetch(`/api/admin/import/clone?${params}`)
const data = await res.json()
if (!res.ok) {
setError(data.error || 'Failed to load')
return
}
setItems(data.items || [])
setMeta(data.meta || null)
setStats(data.stats || null)
setSelected(new Set())
} catch {
setError('Network error')
} finally {
setLoading(false)
}
},
[source.id],
)
useEffect(() => {
setPage(1)
setSearchTerm('')
setActiveSearch('')
setItems([])
setStats(null)
setMeta(null)
setFilter('all')
fetchItems('', 1, 'all')
}, [fetchItems])
function doSearch() {
setActiveSearch(searchTerm)
setPage(1)
fetchItems(searchTerm, 1, filter)
}
function goPage(dir: 'prev' | 'next') {
const next = dir === 'next' ? page + 1 : Math.max(1, page - 1)
setPage(next)
fetchItems(activeSearch, next, filter)
}
function changeFilter(f: 'all' | 'missing' | 'present') {
setFilter(f)
setPage(1)
fetchItems(activeSearch, 1, f)
}
const importable = items.filter((it) => !it.present)
const total = meta?.total ?? 0
const lastPage = Math.max(Math.ceil(total / PER_PAGE), 1)
function toggle(classname: string) {
setSelected((prev) => {
const n = new Set(prev)
if (n.has(classname)) n.delete(classname)
else n.add(classname)
return n
})
}
function markDone(classname: string) {
setItems((prev) =>
prev.map((it) => (it.classname === classname ? { ...it, present: true } : it)),
)
}
async function cloneViaSse(toClone: FurniItem[]) {
setBatchProgress({ done: 0, total: toClone.length })
let done = 0
await runSseImport(
'/api/admin/import/clone/batch',
{ sourceId: source.id, classnames: toClone.map((it) => it.classname), concurrency: 2 },
(classname) => {
done++
markDone(classname)
setBatchProgress({ done, total: toClone.length })
},
(succeeded, failed) => {
setBatchProgress(null)
setSelected(new Set())
if (succeeded > 0) toast.success(`${succeeded} furni cloned`)
if (failed > 0) toast.error(`${failed} failed`)
// Refresh stats after batch
fetchItems(activeSearch, page, filter)
},
)
setBatchProgress(null)
}
async function cloneOne(it: FurniItem) {
setBusyClassname(it.classname)
try {
await cloneViaSse([it])
} finally {
setBusyClassname(null)
}
}
async function cloneSelected() {
const toClone = items.filter((it) => selected.has(it.classname) && !it.present)
if (toClone.length === 0) return
await cloneViaSse(toClone)
}
// Clone EVERY not-yet-present furni from the source (across all pages),
// in chunks of 400 to stay under the batch endpoint's 500 cap.
async function cloneAll() {
let names: string[] = []
try {
const res = await fetch(
`/api/admin/import/clone?source=${encodeURIComponent(source.id)}&action=clonable`,
)
const data = await res.json()
if (!res.ok) {
toast.error(data.error || 'Failed to load clonable list')
return
}
names = data.classnames || []
} catch {
toast.error('Network error')
return
}
if (names.length === 0) {
toast.info('Nothing to clone — everything is already present')
return
}
if (
!window.confirm(
`Clone ALL ${names.length} furni from "${source.name}"? This can take a while.`,
)
) {
return
}
const CHUNK = 400
setBatchProgress({ done: 0, total: names.length })
let done = 0
let okCount = 0
let failCount = 0
for (let i = 0; i < names.length; i += CHUNK) {
const chunk = names.slice(i, i + CHUNK)
await runSseImport(
'/api/admin/import/clone/batch',
{ sourceId: source.id, classnames: chunk, concurrency: 2 },
(classname) => {
done++
markDone(classname)
setBatchProgress({ done, total: names.length })
},
(succeeded, failed) => {
okCount += succeeded
failCount += failed
},
)
}
setBatchProgress(null)
setSelected(new Set())
if (okCount > 0) toast.success(`${okCount} furni cloned`)
if (failCount > 0) toast.error(`${failCount} failed`)
fetchItems(activeSearch, page, filter)
}
return (
<div className="space-y-4">
{/* Stats bar */}
{stats && (
<div className="flex items-center gap-3 flex-wrap">
<div className="flex items-center gap-1.5 text-sm">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{stats.total}</span>
<span className="text-muted-foreground">total</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Check className="h-4 w-4 text-emerald-500" />
<span className="font-medium text-emerald-600">{stats.present}</span>
<span className="text-muted-foreground">present</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Download className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{stats.clonable}</span>
<span className="text-muted-foreground">clonable</span>
</div>
</div>
)}
{/* Search bar */}
<div className="flex gap-2 flex-wrap">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search by classname or name…"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') doSearch()
if (e.key === 'Escape') {
setSearchTerm('')
setActiveSearch('')
setPage(1)
fetchItems('', 1, filter)
}
}}
className="pl-9 pr-8"
/>
{searchTerm && (
<button
type="button"
onClick={() => {
setSearchTerm('')
setActiveSearch('')
setPage(1)
fetchItems('', 1, filter)
}}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
<Button onClick={doSearch} size="sm" disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
</Button>
</div>
{/* Filter: all / not-present / present */}
<div className="flex items-center gap-1 flex-wrap">
{(
[
{ key: 'all', label: 'All', count: stats?.total },
{ key: 'missing', label: "Not present (don't have)", count: stats?.clonable },
{ key: 'present', label: 'Present', count: stats?.present },
] as const
).map((f) => (
<Button
key={f.key}
type="button"
size="sm"
variant={filter === f.key ? 'default' : 'outline'}
className="h-7 text-xs"
disabled={loading || !!batchProgress}
onClick={() => changeFilter(f.key)}
>
{f.label}
{typeof f.count === 'number' ? ` (${f.count})` : ''}
</Button>
))}
</div>
{/* Bulk actions */}
{(importable.length > 0 || (stats?.clonable ?? 0) > 0) && (
<div className="flex items-center gap-2 flex-wrap">
{importable.length > 0 && (
<Button
variant="outline"
size="sm"
className="text-xs h-8"
disabled={!!batchProgress}
onClick={() =>
setSelected((prev) =>
prev.size === importable.length
? new Set()
: new Set(importable.map((it) => it.classname)),
)
}
>
{selected.size === importable.length
? 'Deselect page'
: `Select page (${importable.length})`}
</Button>
)}
{selected.size > 0 && (
<Button
variant="outline"
size="sm"
className="h-8"
onClick={cloneSelected}
disabled={!!batchProgress}
>
{batchProgress ? (
<Loader2 className="w-4 h-4 animate-spin mr-1" />
) : (
<CloudDownload className="w-4 h-4 mr-1" />
)}
Clone {selected.size} selected
</Button>
)}
{(stats?.clonable ?? 0) > 0 && (
<Button size="sm" className="h-8" onClick={cloneAll} disabled={!!batchProgress}>
{batchProgress ? (
<Loader2 className="w-4 h-4 animate-spin mr-1" />
) : (
<CloudDownload className="w-4 h-4 mr-1" />
)}
Clone all clonable ({stats?.clonable})
</Button>
)}
{batchProgress && (
<span className="text-xs text-muted-foreground">
{batchProgress.done}/{batchProgress.total}
</span>
)}
</div>
)}
{/* Error */}
{error && (
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
<AlertCircle className="w-4 h-4 shrink-0" />
{error}
</div>
)}
{/* Empty state */}
{!loading && items.length === 0 && !error && (
<div className="text-center py-12 text-muted-foreground">
<CloudDownload className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p className="text-sm">No furni found{activeSearch ? ` for "${activeSearch}"` : ''}</p>
</div>
)}
{/* Grid */}
{items.length > 0 && (
<div
className={cn(
'grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3',
loading && 'opacity-50',
)}
>
{items.map((it) => {
const isSelected = selected.has(it.classname)
return (
<div
key={it.classname}
className={cn(
'group rounded-lg border overflow-hidden bg-card relative hover:border-border transition-all',
it.present && 'shadow-[0_0_6px_rgba(34,197,94,0.15)]',
isSelected && 'ring-2 ring-primary border-primary',
)}
>
{!it.present && (
<button
type="button"
onClick={() => toggle(it.classname)}
className={cn(
'absolute top-1.5 left-1.5 z-10 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors',
isSelected
? 'bg-primary border-primary text-primary-foreground'
: 'bg-background/80 border-muted-foreground/30 hover:border-muted-foreground',
)}
>
{isSelected && <Check className="w-3 h-3" />}
</button>
)}
{/* Type badge */}
<div className="absolute top-1.5 right-1.5 z-10">
<Badge variant="outline" className="text-[9px] px-1 py-0 bg-background/80">
{it.itemType === 's' ? 'floor' : 'wall'}
</Badge>
</div>
<div className="relative flex items-center justify-center h-28 bg-accent/20">
<FurniIcon
sourceId={source.id}
iconBaseUrl={source.iconBaseUrl}
classname={it.classname}
/>
{/* Hover detail tooltip */}
<div className="absolute bottom-1 left-1 right-1 z-10 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
<div className="bg-black/80 backdrop-blur-sm rounded px-2 py-1.5 text-[10px] text-white space-y-0.5">
{it.description ? <p className="truncate">{it.description}</p> : null}
<div className="flex gap-2 text-white/70">
{it.revision ? <span>Rev: {it.revision}</span> : null}
<span>{it.itemType === 's' ? 'Floor' : 'Wall'}</span>
<span>
{it.xdim}×{it.ydim}
</span>
</div>
</div>
</div>
</div>
<div className="px-2.5 py-2 border-t space-y-1">
<div className="text-xs font-bold truncate" title={it.name}>
{it.name || it.classname}
</div>
<div className="text-[10px] text-muted-foreground truncate" title={it.classname}>
{it.classname}
</div>
<div className="text-[10px] text-muted-foreground truncate">
{it.itemType === 's' ? 'Floor' : 'Wall'} · {it.category || 'other'}
</div>
<div className="pt-1">
{it.present ? (
<Badge className="text-[10px] px-1.5 py-0 bg-emerald-500/15 text-emerald-500 border-0 gap-0.5 w-full justify-center">
<Check className="w-2.5 h-2.5" />
Present
</Badge>
) : (
<Button
size="sm"
variant="outline"
className="w-full text-xs h-7"
disabled={busyClassname === it.classname || !!batchProgress}
onClick={() => cloneOne(it)}
>
{busyClassname === it.classname ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<CloudDownload className="w-3 h-3 mr-1" />
)}
Clone
</Button>
)}
</div>
</div>
</div>
)
})}
</div>
)}
{/* Pagination */}
{total > PER_PAGE && (
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">
Page {page} / {lastPage}
</span>
<div className="flex gap-1">
<Button
variant="outline"
size="sm"
disabled={page <= 1 || loading}
onClick={() => goPage('prev')}
>
&larr; Prev
</Button>
<Button
variant="outline"
size="sm"
disabled={page >= lastPage || loading}
onClick={() => goPage('next')}
>
Next &rarr;
</Button>
</div>
</div>
)}
</div>
)
}
// ── Root component ────────────────────────────────────────────────────────────
export function ImportCloneClient() {
const [sources, setSources] = useState<CloneSource[]>([])
const [activeSource, setActiveSource] = useState<CloneSource | null>(null)
const [loadingSources, setLoadingSources] = useState(true)
const fetchSources = useCallback(async () => {
try {
const res = await fetch('/api/admin/import/clone?action=sources')
const data = await res.json()
if (res.ok) {
setSources(data.sources || [])
}
} catch {
/* ignore */
} finally {
setLoadingSources(false)
}
}, [])
useEffect(() => {
fetchSources()
}, [fetchSources])
return (
<div className="space-y-6">
{/* Sources panel */}
<div className="rounded-xl border bg-card p-4 space-y-4">
{loadingSources ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" />
Loading sources…
</div>
) : (
<SourcesManager
sources={sources}
activeSourceId={activeSource?.id ?? null}
onSelect={setActiveSource}
onRefresh={fetchSources}
/>
)}
</div>
{/* Furni grid panel */}
{activeSource ? (
<div className="rounded-xl border bg-card p-4">
<div className="flex items-center gap-2 mb-4">
<CloudDownload className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium">{activeSource.name}</span>
</div>
<FurniGrid source={activeSource} />
</div>
) : (
<div className="rounded-xl border bg-card p-8 text-center text-muted-foreground text-sm">
Select a source above to browse and clone furni.
</div>
)}
</div>
)
}
+11
View File
@@ -0,0 +1,11 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { ImportCloneClient } from './import-clone-client'
export default async function ImportClonePage(_props: { params: Promise<{ locale: string }> }) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ASSETS_IMPORT, session.user.rank)) {
redirect('/admin')
}
return <ImportCloneClient />
}
@@ -0,0 +1,838 @@
'use client'
import {
AlertCircle,
Check,
Download,
Loader2,
Package,
Search,
Shirt,
Trash2,
X,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
// ── Shared types ─────────────────────────────────────────────────────────────
interface FigureItem {
lib: string
revision: number
nitroExists: boolean
previewType?: string
previewId?: number
}
interface ClothingSetItem {
setType: string
setId: number
gender: string
club: number
sellable: boolean
present: boolean
}
type Mode = 'libs' | 'sets'
const PER_PAGE = 100
// ── Shared SSE reader ─────────────────────────────────────────────────────────
async function runSseImport(
url: string,
body: unknown,
onDone: (label: string) => void,
onComplete: (succeeded: number, failed: number) => void,
): Promise<void> {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.body) {
toast.error('No response stream')
return
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buf = ''
let succeeded = 0
let failed = 0
while (true) {
const { value, done: streamDone } = await reader.read()
if (streamDone) break
buf += decoder.decode(value, { stream: true })
const parts = buf.split('\n\n')
buf = parts.pop() ?? ''
for (const part of parts) {
if (!part.startsWith('data: ')) continue
const evt = JSON.parse(part.slice(6))
if (evt.type === 'item_progress' && (evt.status === 'done' || evt.status === 'failed')) {
onDone(evt.classname)
}
if (evt.type === 'batch_complete') {
succeeded = evt.succeeded
failed = evt.failed
}
}
}
onComplete(succeeded, failed)
}
// ── Avatar preview (renders a mini avatar wearing the item) ───────────────────
// A default dressed avatar; the previewed part overrides/adds its slot so the
// item is shown on a complete figure.
const BASE_FIGURE: Record<string, string> = {
hd: 'hd-180-1',
hr: 'hr-828-45',
ch: 'ch-665-92',
lg: 'lg-700-82',
sh: 'sh-705-62',
}
// Head-worn slots → render head-only (zoomed) so the item fills the frame;
// everything else renders the full body.
const HEAD_TYPES = new Set(['hd', 'hr', 'ha', 'he', 'ea', 'fa', 'fc'])
function buildPreviewFigure(type: string, id: number): string {
const parts: Record<string, string> = { ...BASE_FIGURE }
parts[type] = `${type}-${id}` // default color
return Object.values(parts).join('.')
}
function AvatarPreview({ type, id }: { type?: string; id?: number }) {
const [failed, setFailed] = useState(false)
if (failed || !type || id === undefined) {
return <Shirt className="w-8 h-8 text-muted-foreground/60" />
}
const figure = buildPreviewFigure(type, id)
const headOnly = HEAD_TYPES.has(type) ? '&headonly=1' : ''
return (
// biome-ignore lint/performance/noImgElement: dynamic avatar imaging, not a Next asset
<img
src={`/api/imaging/avatar?figure=${encodeURIComponent(figure)}&size=l&direction=2&head_direction=3${headOnly}`}
alt={`${type}-${id}`}
className="max-h-full object-contain image-pixelated"
onError={() => setFailed(true)}
/>
)
}
// ── Librerie (v1) view ────────────────────────────────────────────────────────
function LibsView() {
const [searchTerm, setSearchTerm] = useState('')
const [activeSearch, setActiveSearch] = useState('')
const [items, setItems] = useState<FigureItem[]>([])
const [page, setPage] = useState(1)
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [selected, setSelected] = useState<Set<string>>(new Set())
const [batchProgress, setBatchProgress] = useState<{ done: number; total: number } | null>(null)
const [busyLib, setBusyLib] = useState<string | null>(null)
const fetchItems = useCallback(async (search: string, pageNum: number) => {
setLoading(true)
setError('')
try {
const params = new URLSearchParams({ page: String(pageNum) })
if (search) params.set('search', search)
const res = await fetch(`/api/admin/import/clothing?${params}`)
const data = await res.json()
if (!res.ok) {
setError(data.error || 'Failed to load')
return
}
setItems(data.items || [])
setTotal(data.meta?.total || 0)
setSelected(new Set())
} catch {
setError('Network error')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
fetchItems('', 1)
}, [fetchItems])
function doSearch() {
setActiveSearch(searchTerm)
setPage(1)
fetchItems(searchTerm, 1)
}
function goPage(dir: 'prev' | 'next') {
const next = dir === 'next' ? page + 1 : Math.max(1, page - 1)
setPage(next)
fetchItems(activeSearch, next)
}
const importable = useMemo(() => items.filter((p) => !p.nitroExists), [items])
const importedCount = useMemo(() => items.filter((p) => p.nitroExists).length, [items])
const lastPage = Math.max(Math.ceil(total / PER_PAGE), 1)
function toggle(lib: string) {
setSelected((prev) => {
const n = new Set(prev)
if (n.has(lib)) n.delete(lib)
else n.add(lib)
return n
})
}
function markDone(lib: string) {
setItems((prev) => prev.map((p) => (p.lib === lib ? { ...p, nitroExists: true } : p)))
}
async function importViaSse(toImport: FigureItem[]) {
setBatchProgress({ done: 0, total: toImport.length })
let done = 0
await runSseImport(
'/api/admin/import/clothing/batch',
{ items: toImport, concurrency: 3 },
(label) => {
done++
markDone(label)
setBatchProgress({ done, total: toImport.length })
},
(succeeded, failed) => {
setBatchProgress(null)
setSelected(new Set())
if (succeeded > 0) toast.success(`${succeeded} libraries imported`)
if (failed > 0) toast.error(`${failed} failed`)
},
)
setBatchProgress(null)
}
async function importOne(p: FigureItem) {
setBusyLib(p.lib)
try {
await importViaSse([p])
} finally {
setBusyLib(null)
}
}
async function importSelected() {
const toImport = items.filter((p) => selected.has(p.lib) && !p.nitroExists)
if (toImport.length === 0) return
await importViaSse(toImport)
}
async function remove(p: FigureItem) {
setBusyLib(p.lib)
try {
const res = await fetch(`/api/admin/import/clothing?lib=${encodeURIComponent(p.lib)}`, {
method: 'DELETE',
})
const data = await res.json()
if (res.ok) {
toast.success(`${p.lib} removed`)
setItems((prev) => prev.map((x) => (x.lib === p.lib ? { ...x, nitroExists: false } : x)))
} else {
toast.error(data.error || 'Delete failed')
}
} finally {
setBusyLib(null)
}
}
return (
<div className="space-y-4">
{(items.length > 0 || total > 0) && (
<div className="flex items-center gap-3 flex-wrap">
<div className="flex items-center gap-1.5 text-sm">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{total}</span>
<span className="text-muted-foreground">libraries</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Check className="h-4 w-4 text-emerald-500" />
<span className="font-medium text-emerald-600">{importedCount}</span>
<span className="text-muted-foreground">on this page</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Download className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{importable.length}</span>
<span className="text-muted-foreground">missing here</span>
</div>
</div>
)}
<div className="flex gap-2 flex-wrap">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search libraries (e.g. Hair_F, shirt_M)..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') doSearch()
if (e.key === 'Escape') {
setSearchTerm('')
setActiveSearch('')
setPage(1)
fetchItems('', 1)
}
}}
className="pl-9 pr-8"
/>
{searchTerm && (
<button
type="button"
onClick={() => {
setSearchTerm('')
setActiveSearch('')
setPage(1)
fetchItems('', 1)
}}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
<Button onClick={doSearch} size="sm" disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
</Button>
</div>
{importable.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<Button
variant="outline"
size="sm"
className="text-xs h-8"
disabled={!!batchProgress}
onClick={() =>
setSelected((prev) =>
prev.size === importable.length ? new Set() : new Set(importable.map((p) => p.lib)),
)
}
>
{selected.size === importable.length
? 'Deselect page'
: `Select page (${importable.length})`}
</Button>
{selected.size > 0 && (
<Button size="sm" className="h-8" onClick={importSelected} disabled={!!batchProgress}>
{batchProgress ? (
<Loader2 className="w-4 h-4 animate-spin mr-1" />
) : (
<Download className="w-4 h-4 mr-1" />
)}
Import {selected.size} selected
</Button>
)}
{batchProgress && (
<span className="text-xs text-muted-foreground">
{batchProgress.done}/{batchProgress.total}
</span>
)}
</div>
)}
{error && (
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
<AlertCircle className="w-4 h-4 shrink-0" />
{error}
</div>
)}
{!loading && items.length === 0 && !error && (
<div className="text-center py-12 text-muted-foreground">
<Shirt className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p className="text-sm">
No libraries found{activeSearch ? ` for "${activeSearch}"` : ''}
</p>
</div>
)}
{items.length > 0 && (
<div
className={cn(
'grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3',
loading && 'opacity-50',
)}
>
{items.map((p) => {
const isSelected = selected.has(p.lib)
return (
<div
key={p.lib}
className={cn(
'rounded-lg border overflow-hidden bg-card relative hover:border-border transition-all',
p.nitroExists && 'shadow-[0_0_6px_rgba(34,197,94,0.15)]',
isSelected && 'ring-2 ring-primary border-primary',
)}
>
{!p.nitroExists && (
<button
type="button"
onClick={() => toggle(p.lib)}
className={cn(
'absolute top-1.5 left-1.5 z-10 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors',
isSelected
? 'bg-primary border-primary text-primary-foreground'
: 'bg-background/80 border-muted-foreground/30 hover:border-muted-foreground',
)}
>
{isSelected && <Check className="w-3 h-3" />}
</button>
)}
<div className="flex items-center justify-center h-28 bg-accent/20">
<AvatarPreview type={p.previewType} id={p.previewId} />
</div>
<div className="px-2.5 py-2 border-t space-y-1">
<div className="text-xs font-bold truncate" title={p.lib}>
{p.lib}
</div>
<div className="pt-1">
{p.nitroExists ? (
<div className="flex items-center gap-1">
<Badge className="text-[10px] px-1.5 py-0 bg-emerald-500/15 text-emerald-500 border-0 gap-0.5 flex-1 justify-center">
<Check className="w-2.5 h-2.5" />
Imported
</Badge>
<Button
variant="ghost"
size="sm"
className="h-5 w-5 p-0 shrink-0"
title="Remove library"
disabled={busyLib === p.lib || !!batchProgress}
onClick={() => remove(p)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
) : (
<Button
size="sm"
variant="outline"
className="w-full text-xs h-7"
disabled={busyLib === p.lib || !!batchProgress}
onClick={() => importOne(p)}
>
{busyLib === p.lib ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
Import
</Button>
)}
</div>
</div>
</div>
)
})}
</div>
)}
{total > PER_PAGE && (
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">
Page {page} / {lastPage}
</span>
<div className="flex gap-1">
<Button
variant="outline"
size="sm"
disabled={page <= 1 || loading}
onClick={() => goPage('prev')}
>
&larr; Prev
</Button>
<Button
variant="outline"
size="sm"
disabled={page >= lastPage || loading}
onClick={() => goPage('next')}
>
Next &rarr;
</Button>
</div>
</div>
)}
</div>
)
}
// ── Vestiti / Sets (v2) view ──────────────────────────────────────────────────
function SetsView() {
const [searchTerm, setSearchTerm] = useState('')
const [activeSearch, setActiveSearch] = useState('')
const [items, setItems] = useState<ClothingSetItem[]>([])
const [page, setPage] = useState(1)
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [selected, setSelected] = useState<Set<string>>(new Set())
const [batchProgress, setBatchProgress] = useState<{ done: number; total: number } | null>(null)
const [busyKey, setBusyKey] = useState<string | null>(null)
function itemKey(it: ClothingSetItem): string {
return `${it.setType}-${it.setId}`
}
const fetchItems = useCallback(async (search: string, pageNum: number) => {
setLoading(true)
setError('')
try {
const params = new URLSearchParams({ page: String(pageNum) })
if (search) params.set('search', search)
const res = await fetch(`/api/admin/import/clothing/sets?${params}`)
const data = await res.json()
if (!res.ok) {
setError(data.error || 'Failed to load')
return
}
setItems(data.items || [])
setTotal(data.meta?.total || 0)
setSelected(new Set())
} catch {
setError('Network error')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
fetchItems('', 1)
}, [fetchItems])
function doSearch() {
setActiveSearch(searchTerm)
setPage(1)
fetchItems(searchTerm, 1)
}
function goPage(dir: 'prev' | 'next') {
const next = dir === 'next' ? page + 1 : Math.max(1, page - 1)
setPage(next)
fetchItems(activeSearch, next)
}
const importable = useMemo(() => items.filter((it) => !it.present), [items])
const presentCount = useMemo(() => items.filter((it) => it.present).length, [items])
const lastPage = Math.max(Math.ceil(total / PER_PAGE), 1)
function toggle(key: string) {
setSelected((prev) => {
const n = new Set(prev)
if (n.has(key)) n.delete(key)
else n.add(key)
return n
})
}
function markDone(label: string) {
setItems((prev) => prev.map((it) => (itemKey(it) === label ? { ...it, present: true } : it)))
}
async function importViaSse(toImport: ClothingSetItem[]) {
setBatchProgress({ done: 0, total: toImport.length })
let done = 0
await runSseImport(
'/api/admin/import/clothing/sets/batch',
{
items: toImport.map((it) => ({ setType: it.setType, setId: it.setId })),
concurrency: 3,
},
(label) => {
done++
markDone(label)
setBatchProgress({ done, total: toImport.length })
},
(succeeded, failed) => {
setBatchProgress(null)
setSelected(new Set())
if (succeeded > 0) toast.success(`${succeeded} sets imported`)
if (failed > 0) toast.error(`${failed} failed`)
},
)
setBatchProgress(null)
}
async function importOne(it: ClothingSetItem) {
const key = itemKey(it)
setBusyKey(key)
try {
await importViaSse([it])
} finally {
setBusyKey(null)
}
}
async function importSelected() {
const toImport = items.filter((it) => selected.has(itemKey(it)) && !it.present)
if (toImport.length === 0) return
await importViaSse(toImport)
}
return (
<div className="space-y-4">
{(items.length > 0 || total > 0) && (
<div className="flex items-center gap-3 flex-wrap">
<div className="flex items-center gap-1.5 text-sm">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{total}</span>
<span className="text-muted-foreground">sets</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Check className="h-4 w-4 text-emerald-500" />
<span className="font-medium text-emerald-600">{presentCount}</span>
<span className="text-muted-foreground">on this page</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Download className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{importable.length}</span>
<span className="text-muted-foreground">missing here</span>
</div>
</div>
)}
<div className="flex gap-2 flex-wrap">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search by set id or type (e.g. hr, ch, 1027)..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') doSearch()
if (e.key === 'Escape') {
setSearchTerm('')
setActiveSearch('')
setPage(1)
fetchItems('', 1)
}
}}
className="pl-9 pr-8"
/>
{searchTerm && (
<button
type="button"
onClick={() => {
setSearchTerm('')
setActiveSearch('')
setPage(1)
fetchItems('', 1)
}}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
<Button onClick={doSearch} size="sm" disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
</Button>
</div>
{importable.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<Button
variant="outline"
size="sm"
className="text-xs h-8"
disabled={!!batchProgress}
onClick={() =>
setSelected((prev) =>
prev.size === importable.length
? new Set()
: new Set(importable.map((it) => itemKey(it))),
)
}
>
{selected.size === importable.length
? 'Deselect page'
: `Select page (${importable.length})`}
</Button>
{selected.size > 0 && (
<Button size="sm" className="h-8" onClick={importSelected} disabled={!!batchProgress}>
{batchProgress ? (
<Loader2 className="w-4 h-4 animate-spin mr-1" />
) : (
<Download className="w-4 h-4 mr-1" />
)}
Import {selected.size} selected
</Button>
)}
{batchProgress && (
<span className="text-xs text-muted-foreground">
{batchProgress.done}/{batchProgress.total}
</span>
)}
</div>
)}
{error && (
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
<AlertCircle className="w-4 h-4 shrink-0" />
{error}
</div>
)}
{!loading && items.length === 0 && !error && (
<div className="text-center py-12 text-muted-foreground">
<Shirt className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p className="text-sm">No sets found{activeSearch ? ` for "${activeSearch}"` : ''}</p>
</div>
)}
{items.length > 0 && (
<div
className={cn(
'grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3',
loading && 'opacity-50',
)}
>
{items.map((it) => {
const key = itemKey(it)
const isSelected = selected.has(key)
return (
<div
key={key}
className={cn(
'rounded-lg border overflow-hidden bg-card relative hover:border-border transition-all',
it.present && 'shadow-[0_0_6px_rgba(34,197,94,0.15)]',
isSelected && 'ring-2 ring-primary border-primary',
)}
>
{!it.present && (
<button
type="button"
onClick={() => toggle(key)}
className={cn(
'absolute top-1.5 left-1.5 z-10 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors',
isSelected
? 'bg-primary border-primary text-primary-foreground'
: 'bg-background/80 border-muted-foreground/30 hover:border-muted-foreground',
)}
>
{isSelected && <Check className="w-3 h-3" />}
</button>
)}
<div className="flex items-center justify-center h-28 bg-accent/20">
<AvatarPreview type={it.setType} id={it.setId} />
</div>
<div className="px-2.5 py-2 border-t space-y-1">
<div className="text-xs font-bold truncate" title={key}>
{it.setType}-{it.setId}
</div>
<div className="flex items-center gap-1 flex-wrap">
<Badge variant="outline" className="text-[10px] px-1.5 py-0">
{it.gender}
</Badge>
{it.club > 0 && (
<Badge className="text-[10px] px-1.5 py-0 bg-yellow-500/20 text-yellow-600 border-0">
HC
</Badge>
)}
{it.sellable && (
<Badge className="text-[10px] px-1.5 py-0 bg-blue-500/15 text-blue-500 border-0">
$
</Badge>
)}
</div>
<div className="pt-1">
{it.present ? (
<Badge className="text-[10px] px-1.5 py-0 bg-emerald-500/15 text-emerald-500 border-0 gap-0.5 w-full justify-center">
<Check className="w-2.5 h-2.5" />
Imported
</Badge>
) : (
<Button
size="sm"
variant="outline"
className="w-full text-xs h-7"
disabled={busyKey === key || !!batchProgress}
onClick={() => importOne(it)}
>
{busyKey === key ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
Import
</Button>
)}
</div>
</div>
</div>
)
})}
</div>
)}
{total > PER_PAGE && (
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">
Page {page} / {lastPage}
</span>
<div className="flex gap-1">
<Button
variant="outline"
size="sm"
disabled={page <= 1 || loading}
onClick={() => goPage('prev')}
>
&larr; Prev
</Button>
<Button
variant="outline"
size="sm"
disabled={page >= lastPage || loading}
onClick={() => goPage('next')}
>
Next &rarr;
</Button>
</div>
</div>
)}
</div>
)
}
// ── Root component with mode toggle ──────────────────────────────────────────
export function ImportClothingClient() {
const [mode, setMode] = useState<Mode>('libs')
return (
<div className="space-y-4">
<div className="flex gap-1 rounded-lg border p-1 w-fit">
<Button
size="sm"
variant={mode === 'libs' ? 'default' : 'ghost'}
className="h-7 text-xs"
onClick={() => setMode('libs')}
>
Librerie
</Button>
<Button
size="sm"
variant={mode === 'sets' ? 'default' : 'ghost'}
className="h-7 text-xs"
onClick={() => setMode('sets')}
>
Vestiti (set)
</Button>
</div>
{mode === 'libs' ? <LibsView /> : <SetsView />}
</div>
)
}
+13
View File
@@ -0,0 +1,13 @@
export default function Loading() {
return (
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
{Array.from({ length: 18 }).map((_, i) => (
<div key={`figure-skeleton-${i}`} className="rounded-lg border bg-card p-3 animate-pulse">
<div className="h-12 w-12 bg-muted rounded mx-auto mb-2" />
<div className="h-4 bg-muted rounded w-3/4 mx-auto mb-1" />
<div className="h-7 bg-muted rounded" />
</div>
))}
</div>
)
}
+11
View File
@@ -0,0 +1,11 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { ImportClothingClient } from './import-clothing-client'
export default async function ImportClothingPage(_props: { params: Promise<{ locale: string }> }) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ASSETS_IMPORT, session.user.rank)) {
redirect('/admin')
}
return <ImportClothingClient />
}
@@ -0,0 +1,394 @@
// src/app/[locale]/admin/import/effects/import-effects-client.tsx
'use client'
import {
AlertCircle,
Check,
Download,
Loader2,
Music,
Package,
Search,
Sparkles,
Trash2,
X,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
interface EffectItem {
id: string
lib: string
type: string
revision: number
present: boolean
nitroExists: boolean
}
type Filter = 'all' | 'fx' | 'dance'
export function ImportEffectsClient() {
const [searchTerm, setSearchTerm] = useState('')
const [effects, setEffects] = useState<EffectItem[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [filter, setFilter] = useState<Filter>('all')
const [selected, setSelected] = useState<Set<string>>(new Set())
const [batchProgress, setBatchProgress] = useState<{ done: number; total: number } | null>(null)
const [busyLib, setBusyLib] = useState<string | null>(null)
const fetchEffects = useCallback(async (search: string) => {
setLoading(true)
setError('')
try {
const params = new URLSearchParams()
if (search) params.set('search', search)
const res = await fetch(`/api/admin/import/effects?${params}`)
const data = await res.json()
if (!res.ok) {
setError(data.error || 'Failed to load')
return
}
setEffects(data.effects || [])
setSelected(new Set())
} catch {
setError('Network error')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
fetchEffects('')
}, [fetchEffects])
const visible = useMemo(
() => effects.filter((e) => filter === 'all' || e.type === filter),
[effects, filter],
)
const importable = useMemo(() => visible.filter((e) => !e.present || !e.nitroExists), [visible])
const importedCount = useMemo(
() => visible.filter((e) => e.present && e.nitroExists).length,
[visible],
)
function toggle(lib: string) {
setSelected((prev) => {
const n = new Set(prev)
if (n.has(lib)) n.delete(lib)
else n.add(lib)
return n
})
}
function markDone(lib: string) {
setEffects((prev) =>
prev.map((e) => (e.lib === lib ? { ...e, present: true, nitroExists: true } : e)),
)
}
async function importViaSse(items: EffectItem[]) {
setBatchProgress({ done: 0, total: items.length })
const res = await fetch('/api/admin/import/effects/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items, concurrency: 3 }),
})
if (!res.body) {
toast.error('No response stream')
setBatchProgress(null)
return
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buf = ''
let done = 0
let succeeded = 0
let failed = 0
while (true) {
const { value, done: streamDone } = await reader.read()
if (streamDone) break
buf += decoder.decode(value, { stream: true })
const parts = buf.split('\n\n')
buf = parts.pop() ?? ''
for (const part of parts) {
if (!part.startsWith('data: ')) continue
const evt = JSON.parse(part.slice(6))
if (evt.type === 'item_progress' && evt.status === 'done') {
done++
succeeded++
markDone(evt.classname)
setBatchProgress({ done, total: items.length })
} else if (evt.type === 'item_progress' && evt.status === 'failed') {
done++
failed++
setBatchProgress({ done, total: items.length })
} else if (evt.type === 'batch_complete') {
succeeded = evt.succeeded
failed = evt.failed
}
}
}
setBatchProgress(null)
setSelected(new Set())
if (succeeded > 0) toast.success(`${succeeded} effect(s) imported`)
if (failed > 0) toast.error(`${failed} failed`)
}
async function importOne(e: EffectItem) {
setBusyLib(e.lib)
try {
await importViaSse([e])
} finally {
setBusyLib(null)
}
}
async function importSelected() {
const items = visible.filter((e) => selected.has(e.lib) && (!e.present || !e.nitroExists))
if (items.length === 0) return
await importViaSse(items)
}
async function remove(e: EffectItem) {
setBusyLib(e.lib)
try {
const res = await fetch(`/api/admin/import/effects?lib=${encodeURIComponent(e.lib)}`, {
method: 'DELETE',
})
const data = await res.json()
if (res.ok) {
toast.success(`${e.lib} removed`)
setEffects((prev) =>
prev.map((x) => (x.lib === e.lib ? { ...x, present: false, nitroExists: false } : x)),
)
} else {
toast.error(data.error || 'Delete failed')
}
} finally {
setBusyLib(null)
}
}
return (
<div className="space-y-4">
{/* Stats */}
{effects.length > 0 && (
<div className="flex items-center gap-3 flex-wrap">
<div className="flex items-center gap-1.5 text-sm">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{visible.length}</span>
<span className="text-muted-foreground">effects</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Check className="h-4 w-4 text-emerald-500" />
<span className="font-medium text-emerald-600">{importedCount}</span>
<span className="text-muted-foreground">imported</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Download className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{importable.length}</span>
<span className="text-muted-foreground">available</span>
</div>
</div>
)}
{/* Search + filter */}
<div className="flex gap-2 flex-wrap">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search effects by lib / id..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') fetchEffects(searchTerm)
if (e.key === 'Escape') {
setSearchTerm('')
fetchEffects('')
}
}}
className="pl-9 pr-8"
/>
{searchTerm && (
<button
type="button"
onClick={() => {
setSearchTerm('')
fetchEffects('')
}}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
<Button onClick={() => fetchEffects(searchTerm)} size="sm" disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
</Button>
{(['all', 'fx', 'dance'] as Filter[]).map((f) => (
<Button
key={f}
size="sm"
variant={filter === f ? 'default' : 'outline'}
onClick={() => setFilter(f)}
>
{f.toUpperCase()}
</Button>
))}
</div>
{/* Bulk actions */}
{importable.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<Button
variant="outline"
size="sm"
className="text-xs h-8"
disabled={!!batchProgress}
onClick={() =>
setSelected((prev) =>
prev.size === importable.length ? new Set() : new Set(importable.map((e) => e.lib)),
)
}
>
{selected.size === importable.length
? 'Deselect All'
: `Select All (${importable.length})`}
</Button>
{selected.size > 0 && (
<Button size="sm" className="h-8" onClick={importSelected} disabled={!!batchProgress}>
{batchProgress ? (
<Loader2 className="w-4 h-4 animate-spin mr-1" />
) : (
<Download className="w-4 h-4 mr-1" />
)}
Import {selected.size} selected
</Button>
)}
{batchProgress && (
<span className="text-xs text-muted-foreground">
{batchProgress.done}/{batchProgress.total}
</span>
)}
</div>
)}
{/* Error */}
{error && (
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
<AlertCircle className="w-4 h-4 shrink-0" />
{error}
</div>
)}
{/* Empty */}
{!loading && visible.length === 0 && !error && (
<div className="text-center py-12 text-muted-foreground">
<Sparkles className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p className="text-sm">No effects found</p>
</div>
)}
{/* Grid */}
{visible.length > 0 && (
<div
className={cn(
'grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3',
loading && 'opacity-50',
)}
>
{visible.map((e) => {
const imported = e.present && e.nitroExists
const isSelected = selected.has(e.lib)
return (
<div
key={e.lib}
className={cn(
'rounded-lg border overflow-hidden bg-card relative hover:border-border transition-all',
imported && 'shadow-[0_0_6px_rgba(34,197,94,0.15)]',
isSelected && 'ring-2 ring-primary border-primary',
)}
>
{!imported && (
<button
type="button"
onClick={() => toggle(e.lib)}
className={cn(
'absolute top-1.5 left-1.5 z-10 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors',
isSelected
? 'bg-primary border-primary text-primary-foreground'
: 'bg-background/80 border-muted-foreground/30 hover:border-muted-foreground',
)}
>
{isSelected && <Check className="w-3 h-3" />}
</button>
)}
<div
className={cn(
'flex flex-col items-center justify-center h-20 gap-1',
e.type === 'dance'
? 'bg-gradient-to-br from-amber-500/25 to-orange-500/10'
: 'bg-gradient-to-br from-violet-500/25 to-fuchsia-500/10',
)}
>
{e.type === 'dance' ? (
<Music className="w-7 h-7 text-amber-500/80" />
) : (
<Sparkles className="w-7 h-7 text-violet-500/80" />
)}
<span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
{e.type}
</span>
</div>
<div className="px-2.5 py-2 border-t space-y-1">
<div className="text-xs font-bold truncate">{e.lib}</div>
<div className="text-[10px] text-muted-foreground truncate">id {e.id}</div>
<div className="pt-1">
{imported ? (
<div className="flex items-center gap-1">
<Badge className="text-[10px] px-1.5 py-0 bg-emerald-500/15 text-emerald-500 border-0 gap-0.5 flex-1 justify-center">
<Check className="w-2.5 h-2.5" />
Imported
</Badge>
<Button
variant="ghost"
size="sm"
className="h-5 w-5 p-0 shrink-0"
title="Remove effect"
disabled={busyLib === e.lib || !!batchProgress}
onClick={() => remove(e)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
) : (
<Button
size="sm"
variant="outline"
className="w-full text-xs h-7"
disabled={busyLib === e.lib || !!batchProgress}
onClick={() => importOne(e)}
>
{busyLib === e.lib ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
Import
</Button>
)}
</div>
</div>
</div>
)
})}
</div>
)}
</div>
)
}
+14
View File
@@ -0,0 +1,14 @@
// src/app/[locale]/admin/import/effects/loading.tsx
export default function Loading() {
return (
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
{Array.from({ length: 18 }).map((_, i) => (
<div key={`effect-skeleton-${i}`} className="rounded-lg border bg-card p-3 animate-pulse">
<div className="h-12 w-12 bg-muted rounded mx-auto mb-2" />
<div className="h-4 bg-muted rounded w-3/4 mx-auto mb-1" />
<div className="h-7 bg-muted rounded" />
</div>
))}
</div>
)
}
+12
View File
@@ -0,0 +1,12 @@
// src/app/[locale]/admin/import/effects/page.tsx
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { ImportEffectsClient } from './import-effects-client'
export default async function ImportEffectsPage(_props: { params: Promise<{ locale: string }> }) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ASSETS_IMPORT, session.user.rank)) {
redirect('/admin')
}
return <ImportEffectsClient />
}
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function ImportFurniLoading() {
return (
<div className="space-y-6">
<div>
<Skeleton className="h-9 w-48" />
<Skeleton className="h-5 w-72 mt-2" />
</div>
<div className="rounded-lg border bg-card p-6 space-y-4">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-10 w-full" />
</div>
))}
<Skeleton className="h-10 w-24 mt-4" />
</div>
</div>
)
}
@@ -0,0 +1,755 @@
'use client'
import {
Box,
Check,
Compass,
Copy,
Eye,
Layers,
Loader2,
MousePointerClick,
Palette,
RotateCcw,
Ruler,
Save,
Sparkles,
} from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Textarea } from '@/components/ui/textarea'
interface NitroEditorDialogProps {
classname: string
open: boolean
onOpenChange: (open: boolean) => void
}
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
function updateNested(obj: any, path: string, value: unknown): any {
const clone = JSON.parse(JSON.stringify(obj))
const keys = path.split('.')
let current = clone
for (let i = 0; i < keys.length - 1; i++) {
if (!current[keys[i]]) current[keys[i]] = {}
current = current[keys[i]]
}
current[keys[keys.length - 1]] = value
return clone
}
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
function getNested(obj: any, path: string, fallback?: unknown): any {
const keys = path.split('.')
let current = obj
for (const key of keys) {
if (current == null || typeof current !== 'object') return fallback
current = current[key]
}
return current ?? fallback
}
const ALL_DIRECTIONS = [0, 1, 2, 3, 4, 5, 6, 7]
const DIR_LABELS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
function hexToColor(hex: string): string {
return `#${hex.padStart(6, '0')}`
}
function CopyClassname({ value }: { value: string }) {
const [copied, setCopied] = useState(false)
return (
<button
type="button"
className="flex items-center gap-1.5 font-mono text-sm text-muted-foreground mt-0.5 hover:text-foreground transition-colors"
onClick={() => {
navigator.clipboard.writeText(value)
setCopied(true)
setTimeout(() => setCopied(false), 1500)
}}
>
<span className="truncate">{value}</span>
{copied ? (
<Check className="w-3 h-3 text-green-500 shrink-0" />
) : (
<Copy className="w-3 h-3 shrink-0" />
)}
</button>
)
}
export function NitroEditorDialog({ classname, open, onOpenChange }: NitroEditorDialogProps) {
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
const [metadata, setMetadata] = useState<any>(null)
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
const [originalMetadata, setOriginalMetadata] = useState<any>(null)
const [jsonText, setJsonText] = useState('')
const [loading, setLoading] = useState(false)
const [saving, setSaving] = useState(false)
const [activeTab, setActiveTab] = useState<string>('visual')
const [flags, setFlags] = useState({ canstandon: false, cansiton: false, canlayon: false })
const [originalFlags, setOriginalFlags] = useState({
canstandon: false,
cansiton: false,
canlayon: false,
})
const [jsonError, setJsonError] = useState<string | null>(null)
const fetchMetadata = useCallback(async () => {
if (!classname) return
setLoading(true)
setJsonError(null)
try {
const res = await fetch(
`/api/admin/import/furni/nitro-editor?classname=${encodeURIComponent(classname)}`,
)
if (!res.ok) {
const err = await res.json().catch(() => ({}))
toast.error(err.error || 'Failed to load .nitro metadata')
onOpenChange(false)
return
}
const data = await res.json()
setMetadata(data.metadata)
setOriginalMetadata(JSON.parse(JSON.stringify(data.metadata)))
setJsonText(JSON.stringify(data.metadata, null, 2))
setFlags(data.flags)
setOriginalFlags({ ...data.flags })
} catch {
toast.error('Network error loading .nitro metadata')
onOpenChange(false)
} finally {
setLoading(false)
}
}, [classname, onOpenChange])
useEffect(() => {
if (open && classname) {
setActiveTab('visual')
fetchMetadata()
}
}, [open, classname, fetchMetadata])
const handleTabChange = (newTab: string) => {
if (activeTab === 'json' && newTab === 'visual') {
try {
const parsed = JSON.parse(jsonText)
setMetadata(parsed)
setJsonError(null)
} catch {
toast.error('Invalid JSON — fix it before switching to Visual tab')
return
}
} else if (activeTab === 'visual' && newTab === 'json') {
setJsonText(JSON.stringify(metadata, null, 2))
}
setActiveTab(newTab)
}
const handleReset = () => {
if (!originalMetadata) return
setMetadata(JSON.parse(JSON.stringify(originalMetadata)))
setFlags({ ...originalFlags })
setJsonText(JSON.stringify(originalMetadata, null, 2))
toast.info('Reset to original values')
}
const handleSave = async () => {
let metadataToSave = metadata
if (activeTab === 'json') {
try {
metadataToSave = JSON.parse(jsonText)
} catch {
toast.error('Invalid JSON')
return
}
}
setSaving(true)
try {
const res = await fetch('/api/admin/import/furni/nitro-editor', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
classname,
metadata: metadataToSave,
...flags,
}),
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
toast.error(err.error || 'Save failed')
return
}
toast.success('Nitro metadata salvato')
setMetadata(metadataToSave)
setOriginalMetadata(JSON.parse(JSON.stringify(metadataToSave)))
setOriginalFlags({ ...flags })
setJsonText(JSON.stringify(metadataToSave, null, 2))
} catch {
toast.error('Network error')
} finally {
setSaving(false)
}
}
// ── Visual tab helpers ──
const dims = metadata
? getNested(metadata, 'logic.model.dimensions', { x: 1, y: 1, z: 0 })
: { x: 1, y: 1, z: 0 }
const directions: number[] = metadata ? getNested(metadata, 'logic.model.directions', [0]) : [0]
const setDim = (axis: 'x' | 'y' | 'z', value: string) => {
const num = axis === 'z' ? parseFloat(value) || 0 : parseInt(value, 10) || 0
setMetadata((prev: unknown) => updateNested(prev, `logic.model.dimensions.${axis}`, num))
}
const toggleDirection = (dir: number) => {
const current: number[] = getNested(metadata, 'logic.model.directions', [0])
const next = current.includes(dir)
? current.filter((d: number) => d !== dir)
: [...current, dir].sort((a: number, b: number) => a - b)
if (next.length === 0) return
setMetadata((prev: unknown) => updateNested(prev, 'logic.model.directions', next))
}
// Get visualization with size=64 for layer/color editing
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
const viz64 = metadata?.visualizations?.find((v: any) => v.size === 64)
const viz64Index =
metadata?.visualizations?.findIndex((v: { size: number }) => v.size === 64) ?? -1
const layerCount = viz64?.layers ? Object.keys(viz64.layers).length : 0
const colorCount = viz64?.colors ? Object.keys(viz64.colors).length : 0
const animCount = viz64?.animations ? Object.keys(viz64.animations).length : 0
const handleJsonTextChange = (value: string) => {
setJsonText(value)
try {
JSON.parse(value)
setJsonError(null)
} catch (e) {
setJsonError((e as Error).message)
}
}
// Check if there are unsaved changes
const hasChanges =
metadata &&
originalMetadata &&
(JSON.stringify(metadata) !== JSON.stringify(originalMetadata) ||
JSON.stringify(flags) !== JSON.stringify(originalFlags))
// Furni preview URL
const starIdx = classname.indexOf('*')
const baseClassname = starIdx !== -1 ? classname.substring(0, starIdx) : classname
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-4xl max-h-[90vh] flex flex-col p-0 gap-0">
{/* Header with preview */}
<DialogHeader className="px-6 pt-5 pb-4 border-b bg-muted/30">
<div className="flex items-start gap-4">
{/* Furni preview */}
<div
className="w-20 h-20 rounded-lg border bg-card flex items-center justify-center shrink-0 overflow-hidden"
style={{
backgroundImage: 'url(/images/furni_floor.png)',
backgroundRepeat: 'repeat',
backgroundPosition: 'center',
}}
>
<img
src={`/swf/dcr/hof_furni/icons/${baseClassname}_icon.png`}
alt={classname}
className="max-w-[60px] max-h-[60px] drop-shadow-md"
style={{ imageRendering: 'pixelated' }}
onError={(e) => {
;(e.target as HTMLImageElement).style.opacity = '0'
}}
/>
</div>
<div className="flex-1 min-w-0">
<DialogTitle className="text-lg">Edit Nitro</DialogTitle>
<CopyClassname value={classname} />
{/* Quick stats */}
{metadata && (
<div className="flex gap-2 mt-2 flex-wrap">
<Badge variant="outline" className="text-[10px] gap-1">
<Ruler className="w-2.5 h-2.5" />
{dims.x}×{dims.y}×{dims.z}
</Badge>
<Badge variant="outline" className="text-[10px] gap-1">
<Compass className="w-2.5 h-2.5" />
{directions.length} dir
</Badge>
<Badge variant="outline" className="text-[10px] gap-1">
<Layers className="w-2.5 h-2.5" />
{layerCount} layers
</Badge>
{colorCount > 0 && (
<Badge variant="outline" className="text-[10px] gap-1">
<Palette className="w-2.5 h-2.5" />
{colorCount} colori
</Badge>
)}
{animCount > 0 && (
<Badge variant="outline" className="text-[10px] gap-1">
<Sparkles className="w-2.5 h-2.5" />
{animCount} anim
</Badge>
)}
<Badge variant="outline" className="text-[10px] gap-1">
<Eye className="w-2.5 h-2.5" />
{metadata.visualizationType || '?'}
</Badge>
</div>
)}
</div>
</div>
</DialogHeader>
{loading ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : metadata ? (
<Tabs
value={activeTab}
onValueChange={handleTabChange}
className="flex-1 flex flex-col min-h-0"
>
<div className="px-6 pt-3 pb-0">
<TabsList className="w-fit">
<TabsTrigger value="visual" className="gap-1.5">
<Box className="w-3.5 h-3.5" />
Visual
</TabsTrigger>
<TabsTrigger value="json" className="gap-1.5">
{'{ }'}
JSON
</TabsTrigger>
</TabsList>
</div>
{/* ── Visual Tab ── */}
<TabsContent value="visual" className="overflow-y-auto flex-1 px-6 py-4 space-y-5">
{/* Dimensions + Interaction in 2-column layout */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
{/* Dimensions card */}
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<Ruler className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Dimensioni</h3>
</div>
<div className="grid grid-cols-3 gap-3">
<div>
<Label htmlFor="dim-x" className="text-xs text-muted-foreground">
X (larghezza)
</Label>
<Input
id="dim-x"
type="number"
min={1}
value={dims.x}
onChange={(e) => setDim('x', e.target.value)}
className="mt-1"
/>
</div>
<div>
<Label htmlFor="dim-y" className="text-xs text-muted-foreground">
Y (profondità)
</Label>
<Input
id="dim-y"
type="number"
min={1}
value={dims.y}
onChange={(e) => setDim('y', e.target.value)}
className="mt-1"
/>
</div>
<div>
<Label htmlFor="dim-z" className="text-xs text-muted-foreground">
Z (altezza)
</Label>
<Input
id="dim-z"
type="number"
step={0.01}
min={0}
value={dims.z}
onChange={(e) => setDim('z', e.target.value)}
className="mt-1"
/>
</div>
</div>
</section>
{/* Interaction card */}
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<MousePointerClick className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Interazione</h3>
</div>
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
<span className="text-sm">Can Stand On</span>
<Switch
checked={flags.canstandon}
onCheckedChange={(v) => setFlags((f) => ({ ...f, canstandon: !!v }))}
/>
</div>
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
<span className="text-sm">Can Sit On</span>
<Switch
checked={flags.cansiton}
onCheckedChange={(v) => setFlags((f) => ({ ...f, cansiton: !!v }))}
/>
</div>
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
<span className="text-sm">Can Lay On</span>
<Switch
checked={flags.canlayon}
onCheckedChange={(v) => setFlags((f) => ({ ...f, canlayon: !!v }))}
/>
</div>
</div>
</section>
</div>
{/* Directions - visual compass */}
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<Compass className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Direzioni</h3>
<span className="text-xs text-muted-foreground ml-auto">
{directions.length} attive
</span>
</div>
<div className="flex items-center justify-center">
<div className="relative w-48 h-48">
{/* Compass circle */}
<div className="absolute inset-0 rounded-full border-2 border-muted" />
<div className="absolute inset-4 rounded-full border border-muted/50" />
{/* Direction buttons arranged in circle */}
{ALL_DIRECTIONS.map((dir) => {
const angle = (dir * 45 - 90) * (Math.PI / 180)
const r = 80
const x = 96 + r * Math.cos(angle) - 18
const y = 96 + r * Math.sin(angle) - 18
const isActive = directions.includes(dir)
return (
<button
type="button"
key={dir}
className={`absolute w-9 h-9 rounded-full border-2 flex flex-col items-center justify-center text-xs font-medium transition-all ${
isActive
? 'bg-primary text-primary-foreground border-primary shadow-md scale-110'
: 'bg-card text-muted-foreground border-muted hover:border-foreground/30 hover:scale-105'
}`}
style={{ left: x, top: y }}
onClick={() => toggleDirection(dir)}
>
<span className="text-[9px] leading-none">{DIR_LABELS[dir]}</span>
<span className="text-[8px] leading-none opacity-60">{dir}</span>
</button>
)
})}
{/* Center label */}
<div className="absolute inset-0 flex items-center justify-center">
<span className="text-xs text-muted-foreground font-medium">
{directions.length}/8
</span>
</div>
</div>
</div>
</section>
{/* Types */}
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<Eye className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Tipo</h3>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label htmlFor="viz-type" className="text-xs text-muted-foreground">
Visualization Type
</Label>
<Input
id="viz-type"
value={metadata.visualizationType || ''}
onChange={(e) =>
setMetadata((prev: unknown) =>
updateNested(prev, 'visualizationType', e.target.value),
)
}
className="mt-1 font-mono text-sm"
/>
</div>
<div>
<Label htmlFor="logic-type" className="text-xs text-muted-foreground">
Logic Type
</Label>
<Input
id="logic-type"
value={metadata.logicType || ''}
onChange={(e) =>
setMetadata((prev: unknown) =>
updateNested(prev, 'logicType', e.target.value),
)
}
className="mt-1 font-mono text-sm"
/>
</div>
</div>
</section>
{/* Layers */}
{viz64?.layers && layerCount > 0 && (
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<Layers className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Layer</h3>
<Badge variant="secondary" className="text-[10px] ml-auto">
{layerCount}
</Badge>
</div>
<div className="rounded-md border overflow-hidden">
{/* Header */}
<div className="grid grid-cols-4 gap-2 items-center text-[10px] font-medium text-muted-foreground uppercase tracking-wider bg-muted/50 px-3 py-1.5">
<span>Layer</span>
<span>Z-Index</span>
<span>Alpha</span>
<span>Ink</span>
</div>
{Object.entries(viz64.layers).map(([layerId, layerData], idx) => {
const layer = layerData as Record<string, unknown>
return (
<div
key={layerId}
className={`grid grid-cols-4 gap-2 items-center text-sm px-3 py-1.5 ${
idx % 2 === 0 ? 'bg-card' : 'bg-muted/20'
}`}
>
<span className="font-mono text-xs">
<Badge variant="outline" className="text-[10px] px-1.5">
#{layerId}
</Badge>
</span>
<Input
type="number"
className="h-7 text-xs"
value={(layer.z as number) ?? 0}
onChange={(e) => {
setMetadata((prev: unknown) =>
updateNested(
prev,
`visualizations.${viz64Index}.layers.${layerId}.z`,
parseInt(e.target.value, 10) || 0,
),
)
}}
/>
<Input
type="number"
className="h-7 text-xs"
min={0}
max={255}
value={(layer.alpha as number) ?? 255}
onChange={(e) => {
setMetadata((prev: unknown) =>
updateNested(
prev,
`visualizations.${viz64Index}.layers.${layerId}.alpha`,
parseInt(e.target.value, 10) || 0,
),
)
}}
/>
<Input
className="h-7 text-xs font-mono"
value={(layer.ink as string) ?? ''}
placeholder="—"
onChange={(e) => {
setMetadata((prev: unknown) =>
updateNested(
prev,
`visualizations.${viz64Index}.layers.${layerId}.ink`,
e.target.value || undefined,
),
)
}}
/>
</div>
)
})}
</div>
</section>
)}
{/* Colors */}
{viz64?.colors && colorCount > 0 && (
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<Palette className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Colori</h3>
<Badge variant="secondary" className="text-[10px] ml-auto">
{colorCount} varianti
</Badge>
</div>
<div className="space-y-3">
{Object.entries(viz64.colors).map(([colorId, colorLayers]) => (
<div key={colorId} className="rounded-md border p-3">
<div className="flex items-center gap-2 mb-2">
<span className="text-xs font-medium">Variante #{colorId}</span>
{/* Color preview dots */}
<div className="flex gap-1 ml-auto">
{Object.values(colorLayers as Record<string, { color: number }>).map(
(lc, i) => (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: color preview dots, position is the identity
key={i}
className="w-4 h-4 rounded-full border border-border shadow-sm"
style={{
backgroundColor: hexToColor(
typeof lc.color === 'number'
? lc.color.toString(16).padStart(6, '0')
: '000000',
),
}}
/>
),
)}
</div>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
{Object.entries(colorLayers as Record<string, { color: number }>).map(
([layerId, layerColor]) => (
<div key={layerId} className="flex items-center gap-2">
<Label className="text-xs text-muted-foreground shrink-0 w-6">
L{layerId}
</Label>
<div className="relative flex-1">
<Input
className="h-7 text-xs font-mono pl-8"
value={
typeof layerColor.color === 'number'
? layerColor.color
.toString(16)
.padStart(6, '0')
.toUpperCase()
: String(layerColor.color)
}
onChange={(e) => {
const hex = e.target.value
.replace(/[^0-9a-fA-F]/g, '')
.slice(0, 6)
const num = parseInt(hex, 16) || 0
setMetadata((prev: unknown) =>
updateNested(
prev,
`visualizations.${viz64Index}.colors.${colorId}.${layerId}.color`,
num,
),
)
}}
/>
{/* Color swatch inside input */}
<div
className="absolute left-1.5 top-1/2 -translate-y-1/2 w-4 h-4 rounded border border-border"
style={{
backgroundColor: hexToColor(
typeof layerColor.color === 'number'
? layerColor.color.toString(16).padStart(6, '0')
: '000000',
),
}}
/>
</div>
</div>
),
)}
</div>
</div>
))}
</div>
</section>
)}
</TabsContent>
{/* ── JSON Tab ── */}
<TabsContent value="json" className="flex-1 flex flex-col min-h-0 px-6 py-4">
<div className="relative flex-1 min-h-0">
<Textarea
className="h-full min-h-[400px] font-mono text-xs resize-none"
value={jsonText}
onChange={(e) => handleJsonTextChange(e.target.value)}
spellCheck={false}
/>
{jsonError && (
<div className="absolute bottom-2 left-2 right-2 rounded-md bg-destructive/10 border border-destructive/20 px-3 py-1.5 text-xs text-destructive">
{jsonError}
</div>
)}
</div>
</TabsContent>
</Tabs>
) : null}
<DialogFooter className="px-6 py-4 border-t bg-muted/30">
<div className="flex items-center gap-2 w-full">
{hasChanges && (
<Badge
variant="secondary"
className="text-[10px] gap-1 animate-[pulse_1s_ease-in-out_1]"
>
Modifiche non salvate
</Badge>
)}
<div className="flex-1" />
<Button
variant="ghost"
size="sm"
onClick={handleReset}
disabled={saving || loading || !metadata || !hasChanges}
className="gap-1.5"
>
<RotateCcw className="w-3.5 h-3.5" />
Reset
</Button>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
Annulla
</Button>
<Button
onClick={handleSave}
disabled={saving || loading || !metadata}
className="gap-1.5"
>
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
Salva
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { ImportFurniClient } from './import-furni-client'
export default async function ImportFurniPage(_props: { params: Promise<{ locale: string }> }) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)) {
redirect('/admin')
}
return <ImportFurniClient />
}
@@ -0,0 +1,356 @@
'use client'
import {
AlertCircle,
Check,
Download,
Loader2,
Package,
PawPrint,
Search,
Trash2,
X,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
interface PetItem {
lib: string
nitroExists: boolean
}
/** Real pet preview cropped from its .nitro; falls back to the paw glyph. */
function PetIcon({ lib }: { lib: string }) {
const [failed, setFailed] = useState(false)
if (failed) return <PawPrint className="w-8 h-8 text-muted-foreground/60" />
return (
// biome-ignore lint/performance/noImgElement: tiny dynamic sprite, not a Next asset
<img
src={`/api/admin/import/pets/icon?lib=${encodeURIComponent(lib)}&v=6`}
alt={lib}
className="image-pixelated"
style={{ maxHeight: 56, maxWidth: 56 }}
onError={() => setFailed(true)}
/>
)
}
export function ImportPetsClient() {
const [searchTerm, setSearchTerm] = useState('')
const [pets, setPets] = useState<PetItem[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [selected, setSelected] = useState<Set<string>>(new Set())
const [batchProgress, setBatchProgress] = useState<{ done: number; total: number } | null>(null)
const [busyLib, setBusyLib] = useState<string | null>(null)
const fetchPets = useCallback(async (search: string) => {
setLoading(true)
setError('')
try {
const params = new URLSearchParams()
if (search) params.set('search', search)
const res = await fetch(`/api/admin/import/pets?${params}`)
const data = await res.json()
if (!res.ok) {
setError(data.error || 'Failed to load')
return
}
setPets(data.pets || [])
setSelected(new Set())
} catch {
setError('Network error')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
fetchPets('')
}, [fetchPets])
const importable = useMemo(() => pets.filter((p) => !p.nitroExists), [pets])
const importedCount = useMemo(() => pets.filter((p) => p.nitroExists).length, [pets])
function toggle(lib: string) {
setSelected((prev) => {
const n = new Set(prev)
if (n.has(lib)) n.delete(lib)
else n.add(lib)
return n
})
}
function markDone(lib: string) {
setPets((prev) => prev.map((p) => (p.lib === lib ? { ...p, nitroExists: true } : p)))
}
async function importViaSse(items: PetItem[]) {
setBatchProgress({ done: 0, total: items.length })
const res = await fetch('/api/admin/import/pets/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items, concurrency: 3 }),
})
if (!res.body) {
toast.error('No response stream')
setBatchProgress(null)
return
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buf = ''
let done = 0
let succeeded = 0
let failed = 0
while (true) {
const { value, done: streamDone } = await reader.read()
if (streamDone) break
buf += decoder.decode(value, { stream: true })
const parts = buf.split('\n\n')
buf = parts.pop() ?? ''
for (const part of parts) {
if (!part.startsWith('data: ')) continue
const evt = JSON.parse(part.slice(6))
if (evt.type === 'item_progress' && evt.status === 'done') {
done++
markDone(evt.classname)
setBatchProgress({ done, total: items.length })
} else if (evt.type === 'item_progress' && evt.status === 'failed') {
done++
setBatchProgress({ done, total: items.length })
} else if (evt.type === 'batch_complete') {
succeeded = evt.succeeded
failed = evt.failed
}
}
}
setBatchProgress(null)
setSelected(new Set())
if (succeeded > 0) toast.success(`${succeeded} pet(s) imported`)
if (failed > 0) toast.error(`${failed} failed`)
}
async function importOne(p: PetItem) {
setBusyLib(p.lib)
try {
await importViaSse([p])
} finally {
setBusyLib(null)
}
}
async function importSelected() {
const items = pets.filter((p) => selected.has(p.lib) && !p.nitroExists)
if (items.length === 0) return
await importViaSse(items)
}
async function remove(p: PetItem) {
setBusyLib(p.lib)
try {
const res = await fetch(`/api/admin/import/pets?lib=${encodeURIComponent(p.lib)}`, {
method: 'DELETE',
})
const data = await res.json()
if (res.ok) {
toast.success(`${p.lib} removed`)
setPets((prev) => prev.map((x) => (x.lib === p.lib ? { ...x, nitroExists: false } : x)))
} else {
toast.error(data.error || 'Delete failed')
}
} finally {
setBusyLib(null)
}
}
return (
<div className="space-y-4">
{pets.length > 0 && (
<div className="flex items-center gap-3 flex-wrap">
<div className="flex items-center gap-1.5 text-sm">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{pets.length}</span>
<span className="text-muted-foreground">pets</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Check className="h-4 w-4 text-emerald-500" />
<span className="font-medium text-emerald-600">{importedCount}</span>
<span className="text-muted-foreground">imported</span>
</div>
<div className="flex items-center gap-1.5 text-sm">
<Download className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{importable.length}</span>
<span className="text-muted-foreground">missing</span>
</div>
</div>
)}
<div className="flex gap-2 flex-wrap">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search pets..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') fetchPets(searchTerm)
if (e.key === 'Escape') {
setSearchTerm('')
fetchPets('')
}
}}
className="pl-9 pr-8"
/>
{searchTerm && (
<button
type="button"
onClick={() => {
setSearchTerm('')
fetchPets('')
}}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
<Button onClick={() => fetchPets(searchTerm)} size="sm" disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
</Button>
</div>
{importable.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<Button
variant="outline"
size="sm"
className="text-xs h-8"
disabled={!!batchProgress}
onClick={() =>
setSelected((prev) =>
prev.size === importable.length ? new Set() : new Set(importable.map((p) => p.lib)),
)
}
>
{selected.size === importable.length
? 'Deselect All'
: `Select All (${importable.length})`}
</Button>
{selected.size > 0 && (
<Button size="sm" className="h-8" onClick={importSelected} disabled={!!batchProgress}>
{batchProgress ? (
<Loader2 className="w-4 h-4 animate-spin mr-1" />
) : (
<Download className="w-4 h-4 mr-1" />
)}
Import {selected.size} selected
</Button>
)}
{batchProgress && (
<span className="text-xs text-muted-foreground">
{batchProgress.done}/{batchProgress.total}
</span>
)}
</div>
)}
{error && (
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
<AlertCircle className="w-4 h-4 shrink-0" />
{error}
</div>
)}
{!loading && pets.length === 0 && !error && (
<div className="text-center py-12 text-muted-foreground">
<PawPrint className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p className="text-sm">No pets found</p>
</div>
)}
{pets.length > 0 && (
<div
className={cn(
'grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3',
loading && 'opacity-50',
)}
>
{pets.map((p) => {
const isSelected = selected.has(p.lib)
return (
<div
key={p.lib}
className={cn(
'rounded-lg border overflow-hidden bg-card relative hover:border-border transition-all',
p.nitroExists && 'shadow-[0_0_6px_rgba(34,197,94,0.15)]',
isSelected && 'ring-2 ring-primary border-primary',
)}
>
{!p.nitroExists && (
<button
type="button"
onClick={() => toggle(p.lib)}
className={cn(
'absolute top-1.5 left-1.5 z-10 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors',
isSelected
? 'bg-primary border-primary text-primary-foreground'
: 'bg-background/80 border-muted-foreground/30 hover:border-muted-foreground',
)}
>
{isSelected && <Check className="w-3 h-3" />}
</button>
)}
<div className="flex items-center justify-center h-20 bg-accent/20">
<PetIcon lib={p.lib} />
</div>
<div className="px-2.5 py-2 border-t space-y-1">
<div className="text-xs font-bold truncate">{p.lib}</div>
<div className="pt-1">
{p.nitroExists ? (
<div className="flex items-center gap-1">
<Badge className="text-[10px] px-1.5 py-0 bg-emerald-500/15 text-emerald-500 border-0 gap-0.5 flex-1 justify-center">
<Check className="w-2.5 h-2.5" />
Imported
</Badge>
<Button
variant="ghost"
size="sm"
className="h-5 w-5 p-0 shrink-0"
title="Remove pet"
disabled={busyLib === p.lib || !!batchProgress}
onClick={() => remove(p)}
>
<Trash2 className="w-3 h-3" />
</Button>
</div>
) : (
<Button
size="sm"
variant="outline"
className="w-full text-xs h-7"
disabled={busyLib === p.lib || !!batchProgress}
onClick={() => importOne(p)}
>
{busyLib === p.lib ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
Import
</Button>
)}
</div>
</div>
</div>
)
})}
</div>
)}
</div>
)
}
+13
View File
@@ -0,0 +1,13 @@
export default function Loading() {
return (
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
{Array.from({ length: 18 }).map((_, i) => (
<div key={`pet-skeleton-${i}`} className="rounded-lg border bg-card p-3 animate-pulse">
<div className="h-12 w-12 bg-muted rounded mx-auto mb-2" />
<div className="h-4 bg-muted rounded w-3/4 mx-auto mb-1" />
<div className="h-7 bg-muted rounded" />
</div>
))}
</div>
)
}
+11
View File
@@ -0,0 +1,11 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { ImportPetsClient } from './import-pets-client'
export default async function ImportPetsPage(_props: { params: Promise<{ locale: string }> }) {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ASSETS_IMPORT, session.user.rank)) {
redirect('/admin')
}
return <ImportPetsClient />
}
+12
View File
@@ -0,0 +1,12 @@
import { redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { RepairClient } from './repair-client'
export default async function RepairImportedPage() {
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)) {
redirect('/admin')
}
return <RepairClient />
}
@@ -0,0 +1,757 @@
'use client'
import {
AlertCircle,
CheckCircle2,
Loader2,
Play,
RefreshCw,
Search,
Trash2,
Wrench,
XCircle,
} from 'lucide-react'
import { useCallback, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { deleteImportedFurni } from '@/actions/import-furni'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
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'
type MissingKind = 'nitro' | 'icon' | 'both'
interface MissingItem {
id: number
classname: string
baseClassname: string
revision: number
type: 's' | 'i'
publicName: string
hasSwf: boolean
hasIcon: boolean
hasNitro: boolean
missing: MissingKind
unrepairable: boolean
}
interface AuditSummary {
total: number
missingBoth: number
missingNitro: number
missingIcon: number
unrepairable: number
items: MissingItem[]
}
type ItemStatus = 'idle' | 'working' | 'done' | 'partial' | 'failed'
interface ItemProgress {
status: ItemStatus
message?: string
nitroRepaired?: boolean
iconRepaired?: boolean
unrepairable?: boolean
}
interface RepairSummary {
succeeded: number
partial: number
failed: number
unrepairable: number
duration: number
}
const TAB_FILTERS: Record<string, (m: MissingItem) => boolean> = {
all: () => true,
both: (m) => m.missing === 'both',
nitro: (m) => m.missing === 'nitro',
icon: (m) => m.missing === 'icon',
unrepairable: (m) => m.unrepairable,
}
export function RepairClient() {
const [summary, setSummary] = useState<AuditSummary | null>(null)
const [auditing, setAuditing] = useState(false)
const [repairing, setRepairing] = useState(false)
const [search, setSearch] = useState('')
const [tab, setTab] = useState<keyof typeof TAB_FILTERS>('all')
const [selected, setSelected] = useState<Set<string>>(new Set())
const [progress, setProgress] = useState<Map<string, ItemProgress>>(new Map())
const [lastSummary, setLastSummary] = useState<RepairSummary | null>(null)
const [confirmDeleteAll, setConfirmDeleteAll] = useState(false)
// ── Audit ──────────────────────────────────────────────────────────
const runAudit = useCallback(async () => {
setAuditing(true)
setLastSummary(null)
try {
const res = await fetch('/api/admin/import/repair/audit', { method: 'POST' })
if (!res.ok) {
toast.error('Audit failed')
return
}
const data = await res.json()
setSummary(data)
setSelected(new Set())
setProgress(new Map())
toast.success(
`Audit: ${data.items.length} item${data.items.length === 1 ? '' : 's'} need repair (${data.total} scanned)`,
)
} catch {
toast.error('Audit network error')
} finally {
setAuditing(false)
}
}, [])
// ── Filters ────────────────────────────────────────────────────────
const filtered = useMemo(() => {
if (!summary) return []
const s = search.trim().toLowerCase()
return summary.items.filter((it) => {
if (!TAB_FILTERS[tab](it)) return false
if (!s) return true
return (
it.classname.toLowerCase().includes(s) ||
it.publicName.toLowerCase().includes(s) ||
String(it.id).includes(s)
)
})
}, [summary, search, tab])
// ── Selection ──────────────────────────────────────────────────────
const allSelected = filtered.length > 0 && filtered.every((i) => selected.has(i.classname))
const toggleAll = () => {
setSelected((prev) => {
if (allSelected) {
const next = new Set(prev)
for (const i of filtered) {
next.delete(i.classname)
}
return next
}
const next = new Set(prev)
for (const i of filtered) {
next.add(i.classname)
}
return next
})
}
const toggleOne = (cn: string) => {
setSelected((prev) => {
const next = new Set(prev)
if (next.has(cn)) next.delete(cn)
else next.add(cn)
return next
})
}
// ── Repair ─────────────────────────────────────────────────────────
const runRepair = useCallback(async (classnames: string[]) => {
if (classnames.length === 0) return
setRepairing(true)
setLastSummary(null)
// Init progress for these items
setProgress((prev) => {
const next = new Map(prev)
for (const cn of classnames) {
next.set(cn, { status: 'working' })
}
return next
})
try {
const res = await fetch('/api/admin/import/repair', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ classnames, concurrency: 6 }),
})
if (!res.ok || !res.body) {
toast.error('Failed to start repair')
setRepairing(false)
return
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (!line.startsWith('data: ')) continue
try {
const event = JSON.parse(line.slice(6))
if (event.type === 'repair_progress') {
setProgress((prev) => {
const next = new Map(prev)
next.set(event.classname, {
status: event.status as ItemStatus,
message: event.error || (event.warnings?.[0] ?? undefined),
nitroRepaired: event.nitroRepaired,
iconRepaired: event.iconRepaired,
unrepairable: event.unrepairable,
})
return next
})
// Promote newly-discovered unrepairable flags onto the audit list
if (event.unrepairable) {
setSummary((prev) => {
if (!prev) return prev
const item = prev.items.find((i) => i.classname === event.classname)
if (!item || item.unrepairable) return prev
return {
...prev,
unrepairable: prev.unrepairable + 1,
items: prev.items.map((i) =>
i.classname === event.classname ? { ...i, unrepairable: true } : i,
),
}
})
}
// Remove repaired items from the audit list on "done"
if (event.status === 'done') {
setSummary((prev) => {
if (!prev) return prev
const items = prev.items.filter((i) => i.classname !== event.classname)
const diff = prev.items.length - items.length
if (diff === 0) return prev
const removed = prev.items.find((i) => i.classname === event.classname)
return {
...prev,
items,
missingBoth: prev.missingBoth - (removed?.missing === 'both' ? 1 : 0),
missingNitro: prev.missingNitro - (removed?.missing === 'nitro' ? 1 : 0),
missingIcon: prev.missingIcon - (removed?.missing === 'icon' ? 1 : 0),
}
})
setSelected((prev) => {
const next = new Set(prev)
next.delete(event.classname)
return next
})
}
} else if (event.type === 'repair_complete') {
setLastSummary({
succeeded: event.succeeded,
partial: event.partial,
failed: event.failed,
unrepairable: event.unrepairable ?? 0,
duration: event.duration,
})
}
} catch {
/* skip malformed */
}
}
}
} catch {
toast.error('Connection lost during repair')
} finally {
setRepairing(false)
}
}, [])
// ── Delete unrepairable items ──────────────────────────────────────
const deleteSelected = useCallback(async () => {
const toDelete = Array.from(selected)
if (toDelete.length === 0) return
setConfirmDeleteAll(false)
let ok = 0
let fail = 0
for (const cn of toDelete) {
setProgress((prev) => {
const next = new Map(prev)
next.set(cn, { status: 'working', message: 'Deleting…' })
return next
})
try {
const result = await deleteImportedFurni({ classname: cn })
if (result.ok) {
ok++
setSummary((prev) => {
if (!prev) return prev
const removed = prev.items.find((i) => i.classname === cn)
if (!removed) return prev
return {
...prev,
total: prev.total - 1,
items: prev.items.filter((i) => i.classname !== cn),
missingBoth: prev.missingBoth - (removed.missing === 'both' ? 1 : 0),
missingNitro: prev.missingNitro - (removed.missing === 'nitro' ? 1 : 0),
missingIcon: prev.missingIcon - (removed.missing === 'icon' ? 1 : 0),
}
})
setSelected((prev) => {
const next = new Set(prev)
next.delete(cn)
return next
})
} else {
fail++
setProgress((prev) => {
const next = new Map(prev)
next.set(cn, { status: 'failed', message: 'Delete failed' })
return next
})
}
} catch {
fail++
setProgress((prev) => {
const next = new Map(prev)
next.set(cn, { status: 'failed', message: 'Delete error' })
return next
})
}
}
toast.success(`Deleted ${ok}${fail > 0 ? `, ${fail} failed` : ''}`)
}, [selected])
// ── Render ─────────────────────────────────────────────────────────
const selectedArray = Array.from(selected)
const selectedCount = selectedArray.length
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Repair Imported Assets</h1>
<p className="text-muted-foreground">
Re-download missing <code className="rounded bg-muted px-1">.nitro</code> bundles and
icons for items already imported. Items with no public asset on habbo.com can be deleted
from here.
</p>
</div>
<div className="flex gap-2">
<Button onClick={runAudit} disabled={auditing || repairing}>
{auditing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Scanning…
</>
) : (
<>
<RefreshCw className="mr-2 h-4 w-4" /> {summary ? 'Re-scan' : 'Scan Assets'}
</>
)}
</Button>
</div>
</div>
{/* Initial empty state */}
{!summary && !auditing && (
<div className="rounded-md border bg-muted/30 p-10 text-center">
<Wrench className="mx-auto mb-3 h-10 w-10 text-muted-foreground" />
<p className="font-medium">
Click &ldquo;Scan Assets&rdquo; to audit imported furniture.
</p>
<p className="text-sm text-muted-foreground">
This checks every row in <code>items_base</code> against files on disk. Scanning ~33k
items takes a few seconds.
</p>
</div>
)}
{/* Stats */}
{summary && (
<div className="grid grid-cols-2 gap-4 md:grid-cols-5">
<StatCard label="Imported total" value={summary.total} tone="default" />
<StatCard
label="Missing both"
value={summary.missingBoth}
tone="danger"
sub="no .nitro · no icon"
/>
<StatCard
label="Missing .nitro"
value={summary.missingNitro}
tone="warn"
sub="shows black cube"
/>
<StatCard
label="Missing icon"
value={summary.missingIcon}
tone="info"
sub="generic icon in client"
/>
<StatCard
label="Unrepairable"
value={summary.unrepairable}
tone="danger"
sub="no asset on habbo.com"
/>
</div>
)}
{/* Batch repair summary */}
{lastSummary && (
<div className="rounded-md border bg-muted/30 p-3 text-sm">
Last run: <b>{lastSummary.succeeded}</b> fixed
{lastSummary.partial > 0 && (
<>
, <b>{lastSummary.partial}</b> partial
</>
)}
{lastSummary.failed > 0 && (
<>
, <b className="text-destructive">{lastSummary.failed}</b> failed
</>
)}
{lastSummary.unrepairable > 0 && (
<>
, <b className="text-destructive">{lastSummary.unrepairable}</b> unrepairable
</>
)}
&nbsp;·&nbsp;{(lastSummary.duration / 1000).toFixed(1)}s
</div>
)}
{/* Table area */}
{summary && summary.items.length === 0 && (
<div className="rounded-md border bg-muted/30 p-10 text-center">
<CheckCircle2 className="mx-auto mb-3 h-10 w-10 text-emerald-500" />
<p className="font-medium">All imported items have their assets on disk.</p>
<p className="text-sm text-muted-foreground">
{summary.total} items scanned, nothing to repair.
</p>
</div>
)}
{summary && summary.items.length > 0 && (
<>
{/* Toolbar */}
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-[240px]">
<Search className="pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Filter by classname, name, or id…"
className="pl-8"
/>
</div>
<Button
variant="default"
onClick={() => {
// Skip unrepairable items — no point paying the network cost for them
const pool = selectedCount > 0 ? selectedArray : filtered.map((i) => i.classname)
const unrep =
summary?.items.filter((i) => i.unrepairable).map((i) => i.classname) ?? []
const unrepSet = new Set(unrep)
const targets = pool.filter((cn) => !unrepSet.has(cn))
if (targets.length === 0) {
toast.info('Nothing to repair — selected items are all flagged unrepairable.')
return
}
runRepair(targets)
}}
disabled={repairing || filtered.length === 0}
>
{repairing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Repairing…
</>
) : (
<>
<Play className="mr-2 h-4 w-4" />
{selectedCount > 0
? `Repair Selected (${selectedCount})`
: `Repair All Visible (${filtered.length})`}
</>
)}
</Button>
<Button
variant="destructive"
onClick={() => setConfirmDeleteAll(true)}
disabled={repairing || selectedCount === 0}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete Selected ({selectedCount})
</Button>
{summary && summary.unrepairable > 0 && (
<Button
variant="destructive"
onClick={() => {
// Auto-select every unrepairable item, then open the same confirm dialog
const unrep = summary.items.filter((i) => i.unrepairable).map((i) => i.classname)
setSelected(new Set(unrep))
setConfirmDeleteAll(true)
}}
disabled={repairing}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete All Unrepairable ({summary.unrepairable})
</Button>
)}
</div>
{/* Tabs */}
<Tabs value={tab} onValueChange={(v) => setTab(v as keyof typeof TAB_FILTERS)}>
<TabsList>
<TabsTrigger value="all">All ({summary.items.length})</TabsTrigger>
<TabsTrigger value="both">Both ({summary.missingBoth})</TabsTrigger>
<TabsTrigger value="nitro">.nitro ({summary.missingNitro})</TabsTrigger>
<TabsTrigger value="icon">Icon ({summary.missingIcon})</TabsTrigger>
<TabsTrigger value="unrepairable">Unrepairable ({summary.unrepairable})</TabsTrigger>
</TabsList>
<TabsContent value={tab} className="mt-4">
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[40px]">
<Checkbox
checked={allSelected}
onCheckedChange={toggleAll}
aria-label="Select all"
/>
</TableHead>
<TableHead className="w-[80px]">ID</TableHead>
<TableHead>Classname</TableHead>
<TableHead className="w-[90px]">Rev</TableHead>
<TableHead className="w-[100px]">.nitro</TableHead>
<TableHead className="w-[100px]">Icon</TableHead>
<TableHead className="w-[100px]">SWF</TableHead>
<TableHead className="w-[240px]">Status</TableHead>
<TableHead className="w-[120px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filtered.length === 0 && (
<TableRow>
<TableCell colSpan={9} className="py-10 text-center text-muted-foreground">
No items match the current filter.
</TableCell>
</TableRow>
)}
{filtered.map((it) => (
<ItemRow
key={it.classname}
item={it}
selected={selected.has(it.classname)}
onToggle={() => toggleOne(it.classname)}
progress={progress.get(it.classname)}
onRepair={() => runRepair([it.classname])}
disabled={repairing}
/>
))}
</TableBody>
</Table>
</div>
</TabsContent>
</Tabs>
</>
)}
<Dialog open={confirmDeleteAll} onOpenChange={setConfirmDeleteAll}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
Delete {selectedCount} imported item{selectedCount === 1 ? '' : 's'}?
</DialogTitle>
<DialogDescription>
This removes the rows from <code>items_base</code> / <code>catalog_items</code>, the
entry in <code>FurnitureData.json</code>, and any remaining asset files on disk. Use
this for items that have no public asset on habbo.com and therefore cannot be
repaired. This cannot be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setConfirmDeleteAll(false)}>
Cancel
</Button>
<Button variant="destructive" onClick={deleteSelected}>
<Trash2 className="mr-2 h-4 w-4" /> Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
// ── Small cell helpers ────────────────────────────────────────────────
function StatCard({
label,
value,
tone,
sub,
}: {
label: string
value: number
tone: 'default' | 'danger' | 'warn' | 'info'
sub?: string
}) {
const tones = {
default: 'border-border',
danger: 'border-destructive/40 bg-destructive/5',
warn: 'border-amber-500/40 bg-amber-500/5',
info: 'border-sky-500/40 bg-sky-500/5',
}
return (
<div className={`rounded-md border p-4 ${tones[tone]}`}>
<div className="text-xs uppercase tracking-wide text-muted-foreground">{label}</div>
<div className="mt-1 text-2xl font-bold">{value.toLocaleString()}</div>
{sub && <div className="mt-0.5 text-xs text-muted-foreground">{sub}</div>}
</div>
)
}
function FileBadge({ present }: { present: boolean }) {
return present ? (
<Badge
variant="secondary"
className="border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"
>
<CheckCircle2 className="mr-1 h-3 w-3" /> On disk
</Badge>
) : (
<Badge variant="secondary" className="border-destructive/40 bg-destructive/10 text-destructive">
<XCircle className="mr-1 h-3 w-3" /> Missing
</Badge>
)
}
function StatusCell({ progress }: { progress?: ItemProgress }) {
if (!progress || progress.status === 'idle')
return <span className="text-muted-foreground text-xs">—</span>
if (progress.status === 'working') {
return (
<span className="flex items-center gap-1 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
{progress.message || 'Working…'}
</span>
)
}
if (progress.status === 'done') {
const parts = [
progress.nitroRepaired ? '.nitro ✓' : null,
progress.iconRepaired ? 'icon ✓' : null,
].filter(Boolean)
return (
<span className="flex items-center gap-1 text-xs text-emerald-600 dark:text-emerald-400">
<CheckCircle2 className="h-3 w-3" />
{parts.length > 0 ? parts.join(' · ') : 'Repaired'}
</span>
)
}
if (progress.status === 'partial') {
return (
<span
className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400"
title={progress.message}
>
<AlertCircle className="h-3 w-3" />
Partial · {progress.message || 'check logs'}
</span>
)
}
return (
<span className="flex items-center gap-1 text-xs text-destructive" title={progress.message}>
<XCircle className="h-3 w-3" />
{progress.message || 'Failed'}
</span>
)
}
function ItemRow({
item,
selected,
onToggle,
progress,
onRepair,
disabled,
}: {
item: MissingItem
selected: boolean
onToggle: () => void
progress?: ItemProgress
onRepair: () => void
disabled: boolean
}) {
const isUnrepairable = item.unrepairable || progress?.unrepairable
return (
<TableRow className={isUnrepairable ? 'bg-destructive/5' : undefined}>
<TableCell>
<Checkbox
checked={selected}
onCheckedChange={onToggle}
aria-label={`Select ${item.classname}`}
/>
</TableCell>
<TableCell className="font-mono text-xs">{item.id}</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<span className="font-mono text-sm">{item.classname}</span>
{isUnrepairable && (
<Badge
variant="secondary"
className="border-destructive/40 bg-destructive/10 text-destructive"
>
<AlertCircle className="mr-1 h-3 w-3" /> Unrepairable
</Badge>
)}
</div>
<div className="text-xs text-muted-foreground">{item.publicName}</div>
</TableCell>
<TableCell className="text-xs">{item.revision || '—'}</TableCell>
<TableCell>
<FileBadge present={item.hasNitro} />
</TableCell>
<TableCell>
<FileBadge present={item.hasIcon} />
</TableCell>
<TableCell>
<FileBadge present={item.hasSwf} />
</TableCell>
<TableCell>
<StatusCell progress={progress} />
</TableCell>
<TableCell>
<Button
size="sm"
variant="outline"
onClick={onRepair}
disabled={disabled || progress?.status === 'working' || isUnrepairable}
title={isUnrepairable ? 'habbo.com does not have this asset' : 'Retry download + convert'}
>
{progress?.status === 'working' ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Wrench className="h-3 w-3" />
)}
</Button>
</TableCell>
</TableRow>
)
}
+13 -10
View File
@@ -1,10 +1,5 @@
import { Shield } from "lucide-react";
import {
addBlacklist,
addWhitelist,
deleteBlacklist,
deleteWhitelist,
} from "@/actions/admin-ip";
import { addBlacklist, addWhitelist, deleteBlacklist, deleteWhitelist } from "@/actions/admin-ip";
import { StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
import { getTranslations } from "next-intl/server";
@@ -109,8 +104,12 @@ export default async function AdminIp() {
{whitelist.map((w) => (
<tr key={String(w.id)}>
<td>{w.ipAddress}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{w.asn ?? "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDate(w.createdAt)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{w.asn ?? "—"}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDate(w.createdAt)}
</td>
<td>
<form action={deleteWhitelist}>
<input type="hidden" name="id" value={String(w.id)} />
@@ -163,8 +162,12 @@ export default async function AdminIp() {
{blacklist.map((b) => (
<tr key={String(b.id)}>
<td>{b.ipAddress}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{b.asn ?? "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDate(b.createdAt)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{b.asn ?? "—"}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDate(b.createdAt)}
</td>
<td>
<form action={deleteBlacklist}>
<input type="hidden" name="id" value={String(b.id)} />
+73 -13
View File
@@ -7,12 +7,48 @@ import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { siteSettings } from "@/lib/services/site-settings";
import {
LayoutDashboard, Newspaper, Tags, Compass, HelpCircle, Megaphone, SquarePen, Image,
Users, Ban, Globe, Shield, ClipboardList, Group, Key,
Store, ShoppingCart, Receipt, Ticket, CreditCard, Gem, Award, Trophy, Calendar,
Radio, History,
Terminal, Monitor, Bell, FileText, Filter, Wrench, Settings, DoorOpen, Mail, Palette, Cog,
LayoutDashboard,
Newspaper,
Tags,
Compass,
HelpCircle,
Megaphone,
SquarePen,
Image,
Users,
Ban,
Globe,
Shield,
ClipboardList,
Group,
Key,
Store,
ShoppingCart,
Receipt,
Ticket,
CreditCard,
Gem,
Award,
Trophy,
Calendar,
Radio,
History,
Terminal,
Monitor,
Bell,
FileText,
Filter,
Wrench,
Settings,
DoorOpen,
Mail,
Palette,
Cog,
LogOut,
Music,
Languages,
Upload,
MessageSquare,
} from "lucide-react";
export const dynamic = "force-dynamic";
@@ -20,11 +56,13 @@ export const dynamic = "force-dynamic";
function getNavGroups(t: (key: string) => string) {
return [
{
label: t("overview"), icon: <LayoutDashboard size={14} />,
label: t("overview"),
icon: <LayoutDashboard size={14} />,
items: [{ href: "/admin", label: t("dashboard"), icon: <LayoutDashboard size={16} /> }],
},
{
label: t("content"), icon: <Newspaper size={14} />,
label: t("content"),
icon: <Newspaper size={14} />,
items: [
{ href: "/admin/articles", label: t("articles"), icon: <Newspaper size={16} /> },
{ href: "/admin/tags", label: t("tags"), icon: <Tags size={16} /> },
@@ -33,10 +71,12 @@ function getNavGroups(t: (key: string) => string) {
{ href: "/admin/ads", label: t("advertisements"), icon: <Megaphone size={16} /> },
{ 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} /> },
],
},
{
label: t("usersAccess"), icon: <Shield size={14} />,
label: t("usersAccess"),
icon: <Shield size={14} />,
items: [
{ href: "/admin/users", label: t("users"), icon: <Users size={16} /> },
{ href: "/admin/bans", label: t("bans"), icon: <Ban size={16} /> },
@@ -48,7 +88,8 @@ function getNavGroups(t: (key: string) => string) {
],
},
{
label: t("economy"), icon: <ShoppingCart size={14} />,
label: t("economy"),
icon: <ShoppingCart size={14} />,
items: [
{ href: "/admin/catalog", label: t("catalog"), icon: <Store size={16} /> },
{ href: "/admin/shop", label: t("shop"), icon: <ShoppingCart size={16} /> },
@@ -62,14 +103,25 @@ function getNavGroups(t: (key: string) => string) {
],
},
{
label: t("radio"), icon: <Radio size={14} />,
label: t("radio"),
icon: <Radio size={14} />,
items: [
{ href: "/admin/radio", label: t("radio"), icon: <Radio size={16} /> },
{ href: "/admin/radio/history", label: t("radioHistory"), icon: <History size={16} /> },
{ href: "/admin/radio/banners", label: t("radioBanners"), icon: <Image size={16} /> },
{ href: "/admin/radio/embed", label: t("radioEmbed"), icon: <Radio size={16} /> },
{ href: "/admin/radio/api-keys", label: t("radioApiKeys"), icon: <Key size={16} /> },
{ href: "/admin/radio/moderation", label: t("radioModeration"), icon: <Shield size={16} /> },
{ href: "/admin/radio/settings", label: t("radioSettings"), icon: <Settings size={16} /> },
{ href: "/admin/radio/monitoring", label: t("radioMonitoring"), icon: <Monitor size={16} /> },
{ href: "/admin/radio/points", label: t("radioPoints"), icon: <Gem size={16} /> },
{ href: "/admin/radio/ranks", label: t("radioRanks"), icon: <Group size={16} /> },
{ href: "/admin/radio/autodj", label: t("radioAutodj"), icon: <Radio size={16} /> },
],
},
{
label: t("system"), icon: <Settings size={14} />,
label: t("system"),
icon: <Settings size={14} />,
items: [
{ href: "/admin/commandocentrum", label: t("commandocentrum"), icon: <Terminal size={16} /> },
{ href: "/admin/emulator", label: t("emulator"), icon: <Monitor size={16} /> },
@@ -83,6 +135,9 @@ function getNavGroups(t: (key: string) => string) {
{ href: "/admin/theme", label: t("theme"), icon: <Palette size={16} /> },
{ href: "/admin/media", label: t("media"), icon: <Image size={16} /> },
{ href: "/admin/favicon", label: t("favicon"), icon: <Image size={16} /> },
{ href: "/admin/sounds", label: t("sounds"), icon: <Music size={16} /> },
{ href: "/admin/translations", label: t("translations"), icon: <Languages size={16} /> },
{ href: "/admin/import", label: t("import"), icon: <Upload size={16} /> },
{ href: "/admin/settings", label: t("settings"), icon: <Cog size={16} /> },
],
},
@@ -117,12 +172,17 @@ async function Sidebar({ staff }: { staff: { id: number; username: string; rank:
return (
<aside className="sticky top-0 self-start h-screen bg-gradient-to-b from-[#1e1b2e] to-[#151226] text-[#c8cbe0] shadow-xl flex flex-col">
<div className="flex items-center gap-3 px-4 py-5 border-b border-white/[0.06]">
<span className="flex-none w-10 h-10 rounded-xl grid place-items-center font-extrabold text-base text-[#1a1a2e] bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-hover)] shadow-lg shadow-[var(--color-primary)]/20" aria-hidden>
<span
className="flex-none w-10 h-10 rounded-xl grid place-items-center font-extrabold text-base text-[#1a1a2e] bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-hover)] shadow-lg shadow-[var(--color-primary)]/20"
aria-hidden
>
{initial}
</span>
<div className="min-w-0 flex-1">
<div className="font-semibold text-sm text-white truncate">{staff.username}</div>
<span className="inline-block mt-0.5 text-[0.6rem] font-bold uppercase tracking-widest text-[rgba(200,203,224,0.5)]">{t("rankLabel", { rank: staff.rank })}</span>
<span className="inline-block mt-0.5 text-[0.6rem] font-bold uppercase tracking-widest text-[rgba(200,203,224,0.5)]">
{t("rankLabel", { rank: staff.rank })}
</span>
</div>
</div>
+4 -1
View File
@@ -1,7 +1,10 @@
export default function AdminLoading() {
return (
<div style={{ display: "flex", justifyContent: "center", padding: "4rem 0" }}>
<div className="animate-spin w-8 h-8 border-4 rounded-full" style={{ borderColor: "var(--color-primary)", borderTopColor: "transparent" }} />
<div
className="animate-spin w-8 h-8 border-4 rounded-full"
style={{ borderColor: "var(--color-primary)", borderTopColor: "transparent" }}
/>
</div>
);
}
+33 -18
View File
@@ -27,11 +27,7 @@ export default async function AdminStaffActivities({
let whereClause = {};
if (q) {
whereClause = {
OR: [
{ action: { contains: q } },
{ description: { contains: q } },
{ ipAddress: { contains: q } },
],
OR: [{ action: { contains: q } }, { description: { contains: q } }, { ipAddress: { contains: q } }],
};
}
@@ -81,7 +77,9 @@ export default async function AdminStaffActivities({
const pages = Math.max(1, Math.ceil(total / PER_PAGE));
const onlineCount = activities.filter((a) => a.createdAt && new Date(a.createdAt).getTime() > Date.now() - 60000).length;
const onlineCount = activities.filter(
(a) => a.createdAt && new Date(a.createdAt).getTime() > Date.now() - 60000,
).length;
return (
<main>
@@ -119,12 +117,12 @@ export default async function AdminStaffActivities({
placeholder={t("staffId")}
className="w-[120px]"
/>
<input
name="action"
defaultValue={action ?? ""}
placeholder={t("actionType")}
className="w-[160px]"
/>
<input
name="action"
defaultValue={action ?? ""}
placeholder={t("actionType")}
className="w-[160px]"
/>
<button type="submit" className="btn btn-primary">
{t("filter")}
@@ -156,20 +154,33 @@ export default async function AdminStaffActivities({
<tbody>
{activities.map((a) => (
<tr key={String(a.id)}>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{fromDate(a.createdAt)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{t("staffWithId", { id: Number(a.userId), name: nameById.get(Number(a.userId)) ?? "unknown" })}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{fromDate(a.createdAt)}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{t("staffWithId", {
id: Number(a.userId),
name: nameById.get(Number(a.userId)) ?? "unknown",
})}
</td>
<td>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{a.action}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{a.action}
</span>
</td>
<td>{a.description}</td>
<td>
{a.targetType && a.targetId ? (
<span className="text-sm text-gray-500 dark:text-gray-400">{a.targetType === "user" ? t("userPrefix") : ""}#{String(a.targetId)}</span>
<span className="text-sm text-gray-500 dark:text-gray-400">
{a.targetType === "user" ? t("userPrefix") : ""}#{String(a.targetId)}
</span>
) : (
<span className="text-sm text-gray-500 dark:text-gray-400">—</span>
)}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{a.ipAddress || "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{a.ipAddress || "—"}
</td>
</tr>
))}
</tbody>
@@ -183,7 +194,11 @@ export default async function AdminStaffActivities({
{page < pages ? (
<>
{" · "}
<a href={`/admin/logs?q=${encodeURIComponent(q)}&staffId=${staffId || ""}&action=${action || ""}&page=${page + 1}`}>{t("next")} →</a>
<a
href={`/admin/logs?q=${encodeURIComponent(q)}&staffId=${staffId || ""}&action=${action || ""}&page=${page + 1}`}
>
{t("next")} →
</a>
</>
) : null}
</p>
+10 -19
View File
@@ -6,11 +6,7 @@ import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
const KEYS = [
"maintenance_enabled",
"maintenance_message",
"min_maintenance_login_rank",
] as const;
const KEYS = ["maintenance_enabled", "maintenance_message", "min_maintenance_login_rank"] as const;
export default async function AdminMaintenance() {
const t = await getTranslations("pages.admin.maintenance");
@@ -42,7 +38,9 @@ export default async function AdminMaintenance() {
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t.rich("subtitle", { code: (chunks) => <code>{chunks}</code> })}</p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
{t.rich("subtitle", { code: (chunks) => <code>{chunks}</code> })}
</p>
</div>
</div>
@@ -54,12 +52,7 @@ export default async function AdminMaintenance() {
hint={enabled ? t("hotelLockedDown") : t("hotelOpen")}
icon={enabled ? "🚧" : "🟢"}
/>
<StatusCard
label={t("minLoginRank")}
value={minRankValue}
hint={t("duringMaintenance")}
icon="🛡️"
/>
<StatusCard label={t("minLoginRank")} value={minRankValue} hint={t("duringMaintenance")} icon="🛡️" />
<StatusCard
label={t("splashMessage")}
value={message ? t("set") : t("empty")}
@@ -71,17 +64,15 @@ export default async function AdminMaintenance() {
<section className="mt-6">
<h2 className="admin-section-title">{t("currentState")}</h2>
<div className="admin-card flex items-center gap-3">
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${enabled ? "bg-red-500/22 text-[var(--color-text)]" : "bg-green-600/20 text-[var(--color-text)]"}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${enabled ? "bg-red-500/22 text-[var(--color-text)]" : "bg-green-600/20 text-[var(--color-text)]"}`}
>
{enabled ? t("enabled") : t("disabled")}
</span>
<div>
<strong>
{t("maintenanceCurrently", { status: enabled ? t("enabled") : t("disabled") })}
</strong>
<strong>{t("maintenanceCurrently", { status: enabled ? t("enabled") : t("disabled") })}</strong>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1 m-0">
{enabled
? t("onlyRankCanLogin", { rank: minRankValue })
: t("hotelOpenToEveryone")}
{enabled ? t("onlyRankCanLogin", { rank: minRankValue }) : t("hotelOpenToEveryone")}
</p>
</div>
</div>
+7 -1
View File
@@ -16,7 +16,13 @@ export default async function AdminMediaPage() {
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle")}</p>
</div>
<Link href="/admin/articles" className="text-sm text-gray-500 dark:text-gray-400" style={{ fontSize: "0.88rem" }}>← {t("articles")}</Link>
<Link
href="/admin/articles"
className="text-sm text-gray-500 dark:text-gray-400"
style={{ fontSize: "0.88rem" }}
>
← {t("articles")}
</Link>
</div>
<AdminMediaGrid />
</main>
+10 -9
View File
@@ -31,7 +31,11 @@ type PublicRow = {
// Reusable yes/no pill so emulator boolean-ish "1"/"0" columns read consistently.
function YesNo({ on }: { on: boolean }) {
return (
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${on ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}>{on ? "Yes" : "No"}</span>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${on ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}
>
{on ? "Yes" : "No"}
</span>
);
}
@@ -117,12 +121,7 @@ export default async function AdminNavigation() {
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("flatCategories")} value={flatcats.length} icon="📂" />
<StatusCard
label={t("publicFlatcats")}
value={publicFlatcats}
hint={t("markedPublic")}
icon="🌐"
/>
<StatusCard label={t("publicFlatcats")} value={publicFlatcats} hint={t("markedPublic")} icon="🌐" />
<StatusCard label={t("publicRooms")} value={publics.length} icon="🚪" />
<StatusCard
label={t("visibleRooms")}
@@ -161,7 +160,9 @@ export default async function AdminNavigation() {
<tr key={c.id}>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{c.id}</td>
<td>{c.caption || "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{c.captionSave || "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{c.captionSave || "—"}
</td>
<td>{c.minRank}</td>
<td>{c.maxUserCount}</td>
<td>
@@ -206,7 +207,7 @@ export default async function AdminNavigation() {
<span className="text-sm text-gray-500 dark:text-gray-400">#{p.public_cat_id}</span>
</td>
<td>
{roomNameById.get(p.room_id) || t("unnamed")}{" "}
{roomNameById.get(p.room_id) || t("unnamed")}{" "}
<span className="text-sm text-gray-500 dark:text-gray-400">#{p.room_id}</span>
</td>
<td>
+69 -18
View File
@@ -25,8 +25,7 @@ export default async function AdminDashboard() {
prisma.websiteArticles.count(),
prisma.ban.count({ where: { banExpire: { gt: Math.floor(Date.now() / 1000) } } }),
]);
} catch {
}
} catch {}
const dbOk = users >= 0;
const rankGroups = await prisma.user
@@ -62,26 +61,64 @@ export default async function AdminDashboard() {
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
<StatusCard label={t("playersOnline")} value={online} hint={dbOk ? t("totalAccounts", { count: users }) : t("databaseDown")} state={dbOk ? "neutral" : "danger"} icon={<Users size={18} />} />
<StatusCard label={t("articles")} value={dbOk ? articles : "—"} state="neutral" icon={<Newspaper size={18} />} />
<StatusCard label={t("activeBans")} value={dbOk ? bans : "—"} state={bans > 0 ? "warn" : "neutral"} icon={<Ban size={18} />} />
<StatusCard label={t("database")} value={dbOk ? t("databaseConnected") : t("databaseDown")} state={dbOk ? "ok" : "danger"} icon={<Database size={18} />} />
<StatusCard
label={t("playersOnline")}
value={online}
hint={dbOk ? t("totalAccounts", { count: users }) : t("databaseDown")}
state={dbOk ? "neutral" : "danger"}
icon={<Users size={18} />}
/>
<StatusCard
label={t("articles")}
value={dbOk ? articles : "—"}
state="neutral"
icon={<Newspaper size={18} />}
/>
<StatusCard
label={t("activeBans")}
value={dbOk ? bans : "—"}
state={bans > 0 ? "warn" : "neutral"}
icon={<Ban size={18} />}
/>
<StatusCard
label={t("database")}
value={dbOk ? t("databaseConnected") : t("databaseDown")}
state={dbOk ? "ok" : "danger"}
icon={<Database size={18} />}
/>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<section className="admin-card p-5">
<h2 className="text-sm font-bold text-[var(--color-text)] mb-4 admin-section-title">{t("usersByRank")}</h2>
<h2 className="text-sm font-bold text-[var(--color-text)] mb-4 admin-section-title">
{t("usersByRank")}
</h2>
{rankCounts.length === 0 ? (
<p className="text-xs text-[var(--color-text-muted)]">{dbOk ? t("noAccountsToBreakDown") : t("databaseDown")}</p>
<p className="text-xs text-[var(--color-text-muted)]">
{dbOk ? t("noAccountsToBreakDown") : t("databaseDown")}
</p>
) : (
<div className="space-y-2.5">
{rankCounts.map((r) => {
const pct = maxRankCount > 0 ? Math.round((r.count / maxRankCount) * 100) : 0;
return (
<div key={r.rank} className="grid items-center gap-3" style={{ gridTemplateColumns: "5rem 1fr 2.5rem" }}>
<span className="text-xs font-medium text-[var(--color-text-muted)]">{t("rankLabel", { rank: r.rank })}</span>
<div className="h-3 rounded-md overflow-hidden bg-[var(--color-primary)]/10" role="img" aria-label={t("rankWithCount", { rank: r.rank, count: r.count })}>
<div className="h-full rounded-md bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary-hover)] transition-all duration-500" style={{ width: `${Math.max(pct, r.count > 0 ? 4 : 0)}%` }} />
<div
key={r.rank}
className="grid items-center gap-3"
style={{ gridTemplateColumns: "5rem 1fr 2.5rem" }}
>
<span className="text-xs font-medium text-[var(--color-text-muted)]">
{t("rankLabel", { rank: r.rank })}
</span>
<div
className="h-3 rounded-md overflow-hidden bg-[var(--color-primary)]/10"
role="img"
aria-label={t("rankWithCount", { rank: r.rank, count: r.count })}
>
<div
className="h-full rounded-md bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary-hover)] transition-all duration-500"
style={{ width: `${Math.max(pct, r.count > 0 ? 4 : 0)}%` }}
/>
</div>
<strong className="text-xs text-right text-[var(--color-text-muted)]">{r.count}</strong>
</div>
@@ -93,8 +130,13 @@ export default async function AdminDashboard() {
<section className="admin-card p-5">
<div className="flex items-center justify-between mb-4">
<h2 className="text-sm font-bold text-[var(--color-text)] admin-section-title">{t("recentStaffActivity")}</h2>
<Link href="/admin/commandocentrum" className="text-xs font-medium text-[var(--color-primary)] hover:text-[var(--color-primary-hover)] flex items-center gap-1 no-underline">
<h2 className="text-sm font-bold text-[var(--color-text)] admin-section-title">
{t("recentStaffActivity")}
</h2>
<Link
href="/admin/commandocentrum"
className="text-xs font-medium text-[var(--color-primary)] hover:text-[var(--color-primary-hover)] flex items-center gap-1 no-underline"
>
{t("viewAll")} <ArrowRight size={12} />
</Link>
</div>
@@ -103,17 +145,26 @@ export default async function AdminDashboard() {
) : (
<div className="space-y-0">
{activity.map((a, i) => (
<div key={String(a.id)} className={`flex items-center gap-3 py-2.5 ${i > 0 ? "border-t border-[var(--border-subtle)]" : ""}`}>
<div
key={String(a.id)}
className={`flex items-center gap-3 py-2.5 ${i > 0 ? "border-t border-[var(--border-subtle)]" : ""}`}
>
<div className="w-7 h-7 rounded-full bg-[var(--color-primary)]/10 grid place-items-center flex-none">
<Activity size={12} className="text-[var(--color-primary)]" />
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-[var(--color-text)] truncate">{nameById.get(Number(a.userId)) ?? `#${a.userId}`}</div>
<div className="text-sm font-medium text-[var(--color-text)] truncate">
{nameById.get(Number(a.userId)) ?? `#${a.userId}`}
</div>
<div className="text-xs text-[var(--color-text-muted)] truncate">{a.description}</div>
</div>
<div className="text-right flex-none">
<span className="inline-block text-[0.6rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)] admin-card inline-flex items-center justify-center min-w-[60px]">{a.action}</span>
<div className="text-[0.6rem] text-[var(--color-text-muted)] mt-0.5">{fromDate(a.createdAt)}</div>
<span className="inline-block text-[0.6rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)] admin-card inline-flex items-center justify-center min-w-[60px]">
{a.action}
</span>
<div className="text-[0.6rem] text-[var(--color-text-muted)] mt-0.5">
{fromDate(a.createdAt)}
</div>
</div>
</div>
))}
+75
View File
@@ -0,0 +1,75 @@
import { notFound, redirect } from 'next/navigation'
import { AdminBreadcrumb } from '@/components/admin/admin-breadcrumb'
import { getAdminContext } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { fetchEmulatorRankForEdit } from '@/lib/services/permission-ranks'
import { RankEditClient } from './rank-edit-client'
export default async function RankEditPage({
params,
}: {
params: Promise<{ locale: string; id: string }>
}) {
const { id: rawId } = await params
const { permissions } = await getAdminContext()
if (!permissions.isSuperAdmin) redirect('/admin')
const rankId = parseInt(rawId, 10)
if (Number.isNaN(rankId)) notFound()
const rank = await fetchEmulatorRankForEdit(prisma, rankId)
if (!rank) notFound()
// Fetch users with this rank (limit 200)
const users = await prisma.user.findMany({
where: { rank: rankId },
select: { id: true, username: true, look: true },
orderBy: { username: 'asc' },
take: 200,
})
const totalUsers = await prisma.user.count({ where: { rank: rankId } })
// Fetch all CMS permissions
const allCmsPermissions = await prisma.aclPermission.findMany({
orderBy: { slug: 'asc' },
})
// Auto-create CMS role for rank >= 4
let cmsRole: { id: number; slug: string; title: string; permissionSlugs: string[] } | null = null
if (rankId >= 4) {
const role = await prisma.aclRole.upsert({
where: { slug: `rank_${rankId}` },
create: { slug: `rank_${rankId}`, title: rank.rank_name || `Rank ${rankId}` },
update: {},
include: {
rolePermissions: { include: { permission: true } },
},
})
cmsRole = {
id: role.id,
slug: role.slug,
title: role.title,
permissionSlugs: role.rolePermissions.map((rp) => rp.permission.slug),
}
}
return (
<div className="space-y-6">
<AdminBreadcrumb
items={[
{ label: 'Permissions', href: '/admin/permissions' },
{ label: rank.rank_name || `Rank ${rankId}` },
]}
/>
<RankEditClient
rank={rank}
users={users}
totalUsers={totalUsers}
cmsRole={cmsRole}
allCmsPermissions={allCmsPermissions}
/>
</div>
)
}
@@ -0,0 +1,728 @@
'use client'
import {
ArrowLeft,
ChevronDown,
Crown,
Loader2,
Save,
Search,
Settings,
Shield,
ShieldCheck,
Terminal,
UserCheck,
} from 'lucide-react'
import Link from 'next/link'
import { useMemo, useState } from 'react'
import { toast } from 'sonner'
import { saveRank as saveRankAction, setCmsPermissions } from '@/actions/permissions'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useServerAction } from '@/hooks/use-server-action'
import { getAvatarUrl } from '@/lib/imager'
import { cn } from '@/lib/utils'
/* ─── Types ──────────────────────────────────────────────── */
interface RankData {
id: number
rank_name: string
badge: string
level: number
prefix: string
prefix_color: string
hidden_rank: string
log_commands: string
room_effect: number
auto_credits_amount: number
auto_pixels_amount: number
auto_gotw_amount: number
auto_points_amount: number
permissions: Record<string, string>
permissionMaxValues: Record<string, number>
}
interface RankUser {
id: number
username: string
look: string
}
interface CmsRoleData {
id: number
slug: string
title: string
permissionSlugs: string[]
}
interface CmsPermission {
id: number
slug: string
title: string
}
interface Props {
rank: RankData
users: RankUser[]
totalUsers: number
cmsRole: CmsRoleData | null
allCmsPermissions: CmsPermission[]
}
/* ─── Helpers ────────────────────────────────────────────── */
function categorizePerms(keys: string[]) {
const commands: string[] = []
const account: string[] = []
const other: string[] = []
for (const key of keys.sort()) {
if (key.startsWith('cmd_') || key === 'kiss_cmd') commands.push(key)
else if (key.startsWith('acc_')) account.push(key)
else other.push(key)
}
return { commands, account, other }
}
/* ─── Tri-state Toggle ───────────────────────────────────── */
function PermToggle({
value,
maxValue,
onChange,
}: {
value: string
maxValue: number
onChange: (v: string) => void
}) {
const values = Array.from({ length: Math.max(1, maxValue) + 1 }, (_, i) => String(i))
return (
<div className="flex gap-0.5 shrink-0">
{values.map((v) => (
<button
key={v}
type="button"
onClick={() => onChange(v)}
className={cn(
'w-7 h-6 text-[11px] font-mono rounded transition-all font-medium',
v === value
? v === '0'
? 'bg-zinc-500 text-white shadow-sm'
: v === '1'
? 'bg-emerald-500 text-white shadow-sm'
: 'bg-amber-500 text-white shadow-sm'
: 'bg-muted/60 text-muted-foreground/40 hover:bg-muted hover:text-muted-foreground',
)}
>
{v}
</button>
))}
</div>
)
}
/* ─── Main Component ─────────────────────────────────────── */
export function RankEditClient({
rank: initialRank,
users,
totalUsers,
cmsRole: initialCmsRole,
allCmsPermissions,
}: Props) {
const { run, isPending } = useServerAction()
const [general, setGeneral] = useState({
rank_name: initialRank.rank_name,
badge: initialRank.badge,
prefix: initialRank.prefix,
prefix_color: initialRank.prefix_color,
hidden_rank: initialRank.hidden_rank,
log_commands: initialRank.log_commands,
room_effect: initialRank.room_effect,
auto_credits_amount: initialRank.auto_credits_amount,
auto_pixels_amount: initialRank.auto_pixels_amount,
auto_gotw_amount: initialRank.auto_gotw_amount,
auto_points_amount: initialRank.auto_points_amount,
})
const [perms, setPerms] = useState<Record<string, string>>(initialRank.permissions)
const [cmsPermSlugs, setCmsPermSlugs] = useState<string[]>(initialCmsRole?.permissionSlugs ?? [])
const [permSearch, setPermSearch] = useState('')
const [cmsSearch, setCmsSearch] = useState('')
const [collapsed, setCollapsed] = useState<Set<string>>(new Set())
const cats = useMemo(
() => categorizePerms(Object.keys(initialRank.permissions)),
[initialRank.permissions],
)
const enabledCount = Object.values(perms).filter((v) => v !== '0').length
const totalCount = Object.keys(perms).length
function setNum(field: string, val: string) {
setGeneral((p) => ({ ...p, [field]: parseInt(val, 10) || 0 }))
}
function saveRank() {
run(() => saveRankAction({ id: initialRank.id, fields: { ...general, ...perms } }), {
successMessage: 'Rank saved',
})
}
async function toggleCms(slug: string) {
if (!initialCmsRole) return
const prev = cmsPermSlugs
const next = prev.includes(slug) ? prev.filter((s) => s !== slug) : [...prev, slug]
setCmsPermSlugs(next)
try {
const r = await setCmsPermissions({ roleId: initialCmsRole.id, permissionSlugs: next })
if (!r.ok) {
setCmsPermSlugs(prev)
toast.error('Failed')
}
} catch {
setCmsPermSlugs(prev)
toast.error('Failed')
}
}
function toggle(key: string) {
setCollapsed((p) => {
const n = new Set(p)
if (n.has(key)) n.delete(key)
else n.add(key)
return n
})
}
/* ── Collapsible perm section ──────────────────────────── */
function setSectionAll(keys: string[], value: string) {
setPerms((p) => {
const next = { ...p }
for (const k of keys) next[k] = value
return next
})
}
function setAllPerms(value: string) {
setPerms((p) => {
const next = { ...p }
for (const k of Object.keys(next)) next[k] = value
return next
})
}
function PermSection({
title,
keys,
sectionKey,
}: {
title: string
keys: string[]
sectionKey: string
}) {
const filtered = permSearch
? keys.filter((k) => k.toLowerCase().includes(permSearch.toLowerCase()))
: keys
if (permSearch && filtered.length === 0) return null
const on = filtered.filter((k) => (perms[k] ?? '0') !== '0').length
const _allOn = on === filtered.length
const open = !collapsed.has(sectionKey)
return (
<div className="border rounded-lg overflow-hidden">
<div className="flex items-center bg-muted/30">
<button
type="button"
onClick={() => toggle(sectionKey)}
className="flex flex-1 items-center justify-between px-4 py-3 hover:bg-muted/50 transition-colors"
>
<span className="text-sm font-medium">{title}</span>
<div className="flex items-center gap-2">
<Badge variant={on > 0 ? 'default' : 'secondary'} className="text-[10px]">
{on}/{filtered.length}
</Badge>
<ChevronDown
className={cn(
'h-4 w-4 text-muted-foreground transition-transform',
!open && '-rotate-90',
)}
/>
</div>
</button>
{open && (
<div className="flex gap-1 pr-3 shrink-0">
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-[10px]"
onClick={(e) => {
e.stopPropagation()
setSectionAll(filtered, '1')
}}
>
All On
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-[10px]"
onClick={(e) => {
e.stopPropagation()
setSectionAll(filtered, '0')
}}
>
All Off
</Button>
</div>
)}
</div>
{open && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-px bg-border">
{filtered.map((key) => (
<div
key={key}
className={cn(
'flex items-center justify-between px-3 py-2 bg-card',
(perms[key] ?? '0') !== '0' && 'bg-emerald-500/5',
)}
>
<span className="font-mono text-xs truncate mr-3">{key}</span>
<PermToggle
value={perms[key] ?? '0'}
maxValue={initialRank.permissionMaxValues[key] ?? 1}
onChange={(v) => setPerms((p) => ({ ...p, [key]: v }))}
/>
</div>
))}
</div>
)}
</div>
)
}
const filteredCms = cmsSearch
? allCmsPermissions.filter(
(p) =>
p.slug.toLowerCase().includes(cmsSearch.toLowerCase()) ||
p.title?.toLowerCase().includes(cmsSearch.toLowerCase()),
)
: allCmsPermissions
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center gap-3">
<Link href="/admin/permissions">
<Button variant="ghost" size="icon" className="h-8 w-8">
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
{initialRank.id >= 7 ? (
<Crown className="h-6 w-6 text-yellow-500" />
) : initialRank.id >= 5 ? (
<ShieldCheck className="h-6 w-6 text-blue-500" />
) : (
<Shield className="h-6 w-6 text-muted-foreground" />
)}
<div>
<h1 className="text-2xl font-bold">{general.rank_name || `Rank ${initialRank.id}`}</h1>
<p className="text-sm text-muted-foreground">
Rank #{initialRank.id} &middot; Level {initialRank.level} &middot; {totalUsers} users
</p>
</div>
</div>
{/* Tabs */}
<Tabs defaultValue="general">
<TabsList>
<TabsTrigger value="general">
<Settings className="w-3.5 h-3.5 mr-1" /> General
</TabsTrigger>
<TabsTrigger value="emulator">
<Terminal className="w-3.5 h-3.5 mr-1" /> Emulator ({enabledCount})
</TabsTrigger>
<TabsTrigger value="cms">
<UserCheck className="w-3.5 h-3.5 mr-1" /> CMS ({cmsPermSlugs.length})
</TabsTrigger>
<TabsTrigger value="users">Users ({totalUsers})</TabsTrigger>
</TabsList>
{/* ═══ General ═══ */}
<TabsContent value="general" className="space-y-4">
<Card>
<CardHeader>
<CardTitle className="text-base">Rank Settings</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
<div className="space-y-1.5">
<Label className="text-xs">Rank Name</Label>
<Input
value={general.rank_name}
onChange={(e) => setGeneral({ ...general, rank_name: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Badge</Label>
<Input
value={general.badge}
onChange={(e) => setGeneral({ ...general, badge: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Prefix</Label>
<Input
value={general.prefix}
onChange={(e) => setGeneral({ ...general, prefix: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Prefix Color</Label>
<div className="flex gap-2">
<Input
value={general.prefix_color}
onChange={(e) => setGeneral({ ...general, prefix_color: e.target.value })}
/>
{general.prefix_color && (
<div
className="w-9 h-9 rounded border shrink-0"
style={{
backgroundColor: general.prefix_color.startsWith('#')
? general.prefix_color
: `#${general.prefix_color}`,
}}
/>
)}
</div>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-4">
<div className="flex items-center justify-between rounded-lg border p-3">
<div>
<Label className="text-sm">Hidden Rank</Label>
<p className="text-xs text-muted-foreground">Hide from public</p>
</div>
<Switch
checked={general.hidden_rank === '1'}
onCheckedChange={(v) => setGeneral({ ...general, hidden_rank: v ? '1' : '0' })}
/>
</div>
<div className="flex items-center justify-between rounded-lg border p-3">
<div>
<Label className="text-sm">Log Commands</Label>
<p className="text-xs text-muted-foreground">Record to audit log</p>
</div>
<Switch
checked={general.log_commands === '1'}
onCheckedChange={(v) => setGeneral({ ...general, log_commands: v ? '1' : '0' })}
/>
</div>
<div className="space-y-1.5 rounded-lg border p-3">
<Label className="text-xs">Room Effect ID</Label>
<Input
type="number"
value={general.room_effect}
onChange={(e) => setNum('room_effect', e.target.value)}
/>
</div>
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4">
<div className="space-y-1.5">
<Label className="text-xs">Auto Credits</Label>
<Input
type="number"
value={general.auto_credits_amount}
onChange={(e) => setNum('auto_credits_amount', e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Auto Pixels</Label>
<Input
type="number"
value={general.auto_pixels_amount}
onChange={(e) => setNum('auto_pixels_amount', e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Auto GOTW</Label>
<Input
type="number"
value={general.auto_gotw_amount}
onChange={(e) => setNum('auto_gotw_amount', e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Auto Points</Label>
<Input
type="number"
value={general.auto_points_amount}
onChange={(e) => setNum('auto_points_amount', e.target.value)}
/>
</div>
</div>
<div className="flex justify-end mt-4">
<Button onClick={saveRank} disabled={isPending} size="sm">
{isPending ? (
<Loader2 className="w-4 h-4 mr-1 animate-spin" />
) : (
<Save className="w-4 h-4 mr-1" />
)}
Save
</Button>
</div>
</CardContent>
</Card>
{/* Users preview */}
<Card>
<CardHeader>
<CardTitle className="text-base">
Users with this rank
{totalUsers > users.length && (
<span className="text-muted-foreground font-normal ml-1 text-sm">
(showing {users.length} of {totalUsers})
</span>
)}
</CardTitle>
</CardHeader>
<CardContent>
{users.length === 0 ? (
<p className="text-sm text-muted-foreground">No users with this rank.</p>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2">
{users.map((u) => (
<Link
key={u.id}
href={`/admin/users/show/${u.id}`}
className="flex items-center gap-2 rounded-lg border p-2 hover:bg-muted/50 transition-colors"
>
<img
src={getAvatarUrl(u.look, { size: 's', headDirection: 2 })}
alt=""
className="w-8 h-12 object-cover"
/>
<span className="text-xs font-medium truncate">{u.username}</span>
</Link>
))}
</div>
)}
</CardContent>
</Card>
</TabsContent>
{/* ═══ Emulator Permissions ═══ */}
<TabsContent value="emulator" className="space-y-4">
<div className="flex items-center justify-between flex-wrap gap-2">
<p className="text-sm text-muted-foreground">
{enabledCount} of {totalCount} permissions enabled
</p>
<div className="flex items-center gap-3">
<div className="flex gap-1">
<Button
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={() => setAllPerms('1')}
>
Enable All
</Button>
<Button
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={() => setAllPerms('0')}
>
Disable All
</Button>
</div>
<div className="flex gap-2 text-[11px] text-muted-foreground">
<span className="flex items-center gap-1">
<span className="w-3 h-3 rounded bg-zinc-500 inline-block" /> Off
</span>
<span className="flex items-center gap-1">
<span className="w-3 h-3 rounded bg-emerald-500 inline-block" /> On
</span>
<span className="flex items-center gap-1">
<span className="w-3 h-3 rounded bg-amber-500 inline-block" /> Owner
</span>
</div>
</div>
</div>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search permissions..."
value={permSearch}
onChange={(e) => setPermSearch(e.target.value)}
className="pl-9"
/>
</div>
<PermSection title="Commands" keys={cats.commands} sectionKey="cmd" />
<PermSection title="Account" keys={cats.account} sectionKey="acc" />
{cats.other.length > 0 && (
<PermSection title="Other" keys={cats.other} sectionKey="other" />
)}
<div className="flex justify-end">
<Button onClick={saveRank} disabled={isPending}>
{isPending ? (
<Loader2 className="w-4 h-4 mr-1 animate-spin" />
) : (
<Save className="w-4 h-4 mr-1" />
)}
Save Rank
</Button>
</div>
</TabsContent>
{/* ═══ CMS Permissions ═══ */}
<TabsContent value="cms" className="space-y-4">
{initialRank.id < 4 ? (
<div className="rounded-lg border bg-card p-6 text-center">
<p className="text-muted-foreground">
CMS permissions are available from rank 4 and above.
</p>
</div>
) : (
<>
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
{cmsPermSlugs.length} of {allCmsPermissions.length} assigned
</p>
<div className="flex gap-1">
<Button
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={async () => {
if (!initialCmsRole) return
const all = allCmsPermissions.map((p) => p.slug)
setCmsPermSlugs(all)
const r = await setCmsPermissions({
roleId: initialCmsRole.id,
permissionSlugs: all,
})
if (!r.ok) {
setCmsPermSlugs(initialCmsRole.permissionSlugs)
toast.error('Failed')
}
}}
>
Select All
</Button>
<Button
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={async () => {
if (!initialCmsRole) return
setCmsPermSlugs([])
const r = await setCmsPermissions({
roleId: initialCmsRole.id,
permissionSlugs: [],
})
if (!r.ok) {
setCmsPermSlugs(initialCmsRole.permissionSlugs)
toast.error('Failed')
}
}}
>
Deselect All
</Button>
</div>
</div>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search CMS permissions..."
value={cmsSearch}
onChange={(e) => setCmsSearch(e.target.value)}
className="pl-9"
/>
</div>
<div className="space-y-1">
{filteredCms.map((perm) => {
const on = cmsPermSlugs.includes(perm.slug)
return (
<div
key={perm.id}
className={cn(
'flex items-center gap-3 rounded-lg border px-4 py-3 transition-all',
on ? 'border-emerald-500/40 bg-emerald-500/5' : 'hover:bg-muted/50',
)}
>
<Checkbox checked={on} onCheckedChange={() => toggleCms(perm.slug)} />
<div className="flex-1 min-w-0">
<span className="text-sm font-mono">{perm.slug}</span>
{perm.title && (
<span className="text-xs text-muted-foreground ml-2">{perm.title}</span>
)}
</div>
{on && (
<Badge className="bg-emerald-500/15 text-emerald-600 border-emerald-500/30 text-[10px]">
Active
</Badge>
)}
</div>
)
})}
</div>
{filteredCms.length === 0 && (
<p className="text-sm text-muted-foreground text-center py-4">
No permissions match your search.
</p>
)}
</>
)}
</TabsContent>
{/* ═══ Users ═══ */}
<TabsContent value="users">
<Card>
<CardHeader>
<CardTitle className="text-base">
Users with this rank
{totalUsers > users.length && (
<span className="text-muted-foreground font-normal ml-1 text-sm">
(showing {users.length} of {totalUsers})
</span>
)}
</CardTitle>
</CardHeader>
<CardContent>
{users.length === 0 ? (
<p className="text-sm text-muted-foreground">No users with this rank.</p>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2">
{users.map((u) => (
<Link
key={u.id}
href={`/admin/users/show/${u.id}`}
className="flex items-center gap-2 rounded-lg border p-2 hover:bg-muted/50 transition-colors"
>
<img
src={getAvatarUrl(u.look, { size: 's', headDirection: 2 })}
alt=""
className="w-8 h-12 object-cover"
/>
<span className="text-xs font-medium truncate">{u.username}</span>
</Link>
))}
</div>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function PermissionsLoading() {
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>
)
}
+32 -142
View File
@@ -1,150 +1,40 @@
import {
createPermission,
deletePermission,
updatePermission,
} from "@/actions/admin-permissions";
import { StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
import { Shield } from "lucide-react";
import { getTranslations } from "next-intl/server";
import { redirect } from 'next/navigation'
import { Prisma } from '@/generated/prisma/client'
import { getAdminContext } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { fetchEmulatorRankSummaries } from '@/lib/services/permission-ranks'
import { PermissionsList } from './permissions-list'
export const dynamic = "force-dynamic";
export default async function PermissionsPage(_props: { params: Promise<{ locale: string }> }) {
const { permissions } = await getAdminContext()
if (!permissions.isSuperAdmin) redirect('/admin')
// Manages website_permissions (model WebsitePermissions) — the CMS-owned
// permission -> minimum-rank mapping. Each row names a permission and the lowest
// rank allowed to use it, with an optional description.
type PermissionRow = {
id: bigint;
permission: string;
minRank: number;
description: string | null;
};
const ranks = await fetchEmulatorRankSummaries(prisma)
export default async function AdminPermissions() {
const t = await getTranslations("pages.admin.permissions");
let permissions: PermissionRow[] = [];
try {
permissions = await prisma.websitePermissions.findMany({
select: { id: true, permission: true, minRank: true, description: true },
orderBy: { minRank: "asc" },
take: 500,
});
} catch {
permissions = [];
// User counts per rank
const rawCounts: { rank: number; cnt: number }[] = await prisma.$queryRaw(
Prisma.sql`SELECT \`rank\`, COUNT(*) as cnt FROM users GROUP BY \`rank\``,
)
const countMap: Record<number, number> = {}
for (const row of rawCounts) {
countMap[Number(row.rank)] = Number(row.cnt)
}
const highestRank = permissions.reduce((max, p) => Math.max(max, p.minRank), 0);
// Auto-create CMS roles for ranks >= 4
for (const rank of ranks) {
if (rank.id >= 4) {
await prisma.aclRole.upsert({
where: { slug: `rank_${rank.id}` },
create: { slug: `rank_${rank.id}`, title: rank.rank_name || `Rank ${rank.id}` },
update: {},
})
}
}
return (
<main>
<div className="flex items-center gap-3 mb-6">
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-[var(--color-primary)]/20 to-[var(--color-primary)]/5 grid place-items-center">
<Shield size={20} className="text-[var(--color-primary)]" />
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle")}</p>
</div>
</div>
const ranksWithCounts = ranks.map((rank) => ({
...rank,
userCount: countMap[rank.id] ?? 0,
}))
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("permissions")} value={permissions.length} icon="🔑" />
<StatusCard label={t("highestMinRank")} value={highestRank} icon="🎖️" />
</div>
<form action={createPermission} className="admin-card mb-6">
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addPermission")}</h3>
<div className="flex gap-2 flex-wrap">
<input name="permission" placeholder={t("permissionPlaceholder")} required maxLength={255} />
<input
name="minRank"
type="number"
min={0}
placeholder={t("minRankPlaceholder")}
defaultValue={1}
className="w-[110px]"
/>
<input
name="description"
placeholder={t("descriptionPlaceholder")}
className="flex-1 min-w-[160px]"
/>
<button type="submit" className="btn btn-primary">
{t("save")}
</button>
</div>
</form>
<section className="mt-6">
<h2 className="admin-section-title">{t("permissions")} ({permissions.length})</h2>
{permissions.length === 0 ? (
<div className="admin-empty">{t("noPermissions")}</div>
) : (
<div className="overflow-x-auto">
<table>
<thead>
<tr>
<th>{t("colId")}</th>
<th>{t("colPermission")}</th>
<th>{t("colMinRank")}</th>
<th>{t("colDescription")}</th>
<th />
</tr>
</thead>
<tbody>
{permissions.map((p) => (
<tr key={String(p.id)}>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{String(p.id)}</td>
<td>
<form
id={`perm-${String(p.id)}`}
action={updatePermission}
style={{ display: "contents" }}
>
<input type="hidden" name="id" value={String(p.id)} />
<input name="permission" defaultValue={p.permission} required maxLength={255} />
</form>
</td>
<td>
<input
form={`perm-${String(p.id)}`}
name="minRank"
type="number"
min={0}
defaultValue={p.minRank}
className="w-[90px]"
/>
</td>
<td>
<input
form={`perm-${String(p.id)}`}
name="description"
defaultValue={p.description ?? ""}
className="w-full"
/>
</td>
<td className="flex gap-2">
<button
type="submit"
form={`perm-${String(p.id)}`}
className="btn btn-primary"
>
{t("save")}
</button>
<form action={deletePermission}>
<input type="hidden" name="id" value={String(p.id)} />
<button type="submit" className="btn btn-danger">
{t("delete")}
</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</main>
);
return <PermissionsList ranks={ranksWithCounts} />
}
@@ -0,0 +1,267 @@
'use client'
import {
Crown,
EyeOff,
Pencil,
Plus,
Shield,
ShieldCheck,
Trash2,
UserCheck,
Users,
} from 'lucide-react'
import Link from 'next/link'
import { useState } from 'react'
import { toast } from 'sonner'
import { createRank, deleteRank } from '@/actions/permissions'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useServerAction } from '@/hooks/use-server-action'
interface RankSummary {
id: number
rank_name: string
badge: string
level: number
prefix: string
prefix_color: string
hidden_rank: string
userCount: number
}
interface Props {
ranks: RankSummary[]
}
const RANK_ICONS: Record<number, React.ReactNode> = {
7: <Crown className="h-4 w-4 text-yellow-500" />,
6: <ShieldCheck className="h-4 w-4 text-red-500" />,
5: <Shield className="h-4 w-4 text-blue-500" />,
4: <UserCheck className="h-4 w-4 text-green-500" />,
}
const RANK_COLORS: Record<number, string> = {
7: 'border-yellow-500/50 bg-yellow-500/5',
6: 'border-red-500/30 bg-red-500/5',
5: 'border-blue-500/30 bg-blue-500/5',
4: 'border-green-500/30 bg-green-500/5',
}
export function PermissionsList({ ranks: initialRanks }: Props) {
const { run, isPending } = useServerAction()
const [ranks, setRanks] = useState(initialRanks)
const [deleteTarget, setDeleteTarget] = useState<RankSummary | null>(null)
const [showCreate, setShowCreate] = useState(false)
const [newRankName, setNewRankName] = useState('')
const [newRankLevel, setNewRankLevel] = useState('')
const totalUsers = ranks.reduce((sum, r) => sum + r.userCount, 0)
function handleCreate() {
const level = parseInt(newRankLevel, 10)
if (!newRankName.trim() || !level || level < 1) {
toast.error('Name and a valid level are required')
return
}
run(() => createRank({ rank_name: newRankName.trim(), level }), {
successMessage: 'Rank created',
onSuccess: () => {
setShowCreate(false)
setNewRankName('')
setNewRankLevel('')
},
})
}
function handleDelete() {
if (!deleteTarget) return
run(() => deleteRank({ id: deleteTarget.id }), {
successMessage: 'Rank deleted',
onSuccess: () => {
setRanks((prev) => prev.filter((r) => r.id !== deleteTarget!.id))
setDeleteTarget(null)
},
})
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
<ShieldCheck className="h-7 w-7" />
Permissions
</h1>
<p className="text-muted-foreground">
{ranks.length} ranks &middot; {totalUsers.toLocaleString()} users total
</p>
</div>
<Button onClick={() => setShowCreate(true)}>
<Plus className="h-4 w-4 mr-1.5" />
New Rank
</Button>
</div>
{/* Rank cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{ranks.map((rank) => {
const prefixColor = rank.prefix_color
? rank.prefix_color.startsWith('#')
? rank.prefix_color
: `#${rank.prefix_color}`
: undefined
return (
<div
key={rank.id}
className={`rounded-xl border p-4 flex flex-col gap-3 hover:shadow-lg transition-all ${RANK_COLORS[rank.id] || ''}`}
>
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{RANK_ICONS[rank.id] || <Shield className="h-4 w-4 text-muted-foreground" />}
<span className="font-bold">{rank.rank_name || `Rank ${rank.id}`}</span>
</div>
<div className="flex items-center gap-1.5">
{rank.hidden_rank === '1' && (
<span title="Hidden rank">
<EyeOff className="h-3.5 w-3.5 text-muted-foreground" />
</span>
)}
<Badge variant="secondary" className="font-mono text-[10px]">
#{rank.id}
</Badge>
</div>
</div>
{/* Badges row */}
<div className="flex flex-wrap gap-1.5">
<Badge variant="outline" className="text-[11px]">
Level {rank.level}
</Badge>
{rank.badge && (
<Badge variant="outline" className="font-mono text-[11px]">
{rank.badge}
</Badge>
)}
{rank.prefix && (
<Badge
variant="outline"
className="text-[11px]"
style={{ color: prefixColor, borderColor: prefixColor }}
>
{rank.prefix}
</Badge>
)}
</div>
{/* User count */}
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Users className="h-3 w-3" />
{rank.userCount.toLocaleString()} users
</div>
{/* Actions */}
<div className="flex gap-2 mt-auto pt-1">
<Link href={`/admin/permissions/${rank.id}`} className="flex-1">
<Button variant="outline" size="sm" className="w-full">
<Pencil className="h-3.5 w-3.5 mr-1.5" />
Configure
</Button>
</Link>
<Button
variant="outline"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive shrink-0"
disabled={rank.userCount > 0 || isPending}
onClick={() => setDeleteTarget(rank)}
title={
rank.userCount > 0 ? `Cannot delete: ${rank.userCount} users` : 'Delete rank'
}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</div>
)
})}
</div>
{/* Create rank dialog */}
<Dialog open={showCreate} onOpenChange={setShowCreate}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Rank</DialogTitle>
<DialogDescription>
Add a new permission rank. You can configure its permissions after creation.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label>Rank Name</Label>
<Input
value={newRankName}
onChange={(e) => setNewRankName(e.target.value)}
placeholder="e.g. Moderator"
/>
</div>
<div className="space-y-2">
<Label>Level</Label>
<Input
type="number"
value={newRankLevel}
onChange={(e) => setNewRankLevel(e.target.value)}
placeholder="e.g. 5"
min={1}
/>
<p className="text-xs text-muted-foreground">
Higher level = more base permissions in the emulator
</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowCreate(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={isPending}>
{isPending ? 'Creating...' : 'Create'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete confirmation dialog */}
<Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Delete Rank #{deleteTarget?.id}?</DialogTitle>
<DialogDescription>
This will permanently delete &quot;{deleteTarget?.rank_name}&quot; and its CMS role.
This cannot be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteTarget(null)}>
Cancel
</Button>
<Button variant="destructive" onClick={handleDelete} disabled={isPending}>
{isPending ? 'Deleting...' : 'Delete'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
+21 -4
View File
@@ -51,12 +51,27 @@ export default async function AdminPhotos() {
<img
src={p.url}
alt={t("photoAlt", { id: String(p.id) })}
style={{ width: "100%", height: 200, objectFit: "cover", display: "block", background: "#f1f5f9" }}
style={{
width: "100%",
height: 200,
objectFit: "cover",
display: "block",
background: "#f1f5f9",
}}
/>
<div style={{ padding: "0.85rem 1.05rem 1.05rem" }}>
<div style={{ display: "flex", justifyContent: "space-between", gap: "0.5rem", alignItems: "baseline" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
gap: "0.5rem",
alignItems: "baseline",
}}
>
<strong>#{String(p.id)}</strong>
<span className="text-sm text-gray-500 dark:text-gray-400">{t("colRoom")} {p.roomId}</span>
<span className="text-sm text-gray-500 dark:text-gray-400">
{t("colRoom")} {p.roomId}
</span>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400" style={{ margin: "0.3rem 0 0" }}>
{t("colUser")} {p.userId} ·{" "}
@@ -64,7 +79,9 @@ export default async function AdminPhotos() {
</p>
<form action={deletePhoto} style={{ marginTop: "0.75rem" }}>
<input type="hidden" name="id" value={String(p.id)} />
<button type="submit" className="btn btn-danger">{t("delete")}</button>
<button type="submit" className="btn btn-danger">
{t("delete")}
</button>
</form>
</div>
</div>
+20 -12
View File
@@ -90,9 +90,7 @@ export default async function AdminRadioApiKeysPage() {
{dbError ? (
<div className="admin-card" style={{ marginTop: "1rem" }}>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">
{t("apiKeysForm.dbError")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">{t("apiKeysForm.dbError")}</p>
</div>
) : (
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
@@ -115,9 +113,7 @@ export default async function AdminRadioApiKeysPage() {
<section className="mt-6">
<h2>{t("apiKeysForm.generateKey")}</h2>
<p className="text-xs text-gray-500 dark:text-gray-400">
{t("apiKeysForm.generateHint")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{t("apiKeysForm.generateHint")}</p>
<form action={createApiKey} className="admin-card">
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
@@ -190,17 +186,29 @@ export default async function AdminRadioApiKeysPage() {
<tbody>
{keys.map((k) => (
<tr key={String(k.id)}>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{String(k.id)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{String(k.id)}
</td>
<td>{k.name}</td>
<td>
<code title={t("apiKeysForm.maskedHint")}>{maskKey(k.key)}</code>
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{k.allowedIps || t("apiKeysForm.any")}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{k.rateLimit}/min</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDate(k.lastUsedAt)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDate(k.expiresAt)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{k.allowedIps || t("apiKeysForm.any")}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{k.rateLimit}/min
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDate(k.lastUsedAt)}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDate(k.expiresAt)}
</td>
<td>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${k.isActive ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${k.isActive ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}
>
{k.isActive ? t("apiKeysForm.activeLabel") : t("apiKeysForm.inactiveLabel")}
</span>
</td>
+59 -47
View File
@@ -1,14 +1,14 @@
import Link from 'next/link';
import Image from 'next/image';
import { createTrack, deleteTrack, toggleTrack } from '@/actions/admin-radio-autodj';
import { StatusCard } from '@/components/admin/dashboard';
import { prisma } from '@/lib/prisma';
import { Disc3 } from 'lucide-react';
import Link from "next/link";
import Image from "next/image";
import { createTrack, deleteTrack, toggleTrack } from "@/actions/admin-radio-autodj";
import { StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
import { Disc3 } from "lucide-react";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
export const metadata = { title: 'Radio AutoDJ' };
export const metadata = { title: "Radio AutoDJ" };
type Track = {
id: bigint;
@@ -24,14 +24,14 @@ type Track = {
};
function formatDuration(seconds: number | null): string {
if (seconds == null || seconds < 0) return '\u2014';
if (seconds == null || seconds < 0) return "\u2014";
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m}:${String(s).padStart(2, '0')}`;
return `${m}:${String(s).padStart(2, "0")}`;
}
function formatDate(d: Date | null): string {
return d ? d.toISOString().slice(0, 16).replace('T', ' ') : '\u2014';
return d ? d.toISOString().slice(0, 16).replace("T", " ") : "\u2014";
}
export default async function AdminRadioAutoDjPage() {
@@ -55,7 +55,7 @@ export default async function AdminRadioAutoDjPage() {
isActive: true,
sortOrder: true,
},
orderBy: [{ sortOrder: 'asc' }, { title: 'asc' }],
orderBy: [{ sortOrder: "asc" }, { title: "asc" }],
})
.catch(() => {
dbError = true;
@@ -72,11 +72,11 @@ export default async function AdminRadioAutoDjPage() {
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio/history">{t("history")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link> ·{" "}
<Link href="/admin/radio/autodj">{t("autoDj")}</Link>
</nav>
@@ -93,9 +93,7 @@ export default async function AdminRadioAutoDjPage() {
{dbError ? (
<div className="admin-card mb-6">
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">
{t("autoDjForm.dbError")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">{t("autoDjForm.dbError")}</p>
</div>
) : (
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
@@ -103,13 +101,13 @@ export default async function AdminRadioAutoDjPage() {
<StatusCard
label={t("autoDjForm.active")}
value={activeCount}
state={activeCount > 0 ? 'ok' : 'neutral'}
state={activeCount > 0 ? "ok" : "neutral"}
icon="\u{25B6}\uFE0F"
/>
<StatusCard
label={t("autoDjForm.inactive")}
value={inactiveCount}
state={inactiveCount > 0 ? 'warn' : 'neutral'}
state={inactiveCount > 0 ? "warn" : "neutral"}
icon="\u{23F8}\uFE0F"
/>
</div>
@@ -121,7 +119,7 @@ export default async function AdminRadioAutoDjPage() {
<form action={createTrack} className="admin-card">
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label htmlFor="new_title" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_title" style={{ display: "block", fontWeight: 700 }}>
{t("autoDjForm.title")}
</label>
<input
@@ -129,34 +127,34 @@ export default async function AdminRadioAutoDjPage() {
name="title"
placeholder={t("autoDjForm.titlePlaceholder")}
required
style={{ width: '100%' }}
style={{ width: "100%" }}
/>
</div>
<div>
<label htmlFor="new_artist" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_artist" style={{ display: "block", fontWeight: 700 }}>
{t("autoDjForm.artist")}
</label>
<input id="new_artist" name="artist" style={{ width: '100%' }} />
<input id="new_artist" name="artist" style={{ width: "100%" }} />
</div>
<div>
<label htmlFor="new_album" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_album" style={{ display: "block", fontWeight: 700 }}>
{t("autoDjForm.album")}
</label>
<input id="new_album" name="album" style={{ width: '100%' }} />
<input id="new_album" name="album" style={{ width: "100%" }} />
</div>
<div>
<label htmlFor="new_artworkUrl" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_artworkUrl" style={{ display: "block", fontWeight: 700 }}>
{t("autoDjForm.artworkUrl")}
</label>
<input
id="new_artworkUrl"
name="artworkUrl"
placeholder={t("autoDjForm.artworkUrlPlaceholder")}
style={{ width: '100%' }}
style={{ width: "100%" }}
/>
</div>
<div>
<label htmlFor="new_duration" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_duration" style={{ display: "block", fontWeight: 700 }}>
{t("autoDjForm.duration")}
</label>
<input
@@ -165,11 +163,11 @@ export default async function AdminRadioAutoDjPage() {
type="number"
min={0}
placeholder={t("autoDjForm.durationPlaceholder")}
style={{ width: '100%' }}
style={{ width: "100%" }}
/>
</div>
<div>
<label htmlFor="new_sortOrder" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_sortOrder" style={{ display: "block", fontWeight: 700 }}>
{t("autoDjForm.sortOrder")}
</label>
<input
@@ -177,16 +175,16 @@ export default async function AdminRadioAutoDjPage() {
name="sortOrder"
type="number"
defaultValue={0}
style={{ width: '100%' }}
style={{ width: "100%" }}
/>
</div>
<div style={{ display: 'flex', alignItems: 'flex-end' }}>
<label style={{ display: 'inline-flex', gap: '0.4rem', alignItems: 'center' }}>
<div style={{ display: "flex", alignItems: "flex-end" }}>
<label style={{ display: "inline-flex", gap: "0.4rem", alignItems: "center" }}>
<input type="checkbox" name="isActive" value="1" defaultChecked /> {t("autoDjForm.active")}
</label>
</div>
</div>
<div style={{ marginTop: '0.75rem' }}>
<div style={{ marginTop: "0.75rem" }}>
<button type="submit" className="btn btn-primary">
{t("autoDjForm.addTrack")}
</button>
@@ -217,7 +215,9 @@ export default async function AdminRadioAutoDjPage() {
<tbody>
{tracks.map((track) => (
<tr key={String(track.id)}>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{track.sortOrder}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{track.sortOrder}
</td>
<td>
<span className="inline-flex gap-2 items-center">
{track.artworkUrl ? (
@@ -226,28 +226,40 @@ export default async function AdminRadioAutoDjPage() {
alt=""
width={32}
height={32}
style={{ borderRadius: 4, objectFit: 'cover' }}
style={{ borderRadius: 4, objectFit: "cover" }}
unoptimized
/>
) : null}
<strong>{track.title}</strong>
</span>
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{track.artist ?? '\u2014'}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{track.album ?? '\u2014'}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDuration(track.duration)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{track.playCount}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDate(track.lastPlayedAt)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{track.artist ?? "\u2014"}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{track.album ?? "\u2014"}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDuration(track.duration)}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{track.playCount}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDate(track.lastPlayedAt)}
</td>
<td>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${track.isActive ? 'bg-green-600/20 text-[var(--color-text)]' : 'bg-red-500/22 text-[var(--color-text)]'}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${track.isActive ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}
>
{track.isActive ? t("autoDjForm.activeLabel") : t("autoDjForm.inactiveLabel")}
</span>
</td>
<td>
<div style={{ display: 'flex', gap: '0.4rem', flexWrap: 'wrap' }}>
<div style={{ display: "flex", gap: "0.4rem", flexWrap: "wrap" }}>
<form action={toggleTrack}>
<input type="hidden" name="id" value={String(track.id)} />
<input type="hidden" name="isActive" value={track.isActive ? '0' : '1'} />
<input type="hidden" name="isActive" value={track.isActive ? "0" : "1"} />
<button type="submit" className="btn">
{track.isActive ? t("autoDjForm.deactivate") : t("autoDjForm.activate")}
</button>
+48 -76
View File
@@ -1,16 +1,12 @@
import Link from 'next/link';
import {
createRadioBanner,
deleteRadioBanner,
updateRadioBanner,
} from '@/actions/admin-radio-extra';
import { prisma } from '@/lib/prisma';
import { StatusCard } from '@/components/admin/dashboard';
import NextImage from 'next/image';
import { Image as LucideImage } from 'lucide-react';
import Link from "next/link";
import { createRadioBanner, deleteRadioBanner, updateRadioBanner } from "@/actions/admin-radio-extra";
import { prisma } from "@/lib/prisma";
import { StatusCard } from "@/components/admin/dashboard";
import NextImage from "next/image";
import { Image as LucideImage } from "lucide-react";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
type Banner = {
id: bigint;
@@ -24,7 +20,7 @@ type Banner = {
};
function formatDate(d: Date | null): string {
return d ? d.toISOString().slice(0, 16).replace('T', ' ') : '\u2014';
return d ? d.toISOString().slice(0, 16).replace("T", " ") : "\u2014";
}
export default async function AdminRadioBannersPage() {
@@ -45,7 +41,7 @@ export default async function AdminRadioBannersPage() {
isActive: true,
createdAt: true,
},
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
orderBy: [{ sortOrder: "asc" }, { id: "asc" }],
});
} catch {
dbError = true;
@@ -58,10 +54,10 @@ export default async function AdminRadioBannersPage() {
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link>
</nav>
@@ -77,9 +73,7 @@ export default async function AdminRadioBannersPage() {
{dbError ? (
<div className="admin-card mb-6">
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">
{t("banners.dbError")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">{t("banners.dbError")}</p>
</div>
) : (
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
@@ -87,13 +81,13 @@ export default async function AdminRadioBannersPage() {
<StatusCard
label={t("banners.statusActive")}
value={activeCount}
state={activeCount > 0 ? 'ok' : 'neutral'}
state={activeCount > 0 ? "ok" : "neutral"}
icon="\u{2705}"
/>
<StatusCard
label={t("banners.statusHidden")}
value={hiddenCount}
state={hiddenCount > 0 ? 'warn' : 'neutral'}
state={hiddenCount > 0 ? "warn" : "neutral"}
icon="\u{1F6AB}"
/>
</div>
@@ -104,7 +98,7 @@ export default async function AdminRadioBannersPage() {
<form action={createRadioBanner} className="admin-card">
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label htmlFor="new_imagePath" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_imagePath" style={{ display: "block", fontWeight: 700 }}>
{t("banners.form.imagePath")}
</label>
<input
@@ -112,28 +106,23 @@ export default async function AdminRadioBannersPage() {
name="imagePath"
placeholder={t("banners.form.imagePathPlaceholder")}
required
style={{ width: '100%' }}
style={{ width: "100%" }}
/>
</div>
<div>
<label htmlFor="new_title" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_title" style={{ display: "block", fontWeight: 700 }}>
{t("banners.form.title")}
</label>
<input id="new_title" name="title" style={{ width: '100%' }} />
<input id="new_title" name="title" style={{ width: "100%" }} />
</div>
<div style={{ gridColumn: '1 / -1' }}>
<label htmlFor="new_description" style={{ display: 'block', fontWeight: 700 }}>
<div style={{ gridColumn: "1 / -1" }}>
<label htmlFor="new_description" style={{ display: "block", fontWeight: 700 }}>
{t("banners.form.description")}
</label>
<textarea
id="new_description"
name="description"
rows={2}
style={{ width: '100%' }}
/>
<textarea id="new_description" name="description" rows={2} style={{ width: "100%" }} />
</div>
<div>
<label htmlFor="new_sortOrder" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_sortOrder" style={{ display: "block", fontWeight: 700 }}>
{t("banners.form.sortOrder")}
</label>
<input
@@ -141,16 +130,16 @@ export default async function AdminRadioBannersPage() {
name="sortOrder"
type="number"
defaultValue={0}
style={{ width: '100%' }}
style={{ width: "100%" }}
/>
</div>
<div style={{ display: 'flex', alignItems: 'flex-end' }}>
<label style={{ display: 'inline-flex', gap: '0.4rem', alignItems: 'center' }}>
<div style={{ display: "flex", alignItems: "flex-end" }}>
<label style={{ display: "inline-flex", gap: "0.4rem", alignItems: "center" }}>
<input type="checkbox" name="isActive" value="1" defaultChecked /> {t("banners.form.active")}
</label>
</div>
</div>
<div style={{ marginTop: '0.75rem' }}>
<div style={{ marginTop: "0.75rem" }}>
<button type="submit" className="btn btn-primary">
{t("banners.createBanner")}
</button>
@@ -169,8 +158,10 @@ export default async function AdminRadioBannersPage() {
<div className="flex justify-between items-baseline gap-3">
<strong>#{String(b.id)}</strong>
<span className="text-sm text-gray-500 dark:text-gray-400 inline-flex gap-2 items-center">
{t("banners.byUser", { id: String(b.userId) })} · {formatDate(b.createdAt)} ·{' '}
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${b.isActive ? 'bg-green-600/20 text-[var(--color-text)]' : 'bg-red-500/22 text-[var(--color-text)]'}`}>
{t("banners.byUser", { id: String(b.userId) })} · {formatDate(b.createdAt)} ·{" "}
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${b.isActive ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}
>
{b.isActive ? t("banners.active") : t("banners.hidden")}
</span>
</span>
@@ -191,10 +182,7 @@ export default async function AdminRadioBannersPage() {
<input type="hidden" name="id" value={String(b.id)} />
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label
htmlFor={`img_${b.id}`}
style={{ display: 'block', fontWeight: 700 }}
>
<label htmlFor={`img_${b.id}`} style={{ display: "block", fontWeight: 700 }}>
{t("banners.form.imagePath")}
</label>
<input
@@ -202,43 +190,34 @@ export default async function AdminRadioBannersPage() {
name="imagePath"
defaultValue={b.imagePath}
required
style={{ width: '100%' }}
style={{ width: "100%" }}
/>
</div>
<div>
<label
htmlFor={`title_${b.id}`}
style={{ display: 'block', fontWeight: 700 }}
>
<label htmlFor={`title_${b.id}`} style={{ display: "block", fontWeight: 700 }}>
{t("banners.form.title")}
</label>
<input
id={`title_${b.id}`}
name="title"
defaultValue={b.title ?? ''}
style={{ width: '100%' }}
defaultValue={b.title ?? ""}
style={{ width: "100%" }}
/>
</div>
<div style={{ gridColumn: '1 / -1' }}>
<label
htmlFor={`desc_${b.id}`}
style={{ display: 'block', fontWeight: 700 }}
>
<div style={{ gridColumn: "1 / -1" }}>
<label htmlFor={`desc_${b.id}`} style={{ display: "block", fontWeight: 700 }}>
{t("banners.form.description")}
</label>
<textarea
id={`desc_${b.id}`}
name="description"
rows={2}
defaultValue={b.description ?? ''}
style={{ width: '100%' }}
defaultValue={b.description ?? ""}
style={{ width: "100%" }}
/>
</div>
<div>
<label
htmlFor={`sort_${b.id}`}
style={{ display: 'block', fontWeight: 700 }}
>
<label htmlFor={`sort_${b.id}`} style={{ display: "block", fontWeight: 700 }}>
{t("banners.form.sortOrder")}
</label>
<input
@@ -246,31 +225,24 @@ export default async function AdminRadioBannersPage() {
name="sortOrder"
type="number"
defaultValue={b.sortOrder}
style={{ width: '100%' }}
style={{ width: "100%" }}
/>
</div>
<div style={{ display: 'flex', alignItems: 'flex-end' }}>
<label
style={{ display: 'inline-flex', gap: '0.4rem', alignItems: 'center' }}
>
<input
type="checkbox"
name="isActive"
value="1"
defaultChecked={b.isActive}
/>{' '}
<div style={{ display: "flex", alignItems: "flex-end" }}>
<label style={{ display: "inline-flex", gap: "0.4rem", alignItems: "center" }}>
<input type="checkbox" name="isActive" value="1" defaultChecked={b.isActive} />{" "}
{t("banners.form.active")}
</label>
</div>
</div>
<div style={{ marginTop: '0.6rem' }}>
<div style={{ marginTop: "0.6rem" }}>
<button type="submit" className="btn btn-primary">
{t("banners.save")}
</button>
</div>
</form>
<form action={deleteRadioBanner} style={{ marginTop: '0.5rem' }}>
<form action={deleteRadioBanner} style={{ marginTop: "0.5rem" }}>
<input type="hidden" name="id" value={String(b.id)} />
<button type="submit" className="btn btn-danger">
{t("banners.delete")}
+7 -11
View File
@@ -1,6 +1,6 @@
'use client';
"use client";
import { useState } from 'react';
import { useState } from "react";
/**
* Read-only copy box for an embed snippet. Renders the code inside a
@@ -27,28 +27,24 @@ export function EmbedSnippet({
// Clipboard API unavailable (e.g. insecure context) — fall back to
// selecting the textarea so the user can copy manually.
const el = document.getElementById(
`snippet-${title.replace(/\s+/g, '-').toLowerCase()}`,
`snippet-${title.replace(/\s+/g, "-").toLowerCase()}`,
) as HTMLTextAreaElement | null;
el?.select();
}
}
const id = `snippet-${title.replace(/\s+/g, '-').toLowerCase()}`;
const lines = snippet.split('\n').length;
const id = `snippet-${title.replace(/\s+/g, "-").toLowerCase()}`;
const lines = snippet.split("\n").length;
return (
<section className="mt-6">
<div className="flex items-center justify-between gap-4 mb-1">
<h2 className="m-0 text-base font-bold text-[var(--color-text)]">{title}</h2>
<button type="button" className="btn btn-primary" onClick={copy}>
{copied ? 'Copied!' : 'Copy'}
{copied ? "Copied!" : "Copy"}
</button>
</div>
{description ? (
<p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
{description}
</p>
) : null}
{description ? <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">{description}</p> : null}
<textarea
id={id}
readOnly
+35 -36
View File
@@ -1,54 +1,54 @@
import Link from 'next/link';
import { StatusCard } from '@/components/admin/dashboard';
import { siteSettings } from '@/lib/services/site-settings';
import { requireStaff } from '@/lib/admin/guard';
import { EmbedSnippet } from './embed-snippet';
import { Code } from 'lucide-react';
import Link from "next/link";
import { StatusCard } from "@/components/admin/dashboard";
import { siteSettings } from "@/lib/services/site-settings";
import { requireStaff } from "@/lib/admin/guard";
import { EmbedSnippet } from "./embed-snippet";
import { Code } from "lucide-react";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
export const metadata = { title: 'Radio Embed' };
export const metadata = { title: "Radio Embed" };
export default async function AdminRadioEmbedPage() {
await requireStaff();
const t = await getTranslations("pages.admin.radio");
let streamUrl = '';
let radioName = 'Radio';
let nowPlayingApiUrl = '';
let streamUrl = "";
let radioName = "Radio";
let nowPlayingApiUrl = "";
try {
streamUrl = (await siteSettings.get('radio_stream_url', '')) ?? '';
streamUrl = (await siteSettings.get("radio_stream_url", "")) ?? "";
radioName =
(await siteSettings.get('radio_name', null)) ??
(await siteSettings.get('hotel_name', 'Radio')) ??
'Radio';
nowPlayingApiUrl = (await siteSettings.get('radio_now_playing_api_url', '')) ?? '';
(await siteSettings.get("radio_name", null)) ??
(await siteSettings.get("hotel_name", "Radio")) ??
"Radio";
nowPlayingApiUrl = (await siteSettings.get("radio_now_playing_api_url", "")) ?? "";
} catch {
streamUrl = '';
streamUrl = "";
}
streamUrl = streamUrl.trim();
nowPlayingApiUrl = nowPlayingApiUrl.trim();
const hasStream = streamUrl !== '';
const hasStream = streamUrl !== "";
const audioSnippet = hasStream
? `<audio controls preload="none" src="${streamUrl}">\n ${t("embedPage.audioUnsupported")}\n</audio>`
: '';
: "";
const iframeSnippet = hasStream
? `<iframe\n src="/radio/embed"\n title="${radioName}"\n width="320"\n height="120"\n frameborder="0"\n allow="autoplay"\n style="border:0;border-radius:8px;overflow:hidden"\n></iframe>`
: '';
: "";
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/embed">{t("embed")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/embed">{t("embed")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link>
</nav>
@@ -67,14 +67,14 @@ export default async function AdminRadioEmbedPage() {
<StatusCard
label={t("embedPage.streamUrl")}
value={hasStream ? t("embedPage.configured") : t("embedPage.missing")}
state={hasStream ? 'ok' : 'danger'}
state={hasStream ? "ok" : "danger"}
icon="\u{1F4BB}"
/>
<StatusCard label={t("embedPage.radioName")} value={radioName} icon="\u{1F399}\uFE0F" />
<StatusCard
label={t("embedPage.nowPlayingApi")}
value={nowPlayingApiUrl ? t("embedPage.set") : t("embedPage.notSet")}
state={nowPlayingApiUrl ? 'ok' : 'neutral'}
state={nowPlayingApiUrl ? "ok" : "neutral"}
icon="\u{1F3B5}"
/>
</div>
@@ -83,9 +83,7 @@ export default async function AdminRadioEmbedPage() {
{!hasStream ? (
<section className="mt-6">
<h2 className="admin-section-title">{t("embedPage.noStreamUrl")}</h2>
<p className="text-xs text-gray-500 dark:text-gray-400">
{t("embedPage.noStreamUrlText")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{t("embedPage.noStreamUrlText")}</p>
<p>
<Link href="/admin/radio/settings" className="btn btn-primary">
{t("embedPage.goToSettings")}
@@ -96,15 +94,16 @@ export default async function AdminRadioEmbedPage() {
<>
<section className="mt-6">
<h2 className="admin-section-title">{t("embedPage.livePreview")}</h2>
<p className="text-xs text-gray-500 dark:text-gray-400">
{t("embedPage.livePreviewText")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{t("embedPage.livePreviewText")}</p>
<div className="admin-card">
{ }
<audio controls preload="none" src={streamUrl} style={{ width: '100%' }}>
{}
<audio controls preload="none" src={streamUrl} style={{ width: "100%" }}>
{t("embedPage.audioUnsupported")}
</audio>
<p className="text-xs text-gray-500 dark:text-gray-400" style={{ margin: '0.5rem 0 0', wordBreak: 'break-all' }}>
<p
className="text-xs text-gray-500 dark:text-gray-400"
style={{ margin: "0.5rem 0 0", wordBreak: "break-all" }}
>
{t("embedPage.source")}: <code>{streamUrl}</code>
</p>
</div>
+33 -30
View File
@@ -1,10 +1,10 @@
import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import { StatusCard } from '@/components/admin/dashboard';
import { Clock } from 'lucide-react';
import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { StatusCard } from "@/components/admin/dashboard";
import { Clock } from "lucide-react";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
type History = {
id: bigint;
@@ -17,13 +17,13 @@ type History = {
};
function formatDate(d: Date | null): string {
return d ? d.toISOString().slice(0, 16).replace('T', ' ') : '\u2014';
return d ? d.toISOString().slice(0, 16).replace("T", " ") : "\u2014";
}
function formatDuration(start: Date, end: Date | null): string {
if (!end) return '\u2014';
if (!end) return "\u2014";
const ms = end.getTime() - start.getTime();
if (ms <= 0) return '\u2014';
if (ms <= 0) return "\u2014";
const mins = Math.round(ms / 60000);
const h = Math.floor(mins / 60);
const m = mins % 60;
@@ -48,7 +48,7 @@ export default async function AdminRadioHistoryPage() {
listenersCount: true,
notes: true,
},
orderBy: { startedAt: 'desc' },
orderBy: { startedAt: "desc" },
take: 100,
});
@@ -68,19 +68,16 @@ export default async function AdminRadioHistoryPage() {
}
const liveCount = history.filter((h) => !h.endedAt).length;
const peakListeners = history.reduce(
(max, h) => (h.listenersCount > max ? h.listenersCount : max),
0,
);
const peakListeners = history.reduce((max, h) => (h.listenersCount > max ? h.listenersCount : max), 0);
const uniqueDjs = new Set(history.map((h) => String(h.userId))).size;
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link>
</nav>
@@ -96,9 +93,7 @@ export default async function AdminRadioHistoryPage() {
{dbError ? (
<div className="admin-card mb-6">
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">
{t("historyPage.dbError")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">{t("historyPage.dbError")}</p>
</div>
) : (
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
@@ -106,7 +101,7 @@ export default async function AdminRadioHistoryPage() {
<StatusCard
label={t("historyPage.onAirNow")}
value={liveCount}
state={liveCount > 0 ? 'ok' : 'neutral'}
state={liveCount > 0 ? "ok" : "neutral"}
icon="\u{1F534}"
/>
<StatusCard label={t("historyPage.uniqueDjs")} value={uniqueDjs} icon="\u{1F9D1}\u200D\u{1F3A4}" />
@@ -114,9 +109,7 @@ export default async function AdminRadioHistoryPage() {
</div>
)}
{!dbError && history.length === 0 ? (
<div className="admin-empty">{t("historyPage.empty")}</div>
) : null}
{!dbError && history.length === 0 ? <div className="admin-empty">{t("historyPage.empty")}</div> : null}
{history.length > 0 ? (
<section className="mt-6">
@@ -139,18 +132,28 @@ export default async function AdminRadioHistoryPage() {
<tr key={String(h.id)}>
<td>{String(h.id)}</td>
<td>{names.get(String(h.userId)) ?? `#${String(h.userId)}`}</td>
<td>{h.showName ?? '\u2014'}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDate(h.startedAt)}</td>
<td>{h.showName ?? "\u2014"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDate(h.startedAt)}
</td>
<td>
{h.endedAt ? (
<span className="text-sm text-gray-500 dark:text-gray-400">{formatDate(h.endedAt)}</span>
<span className="text-sm text-gray-500 dark:text-gray-400">
{formatDate(h.endedAt)}
</span>
) : (
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-green-600/20 text-[var(--color-text)]">{t("historyPage.onAir")}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-green-600/20 text-[var(--color-text)]">
{t("historyPage.onAir")}
</span>
)}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDuration(h.startedAt, h.endedAt)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDuration(h.startedAt, h.endedAt)}
</td>
<td>{h.listenersCount}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{h.notes ?? '\u2014'}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{h.notes ?? "\u2014"}
</td>
</tr>
))}
</tbody>
+16 -14
View File
@@ -1,11 +1,11 @@
import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import { deleteShout } from '@/actions/admin-radio-moderation';
import { StatusCard } from '@/components/admin/dashboard';
import { Shield } from 'lucide-react';
import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { deleteShout } from "@/actions/admin-radio-moderation";
import { StatusCard } from "@/components/admin/dashboard";
import { Shield } from "lucide-react";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
type Shout = {
id: bigint;
@@ -16,7 +16,7 @@ type Shout = {
};
function formatDate(d: Date | null): string {
return d ? d.toISOString().slice(0, 16).replace('T', ' ') : '\u2014';
return d ? d.toISOString().slice(0, 16).replace("T", " ") : "\u2014";
}
export default async function AdminRadioModerationPage() {
@@ -32,7 +32,7 @@ export default async function AdminRadioModerationPage() {
createdAt: true,
updatedAt: true,
},
orderBy: { id: 'desc' },
orderBy: { id: "desc" },
take: 50,
});
} catch {
@@ -42,11 +42,11 @@ export default async function AdminRadioModerationPage() {
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/moderation">{t("moderation")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/moderation">{t("moderation")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link>
</nav>
@@ -85,7 +85,9 @@ export default async function AdminRadioModerationPage() {
<td>{String(s.id)}</td>
<td>{String(s.userId)}</td>
<td>{s.message}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{formatDate(s.createdAt)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{formatDate(s.createdAt)}
</td>
<td>
<form action={deleteShout}>
<input type="hidden" name="id" value={String(s.id)} />
+67 -70
View File
@@ -1,13 +1,13 @@
import Link from 'next/link';
import { requireStaff } from '@/lib/admin/guard';
import { siteSettings } from '@/lib/services/site-settings';
import { StatusCard, DiagnosticRow } from '@/components/admin/dashboard';
import { Radio } from 'lucide-react';
import Link from "next/link";
import { requireStaff } from "@/lib/admin/guard";
import { siteSettings } from "@/lib/services/site-settings";
import { StatusCard, DiagnosticRow } from "@/components/admin/dashboard";
import { Radio } from "lucide-react";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
export const metadata = { title: 'Radio Monitoring' };
export const metadata = { title: "Radio Monitoring" };
const FETCH_TIMEOUT_MS = 4000;
@@ -25,14 +25,14 @@ async function probe(url: string): Promise<ProbeResult> {
try {
const res = await fetch(url, {
signal: controller.signal,
cache: 'no-store',
headers: { accept: 'application/json, text/plain, */*' },
cache: "no-store",
headers: { accept: "application/json, text/plain, */*" },
});
const raw = await res.text();
let json: unknown = null;
let text: string | null = null;
const trimmed = raw.trim();
if (trimmed !== '') {
if (trimmed !== "") {
try {
json = JSON.parse(trimmed);
} catch {
@@ -47,13 +47,13 @@ async function probe(url: string): Promise<ProbeResult> {
error: res.ok ? null : `HTTP ${res.status}`,
};
} catch (e) {
const aborted = e instanceof Error && e.name === 'AbortError';
const aborted = e instanceof Error && e.name === "AbortError";
return {
reachable: false,
status: null,
json: null,
text: null,
error: aborted ? `Timed out after ${FETCH_TIMEOUT_MS / 1000}s` : 'Fetch failed',
error: aborted ? `Timed out after ${FETCH_TIMEOUT_MS / 1000}s` : "Fetch failed",
};
} finally {
clearTimeout(timer);
@@ -61,13 +61,13 @@ async function probe(url: string): Promise<ProbeResult> {
}
function isRecord(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
return typeof v === "object" && v !== null && !Array.isArray(v);
}
function pickString(obj: Record<string, unknown>, key: string): string | null {
// eslint-disable-next-line security/detect-object-injection -- only called with hardcoded keys
const v = obj[key];
return typeof v === 'string' && v.trim() !== '' ? v.trim() : null;
return typeof v === "string" && v.trim() !== "" ? v.trim() : null;
}
function parseNowPlaying(result: ProbeResult): string | null {
@@ -75,46 +75,46 @@ function parseNowPlaying(result: ProbeResult): string | null {
return result.text && result.text.length <= 200 ? result.text : null;
}
const data = result.json;
if (typeof data === 'string') return data.trim() || null;
if (typeof data === "string") return data.trim() || null;
if (!isRecord(data)) return null;
const np = data.now_playing;
if (typeof np === 'string' && np.trim() !== '') return np.trim();
if (typeof np === "string" && np.trim() !== "") return np.trim();
if (isRecord(np)) {
const song = np.song;
if (isRecord(song)) {
const title = pickString(song, 'title');
const artist = pickString(song, 'artist');
const title = pickString(song, "title");
const artist = pickString(song, "artist");
if (title || artist) {
return [artist, title].filter(Boolean).join(' - ');
return [artist, title].filter(Boolean).join(" - ");
}
const txt = pickString(song, 'text');
const txt = pickString(song, "text");
if (txt) return txt;
}
}
const song = data.song;
if (isRecord(song)) {
const title = pickString(song, 'title');
const artist = pickString(song, 'artist');
if (title || artist) return [artist, title].filter(Boolean).join(' - ');
const title = pickString(song, "title");
const artist = pickString(song, "artist");
if (title || artist) return [artist, title].filter(Boolean).join(" - ");
}
const title = pickString(data, 'title');
const artist = pickString(data, 'artist');
if (title || artist) return [artist, title].filter(Boolean).join(' - ');
const title = pickString(data, "title");
const artist = pickString(data, "artist");
if (title || artist) return [artist, title].filter(Boolean).join(" - ");
return pickString(data, 'text') ?? pickString(data, 'song') ?? null;
return pickString(data, "text") ?? pickString(data, "song") ?? null;
}
function findNumberDeep(value: unknown, keys: string[], depth = 0): number | null {
if (depth > 4) return null;
if (typeof value === 'number' && Number.isFinite(value)) return value;
if (typeof value === "number" && Number.isFinite(value)) return value;
if (!isRecord(value)) return null;
for (const key of keys) {
// eslint-disable-next-line security/detect-object-injection -- keys from hardcoded array
const v = value[key];
if (typeof v === 'number' && Number.isFinite(v)) return v;
if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) {
if (typeof v === "number" && Number.isFinite(v)) return v;
if (typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v))) {
return Number(v);
}
}
@@ -135,21 +135,21 @@ function parseListeners(result: ProbeResult): number | null {
return null;
}
const data = result.json;
if (typeof data === 'number' && Number.isFinite(data)) return data;
if (typeof data === "number" && Number.isFinite(data)) return data;
return findNumberDeep(data, [
'current',
'total',
'num_listeners',
'listeners',
'unique_listeners',
'count',
"current",
"total",
"num_listeners",
"listeners",
"unique_listeners",
"count",
]);
}
function shortUrl(url: string): string {
try {
const u = new URL(url);
return u.host + (u.pathname === '/' ? '' : u.pathname);
return u.host + (u.pathname === "/" ? "" : u.pathname);
} catch {
return url.length > 60 ? `${url.slice(0, 57)}\u2026` : url;
}
@@ -164,9 +164,9 @@ export default async function AdminRadioMonitoringPage() {
let listenersUrl: string | null = null;
let streamUrl: string | null = null;
try {
nowPlayingUrl = (await siteSettings.get('radio_now_playing_api_url', '')) || null;
listenersUrl = (await siteSettings.get('radio_listeners_api_url', '')) || null;
streamUrl = (await siteSettings.get('radio_stream_url', '')) || null;
nowPlayingUrl = (await siteSettings.get("radio_now_playing_api_url", "")) || null;
listenersUrl = (await siteSettings.get("radio_listeners_api_url", "")) || null;
streamUrl = (await siteSettings.get("radio_stream_url", "")) || null;
} catch {
nowPlayingUrl = null;
listenersUrl = null;
@@ -195,11 +195,11 @@ export default async function AdminRadioMonitoringPage() {
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/monitoring">{t("monitoring.title")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/monitoring">{t("monitoring.title")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link>
</nav>
@@ -210,7 +210,9 @@ export default async function AdminRadioMonitoringPage() {
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("monitoring.title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("monitoring.subtitle", { timeout: FETCH_TIMEOUT_MS / 1000 })}</p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
{t("monitoring.subtitle", { timeout: FETCH_TIMEOUT_MS / 1000 })}
</p>
</div>
</div>
@@ -218,23 +220,27 @@ export default async function AdminRadioMonitoringPage() {
<StatusCard
label={t("monitoring.stream")}
value={
!streamConfigured ? t("monitoring.notConfigured") : streamOnline ? t("monitoring.online") : t("monitoring.offline")
!streamConfigured
? t("monitoring.notConfigured")
: streamOnline
? t("monitoring.online")
: t("monitoring.offline")
}
state={!streamConfigured ? 'neutral' : streamOnline ? 'ok' : 'danger'}
state={!streamConfigured ? "neutral" : streamOnline ? "ok" : "danger"}
hint={streamUrl ? shortUrl(streamUrl) : undefined}
icon="\u{1F4E1}"
/>
<StatusCard
label={t("monitoring.nowPlaying")}
value={nowPlaying ?? '\u2014'}
state={nowPlaying ? 'ok' : 'neutral'}
value={nowPlaying ?? "\u2014"}
state={nowPlaying ? "ok" : "neutral"}
hint={!nowPlayingUrl ? t("monitoring.noNowPlayingHint") : undefined}
icon="\u{1F3B5}"
/>
<StatusCard
label={t("monitoring.listeners")}
value={listeners ?? '\u2014'}
state={listeners != null ? 'ok' : 'neutral'}
value={listeners ?? "\u2014"}
state={listeners != null ? "ok" : "neutral"}
hint={!listenersUrl ? t("monitoring.noListenersHint") : undefined}
icon="\u{1F3A7}"
/>
@@ -243,38 +249,29 @@ export default async function AdminRadioMonitoringPage() {
<section className="mt-6">
<h2 className="admin-section-title">{t("monitoring.endpointDiagnostics")}</h2>
<p className="text-xs text-gray-500 dark:text-gray-400">
{t("monitoring.diagnosticsLegend")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{t("monitoring.diagnosticsLegend")}</p>
<div className="flex flex-col">
{endpoints.map((ep) => {
let state: 'ok' | 'warn' | 'danger';
let state: "ok" | "warn" | "danger";
let detail: string;
if (!ep.url) {
state = 'warn';
state = "warn";
detail = t("monitoring.notConfigured");
} else if (ep.result?.reachable) {
state = 'ok';
state = "ok";
detail = `${shortUrl(ep.url)}${
ep.result.status != null ? ` \u00B7 HTTP ${ep.result.status}` : ''
ep.result.status != null ? ` \u00B7 HTTP ${ep.result.status}` : ""
}`;
} else {
state = 'danger';
state = "danger";
detail = `${shortUrl(ep.url)} \u00B7 ${ep.result?.error ?? t("monitoring.unreachable")}`;
}
return (
<DiagnosticRow
key={ep.label}
label={ep.label}
detail={detail}
state={state}
/>
);
return <DiagnosticRow key={ep.label} label={ep.label} detail={detail} state={state} />;
})}
<DiagnosticRow
label={t("monitoring.streamUrl")}
detail={streamUrl ? shortUrl(streamUrl) : t("monitoring.notConfigured")}
state={streamUrl ? 'ok' : 'warn'}
state={streamUrl ? "ok" : "warn"}
/>
</div>
</section>
+42 -34
View File
@@ -1,10 +1,10 @@
import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import { deleteShout } from '@/actions/admin-radio';
import { StatusCard } from '@/components/admin/dashboard';
import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { deleteShout } from "@/actions/admin-radio-moderation";
import { StatusCard } from "@/components/admin/dashboard";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
type Shout = {
id: bigint;
@@ -35,18 +35,18 @@ type Schedule = {
};
function formatDate(d: Date | null): string {
return d ? d.toISOString().slice(0, 16).replace('T', ' ') : '\u2014';
return d ? d.toISOString().slice(0, 16).replace("T", " ") : "\u2014";
}
function formatTime(d: Date | null): string {
return d ? d.toISOString().slice(11, 16) : '\u2014';
return d ? d.toISOString().slice(11, 16) : "\u2014";
}
function statusBadgeClass(status: string): string {
const s = status.toLowerCase();
if (s === 'approved' || s === 'accepted') return 'ok';
if (s === 'rejected' || s === 'denied') return 'danger';
return '';
if (s === "approved" || s === "accepted") return "ok";
if (s === "rejected" || s === "denied") return "danger";
return "";
}
export default async function AdminRadioPage() {
@@ -59,7 +59,7 @@ export default async function AdminRadioPage() {
try {
shouts = await prisma.radioShouts.findMany({
select: { id: true, userId: true, message: true, createdAt: true },
orderBy: { id: 'desc' },
orderBy: { id: "desc" },
take: 25,
});
} catch {
@@ -78,7 +78,7 @@ export default async function AdminRadioPage() {
discordUsername: true,
createdAt: true,
},
orderBy: { id: 'desc' },
orderBy: { id: "desc" },
take: 25,
});
} catch {
@@ -96,52 +96,50 @@ export default async function AdminRadioPage() {
showName: true,
isActive: true,
},
orderBy: { id: 'desc' },
orderBy: { id: "desc" },
take: 25,
});
} catch {
schedules = [];
}
const pendingApps = applications.filter(
(a) => a.status.toLowerCase() === 'pending',
).length;
const pendingApps = applications.filter((a) => a.status.toLowerCase() === "pending").length;
const activeSchedules = schedules.filter((sc) => sc.isActive).length;
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link>
</nav>
<h1>{t("title")}</h1>
<p className="text-xs text-gray-500 dark:text-gray-400">
{t("subtitle")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{t("subtitle")}</p>
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("shouts")} value={shouts.length} icon="\u{1F4E3}" />
<StatusCard
label={t("pendingApplications")}
value={pendingApps}
state={pendingApps > 0 ? 'warn' : 'ok'}
state={pendingApps > 0 ? "warn" : "ok"}
icon="\u{1F4DD}"
/>
<StatusCard label={t("schedules")} value={schedules.length} icon="\u{1F5D3}\uFE0F" />
<StatusCard
label={t("activeSchedules")}
value={activeSchedules}
state={activeSchedules > 0 ? 'ok' : 'neutral'}
state={activeSchedules > 0 ? "ok" : "neutral"}
icon="\u{1F399}\uFE0F"
/>
</div>
<section className="mt-6">
<h2>{t("shouts")} ({shouts.length})</h2>
<h2>
{t("shouts")} ({shouts.length})
</h2>
{shouts.length === 0 ? (
<p className="text-xs text-gray-500 dark:text-gray-400">{t("noShouts")}</p>
) : (
@@ -158,7 +156,9 @@ export default async function AdminRadioPage() {
<tbody>
{shouts.map((s) => (
<tr key={String(s.id)}>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{String(s.id)}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{String(s.id)}
</td>
<td>{String(s.userId)}</td>
<td>{s.message}</td>
<td className="text-sm text-gray-500 dark:text-gray-400">{formatDate(s.createdAt)}</td>
@@ -178,7 +178,9 @@ export default async function AdminRadioPage() {
</section>
<section className="mt-6">
<h2>{t("applications")} ({applications.length})</h2>
<h2>
{t("applications")} ({applications.length})
</h2>
{applications.length === 0 ? (
<p className="text-xs text-gray-500 dark:text-gray-400">{t("noApplications")}</p>
) : (
@@ -202,10 +204,12 @@ export default async function AdminRadioPage() {
<td>{String(a.userId)}</td>
<td>{a.realName}</td>
<td>{a.age}</td>
<td>{a.musicStyle ?? '\u2014'}</td>
<td>{a.discordUsername ?? '\u2014'}</td>
<td>{a.musicStyle ?? "\u2014"}</td>
<td>{a.discordUsername ?? "\u2014"}</td>
<td>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${statusBadgeClass(a.status) === 'ok' ? 'bg-green-600/20 text-[var(--color-text)]' : statusBadgeClass(a.status) === 'danger' ? 'bg-red-500/22 text-[var(--color-text)]' : 'bg-[var(--color-primary)]/18 text-[var(--color-text)]'}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${statusBadgeClass(a.status) === "ok" ? "bg-green-600/20 text-[var(--color-text)]" : statusBadgeClass(a.status) === "danger" ? "bg-red-500/22 text-[var(--color-text)]" : "bg-[var(--color-primary)]/18 text-[var(--color-text)]"}`}
>
{a.status}
</span>
</td>
@@ -218,7 +222,9 @@ export default async function AdminRadioPage() {
</section>
<section className="mt-6">
<h2>{t("schedules")} ({schedules.length})</h2>
<h2>
{t("schedules")} ({schedules.length})
</h2>
{schedules.length === 0 ? (
<p className="text-xs text-gray-500 dark:text-gray-400">{t("noSchedules")}</p>
) : (
@@ -242,9 +248,11 @@ export default async function AdminRadioPage() {
<td>{sc.day}</td>
<td>{formatTime(sc.startTime)}</td>
<td>{formatTime(sc.endTime)}</td>
<td>{sc.showName ?? '\u2014'}</td>
<td>{sc.showName ?? "\u2014"}</td>
<td>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${sc.isActive ? 'bg-green-600/20 text-[var(--color-text)]' : 'bg-red-500/22 text-[var(--color-text)]'}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${sc.isActive ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}
>
{sc.isActive ? t("active") : t("inactive")}
</span>
</td>
+6 -13
View File
@@ -79,7 +79,9 @@ export default async function AdminRadioPointsPage({
{saved === "1" ? (
<p>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-green-600/20 text-[var(--color-text)]">{t("pointsForm.saved")}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-green-600/20 text-[var(--color-text)]">
{t("pointsForm.saved")}
</span>
</p>
) : null}
@@ -149,10 +151,7 @@ export default async function AdminRadioPointsPage({
</div>
<div>
<label
htmlFor="radio_points_per_minute"
style={{ display: "block", fontWeight: 700 }}
>
<label htmlFor="radio_points_per_minute" style={{ display: "block", fontWeight: 700 }}>
{t("pointsForm.pointsPerMinute")}
</label>
<input
@@ -170,10 +169,7 @@ export default async function AdminRadioPointsPage({
</div>
<div>
<label
htmlFor="radio_points_max_per_day"
style={{ display: "block", fontWeight: 700 }}
>
<label htmlFor="radio_points_max_per_day" style={{ display: "block", fontWeight: 700 }}>
{t("pointsForm.maxPerDay")}
</label>
<input
@@ -191,10 +187,7 @@ export default async function AdminRadioPointsPage({
</div>
<div>
<label
htmlFor="radio_points_min_listeners"
style={{ display: "block", fontWeight: 700 }}
>
<label htmlFor="radio_points_min_listeners" style={{ display: "block", fontWeight: 700 }}>
{t("pointsForm.minListeners")}
</label>
<input
+31 -42
View File
@@ -1,15 +1,11 @@
import Link from 'next/link';
import {
createRadioRank,
deleteRadioRank,
updateRadioRank,
} from '@/actions/admin-radio-extra';
import { prisma } from '@/lib/prisma';
import { StatusCard } from '@/components/admin/dashboard';
import { Medal } from 'lucide-react';
import Link from "next/link";
import { createRadioRank, deleteRadioRank, updateRadioRank } from "@/actions/admin-radio-extra";
import { prisma } from "@/lib/prisma";
import { StatusCard } from "@/components/admin/dashboard";
import { Medal } from "lucide-react";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
type Rank = {
id: bigint;
@@ -34,7 +30,7 @@ export default async function AdminRadioRanksPage() {
badgeCode: true,
isActive: true,
},
orderBy: { id: 'asc' },
orderBy: { id: "asc" },
});
} catch {
dbError = true;
@@ -46,10 +42,10 @@ export default async function AdminRadioRanksPage() {
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link>
</nav>
@@ -65,9 +61,7 @@ export default async function AdminRadioRanksPage() {
{dbError ? (
<div className="admin-card mb-6">
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">
{t("ranksForm.dbError")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">{t("ranksForm.dbError")}</p>
</div>
) : (
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
@@ -75,7 +69,7 @@ export default async function AdminRadioRanksPage() {
<StatusCard
label={t("ranksForm.active")}
value={activeCount}
state={activeCount > 0 ? 'ok' : 'neutral'}
state={activeCount > 0 ? "ok" : "neutral"}
icon="\u{2705}"
/>
</div>
@@ -86,30 +80,30 @@ export default async function AdminRadioRanksPage() {
<form action={createRadioRank} className="admin-card">
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<div>
<label htmlFor="new_name" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_name" style={{ display: "block", fontWeight: 700 }}>
{t("ranksForm.name")}
</label>
<input id="new_name" name="name" required style={{ width: '100%' }} />
<input id="new_name" name="name" required style={{ width: "100%" }} />
</div>
<div>
<label htmlFor="new_badge" style={{ display: 'block', fontWeight: 700 }}>
<label htmlFor="new_badge" style={{ display: "block", fontWeight: 700 }}>
{t("ranksForm.badgeCode")}
</label>
<input id="new_badge" name="badgeCode" style={{ width: '100%' }} />
<input id="new_badge" name="badgeCode" style={{ width: "100%" }} />
</div>
<div style={{ display: 'flex', alignItems: 'flex-end' }}>
<label style={{ display: 'inline-flex', gap: '0.4rem', alignItems: 'center' }}>
<div style={{ display: "flex", alignItems: "flex-end" }}>
<label style={{ display: "inline-flex", gap: "0.4rem", alignItems: "center" }}>
<input type="checkbox" name="isActive" value="1" defaultChecked /> {t("ranksForm.active")}
</label>
</div>
<div style={{ gridColumn: '1 / -1' }}>
<label htmlFor="new_desc" style={{ display: 'block', fontWeight: 700 }}>
<div style={{ gridColumn: "1 / -1" }}>
<label htmlFor="new_desc" style={{ display: "block", fontWeight: 700 }}>
{t("ranksForm.description")}
</label>
<input id="new_desc" name="description" style={{ width: '100%' }} />
<input id="new_desc" name="description" style={{ width: "100%" }} />
</div>
</div>
<div style={{ marginTop: '0.75rem' }}>
<div style={{ marginTop: "0.75rem" }}>
<button type="submit" className="btn btn-primary">
{t("ranksForm.createRank")}
</button>
@@ -127,7 +121,9 @@ export default async function AdminRadioRanksPage() {
<div key={String(r.id)} className="admin-card">
<div className="flex justify-between items-baseline gap-3 mb-2">
<strong>#{String(r.id)}</strong>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${r.isActive ? 'bg-green-600/20 text-[var(--color-text)]' : 'bg-red-500/22 text-[var(--color-text)]'}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${r.isActive ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}
>
{r.isActive ? t("ranksForm.activeLabel") : t("ranksForm.inactiveLabel")}
</span>
</div>
@@ -143,25 +139,18 @@ export default async function AdminRadioRanksPage() {
/>
<input
name="badgeCode"
defaultValue={r.badgeCode ?? ''}
defaultValue={r.badgeCode ?? ""}
placeholder={t("ranksForm.badgeCode")}
style={{ minWidth: 100 }}
/>
<input
name="description"
defaultValue={r.description ?? ''}
defaultValue={r.description ?? ""}
placeholder={t("ranksForm.description")}
className="flex-1 min-w-[160px]"
/>
<label
style={{ display: 'inline-flex', gap: '0.3rem', alignItems: 'center' }}
>
<input
type="checkbox"
name="isActive"
value="1"
defaultChecked={r.isActive}
/>{' '}
<label style={{ display: "inline-flex", gap: "0.3rem", alignItems: "center" }}>
<input type="checkbox" name="isActive" value="1" defaultChecked={r.isActive} />{" "}
{t("ranksForm.active")}
</label>
<button type="submit" className="btn btn-primary">
@@ -169,7 +158,7 @@ export default async function AdminRadioRanksPage() {
</button>
</form>
<form action={deleteRadioRank} style={{ marginTop: '0.5rem' }}>
<form action={deleteRadioRank} style={{ marginTop: "0.5rem" }}>
<input type="hidden" name="id" value={String(r.id)} />
<button type="submit" className="btn btn-danger">
{t("ranksForm.deleteRank", { id: String(r.id) })}
+144 -146
View File
@@ -1,181 +1,181 @@
import Link from 'next/link';
import { saveRadioSetting, saveRadioSettings } from '@/actions/admin-radio-extra';
import { prisma } from '@/lib/prisma';
import { StatusCard } from '@/components/admin/dashboard';
import { Settings } from 'lucide-react';
import Link from "next/link";
import { saveRadioSetting, saveRadioSettings } from "@/actions/admin-radio-extra";
import { prisma } from "@/lib/prisma";
import { StatusCard } from "@/components/admin/dashboard";
import { Settings } from "lucide-react";
import { getTranslations } from "next-intl/server";
export const dynamic = 'force-dynamic';
export const dynamic = "force-dynamic";
type Field = { key: string; comment: string };
type Group = { title: string; fields: Field[] };
const GROUPS: Group[] = [
{
title: 'AzureCast & Stream',
title: "AzureCast & Stream",
fields: [
{ key: 'radio_enabled', comment: 'Radio enabled (0=no, 1=yes)' },
{ key: 'radio_stream_url', comment: 'Main stream URL' },
{ key: 'radio_stream_backup_url', comment: 'Backup stream URL' },
{ key: 'radio_azurecast_base_url', comment: 'AzureCast base URL' },
{ key: 'radio_azurecast_station_id', comment: 'AzureCast station ID' },
{ key: 'radio_azurecast_api_key', comment: 'AzureCast API key' },
{ key: 'radio_azurecast_port', comment: 'AzureCast stream port' },
{ key: 'radio_azurecast_protocol', comment: 'AzureCast protocol (http/https)' },
{ key: 'radio_azurecast_use_proxy', comment: 'Use AzureCast proxy (0=no, 1=yes)' },
{ key: "radio_enabled", comment: "Radio enabled (0=no, 1=yes)" },
{ key: "radio_stream_url", comment: "Main stream URL" },
{ key: "radio_stream_backup_url", comment: "Backup stream URL" },
{ key: "radio_azurecast_base_url", comment: "AzureCast base URL" },
{ key: "radio_azurecast_station_id", comment: "AzureCast station ID" },
{ key: "radio_azurecast_api_key", comment: "AzureCast API key" },
{ key: "radio_azurecast_port", comment: "AzureCast stream port" },
{ key: "radio_azurecast_protocol", comment: "AzureCast protocol (http/https)" },
{ key: "radio_azurecast_use_proxy", comment: "Use AzureCast proxy (0=no, 1=yes)" },
],
},
{
title: 'External sources',
title: "External sources",
fields: [
{ key: 'radio_sambroadcaster_api_url', comment: 'Sambroadcaster API URL' },
{ key: 'radio_sambroadcaster_password', comment: 'Sambroadcaster password' },
{ key: 'radio_virtual_dj_url', comment: 'Virtual DJ URL' },
{ key: 'radio_virtual_dj_password', comment: 'Virtual DJ password' },
{ key: 'radio_djs_api_url', comment: 'DJs API URL' },
{ key: "radio_sambroadcaster_api_url", comment: "Sambroadcaster API URL" },
{ key: "radio_sambroadcaster_password", comment: "Sambroadcaster password" },
{ key: "radio_virtual_dj_url", comment: "Virtual DJ URL" },
{ key: "radio_virtual_dj_password", comment: "Virtual DJ password" },
{ key: "radio_djs_api_url", comment: "DJs API URL" },
],
},
{
title: 'Player',
title: "Player",
fields: [
{ key: 'radio_style', comment: 'Player style (dark/light/blue/purple/pink/gold)' },
{ key: 'radio_player_type', comment: 'Player type (default/minimal/embedded)' },
{ key: 'radio_auto_play', comment: 'Auto-play on page load (0=no, 1=yes)' },
{ key: 'radio_auto_play_delay', comment: 'Auto-play delay in seconds' },
{ key: 'radio_mute_on_start', comment: 'Muted on start (0=no, 1=yes)' },
{ key: 'radio_volume', comment: 'Default volume (0-100)' },
{ key: 'radio_language', comment: 'Default language (nl/en/de/fr/es/pt/it/br)' },
{ key: 'radio_multi_language_enabled', comment: 'Multi-language support (0=no, 1=yes)' },
{ key: 'radio_player_color_primary', comment: 'Player primary color' },
{ key: 'radio_player_color_secondary', comment: 'Player secondary color' },
{ key: 'radio_player_color_text', comment: 'Player text color' },
{ key: 'radio_player_color_accent', comment: 'Player accent color' },
{ key: "radio_style", comment: "Player style (dark/light/blue/purple/pink/gold)" },
{ key: "radio_player_type", comment: "Player type (default/minimal/embedded)" },
{ key: "radio_auto_play", comment: "Auto-play on page load (0=no, 1=yes)" },
{ key: "radio_auto_play_delay", comment: "Auto-play delay in seconds" },
{ key: "radio_mute_on_start", comment: "Muted on start (0=no, 1=yes)" },
{ key: "radio_volume", comment: "Default volume (0-100)" },
{ key: "radio_language", comment: "Default language (nl/en/de/fr/es/pt/it/br)" },
{ key: "radio_multi_language_enabled", comment: "Multi-language support (0=no, 1=yes)" },
{ key: "radio_player_color_primary", comment: "Player primary color" },
{ key: "radio_player_color_secondary", comment: "Player secondary color" },
{ key: "radio_player_color_text", comment: "Player text color" },
{ key: "radio_player_color_accent", comment: "Player accent color" },
],
},
{
title: 'Now playing & history',
title: "Now playing & history",
fields: [
{ key: 'radio_now_playing_enabled', comment: 'Show now playing info (0=no, 1=yes)' },
{ key: 'radio_now_playing_api_url', comment: 'Now playing API URL' },
{ key: 'radio_now_playing_cache_duration', comment: 'Now playing cache duration in seconds' },
{ key: 'radio_show_song_history', comment: 'Show song history (0=no, 1=yes)' },
{ key: 'radio_song_history_count', comment: 'Number of songs in history' },
{ key: "radio_now_playing_enabled", comment: "Show now playing info (0=no, 1=yes)" },
{ key: "radio_now_playing_api_url", comment: "Now playing API URL" },
{ key: "radio_now_playing_cache_duration", comment: "Now playing cache duration in seconds" },
{ key: "radio_show_song_history", comment: "Show song history (0=no, 1=yes)" },
{ key: "radio_song_history_count", comment: "Number of songs in history" },
],
},
{
title: 'Listeners',
title: "Listeners",
fields: [
{ key: 'radio_listeners_enabled', comment: 'Show listeners count (0=no, 1=yes)' },
{ key: 'radio_listeners_api_url', comment: 'Listeners API URL' },
{ key: 'radio_listeners_update_interval', comment: 'Listeners update interval in seconds' },
{ key: 'radio_show_listener_peak', comment: 'Show listener peak (0=no, 1=yes)' },
{ key: 'radio_peak_reset_time', comment: 'Peak reset time (HH:MM)' },
{ key: 'radio_store_listener_stats', comment: 'Store listener statistics (0=no, 1=yes)' },
{ key: 'radio_stats_retention_days', comment: 'Statistics retention in days' },
{ key: 'radio_show_listener_graph', comment: 'Show listener graph (0=no, 1=yes)' },
{ key: 'radio_listener_graph_period', comment: 'Listener graph period (1h/6h/12h/24h/7d)' },
{ key: 'radio_show_average_listeners', comment: 'Show average listeners (0=no, 1=yes)' },
{ key: 'radio_show_unique_listeners', comment: 'Show unique listeners (0=no, 1=yes)' },
{ key: 'radio_listener_alerts_enabled', comment: 'Enable listener alerts (0=no, 1=yes)' },
{ key: 'radio_min_listeners_threshold', comment: 'Minimum listeners threshold' },
{ key: 'radio_listener_alert_threshold_high', comment: 'High listener alert threshold' },
{ key: 'radio_listener_alert_threshold_low', comment: 'Low listener alert threshold' },
{ key: "radio_listeners_enabled", comment: "Show listeners count (0=no, 1=yes)" },
{ key: "radio_listeners_api_url", comment: "Listeners API URL" },
{ key: "radio_listeners_update_interval", comment: "Listeners update interval in seconds" },
{ key: "radio_show_listener_peak", comment: "Show listener peak (0=no, 1=yes)" },
{ key: "radio_peak_reset_time", comment: "Peak reset time (HH:MM)" },
{ key: "radio_store_listener_stats", comment: "Store listener statistics (0=no, 1=yes)" },
{ key: "radio_stats_retention_days", comment: "Statistics retention in days" },
{ key: "radio_show_listener_graph", comment: "Show listener graph (0=no, 1=yes)" },
{ key: "radio_listener_graph_period", comment: "Listener graph period (1h/6h/12h/24h/7d)" },
{ key: "radio_show_average_listeners", comment: "Show average listeners (0=no, 1=yes)" },
{ key: "radio_show_unique_listeners", comment: "Show unique listeners (0=no, 1=yes)" },
{ key: "radio_listener_alerts_enabled", comment: "Enable listener alerts (0=no, 1=yes)" },
{ key: "radio_min_listeners_threshold", comment: "Minimum listeners threshold" },
{ key: "radio_listener_alert_threshold_high", comment: "High listener alert threshold" },
{ key: "radio_listener_alert_threshold_low", comment: "Low listener alert threshold" },
],
},
{
title: 'DJ',
title: "DJ",
fields: [
{ key: 'radio_show_current_dj', comment: 'Show current DJ (0=no, 1=yes)' },
{ key: 'radio_current_dj_id', comment: 'Manual DJ user ID' },
{ key: 'radio_dj_avatar_size', comment: 'DJ avatar size in pixels' },
{ key: 'radio_show_dj_schedule', comment: 'Show DJ schedule (0=no, 1=yes)' },
{ key: 'radio_auto_dj_detection', comment: 'Enable auto DJ detection (0=no, 1=yes)' },
{ key: 'radio_dj_detection_interval', comment: 'DJ detection interval in seconds' },
{ key: 'auto_dj_detected_action', comment: 'Action on DJ detection (set_dj/notify/both)' },
{ key: "radio_show_current_dj", comment: "Show current DJ (0=no, 1=yes)" },
{ key: "radio_current_dj_id", comment: "Manual DJ user ID" },
{ key: "radio_dj_avatar_size", comment: "DJ avatar size in pixels" },
{ key: "radio_show_dj_schedule", comment: "Show DJ schedule (0=no, 1=yes)" },
{ key: "radio_auto_dj_detection", comment: "Enable auto DJ detection (0=no, 1=yes)" },
{ key: "radio_dj_detection_interval", comment: "DJ detection interval in seconds" },
{ key: "auto_dj_detected_action", comment: "Action on DJ detection (set_dj/notify/both)" },
],
},
{
title: 'Shouts & chat',
title: "Shouts & chat",
fields: [
{ key: 'radio_shouts_enabled', comment: 'Enable shouts (0=no, 1=yes)' },
{ key: 'radio_shouts_max_length', comment: 'Maximum shout length in characters' },
{ key: 'radio_shouts_cooldown', comment: 'Shout cooldown in seconds' },
{ key: 'radio_shouts_require_moderation', comment: 'Require shout moderation (0=no, 1=yes)' },
{ key: 'radio_chat_enabled', comment: 'Enable live chat (0=no, 1=yes)' },
{ key: 'radio_chat_position', comment: 'Chat position (left/right/bottom)' },
{ key: 'radio_chat_width', comment: 'Chat width in pixels' },
{ key: 'radio_chat_height', comment: 'Chat height in pixels' },
{ key: 'radio_chat_messages_count', comment: 'Number of chat messages to show' },
{ key: 'radio_chat_show_timestamps', comment: 'Show chat timestamps (0=no, 1=yes)' },
{ key: 'radio_chat_allow_links', comment: 'Allow links in chat (0=no, 1=yes)' },
{ key: 'radio_chat_allow_emojis', comment: 'Allow emojis in chat (0=no, 1=yes)' },
{ key: "radio_shouts_enabled", comment: "Enable shouts (0=no, 1=yes)" },
{ key: "radio_shouts_max_length", comment: "Maximum shout length in characters" },
{ key: "radio_shouts_cooldown", comment: "Shout cooldown in seconds" },
{ key: "radio_shouts_require_moderation", comment: "Require shout moderation (0=no, 1=yes)" },
{ key: "radio_chat_enabled", comment: "Enable live chat (0=no, 1=yes)" },
{ key: "radio_chat_position", comment: "Chat position (left/right/bottom)" },
{ key: "radio_chat_width", comment: "Chat width in pixels" },
{ key: "radio_chat_height", comment: "Chat height in pixels" },
{ key: "radio_chat_messages_count", comment: "Number of chat messages to show" },
{ key: "radio_chat_show_timestamps", comment: "Show chat timestamps (0=no, 1=yes)" },
{ key: "radio_chat_allow_links", comment: "Allow links in chat (0=no, 1=yes)" },
{ key: "radio_chat_allow_emojis", comment: "Allow emojis in chat (0=no, 1=yes)" },
],
},
{
title: 'Requests & widget',
title: "Requests & widget",
fields: [
{ key: 'radio_request_form_enabled', comment: 'Enable song requests (0=no, 1=yes)' },
{ key: 'radio_request_max_per_user', comment: 'Maximum requests per user' },
{ key: 'radio_request_cooldown', comment: 'Request cooldown in seconds' },
{ key: 'radio_voting_enabled', comment: 'Enable request voting (0=no, 1=yes)' },
{ key: 'radio_voting_show_song_requests', comment: 'Show requests with votes (0=no, 1=yes)' },
{ key: 'radio_widget_enabled', comment: 'Enable radio widget (0=no, 1=yes)' },
{ key: 'radio_widget_show_globally', comment: 'Show widget globally (0=no, 1=yes)' },
{ key: 'radio_widget_position', comment: 'Widget position' },
{ key: "radio_request_form_enabled", comment: "Enable song requests (0=no, 1=yes)" },
{ key: "radio_request_max_per_user", comment: "Maximum requests per user" },
{ key: "radio_request_cooldown", comment: "Request cooldown in seconds" },
{ key: "radio_voting_enabled", comment: "Enable request voting (0=no, 1=yes)" },
{ key: "radio_voting_show_song_requests", comment: "Show requests with votes (0=no, 1=yes)" },
{ key: "radio_widget_enabled", comment: "Enable radio widget (0=no, 1=yes)" },
{ key: "radio_widget_show_globally", comment: "Show widget globally (0=no, 1=yes)" },
{ key: "radio_widget_position", comment: "Widget position" },
],
},
{
title: 'Offline & branding',
title: "Offline & branding",
fields: [
{ key: 'radio_show_offline_message', comment: 'Show offline message (0=no, 1=yes)' },
{ key: 'radio_offline_message', comment: 'Offline message text' },
{ key: 'radio_offline_image', comment: 'Offline page image URL' },
{ key: 'radio_background_image', comment: 'Background image URL' },
{ key: 'radio_logo_url', comment: 'Radio logo URL' },
{ key: "radio_show_offline_message", comment: "Show offline message (0=no, 1=yes)" },
{ key: "radio_offline_message", comment: "Offline message text" },
{ key: "radio_offline_image", comment: "Offline page image URL" },
{ key: "radio_background_image", comment: "Background image URL" },
{ key: "radio_logo_url", comment: "Radio logo URL" },
],
},
{
title: 'Applications',
title: "Applications",
fields: [
{ key: 'radio_applications_enabled', comment: 'Enable DJ applications (0=no, 1=yes)' },
{ key: 'radio_applications_max_per_day', comment: 'Maximum applications per day' },
{ key: 'radio_applications_require_approval', comment: 'Require application approval (0=no, 1=yes)' },
{ key: "radio_applications_enabled", comment: "Enable DJ applications (0=no, 1=yes)" },
{ key: "radio_applications_max_per_day", comment: "Maximum applications per day" },
{ key: "radio_applications_require_approval", comment: "Require application approval (0=no, 1=yes)" },
],
},
{
title: 'Stats display',
title: "Stats display",
fields: [
{ key: 'radio_stats_show_daily', comment: 'Show daily statistics (0=no, 1=yes)' },
{ key: 'radio_stats_show_weekly', comment: 'Show weekly statistics (0=no, 1=yes)' },
{ key: 'radio_stats_show_monthly', comment: 'Show monthly statistics (0=no, 1=yes)' },
{ key: 'radio_stats_show_top_djs', comment: 'Show top DJs (0=no, 1=yes)' },
{ key: 'radio_stats_show_top_songs', comment: 'Show top songs (0=no, 1=yes)' },
{ key: "radio_stats_show_daily", comment: "Show daily statistics (0=no, 1=yes)" },
{ key: "radio_stats_show_weekly", comment: "Show weekly statistics (0=no, 1=yes)" },
{ key: "radio_stats_show_monthly", comment: "Show monthly statistics (0=no, 1=yes)" },
{ key: "radio_stats_show_top_djs", comment: "Show top DJs (0=no, 1=yes)" },
{ key: "radio_stats_show_top_songs", comment: "Show top songs (0=no, 1=yes)" },
],
},
{
title: 'Social & contact',
title: "Social & contact",
fields: [
{ key: 'radio_social_facebook', comment: 'Facebook URL' },
{ key: 'radio_social_twitter', comment: 'Twitter URL' },
{ key: 'radio_social_instagram', comment: 'Instagram URL' },
{ key: 'radio_social_discord', comment: 'Discord URL' },
{ key: 'radio_social_youtube', comment: 'YouTube URL' },
{ key: 'radio_social_twitch', comment: 'Twitch URL' },
{ key: 'radio_contact_email', comment: 'Contact email' },
{ key: 'radio_contact_phone', comment: 'Contact phone' },
{ key: 'radio_about_text', comment: 'About radio text' },
{ key: "radio_social_facebook", comment: "Facebook URL" },
{ key: "radio_social_twitter", comment: "Twitter URL" },
{ key: "radio_social_instagram", comment: "Instagram URL" },
{ key: "radio_social_discord", comment: "Discord URL" },
{ key: "radio_social_youtube", comment: "YouTube URL" },
{ key: "radio_social_twitch", comment: "Twitch URL" },
{ key: "radio_contact_email", comment: "Contact email" },
{ key: "radio_contact_phone", comment: "Contact phone" },
{ key: "radio_about_text", comment: "About radio text" },
],
},
{
title: 'Discord webhook & custom code',
title: "Discord webhook & custom code",
fields: [
{ key: 'radio_discord_webhook_url', comment: 'Discord webhook URL' },
{ key: 'radio_discord_enabled', comment: 'Enable Discord notifications (0=no, 1=yes)' },
{ key: 'radio_discord_dj_live', comment: 'Discord DJ live notification (0=no, 1=yes)' },
{ key: 'radio_discord_song_changes', comment: 'Discord song change notification (0=no, 1=yes)' },
{ key: 'radio_discord_custom_message', comment: 'Custom Discord message template' },
{ key: 'radio_custom_css', comment: 'Custom CSS code' },
{ key: 'radio_custom_js', comment: 'Custom JavaScript code' },
{ key: "radio_discord_webhook_url", comment: "Discord webhook URL" },
{ key: "radio_discord_enabled", comment: "Enable Discord notifications (0=no, 1=yes)" },
{ key: "radio_discord_dj_live", comment: "Discord DJ live notification (0=no, 1=yes)" },
{ key: "radio_discord_song_changes", comment: "Discord song change notification (0=no, 1=yes)" },
{ key: "radio_discord_custom_message", comment: "Custom Discord message template" },
{ key: "radio_custom_css", comment: "Custom CSS code" },
{ key: "radio_custom_js", comment: "Custom JavaScript code" },
],
},
];
@@ -195,12 +195,8 @@ export default async function AdminRadioSettingsPage() {
});
values = new Map(rows.map((r) => [r.key, r.value]));
extra = rows
.filter(
(r) =>
(r.key.startsWith('radio_') || r.key.startsWith('auto_dj_')) &&
!CURATED_KEYS.has(r.key),
)
.map((r) => ({ key: r.key, comment: r.comment ?? '' }));
.filter((r) => (r.key.startsWith("radio_") || r.key.startsWith("auto_dj_")) && !CURATED_KEYS.has(r.key))
.map((r) => ({ key: r.key, comment: r.comment ?? "" }));
} catch {
dbError = true;
}
@@ -209,22 +205,22 @@ export default async function AdminRadioSettingsPage() {
? [...GROUPS, { title: t("settingsForm.otherSettings"), fields: extra }]
: GROUPS;
const allKeys = [...CURATED_KEYS, ...extra.map((e) => e.key)].join(',');
const allKeys = [...CURATED_KEYS, ...extra.map((e) => e.key)].join(",");
const totalKeys = CURATED_KEYS.size + extra.length;
const configuredKeys = [...CURATED_KEYS].filter((k) => {
const v = values.get(k);
return v != null && v !== '';
return v != null && v !== "";
}).length;
const radioEnabled = (values.get('radio_enabled') ?? '') === '1';
const radioEnabled = (values.get("radio_enabled") ?? "") === "1";
return (
<main>
<nav className="text-xs text-gray-500 dark:text-gray-400 mb-2">
<Link href="/admin/radio">{t("title")}</Link> ·{' '}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{' '}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{' '}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{' '}
<Link href="/admin/radio">{t("title")}</Link> ·{" "}
<Link href="/admin/radio/settings">{t("settings")}</Link> ·{" "}
<Link href="/admin/radio/banners">{t("banners.title")}</Link> ·{" "}
<Link href="/admin/radio/ranks">{t("ranks")}</Link> ·{" "}
<Link href="/admin/radio/history">{t("history")}</Link>
</nav>
@@ -240,16 +236,14 @@ export default async function AdminRadioSettingsPage() {
{dbError ? (
<div className="admin-card mb-6">
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">
{t("settingsForm.dbError")}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">{t("settingsForm.dbError")}</p>
</div>
) : (
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard
label="Radio"
value={radioEnabled ? t("settingsForm.enabled") : t("settingsForm.disabled")}
state={radioEnabled ? 'ok' : 'danger'}
state={radioEnabled ? "ok" : "danger"}
icon="\u{1F4BB}"
/>
<StatusCard label={t("settingsForm.totalKeys")} value={totalKeys} icon="\u{1F511}" />
@@ -262,7 +256,7 @@ export default async function AdminRadioSettingsPage() {
<StatusCard
label={t("settingsForm.customKeys")}
value={extra.length}
state={extra.length > 0 ? 'warn' : 'neutral'}
state={extra.length > 0 ? "warn" : "neutral"}
icon="\u{2795}"
/>
</div>
@@ -277,25 +271,25 @@ export default async function AdminRadioSettingsPage() {
</div>
{groups.map((group) => (
<section key={group.title} className="admin-card" style={{ marginBottom: '1.25rem' }}>
<section key={group.title} className="admin-card" style={{ marginBottom: "1.25rem" }}>
<h2 style={{ marginTop: 0 }}>{group.title}</h2>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
{group.fields.map((field) => (
<div key={field.key}>
<label
htmlFor={`f_${field.key}`}
style={{ display: 'block', fontWeight: 700, fontSize: '0.85rem' }}
style={{ display: "block", fontWeight: 700, fontSize: "0.85rem" }}
>
{field.key}
</label>
<input
id={`f_${field.key}`}
name={field.key}
defaultValue={values.get(field.key) ?? ''}
style={{ width: '100%' }}
defaultValue={values.get(field.key) ?? ""}
style={{ width: "100%" }}
/>
{field.comment ? (
<p className="text-xs text-gray-500 dark:text-gray-400" style={{ margin: '0.2rem 0 0' }}>
<p className="text-xs text-gray-500 dark:text-gray-400" style={{ margin: "0.2rem 0 0" }}>
{field.comment}
</p>
) : null}
@@ -312,11 +306,15 @@ export default async function AdminRadioSettingsPage() {
</div>
</form>
<section className="admin-card" style={{ marginTop: '1.5rem' }}>
<section className="admin-card" style={{ marginTop: "1.5rem" }}>
<h3 style={{ marginTop: 0 }}>{t("settingsForm.singleKey")}</h3>
<form action={saveRadioSetting} className="flex gap-2 flex-wrap">
<input name="key" placeholder={t("settingsForm.keyPlaceholder")} required />
<input name="value" placeholder={t("settingsForm.valuePlaceholder")} className="flex-1 min-w-[160px]" />
<input
name="value"
placeholder={t("settingsForm.valuePlaceholder")}
className="flex-1 min-w-[160px]"
/>
<input name="comment" placeholder={t("settingsForm.commentPlaceholder")} />
<button type="submit" className="btn btn-primary">
{t("settingsForm.saveSingle")}
+78 -27
View File
@@ -1,10 +1,5 @@
import { getTranslations } from "next-intl/server";
import {
createCategory,
createValue,
deleteCategory,
deleteValue,
} from "@/actions/admin-rare-values";
import { createCategory, createValue, deleteCategory, deleteValue } from "@/actions/admin-rare-values";
import { StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
import { Gem } from "lucide-react";
@@ -62,16 +57,28 @@ export default async function AdminRareValues() {
<form action={createCategory} className="admin-card mb-6">
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addCategory")}</h3>
<div className="flex gap-2 flex-wrap">
<input name="name" placeholder={t("categoryForm.namePlaceholder")} required className="flex-1 min-w-[160px]" />
<input
name="name"
placeholder={t("categoryForm.namePlaceholder")}
required
className="flex-1 min-w-[160px]"
/>
<input name="badge" placeholder={t("badgePlaceholder")} required />
<input name="priority" type="number" min={1} defaultValue={1} placeholder={t("priorityPlaceholder")} className="w-[110px]" />
<button type="submit" className="btn btn-primary">{t("addCategoryButton")}</button>
<input
name="priority"
type="number"
min={1}
defaultValue={1}
placeholder={t("priorityPlaceholder")}
className="w-[110px]"
/>
<button type="submit" className="btn btn-primary">
{t("addCategoryButton")}
</button>
</div>
</form>
{categories.length === 0 ? (
<div className="admin-empty">{t("noCategories")}</div>
) : null}
{categories.length === 0 ? <div className="admin-empty">{t("noCategories")}</div> : null}
<div className="grid">
{categories.map((cat) => {
@@ -82,13 +89,21 @@ export default async function AdminRareValues() {
<div className="flex gap-3 items-baseline justify-between flex-wrap">
<div style={{ display: "flex", gap: "0.6rem", alignItems: "baseline", flexWrap: "wrap" }}>
<strong>{cat.name}</strong>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{t("badgeLabel", { badge: cat.badge })}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{t("priorityLabel", { priority: cat.priority })}</span>
<span className="text-sm text-gray-500 dark:text-gray-400">{t("itemCount", { count: rows.length })}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{t("badgeLabel", { badge: cat.badge })}
</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{t("priorityLabel", { priority: cat.priority })}
</span>
<span className="text-sm text-gray-500 dark:text-gray-400">
{t("itemCount", { count: rows.length })}
</span>
</div>
<form action={deleteCategory}>
<input type="hidden" name="id" value={catId} />
<button type="submit" className="btn btn-danger">{t("deleteCategory")}</button>
<button type="submit" className="btn btn-danger">
{t("deleteCategory")}
</button>
</form>
</div>
@@ -108,17 +123,25 @@ export default async function AdminRareValues() {
{rows.map((v) => (
<tr key={String(v.id)}>
<td>{v.name}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{v.itemId ?? "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{v.itemId ?? "—"}
</td>
<td>{v.creditValue ?? "—"}</td>
<td>{v.currencyValue ?? "—"}</td>
<td>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{v.currencyType}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{v.currencyType}
</span>
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{v.furnitureIcon}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{v.furnitureIcon}</td>
<td>
<form action={deleteValue}>
<input type="hidden" name="id" value={String(v.id)} />
<button type="submit" className="btn btn-danger">✕</button>
<button type="submit" className="btn btn-danger">
✕
</button>
</form>
</td>
</tr>
@@ -134,17 +157,45 @@ export default async function AdminRareValues() {
<form action={createValue} style={{ marginTop: "0.75rem" }}>
<input type="hidden" name="categoryId" value={catId} />
<div className="flex gap-2 flex-wrap">
<input name="name" placeholder={t("itemForm.itemNamePlaceholder")} required className="flex-1 min-w-[140px]" />
<input name="itemId" type="number" min={1} placeholder={t("itemForm.itemIdPlaceholder")} className="w-[110px]" />
<input name="furnitureIcon" placeholder={t("itemForm.iconPlaceholder")} required className="min-w-[140px]" />
<input name="creditValue" placeholder={t("itemForm.creditsPlaceholder")} className="w-[130px]" />
<input name="currencyValue" placeholder={t("itemForm.currencyValuePlaceholder")} className="w-[130px]" />
<input
name="name"
placeholder={t("itemForm.itemNamePlaceholder")}
required
className="flex-1 min-w-[140px]"
/>
<input
name="itemId"
type="number"
min={1}
placeholder={t("itemForm.itemIdPlaceholder")}
className="w-[110px]"
/>
<input
name="furnitureIcon"
placeholder={t("itemForm.iconPlaceholder")}
required
className="min-w-[140px]"
/>
<input
name="creditValue"
placeholder={t("itemForm.creditsPlaceholder")}
className="w-[130px]"
/>
<input
name="currencyValue"
placeholder={t("itemForm.currencyValuePlaceholder")}
className="w-[130px]"
/>
<select name="currencyType" defaultValue="diamonds">
{CURRENCY_TYPES.map((c) => (
<option key={c} value={c}>{c}</option>
<option key={c} value={c}>
{c}
</option>
))}
</select>
<button type="submit" className="btn btn-primary">{t("itemForm.addValue")}</button>
<button type="submit" className="btn btn-primary">
{t("itemForm.addValue")}
</button>
</div>
</form>
</div>
@@ -0,0 +1,179 @@
'use client'
import { useEffect, useState } from 'react'
import { updateRoomItem } from '@/actions/rooms'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
interface EditItem {
id: number
name: string
type: string
x: number
y: number
z: number
rot: number
wallPos: string
extraData: string
}
interface Props {
roomId: number
item: EditItem | null
open: boolean
onOpenChange: (open: boolean) => void
}
export function EditItemDialog({ roomId, item, open, onOpenChange }: Props) {
const { run, isPending } = useServerAction()
const [x, setX] = useState('0')
const [y, setY] = useState('0')
const [z, setZ] = useState('0')
const [rot, setRot] = useState('0')
const [wallPos, setWallPos] = useState('')
const [extraData, setExtraData] = useState('')
const isWall = item?.type === 'i'
useEffect(() => {
if (item) {
setX(String(item.x))
setY(String(item.y))
setZ(String(item.z))
setRot(String(item.rot))
setWallPos(item.wallPos)
setExtraData(item.extraData)
}
}, [item])
function handleSave() {
if (!item) return
const payload = isWall
? { roomId, itemId: item.id, wallPos, extraData }
: {
roomId,
itemId: item.id,
x: Number(x),
y: Number(y),
z: Number(z),
rot: Number(rot),
extraData,
}
run(() => updateRoomItem(payload), {
successMessage: 'Item updated and room reloaded',
onSuccess: () => onOpenChange(false),
})
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[480px]">
<DialogHeader>
<DialogTitle>Edit furniture</DialogTitle>
<DialogDescription>{item ? `${item.name} (#${item.id})` : ''}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{isWall ? (
<div className="space-y-2">
<Label htmlFor="wallPos">Wall position</Label>
<Input
id="wallPos"
value={wallPos}
onChange={(e) => setWallPos(e.target.value)}
placeholder=":w=0,0 l=0,0 r"
className="font-mono"
/>
<p className="text-xs text-muted-foreground">
Format: <code>:w=X,Y l=X,Y r</code>
</p>
</div>
) : (
<>
<div className="grid grid-cols-3 gap-3">
<div className="space-y-2">
<Label htmlFor="x">X</Label>
<Input
id="x"
type="number"
value={x}
onChange={(e) => setX(e.target.value)}
className="font-mono"
/>
</div>
<div className="space-y-2">
<Label htmlFor="y">Y</Label>
<Input
id="y"
type="number"
value={y}
onChange={(e) => setY(e.target.value)}
className="font-mono"
/>
</div>
<div className="space-y-2">
<Label htmlFor="z">Z</Label>
<Input
id="z"
type="number"
step="0.01"
value={z}
onChange={(e) => setZ(e.target.value)}
className="font-mono"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="rot">Rotation (0-7)</Label>
<Input
id="rot"
type="number"
min={0}
max={7}
value={rot}
onChange={(e) => setRot(e.target.value)}
className="font-mono w-24"
/>
</div>
</>
)}
<div className="space-y-2">
<Label htmlFor="extraData">Extra data</Label>
<Textarea
id="extraData"
value={extraData}
onChange={(e) => setExtraData(e.target.value)}
rows={3}
className="font-mono text-xs"
placeholder="(empty)"
/>
<p className="text-xs text-muted-foreground">
Item state/data (e.g. dice value, sticky note text, color)
</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isPending}>
Cancel
</Button>
<Button onClick={handleSave} disabled={isPending}>
{isPending ? 'Saving...' : 'Save'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,701 @@
'use client'
import {
Armchair,
ArrowDown,
ArrowLeft,
ArrowUp,
ArrowUpDown,
ChevronLeft,
ChevronRight,
Frame,
Layers,
Pencil,
RefreshCw,
Search,
Trash2,
Users,
UserX,
} from 'lucide-react'
import Link from 'next/link'
import { useMemo, useState } from 'react'
import { bulkDeleteRoomItems, deleteRoomItem, roomRconAction } from '@/actions/rooms'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useServerAction } from '@/hooks/use-server-action'
import { EditItemDialog } from './edit-item-dialog'
interface FurniRow {
id: number
baseId: number
name: string
itemName: string
type: string
x: number
y: number
z: number
rot: number
wallPos: string
userId: number
ownerUsername: string | null
extraData: string
}
interface Props {
room: {
id: number
name: string
ownerUsername: string
}
items?: FurniRow[]
canEdit: boolean
}
const PER_PAGE = 50
type SortKey = 'id' | 'name' | 'type' | 'pos' | 'owner'
type SortDir = 'asc' | 'desc'
type View = 'flat' | 'grouped'
function iconUrl(itemName: string) {
if (!itemName) return null
const base = itemName.split('*')[0]
return `/swf/dcr/hof_furni/icons/${base}_icon.png`
}
function isWallType(t: string) {
return t === 'i'
}
export function FurniClient({ room, items = [], canEdit }: Props) {
const { run, isPending } = useServerAction()
const [search, setSearch] = useState('')
const [page, setPage] = useState(1)
const [view, setView] = useState<View>('flat')
const [typeFilter, setTypeFilter] = useState<'all' | 'floor' | 'wall'>('all')
const [ownerFilter, setOwnerFilter] = useState<string>('all')
const [sortKey, setSortKey] = useState<SortKey>('id')
const [sortDir, setSortDir] = useState<SortDir>('desc')
const [selected, setSelected] = useState<Set<number>>(new Set())
const [editingItem, setEditingItem] = useState<FurniRow | null>(null)
// ── Stats ──────────────────────────────────────────────────
const stats = useMemo(() => {
const floor = items.filter((i) => !isWallType(i.type)).length
const wall = items.filter((i) => isWallType(i.type)).length
const uniqueBases = new Set(items.map((i) => i.baseId)).size
const owners = new Set(items.map((i) => i.userId).filter((u) => u > 0)).size
return { total: items.length, floor, wall, uniqueBases, owners }
}, [items])
// ── Owner options for filter ───────────────────────────────
const ownerOptions = useMemo(() => {
const map = new Map<string, number>()
for (const i of items) {
const key = i.ownerUsername ?? `#${i.userId}`
map.set(key, (map.get(key) ?? 0) + 1)
}
return Array.from(map.entries()).sort((a, b) => b[1] - a[1])
}, [items])
// ── Filtering ──────────────────────────────────────────────
const filtered = useMemo(() => {
const q = search.trim().toLowerCase()
return items.filter((i) => {
if (typeFilter === 'floor' && isWallType(i.type)) return false
if (typeFilter === 'wall' && !isWallType(i.type)) return false
if (ownerFilter !== 'all') {
const key = i.ownerUsername ?? `#${i.userId}`
if (key !== ownerFilter) return false
}
if (q) {
return (
i.name.toLowerCase().includes(q) ||
i.itemName.toLowerCase().includes(q) ||
String(i.baseId).includes(q) ||
String(i.id).includes(q)
)
}
return true
})
}, [items, search, typeFilter, ownerFilter])
// ── Sorting ────────────────────────────────────────────────
const sorted = useMemo(() => {
const arr = [...filtered]
arr.sort((a, b) => {
let cmp = 0
switch (sortKey) {
case 'id':
cmp = a.id - b.id
break
case 'name':
cmp = a.name.localeCompare(b.name)
break
case 'type':
cmp = a.type.localeCompare(b.type)
break
case 'pos':
cmp = a.x - b.x || a.y - b.y
break
case 'owner':
cmp = (a.ownerUsername ?? '').localeCompare(b.ownerUsername ?? '')
break
}
return sortDir === 'asc' ? cmp : -cmp
})
return arr
}, [filtered, sortKey, sortDir])
// ── Grouped view ───────────────────────────────────────────
const grouped = useMemo(() => {
const map = new Map<number, { base: FurniRow; count: number; ids: number[] }>()
for (const i of filtered) {
const existing = map.get(i.baseId)
if (existing) {
existing.count++
existing.ids.push(i.id)
} else {
map.set(i.baseId, { base: i, count: 1, ids: [i.id] })
}
}
return Array.from(map.values()).sort((a, b) => b.count - a.count)
}, [filtered])
// ── Pagination (flat view only) ─────────────────────────────
const lastPage = Math.max(1, Math.ceil(sorted.length / PER_PAGE))
const currentPage = Math.min(page, lastPage)
const pageRows = sorted.slice((currentPage - 1) * PER_PAGE, currentPage * PER_PAGE)
// ── Handlers ───────────────────────────────────────────────
function toggleSort(key: SortKey) {
if (sortKey === key) {
setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'))
} else {
setSortKey(key)
setSortDir('asc')
}
}
function SortIcon({ k }: { k: SortKey }) {
if (sortKey !== k) return <ArrowUpDown className="w-3 h-3 opacity-40" />
return sortDir === 'asc' ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />
}
function togglePageSelection(checked: boolean) {
const next = new Set(selected)
for (const r of pageRows) {
if (checked) next.add(r.id)
else next.delete(r.id)
}
setSelected(next)
}
function toggleRowSelection(id: number, checked: boolean) {
const next = new Set(selected)
if (checked) next.add(id)
else next.delete(id)
setSelected(next)
}
function handleRcon(action: 'reload' | 'kick') {
if (action === 'kick' && !confirm('Kick all users from this room?')) return
run(() => roomRconAction({ roomId: room.id, action }), {
successMessage: action === 'reload' ? 'Room reloaded' : 'All users kicked',
})
}
function handleDelete(itemId: number, name: string) {
if (!confirm(`Delete "${name}" (#${itemId}) from this room?`)) return
run(() => deleteRoomItem({ roomId: room.id, itemId }), { successMessage: 'Item deleted' })
}
function handleBulkDelete() {
if (selected.size === 0) return
if (!confirm(`Delete ${selected.size} selected item${selected.size > 1 ? 's' : ''}?`)) return
run(() => bulkDeleteRoomItems({ roomId: room.id, itemIds: Array.from(selected) }), {
successMessage: `${selected.size} item(s) deleted`,
onSuccess: () => setSelected(new Set()),
})
}
function handleDeleteGroup(_baseId: number, ids: number[], name: string) {
if (!confirm(`Delete all ${ids.length} "${name}" from this room?`)) return
run(() => bulkDeleteRoomItems({ roomId: room.id, itemIds: ids }), {
successMessage: `${ids.length} item(s) deleted`,
})
}
const allPageSelected = pageRows.length > 0 && pageRows.every((r) => selected.has(r.id))
return (
<div className="space-y-6">
{/* ── Header ─────────────────────────────────────────── */}
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-4">
<Link href={`/admin/rooms/show/${room.id}`}>
<Button variant="outline" size="sm">
<ArrowLeft className="w-4 h-4 mr-1" /> Back
</Button>
</Link>
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<Armchair className="w-6 h-6" />
{room.name}
</h1>
<p className="text-sm text-muted-foreground">
Room #{room.id} · Owner: {room.ownerUsername}
</p>
</div>
</div>
{canEdit && (
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleRcon('reload')}
disabled={isPending}
>
<RefreshCw className="w-4 h-4 mr-1" /> Reload
</Button>
<Button
variant="destructive"
size="sm"
onClick={() => handleRcon('kick')}
disabled={isPending}
>
<UserX className="w-4 h-4 mr-1" /> Kick All
</Button>
</div>
)}
</div>
{/* ── Stats Cards ────────────────────────────────────── */}
<div className="grid grid-cols-2 md:grid-cols-5 gap-3">
<StatCard icon={<Armchair className="w-4 h-4" />} label="Total" value={stats.total} />
<StatCard icon={<Layers className="w-4 h-4" />} label="Floor" value={stats.floor} />
<StatCard icon={<Frame className="w-4 h-4" />} label="Wall" value={stats.wall} />
<StatCard
icon={<Armchair className="w-4 h-4" />}
label="Unique furni"
value={stats.uniqueBases}
/>
<StatCard icon={<Users className="w-4 h-4" />} label="Owners" value={stats.owners} />
</div>
{/* ── Toolbar ────────────────────────────────────────── */}
<Card>
<CardContent className="pt-6 space-y-4">
<div className="flex flex-wrap items-center gap-3">
<div className="relative flex-1 min-w-[200px] max-w-sm">
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="Search by name or ID..."
value={search}
onChange={(e) => {
setSearch(e.target.value)
setPage(1)
}}
className="pl-8"
/>
</div>
<Select
value={typeFilter}
onValueChange={(v: 'all' | 'floor' | 'wall') => {
setTypeFilter(v)
setPage(1)
}}
>
<SelectTrigger className="w-[140px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All types</SelectItem>
<SelectItem value="floor">Floor only</SelectItem>
<SelectItem value="wall">Wall only</SelectItem>
</SelectContent>
</Select>
<Select
value={ownerFilter}
onValueChange={(v) => {
setOwnerFilter(v)
setPage(1)
}}
>
<SelectTrigger className="w-[180px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All owners</SelectItem>
{ownerOptions.map(([name, count]) => (
<SelectItem key={name} value={name}>
{name} ({count})
</SelectItem>
))}
</SelectContent>
</Select>
<Tabs value={view} onValueChange={(v) => setView(v as View)} className="ml-auto">
<TabsList>
<TabsTrigger value="flat">Flat</TabsTrigger>
<TabsTrigger value="grouped">Grouped</TabsTrigger>
</TabsList>
</Tabs>
</div>
{/* Bulk action bar */}
{view === 'flat' && selected.size > 0 && canEdit && (
<div className="flex items-center justify-between bg-muted/50 border rounded-md px-3 py-2">
<span className="text-sm">
<strong>{selected.size}</strong> selected
</span>
<div className="flex gap-2">
<Button variant="ghost" size="sm" onClick={() => setSelected(new Set())}>
Clear
</Button>
<Button
variant="destructive"
size="sm"
onClick={handleBulkDelete}
disabled={isPending}
>
<Trash2 className="w-4 h-4 mr-1" /> Delete selected
</Button>
</div>
</div>
)}
{/* ── Flat Table ─────────────────────────────────── */}
{view === 'flat' ? (
<>
<div className="border rounded-md overflow-hidden">
<Table>
<TableHeader>
<TableRow>
{canEdit && (
<TableHead className="w-10">
<Checkbox
checked={allPageSelected}
onCheckedChange={(c) => togglePageSelection(c === true)}
/>
</TableHead>
)}
<TableHead className="w-16"></TableHead>
<TableHead>
<button
type="button"
className="flex items-center gap-1 hover:text-foreground"
onClick={() => toggleSort('name')}
>
Name <SortIcon k="name" />
</button>
</TableHead>
<TableHead className="w-20">
<button
type="button"
className="flex items-center gap-1 hover:text-foreground"
onClick={() => toggleSort('type')}
>
Type <SortIcon k="type" />
</button>
</TableHead>
<TableHead className="w-32">
<button
type="button"
className="flex items-center gap-1 hover:text-foreground"
onClick={() => toggleSort('pos')}
>
Position <SortIcon k="pos" />
</button>
</TableHead>
<TableHead className="w-16">Rot</TableHead>
<TableHead className="w-32">
<button
type="button"
className="flex items-center gap-1 hover:text-foreground"
onClick={() => toggleSort('owner')}
>
Owner <SortIcon k="owner" />
</button>
</TableHead>
<TableHead className="w-24">
<button
type="button"
className="flex items-center gap-1 hover:text-foreground"
onClick={() => toggleSort('id')}
>
ID <SortIcon k="id" />
</button>
</TableHead>
{canEdit && <TableHead className="w-24 text-right">Actions</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{pageRows.length === 0 ? (
<TableRow>
<TableCell
colSpan={canEdit ? 9 : 7}
className="text-center text-muted-foreground py-12"
>
{items.length === 0 ? (
<div className="space-y-2">
<Armchair className="w-10 h-10 mx-auto opacity-30" />
<p>This room has no furniture.</p>
</div>
) : (
<p>No items match your filters.</p>
)}
</TableCell>
</TableRow>
) : (
pageRows.map((item) => {
const icon = iconUrl(item.itemName)
const wall = isWallType(item.type)
const isSelected = selected.has(item.id)
return (
<TableRow
key={item.id}
className={isSelected ? 'bg-muted/40' : 'hover:bg-muted/30'}
>
{canEdit && (
<TableCell>
<Checkbox
checked={isSelected}
onCheckedChange={(c) => toggleRowSelection(item.id, c === true)}
/>
</TableCell>
)}
<TableCell>
{icon ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={icon}
alt={item.name}
className="w-10 h-10 object-contain"
onError={(e) => {
;(e.target as HTMLImageElement).style.visibility = 'hidden'
}}
/>
) : (
<div className="w-10 h-10 bg-muted rounded" />
)}
</TableCell>
<TableCell>
<div className="font-medium">{item.name}</div>
<div className="text-xs text-muted-foreground font-mono">
{item.itemName || `base #${item.baseId}`}
</div>
</TableCell>
<TableCell>
<Badge variant={wall ? 'outline' : 'secondary'}>
{wall ? 'Wall' : item.type === 's' ? 'Floor' : item.type}
</Badge>
</TableCell>
<TableCell className="font-mono text-xs">
{wall
? item.wallPos || '-'
: `${item.x},${item.y},${item.z.toFixed(1)}`}
</TableCell>
<TableCell className="font-mono text-xs">{item.rot}</TableCell>
<TableCell className="text-sm">
{item.ownerUsername ? (
<Link
href={`/admin/users/show/${item.userId}`}
className="text-primary hover:underline"
>
{item.ownerUsername}
</Link>
) : (
<span className="text-muted-foreground">#{item.userId}</span>
)}
</TableCell>
<TableCell className="font-mono text-xs">#{item.id}</TableCell>
{canEdit && (
<TableCell className="text-right">
<div className="flex justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => setEditingItem(item)}
disabled={isPending}
title="Edit"
>
<Pencil className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(item.id, item.name)}
disabled={isPending}
title="Delete"
>
<Trash2 className="w-4 h-4 text-destructive" />
</Button>
</div>
</TableCell>
)}
</TableRow>
)
})
)}
</TableBody>
</Table>
</div>
{lastPage > 1 && (
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">
Showing {(currentPage - 1) * PER_PAGE + 1}-
{Math.min(currentPage * PER_PAGE, sorted.length)} of {sorted.length}
</span>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="w-4 h-4" />
</Button>
<span className="text-sm flex items-center px-2">
{currentPage} / {lastPage}
</span>
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.min(lastPage, p + 1))}
disabled={currentPage === lastPage}
>
<ChevronRight className="w-4 h-4" />
</Button>
</div>
</div>
)}
</>
) : (
/* ── Grouped View ──────────────────────────────── */
<div className="border rounded-md overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-16"></TableHead>
<TableHead>Furniture</TableHead>
<TableHead className="w-24">Type</TableHead>
<TableHead className="w-24 text-right">Count</TableHead>
{canEdit && <TableHead className="w-32 text-right">Action</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{grouped.length === 0 ? (
<TableRow>
<TableCell
colSpan={canEdit ? 5 : 4}
className="text-center text-muted-foreground py-12"
>
No items.
</TableCell>
</TableRow>
) : (
grouped.map((g) => {
const icon = iconUrl(g.base.itemName)
const wall = isWallType(g.base.type)
return (
<TableRow key={g.base.baseId} className="hover:bg-muted/30">
<TableCell>
{icon ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={icon}
alt={g.base.name}
className="w-10 h-10 object-contain"
onError={(e) => {
;(e.target as HTMLImageElement).style.visibility = 'hidden'
}}
/>
) : (
<div className="w-10 h-10 bg-muted rounded" />
)}
</TableCell>
<TableCell>
<div className="font-medium">{g.base.name}</div>
<div className="text-xs text-muted-foreground font-mono">
{g.base.itemName || `base #${g.base.baseId}`}
</div>
</TableCell>
<TableCell>
<Badge variant={wall ? 'outline' : 'secondary'}>
{wall ? 'Wall' : g.base.type === 's' ? 'Floor' : g.base.type}
</Badge>
</TableCell>
<TableCell className="text-right">
<Badge>{g.count}</Badge>
</TableCell>
{canEdit && (
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
onClick={() => handleDeleteGroup(g.base.baseId, g.ids, g.base.name)}
disabled={isPending}
>
<Trash2 className="w-4 h-4 text-destructive mr-1" />
Delete all
</Button>
</TableCell>
)}
</TableRow>
)
})
)}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
<EditItemDialog
roomId={room.id}
item={editingItem}
open={editingItem !== null}
onOpenChange={(o) => !o && setEditingItem(null)}
/>
</div>
)
}
function StatCard({ icon, label, value }: { icon: React.ReactNode; label: string; value: number }) {
return (
<Card>
<CardContent className="pt-6">
<div className="flex items-center justify-between">
<div>
<div className="text-xs text-muted-foreground">{label}</div>
<div className="text-2xl font-bold">{value.toLocaleString()}</div>
</div>
<div className="text-muted-foreground">{icon}</div>
</div>
</CardContent>
</Card>
)
}
+84
View File
@@ -0,0 +1,84 @@
import { redirect } from 'next/navigation'
import { AdminBreadcrumb } from '@/components/admin/admin-breadcrumb'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { loadRoom } from '../../_lib/load-room'
import { FurniClient } from './furni-client'
export default async function RoomFurniPage({
params,
}: {
params: Promise<{ id: string; locale: string }>
}) {
const { id } = await params
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ROOMS_VIEW, session.user.rank)) redirect('/admin')
const room = await loadRoom(id)
// Load items in this room. items.item_id → items_base.id
const items = await prisma.item.findMany({
where: { roomId: room.id },
orderBy: { id: 'desc' },
})
// Resolve item bases
const baseIds = Array.from(new Set(items.map((i) => i.itemId)))
const bases = baseIds.length
? await prisma.itemsBase.findMany({
where: { id: { in: baseIds } },
select: { id: true, itemName: true, publicName: true, type: true },
})
: []
const baseMap = new Map(bases.map((b) => [b.id, b]))
// Resolve owner usernames
const userIds = Array.from(new Set(items.map((i) => i.userId).filter((u) => u > 0)))
const users = userIds.length
? await prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true },
})
: []
const userMap = new Map(users.map((u) => [u.id, u.username]))
const rows = items.map((i) => {
const base = baseMap.get(i.itemId)
return {
id: i.id,
baseId: i.itemId,
name: base?.publicName || base?.itemName || `#${i.itemId}`,
itemName: base?.itemName ?? '',
type: base?.type ?? '?',
x: i.x,
y: i.y,
z: i.z,
rot: i.rot,
wallPos: i.wallPos,
userId: i.userId,
ownerUsername: userMap.get(i.userId) ?? null,
extraData: i.extraData,
}
})
return (
<div className="space-y-6">
<AdminBreadcrumb
items={[
{ label: 'Rooms', href: '/admin/rooms' },
{ label: room.name, href: `/admin/rooms/show/${room.id}` },
{ label: 'Furniture' },
]}
/>
<FurniClient
room={{
id: room.id,
name: room.name,
ownerUsername: room.owner?.username ?? room.owner_name,
}}
items={rows}
canEdit={session.user.rank >= 4}
/>
</div>
)
}
+5 -78
View File
@@ -1,83 +1,10 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { DoorOpen } from "lucide-react";
import { redirect } from 'next/navigation'
export const dynamic = "force-dynamic";
export default async function AdminRoomDetail({
export default async function RoomLegacyPage({
params,
}: {
params: Promise<{ id: string }>;
params: Promise<{ locale: string; id: string }>
}) {
const t = await getTranslations("pages.admin.rooms");
const { id } = await params;
const roomId = Number(id);
if (!Number.isInteger(roomId) || roomId <= 0) notFound();
let room: Awaited<ReturnType<typeof prisma.rooms.findUnique>> = null;
try {
room = await prisma.rooms.findUnique({ where: { id: roomId } });
} catch {
room = null;
}
if (!room) notFound();
const fields: Array<[string, string]> = [
[t("colId"), String(room.id)],
[t("colName"), room.name || t("unnamed")],
[t("detail.description"), room.description || "—"],
[t("detail.owner"), `${room.ownerName || "—"} (#${room.ownerId})`],
[t("detail.state"), room.state],
[t("colUsers"), `${room.users} / ${room.usersMax}`],
[t("colCategory"), String(room.category)],
[t("detail.score"), String(room.score)],
[t("detail.model"), room.model],
[t("detail.guildId"), room.guildId ? String(room.guildId) : "—"],
[t("detail.tags"), room.tags || "—"],
[t("detail.password"), room.password ? t("detail.yes") : "—"],
[t("detail.public"), room.isPublic === "1" ? t("detail.yes") : t("detail.no")],
[t("detail.staffPicked"), room.isStaffPicked === "1" ? t("detail.yes") : t("detail.no")],
[t("detail.forSale"), room.isForSale === "1" ? t("detail.yes") : t("detail.no")],
[t("detail.tradeMode"), String(room.tradeMode)],
];
return (
<main>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-1">
<Link href="/admin/rooms">← {t("title")}</Link>
</p>
<div className="flex items-center gap-3 mb-6">
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-[var(--color-primary)]/20 to-[var(--color-primary)]/5 grid place-items-center">
<DoorOpen size={20} className="text-[var(--color-primary)]" />
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{room.name || t("unnamed")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("detail.subtitle", { id: room.id, owner: room.ownerName || "—", users: room.users, maxUsers: room.usersMax, state: room.state })}</p>
</div>
</div>
<div className="admin-card">
<table>
<tbody>
{fields.map(([label, value]) => (
<tr key={label}>
<th className="w-[35%] whitespace-nowrap">{label}</th>
<td>{value}</td>
</tr>
))}
</tbody>
</table>
</div>
{room.ownerId ? (
<p className="muted" style={{ marginTop: "1rem" }}>
<Link href={`/admin/users/${room.ownerId}`}>{t("detail.viewOwner")} →</Link>
</p>
) : null}
</main>
);
const { id } = await params
redirect(`/admin/rooms/show/${id}`)
}
+221
View File
@@ -0,0 +1,221 @@
'use client'
import { zodResolver } from '@hookform/resolvers/zod'
import { Loader2, Lock, LogOut, RefreshCw, Save, Trash2, Unlock } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { deleteRoom, roomRconAction, updateRoom } from '@/actions/rooms'
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 { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
import { type UpdateRoomInput, updateRoomSchema } from '@/lib/validators/room'
interface RoomEditFormProps {
room: {
id: number
name: string
description: string
state: string
usersMax: number
users: number
ownerName: string
}
}
export function RoomEditForm({ room }: RoomEditFormProps) {
const { run, isPending } = useServerAction()
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm<UpdateRoomInput>({
resolver: zodResolver(updateRoomSchema),
defaultValues: {
name: room.name,
description: room.description,
state: room.state as 'open' | 'locked' | 'password' | 'invisible',
usersMax: room.usersMax,
},
})
function onSubmit(data: UpdateRoomInput) {
run(() => updateRoom({ id: room.id, ...data }), {
successMessage: 'Room updated successfully.',
})
}
function handleDelete() {
if (!confirm('Are you sure you want to delete this room? This cannot be undone.')) return
run(() => deleteRoom({ id: room.id }), { redirectTo: '/admin/rooms' })
}
function handleRconAction(action: 'kick' | 'lock' | 'unlock' | 'reload') {
run(() => roomRconAction({ roomId: room.id, action }), {
successMessage: `Action "${action}" executed successfully.`,
errorMessage: `Action "${action}" failed. Is the emulator running?`,
})
}
return (
<div className="space-y-4">
<div className="grid gap-6 lg:grid-cols-2">
{/* Edit Form */}
<Card>
<CardHeader>
<CardTitle>Room Details</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">Name</Label>
<Input id="name" {...register('name')} />
{errors.name && <p className="text-sm text-destructive">{errors.name.message}</p>}
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea id="description" rows={3} {...register('description')} />
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label>State</Label>
<Select
defaultValue={room.state}
onValueChange={(v) =>
setValue('state', v as 'open' | 'locked' | 'password' | 'invisible')
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="open">Open</SelectItem>
<SelectItem value="locked">Locked</SelectItem>
<SelectItem value="password">Password</SelectItem>
<SelectItem value="invisible">Invisible</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="usersMax">Max Users</Label>
<Input
id="usersMax"
type="number"
{...register('usersMax', { valueAsNumber: true })}
/>
</div>
</div>
<div className="flex items-center gap-3">
<Button type="submit" disabled={isPending}>
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save Changes
</Button>
<Button
type="button"
variant="destructive"
onClick={handleDelete}
disabled={isPending}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete Room
</Button>
</div>
</form>
</CardContent>
</Card>
{/* RCON Actions */}
<Card>
<CardHeader>
<CardTitle>Quick Actions</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Owner</span>
<span className="font-medium">{room.ownerName}</span>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Current Users</span>
<Badge>
{room.users} / {room.usersMax}
</Badge>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">State</span>
<Badge
variant={
room.state === 'open'
? 'default'
: room.state === 'locked'
? 'secondary'
: 'destructive'
}
>
{room.state}
</Badge>
</div>
<div className="border-t pt-4 space-y-2">
<p className="text-sm font-medium">RCON Commands</p>
<div className="grid grid-cols-2 gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleRconAction('kick')}
disabled={isPending}
>
<LogOut className="mr-2 h-4 w-4" />
Kick All
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleRconAction('lock')}
disabled={isPending}
>
<Lock className="mr-2 h-4 w-4" />
Lock
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleRconAction('unlock')}
disabled={isPending}
>
<Unlock className="mr-2 h-4 w-4" />
Unlock
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleRconAction('reload')}
disabled={isPending}
>
<RefreshCw className="mr-2 h-4 w-4" />
Reload
</Button>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
)
}
+15
View File
@@ -0,0 +1,15 @@
import { notFound } from 'next/navigation'
import { prisma } from '@/lib/prisma'
export async function loadRoom(id: string) {
const roomId = parseInt(id, 10)
if (Number.isNaN(roomId)) notFound()
const room = await prisma.room.findUnique({
where: { id: roomId },
include: { owner: { select: { id: true, username: true, look: true } } },
})
if (!room) notFound()
return room
}
+69
View File
@@ -0,0 +1,69 @@
import { DoorOpen, Eye } from 'lucide-react'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { AdminBreadcrumb } from '@/components/admin/admin-breadcrumb'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { loadRoom } from '../../_lib/load-room'
import { RoomEditForm } from '../../[id]/room-edit-form'
export default async function RoomEditPage({
params,
}: {
params: Promise<{ locale: string; id: string }>
}) {
const { id } = await params
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ROOMS_VIEW, session.user.rank) || session.user.rank < 4) {
redirect('/admin')
}
const room = await loadRoom(id)
return (
<div className="space-y-6">
<AdminBreadcrumb
items={[
{ label: 'Rooms', href: '/admin/rooms' },
{ label: room.name, href: `/admin/rooms/show/${room.id}` },
{ label: 'Edit' },
]}
/>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<DoorOpen className="h-6 w-6 text-muted-foreground" />
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
Edit: {room.name}
<Badge variant="secondary" className="text-xs">
#{room.id}
</Badge>
</h1>
<p className="text-sm text-muted-foreground">
Owner: {room.owner.username} &middot; {room.users}/{room.usersMax} users
</p>
</div>
</div>
<Button variant="outline" asChild>
<Link href={`/admin/rooms/show/${room.id}`}>
<Eye className="mr-2 h-4 w-4" /> View
</Link>
</Button>
</div>
<RoomEditForm
room={{
id: room.id,
name: room.name,
description: room.description,
state: room.state,
usersMax: room.usersMax,
users: room.users,
ownerName: room.owner.username,
}}
/>
</div>
)
}
+28
View File
@@ -0,0 +1,28 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function RoomsLoading() {
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>
)
}
+43 -141
View File
@@ -1,152 +1,54 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
import { DoorOpen } from "lucide-react";
import { fetchAdminList } from '@/lib/admin-list'
import { canAccess, PERMS } from '@/lib/permissions'
import { RoomsTable } from './rooms-table'
export const dynamic = "force-dynamic";
const PER_PAGE = 25;
type RoomRow = {
id: number;
name: string;
ownerName: string;
users: number;
usersMax: number;
state: string;
category: number;
};
export default async function AdminRooms({
export default async function RoomsPage({
params: paramsPromise,
searchParams,
}: {
searchParams: Promise<{ q?: string; page?: string }>;
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
const t = await getTranslations("pages.admin.rooms");
const sp = await searchParams;
const q = (sp.q ?? "").trim();
const page = Math.max(1, Number(sp.page ?? "1") || 1);
const where = q
? { OR: [{ name: { contains: q } }, { ownerName: { contains: q } }] }
: {};
let rooms: RoomRow[] = [];
let total = 0;
try {
[rooms, total] = await Promise.all([
prisma.rooms.findMany({
where,
select: {
id: true,
name: true,
ownerName: true,
users: true,
usersMax: true,
state: true,
category: true,
},
orderBy: { id: "desc" },
skip: (page - 1) * PER_PAGE,
take: PER_PAGE,
const result = await fetchAdminList(
{
permission: PERMS.ROOMS_VIEW,
model: 'room',
searchFields: ['name', 'owner.username'],
include: { owner: { select: { username: true } } },
mapRow: (r) => ({
id: r.id,
name: r.name,
ownerName: r.owner.username,
ownerId: r.owner?.id ?? 0,
state: r.state,
users: r.users,
usersMax: r.usersMax,
description: r.description,
}),
prisma.rooms.count({ where }),
]);
} catch {
rooms = [];
total = 0;
}
},
paramsPromise,
searchParams,
)
const pages = Math.max(1, Math.ceil(total / PER_PAGE));
const qs = (p: number) =>
`/admin/rooms?q=${encodeURIComponent(q)}&page=${p}`;
const openOnPage = rooms.filter((r) => r.state === "open").length;
const usersOnPage = rooms.reduce((sum, r) => sum + r.users, 0);
const canEdit = canAccess(result.permissions, PERMS.ROOMS_VIEW, result.rank) && result.rank >= 4
return (
<main>
<div className="flex items-center gap-3 mb-6">
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-[var(--color-primary)]/20 to-[var(--color-primary)]/5 grid place-items-center">
<DoorOpen size={20} className="text-[var(--color-primary)]" />
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{q ? t("matchingQuery", { query: q }) + " · " : ""}{t("totalRooms", { count: total })}</p>
</div>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Rooms</h1>
<p className="text-muted-foreground">{result.total.toLocaleString()} rooms total</p>
</div>
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={q ? t("matchingRooms") : t("totalRooms", { count: total })} value={total} icon="🏠" />
<StatusCard label={t("openThisPage")} value={openOnPage} state="ok" icon="🔓" />
<StatusCard label={t("usersInRoom")} value={usersOnPage} icon="👥" />
</div>
<form className="flex gap-2 mb-4">
<input name="q" defaultValue={q} placeholder={t("searchPlaceholder")} />
<button type="submit" className="btn btn-primary">
{t("search")}
</button>
</form>
<div className="admin-card overflow-x-auto" style={{ padding: 0 }}>
<table>
<thead>
<tr>
<th>{t("colId")}</th>
<th>{t("colName")}</th>
<th>{t("colOwner")}</th>
<th>{t("colUsers")}</th>
<th>{t("colState")}</th>
<th>{t("colCategory")}</th>
</tr>
</thead>
<tbody>
{rooms.map((r) => (
<tr key={r.id}>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{r.id}</td>
<td>
<Link href={`/admin/rooms/${r.id}`}>{r.name || t("unnamed")}</Link>
</td>
<td>{r.ownerName || "—"}</td>
<td>
{r.users} / {r.usersMax}
</td>
<td>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${r.state === "open" ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}>
{r.state}
</span>
</td>
<td>{r.category}</td>
</tr>
))}
</tbody>
</table>
</div>
{rooms.length === 0 ? (
<p className="text-xs text-gray-500 dark:text-gray-400" style={{ marginTop: "1rem" }}>
{t("noRooms")}
</p>
) : null}
<p className="text-xs text-gray-500 dark:text-gray-400" style={{ marginTop: "1rem" }}>
{t("pagination", { page, pages, total })}
{page > 1 ? (
<>
{" · "}
<Link href={qs(page - 1)}>← {t("prev")}</Link>
</>
) : null}
{page < pages ? (
<>
{" · "}
<Link href={qs(page + 1)}>{t("next")} →</Link>
</>
) : null}
</p>
</main>
);
<RoomsTable
data={{
rows: result.rows,
total: result.total,
page: result.page,
perPage: result.perPage,
lastPage: result.lastPage,
}}
canEdit={canEdit}
/>
</div>
)
}
+131
View File
@@ -0,0 +1,131 @@
'use client'
import { Eye, Pencil, Sofa, Wifi } 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 RoomRow {
id: number
name: string
ownerName: string
ownerId: number
state: string
users: number
usersMax: number
description: string
}
const stateVariants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
open: 'default',
locked: 'secondary',
password: 'destructive',
invisible: 'outline',
}
function getColumns(canEdit: boolean): DataTableColumn<RoomRow>[] {
return [
{ key: 'id', label: 'ID', sortable: true },
{
key: 'name',
label: 'Room',
sortable: true,
render: (_, row) => (
<Link href={`/admin/rooms/show/${row.id}`} className="hover:opacity-80">
<div className="min-w-0">
<span className="font-medium block">{row.name}</span>
{row.description && (
<span className="text-xs text-muted-foreground truncate block max-w-[250px]">
{row.description}
</span>
)}
</div>
</Link>
),
},
{
key: 'ownerName',
label: 'Owner',
render: (_, row) => (
<Link
href={`/admin/users/show/${row.ownerId}`}
className="text-sm text-primary hover:underline"
>
{row.ownerName}
</Link>
),
},
{
key: 'state',
label: 'State',
sortable: true,
filterKey: 'filter_state',
filterOptions: [
{ label: 'Open', value: 'open' },
{ label: 'Locked', value: 'locked' },
{ label: 'Password', value: 'password' },
{ label: 'Invisible', value: 'invisible' },
],
render: (value) => (
<Badge variant={stateVariants[String(value)] || 'outline'}>{String(value)}</Badge>
),
},
{
key: 'users',
label: 'Users',
sortable: true,
render: (_, row) => (
<span className="flex items-center gap-1.5 text-sm">
{row.users > 0 && <Wifi className="h-3 w-3 text-green-500" />}
<span className={row.users > 0 ? 'font-medium' : 'text-muted-foreground'}>
{row.users}
</span>
<span className="text-muted-foreground">/ {row.usersMax}</span>
</span>
),
},
{
key: 'actions',
label: '',
render: (_, row) => (
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" asChild>
<Link href={`/admin/rooms/show/${row.id}`}>
<Eye className="h-4 w-4" />
</Link>
</Button>
<Button variant="ghost" size="icon" asChild>
<Link href={`/admin/rooms/${row.id}/furni`}>
<Sofa className="h-4 w-4" />
</Link>
</Button>
{canEdit && (
<Button variant="ghost" size="icon" asChild>
<Link href={`/admin/rooms/edit/${row.id}`}>
<Pencil className="h-4 w-4" />
</Link>
</Button>
)}
</div>
),
},
]
}
interface RoomsTableProps {
data: PaginatedResult<RoomRow>
canEdit: boolean
}
export function RoomsTable({ data, canEdit }: RoomsTableProps) {
return (
<DataTable
data={data}
columns={getColumns(canEdit)}
searchPlaceholder="Search by room name or owner..."
exportUrl={canEdit ? '/api/admin/export?type=rooms' : undefined}
/>
)
}
+128
View File
@@ -0,0 +1,128 @@
import { DoorOpen, Eye, Globe, Lock, Pencil, Sofa, Users } from 'lucide-react'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { AdminBreadcrumb } from '@/components/admin/admin-breadcrumb'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { loadRoom } from '../../_lib/load-room'
const stateVariants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
open: 'default',
locked: 'secondary',
password: 'destructive',
invisible: 'outline',
}
export default async function RoomShowPage({
params,
}: {
params: Promise<{ locale: string; id: string }>
}) {
const { id } = await params
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.ROOMS_VIEW, session.user.rank)) redirect('/admin')
const room = await loadRoom(id)
const canEdit = session.user.rank >= 4
return (
<div className="space-y-6">
<AdminBreadcrumb items={[{ label: 'Rooms', href: '/admin/rooms' }, { label: room.name }]} />
{/* Hero */}
<div className="rounded-xl border bg-gradient-to-r from-card to-muted/30 p-6">
<div className="flex items-start justify-between gap-4">
<div className="space-y-2">
<div className="flex items-center gap-2">
<DoorOpen className="h-6 w-6 text-muted-foreground" />
<h1 className="text-2xl font-bold">{room.name}</h1>
<Badge variant="secondary" className="text-xs">
#{room.id}
</Badge>
<Badge variant={stateVariants[room.state] || 'outline'}>{room.state}</Badge>
</div>
{room.description && <p className="text-muted-foreground">{room.description}</p>}
<div className="flex items-center gap-4 text-sm">
<span className="flex items-center gap-1.5">
<Users className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{room.users}</span> / {room.usersMax} users
</span>
<Link
href={`/admin/users/show/${room.owner.id}`}
className="text-primary hover:underline"
>
Owner: {room.owner.username}
</Link>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" asChild>
<Link href={`/admin/rooms/${room.id}/furni`}>
<Sofa className="mr-2 h-4 w-4" /> Furniture
</Link>
</Button>
{canEdit && (
<Button asChild>
<Link href={`/admin/rooms/edit/${room.id}`}>
<Pencil className="mr-2 h-4 w-4" /> Edit
</Link>
</Button>
)}
</div>
</div>
</div>
{/* Info grid */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Users className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-2xl font-bold">
{room.users} / {room.usersMax}
</p>
<p className="text-xs text-muted-foreground">Current Users</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Lock className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-2xl font-bold capitalize">{room.state}</p>
<p className="text-xs text-muted-foreground">Access State</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Eye className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-2xl font-bold">{room.score}</p>
<p className="text-xs text-muted-foreground">Score</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Globe className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-2xl font-bold truncate">{room.category}</p>
<p className="text-xs text-muted-foreground">Category</p>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
)
}
Loaded 100 of 338 files, more files were not shown because too many files have changed in this diff. Show more