revert fb8e77bb68
Local Build and Deploy / deploy (push) Successful in 1m11s

revert style: clean up code with prettier and eslint
This commit is contained in:
remco committed 2026-07-12 21:02:03 +02:00
1 parent 27de078f54
commit e85e4d74ea
378 files changed
+20710 -22428

No files matched your search

@@ -1,54 +1,54 @@
"use client";
'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";
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;
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;
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[];
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({
@@ -78,15 +78,14 @@ export function CatalogDetailTabs({
</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;
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-[var(--admin-warning-subtle)] text-[var(--admin-warning)] text-[10px] px-1.5 py-0.5 leading-none font-medium">
<span className="ml-1 rounded-full bg-[var(--admin-warning-subtle)] text-[var(--admin-warning)] text-[10px] px-1.5 py-0.5 leading-none font-medium">
{missing}
</span>
) : null;
) : null
})()}
</TabsTrigger>
</TabsList>
@@ -123,5 +122,5 @@ export function CatalogDetailTabs({
/>
</TabsContent>
</Tabs>
);
)
}
@@ -2,6 +2,6 @@
* 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";
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
@@ -1,8 +1,8 @@
"use client";
'use client'
import { Check, ChevronsUpDown, Star } from "lucide-react";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Check, ChevronsUpDown, Star } from 'lucide-react'
import { useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import {
Command,
CommandEmpty,
@@ -10,11 +10,11 @@ import {
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";
} 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 ──────────────────────────────────────────────
@@ -25,21 +25,21 @@ export function ToggleField({
onChange,
disabled,
}: {
label: string;
label: string
/** Boolean checked state */
checked?: boolean;
checked?: boolean
/** Number or string (0/1 or '0'/'1') — converted to boolean automatically */
value?: number | string;
onChange: (v: boolean) => void;
disabled?: boolean;
value?: number | string
onChange: (v: boolean) => void
disabled?: boolean
}) {
const isChecked = checked ?? (value === 1 || value === "1");
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 ──────────────────────────────────
@@ -50,19 +50,19 @@ export function InteractionTypeCombobox({
types,
disabled,
}: {
value: string;
onChange: (v: string) => void;
types: string[];
disabled?: boolean;
value: string
onChange: (v: string) => void
types: string[]
disabled?: boolean
}) {
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
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]);
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}>
@@ -74,7 +74,7 @@ export function InteractionTypeCombobox({
disabled={disabled}
className="w-full justify-between font-normal h-8 text-sm"
>
<span className="truncate">{value || "Select type..."}</span>
<span className="truncate">{value || 'Select type...'}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
@@ -92,15 +92,15 @@ export function InteractionTypeCombobox({
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("");
onChange(inputValue.trim())
setOpen(false)
setInputValue('')
}}
>
Use &quot;{inputValue.trim()}&quot;
</button>
) : (
"No types found."
'No types found.'
)}
</CommandEmpty>
<CommandGroup>
@@ -109,12 +109,14 @@ export function InteractionTypeCombobox({
key={t}
value={t}
onSelect={() => {
onChange(t);
setOpen(false);
setInputValue("");
onChange(t)
setOpen(false)
setInputValue('')
}}
>
<Check className={cn("mr-2 h-4 w-4", value === t ? "opacity-100" : "opacity-0")} />
<Check
className={cn('mr-2 h-4 w-4', value === t ? 'opacity-100' : 'opacity-0')}
/>
<span className="truncate">{t}</span>
</CommandItem>
))}
@@ -123,7 +125,7 @@ export function InteractionTypeCombobox({
</Command>
</PopoverContent>
</Popover>
);
)
}
// ── Move Page Combobox with smart suggestions ─────────────────
@@ -135,32 +137,35 @@ export function MovePageCombobox({
currentPageId,
suggestedPageIds,
}: {
value: number | null;
onChange: (id: number | null) => void;
pages: { id: number; caption: string }[];
currentPageId: number;
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[];
suggestedPageIds?: number[]
}) {
const [open, setOpen] = useState(false);
const [open, setOpen] = useState(false)
const options = useMemo(() => pages.filter((p) => p.id !== currentPageId), [pages, currentPageId]);
const options = useMemo(() => pages.filter((p) => p.id !== currentPageId), [pages, currentPageId])
const selectedPage = value ? pages.find((p) => p.id === value) : null;
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]));
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]);
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]);
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}>
@@ -173,7 +178,9 @@ export function MovePageCombobox({
>
{selectedPage ? (
<span className="truncate">
<span className="text-muted-foreground font-mono text-xs mr-1.5">#{selectedPage.id}</span>
<span className="text-muted-foreground font-mono text-xs mr-1.5">
#{selectedPage.id}
</span>
{selectedPage.caption}
</span>
) : (
@@ -196,13 +203,20 @@ export function MovePageCombobox({
key={`s-${page.id}`}
value={`${page.id} ${page.caption}`}
onSelect={() => {
onChange(page.id);
setOpen(false);
onChange(page.id)
setOpen(false)
}}
>
<Check className={cn("mr-2 h-4 w-4", value === page.id ? "opacity-100" : "opacity-0")} />
<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-[var(--admin-warning)]" />
<span className="text-muted-foreground font-mono text-xs mr-1.5">#{page.id}</span>
<span className="text-muted-foreground font-mono text-xs mr-1.5">
#{page.id}
</span>
<span className="truncate">{page.caption}</span>
</CommandItem>
))}
@@ -210,17 +224,19 @@ export function MovePageCombobox({
)}
{/* All pages */}
<CommandGroup heading={suggested.length > 0 ? "All pages" : undefined}>
<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);
onChange(page.id)
setOpen(false)
}}
>
<Check className={cn("mr-2 h-4 w-4", value === page.id ? "opacity-100" : "opacity-0")} />
<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>
@@ -230,5 +246,5 @@ export function MovePageCombobox({
</Command>
</PopoverContent>
</Popover>
);
)
}
@@ -1,7 +1,7 @@
"use client";
'use client'
import { Image as ImageIcon } from "lucide-react";
import { getHabboCdnIconUrl, getLocalIconUrl } from "@/lib/furni/classname";
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) {
@@ -9,34 +9,34 @@ export function FurniIcon({ classname, revision }: { classname: string; revision
<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);
const localUrl = getLocalIconUrl(classname)
function handleError(e: React.SyntheticEvent<HTMLImageElement>) {
const img = e.target as HTMLImageElement;
const stage = img.dataset.fallback;
const img = e.target as HTMLImageElement
const stage = img.dataset.fallback
if (!stage && revision > 0) {
img.dataset.fallback = "cdn";
img.src = getHabboCdnIconUrl(classname, revision);
img.dataset.fallback = 'cdn'
img.src = getHabboCdnIconUrl(classname, revision)
} else {
img.dataset.fallback = "none";
img.style.opacity = "0";
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" }}
style={{ imageRendering: 'pixelated' }}
onError={handleError}
loading="lazy"
/>
</div>
);
)
}
@@ -1,4 +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";
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'
@@ -1,53 +1,59 @@
"use client";
'use client'
import { Loader2, Music } from "lucide-react";
import { useEffect, useState } from "react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
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";
} 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";
export { invalidateSongPickerCache } from '@/lib/client-cache/song-picker-cache'
interface Props {
value: number;
onChange: (id: number) => void;
disabled?: boolean;
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")}`;
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);
const initial = getCachedSongPickerOptions()
const [options, setOptions] = useState<SoundtrackOption[]>(initial ?? [])
const [loading, setLoading] = useState(!initial)
useEffect(() => {
if (getCachedSongPickerOptions()) return;
let cancelled = false;
if (getCachedSongPickerOptions()) return
let cancelled = false
loadSongPickerOptions()
.then((items) => {
if (!cancelled) setOptions(items);
if (!cancelled) setOptions(items)
})
.catch(() => {
if (!cancelled) setOptions([]);
if (!cancelled) setOptions([])
})
.finally(() => {
if (!cancelled) setLoading(false);
});
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true;
};
}, []);
cancelled = true
}
}, [])
return (
<Select
@@ -75,12 +81,14 @@ export function SongPicker({ value, onChange, disabled }: Props) {
<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 className="text-xs text-muted-foreground font-mono">
{formatLength(opt.length)}
</span>
)}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
);
)
}
@@ -1,71 +1,71 @@
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;
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;
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;
costCredits: number
costPoints: number
pointsType: number
amount: number
}
export const POINTS_TYPES: Record<number, { label: string; color: string }> = {
0: { label: "Duckets", color: "text-[var(--admin-info)]" },
5: { label: "Diamonds", color: "text-[var(--admin-accent-text)]" },
101: { label: "Snowflakes", color: "text-[var(--admin-info)]" },
103: { label: "Hearts", color: "text-[var(--admin-error)]" },
104: { label: "Stars", color: "text-[var(--admin-warning)]" },
105: { label: "Shells", color: "text-[var(--admin-warning)]" },
};
0: { label: 'Duckets', color: 'text-[var(--admin-info)]' },
5: { label: 'Diamonds', color: 'text-[var(--admin-accent-text)]' },
101: { label: 'Snowflakes', color: 'text-[var(--admin-info)]' },
103: { label: 'Hearts', color: 'text-[var(--admin-error)]' },
104: { label: 'Stars', color: 'text-[var(--admin-warning)]' },
105: { label: 'Shells', color: 'text-[var(--admin-warning)]' },
}
export const DEFAULT_NEW_ITEM = {
catalogName: "",
itemIds: "0",
catalogName: '',
itemIds: '0',
costCredits: 0,
costPoints: 0,
pointsType: 0,
@@ -75,11 +75,11 @@ export const DEFAULT_NEW_ITEM = {
orderNumber: 1,
offerId: -1,
songId: 0,
haveOffer: "1",
clubOnly: "0",
extradata: "",
};
haveOffer: '1',
clubOnly: '0',
extradata: '',
}
export function getPointsLabel(type: number) {
return POINTS_TYPES[type] || { label: `Type ${type}`, color: "theme-text-muted" };
return POINTS_TYPES[type] || { label: `Type ${type}`, color: 'theme-text-muted' }
}
+170 -149
View File
@@ -1,4 +1,4 @@
"use client";
'use client'
import {
Check,
@@ -11,17 +11,17 @@ import {
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";
} 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,
@@ -29,109 +29,120 @@ import {
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";
} 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;
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 }[];
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);
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",
enabled: catalogPage.enabled as '0' | '1',
visible: catalogPage.visible as '0' | '1',
minRank: catalogPage.minRank,
clubOnly: catalogPage.clubOnly as "0" | "1",
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 || "",
});
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;
if (!canEdit) return
function onKeyDown(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key === "s") {
e.preventDefault();
formRef.current?.requestSubmit();
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
formRef.current?.requestSubmit()
}
}
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [canEdit]);
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 }));
setForm((prev) => ({ ...prev, [key]: value }))
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
e.preventDefault()
run(() => updateCatalogPage({ id: catalogPage.id, ...form }), {
successMessage: "Page updated and catalog synced.",
errorMessage: "Failed to update.",
});
successMessage: 'Page updated and catalog synced.',
errorMessage: 'Failed to update.',
})
}
function handleDelete() {
const childCount = childPages.length;
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;
: 'Delete this catalog page and all its items?'
if (!confirm(msg)) return
run(() => deleteCatalogPage({ id: catalogPage.id }), {
successMessage: "Page deleted.",
redirectTo: "/admin/catalog",
});
successMessage: 'Page deleted.',
redirectTo: '/admin/catalog',
})
}
const layoutColorClass = LAYOUT_COLORS[form.pageLayout] || "bg-muted text-muted-foreground";
const layoutColorClass = LAYOUT_COLORS[form.pageLayout] || 'bg-muted text-muted-foreground'
return (
<form ref={formRef} onSubmit={handleSubmit}>
@@ -164,7 +175,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
<Input
id="caption"
value={form.caption}
onChange={(e) => update("caption", e.target.value)}
onChange={(e) => update('caption', e.target.value)}
disabled={!canEdit}
/>
</div>
@@ -172,7 +183,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
<Label>Parent Page</Label>
<ParentCombobox
value={form.parentId}
onChange={(id) => update("parentId", id)}
onChange={(id) => update('parentId', id)}
pages={allPages}
currentPageId={catalogPage.id}
disabled={!canEdit}
@@ -184,11 +195,11 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
<Label>Layout</Label>
<LayoutSelect
value={form.pageLayout}
onChange={(v) => update("pageLayout", v)}
onChange={(v) => update('pageLayout', v)}
disabled={!canEdit}
/>
<p className="text-xs text-muted-foreground">
{LAYOUT_DESCRIPTIONS[form.pageLayout as CatalogLayout] ?? "Custom layout"}
{LAYOUT_DESCRIPTIONS[form.pageLayout as CatalogLayout] ?? 'Custom layout'}
</p>
</div>
@@ -199,7 +210,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
id="orderNum"
type="number"
value={form.orderNum}
onChange={(e) => update("orderNum", parseInt(e.target.value, 10) || 0)}
onChange={(e) => update('orderNum', parseInt(e.target.value, 10) || 0)}
disabled={!canEdit}
/>
</div>
@@ -211,7 +222,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
min={1}
max={100}
value={form.minRank}
onChange={(e) => update("minRank", parseInt(e.target.value, 10) || 1)}
onChange={(e) => update('minRank', parseInt(e.target.value, 10) || 1)}
disabled={!canEdit}
/>
</div>
@@ -224,7 +235,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
<Label>Headline</Label>
<CatalogImagePicker
value={form.pageHeadline}
onChange={(v) => update("pageHeadline", v)}
onChange={(v) => update('pageHeadline', v)}
type="header"
label="Headline image"
disabled={!canEdit}
@@ -235,7 +246,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
<Label>Teaser</Label>
<CatalogImagePicker
value={form.pageTeaser}
onChange={(v) => update("pageTeaser", v)}
onChange={(v) => update('pageTeaser', v)}
type="teaser"
label="Teaser image"
disabled={!canEdit}
@@ -247,7 +258,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
id="pageText1"
label="Text 1"
value={form.pageText1}
onChange={(v) => update("pageText1", v)}
onChange={(v) => update('pageText1', v)}
disabled={!canEdit}
rows={4}
max={5000}
@@ -256,7 +267,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
id="pageText2"
label="Text 2"
value={form.pageText2}
onChange={(v) => update("pageText2", v)}
onChange={(v) => update('pageText2', v)}
disabled={!canEdit}
rows={4}
max={5000}
@@ -267,7 +278,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
id="pageTextDetails"
label="Details"
value={form.pageTextDetails}
onChange={(v) => update("pageTextDetails", v)}
onChange={(v) => update('pageTextDetails', v)}
disabled={!canEdit}
rows={3}
max={5000}
@@ -276,7 +287,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
id="pageTextTeaser"
label="Text Teaser"
value={form.pageTextTeaser}
onChange={(v) => update("pageTextTeaser", v)}
onChange={(v) => update('pageTextTeaser', v)}
disabled={!canEdit}
rows={3}
max={5000}
@@ -286,7 +297,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
id="pageSpecial"
label="Special"
value={form.pageSpecial}
onChange={(v) => update("pageSpecial", v)}
onChange={(v) => update('pageSpecial', v)}
disabled={!canEdit}
rows={2}
max={2048}
@@ -300,7 +311,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
<div className="flex items-center gap-3">
<IconPicker
value={form.iconImage}
onChange={(id) => update("iconImage", id)}
onChange={(id) => update('iconImage', id)}
disabled={!canEdit}
/>
<p className="text-xs text-muted-foreground">
@@ -317,11 +328,12 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
min={0}
className="w-32"
value={form.iconColor}
onChange={(e) => update("iconColor", parseInt(e.target.value, 10) || 0)}
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.
Legacy tint value. Leave at default unless you need to match a specific
theme.
</p>
</div>
</div>
@@ -349,10 +361,12 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
>
<span>
{child.caption}
<span className="ml-2 text-muted-foreground font-mono text-xs">#{child.id}</span>
<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 variant={child.enabled === '1' ? 'default' : 'outline'}>
{child.enabled === '1' ? 'Enabled' : 'Disabled'}
</Badge>
</Link>
))}
@@ -375,8 +389,13 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
<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)}>
<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>
@@ -388,24 +407,24 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
id="tg-enabled"
label="Enabled"
description="Active in the catalog"
checked={form.enabled === "1"}
onChange={(v) => update("enabled", v ? "1" : "0")}
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")}
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")}
checked={form.clubOnly === '1'}
onChange={(v) => update('clubOnly', v ? '1' : '0')}
disabled={!canEdit}
/>
</div>
@@ -452,7 +471,7 @@ export function CatalogPageForm({ catalogPage, childPages, canEdit, allPages }:
</div>
</div>
</form>
);
)
}
// ── Toggle row ─────────────────────────────────────────────────
@@ -465,12 +484,12 @@ function ToggleRow({
onChange,
disabled,
}: {
id: string;
label: string;
description: string;
checked: boolean;
onChange: (v: boolean) => void;
disabled?: boolean;
id: string
label: string
description: string
checked: boolean
onChange: (v: boolean) => void
disabled?: boolean
}) {
return (
<div className="flex items-start justify-between gap-3">
@@ -482,7 +501,7 @@ function ToggleRow({
</div>
<Switch id={id} checked={checked} onCheckedChange={onChange} disabled={disabled} />
</div>
);
)
}
// ── Text field with counter ────────────────────────────────────
@@ -495,12 +514,12 @@ function _TextField({
disabled,
max,
}: {
id: string;
label: string;
value: string;
onChange: (v: string) => void;
disabled?: boolean;
max?: number;
id: string
label: string
value: string
onChange: (v: string) => void
disabled?: boolean
max?: number
}) {
return (
<div className="space-y-2">
@@ -520,7 +539,7 @@ function _TextField({
maxLength={max}
/>
</div>
);
)
}
function TextareaField({
@@ -532,13 +551,13 @@ function TextareaField({
rows = 3,
max,
}: {
id: string;
label: string;
value: string;
onChange: (v: string) => void;
disabled?: boolean;
rows?: number;
max?: number;
id: string
label: string
value: string
onChange: (v: string) => void
disabled?: boolean
rows?: number
max?: number
}) {
return (
<div className="space-y-2">
@@ -559,7 +578,7 @@ function TextareaField({
maxLength={max}
/>
</div>
);
)
}
// ── Layout select with color swatch ────────────────────────────
@@ -569,9 +588,9 @@ function LayoutSelect({
onChange,
disabled,
}: {
value: string;
onChange: (v: string) => void;
disabled?: boolean;
value: string
onChange: (v: string) => void
disabled?: boolean
}) {
return (
<Select value={value} onValueChange={onChange} disabled={disabled}>
@@ -580,19 +599,19 @@ function LayoutSelect({
</SelectTrigger>
<SelectContent>
{CATALOG_LAYOUTS.map((layout) => {
const colorClass = LAYOUT_COLORS[layout] || "bg-muted text-muted-foreground";
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)} />
<span className={cn('inline-block h-2 w-2 rounded-full', colorClass)} />
{layout}
</span>
</SelectItem>
);
)
})}
</SelectContent>
</Select>
);
)
}
// ── Parent page combobox with search ────────────────────────────
@@ -604,16 +623,16 @@ function ParentCombobox({
currentPageId,
disabled,
}: {
value: number;
onChange: (id: number) => void;
pages: { id: number; caption: string }[];
currentPageId: number;
disabled?: boolean;
value: number
onChange: (id: number) => void
pages: { id: number; caption: string }[]
currentPageId: number
disabled?: boolean
}) {
const [open, setOpen] = useState(false);
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);
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}>
@@ -629,7 +648,7 @@ function ParentCombobox({
{selected ? (
<span className="truncate">
<span className="text-muted-foreground font-mono text-xs mr-1.5">
{selected.id === -1 ? "—" : `#${selected.id}`}
{selected.id === -1 ? '—' : `#${selected.id}`}
</span>
{selected.caption}
</span>
@@ -648,11 +667,11 @@ function ParentCombobox({
<CommandItem
value="root"
onSelect={() => {
onChange(-1);
setOpen(false);
onChange(-1)
setOpen(false)
}}
>
<Check className={cn("mr-2 h-4 w-4", value === -1 ? "opacity-100" : "opacity-0")} />
<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>
@@ -661,11 +680,13 @@ function ParentCombobox({
key={page.id}
value={`${page.id} ${page.caption}`}
onSelect={() => {
onChange(page.id);
setOpen(false);
onChange(page.id)
setOpen(false)
}}
>
<Check className={cn("mr-2 h-4 w-4", value === page.id ? "opacity-100" : "opacity-0")} />
<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>
@@ -675,5 +696,5 @@ function ParentCombobox({
</Command>
</PopoverContent>
</Popover>
);
)
}
@@ -1,4 +1,4 @@
"use client";
'use client'
import {
AlertTriangle,
@@ -11,39 +11,46 @@ import {
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";
} 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;
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 }>;
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";
type FilterMode = 'all' | 'missing' | 'modified'
export function CatalogTranslateTab({
baseItems,
@@ -53,164 +60,164 @@ export function CatalogTranslateTab({
furniDescriptionMap,
furniRevisionMap = {},
}: CatalogTranslateTabProps) {
const router = useRouter();
const { run, isPending } = useServerAction();
const [isSuggesting, setIsSuggesting] = useState(false);
const [filterMode, setFilterMode] = useState<FilterMode>("all");
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());
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] ?? ""])),
);
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] ?? ""),
(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));
case 'missing':
return baseItems.filter((item) => !furniDataIdSet.has(item.id))
case 'modified':
return baseItems.filter((item) => isNameChanged(item) || isDescChanged(item))
default:
return baseItems;
return baseItems
}
}, [baseItems, filterMode, furniDataIdSet, isNameChanged, isDescChanged]);
}, [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 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]);
)
}, [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]);
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 }));
setEditedNames((prev) => ({ ...prev, [id]: value }))
}
function handleDescChange(id: number, value: string) {
setEditedDescs((prev) => ({ ...prev, [id]: value }));
setEditedDescs((prev) => ({ ...prev, [id]: value }))
}
function handleReset() {
setEditedNames(Object.fromEntries(baseItems.map((item) => [item.id, item.publicName])));
setEditedNames(Object.fromEntries(baseItems.map((item) => [item.id, item.publicName])))
setEditedDescs(
Object.fromEntries(baseItems.map((item) => [item.id, furniDescriptionMap[item.id] ?? ""])),
);
Object.fromEntries(baseItems.map((item) => [item.id, furniDescriptionMap[item.id] ?? ''])),
)
}
async function handleSuggestFromHabboFurni() {
if (targetItems.length === 0) return;
setIsSuggesting(true);
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);
const classnames = targetItems.map((item) => item.itemName).filter(Boolean)
if (classnames.length === 0) {
toast.info("No classnames found to look up.");
setIsSuggesting(false);
return;
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 }> = {};
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 chunk = classnames.slice(i, i + CHUNK_SIZE)
const res = await fetch(
`/api/admin/catalog/suggest?classnames=${encodeURIComponent(chunk.join(","))}`,
);
`/api/admin/catalog/suggest?classnames=${encodeURIComponent(chunk.join(','))}`,
)
if (res.ok) {
const data = await res.json();
Object.assign(allSuggestions, data.suggestions || {});
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 };
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;
const suggestion = allSuggestions[item.itemName]
if (!suggestion) continue
if (suggestion.name && suggestion.name !== item.publicName) {
newNames[item.id] = suggestion.name;
nameCount++;
newNames[item.id] = suggestion.name
nameCount++
}
const currentDesc = furniDescriptionMap[item.id] ?? "";
const currentDesc = furniDescriptionMap[item.id] ?? ''
if (suggestion.description && suggestion.description !== currentDesc) {
newDescs[item.id] = suggestion.description;
descCount++;
newDescs[item.id] = suggestion.description
descCount++
}
}
setEditedNames(newNames);
setEditedDescs(newDescs);
setEditedNames(newNames)
setEditedDescs(newDescs)
const total = nameCount + descCount;
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.`);
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}`);
toast.error(`HabboFurni error: ${(err as Error).message}`)
} finally {
setIsSuggesting(false);
setIsSuggesting(false)
}
}
async function handleSaveAll() {
if (changedItems.length === 0) return;
if (changedItems.length === 0) return
run(
() =>
@@ -222,26 +229,26 @@ export function CatalogTranslateTab({
})),
}),
{
successMessage: "Translations saved.",
errorMessage: "Failed to save translations.",
successMessage: 'Translations saved.',
errorMessage: 'Failed to save translations.',
onSuccess: (data) => {
const d = data as Record<string, number | boolean>;
const parts = [];
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`);
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");
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(`${d.furniDataInserted} new item(s) added to FurnitureData.json`)
}
parts.push("emulator cache refreshed");
toast.success(`${parts.join(" · ")}.`);
router.refresh();
parts.push('emulator cache refreshed')
toast.success(`${parts.join(' · ')}.`)
router.refresh()
},
},
);
)
}
return (
@@ -267,7 +274,8 @@ export function CatalogTranslateTab({
<div className="flex items-center gap-1.5 mt-2 text-xs text-[var(--admin-warning)] dark:text-[var(--admin-warning)]">
<AlertTriangle className="h-3.5 w-3.5" />
<span>
{missingItems.length} item(s) missing from FurnitureData.json — will be auto-inserted on save
{missingItems.length} item(s) missing from FurnitureData.json — will be
auto-inserted on save
</span>
</div>
)}
@@ -286,7 +294,7 @@ export function CatalogTranslateTab({
) : (
<Sparkles className="mr-2 h-4 w-4" />
)}
Suggest IT{selected.size > 0 ? ` (${selected.size})` : ""}
Suggest IT{selected.size > 0 ? ` (${selected.size})` : ''}
</Button>
<Button
variant="outline"
@@ -297,7 +305,11 @@ export function CatalogTranslateTab({
<RotateCcw className="mr-2 h-4 w-4" />
Reset
</Button>
<Button size="sm" onClick={handleSaveAll} disabled={isPending || changedItems.length === 0}>
<Button
size="sm"
onClick={handleSaveAll}
disabled={isPending || changedItems.length === 0}
>
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
@@ -315,28 +327,28 @@ export function CatalogTranslateTab({
<Filter className="h-4 w-4 text-muted-foreground" />
<div className="flex gap-1">
<Button
variant={filterMode === "all" ? "default" : "outline"}
variant={filterMode === 'all' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode("all")}
onClick={() => setFilterMode('all')}
>
All ({baseItems.length})
</Button>
<Button
variant={filterMode === "missing" ? "default" : "outline"}
variant={filterMode === 'missing' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode("missing")}
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"}
variant={filterMode === 'modified' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode("modified")}
onClick={() => setFilterMode('modified')}
disabled={changedItems.length === 0}
>
Modified ({changedItems.length})
@@ -350,7 +362,9 @@ export function CatalogTranslateTab({
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>
<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]">
@@ -375,19 +389,19 @@ export function CatalogTranslateTab({
</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];
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-[var(--admin-warning-subtle)] dark:bg-[var(--admin-warning-subtle)]"
? 'bg-[var(--admin-warning-subtle)] dark:bg-[var(--admin-warning-subtle)]'
: isMissing
? "bg-[var(--admin-warning-subtle)] dark:bg-[var(--admin-warning-subtle)]"
? 'bg-[var(--admin-warning-subtle)] dark:bg-[var(--admin-warning-subtle)]'
: undefined
}
>
@@ -400,18 +414,24 @@ export function CatalogTranslateTab({
</TableCell>
<TableCell className="px-1">
{(() => {
const revInfo = furniRevisionMap[item.id];
const revInfo = furniRevisionMap[item.id]
return revInfo ? (
<FurniIcon classname={revInfo.classname} revision={revInfo.revision} />
<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
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">
@@ -419,10 +439,10 @@ export function CatalogTranslateTab({
</TableCell>
<TableCell>
<Input
value={editedNames[item.id] || ""}
value={editedNames[item.id] || ''}
onChange={(e) => handleNameChange(item.id, e.target.value)}
disabled={!canEdit}
className={`h-8 text-sm ${nameChanged ? "border-[var(--admin-warning-border)] dark:border-[var(--admin-warning-border)]" : ""}`}
className={`h-8 text-sm ${nameChanged ? 'border-[var(--admin-warning-border)] dark:border-[var(--admin-warning-border)]' : ''}`}
/>
{currentCatalogName && currentCatalogName !== item.publicName && (
<p className="text-[11px] text-muted-foreground mt-0.5 truncate">
@@ -432,11 +452,11 @@ export function CatalogTranslateTab({
</TableCell>
<TableCell>
<Input
value={editedDescs[item.id] || ""}
value={editedDescs[item.id] || ''}
onChange={(e) => handleDescChange(item.id, e.target.value)}
disabled={!canEdit}
placeholder="No description"
className={`h-8 text-sm ${descChanged ? "border-[var(--admin-warning-border)] dark:border-[var(--admin-warning-border)]" : ""}`}
className={`h-8 text-sm ${descChanged ? 'border-[var(--admin-warning-border)] dark:border-[var(--admin-warning-border)]' : ''}`}
/>
</TableCell>
<TableCell>
@@ -444,7 +464,7 @@ export function CatalogTranslateTab({
{isChanged ? (
<Badge
variant="secondary"
className="text-xs bg-[var(--admin-warning-subtle)] text-[var(--admin-warning)]"
className="text-xs bg-[var(--admin-warning-subtle)] text-[var(--admin-warning)]"
>
Modified
</Badge>
@@ -474,7 +494,7 @@ export function CatalogTranslateTab({
</div>
</TableCell>
</TableRow>
);
)
})}
</TableBody>
</Table>
@@ -483,5 +503,5 @@ export function CatalogTranslateTab({
)}
</CardContent>
</Card>
);
)
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { Skeleton } from "@/components/ui/skeleton";
import { Skeleton } from '@/components/ui/skeleton'
export default function CatalogDetailLoading() {
return (
@@ -37,5 +37,5 @@ export default function CatalogDetailLoading() {
</div>
</div>
</div>
);
)
}
+30 -25
View File
@@ -1,42 +1,42 @@
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";
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 default async function CatalogEditPage({
params,
}: {
params: Promise<{ locale: string; id: string }>;
params: Promise<{ locale: string; id: string }>
}) {
const { id } = await params;
const { session, permissions } = await getAdminContext();
const { id } = await params
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect("/admin");
redirect('/admin')
}
const pageId = parseInt(id, 10);
if (Number.isNaN(pageId)) notFound();
const pageId = parseInt(id, 10)
if (Number.isNaN(pageId)) notFound()
const catalogPage = await prisma.catalogPages.findUnique({
where: { id: pageId },
});
})
if (!catalogPage) notFound();
if (!catalogPage) notFound()
const [children, itemsData, ancestors] = await Promise.all([
prisma.catalogPages.findMany({
where: { parentId: pageId },
orderBy: { orderNum: "asc" },
orderBy: { orderNum: 'asc' },
select: { id: true, caption: true, enabled: true },
}),
loadCatalogItemsData(pageId),
getAncestors(catalogPage.parentId),
]);
])
const {
items: catalogItems,
@@ -47,21 +47,24 @@ export default async function CatalogEditPage({
furniRevisionMap,
interactionTypes,
allPages,
} = itemsData;
} = itemsData
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank);
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
return (
<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">
<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">
<Link
href={`/admin/catalog/${bc.id}`}
className="hover:text-foreground transition-colors"
>
{bc.caption}
</Link>
</Fragment>
@@ -74,7 +77,9 @@ export default async function CatalogEditPage({
<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>
<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
@@ -116,5 +121,5 @@ export default async function CatalogEditPage({
interactionTypes={interactionTypes}
/>
</div>
);
)
}
@@ -1,31 +1,31 @@
import { notFound, redirect } from "next/navigation";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
import { BcPageDetail } from "../bc-manager";
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 }>;
params: Promise<{ locale: string; id: string }>
}) {
const { id: idStr } = await paramsPromise;
const id = parseInt(idStr, 10);
if (Number.isNaN(id)) notFound();
const { id: idStr } = await paramsPromise
const id = parseInt(idStr, 10)
if (Number.isNaN(id)) notFound()
const { session, permissions } = await getAdminContext();
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect("/admin");
redirect('/admin')
}
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank);
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
const bcPage = await prisma.catalogPagesBc.findUnique({ where: { id } });
if (!bcPage) notFound();
const bcPage = await prisma.catalogPagesBc.findUnique({ where: { id } })
if (!bcPage) notFound()
const bcItems = await prisma.catalogItemsBc.findMany({
where: { pageId: id },
orderBy: { orderNumber: "asc" },
});
orderBy: { orderNumber: 'asc' },
})
return (
<BcPageDetail
@@ -41,11 +41,11 @@ export default async function BcPageDetailPage({
enabled: bcPage.enabled,
pageHeadline: bcPage.pageHeadline,
pageTeaser: bcPage.pageTeaser,
pageSpecial: bcPage.pageSpecial ?? "",
pageText1: bcPage.pageText1 ?? "",
pageText2: bcPage.pageText2 ?? "",
pageTextDetails: bcPage.pageTextDetails ?? "",
pageTextTeaser: bcPage.pageTextTeaser ?? "",
pageSpecial: bcPage.pageSpecial ?? '',
pageText1: bcPage.pageText1 ?? '',
pageText2: bcPage.pageText2 ?? '',
pageTextDetails: bcPage.pageTextDetails ?? '',
pageTextTeaser: bcPage.pageTextTeaser ?? '',
}}
items={bcItems.map((i) => ({
id: i.id,
@@ -57,5 +57,5 @@ export default async function BcPageDetailPage({
}))}
canEdit={canEdit}
/>
);
)
}
+132 -105
View File
@@ -1,69 +1,82 @@
"use client";
'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";
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;
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;
id: number
pageId: number
itemIds: string
catalogName: string
orderNumber: number
extradata: string
}
interface BcPageDetailProps {
page: BcPageData;
items: BcItemData[];
canEdit: boolean;
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 { 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",
enabled: page.enabled as '0' | '1',
visible: page.visible as '0' | '1',
pageHeadline: page.pageHeadline,
pageTeaser: page.pageTeaser,
pageSpecial: page.pageSpecial,
@@ -71,31 +84,31 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
pageText2: page.pageText2,
pageTextDetails: page.pageTextDetails,
pageTextTeaser: page.pageTextTeaser,
});
})
// Ctrl+S / Cmd+S to save
useEffect(() => {
if (!canEdit) return;
if (!canEdit) return
function onKeyDown(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key === "s") {
e.preventDefault();
formRef.current?.requestSubmit();
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
formRef.current?.requestSubmit()
}
}
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [canEdit]);
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 }));
setForm((prev) => ({ ...prev, [key]: value }))
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
e.preventDefault()
run(() => updateBcPage({ id: page.id, ...form }), {
successMessage: "BC page updated and catalog synced.",
errorMessage: "Failed to update.",
});
successMessage: 'BC page updated and catalog synced.',
errorMessage: 'Failed to update.',
})
}
return (
@@ -137,7 +150,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
<Input
id="caption"
value={form.caption}
onChange={(e) => update("caption", e.target.value)}
onChange={(e) => update('caption', e.target.value)}
disabled={!canEdit}
/>
</div>
@@ -147,7 +160,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
id="orderNum"
type="number"
value={form.orderNum}
onChange={(e) => update("orderNum", parseInt(e.target.value, 10) || 0)}
onChange={(e) => update('orderNum', parseInt(e.target.value, 10) || 0)}
disabled={!canEdit}
/>
</div>
@@ -157,7 +170,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
<Label>Headline</Label>
<Input
value={form.pageHeadline}
onChange={(e) => update("pageHeadline", e.target.value)}
onChange={(e) => update('pageHeadline', e.target.value)}
disabled={!canEdit}
placeholder="Headline image path"
/>
@@ -166,7 +179,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
<Label>Teaser</Label>
<Input
value={form.pageTeaser}
onChange={(e) => update("pageTeaser", e.target.value)}
onChange={(e) => update('pageTeaser', e.target.value)}
disabled={!canEdit}
placeholder="Teaser image path"
/>
@@ -177,7 +190,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
<Label>Text 1</Label>
<Textarea
value={form.pageText1}
onChange={(e) => update("pageText1", e.target.value)}
onChange={(e) => update('pageText1', e.target.value)}
disabled={!canEdit}
rows={3}
/>
@@ -186,7 +199,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
<Label>Text 2</Label>
<Textarea
value={form.pageText2}
onChange={(e) => update("pageText2", e.target.value)}
onChange={(e) => update('pageText2', e.target.value)}
disabled={!canEdit}
rows={3}
/>
@@ -198,7 +211,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
<Label>Details</Label>
<Textarea
value={form.pageTextDetails}
onChange={(e) => update("pageTextDetails", e.target.value)}
onChange={(e) => update('pageTextDetails', e.target.value)}
disabled={!canEdit}
rows={3}
/>
@@ -207,7 +220,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
<Label>Text Teaser</Label>
<Textarea
value={form.pageTextTeaser}
onChange={(e) => update("pageTextTeaser", e.target.value)}
onChange={(e) => update('pageTextTeaser', e.target.value)}
disabled={!canEdit}
rows={3}
/>
@@ -218,7 +231,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
<Label>Special</Label>
<Textarea
value={form.pageSpecial}
onChange={(e) => update("pageSpecial", e.target.value)}
onChange={(e) => update('pageSpecial', e.target.value)}
disabled={!canEdit}
rows={2}
/>
@@ -250,7 +263,9 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
</CardHeader>
<CardContent>
{items.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">No items in this page.</p>
<p className="text-sm text-muted-foreground text-center py-4">
No items in this page.
</p>
) : (
<Table>
<TableHeader>
@@ -273,7 +288,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
</TableCell>
<TableCell className="text-xs">{item.orderNumber}</TableCell>
<TableCell className="text-xs text-muted-foreground max-w-32 truncate">
{item.extradata || "\u2014"}
{item.extradata || '\u2014'}
</TableCell>
{canEdit && (
<TableCell>
@@ -293,10 +308,10 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
size="sm"
className="h-6 w-6 p-0 text-[var(--admin-error)] hover:text-[var(--admin-error)]"
onClick={() => {
if (!confirm(`Delete item "${item.catalogName}"?`)) return;
if (!confirm(`Delete item "${item.catalogName}"?`)) return
run(() => deleteBcItem({ id: item.id }), {
successMessage: "Item deleted.",
});
successMessage: 'Item deleted.',
})
}}
>
<Trash2 className="h-3 w-3" />
@@ -325,16 +340,16 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
id="tg-enabled"
label="Enabled"
description="Active in the BC catalog"
checked={form.enabled === "1"}
onChange={(v) => update("enabled", v ? "1" : "0")}
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")}
checked={form.visible === '1'}
onChange={(v) => update('visible', v ? '1' : '0')}
disabled={!canEdit}
/>
</div>
@@ -345,8 +360,10 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
Layout: <span className="font-mono">{page.pageLayout}</span>
</span>
<span>
Parent:{" "}
<span className="font-mono">{page.parentId <= 0 ? "Root" : `#${page.parentId}`}</span>
Parent:{' '}
<span className="font-mono">
{page.parentId <= 0 ? 'Root' : `#${page.parentId}`}
</span>
</span>
</div>
@@ -381,9 +398,9 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
onClose={() => setEditingItem(null)}
onSubmit={(data) => {
run(() => updateBcItem({ id: editingItem.id, ...data }), {
successMessage: "Item updated.",
successMessage: 'Item updated.',
onSuccess: () => setEditingItem(null),
});
})
}}
/>
)}
@@ -394,24 +411,24 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
item={{
id: 0,
pageId: page.id,
itemIds: "",
catalogName: "",
itemIds: '',
catalogName: '',
orderNumber: 1,
extradata: "",
extradata: '',
}}
mode="add"
isPending={isPending}
onClose={() => setAddingItem(false)}
onSubmit={(data) => {
run(() => createBcItem({ pageId: page.id, ...data }), {
successMessage: "Item created.",
successMessage: 'Item created.',
onSuccess: () => setAddingItem(false),
});
})
}}
/>
)}
</div>
);
)
}
// ── Toggle row ───────────────────────────────────────────────────────
@@ -424,12 +441,12 @@ function ToggleRow({
onChange,
disabled,
}: {
id: string;
label: string;
description: string;
checked: boolean;
onChange: (v: boolean) => void;
disabled?: boolean;
id: string
label: string
description: string
checked: boolean
onChange: (v: boolean) => void
disabled?: boolean
}) {
return (
<div className="flex items-start justify-between gap-3">
@@ -441,7 +458,7 @@ function ToggleRow({
</div>
<Switch id={id} checked={checked} onCheckedChange={onChange} disabled={disabled} />
</div>
);
)
}
// ── Item Dialog ──────────────────────────────────────────────────────
@@ -453,24 +470,29 @@ function ItemDialog({
onClose,
onSubmit,
}: {
item: BcItemData;
mode: "add" | "edit";
isPending: boolean;
onClose: () => void;
onSubmit: (data: { itemIds: string; catalogName: string; orderNumber: number; extradata: string }) => void;
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>
<DialogTitle>{mode === 'add' ? 'Add BC Item' : `Edit Item #${item.id}`}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
@@ -493,7 +515,9 @@ function ItemDialog({
<Input
type="number"
value={form.orderNumber}
onChange={(e) => setForm((f) => ({ ...f, orderNumber: parseInt(e.target.value, 10) || 0 }))}
onChange={(e) =>
setForm((f) => ({ ...f, orderNumber: parseInt(e.target.value, 10) || 0 }))
}
/>
</div>
<div className="space-y-2">
@@ -510,12 +534,15 @@ function ItemDialog({
<Button variant="outline" onClick={onClose} disabled={isPending}>
Cancel
</Button>
<Button onClick={() => onSubmit(form)} disabled={isPending || !form.catalogName || !form.itemIds}>
<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"}
{mode === 'add' ? 'Add Item' : 'Save'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
)
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { redirect } from "next/navigation";
import { redirect } from 'next/navigation'
export default function BuilderClubPage() {
redirect("/admin/catalog?catalog=bc");
redirect('/admin/catalog?catalog=bc')
}
+44 -32
View File
@@ -1,57 +1,69 @@
"use client";
'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";
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";
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";
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;
toast.error('Caption is required')
return
}
const input = {
caption: caption.trim(),
parentId: parseInt(parentId, 10),
pageLayout,
};
}
const fn = isBc ? () => createBcPage(input) : () => createCatalogPage(input);
const fn = isBc ? () => createBcPage(input) : () => createCatalogPage(input)
run(fn, {
successMessage: `Catalog page "${caption.trim()}" created.`,
onSuccess: (data) => {
setOpen(false);
setCaption("");
setParentId("-1");
setOpen(false)
setCaption('')
setParentId('-1')
if (data.id) {
window.location.href = isBc
? `/admin/catalog/builder-club/${data.id}`
: `/admin/catalog/${data.id}`;
: `/admin/catalog/${data.id}`
}
},
});
})
}
return (
@@ -64,7 +76,7 @@ export function CatalogActions({ catalogType = "normal" }: CatalogActionsProps)
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{isBc ? "Create Builder Club Page" : "Create Catalog Page"}</DialogTitle>
<DialogTitle>{isBc ? 'Create Builder Club Page' : 'Create Catalog Page'}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
@@ -112,5 +124,5 @@ export function CatalogActions({ catalogType = "normal" }: CatalogActionsProps)
</div>
</DialogContent>
</Dialog>
);
)
}
+77 -66
View File
@@ -1,56 +1,57 @@
"use client";
'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";
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;
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";
data: PaginatedResult<CatalogPageRow>
canEdit: boolean
catalogType?: 'normal' | 'bc'
}
export function CatalogTable({ data, canEdit, catalogType = "normal" }: CatalogTableProps) {
const { run, isPending } = useServerAction();
const isBc = catalogType === "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}`);
const detailHref = (id: number) =>
isBc ? `/admin/catalog/builder-club/${id}` : `/admin/catalog/${id}`
function handleToggle(id: number, action: "toggleEnabled" | "toggleVisible") {
function handleToggle(id: number, action: 'toggleEnabled' | 'toggleVisible') {
if (isBc) {
const field = action === "toggleEnabled" ? "enabled" : "visible";
run(() => toggleBcPage({ id, field }), { successMessage: "Updated." });
const field = action === 'toggleEnabled' ? 'enabled' : 'visible'
run(() => toggleBcPage({ id, field }), { successMessage: 'Updated.' })
} else {
run(() => toggleCatalogPage({ id, action }), { successMessage: "Updated." });
run(() => toggleCatalogPage({ id, action }), { successMessage: 'Updated.' })
}
}
const columns: DataTableColumn<CatalogPageRow>[] = [
{ key: "id", label: "ID", sortable: true },
{ key: 'id', label: 'ID', sortable: true },
{
key: "caption",
label: "Caption",
key: 'caption',
label: 'Caption',
sortable: true,
render: (value, row) => (
<Link href={detailHref(row.id)} className="font-medium text-primary hover:underline">
@@ -59,8 +60,8 @@ export function CatalogTable({ data, canEdit, catalogType = "normal" }: CatalogT
),
},
{
key: "parentId",
label: "Parent",
key: 'parentId',
label: 'Parent',
sortable: true,
render: (_, row) =>
row.parentId === -1 ? (
@@ -72,78 +73,86 @@ export function CatalogTable({ data, canEdit, catalogType = "normal" }: CatalogT
),
},
{
key: "pageLayout",
label: "Layout",
key: 'pageLayout',
label: 'Layout',
render: (value) => <Badge variant="secondary">{String(value)}</Badge>,
},
{
key: "enabled",
label: "Enabled",
key: 'enabled',
label: 'Enabled',
sortable: true,
filterKey: "filter_enabled",
filterKey: 'filter_enabled',
filterOptions: [
{ label: "Enabled", value: "1" },
{ label: "Disabled", value: "0" },
{ label: 'Enabled', value: '1' },
{ label: 'Disabled', value: '0' },
],
render: (value, row) =>
canEdit ? (
<button
type="button"
onClick={() => handleToggle(row.id, "toggleEnabled")}
onClick={() => handleToggle(row.id, 'toggleEnabled')}
disabled={isPending}
className="cursor-pointer disabled:opacity-50"
>
<Badge variant={value === "1" ? "default" : "outline"}>{value === "1" ? "Yes" : "No"}</Badge>
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
</button>
) : (
<Badge variant={value === "1" ? "default" : "outline"}>{value === "1" ? "Yes" : "No"}</Badge>
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
),
},
{
key: "visible",
label: "Visible",
key: 'visible',
label: 'Visible',
sortable: true,
filterKey: "filter_visible",
filterKey: 'filter_visible',
filterOptions: [
{ label: "Visible", value: "1" },
{ label: "Hidden", value: "0" },
{ label: 'Visible', value: '1' },
{ label: 'Hidden', value: '0' },
],
render: (value, row) =>
canEdit ? (
<button
type="button"
onClick={() => handleToggle(row.id, "toggleVisible")}
onClick={() => handleToggle(row.id, 'toggleVisible')}
disabled={isPending}
className="cursor-pointer disabled:opacity-50"
>
<Badge variant={value === "1" ? "default" : "outline"}>{value === "1" ? "Yes" : "No"}</Badge>
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
</button>
) : (
<Badge variant={value === "1" ? "default" : "outline"}>{value === "1" ? "Yes" : "No"}</Badge>
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
),
},
...(isBc
? []
: [
{
key: "minRank" as const,
label: "Min Rank",
key: 'minRank' as const,
label: 'Min Rank',
sortable: true,
} satisfies DataTableColumn<CatalogPageRow>,
]),
{
key: "itemCount",
label: "Items",
key: 'itemCount',
label: 'Items',
render: (value) => <span>{String(value)}</span>,
},
{
key: "childCount",
label: "Children",
key: 'childCount',
label: 'Children',
render: (value) => <span>{String(value)}</span>,
},
{
key: "actions",
label: "Actions",
key: 'actions',
label: 'Actions',
render: (_, row) => (
<Button variant="ghost" size="icon" asChild>
<Link href={detailHref(row.id)}>
@@ -152,7 +161,7 @@ export function CatalogTable({ data, canEdit, catalogType = "normal" }: CatalogT
</Button>
),
},
];
]
return (
<DataTable
@@ -160,8 +169,10 @@ export function CatalogTable({ data, canEdit, catalogType = "normal" }: CatalogT
columns={columns}
searchPlaceholder="Search by caption, layout or item..."
bulkActions={
canEdit ? [{ label: "Delete Selected", value: "delete", variant: "destructive" }] : undefined
canEdit
? [{ label: 'Delete Selected', value: 'delete', variant: 'destructive' }]
: undefined
}
/>
);
)
}
+30 -30
View File
@@ -1,38 +1,38 @@
"use client";
'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";
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;
currentView: string
catalogType?: string
}
export function CatalogViewToggle({ currentView, catalogType = "normal" }: CatalogViewToggleProps) {
const router = useRouter();
const searchParams = useSearchParams();
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");
const params = new URLSearchParams(searchParams.toString())
if (view === 'tree') {
params.delete('view')
} else {
params.set("view", view);
params.set('view', view)
}
router.push(`?${params.toString()}`);
router.push(`?${params.toString()}`)
}
function setCatalog(type: string) {
const params = new URLSearchParams(searchParams.toString());
if (type === "normal") {
params.delete("catalog");
const params = new URLSearchParams(searchParams.toString())
if (type === 'normal') {
params.delete('catalog')
} else {
params.set("catalog", type);
params.set('catalog', type)
}
params.delete("view"); // reset to tree when switching
router.push(`?${params.toString()}`);
params.delete('view') // reset to tree when switching
router.push(`?${params.toString()}`)
}
return (
@@ -42,8 +42,8 @@ export function CatalogViewToggle({ currentView, catalogType = "normal" }: Catal
<Button
variant="ghost"
size="sm"
className={cn("h-8 rounded-r-none", catalogType === "normal" && "bg-accent")}
onClick={() => setCatalog("normal")}
className={cn('h-8 rounded-r-none', catalogType === 'normal' && 'bg-accent')}
onClick={() => setCatalog('normal')}
>
<Package className="mr-1.5 h-4 w-4" />
Catalog
@@ -51,8 +51,8 @@ export function CatalogViewToggle({ currentView, catalogType = "normal" }: Catal
<Button
variant="ghost"
size="sm"
className={cn("h-8 rounded-l-none", catalogType === "bc" && "bg-accent")}
onClick={() => setCatalog("bc")}
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
@@ -64,8 +64,8 @@ export function CatalogViewToggle({ currentView, catalogType = "normal" }: Catal
<Button
variant="ghost"
size="sm"
className={cn("h-8 rounded-r-none", currentView === "tree" && "bg-accent")}
onClick={() => setView("tree")}
className={cn('h-8 rounded-r-none', currentView === 'tree' && 'bg-accent')}
onClick={() => setView('tree')}
>
<FolderTree className="mr-1.5 h-4 w-4" />
Tree
@@ -73,13 +73,13 @@ export function CatalogViewToggle({ currentView, catalogType = "normal" }: Catal
<Button
variant="ghost"
size="sm"
className={cn("h-8 rounded-l-none", currentView === "table" && "bg-accent")}
onClick={() => setView("table")}
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>
);
)
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { Skeleton } from "@/components/ui/skeleton";
import { Skeleton } from '@/components/ui/skeleton'
export default function CatalogLoading() {
return (
@@ -40,5 +40,5 @@ export default function CatalogLoading() {
</div>
</div>
</div>
);
)
}
+146 -141
View File
@@ -1,87 +1,87 @@
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";
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'
const CatalogManagerDialog = dynamic(() =>
import("@/components/admin/catalog-manager/catalog-manager-dialog").then((m) => ({
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>>;
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
await paramsPromise;
const { session, permissions } = await getAdminContext();
await paramsPromise
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect("/admin");
redirect('/admin')
}
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank);
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
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";
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;
};
id: number
caption: string
parentId: number
enabled: string
visible: string
iconImage: number
iconColor: number
pageLayout: string
childCount: number
itemCount: number
}
if (catalogType === "bc") {
if (catalogType === 'bc') {
const [totalBcPages, totalBcItems, enabledBcPages] = await Promise.all([
prisma.catalogPagesBc.count(),
prisma.catalogItemsBc.count(),
prisma.catalogPagesBc.count({ where: { enabled: "1" } }),
]);
prisma.catalogPagesBc.count({ where: { enabled: '1' } }),
])
// ── BC tree view ──────────────────────────────────────────────
let bcRootPages: TreeNodeShape[] = [];
if (viewMode === "tree") {
let bcRootPages: TreeNodeShape[] = []
if (viewMode === 'tree') {
const bcRootRaw = await prisma.catalogPagesBc.findMany({
where: { OR: [{ parentId: -1 }, { parentId: 0 }] },
orderBy: { orderNum: "asc" },
});
const bcRootIds = bcRootRaw.map((p) => p.id);
orderBy: { orderNum: 'asc' },
})
const bcRootIds = bcRootRaw.map((p) => p.id)
const [bcChildCounts, bcItemCounts] = await Promise.all([
bcRootIds.length > 0
? prisma.catalogPagesBc.groupBy({
by: ["parentId"],
by: ['parentId'],
where: { parentId: { in: bcRootIds } },
_count: true,
})
: [],
bcRootIds.length > 0
? prisma.catalogItemsBc.groupBy({
by: ["pageId"],
by: ['pageId'],
where: { pageId: { in: bcRootIds } },
_count: true,
})
: [],
]);
const bcChildMap = Object.fromEntries(bcChildCounts.map((c) => [c.parentId, c._count]));
const bcItemMap = Object.fromEntries(bcItemCounts.map((c) => [c.pageId, c._count]));
])
const bcChildMap = Object.fromEntries(bcChildCounts.map((c) => [c.parentId, c._count]))
const bcItemMap = Object.fromEntries(bcItemCounts.map((c) => [c.pageId, c._count]))
bcRootPages = bcRootRaw.map((p) => ({
id: p.id,
caption: p.caption,
@@ -93,45 +93,45 @@ export default async function CatalogPagesPage({
pageLayout: p.pageLayout,
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 };
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;
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);
const where: Record<string, unknown> = {}
const hasParent = parentId !== undefined && !Number.isNaN(parentId)
if (search) {
const pattern = { contains: search };
where.OR = [{ caption: pattern }];
const pattern = { contains: search }
where.OR = [{ caption: pattern }]
}
if (hasParent) where.parentId = parentId;
if (hasParent) where.parentId = parentId
// Prisma sort key is snake_case for BC model. Translate known keys.
const sortKeyMap: Record<string, string> = {
parentId: "parentId",
pageLayout: "pageLayout",
orderNum: "orderNum",
};
const sortKey = sort ? (sortKeyMap[sort] ?? sort) : "orderNum";
const orderBy = { [sortKey]: sort ? order : "asc" };
parentId: 'parentId',
pageLayout: 'pageLayout',
orderNum: 'orderNum',
}
const sortKey = sort ? (sortKeyMap[sort] ?? sort) : 'orderNum'
const orderBy = { [sortKey]: sort ? order : 'asc' }
const [pages, total] = await Promise.all([
prisma.catalogPagesBc.findMany({
@@ -141,23 +141,23 @@ export default async function CatalogPagesPage({
take: perPage,
}),
prisma.catalogPagesBc.count({ where }),
]);
])
bcPagination = calcPagination(total, page, perPage);
bcPagination = calcPagination(total, page, perPage)
const pageIds = pages.map((p) => p.id);
const parentIds = [...new Set(pages.map((p) => p.parentId).filter((id) => id > 0))];
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.catalogPagesBc.groupBy({
by: ["parentId"],
by: ['parentId'],
where: { parentId: { in: pageIds } },
_count: true,
})
: [],
pageIds.length > 0
? prisma.catalogItemsBc.groupBy({
by: ["pageId"],
by: ['pageId'],
where: { pageId: { in: pageIds } },
_count: true,
})
@@ -168,16 +168,17 @@ export default async function CatalogPagesPage({
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]));
])
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]))
bcRows = pages.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parentId,
parentCaption: p.parentId === -1 ? "Root" : (parentNameMap[p.parentId] ?? `#${p.parentId}`),
parentCaption:
p.parentId === -1 ? 'Root' : (parentNameMap[p.parentId] ?? `#${p.parentId}`),
pageLayout: String(p.pageLayout),
enabled: String(p.enabled),
visible: String(p.visible),
@@ -185,7 +186,7 @@ export default async function CatalogPagesPage({
orderNum: p.orderNum,
itemCount: itemCountMap[p.id] ?? 0,
childCount: childCountMap[p.id] ?? 0,
}));
}))
}
return (
@@ -202,13 +203,17 @@ export default async function CatalogPagesPage({
{canEdit && <CatalogActions catalogType="bc" />}
</div>
</div>
{viewMode === "tree" ? (
{viewMode === 'tree' ? (
<CatalogTree rootPages={bcRootPages} catalogType="bc" />
) : (
<CatalogTable data={{ rows: bcRows, ...bcPagination }} canEdit={canEdit} catalogType="bc" />
<CatalogTable
data={{ rows: bcRows, ...bcPagination }}
canEdit={canEdit}
catalogType="bc"
/>
)}
</div>
);
)
}
// ── Normal catalog mode ────────────────────────────────────────
@@ -217,35 +222,35 @@ export default async function CatalogPagesPage({
const [totalPages, totalItems, enabledPages] = await Promise.all([
prisma.catalogPages.count(),
prisma.catalogItems.count(),
prisma.catalogPages.count({ where: { enabled: "1" } }),
]);
prisma.catalogPages.count({ where: { enabled: '1' } }),
])
// ── Tree view data ──────────────────────────────────────────────
let rootPages: TreeNodeShape[] = [];
if (viewMode === "tree") {
let rootPages: TreeNodeShape[] = []
if (viewMode === 'tree') {
const rootPagesRaw = await prisma.catalogPages.findMany({
where: { parentId: -1 },
orderBy: { orderNum: "asc" },
});
const rootIds = rootPagesRaw.map((p) => p.id);
orderBy: { orderNum: 'asc' },
})
const rootIds = rootPagesRaw.map((p) => p.id)
const [rootChildCounts, rootItemCounts] = await Promise.all([
rootIds.length > 0
? prisma.catalogPages.groupBy({
by: ["parentId"],
by: ['parentId'],
where: { parentId: { in: rootIds } },
_count: true,
})
: [],
rootIds.length > 0
? prisma.catalogItems.groupBy({
by: ["pageId"],
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]));
])
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,
@@ -257,34 +262,34 @@ export default async function CatalogPagesPage({
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 };
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;
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);
const where: Record<string, unknown> = {}
const hasParent = parentId !== undefined && !Number.isNaN(parentId)
if (search) {
const searchPattern = `%${search}%`;
const parentClause = hasParent ? Prisma.sql`AND cp.parentId = ${parentId}` : Prisma.empty;
const searchPattern = `%${search}%`
const parentClause = hasParent ? Prisma.sql`AND cp.parentId = ${parentId}` : Prisma.empty
const matchedIds = await prisma.$queryRaw<{ id: number }[]>(Prisma.sql`
SELECT DISTINCT cp.id FROM catalog_pages cp
@@ -296,13 +301,13 @@ export default async function CatalogPagesPage({
OR ib.public_name LIKE ${searchPattern}
OR ib.item_name LIKE ${searchPattern})
${parentClause}
`);
where.id = { in: matchedIds.map((r) => r.id) };
`)
where.id = { in: matchedIds.map((r) => r.id) }
} else if (hasParent) {
where.parentId = parentId;
where.parentId = parentId
}
const orderBy = sort ? { [sort]: order } : { orderNum: "asc" as const };
const orderBy = sort ? { [sort]: order } : { orderNum: 'asc' as const }
const [pages, total] = await Promise.all([
prisma.catalogPages.findMany({
@@ -312,24 +317,24 @@ export default async function CatalogPagesPage({
take: perPage,
}),
prisma.catalogPages.count({ where }),
]);
])
pagination = calcPagination(total, page, perPage);
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 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.catalogPages.groupBy({
by: ["parentId"],
by: ['parentId'],
where: { parentId: { in: pageIds } },
_count: true,
})
: [],
pageIds.length > 0
? prisma.catalogItems.groupBy({
by: ["pageId"],
by: ['pageId'],
where: { pageId: { in: pageIds } },
_count: true,
})
@@ -340,16 +345,16 @@ export default async function CatalogPagesPage({
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]));
])
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}`),
parentCaption: p.parentId === -1 ? 'Root' : (parentNameMap[p.parentId] ?? `#${p.parentId}`),
pageLayout: p.pageLayout,
enabled: p.enabled,
visible: p.visible,
@@ -357,7 +362,7 @@ export default async function CatalogPagesPage({
orderNum: p.orderNum,
itemCount: itemCountMap[p.id] ?? 0,
childCount: childCountMap[p.id] ?? 0,
}));
}))
}
return (
@@ -376,11 +381,11 @@ export default async function CatalogPagesPage({
</div>
</div>
{viewMode === "tree" ? (
{viewMode === 'tree' ? (
<CatalogTree rootPages={rootPages} catalogType="normal" />
) : (
<CatalogTable data={{ rows, ...pagination }} canEdit={canEdit} />
)}
</div>
);
)
}