Harden catalog admin: fix translate/quick-add, RCON sync, and confirm UX.
Local Build and Deploy / deploy (push) Successful in 1m18s

Restore broken Quick Add search, correct Translate saves to items_base and FurnitureData, reparent page deletes, sync RCON on create/toggle/BC mutations, and replace native confirms/prompts with dialogs.

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
SimoandCursor committed 2026-07-17 21:12:58 +02:00
1 parent de9f837da1
commit b52e25578d
20 files changed
+557 -216

No files matched your search

+10 -1
View File
@@ -28,6 +28,7 @@ export async function updateBcPage({
export async function deleteBcItem({ id }: { id: number }) { export async function deleteBcItem({ id }: { id: number }) {
const staff = await requirePermission(PERMS.CATALOG_EDIT); const staff = await requirePermission(PERMS.CATALOG_EDIT);
await prisma.catalogItemsBc.delete({ where: { id } }); await prisma.catalogItemsBc.delete({ where: { id } });
await rcon.updateCatalog();
await logStaffActivity({ await logStaffActivity({
staffId: staff.id, staffId: staff.id,
action: "bc_item_delete", action: "bc_item_delete",
@@ -36,6 +37,7 @@ export async function deleteBcItem({ id }: { id: number }) {
targetId: id, targetId: id,
}); });
revalidatePath("/admin/catalog/builder-club"); revalidatePath("/admin/catalog/builder-club");
return { ok: true as const };
} }
export async function updateBcItem({ export async function updateBcItem({
@@ -50,6 +52,7 @@ export async function updateBcItem({
}) { }) {
const staff = await requirePermission(PERMS.CATALOG_EDIT); const staff = await requirePermission(PERMS.CATALOG_EDIT);
await prisma.catalogItemsBc.update({ where: { id }, data: data as any }); await prisma.catalogItemsBc.update({ where: { id }, data: data as any });
await rcon.updateCatalog();
await logStaffActivity({ await logStaffActivity({
staffId: staff.id, staffId: staff.id,
action: "bc_item_update", action: "bc_item_update",
@@ -58,6 +61,7 @@ export async function updateBcItem({
targetId: id, targetId: id,
}); });
revalidatePath("/admin/catalog/builder-club"); revalidatePath("/admin/catalog/builder-club");
return { ok: true as const };
} }
export async function createBcItem({ export async function createBcItem({
@@ -74,6 +78,7 @@ export async function createBcItem({
const created = await prisma.catalogItemsBc.create({ const created = await prisma.catalogItemsBc.create({
data: { pageId, ...data }, data: { pageId, ...data },
}); });
await rcon.updateCatalog();
await logStaffActivity({ await logStaffActivity({
staffId: staff.id, staffId: staff.id,
action: "bc_item_create", action: "bc_item_create",
@@ -82,6 +87,7 @@ export async function createBcItem({
targetId: created.id, targetId: created.id,
}); });
revalidatePath("/admin/catalog/builder-club"); revalidatePath("/admin/catalog/builder-club");
return { ok: true as const, data: { id: created.id } };
} }
export async function toggleBcPage({ export async function toggleBcPage({
@@ -96,12 +102,14 @@ export async function toggleBcPage({
where: { id }, where: { id },
select: { enabled: true, visible: true }, select: { enabled: true, visible: true },
}); });
if (!page) return; if (!page) return { ok: false as const, error: "Page not found" };
await prisma.catalogPagesBc.update({ await prisma.catalogPagesBc.update({
where: { id }, where: { id },
data: { [field]: page[field] === "1" ? "0" : "1" }, data: { [field]: page[field] === "1" ? "0" : "1" },
}); });
await rcon.updateCatalog();
revalidatePath("/admin/catalog/builder-club"); revalidatePath("/admin/catalog/builder-club");
return { ok: true as const };
} }
export async function createBcPage(input: { export async function createBcPage(input: {
@@ -124,6 +132,7 @@ export async function createBcPage(input: {
pageTeaser: "", pageTeaser: "",
}, },
}); });
await rcon.updateCatalog();
await logStaffActivity({ await logStaffActivity({
staffId: staff.id, staffId: staff.id,
action: "bc_page_create", action: "bc_page_create",
+71 -23
View File
@@ -118,45 +118,93 @@ export async function updateCatalogItem({
export async function translateCatalogItems({ export async function translateCatalogItems({
items, items,
}: { }: {
/** `id` is items_base.id (not catalog_items.id) */
items: Array<{ id: number; publicName: string; description: string }>; items: Array<{ id: number; publicName: string; description: string }>;
}) { }) {
await requirePermission(PERMS.CATALOG_EDIT); await requirePermission(PERMS.CATALOG_EDIT);
const { invalidateFurniDataCache } = await import(
"@/lib/services/catalog-items-loader"
);
const { patchFurniEntryNames } = await import("@/lib/services/furni-data");
let namesUpdated = 0; let namesUpdated = 0;
let descriptionsUpdated = 0; let descriptionsUpdated = 0;
let furniDataUpdated = 0; const furniPatches: Array<{
const _furniDataInserted = 0; classname: string;
itemType: string;
name?: string;
description?: string;
spriteId?: number;
createIfMissing?: boolean;
}> = [];
for (const item of items) { for (const item of items) {
const existing = await prisma.catalogItems.findUnique({ const base = await prisma.itemsBase.findUnique({
where: { id: item.id }, where: { id: item.id },
select: { catalogName: true }, select: {
id: true,
publicName: true,
itemName: true,
type: true,
spriteId: true,
},
}); });
if (!existing) continue; if (!base) continue;
if (item.publicName && item.publicName !== existing.catalogName) { const nextName = item.publicName?.trim() ?? "";
await prisma.catalogItems.update({ const nextDesc = item.description ?? "";
where: { id: item.id }, const nameChanged = nextName !== "" && nextName !== (base.publicName ?? "");
data: { catalogName: item.publicName },
if (nameChanged) {
await prisma.itemsBase.update({
where: { id: base.id },
data: { publicName: nextName },
}); });
// Sync catalogName for catalog rows that reference this base item
const idStr = String(base.id);
const related = await prisma.catalogItems.findMany({
where: {
OR: [
{ itemIds: idStr },
{ itemIds: { startsWith: `${idStr};` } },
{ itemIds: { contains: `;${idStr};` } },
{ itemIds: { endsWith: `;${idStr}` } },
],
},
select: { id: true, catalogName: true },
});
for (const row of related) {
if (row.catalogName !== nextName) {
await prisma.catalogItems.update({
where: { id: row.id },
data: { catalogName: nextName },
});
}
}
namesUpdated++; namesUpdated++;
} }
if (item.description) { if (nextDesc !== "" || nameChanged) {
const baseItem = await prisma.itemsBase.findFirst({ descriptionsUpdated += nextDesc !== "" ? 1 : 0;
where: { itemName: existing.catalogName }, furniPatches.push({
select: { id: true, publicName: true }, classname: base.itemName,
itemType: base.type || "s",
name: nextName || base.publicName || base.itemName,
description: nextDesc,
spriteId: base.spriteId,
createIfMissing: true,
}); });
if (baseItem) {
await prisma.itemsBase.update({
where: { id: baseItem.id },
data: { publicName: item.publicName || baseItem.publicName },
});
furniDataUpdated++;
}
descriptionsUpdated++;
} }
} }
const furniResult =
furniPatches.length > 0
? await patchFurniEntryNames(furniPatches)
: { updated: 0, inserted: 0 };
if (furniResult.updated > 0 || furniResult.inserted > 0) {
invalidateFurniDataCache();
}
await rcon.updateCatalog(); await rcon.updateCatalog();
revalidatePath("/admin/catalog"); revalidatePath("/admin/catalog");
return { return {
@@ -164,8 +212,8 @@ export async function translateCatalogItems({
data: { data: {
namesUpdated, namesUpdated,
descriptionsUpdated, descriptionsUpdated,
furniDataUpdated, furniDataUpdated: furniResult.updated,
furniDataInserted: 0, furniDataInserted: furniResult.inserted,
updated: items.length, updated: items.length,
}, },
}; };
+16 -32
View File
@@ -5,6 +5,7 @@ import { requirePermission } from "@/lib/admin/guard";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma"; import { prisma } from "@/lib/prisma";
import type { ActionResult } from "@/lib/safe-action-shared"; import type { ActionResult } from "@/lib/safe-action-shared";
import { deletePage, movePage } from "@/lib/services/catalog-tree";
import { rcon } from "@/lib/services/rcon"; import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity"; import { logStaffActivity } from "@/lib/services/staff-activity";
@@ -28,7 +29,7 @@ export async function updateCatalogPage({
export async function deleteCatalogPage({ id }: { id: number }) { export async function deleteCatalogPage({ id }: { id: number }) {
const staff = await requirePermission(PERMS.CATALOG_EDIT); const staff = await requirePermission(PERMS.CATALOG_EDIT);
await prisma.catalogPages.delete({ where: { id } }); await deletePage(id, "reparent");
await rcon.updateCatalog(); await rcon.updateCatalog();
await logStaffActivity({ await logStaffActivity({
staffId: staff.id, staffId: staff.id,
@@ -60,6 +61,7 @@ export async function toggleCatalogPage({
where: { id }, where: { id },
data: { [field]: current === "1" ? "0" : "1" }, data: { [field]: current === "1" ? "0" : "1" },
}); });
await rcon.updateCatalog();
revalidatePath("/admin/catalog"); revalidatePath("/admin/catalog");
return { ok: true as const, data: {} }; return { ok: true as const, data: {} };
} }
@@ -95,6 +97,7 @@ export async function createCatalogPage(input: {
includes: "", includes: "",
}, },
}); });
await rcon.updateCatalog();
await logStaffActivity({ await logStaffActivity({
staffId: staff.id, staffId: staff.id,
action: "catalog_page_create", action: "catalog_page_create",
@@ -112,14 +115,19 @@ export async function reorderTreePage(input: {
newOrderNum: number; newOrderNum: number;
}) { }) {
await requirePermission(PERMS.CATALOG_EDIT); await requirePermission(PERMS.CATALOG_EDIT);
if (input.newParentId !== undefined) {
try {
await movePage(input.pageId, input.newParentId);
} catch (err) {
return {
ok: false as const,
error: err instanceof Error ? err.message : "Invalid move",
};
}
}
await prisma.catalogPages.update({ await prisma.catalogPages.update({
where: { id: input.pageId }, where: { id: input.pageId },
data: { data: { orderNum: input.newOrderNum },
orderNum: input.newOrderNum,
...(input.newParentId === undefined
? {}
: { parentId: input.newParentId }),
},
}); });
await rcon.updateCatalog(); await rcon.updateCatalog();
revalidatePath("/admin/catalog"); revalidatePath("/admin/catalog");
@@ -131,31 +139,7 @@ export async function deleteTreePage(input: {
mode: "reparent" | "cascade"; mode: "reparent" | "cascade";
}) { }) {
await requirePermission(PERMS.CATALOG_EDIT); await requirePermission(PERMS.CATALOG_EDIT);
if (input.mode === "cascade") { await deletePage(input.pageId, input.mode);
const children = await prisma.catalogPages.findMany({
where: { parentId: input.pageId },
select: { id: true },
});
const pageIds = [input.pageId, ...children.map((child) => child.id)];
await prisma.$transaction([
prisma.catalogItems.deleteMany({ where: { pageId: { in: pageIds } } }),
prisma.catalogPages.deleteMany({ where: { id: { in: pageIds } } }),
]);
} else {
const page = await prisma.catalogPages.findUnique({
where: { id: input.pageId },
select: { parentId: true },
});
if (!page) return { ok: false as const, error: "Catalog page not found" };
await prisma.$transaction([
prisma.catalogPages.updateMany({
where: { parentId: input.pageId },
data: { parentId: page.parentId },
}),
prisma.catalogItems.deleteMany({ where: { pageId: input.pageId } }),
prisma.catalogPages.delete({ where: { id: input.pageId } }),
]);
}
await rcon.updateCatalog(); await rcon.updateCatalog();
revalidatePath("/admin/catalog"); revalidatePath("/admin/catalog");
return { ok: true as const, data: {} }; return { ok: true as const, data: {} };
@@ -47,6 +47,7 @@ import {
import { BulkImportItems } from "@/components/admin/catalog/bulk-import-items"; import { BulkImportItems } from "@/components/admin/catalog/bulk-import-items";
import { ItemsShopPreview } from "@/components/admin/catalog/items-shop-preview"; import { ItemsShopPreview } from "@/components/admin/catalog/items-shop-preview";
import { QuickAddFurni } from "@/components/admin/catalog/quick-add-furni"; import { QuickAddFurni } from "@/components/admin/catalog/quick-add-furni";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { import {
CurrencyIcon, CurrencyIcon,
currencyKindFromPointsType, currencyKindFromPointsType,
@@ -60,7 +61,6 @@ import {
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
@@ -158,6 +158,7 @@ export function CatalogItemsTable({
}: CatalogItemsTableProps) { }: CatalogItemsTableProps) {
const router = useRouter(); const router = useRouter();
const { run, isPending } = useServerAction(); const { run, isPending } = useServerAction();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [addOpen, setAddOpen] = useState(false); const [addOpen, setAddOpen] = useState(false);
const [editingItem, setEditingItem] = useState<CatalogItemData | null>(null); const [editingItem, setEditingItem] = useState<CatalogItemData | null>(null);
const [editingBase, setEditingBase] = useState<BaseItemData | null>(null); const [editingBase, setEditingBase] = useState<BaseItemData | null>(null);
@@ -378,6 +379,7 @@ export function CatalogItemsTable({
setSavingItemId(null); setSavingItemId(null);
router.refresh(); router.refresh();
}, },
onError: () => setSavingItemId(null),
}, },
); );
} }
@@ -436,7 +438,12 @@ export function CatalogItemsTable({
// ── Bulk delete selected ───────────────────────────────────────── // ── Bulk delete selected ─────────────────────────────────────────
async function handleBulkDelete() { async function handleBulkDelete() {
if (selected.size === 0) return; if (selected.size === 0) return;
if (!confirm(`Delete ${selected.size} selected item(s)?`)) return; const ok = await confirm({
title: "Delete items",
description: `Delete ${selected.size} selected item(s)?`,
confirmLabel: "Delete",
});
if (!ok) return;
run(() => deleteCatalogItems({ ids: [...selected] }), { run(() => deleteCatalogItems({ ids: [...selected] }), {
successMessage: `Deleted ${selected.size} item(s).`, successMessage: `Deleted ${selected.size} item(s).`,
@@ -584,7 +591,12 @@ export function CatalogItemsTable({
} }
async function handleDeleteItem(id: number) { async function handleDeleteItem(id: number) {
if (!confirm("Delete this catalog item?")) return; const ok = await confirm({
title: "Delete item",
description: "Delete this catalog item?",
confirmLabel: "Delete",
});
if (!ok) return;
run(() => deleteCatalogItems({ ids: [id] }), { run(() => deleteCatalogItems({ ids: [id] }), {
successMessage: "Item deleted.", successMessage: "Item deleted.",
errorMessage: "Failed to delete item.", errorMessage: "Failed to delete item.",
@@ -867,6 +879,8 @@ export function CatalogItemsTable({
} }
return ( return (
<>
{confirmDialog}
<Card> <Card>
<CardHeader className="space-y-3"> <CardHeader className="space-y-3">
<div className="flex flex-row items-center justify-between gap-4"> <div className="flex flex-row items-center justify-between gap-4">
@@ -1009,12 +1023,10 @@ export function CatalogItemsTable({
onImported={() => router.refresh()} onImported={() => router.refresh()}
/> />
<Dialog open={addOpen} onOpenChange={setAddOpen}> <Dialog open={addOpen} onOpenChange={setAddOpen}>
<DialogTrigger asChild> <Button size="sm" onClick={() => setAddOpen(true)}>
<Button size="sm"> <Plus className="mr-2 h-4 w-4" />
<Plus className="mr-2 h-4 w-4" /> Add Item
Add Item </Button>
</Button>
</DialogTrigger>
<DialogContent className="max-h-[90vh] overflow-y-auto"> <DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader> <DialogHeader>
<DialogTitle>Add Catalog Item</DialogTitle> <DialogTitle>Add Catalog Item</DialogTitle>
@@ -2302,5 +2314,6 @@ export function CatalogItemsTable({
</Dialog> </Dialog>
</CardContent> </CardContent>
</Card> </Card>
</>
); );
} }
@@ -18,6 +18,7 @@ import { deleteCatalogPage, updateCatalogPage } from "@/actions/catalog";
import { CatalogImagePicker } from "@/components/admin/catalog/catalog-image-picker"; import { CatalogImagePicker } from "@/components/admin/catalog/catalog-image-picker";
import { IconPicker } from "@/components/admin/catalog/icon-picker"; import { IconPicker } from "@/components/admin/catalog/icon-picker";
import { ImagePreview } from "@/components/admin/catalog-manager/image-preview"; import { ImagePreview } from "@/components/admin/catalog-manager/image-preview";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { CatalogIcon, LAYOUT_COLORS } from "@/components/admin/catalog-tree"; import { CatalogIcon, LAYOUT_COLORS } from "@/components/admin/catalog-tree";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -90,6 +91,7 @@ export function CatalogPageForm({
allPages, allPages,
}: CatalogPageFormProps) { }: CatalogPageFormProps) {
const { isPending, run } = useServerAction(); const { isPending, run } = useServerAction();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const formRef = useRef<HTMLFormElement>(null); const formRef = useRef<HTMLFormElement>(null);
const [form, setForm] = useState({ const [form, setForm] = useState({
@@ -140,13 +142,18 @@ export function CatalogPageForm({
}); });
} }
function handleDelete() { async function handleDelete() {
const childCount = childPages.length; const childCount = childPages.length;
const msg = const description =
childCount > 0 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? Its ${childCount} child page(s) will be moved to the parent. All items on this page will be deleted.`
: "Delete this catalog page and all its items?"; : "Delete this catalog page and all its items?";
if (!confirm(msg)) return; const ok = await confirm({
title: "Delete catalog page",
description,
confirmLabel: "Delete",
});
if (!ok) return;
run(() => deleteCatalogPage({ id: catalogPage.id }), { run(() => deleteCatalogPage({ id: catalogPage.id }), {
successMessage: "Page deleted.", successMessage: "Page deleted.",
redirectTo: "/admin/catalog", redirectTo: "/admin/catalog",
@@ -157,7 +164,9 @@ export function CatalogPageForm({
LAYOUT_COLORS[form.pageLayout] || "bg-muted text-muted-foreground"; LAYOUT_COLORS[form.pageLayout] || "bg-muted text-muted-foreground";
return ( return (
<form ref={formRef} onSubmit={handleSubmit}> <>
{confirmDialog}
<form ref={formRef} onSubmit={handleSubmit}>
<div className="grid gap-4 lg:grid-cols-3"> <div className="grid gap-4 lg:grid-cols-3">
{/* ── Left column (2/3): tabs ─────────────────────────── */} {/* ── Left column (2/3): tabs ─────────────────────────── */}
<div className="lg:col-span-2 space-y-4"> <div className="lg:col-span-2 space-y-4">
@@ -495,6 +504,7 @@ export function CatalogPageForm({
</div> </div>
</div> </div>
</form> </form>
</>
); );
} }
@@ -41,6 +41,7 @@ import {
} from "@/components/ui/table"; } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { useServerAction } from "@/hooks/use-server-action"; import { useServerAction } from "@/hooks/use-server-action";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
// ── Types ──────────────────────────────────────────────────────────── // ── Types ────────────────────────────────────────────────────────────
@@ -82,6 +83,7 @@ interface BcPageDetailProps {
export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) { export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
const { isPending, run } = useServerAction(); const { isPending, run } = useServerAction();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const formRef = useRef<HTMLFormElement>(null); const formRef = useRef<HTMLFormElement>(null);
const [editingItem, setEditingItem] = useState<BcItemData | null>(null); const [editingItem, setEditingItem] = useState<BcItemData | null>(null);
const [addingItem, setAddingItem] = useState(false); const [addingItem, setAddingItem] = useState(false);
@@ -130,6 +132,7 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{confirmDialog}
{/* Header */} {/* Header */}
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Link <Link
@@ -338,13 +341,13 @@ export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
variant="ghost" variant="ghost"
size="sm" size="sm"
className="h-6 w-6 p-0 text-[var(--admin-error)] hover:text-[var(--admin-error)]" className="h-6 w-6 p-0 text-[var(--admin-error)] hover:text-[var(--admin-error)]"
onClick={() => { onClick={async () => {
if ( const ok = await confirm({
!confirm( title: "Delete BC item",
`Delete item "${item.catalogName}"?`, description: `Delete item "${item.catalogName}"?`,
) confirmLabel: "Delete",
) });
return; if (!ok) return;
run(() => deleteBcItem({ id: item.id }), { run(() => deleteBcItem({ id: item.id }), {
successMessage: "Item deleted.", successMessage: "Item deleted.",
}); });
+4 -7
View File
@@ -11,7 +11,6 @@ import {
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
@@ -72,12 +71,10 @@ export function CatalogActions({
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> <Button type="button" onClick={() => setOpen(true)}>
<Button> <Plus className="mr-2 h-4 w-4" />
<Plus className="mr-2 h-4 w-4" /> New Page
New Page </Button>
</Button>
</DialogTrigger>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
+8 -11
View File
@@ -1,7 +1,7 @@
import { withAdmin } from "@/lib/api-handler"; import { withAdmin } from "@/lib/api-handler";
import { apiOk } from "@/lib/api-response"; import { apiOk } from "@/lib/api-response";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permissions";
import { lookupHabboIt } from "@/lib/services/habbo-furnidata-cache"; import { batchLookupByClassnames } from "@/lib/services/habbofurni";
export const GET = withAdmin( export const GET = withAdmin(
{ permission: PERMS.CATALOG_VIEW }, { permission: PERMS.CATALOG_VIEW },
@@ -13,19 +13,16 @@ export const GET = withAdmin(
.filter(Boolean) .filter(Boolean)
.slice(0, 100); .slice(0, 100);
const found = await batchLookupByClassnames(classnames);
const suggestions: Record<string, { name: string; description: string }> = const suggestions: Record<string, { name: string; description: string }> =
{}; {};
await Promise.all( for (const [classname, entry] of found) {
classnames.map(async (classname) => { suggestions[classname] = {
const entry = await lookupHabboIt(classname); name: entry.name ?? "",
if (!entry) return; description: entry.description ?? "",
suggestions[classname] = { };
name: entry.name ?? "", }
description: entry.description ?? "",
};
}),
);
return apiOk({ suggestions }); return apiOk({ suggestions });
}, },
+23 -9
View File
@@ -1,5 +1,3 @@
import { promises as fs } from "node:fs";
import path from "node:path";
import { withAdmin } from "@/lib/api-handler"; import { withAdmin } from "@/lib/api-handler";
import { apiError, apiOk } from "@/lib/api-response"; import { apiError, apiOk } from "@/lib/api-response";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permissions";
@@ -9,6 +7,7 @@ import {
getAncestors, getAncestors,
getTreeFlat, getTreeFlat,
} from "@/lib/services/catalog-tree"; } from "@/lib/services/catalog-tree";
import { rcon } from "@/lib/services/rcon";
import type { TreeNode } from "@/types/catalog"; import type { TreeNode } from "@/types/catalog";
type PageRow = { type PageRow = {
@@ -262,6 +261,7 @@ export const PATCH = withAdmin(
where: { id: pageId }, where: { id: pageId },
data: { [field]: current === "1" ? "0" : "1" }, data: { [field]: current === "1" ? "0" : "1" },
}); });
await rcon.updateCatalog();
return apiOk({}); return apiOk({});
} }
const page = await prisma.catalogPages.findUnique({ const page = await prisma.catalogPages.findUnique({
@@ -274,6 +274,7 @@ export const PATCH = withAdmin(
where: { id: pageId }, where: { id: pageId },
data: { [field]: current === "1" ? "0" : "1" }, data: { [field]: current === "1" ? "0" : "1" },
}); });
await rcon.updateCatalog();
return apiOk({}); return apiOk({});
}, },
); );
@@ -304,21 +305,34 @@ export const DELETE = withAdmin(
prisma.catalogPagesBc.delete({ where: { id: pageId } }), prisma.catalogPagesBc.delete({ where: { id: pageId } }),
]); ]);
} else { } else {
const children = await prisma.catalogPagesBc.findMany({ // Deep cascade: collect all descendants
where: { parentId: pageId }, const toDelete: number[] = [pageId];
select: { id: true }, const queue: number[] = [pageId];
}); while (queue.length > 0) {
const ids = [pageId, ...children.map((c) => c.id)]; const children = await prisma.catalogPagesBc.findMany({
where: { parentId: { in: queue } },
select: { id: true },
});
queue.length = 0;
for (const child of children) {
toDelete.push(child.id);
queue.push(child.id);
}
}
await prisma.$transaction([ await prisma.$transaction([
prisma.catalogItemsBc.deleteMany({ prisma.catalogItemsBc.deleteMany({
where: { pageId: { in: ids } }, where: { pageId: { in: toDelete } },
}),
prisma.catalogPagesBc.deleteMany({
where: { id: { in: toDelete } },
}), }),
prisma.catalogPagesBc.deleteMany({ where: { id: { in: ids } } }),
]); ]);
} }
await rcon.updateCatalog();
return apiOk({}); return apiOk({});
} }
await deletePage(pageId, mode); await deletePage(pageId, mode);
await rcon.updateCatalog();
return apiOk({}); return apiOk({});
}, },
); );
+59
View File
@@ -0,0 +1,59 @@
import { withAdmin } from "@/lib/api-handler";
import { apiOk } from "@/lib/api-response";
import { PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
/**
* Search items_base for Quick Add / catalog tooling.
* GET ?q=…&limit=30
*/
export const GET = withAdmin(
{ permission: PERMS.CATALOG_VIEW },
async (request) => {
const q = (request.nextUrl.searchParams.get("q") || "").trim();
const limit = Math.min(
Math.max(
Number.parseInt(request.nextUrl.searchParams.get("limit") || "30", 10) ||
30,
1,
),
50,
);
if (q.length < 2) {
return apiOk({ results: [] });
}
const idExact = Number.parseInt(q, 10);
const rows = await prisma.itemsBase.findMany({
where: {
OR: [
{ itemName: { contains: q } },
{ publicName: { contains: q } },
...(Number.isFinite(idExact) && String(idExact) === q
? [{ id: idExact }]
: []),
],
},
select: {
id: true,
itemName: true,
publicName: true,
type: true,
spriteId: true,
},
take: limit,
orderBy: { id: "asc" },
});
return apiOk({
results: rows.map((r) => ({
id: r.id,
itemName: r.itemName ?? "",
publicName: r.publicName ?? "",
type: r.type ?? "s",
spriteId: r.spriteId ?? 0,
})),
});
},
);
@@ -1,16 +1,20 @@
"use client"; "use client";
import { LayoutGrid } from "lucide-react"; import { LayoutGrid, Plus } from "lucide-react";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { createCatalogPage } from "@/actions/catalog"; import { createCatalogPage } from "@/actions/catalog";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { TooltipProvider } from "@/components/ui/tooltip"; import { TooltipProvider } from "@/components/ui/tooltip";
import type { RootTab } from "@/types/catalog"; import type { RootTab } from "@/types/catalog";
import { BreadcrumbBar } from "./breadcrumb-bar"; import { BreadcrumbBar } from "./breadcrumb-bar";
@@ -47,15 +51,16 @@ export function CatalogManagerDialog() {
function CatalogManagerInner({ function CatalogManagerInner({
open, open,
// biome-ignore lint/correctness/noUnusedFunctionParameters: part of the dialog public API
onOpenChange,
}: { }: {
open: boolean; open: boolean;
onOpenChange: (v: boolean) => void; onOpenChange: (v: boolean) => void;
}) { }) {
const { state, dispatch } = useCatalogManager(); const { state, dispatch } = useCatalogManager();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [createOpen, setCreateOpen] = useState(false);
const [newRootName, setNewRootName] = useState("");
const [creating, setCreating] = useState(false);
// Load root pages when dialog opens
const loadRootPages = useCallback(async () => { const loadRootPages = useCallback(async () => {
dispatch({ type: "SET_LOADING_ROOT", loading: true }); dispatch({ type: "SET_LOADING_ROOT", loading: true });
try { try {
@@ -73,7 +78,6 @@ function CatalogManagerInner({
); );
dispatch({ type: "SET_ROOT_PAGES", pages }); dispatch({ type: "SET_ROOT_PAGES", pages });
// Auto-select first tab if none or missing
if ( if (
pages.length > 0 && pages.length > 0 &&
(!state.activeTabId || !pages.find((p) => p.id === state.activeTabId)) (!state.activeTabId || !pages.find((p) => p.id === state.activeTabId))
@@ -86,53 +90,65 @@ function CatalogManagerInner({
} }
}, [dispatch, state.activeTabId]); }, [dispatch, state.activeTabId]);
// biome-ignore lint/correctness/useExhaustiveDependencies: explicitly chosen here, see surrounding code // biome-ignore lint/correctness/useExhaustiveDependencies: load once when dialog opens
useEffect(() => { useEffect(() => {
if (open) loadRootPages(); if (open) loadRootPages();
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps }, [open]);
// Handle dialog close: preserve tree state, clear selection
useEffect(() => { useEffect(() => {
if (!open) dispatch({ type: "ON_DIALOG_CLOSE" }); if (!open) dispatch({ type: "ON_DIALOG_CLOSE" });
}, [open, dispatch]); }, [open, dispatch]);
const handleTabClick = (id: number) => { async function confirmDiscardIfDirty(): Promise<boolean> {
if (state.editorDirty && !confirm("You have unsaved changes. Discard?")) if (!state.editorDirty) return true;
return; return confirm({
title: "Unsaved changes",
description: "You have unsaved changes. Discard them?",
confirmLabel: "Discard",
cancelLabel: "Keep editing",
});
}
const handleTabClick = async (id: number) => {
if (!(await confirmDiscardIfDirty())) return;
dispatch({ type: "SET_ACTIVE_TAB", id }); dispatch({ type: "SET_ACTIVE_TAB", id });
dispatch({ type: "CLEAR_TREE" }); dispatch({ type: "CLEAR_TREE" });
}; };
const handleCreateRoot = async () => { const handleCreateRoot = async () => {
const caption = prompt("Root page name:"); const caption = newRootName.trim();
if (!caption?.trim()) return; if (!caption) return;
setCreating(true);
try { try {
const result = await createCatalogPage({ const result = await createCatalogPage({
parentId: -1, parentId: -1,
caption: caption.trim(), caption,
}); });
if (!result.ok) throw new Error(result.error); if (!result.ok) throw new Error(result.error);
setCreateOpen(false);
setNewRootName("");
await loadRootPages(); await loadRootPages();
toast.success("Root page created"); toast.success("Root page created");
} catch { } catch {
toast.error("Failed to create root page"); toast.error("Failed to create root page");
} finally {
setCreating(false);
} }
}; };
const handleSelectPage = (id: number) => { const handleSelectPage = async (id: number) => {
if (state.editorDirty && !confirm("You have unsaved changes. Discard?")) if (!(await confirmDiscardIfDirty())) return;
return;
dispatch({ type: "SELECT_PAGE", id: id > 0 ? id : null }); dispatch({ type: "SELECT_PAGE", id: id > 0 ? id : null });
}; };
const handleEditTab = (id: number) => { const handleEditTab = async (id: number) => {
// First ensure this tab is active, then select it in the editor
if (state.activeTabId !== id) { if (state.activeTabId !== id) {
if (!(await confirmDiscardIfDirty())) return;
dispatch({ type: "SET_ACTIVE_TAB", id }); dispatch({ type: "SET_ACTIVE_TAB", id });
dispatch({ type: "CLEAR_TREE" }); dispatch({ type: "CLEAR_TREE" });
} } else if (!(await confirmDiscardIfDirty())) {
if (state.editorDirty && !confirm("You have unsaved changes. Discard?"))
return; return;
}
dispatch({ type: "SELECT_PAGE", id }); dispatch({ type: "SELECT_PAGE", id });
}; };
@@ -140,7 +156,6 @@ function CatalogManagerInner({
dispatch({ type: "UPDATE_NODE", update: { ...updated } }); dispatch({ type: "UPDATE_NODE", update: { ...updated } });
dispatch({ type: "SET_DIRTY", dirty: false }); dispatch({ type: "SET_DIRTY", dirty: false });
// Update root tabs if root page
const rootIdx = state.rootPages.findIndex((p) => p.id === updated.id); const rootIdx = state.rootPages.findIndex((p) => p.id === updated.id);
if (rootIdx !== -1) { if (rootIdx !== -1) {
const pages = [...state.rootPages]; const pages = [...state.rootPages];
@@ -155,7 +170,7 @@ function CatalogManagerInner({
return ( return (
<TooltipProvider delayDuration={300}> <TooltipProvider delayDuration={300}>
{/* Header */} {confirmDialog}
<DialogHeader className="px-4 py-2.5 border-b shrink-0"> <DialogHeader className="px-4 py-2.5 border-b shrink-0">
<DialogTitle className="text-base flex items-center gap-2"> <DialogTitle className="text-base flex items-center gap-2">
<LayoutGrid className="h-4 w-4" /> <LayoutGrid className="h-4 w-4" />
@@ -163,20 +178,17 @@ function CatalogManagerInner({
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
{/* Breadcrumb */}
<BreadcrumbBar /> <BreadcrumbBar />
{/* Root tabs */}
<RootTabs <RootTabs
tabs={state.rootPages} tabs={state.rootPages}
activeTabId={state.activeTabId} activeTabId={state.activeTabId}
onTabClick={handleTabClick} onTabClick={handleTabClick}
onEditTab={handleEditTab} onEditTab={handleEditTab}
onCreateRoot={handleCreateRoot} onCreateRoot={() => setCreateOpen(true)}
loading={state.loadingRoot} loading={state.loadingRoot}
/> />
{/* Main content: tree + editor */}
<div className="flex flex-1 min-h-0"> <div className="flex flex-1 min-h-0">
<SortableTree <SortableTree
activeTabId={state.activeTabId} activeTabId={state.activeTabId}
@@ -191,8 +203,45 @@ function CatalogManagerInner({
/> />
</div> </div>
{/* Stats bar */}
<StatsBar /> <StatsBar />
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>New root page</DialogTitle>
</DialogHeader>
<div className="space-y-2">
<Label htmlFor="root-caption">Name</Label>
<Input
id="root-caption"
value={newRootName}
onChange={(e) => setNewRootName(e.target.value)}
placeholder="e.g. Furniture"
autoFocus
onKeyDown={(e) => {
if (e.key === "Enter") void handleCreateRoot();
}}
/>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setCreateOpen(false)}
>
Cancel
</Button>
<Button
type="button"
disabled={creating || !newRootName.trim()}
onClick={handleCreateRoot}
>
<Plus className="mr-1 h-4 w-4" />
Create
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</TooltipProvider> </TooltipProvider>
); );
} }
@@ -25,6 +25,7 @@ import {
reorderTreePage, reorderTreePage,
toggleCatalogPage, toggleCatalogPage,
} from "@/actions/catalog"; } from "@/actions/catalog";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { CatalogIcon } from "@/components/admin/catalog-tree"; import { CatalogIcon } from "@/components/admin/catalog-tree";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
@@ -48,8 +49,8 @@ import type { RootTab } from "@/types/catalog";
interface RootTabsProps { interface RootTabsProps {
tabs: RootTab[]; tabs: RootTab[];
activeTabId: number | null; activeTabId: number | null;
onTabClick: (id: number) => void; onTabClick: (id: number) => void | Promise<void>;
onEditTab: (id: number) => void; onEditTab: (id: number) => void | Promise<void>;
onCreateRoot: () => void; onCreateRoot: () => void;
loading?: boolean; loading?: boolean;
} }
@@ -62,6 +63,7 @@ export function RootTabs({
onCreateRoot, onCreateRoot,
loading, loading,
}: RootTabsProps) { }: RootTabsProps) {
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [activeDragId, setActiveDragId] = useState<number | null>(null); const [activeDragId, setActiveDragId] = useState<number | null>(null);
const sensors = useSensors( const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }), useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
@@ -112,12 +114,12 @@ export function RootTabs({
}; };
const handleDelete = async (tab: RootTab) => { const handleDelete = async (tab: RootTab) => {
if ( const ok = await confirm({
!confirm( title: "Delete root page",
`Delete root page "${tab.caption}"? Children will be reparented.`, description: `Delete root page "${tab.caption}"? Children will be reparented.`,
) confirmLabel: "Delete",
) });
return; if (!ok) return;
try { try {
await deleteTreePage({ pageId: tab.id, mode: "reparent" }); await deleteTreePage({ pageId: tab.id, mode: "reparent" });
toast.success(`"${tab.caption}" deleted`); toast.success(`"${tab.caption}" deleted`);
@@ -132,6 +134,7 @@ export function RootTabs({
return ( return (
<div className="flex items-center gap-1 border-b bg-muted/30 px-2 py-1.5 overflow-x-auto shrink-0"> <div className="flex items-center gap-1 border-b bg-muted/30 px-2 py-1.5 overflow-x-auto shrink-0">
{confirmDialog}
{loading && ( {loading && (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground mx-2" /> <Loader2 className="h-4 w-4 animate-spin text-muted-foreground mx-2" />
)} )}
@@ -40,9 +40,18 @@ import {
toggleCatalogPage, toggleCatalogPage,
updateCatalogPage, updateCatalogPage,
} from "@/actions/catalog"; } from "@/actions/catalog";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { import {
Tooltip, Tooltip,
TooltipContent, TooltipContent,
@@ -66,7 +75,7 @@ import type { TreeNodeData, TreeNodeUpdate } from "@/types/catalog";
interface SortableTreeProps { interface SortableTreeProps {
activeTabId: number | null; activeTabId: number | null;
selectedPageId: number | null; selectedPageId: number | null;
onSelectPage: (id: number) => void; onSelectPage: (id: number) => void | Promise<void>;
onTreeMutation: () => void; onTreeMutation: () => void;
nodeUpdate?: TreeNodeUpdate | null; nodeUpdate?: TreeNodeUpdate | null;
} }
@@ -83,6 +92,7 @@ export function SortableTree({
nodeUpdate, nodeUpdate,
}: SortableTreeProps) { }: SortableTreeProps) {
const { state, dispatch } = useCatalogManager(); const { state, dispatch } = useCatalogManager();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const { const {
nodes, nodes,
childrenMap, childrenMap,
@@ -97,6 +107,9 @@ export function SortableTree({
const [searchResults, setSearchResults] = useState<TreeNodeData[] | null>( const [searchResults, setSearchResults] = useState<TreeNodeData[] | null>(
null, null,
); );
const [subpageParentId, setSubpageParentId] = useState<number | null>(null);
const [subpageName, setSubpageName] = useState("");
const [creatingSubpage, setCreatingSubpage] = useState(false);
const [searching, setSearching] = useState(false); const [searching, setSearching] = useState(false);
const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null); const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const [activeId, setActiveId] = useState<number | null>(null); const [activeId, setActiveId] = useState<number | null>(null);
@@ -412,22 +425,32 @@ export function SortableTree({
}; };
// ── Actions ───────────────────────────────────────────────── // ── Actions ─────────────────────────────────────────────────
const handleAddSubpage = async (parentId: number) => { const handleAddSubpage = (parentId: number) => {
const caption = prompt("Subpage name:"); setSubpageParentId(parentId);
if (!caption?.trim()) return; setSubpageName("");
};
const handleCreateSubpage = async () => {
if (subpageParentId === null || !subpageName.trim()) return;
setCreatingSubpage(true);
try { try {
const result = await createCatalogPage({ const result = await createCatalogPage({
parentId, parentId: subpageParentId,
caption: caption.trim(), caption: subpageName.trim(),
}); });
if (!result.ok) throw new Error(result.error); if (!result.ok) throw new Error(result.error);
dispatch({ type: "SET_EXPANDED", id: parentId, expanded: true }); dispatch({ type: "SET_EXPANDED", id: subpageParentId, expanded: true });
await loadFullTree(); await loadFullTree();
const data = result.data as Record<string, unknown>; const data = result.data as Record<string, unknown>;
onSelectPage(data.id as number); onSelectPage(data.id as number);
onTreeMutation(); onTreeMutation();
setSubpageParentId(null);
setSubpageName("");
toast.success("Subpage created");
} catch { } catch {
toast.error("Failed to create subpage"); toast.error("Failed to create subpage");
} finally {
setCreatingSubpage(false);
} }
}; };
@@ -457,10 +480,12 @@ export function SortableTree({
const handleDelete = async (id: number) => { const handleDelete = async (id: number) => {
const node = nodes.get(id); const node = nodes.get(id);
if ( const ok = await confirm({
!confirm(`Delete "${node?.caption ?? id}"? Children will be reparented.`) title: "Delete page",
) description: `Delete "${node?.caption ?? id}"? Children will be reparented.`,
return; confirmLabel: "Delete",
});
if (!ok) return;
try { try {
const result = await deleteTreePage({ pageId: id, mode: "reparent" }); const result = await deleteTreePage({ pageId: id, mode: "reparent" });
if (!result.ok) throw new Error(); if (!result.ok) throw new Error();
@@ -548,7 +573,12 @@ export function SortableTree({
const handleBulkDelete = async () => { const handleBulkDelete = async () => {
const ids = [...multiSelectedIds]; const ids = [...multiSelectedIds];
if (!confirm(`Delete ${ids.length} page(s)?`)) return; const ok = await confirm({
title: "Delete pages",
description: `Delete ${ids.length} page(s)? Children will be reparented.`,
confirmLabel: "Delete",
});
if (!ok) return;
await Promise.allSettled( await Promise.allSettled(
ids.map((id) => deleteTreePage({ pageId: id, mode: "reparent" })), ids.map((id) => deleteTreePage({ pageId: id, mode: "reparent" })),
); );
@@ -598,6 +628,7 @@ export function SortableTree({
tabIndex={0} tabIndex={0}
className="flex flex-col h-full border-r w-80 shrink-0" className="flex flex-col h-full border-r w-80 shrink-0"
> >
{confirmDialog}
{/* Header */} {/* Header */}
<div className="border-b px-3 py-2 space-y-2 shrink-0"> <div className="border-b px-3 py-2 space-y-2 shrink-0">
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
@@ -895,6 +926,59 @@ export function SortableTree({
</Button> </Button>
</div> </div>
)} )}
<Dialog
open={subpageParentId !== null}
onOpenChange={(open) => {
if (!open) {
setSubpageParentId(null);
setSubpageName("");
}
}}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>New subpage</DialogTitle>
</DialogHeader>
<div className="space-y-2">
<Label htmlFor="subpage-caption">Name</Label>
<Input
id="subpage-caption"
value={subpageName}
onChange={(e) => setSubpageName(e.target.value)}
placeholder="e.g. Sofas"
autoFocus
onKeyDown={(e) => {
if (e.key === "Enter") void handleCreateSubpage();
}}
/>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => {
setSubpageParentId(null);
setSubpageName("");
}}
>
Cancel
</Button>
<Button
type="button"
disabled={creatingSubpage || !subpageName.trim()}
onClick={handleCreateSubpage}
>
{creatingSubpage ? (
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-1 h-4 w-4" />
)}
Create
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
); );
} }
+10 -2
View File
@@ -32,6 +32,7 @@ import {
useState, useState,
} from "react"; } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
@@ -173,6 +174,7 @@ export function CatalogTree({
catalogType = "normal", catalogType = "normal",
}: CatalogTreeProps) { }: CatalogTreeProps) {
const router = useRouter(); const router = useRouter();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [searchResults, setSearchResults] = useState<TreeNode[] | null>(null); const [searchResults, setSearchResults] = useState<TreeNode[] | null>(null);
const [searching, setSearching] = useState(false); const [searching, setSearching] = useState(false);
@@ -280,7 +282,12 @@ export function CatalogTree({
: ""; : "";
const itemInfo = const itemInfo =
node.itemCount > 0 ? ` ${node.itemCount} item(s) will be deleted.` : ""; node.itemCount > 0 ? ` ${node.itemCount} item(s) will be deleted.` : "";
if (!confirm(`Delete "${node.caption}"?${childInfo}${itemInfo}`)) return; const ok = await confirm({
title: "Delete page",
description: `Delete "${node.caption}"?${childInfo}${itemInfo}`,
confirmLabel: "Delete",
});
if (!ok) return;
try { try {
const res = await fetch( const res = await fetch(
@@ -296,7 +303,7 @@ export function CatalogTree({
toast.error("Failed to delete page."); toast.error("Failed to delete page.");
} }
}, },
[router, catParam], [router, catParam, confirm],
); );
const unfilteredPages = searchResults ?? rootPages; const unfilteredPages = searchResults ?? rootPages;
@@ -320,6 +327,7 @@ export function CatalogTree({
catalogType, catalogType,
}} }}
> >
{confirmDialog}
<TooltipProvider delayDuration={400}> <TooltipProvider delayDuration={400}>
<div className="rounded-lg border bg-card shadow-sm"> <div className="rounded-lg border bg-card shadow-sm">
{/* Header */} {/* Header */}
@@ -11,7 +11,6 @@ import {
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
@@ -134,12 +133,10 @@ export function BulkImportItems({ pageId, onImported }: BulkImportItemsProps) {
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
<Button variant="outline" size="sm"> <Upload className="mr-2 h-4 w-4" />
<Upload className="mr-2 h-4 w-4" /> Bulk Import
Bulk Import </Button>
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl"> <DialogContent className="max-w-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle>Bulk Import Items</DialogTitle> <DialogTitle>Bulk Import Items</DialogTitle>
@@ -9,7 +9,6 @@ import {
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -106,35 +105,34 @@ export function CatalogImagePicker({
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> <Button
<Button type="button"
type="button" variant="outline"
variant="outline" disabled={disabled}
disabled={disabled} className="h-auto w-full justify-start gap-2 px-3 py-2"
className="h-auto w-full justify-start gap-2 px-3 py-2" onClick={() => setOpen(true)}
> >
{value ? ( {value ? (
<CatalogImageThumb name={value} size={40} /> <CatalogImageThumb name={value} size={40} />
) : ( ) : (
<div className="flex h-10 w-16 items-center justify-center rounded bg-muted"> <div className="flex h-10 w-16 items-center justify-center rounded bg-muted">
<ImageIcon className="h-4 w-4 text-muted-foreground" /> <ImageIcon className="h-4 w-4 text-muted-foreground" />
</div>
)}
<div className="min-w-0 text-left">
<p className="text-xs font-medium truncate">
{label ||
(type === "header"
? "Headline image"
: type === "teaser"
? "Teaser image"
: "Image")}
</p>
<p className="text-[11px] text-muted-foreground truncate font-mono">
{value || "None selected"}
</p>
</div> </div>
</Button> )}
</DialogTrigger> <div className="min-w-0 text-left">
<p className="text-xs font-medium truncate">
{label ||
(type === "header"
? "Headline image"
: type === "teaser"
? "Teaser image"
: "Image")}
</p>
<p className="text-[11px] text-muted-foreground truncate font-mono">
{value || "None selected"}
</p>
</div>
</Button>
<DialogContent className="max-w-4xl"> <DialogContent className="max-w-4xl">
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
+23 -16
View File
@@ -9,7 +9,6 @@ import {
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -103,21 +102,29 @@ export function IconPicker({
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> {children ? (
{children ?? ( <button
<Button type="button"
type="button" disabled={disabled}
variant="outline" onClick={() => setOpen(true)}
disabled={disabled} className="contents"
className="h-auto gap-2 px-3 py-2" >
> {children}
<IconPreview iconImage={value} size={24} /> </button>
<span className="font-mono text-xs text-muted-foreground"> ) : (
{value > 0 ? `#${value}` : "None"} <Button
</span> type="button"
</Button> variant="outline"
)} disabled={disabled}
</DialogTrigger> className="h-auto gap-2 px-3 py-2"
onClick={() => setOpen(true)}
>
<IconPreview iconImage={value} size={24} />
<span className="font-mono text-xs text-muted-foreground">
{value > 0 ? `#${value}` : "None"}
</span>
</Button>
)}
<DialogContent className="max-w-3xl"> <DialogContent className="max-w-3xl">
<DialogHeader> <DialogHeader>
<DialogTitle>Select Catalog Icon</DialogTitle> <DialogTitle>Select Catalog Icon</DialogTitle>
@@ -10,7 +10,6 @@ import {
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { useServerAction } from "@/hooks/use-server-action"; import { useServerAction } from "@/hooks/use-server-action";
@@ -122,15 +121,13 @@ export function QuickAddFurni({
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
<Button variant="outline" size="sm"> <Zap className="mr-2 h-4 w-4" />
<Zap className="mr-2 h-4 w-4" /> Quick Add
Quick Add <kbd className="ml-2 hidden rounded border bg-muted px-1 text-[10px] sm:inline">
<kbd className="ml-2 hidden rounded border bg-muted px-1 text-[10px] sm:inline"> Ctrl+K
Ctrl+K </kbd>
</kbd> </Button>
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl"> <DialogContent className="max-w-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle>Quick Add Furni</DialogTitle> <DialogTitle>Quick Add Furni</DialogTitle>
+5
View File
@@ -17,6 +17,8 @@ interface RunOptions {
redirectTo?: string; redirectTo?: string;
/** Called on success with the result data. Overrides default router.refresh(). */ /** Called on success with the result data. Overrides default router.refresh(). */
onSuccess?: (data: Record<string, unknown>) => void; onSuccess?: (data: Record<string, unknown>) => void;
/** Called when the action fails or throws */
onError?: () => void;
} }
/** /**
@@ -42,6 +44,7 @@ export function useServerAction(options: UseServerActionOptions = {}) {
errorMessage = "An error occurred.", errorMessage = "An error occurred.",
redirectTo, redirectTo,
onSuccess, onSuccess,
onError,
} = opts; } = opts;
startTransition(async () => { startTransition(async () => {
@@ -59,10 +62,12 @@ export function useServerAction(options: UseServerActionOptions = {}) {
} }
} else { } else {
toast.error(result.error || errorMessage); toast.error(result.error || errorMessage);
onError?.();
} }
} catch (err) { } catch (err) {
console.error("[useServerAction] Unexpected error:", err); console.error("[useServerAction] Unexpected error:", err);
toast.error(errorMessage); toast.error(errorMessage);
onError?.();
} }
}); });
} }
+59
View File
@@ -245,6 +245,65 @@ export async function removeFurniEntry(classname: string): Promise<boolean> {
}); });
} }
/**
* Patch name/description on existing FurnitureData entries by classname.
* Optionally creates a minimal entry when missing.
*/
export async function patchFurniEntryNames(
updates: Array<{
classname: string;
itemType: string;
name?: string;
description?: string;
spriteId?: number;
createIfMissing?: boolean;
}>,
): Promise<{ updated: number; inserted: number }> {
if (updates.length === 0) return { updated: 0, inserted: 0 };
return withFurniDataLock(async () => {
const furniData = (await readFurniData()) as Record<
string,
{ furnitype: Array<Record<string, unknown>> }
>;
let updated = 0;
let inserted = 0;
for (const u of updates) {
const sectionKey = u.itemType === "i" ? "wallitemtypes" : "roomitemtypes";
if (!furniData[sectionKey]) furniData[sectionKey] = { furnitype: [] };
const section = furniData[sectionKey];
const idx = section.furnitype.findIndex(
(e) => e.classname === u.classname,
);
if (idx >= 0) {
const entry = { ...section.furnitype[idx] };
if (u.name !== undefined) entry.name = u.name;
if (u.description !== undefined) entry.description = u.description;
section.furnitype[idx] = entry;
updated++;
} else if (u.createIfMissing) {
section.furnitype.push({
id: u.spriteId ?? 0,
classname: u.classname,
revision: 0,
category: "unknown",
name: u.name ?? u.classname,
description: u.description ?? "",
offerid: u.spriteId ?? -1,
});
inserted++;
}
}
if (updated > 0 || inserted > 0) {
await writeFurniData(furniData as Record<string, unknown>);
}
return { updated, inserted };
});
}
export async function appendFurniEntriesBatch( export async function appendFurniEntriesBatch(
entries: Array<{ entry: Record<string, unknown>; itemType: string }>, entries: Array<{ entry: Record<string, unknown>; itemType: string }>,
): Promise<void> { ): Promise<void> {