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

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