fix: resolve critical bugs and improve admin panel reliability
- Fix missing await in pets API route causing empty responses - Fix updateSetting to use upsert pattern instead of update-only - Create missing /api/admin/sounds/upload route (upload was broken) - Wire bulk delete actions in catalog table - Replace native confirm() with useConfirmDialog() across rooms and clone pages - Add error logging to silent catch blocks in radio actions and audit route - Add graceful degradation to devops health endpoint - Add cache eviction to clone icon route to prevent memory leak - Internationalize hardcoded Italian strings to English - Remove placeholder created_at fields from prefix API responses - Remove dead code and fix type errors in translations and import pages - Standardize PERMS import path in analytics export route
This commit is contained in:
1 parent
6f53ca514d
commit
1b817fe434
19 files changed
+255
-89
No files matched your search
@@ -4,6 +4,7 @@ import { eq } from "drizzle-orm";
|
|||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { requirePermission } from "@/lib/admin/guard";
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
import { db, RadioBanners, RadioRanks, WebsiteSetting } from "@/lib/db";
|
import { db, RadioBanners, RadioRanks, WebsiteSetting } from "@/lib/db";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
@@ -50,8 +51,8 @@ export async function saveRadioSetting(formData: FormData): Promise<void> {
|
|||||||
.values({ key, value, comment: comment || null })
|
.values({ key, value, comment: comment || null })
|
||||||
.onDuplicateKeyUpdate({ set: { value } });
|
.onDuplicateKeyUpdate({ set: { value } });
|
||||||
siteSettings.reload();
|
siteSettings.reload();
|
||||||
} catch {
|
} catch (err) {
|
||||||
// DB unavailable — fail soft so the action does not throw.
|
logger.error("Failed to save radio setting", { err, key });
|
||||||
}
|
}
|
||||||
revalidatePath("/admin/radio/settings");
|
revalidatePath("/admin/radio/settings");
|
||||||
}
|
}
|
||||||
@@ -81,8 +82,8 @@ export async function saveRadioSettings(formData: FormData): Promise<void> {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
siteSettings.reload();
|
siteSettings.reload();
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Fail soft.
|
logger.error("Failed to bulk-save radio settings", { err, keys });
|
||||||
}
|
}
|
||||||
revalidatePath("/admin/radio/settings");
|
revalidatePath("/admin/radio/settings");
|
||||||
}
|
}
|
||||||
@@ -114,8 +115,8 @@ export async function createRadioBanner(formData: FormData): Promise<void> {
|
|||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Fail soft.
|
logger.error("Failed to create radio banner", { err, imagePath });
|
||||||
}
|
}
|
||||||
revalidatePath("/admin/radio/banners");
|
revalidatePath("/admin/radio/banners");
|
||||||
}
|
}
|
||||||
@@ -147,8 +148,8 @@ export async function updateRadioBanner(formData: FormData): Promise<void> {
|
|||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
})
|
})
|
||||||
.where(eq(RadioBanners.id, id));
|
.where(eq(RadioBanners.id, id));
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Row may be gone; ignore.
|
logger.error("Failed to update radio banner", { err, id: String(id) });
|
||||||
}
|
}
|
||||||
revalidatePath("/admin/radio/banners");
|
revalidatePath("/admin/radio/banners");
|
||||||
}
|
}
|
||||||
@@ -159,8 +160,8 @@ export async function deleteRadioBanner(formData: FormData): Promise<void> {
|
|||||||
if (id === null) return;
|
if (id === null) return;
|
||||||
try {
|
try {
|
||||||
await db.delete(RadioBanners).where(eq(RadioBanners.id, id));
|
await db.delete(RadioBanners).where(eq(RadioBanners.id, id));
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Already deleted; ignore.
|
logger.error("Failed to delete radio banner", { err, id: String(id) });
|
||||||
}
|
}
|
||||||
revalidatePath("/admin/radio/banners");
|
revalidatePath("/admin/radio/banners");
|
||||||
}
|
}
|
||||||
@@ -186,8 +187,8 @@ export async function createRadioRank(formData: FormData): Promise<void> {
|
|||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Fail soft.
|
logger.error("Failed to create radio rank", { err, name });
|
||||||
}
|
}
|
||||||
revalidatePath("/admin/radio/ranks");
|
revalidatePath("/admin/radio/ranks");
|
||||||
}
|
}
|
||||||
@@ -214,8 +215,8 @@ export async function updateRadioRank(formData: FormData): Promise<void> {
|
|||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
})
|
})
|
||||||
.where(eq(RadioRanks.id, id));
|
.where(eq(RadioRanks.id, id));
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Row may be gone; ignore.
|
logger.error("Failed to update radio rank", { err, id: String(id) });
|
||||||
}
|
}
|
||||||
revalidatePath("/admin/radio/ranks");
|
revalidatePath("/admin/radio/ranks");
|
||||||
}
|
}
|
||||||
@@ -226,8 +227,8 @@ export async function deleteRadioRank(formData: FormData): Promise<void> {
|
|||||||
if (id === null) return;
|
if (id === null) return;
|
||||||
try {
|
try {
|
||||||
await db.delete(RadioRanks).where(eq(RadioRanks.id, id));
|
await db.delete(RadioRanks).where(eq(RadioRanks.id, id));
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Already deleted; ignore.
|
logger.error("Failed to delete radio rank", { err, id: String(id) });
|
||||||
}
|
}
|
||||||
revalidatePath("/admin/radio/ranks");
|
revalidatePath("/admin/radio/ranks");
|
||||||
}
|
}
|
||||||
@@ -77,9 +77,9 @@ export async function updateSetting(formData: FormData): Promise<void> {
|
|||||||
);
|
);
|
||||||
if (!key) return;
|
if (!key) return;
|
||||||
await db
|
await db
|
||||||
.update(WebsiteSetting)
|
.insert(WebsiteSetting)
|
||||||
.set({ value })
|
.values({ key, value })
|
||||||
.where(eq(WebsiteSetting.key, key));
|
.onDuplicateKeyUpdate({ set: { value } });
|
||||||
await siteSettings.reload();
|
await siteSettings.reload();
|
||||||
bustGamedataCachesIfNeeded(key);
|
bustGamedataCachesIfNeeded(key);
|
||||||
revalidatePath("/admin/settings");
|
revalidatePath("/admin/settings");
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
import { Pencil } from "lucide-react";
|
import { Pencil } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { toggleCatalogPage } from "@/actions/catalog";
|
import { deleteCatalogPage, toggleCatalogPage } from "@/actions/catalog";
|
||||||
import { toggleBcPage } from "@/actions/catalog-bc";
|
import { deleteBcTreePage, toggleBcPage } from "@/actions/catalog-bc";
|
||||||
import { DataTable } from "@/components/admin/data-table";
|
import { DataTable } from "@/components/admin/data-table";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -175,6 +175,20 @@ export function CatalogTable({
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
async function handleBulkAction(action: string, ids: (number | string)[]) {
|
||||||
|
if (action !== "delete" || ids.length === 0) return;
|
||||||
|
for (const id of ids) {
|
||||||
|
const numId = typeof id === "string" ? Number(id) : id;
|
||||||
|
if (Number.isInteger(numId) && numId > 0) {
|
||||||
|
run(() =>
|
||||||
|
isBc
|
||||||
|
? deleteBcTreePage({ pageId: numId, mode: "reparent" })
|
||||||
|
: deleteCatalogPage({ id: numId }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DataTable
|
<DataTable
|
||||||
data={data}
|
data={data}
|
||||||
@@ -191,6 +205,7 @@ export function CatalogTable({
|
|||||||
]
|
]
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
|
onBulkAction={canEdit ? handleBulkAction : undefined}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } 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 { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -370,6 +371,7 @@ interface FurniGridProps {
|
|||||||
const PER_PAGE = 50;
|
const PER_PAGE = 50;
|
||||||
|
|
||||||
function FurniGrid({ source }: FurniGridProps) {
|
function FurniGrid({ source }: FurniGridProps) {
|
||||||
|
const { confirm, dialog: confirmDialog } = useConfirmDialog();
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [activeSearch, setActiveSearch] = useState("");
|
const [activeSearch, setActiveSearch] = useState("");
|
||||||
const [items, setItems] = useState<FurniItem[]>([]);
|
const [items, setItems] = useState<FurniItem[]>([]);
|
||||||
@@ -554,13 +556,12 @@ function FurniGrid({ source }: FurniGridProps) {
|
|||||||
toast.info("Nothing to clone — everything is already present");
|
toast.info("Nothing to clone — everything is already present");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (
|
const confirmed = await confirm({
|
||||||
!window.confirm(
|
title: "Clone All Furni",
|
||||||
`Clone ALL ${names.length} furni from "${source.name}"? This can take a while.`,
|
description: `Clone ALL ${names.length} furni from "${source.name}"? This can take a while.`,
|
||||||
)
|
confirmLabel: "Clone All",
|
||||||
) {
|
});
|
||||||
return;
|
if (!confirmed) return;
|
||||||
}
|
|
||||||
batchAbortRef.current?.abort();
|
batchAbortRef.current?.abort();
|
||||||
const abort = new AbortController();
|
const abort = new AbortController();
|
||||||
batchAbortRef.current = abort;
|
batchAbortRef.current = abort;
|
||||||
@@ -614,6 +615,7 @@ function FurniGrid({ source }: FurniGridProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{confirmDialog}
|
||||||
{/* Stats bar */}
|
{/* Stats bar */}
|
||||||
{stats && (
|
{stats && (
|
||||||
<div className="flex items-center gap-3 flex-wrap">
|
<div className="flex items-center gap-3 flex-wrap">
|
||||||
|
|||||||
@@ -396,14 +396,6 @@ export function ImportFurniClient({ source }: { source: FurniImportSource }) {
|
|||||||
}
|
}
|
||||||
}, [statusFilter, activeSearch, fetchItems]);
|
}, [statusFilter, activeSearch, fetchItems]);
|
||||||
|
|
||||||
function _doSearch(e?: React.FormEvent) {
|
|
||||||
e?.preventDefault();
|
|
||||||
setActiveSearch(searchTerm);
|
|
||||||
setPage(1);
|
|
||||||
fetchItems(searchTerm, 1, statusFilter);
|
|
||||||
}
|
|
||||||
void _doSearch;
|
|
||||||
|
|
||||||
function goPage(p: number) {
|
function goPage(p: number) {
|
||||||
setPage(p);
|
setPage(p);
|
||||||
fetchItems(activeSearch, p, statusFilter);
|
fetchItems(activeSearch, p, statusFilter);
|
||||||
|
|||||||
@@ -215,7 +215,7 @@ export function NitroEditorDialog({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
toast.success("Nitro metadata salvato");
|
toast.success("Nitro metadata saved");
|
||||||
setMetadata(metadataToSave);
|
setMetadata(metadataToSave);
|
||||||
setOriginalMetadata(JSON.parse(JSON.stringify(metadataToSave)));
|
setOriginalMetadata(JSON.parse(JSON.stringify(metadataToSave)));
|
||||||
setOriginalFlags({ ...flags });
|
setOriginalFlags({ ...flags });
|
||||||
@@ -392,7 +392,7 @@ export function NitroEditorDialog({
|
|||||||
<section className="rounded-lg border bg-card p-4">
|
<section className="rounded-lg border bg-card p-4">
|
||||||
<div className="flex items-center gap-2 mb-3">
|
<div className="flex items-center gap-2 mb-3">
|
||||||
<Ruler className="w-4 h-4 text-muted-foreground" />
|
<Ruler className="w-4 h-4 text-muted-foreground" />
|
||||||
<h3 className="text-sm font-medium">Dimensioni</h3>
|
<h3 className="text-sm font-medium">Dimensions</h3>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-3 gap-3">
|
<div className="grid grid-cols-3 gap-3">
|
||||||
<div>
|
<div>
|
||||||
@@ -400,7 +400,7 @@ export function NitroEditorDialog({
|
|||||||
htmlFor="dim-x"
|
htmlFor="dim-x"
|
||||||
className="text-xs text-muted-foreground"
|
className="text-xs text-muted-foreground"
|
||||||
>
|
>
|
||||||
X (larghezza)
|
X (width)
|
||||||
</Label>
|
</Label>
|
||||||
<Input
|
<Input
|
||||||
id="dim-x"
|
id="dim-x"
|
||||||
@@ -432,7 +432,7 @@ export function NitroEditorDialog({
|
|||||||
htmlFor="dim-z"
|
htmlFor="dim-z"
|
||||||
className="text-xs text-muted-foreground"
|
className="text-xs text-muted-foreground"
|
||||||
>
|
>
|
||||||
Z (altezza)
|
Z (height)
|
||||||
</Label>
|
</Label>
|
||||||
<Input
|
<Input
|
||||||
id="dim-z"
|
id="dim-z"
|
||||||
@@ -451,7 +451,7 @@ export function NitroEditorDialog({
|
|||||||
<section className="rounded-lg border bg-card p-4">
|
<section className="rounded-lg border bg-card p-4">
|
||||||
<div className="flex items-center gap-2 mb-3">
|
<div className="flex items-center gap-2 mb-3">
|
||||||
<MousePointerClick className="w-4 h-4 text-muted-foreground" />
|
<MousePointerClick className="w-4 h-4 text-muted-foreground" />
|
||||||
<h3 className="text-sm font-medium">Interazione</h3>
|
<h3 className="text-sm font-medium">Interaction</h3>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
|
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
|
||||||
@@ -489,7 +489,7 @@ export function NitroEditorDialog({
|
|||||||
<section className="rounded-lg border bg-card p-4">
|
<section className="rounded-lg border bg-card p-4">
|
||||||
<div className="flex items-center gap-2 mb-3">
|
<div className="flex items-center gap-2 mb-3">
|
||||||
<Compass className="w-4 h-4 text-muted-foreground" />
|
<Compass className="w-4 h-4 text-muted-foreground" />
|
||||||
<h3 className="text-sm font-medium">Direzioni</h3>
|
<h3 className="text-sm font-medium">Directions</h3>
|
||||||
<span className="text-xs text-muted-foreground ml-auto">
|
<span className="text-xs text-muted-foreground ml-auto">
|
||||||
{directions.length} attive
|
{directions.length} attive
|
||||||
</span>
|
</span>
|
||||||
@@ -784,7 +784,7 @@ export function NitroEditorDialog({
|
|||||||
variant="secondary"
|
variant="secondary"
|
||||||
className="text-[10px] gap-1 animate-[pulse_1s_ease-in-out_1]"
|
className="text-[10px] gap-1 animate-[pulse_1s_ease-in-out_1]"
|
||||||
>
|
>
|
||||||
Modifiche non salvate
|
Unsaved changes
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
<div className="flex-1" />
|
<div className="flex-1" />
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
deleteRoomItem,
|
deleteRoomItem,
|
||||||
roomRconAction,
|
roomRconAction,
|
||||||
} from "@/actions/rooms";
|
} from "@/actions/rooms";
|
||||||
|
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 { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
@@ -91,6 +92,7 @@ function isWallType(t: string) {
|
|||||||
|
|
||||||
export function FurniClient({ room, items = [], canEdit }: Props) {
|
export function FurniClient({ room, items = [], canEdit }: Props) {
|
||||||
const { run, isPending } = useServerAction();
|
const { run, isPending } = useServerAction();
|
||||||
|
const { confirm, dialog: confirmDialog } = useConfirmDialog();
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [view, setView] = useState<View>("flat");
|
const [view, setView] = useState<View>("flat");
|
||||||
@@ -231,29 +233,44 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
|
|||||||
setSelected(next);
|
setSelected(next);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleRcon(action: "reload" | "kick") {
|
async function handleRcon(action: "reload" | "kick") {
|
||||||
if (action === "kick" && !confirm("Kick all users from this room?")) return;
|
if (action === "kick") {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "Kick Users",
|
||||||
|
description: "Kick all users from this room?",
|
||||||
|
confirmLabel: "Kick",
|
||||||
|
variant: "danger",
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
run(() => roomRconAction({ roomId: room.id, action }), {
|
run(() => roomRconAction({ roomId: room.id, action }), {
|
||||||
successMessage:
|
successMessage:
|
||||||
action === "reload" ? "Room reloaded" : "All users kicked",
|
action === "reload" ? "Room reloaded" : "All users kicked",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleDelete(itemId: number, name: string) {
|
async function handleDelete(itemId: number, name: string) {
|
||||||
if (!confirm(`Delete "${name}" (#${itemId}) from this room?`)) return;
|
const ok = await confirm({
|
||||||
|
title: "Delete Item",
|
||||||
|
description: `Delete "${name}" (#${itemId}) from this room?`,
|
||||||
|
confirmLabel: "Delete",
|
||||||
|
variant: "danger",
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
run(() => deleteRoomItem({ roomId: room.id, itemId }), {
|
run(() => deleteRoomItem({ roomId: room.id, itemId }), {
|
||||||
successMessage: "Item deleted",
|
successMessage: "Item deleted",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleBulkDelete() {
|
async function handleBulkDelete() {
|
||||||
if (selected.size === 0) return;
|
if (selected.size === 0) return;
|
||||||
if (
|
const ok = await confirm({
|
||||||
!confirm(
|
title: "Delete Items",
|
||||||
`Delete ${selected.size} selected item${selected.size > 1 ? "s" : ""}?`,
|
description: `Delete ${selected.size} selected item${selected.size > 1 ? "s" : ""}?`,
|
||||||
)
|
confirmLabel: "Delete",
|
||||||
)
|
variant: "danger",
|
||||||
return;
|
});
|
||||||
|
if (!ok) return;
|
||||||
run(
|
run(
|
||||||
() =>
|
() =>
|
||||||
bulkDeleteRoomItems({ roomId: room.id, itemIds: Array.from(selected) }),
|
bulkDeleteRoomItems({ roomId: room.id, itemIds: Array.from(selected) }),
|
||||||
@@ -264,8 +281,18 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleDeleteGroup(_baseId: number, ids: number[], name: string) {
|
async function handleDeleteGroup(
|
||||||
if (!confirm(`Delete all ${ids.length} "${name}" from this room?`)) return;
|
_baseId: number,
|
||||||
|
ids: number[],
|
||||||
|
name: string,
|
||||||
|
) {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "Delete Items",
|
||||||
|
description: `Delete all ${ids.length} "${name}" from this room?`,
|
||||||
|
confirmLabel: "Delete",
|
||||||
|
variant: "danger",
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
run(() => bulkDeleteRoomItems({ roomId: room.id, itemIds: ids }), {
|
run(() => bulkDeleteRoomItems({ roomId: room.id, itemIds: ids }), {
|
||||||
successMessage: `${ids.length} item(s) deleted`,
|
successMessage: `${ids.length} item(s) deleted`,
|
||||||
});
|
});
|
||||||
@@ -276,6 +303,7 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
{confirmDialog}
|
||||||
{/* ── Header ─────────────────────────────────────────── */}
|
{/* ── Header ─────────────────────────────────────────── */}
|
||||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { deleteRoom, roomRconAction, updateRoom } from "@/actions/rooms";
|
import { deleteRoom, roomRconAction, updateRoom } from "@/actions/rooms";
|
||||||
|
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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
@@ -63,13 +64,17 @@ export function RoomEditForm({ room }: RoomEditFormProps) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleDelete() {
|
const { confirm, dialog: confirmDialog } = useConfirmDialog();
|
||||||
if (
|
|
||||||
!confirm(
|
async function handleDelete() {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "Delete Room",
|
||||||
|
description:
|
||||||
"Are you sure you want to delete this room? This cannot be undone.",
|
"Are you sure you want to delete this room? This cannot be undone.",
|
||||||
)
|
confirmLabel: "Delete",
|
||||||
)
|
variant: "danger",
|
||||||
return;
|
});
|
||||||
|
if (!ok) return;
|
||||||
run(() => deleteRoom({ id: room.id }), { redirectTo: "/admin/rooms" });
|
run(() => deleteRoom({ id: room.id }), { redirectTo: "/admin/rooms" });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,6 +87,7 @@ export function RoomEditForm({ room }: RoomEditFormProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{confirmDialog}
|
||||||
<div className="grid gap-6 lg:grid-cols-2">
|
<div className="grid gap-6 lg:grid-cols-2">
|
||||||
{/* Edit Form */}
|
{/* Edit Form */}
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
@@ -271,7 +271,7 @@ export function SoundsClient({
|
|||||||
onEnded={() => setPlayingId(null)}
|
onEnded={() => setPlayingId(null)}
|
||||||
onError={() =>
|
onError={() =>
|
||||||
toast.error(
|
toast.error(
|
||||||
`Impossibile riprodurre "${s.code}.mp3" da ${baseUrl}.`,
|
`Failed to play "${s.code}.mp3" from ${baseUrl}.`,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ export function TraxPlayer({
|
|||||||
|
|
||||||
const AudioCtor = window.AudioContext;
|
const AudioCtor = window.AudioContext;
|
||||||
if (!AudioCtor) {
|
if (!AudioCtor) {
|
||||||
toast.error("Web Audio API non supportata da questo browser.");
|
toast.error("Web Audio API is not supported by this browser.");
|
||||||
setStatus("error");
|
setStatus("error");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -137,7 +137,7 @@ export function TraxPlayer({
|
|||||||
|
|
||||||
if (failed > 0) {
|
if (failed > 0) {
|
||||||
toast.warning(
|
toast.warning(
|
||||||
`${failed}/${uniqueIds.length} sample non caricati — la riproduzione potrebbe avere buchi.`,
|
`${failed}/${uniqueIds.length} samples failed to load — playback may have gaps.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (failed === uniqueIds.length) {
|
if (failed === uniqueIds.length) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { and, asc, count, like, or, type SQL } from "drizzle-orm";
|
import { and, asc, count, like, or, type SQL, sql } from "drizzle-orm";
|
||||||
import { ExternalLink } from "lucide-react";
|
import { ExternalLink } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { getTranslations } from "next-intl/server";
|
import { getTranslations } from "next-intl/server";
|
||||||
@@ -34,10 +34,12 @@ export default async function EmulatorTranslationsPage({
|
|||||||
const perPage = Math.min(Math.max(parseInt(sp.perPage || "50", 10), 10), 200);
|
const perPage = Math.min(Math.max(parseInt(sp.perPage || "50", 10), 10), 200);
|
||||||
const page = Math.max(parseInt(sp.page || "1", 10), 1);
|
const page = Math.max(parseInt(sp.page || "1", 10), 1);
|
||||||
|
|
||||||
const patternFilters = or(
|
const patternFilters =
|
||||||
...TRANSLATION_KEY_PATTERNS.map((p) => like(EmulatorSettings.key, `${p}%`)),
|
or(
|
||||||
);
|
...TRANSLATION_KEY_PATTERNS.map((p) =>
|
||||||
if (!patternFilters) throw new Error("No emulator translation key patterns");
|
like(EmulatorSettings.key, `${p}%`),
|
||||||
|
),
|
||||||
|
) ?? sql`1=0`;
|
||||||
|
|
||||||
const conditions: SQL[] = [patternFilters];
|
const conditions: SQL[] = [patternFilters];
|
||||||
if (group) conditions.push(like(EmulatorSettings.key, `${group}.%`));
|
if (group) conditions.push(like(EmulatorSettings.key, `${group}.%`));
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { sql } from "drizzle-orm";
|
|||||||
import { withAdmin } from "@/lib/api-handler";
|
import { withAdmin } from "@/lib/api-handler";
|
||||||
import { apiError } from "@/lib/api-response";
|
import { apiError } from "@/lib/api-response";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { PERMS } from "@/lib/permission-slugs";
|
import { PERMS } from "@/lib/permissions";
|
||||||
|
|
||||||
const VALID_REPORTS = new Set(["registrations", "online-by-hour", "economy"]);
|
const VALID_REPORTS = new Set(["registrations", "online-by-hour", "economy"]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,34 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { fetchOpsHealth } from "@/lib/admin/ops-health";
|
import { fetchOpsHealth } from "@/lib/admin/ops-health";
|
||||||
import { withAdmin } from "@/lib/api-handler";
|
import { withAdmin } from "@/lib/api-handler";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
|
|
||||||
export const GET = withAdmin({ permission: PERMS.DEVOPS_VIEW }, async () => {
|
export const GET = withAdmin({ permission: PERMS.DEVOPS_VIEW }, async () => {
|
||||||
const health = await fetchOpsHealth();
|
try {
|
||||||
|
const health = await fetchOpsHealth();
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
database: health.dbOk,
|
database: health.dbOk,
|
||||||
dbLatency: health.dbLatencyMs,
|
dbLatency: health.dbLatencyMs,
|
||||||
redis: health.redisOk,
|
redis: health.redisOk,
|
||||||
emulator: health.emulatorOk,
|
emulator: health.emulatorOk,
|
||||||
onlineUsers: health.onlineUsers,
|
onlineUsers: health.onlineUsers,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
});
|
});
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("Health check failed", { err });
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
database: false,
|
||||||
|
dbLatency: null,
|
||||||
|
redis: false,
|
||||||
|
emulator: false,
|
||||||
|
onlineUsers: 0,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
error: "Health check partially failed",
|
||||||
|
},
|
||||||
|
{ status: 503 },
|
||||||
|
);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { withAdmin } from "@/lib/api-handler";
|
import { withAdmin } from "@/lib/api-handler";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { runCatalogAudit } from "@/lib/services/catalog-audit";
|
import { runCatalogAudit } from "@/lib/services/catalog-audit";
|
||||||
|
|
||||||
@@ -32,8 +33,8 @@ export const POST = withAdmin(
|
|||||||
applySql = body.applySql === true;
|
applySql = body.applySql === true;
|
||||||
repairFurniData = body.repairFurniData === true;
|
repairFurniData = body.repairFurniData === true;
|
||||||
repairStructure = body.repairStructure === true;
|
repairStructure = body.repairStructure === true;
|
||||||
} catch {
|
} catch (err) {
|
||||||
/* no body */
|
logger.warn("Failed to parse audit request body", { err });
|
||||||
}
|
}
|
||||||
|
|
||||||
const stream = new ReadableStream({
|
const stream = new ReadableStream({
|
||||||
@@ -64,8 +65,8 @@ export const POST = withAdmin(
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
controller.close();
|
controller.close();
|
||||||
} catch {
|
} catch (err) {
|
||||||
/* ignore */
|
logger.warn("Failed to close audit SSE stream", { err });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,6 +7,15 @@ import { getSource } from "@/lib/services/clone-sources";
|
|||||||
// In-process cache of extracted icons, keyed by source+classname.
|
// In-process cache of extracted icons, keyed by source+classname.
|
||||||
// null = known-missing (don't refetch the bundle every render).
|
// null = known-missing (don't refetch the bundle every render).
|
||||||
const iconCache = new Map<string, Buffer | null>();
|
const iconCache = new Map<string, Buffer | null>();
|
||||||
|
const MAX_ICON_CACHE_SIZE = 500;
|
||||||
|
|
||||||
|
function pruneIconCache() {
|
||||||
|
while (iconCache.size > MAX_ICON_CACHE_SIZE) {
|
||||||
|
const oldest = iconCache.keys().next().value;
|
||||||
|
if (oldest === undefined) break;
|
||||||
|
iconCache.delete(oldest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// GET ?source=<id>&classname=<cn>
|
// GET ?source=<id>&classname=<cn>
|
||||||
// Fetches the source's .nitro bundle and returns the embedded furni icon as a
|
// Fetches the source's .nitro bundle and returns the embedded furni icon as a
|
||||||
@@ -39,6 +48,7 @@ export const GET = withAdmin(
|
|||||||
}
|
}
|
||||||
icon = extractFurniIconPng(Buffer.from(await res.arrayBuffer()));
|
icon = extractFurniIconPng(Buffer.from(await res.arrayBuffer()));
|
||||||
iconCache.set(cacheKey, icon);
|
iconCache.set(cacheKey, icon);
|
||||||
|
pruneIconCache();
|
||||||
} catch {
|
} catch {
|
||||||
iconCache.set(cacheKey, null);
|
iconCache.set(cacheKey, null);
|
||||||
return apiError("Failed to fetch bundle", 502);
|
return apiError("Failed to fetch bundle", 502);
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export const GET = withAdmin(
|
|||||||
{ permission: PERMS.ASSETS_IMPORT },
|
{ permission: PERMS.ASSETS_IMPORT },
|
||||||
async (request) => {
|
async (request) => {
|
||||||
if (request.nextUrl.searchParams.get("action") === "stats")
|
if (request.nextUrl.searchParams.get("action") === "stats")
|
||||||
return apiOk(getPetStats());
|
return apiOk(await getPetStats());
|
||||||
const search = request.nextUrl.searchParams.get("search") || "";
|
const search = request.nextUrl.searchParams.get("search") || "";
|
||||||
return apiOk({ pets: getPetList(search) });
|
return apiOk({ pets: getPetList(search) });
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -14,9 +14,7 @@ export const GET = withAdmin({ permission: PERMS.PREFIXES_VIEW }, async () => {
|
|||||||
sql`SELECT id, word FROM custom_prefix_blacklist ORDER BY word ASC`,
|
sql`SELECT id, word FROM custom_prefix_blacklist ORDER BY word ASC`,
|
||||||
)) as unknown as [BlacklistWord[], unknown];
|
)) as unknown as [BlacklistWord[], unknown];
|
||||||
|
|
||||||
return apiOk({
|
return apiOk({ words });
|
||||||
words: words.map((w) => ({ ...w, created_at: "" })),
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const POST = withAdmin(
|
export const POST = withAdmin(
|
||||||
|
|||||||
@@ -52,7 +52,6 @@ export const GET = withAdmin(
|
|||||||
icon: p.icon || "",
|
icon: p.icon || "",
|
||||||
effect: p.effect || "",
|
effect: p.effect || "",
|
||||||
active: Boolean(p.active),
|
active: Boolean(p.active),
|
||||||
created_at: "",
|
|
||||||
})),
|
})),
|
||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { desc, eq } from "drizzle-orm";
|
||||||
|
import { withAdmin } from "@/lib/api-handler";
|
||||||
|
import { apiError, apiOk } from "@/lib/api-response";
|
||||||
|
import { db, Soundtracks } from "@/lib/db";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
|
import { PERMS } from "@/lib/permissions";
|
||||||
|
import {
|
||||||
|
extractMp3Duration,
|
||||||
|
getSoundtrackPath,
|
||||||
|
isSafeSoundtrackCode,
|
||||||
|
MAX_SOUNDTRACK_SIZE,
|
||||||
|
validateMp3Bytes,
|
||||||
|
writeSoundtrackFile,
|
||||||
|
} from "@/lib/services/soundtracks";
|
||||||
|
|
||||||
|
export const POST = withAdmin(
|
||||||
|
{ permission: PERMS.CATALOG_EDIT, requireCsrf: true },
|
||||||
|
async (request) => {
|
||||||
|
const formData = await request.formData();
|
||||||
|
const file = formData.get("file");
|
||||||
|
const name = String(formData.get("name") ?? "").trim();
|
||||||
|
const author = String(formData.get("author") ?? "").trim();
|
||||||
|
|
||||||
|
if (!(file instanceof File)) {
|
||||||
|
return apiError("No file uploaded", 400);
|
||||||
|
}
|
||||||
|
if (!name) {
|
||||||
|
return apiError("Name is required", 400);
|
||||||
|
}
|
||||||
|
if (file.size > MAX_SOUNDTRACK_SIZE) {
|
||||||
|
return apiError("File exceeds 10 MB limit", 413);
|
||||||
|
}
|
||||||
|
if (file.size === 0) {
|
||||||
|
return apiError("File is empty", 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buf = Buffer.from(await file.arrayBuffer());
|
||||||
|
if (!validateMp3Bytes(buf)) {
|
||||||
|
return apiError("File is not a valid MP3", 415);
|
||||||
|
}
|
||||||
|
|
||||||
|
const duration = await extractMp3Duration(buf);
|
||||||
|
|
||||||
|
const maxRow = await db
|
||||||
|
.select({ maxId: Soundtracks.id })
|
||||||
|
.from(Soundtracks)
|
||||||
|
.orderBy(desc(Soundtracks.id))
|
||||||
|
.limit(1)
|
||||||
|
.then((rows) => rows[0]?.maxId ?? 0)
|
||||||
|
.catch(() => 0);
|
||||||
|
|
||||||
|
const nextId = maxRow + 1;
|
||||||
|
const code = `song_${nextId}`;
|
||||||
|
|
||||||
|
if (!isSafeSoundtrackCode(code)) {
|
||||||
|
return apiError("Generated code is invalid", 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await db
|
||||||
|
.select({ id: Soundtracks.id })
|
||||||
|
.from(Soundtracks)
|
||||||
|
.where(eq(Soundtracks.code, code))
|
||||||
|
.limit(1)
|
||||||
|
.catch(() => null);
|
||||||
|
|
||||||
|
if (existing && existing.length > 0) {
|
||||||
|
return apiError("Song code already exists", 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
await writeSoundtrackFile(code, buf);
|
||||||
|
|
||||||
|
let id: number;
|
||||||
|
try {
|
||||||
|
const result = await db.insert(Soundtracks).values({
|
||||||
|
code,
|
||||||
|
name: name.slice(0, 100),
|
||||||
|
author: author.slice(0, 50),
|
||||||
|
track: "",
|
||||||
|
length: duration,
|
||||||
|
});
|
||||||
|
id = Number(result[0].insertId);
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("Failed to insert soundtrack record", { err, code });
|
||||||
|
try {
|
||||||
|
await fs.unlink(getSoundtrackPath(code));
|
||||||
|
} catch {
|
||||||
|
/* ignore cleanup failure */
|
||||||
|
}
|
||||||
|
return apiError("Failed to save soundtrack", 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
return apiOk({ ok: true, id, code });
|
||||||
|
},
|
||||||
|
);
|
||||||
Reference in new issue
Block a user