Reapply "Add missing admin action files and navigation links"

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

No files matched your search

+12 -11
View File
@@ -8,12 +8,12 @@ Features full public-facing website, administrative panel, NextAuth authenticati
## Requirements
| Component | Version |
|---|---|
| Node.js | >= 22 |
| pnpm | >= 10.33.4 |
| MySQL / MariaDB | 8.0+ / 10.6+ |
| Redis | Optional (caching / rate limiting) |
| Component | Version |
| --------------- | ---------------------------------- |
| Node.js | >= 22 |
| pnpm | >= 10.33.4 |
| MySQL / MariaDB | 8.0+ / 10.6+ |
| Redis | Optional (caching / rate limiting) |
---
@@ -240,6 +240,7 @@ pnpm jobs:worker
```
Scheduled tasks:
- **Daily at 03:00** — Emulator JAR backup (when `EMULATOR_JAR_PATH` and `EMULATOR_BACKUP_DIR` are configured)
- **Daily at 04:00** — Cleanup of login logs older than 30 days and expired password reset tokens older than 7 days
@@ -288,11 +289,11 @@ Supports Cloudflare Turnstile and Google reCAPTCHA. Configure via **Admin → CM
## Database Architecture
| Component | Type | Migrations |
|---|---|---|
| Emulator tables (`users`, `items`, `rooms`, etc.) | Existing Polaris schema | None — read-only for CMS |
| CMS tables (`website_*`, `radio_*`, etc.) | CMS-owned | `prisma/migrations/*.sql` (9 files) |
| Migration tracking | `cms_migrations` table | Auto-created |
| Component | Type | Migrations |
| ------------------------------------------------- | ----------------------- | ----------------------------------- |
| Emulator tables (`users`, `items`, `rooms`, etc.) | Existing Polaris schema | None — read-only for CMS |
| CMS tables (`website_*`, `radio_*`, etc.) | CMS-owned | `prisma/migrations/*.sql` (9 files) |
| Migration tracking | `cms_migrations` table | Auto-created |
---
+1 -5
View File
@@ -25,10 +25,7 @@ export default tseslint.config(
"no-console": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"warn",
{ argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
],
"@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/no-non-null-assertion": "warn",
@@ -42,7 +39,6 @@ export default tseslint.config(
"security/detect-object-injection": "warn",
"security/detect-non-literal-fs-filename": "warn",
},
},
{
+3 -7
View File
@@ -52,15 +52,11 @@ const nextConfig: NextConfig = {
},
{
source: "/assets/(.*)",
headers: [
{ key: "Cache-Control", value: "public, max-age=31536000, immutable" },
],
headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }],
},
{
source: "/images/(.*)",
headers: [
{ key: "Cache-Control", value: "public, max-age=86400" },
],
headers: [{ key: "Cache-Control", value: "public, max-age=86400" }],
},
];
},
@@ -70,4 +66,4 @@ const nextConfig: NextConfig = {
// src/i18n/request.ts, so URLs and the access-guard middleware stay unchanged.
const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");
export default withNextIntl(nextConfig);
export default withNextIntl(nextConfig);
+6 -1
View File
@@ -72,6 +72,11 @@
"prisma",
"@prisma/client",
"@prisma/engines"
]
],
"overrides": {
"fast-uri": "^3.1.3",
"@hono/node-server": "^1.19.13",
"postcss": "^8.5.16"
}
}
}
+4588 -2421
View File
File diff suppressed because it is too large. Load diff
+7 -7
View File
@@ -5,12 +5,8 @@
"version": "1.0.0",
"description": "Public and administrative REST API for the AtomCMS-Next Habbo retro hotel CMS."
},
"servers": [
{ "url": "/api", "description": "Local API" }
],
"security": [
{ "bearerAuth": [], "sessionAuth": [] }
],
"servers": [{ "url": "/api", "description": "Local API" }],
"security": [{ "bearerAuth": [], "sessionAuth": [] }],
"components": {
"securitySchemes": {
"bearerAuth": {
@@ -54,7 +50,11 @@
"responses": {
"200": {
"description": "Online count",
"content": { "application/json": { "schema": { "type": "object", "properties": { "count": { "type": "integer" } } } } }
"content": {
"application/json": {
"schema": { "type": "object", "properties": { "count": { "type": "integer" } } }
}
}
}
}
}
+10 -10
View File
@@ -1,12 +1,12 @@
(function(){
(function () {
try {
var s=localStorage.getItem('theme');
var dd=document.querySelector('meta[name="theme-default-dark"]');
var defaultDark=dd?dd.getAttribute('content')==='true':false;
if(s==='dark'||(!s&&defaultDark))document.documentElement.classList.add('dark');
var nc=localStorage.getItem('navbarColor'),
nt=localStorage.getItem('navbarTextColor');
if(nc)document.documentElement.style.setProperty('--color-navbar',nc);
if(nt)document.documentElement.style.setProperty('--color-navbar-text',nt);
}catch(e){}
var s = localStorage.getItem("theme");
var dd = document.querySelector('meta[name="theme-default-dark"]');
var defaultDark = dd ? dd.getAttribute("content") === "true" : false;
if (s === "dark" || (!s && defaultDark)) document.documentElement.classList.add("dark");
var nc = localStorage.getItem("navbarColor"),
nt = localStorage.getItem("navbarTextColor");
if (nc) document.documentElement.style.setProperty("--color-navbar", nc);
if (nt) document.documentElement.style.setProperty("--color-navbar-text", nt);
} catch (e) {}
})();
+4 -1
View File
@@ -45,7 +45,10 @@ self.addEventListener("fetch", (event) => {
fetch(req)
.then((res) => {
const copy = res.clone();
caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {});
caches
.open(CACHE)
.then((c) => c.put(req, copy))
.catch(() => {});
return res;
})
.catch(() => caches.match(req).then((hit) => hit || caches.match("/"))),
+2 -7
View File
@@ -41,9 +41,7 @@ async function getApplied(): Promise<Set<string>> {
const mysql = await import("mysql2/promise");
const conn = await mysql.createConnection(url);
try {
const [rows] = await conn.execute(
`SELECT migration FROM \`${TRACKING_TABLE}\` ORDER BY id`,
);
const [rows] = await conn.execute(`SELECT migration FROM \`${TRACKING_TABLE}\` ORDER BY id`);
return new Set((rows as { migration: string }[]).map((r) => r.migration));
} catch {
return new Set();
@@ -79,10 +77,7 @@ async function apply(migration: MigrationFile): Promise<void> {
await conn.execute(stmt);
}
await conn.execute(
`INSERT INTO \`${TRACKING_TABLE}\` (migration) VALUES (?)`,
[migration.id],
);
await conn.execute(`INSERT INTO \`${TRACKING_TABLE}\` (migration) VALUES (?)`, [migration.id]);
console.log(`[migrate] Applied: ${migration.name}`);
} finally {
await conn.end();
+5 -3
View File
@@ -29,7 +29,9 @@ function decryptCbc(payload: string, key: Buffer, serialize = true): string {
value: string;
mac: string;
};
const expected = createHmac("sha256", key).update(json.iv + json.value).digest("hex");
const expected = createHmac("sha256", key)
.update(json.iv + json.value)
.digest("hex");
const a = Buffer.from(expected, "hex");
const b = Buffer.from(json.mac, "hex");
if (a.length !== b.length || !timingSafeEqual(a, b)) {
@@ -59,8 +61,8 @@ function isAlreadyGcm(payload: string, key: Buffer): boolean {
try {
const json = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
if (!json.tag && !json.mac) return false; // can't determine format
if (json.tag) return true; // has authTag => GCM
return false; // has mac => CBC
if (json.tag) return true; // has authTag => GCM
return false; // has mac => CBC
} catch {
return false;
}
+6 -2
View File
@@ -12,7 +12,9 @@ import { formPositiveBigInt } from "@/lib/form-data";
export async function createAd(formData: FormData): Promise<void> {
const staff = await requireStaff();
const image = String(formData.get("image") ?? "").trim().slice(0, 255);
const image = String(formData.get("image") ?? "")
.trim()
.slice(0, 255);
if (!image) return;
const now = new Date();
@@ -40,7 +42,9 @@ export async function updateAd(formData: FormData): Promise<void> {
const raw = String(formData.get("id") ?? "");
if (!/^\d+$/.test(raw)) return;
const id = BigInt(raw);
const image = String(formData.get("image") ?? "").trim().slice(0, 255);
const image = String(formData.get("image") ?? "")
.trim()
.slice(0, 255);
if (!image) return;
try {
+3 -1
View File
@@ -13,7 +13,9 @@ import { rcon } from "@/lib/services/rcon";
export async function sendHotelAlert(formData: FormData): Promise<void> {
await requireStaff();
const message = String(formData.get("message") ?? "").trim().slice(0, 1000);
const message = String(formData.get("message") ?? "")
.trim()
.slice(0, 1000);
if (!message) return;
try {
+9 -3
View File
@@ -53,10 +53,16 @@ export async function updateArticle(formData: FormData): Promise<void> {
await prisma.websiteArticles.update({
where: { id },
data: {
title: String(formData.get("title") ?? "").trim().slice(0, 255),
shortStory: String(formData.get("shortStory") ?? "").trim().slice(0, 255),
title: String(formData.get("title") ?? "")
.trim()
.slice(0, 255),
shortStory: String(formData.get("shortStory") ?? "")
.trim()
.slice(0, 255),
fullStory: String(formData.get("fullStory") ?? "").trim(),
image: String(formData.get("image") ?? "").trim().slice(0, 255),
image: String(formData.get("image") ?? "")
.trim()
.slice(0, 255),
updatedAt: new Date(),
},
});
+3 -1
View File
@@ -9,7 +9,9 @@ export async function giveBadge(formData: FormData): Promise<void> {
await requireStaff();
const userId = Number(formData.get("userId"));
const code = String(formData.get("code") ?? "").trim().slice(0, 32);
const code = String(formData.get("code") ?? "")
.trim()
.slice(0, 32);
if (!(userId > 0) || code.length === 0) return;
// Fire the emulator command so the badge appears live for online users.
+4 -1
View File
@@ -14,7 +14,10 @@ const PERMANENT_SECONDS = 100 * 365 * 24 * 3600;
export async function createBan(formData: FormData): Promise<void> {
const staff = await requireStaff();
const userId = Number(formData.get("userId"));
const reason = String(formData.get("reason") ?? "").trim().slice(0, 200) || "Banned";
const reason =
String(formData.get("reason") ?? "")
.trim()
.slice(0, 200) || "Banned";
const hours = Number(formData.get("hours"));
const type = String(formData.get("type"));
if (!(userId > 0) || !BAN_TYPES.has(type)) return;
+9 -3
View File
@@ -7,8 +7,12 @@ import { formPositiveBigInt } from "@/lib/form-data";
export async function createEmailTemplate(formData: FormData): Promise<void> {
await requireStaff();
const name = String(formData.get("name") ?? "").trim().slice(0, 255);
const subject = String(formData.get("subject") ?? "").trim().slice(0, 255);
const name = String(formData.get("name") ?? "")
.trim()
.slice(0, 255);
const subject = String(formData.get("subject") ?? "")
.trim()
.slice(0, 255);
const body = String(formData.get("body") ?? "");
const variablesRaw = String(formData.get("variables") ?? "").trim();
const isActive = formData.get("isActive") != null;
@@ -36,7 +40,9 @@ export async function updateEmailTemplate(formData: FormData): Promise<void> {
} catch {
return;
}
const subject = String(formData.get("subject") ?? "").trim().slice(0, 255);
const subject = String(formData.get("subject") ?? "")
.trim()
.slice(0, 255);
const body = String(formData.get("body") ?? "");
const variablesRaw = String(formData.get("variables") ?? "").trim();
const isActive = formData.get("isActive") != null;
+6 -2
View File
@@ -11,7 +11,9 @@ import { prisma } from "@/lib/prisma";
export async function updateEmulatorSetting(formData: FormData): Promise<void> {
await requireStaff();
const key = String(formData.get("key") ?? "").trim().slice(0, 100);
const key = String(formData.get("key") ?? "")
.trim()
.slice(0, 100);
const value = String(formData.get("value") ?? "").slice(0, 512);
if (!key) return;
await prisma.emulatorSettings.upsert({
@@ -24,7 +26,9 @@ export async function updateEmulatorSetting(formData: FormData): Promise<void> {
export async function updateEmulatorText(formData: FormData): Promise<void> {
await requireStaff();
const key = String(formData.get("key") ?? "").trim().slice(0, 100);
const key = String(formData.get("key") ?? "")
.trim()
.slice(0, 100);
const value = String(formData.get("value") ?? "").slice(0, 4096);
if (!key) return;
await prisma.emulatorTexts.upsert({
+38 -12
View File
@@ -17,16 +17,29 @@ function parsePosition(value: FormDataEntryValue | null): number {
export async function createHelpQuestion(formData: FormData): Promise<void> {
const staff = await requireStaff();
const name = String(formData.get("name") ?? "").trim().slice(0, 255);
const name = String(formData.get("name") ?? "")
.trim()
.slice(0, 255);
const content = String(formData.get("content") ?? "").trim();
if (!name || !content) return;
const imageUrl = String(formData.get("imageUrl") ?? "").trim().slice(0, 255);
const buttonText = String(formData.get("buttonText") ?? "").trim().slice(0, 255);
const buttonUrl = String(formData.get("buttonUrl") ?? "").trim().slice(0, 255);
const buttonColor = String(formData.get("buttonColor") ?? "").trim().slice(0, 16) || "#eeb425";
const imageUrl = String(formData.get("imageUrl") ?? "")
.trim()
.slice(0, 255);
const buttonText = String(formData.get("buttonText") ?? "")
.trim()
.slice(0, 255);
const buttonUrl = String(formData.get("buttonUrl") ?? "")
.trim()
.slice(0, 255);
const buttonColor =
String(formData.get("buttonColor") ?? "")
.trim()
.slice(0, 16) || "#eeb425";
const buttonBorderColor =
String(formData.get("buttonBorderColor") ?? "").trim().slice(0, 16) || "#facc15";
String(formData.get("buttonBorderColor") ?? "")
.trim()
.slice(0, 16) || "#facc15";
try {
const entry = await prisma.websiteHelpCenterCategories.create({
@@ -63,16 +76,29 @@ export async function updateHelpQuestion(formData: FormData): Promise<void> {
const id = formPositiveBigInt(formData, "id");
if (!id) return;
const name = String(formData.get("name") ?? "").trim().slice(0, 255);
const name = String(formData.get("name") ?? "")
.trim()
.slice(0, 255);
const content = String(formData.get("content") ?? "").trim();
if (!name || !content) return;
const imageUrl = String(formData.get("imageUrl") ?? "").trim().slice(0, 255);
const buttonText = String(formData.get("buttonText") ?? "").trim().slice(0, 255);
const buttonUrl = String(formData.get("buttonUrl") ?? "").trim().slice(0, 255);
const buttonColor = String(formData.get("buttonColor") ?? "").trim().slice(0, 16) || "#eeb425";
const imageUrl = String(formData.get("imageUrl") ?? "")
.trim()
.slice(0, 255);
const buttonText = String(formData.get("buttonText") ?? "")
.trim()
.slice(0, 255);
const buttonUrl = String(formData.get("buttonUrl") ?? "")
.trim()
.slice(0, 255);
const buttonColor =
String(formData.get("buttonColor") ?? "")
.trim()
.slice(0, 16) || "#eeb425";
const buttonBorderColor =
String(formData.get("buttonBorderColor") ?? "").trim().slice(0, 16) || "#facc15";
String(formData.get("buttonBorderColor") ?? "")
.trim()
.slice(0, 16) || "#facc15";
try {
await prisma.websiteHelpCenterCategories.update({
+6 -2
View File
@@ -11,9 +11,13 @@ import { prisma } from "@/lib/prisma";
export async function upsertPermission(formData: FormData): Promise<void> {
await requireStaff();
const permission = String(formData.get("permission") ?? "").trim().slice(0, 255);
const permission = String(formData.get("permission") ?? "")
.trim()
.slice(0, 255);
const minRank = Number(formData.get("minRank"));
const descriptionRaw = String(formData.get("description") ?? "").trim().slice(0, 255);
const descriptionRaw = String(formData.get("description") ?? "")
.trim()
.slice(0, 255);
const description = descriptionRaw.length > 0 ? descriptionRaw : null;
if (!permission || !Number.isFinite(minRank) || minRank < 0) return;
+6 -2
View File
@@ -5,11 +5,15 @@ import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
function parseIp(formData: FormData): string {
return String(formData.get("ipAddress") ?? "").trim().slice(0, 255);
return String(formData.get("ipAddress") ?? "")
.trim()
.slice(0, 255);
}
function parseAsn(formData: FormData): string | null {
const asn = String(formData.get("asn") ?? "").trim().slice(0, 255);
const asn = String(formData.get("asn") ?? "")
.trim()
.slice(0, 255);
return asn || null;
}
+2 -4
View File
@@ -19,10 +19,8 @@ const KEY_MIN_RANK = "min_maintenance_login_rank";
const COMMENTS: Record<string, string> = {
[KEY_ENABLED]: "Determines whether maintenance is enabled or not",
[KEY_MESSAGE]:
"The maintenance message displayed to users while maintenance is activated",
[KEY_MIN_RANK]:
"The minimum rank required to login to the hotel during maintenance",
[KEY_MESSAGE]: "The maintenance message displayed to users while maintenance is activated",
[KEY_MIN_RANK]: "The minimum rank required to login to the hotel during maintenance",
};
async function upsertSetting(key: string, value: string): Promise<void> {
+2 -2
View File
@@ -13,8 +13,8 @@ export async function uploadMedia(formData: FormData): Promise<void> {
await requireStaff();
const file = formData.get("file") as File | null;
if (!file || file.size === 0) return;
if (file.size > MAX_SIZE) throw new Error("File too large (max 5MB)");
if (!ALLOWED.includes(file.type)) throw new Error("Invalid file type");
if (file.size > MAX_SIZE) return;
if (!ALLOWED.includes(file.type)) return;
const baseDir = path.resolve(process.cwd(), MEDIA_DIR);
// eslint-disable-next-line security/detect-non-literal-fs-filename
+6 -2
View File
@@ -20,7 +20,9 @@ function parseMinRank(formData: FormData): number {
export async function createPermission(formData: FormData): Promise<void> {
const staff = await requireStaff();
const permission = String(formData.get("permission") ?? "").trim().slice(0, 255);
const permission = String(formData.get("permission") ?? "")
.trim()
.slice(0, 255);
const minRank = parseMinRank(formData);
const description = String(formData.get("description") ?? "").trim() || null;
if (!permission) return;
@@ -52,7 +54,9 @@ export async function updatePermission(formData: FormData): Promise<void> {
const raw = String(formData.get("id") ?? "");
if (!raw) return;
const id = BigInt(raw);
const permission = String(formData.get("permission") ?? "").trim().slice(0, 255);
const permission = String(formData.get("permission") ?? "")
.trim()
.slice(0, 255);
const minRank = parseMinRank(formData);
const description = String(formData.get("description") ?? "").trim() || null;
if (!permission) return;
+30 -30
View File
@@ -1,9 +1,9 @@
'use server';
"use server";
import { revalidatePath } from 'next/cache';
import { requireStaff } from '@/lib/admin/guard';
import { prisma } from '@/lib/prisma';
import { logStaffActivity } from '@/lib/services/staff-activity';
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { logStaffActivity } from "@/lib/services/staff-activity";
// AutoDJ playlist CRUD (radio_auto_dj_playlist). CMS-owned table backing the
// fallback playlist the radio rotates through when no live DJ is streaming.
@@ -13,7 +13,7 @@ import { logStaffActivity } from '@/lib/services/staff-activity';
/** Parse a FormData field into a positive BigInt id, or null when invalid. */
function parseId(raw: FormDataEntryValue | null): bigint | null {
if (typeof raw !== 'string' || raw.trim() === '') return null;
if (typeof raw !== "string" || raw.trim() === "") return null;
try {
const id = BigInt(raw.trim());
return id > 0n ? id : null;
@@ -23,13 +23,13 @@ function parseId(raw: FormDataEntryValue | null): bigint | null {
}
function str(raw: FormDataEntryValue | null): string {
return typeof raw === 'string' ? raw : '';
return typeof raw === "string" ? raw : "";
}
/** Checkbox/select truthiness: '1', 'true', 'on' → true. */
function bool(raw: FormDataEntryValue | null): boolean {
const v = str(raw).trim().toLowerCase();
return v === '1' || v === 'true' || v === 'on';
return v === "1" || v === "true" || v === "on";
}
/** Parse a non-negative UnsignedInt, falling back to 0. */
@@ -42,7 +42,7 @@ function reqUInt(raw: FormDataEntryValue | null): number {
/** Parse an optional non-negative UnsignedInt; blank/invalid/negative → null. */
function optUInt(raw: FormDataEntryValue | null): number | null {
const s = str(raw).trim();
if (s === '') return null;
if (s === "") return null;
const n = Number(s);
if (!Number.isFinite(n) || n < 0) return null;
return Math.trunc(n);
@@ -52,15 +52,15 @@ function optUInt(raw: FormDataEntryValue | null): number | null {
export async function createTrack(formData: FormData): Promise<void> {
const staff = await requireStaff();
const title = str(formData.get('title')).trim().slice(0, 255);
const title = str(formData.get("title")).trim().slice(0, 255);
if (!title) return;
const artist = str(formData.get('artist')).trim().slice(0, 255);
const album = str(formData.get('album')).trim().slice(0, 255);
const artworkUrl = str(formData.get('artworkUrl')).trim().slice(0, 255);
const duration = optUInt(formData.get('duration'));
const sortOrder = reqUInt(formData.get('sortOrder'));
const isActive = bool(formData.get('isActive'));
const artist = str(formData.get("artist")).trim().slice(0, 255);
const album = str(formData.get("album")).trim().slice(0, 255);
const artworkUrl = str(formData.get("artworkUrl")).trim().slice(0, 255);
const duration = optUInt(formData.get("duration"));
const sortOrder = reqUInt(formData.get("sortOrder"));
const isActive = bool(formData.get("isActive"));
const now = new Date();
try {
@@ -79,24 +79,24 @@ export async function createTrack(formData: FormData): Promise<void> {
});
await logStaffActivity({
staffId: staff.id,
action: 'radio_autodj_create',
description: `Created AutoDJ track "${title}"${artist ? ` by ${artist}` : ''}`,
targetType: 'radio_auto_dj_track',
action: "radio_autodj_create",
description: `Created AutoDJ track "${title}"${artist ? ` by ${artist}` : ""}`,
targetType: "radio_auto_dj_track",
targetId: Number(created.id),
});
} catch {
// Fail soft — DB unavailable; re-render without throwing.
}
revalidatePath('/admin/radio/autodj');
revalidatePath("/admin/radio/autodj");
}
export async function toggleTrack(formData: FormData): Promise<void> {
const staff = await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
// The form posts the desired next state so the toggle is idempotent.
const isActive = bool(formData.get('isActive'));
const isActive = bool(formData.get("isActive"));
try {
await prisma.radioAutoDjPlaylist.update({
@@ -105,33 +105,33 @@ export async function toggleTrack(formData: FormData): Promise<void> {
});
await logStaffActivity({
staffId: staff.id,
action: 'radio_autodj_toggle',
description: `${isActive ? 'Activated' : 'Deactivated'} AutoDJ track #${id}`,
targetType: 'radio_auto_dj_track',
action: "radio_autodj_toggle",
description: `${isActive ? "Activated" : "Deactivated"} AutoDJ track #${id}`,
targetType: "radio_auto_dj_track",
targetId: Number(id),
});
} catch {
// Row may be gone; ignore.
}
revalidatePath('/admin/radio/autodj');
revalidatePath("/admin/radio/autodj");
}
export async function deleteTrack(formData: FormData): Promise<void> {
const staff = await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
try {
await prisma.radioAutoDjPlaylist.delete({ where: { id } });
await logStaffActivity({
staffId: staff.id,
action: 'radio_autodj_delete',
action: "radio_autodj_delete",
description: `Deleted AutoDJ track #${id}`,
targetType: 'radio_auto_dj_track',
targetType: "radio_auto_dj_track",
targetId: Number(id),
});
} catch {
// Already deleted; ignore.
}
revalidatePath('/admin/radio/autodj');
revalidatePath("/admin/radio/autodj");
}
+44 -44
View File
@@ -1,15 +1,15 @@
'use server';
"use server";
import { revalidatePath } from 'next/cache';
import { requireStaff } from '@/lib/admin/guard';
import { prisma } from '@/lib/prisma';
import { siteSettings } from '@/lib/services/site-settings';
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { siteSettings } from "@/lib/services/site-settings";
// ── Helpers ────────────────────────────────────────────────────────────────
/** Parse a FormData field into a positive BigInt id, or null when invalid. */
function parseId(raw: FormDataEntryValue | null): bigint | null {
if (typeof raw !== 'string' || raw.trim() === '') return null;
if (typeof raw !== "string" || raw.trim() === "") return null;
try {
const id = BigInt(raw.trim());
return id > 0n ? id : null;
@@ -19,13 +19,13 @@ function parseId(raw: FormDataEntryValue | null): bigint | null {
}
function str(raw: FormDataEntryValue | null): string {
return typeof raw === 'string' ? raw : '';
return typeof raw === "string" ? raw : "";
}
/** Checkbox/select truthiness: '1', 'true', 'on' → true. */
function bool(raw: FormDataEntryValue | null): boolean {
const v = str(raw).trim().toLowerCase();
return v === '1' || v === 'true' || v === 'on';
return v === "1" || v === "true" || v === "on";
}
// ── Radio settings (website_settings radio_* keys) ─────────────────────────
@@ -37,9 +37,9 @@ function bool(raw: FormDataEntryValue | null): boolean {
*/
export async function saveRadioSetting(formData: FormData): Promise<void> {
await requireStaff();
const key = str(formData.get('key')).trim().slice(0, 255);
const value = str(formData.get('value'));
const comment = str(formData.get('comment')).trim().slice(0, 255);
const key = str(formData.get("key")).trim().slice(0, 255);
const value = str(formData.get("value"));
const comment = str(formData.get("comment")).trim().slice(0, 255);
if (!key) return;
try {
@@ -52,7 +52,7 @@ export async function saveRadioSetting(formData: FormData): Promise<void> {
} catch {
// DB unavailable — fail soft so the action does not throw.
}
revalidatePath('/admin/radio/settings');
revalidatePath("/admin/radio/settings");
}
/**
@@ -62,11 +62,11 @@ export async function saveRadioSetting(formData: FormData): Promise<void> {
*/
export async function saveRadioSettings(formData: FormData): Promise<void> {
await requireStaff();
const keysRaw = str(formData.get('__keys'));
const keysRaw = str(formData.get("__keys"));
const keys = keysRaw
.split(',')
.split(",")
.map((k) => k.trim())
.filter((k) => k.startsWith('radio_') || k.startsWith('auto_dj_'));
.filter((k) => k.startsWith("radio_") || k.startsWith("auto_dj_"));
if (keys.length === 0) return;
try {
@@ -84,21 +84,21 @@ export async function saveRadioSettings(formData: FormData): Promise<void> {
} catch {
// Fail soft.
}
revalidatePath('/admin/radio/settings');
revalidatePath("/admin/radio/settings");
}
// ── Radio banners CRUD (radio_banners) ─────────────────────────────────────
export async function createRadioBanner(formData: FormData): Promise<void> {
const staff = await requireStaff();
const imagePath = str(formData.get('imagePath')).trim().slice(0, 255);
const imagePath = str(formData.get("imagePath")).trim().slice(0, 255);
if (!imagePath) return;
const title = str(formData.get('title')).trim().slice(0, 255);
const description = str(formData.get('description')).trim();
const sortOrderNum = Number(str(formData.get('sortOrder')));
const title = str(formData.get("title")).trim().slice(0, 255);
const description = str(formData.get("description")).trim();
const sortOrderNum = Number(str(formData.get("sortOrder")));
const sortOrder = Number.isFinite(sortOrderNum) ? Math.trunc(sortOrderNum) : 0;
const isActive = bool(formData.get('isActive'));
const isActive = bool(formData.get("isActive"));
const now = new Date();
try {
@@ -117,20 +117,20 @@ export async function createRadioBanner(formData: FormData): Promise<void> {
} catch {
// Fail soft.
}
revalidatePath('/admin/radio/banners');
revalidatePath("/admin/radio/banners");
}
export async function updateRadioBanner(formData: FormData): Promise<void> {
await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
const imagePath = str(formData.get('imagePath')).trim().slice(0, 255);
const title = str(formData.get('title')).trim().slice(0, 255);
const description = str(formData.get('description')).trim();
const sortOrderNum = Number(str(formData.get('sortOrder')));
const imagePath = str(formData.get("imagePath")).trim().slice(0, 255);
const title = str(formData.get("title")).trim().slice(0, 255);
const description = str(formData.get("description")).trim();
const sortOrderNum = Number(str(formData.get("sortOrder")));
const sortOrder = Number.isFinite(sortOrderNum) ? Math.trunc(sortOrderNum) : 0;
const isActive = bool(formData.get('isActive'));
const isActive = bool(formData.get("isActive"));
if (!imagePath) return;
try {
@@ -148,31 +148,31 @@ export async function updateRadioBanner(formData: FormData): Promise<void> {
} catch {
// Row may be gone; ignore.
}
revalidatePath('/admin/radio/banners');
revalidatePath("/admin/radio/banners");
}
export async function deleteRadioBanner(formData: FormData): Promise<void> {
await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
try {
await prisma.radioBanners.delete({ where: { id } });
} catch {
// Already deleted; ignore.
}
revalidatePath('/admin/radio/banners');
revalidatePath("/admin/radio/banners");
}
// ── Radio ranks CRUD (radio_ranks) ─────────────────────────────────────────
export async function createRadioRank(formData: FormData): Promise<void> {
await requireStaff();
const name = str(formData.get('name')).trim().slice(0, 255);
const name = str(formData.get("name")).trim().slice(0, 255);
if (!name) return;
const description = str(formData.get('description')).trim().slice(0, 255);
const badgeCode = str(formData.get('badgeCode')).trim().slice(0, 255);
const isActive = bool(formData.get('isActive'));
const description = str(formData.get("description")).trim().slice(0, 255);
const badgeCode = str(formData.get("badgeCode")).trim().slice(0, 255);
const isActive = bool(formData.get("isActive"));
const now = new Date();
try {
@@ -189,18 +189,18 @@ export async function createRadioRank(formData: FormData): Promise<void> {
} catch {
// Fail soft.
}
revalidatePath('/admin/radio/ranks');
revalidatePath("/admin/radio/ranks");
}
export async function updateRadioRank(formData: FormData): Promise<void> {
await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
const name = str(formData.get('name')).trim().slice(0, 255);
const description = str(formData.get('description')).trim().slice(0, 255);
const badgeCode = str(formData.get('badgeCode')).trim().slice(0, 255);
const isActive = bool(formData.get('isActive'));
const name = str(formData.get("name")).trim().slice(0, 255);
const description = str(formData.get("description")).trim().slice(0, 255);
const badgeCode = str(formData.get("badgeCode")).trim().slice(0, 255);
const isActive = bool(formData.get("isActive"));
if (!name) return;
try {
@@ -217,17 +217,17 @@ export async function updateRadioRank(formData: FormData): Promise<void> {
} catch {
// Row may be gone; ignore.
}
revalidatePath('/admin/radio/ranks');
revalidatePath("/admin/radio/ranks");
}
export async function deleteRadioRank(formData: FormData): Promise<void> {
await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
try {
await prisma.radioRanks.delete({ where: { id } });
} catch {
// Already deleted; ignore.
}
revalidatePath('/admin/radio/ranks');
revalidatePath("/admin/radio/ranks");
}
+10 -10
View File
@@ -1,13 +1,13 @@
'use server';
"use server";
import { revalidatePath } from 'next/cache';
import { requireStaff } from '@/lib/admin/guard';
import { logStaffActivity } from '@/lib/services/staff-activity';
import { prisma } from '@/lib/prisma';
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { logStaffActivity } from "@/lib/services/staff-activity";
import { prisma } from "@/lib/prisma";
/** Parse a FormData field into a positive BigInt id, or null when invalid. */
function parseId(raw: FormDataEntryValue | null): bigint | null {
if (typeof raw !== 'string' || raw.trim() === '') return null;
if (typeof raw !== "string" || raw.trim() === "") return null;
try {
const id = BigInt(raw.trim());
return id > 0n ? id : null;
@@ -23,21 +23,21 @@ function parseId(raw: FormDataEntryValue | null): bigint | null {
*/
export async function deleteShout(formData: FormData): Promise<void> {
const staff = await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
try {
await prisma.radioShouts.delete({ where: { id } });
await logStaffActivity({
staffId: staff.id,
action: 'radio.shout.delete',
action: "radio.shout.delete",
description: `Deleted radio shout #${id}`,
targetType: 'radio_shout',
targetType: "radio_shout",
targetId: Number(id),
});
} catch {
// Row may already be gone; ignore so the action does not throw.
}
revalidatePath('/admin/radio/moderation');
revalidatePath("/admin/radio/moderation");
}
+1 -27
View File
@@ -1,27 +1 @@
'use server';
import { revalidatePath } from 'next/cache';
import { prisma } from '@/lib/prisma';
import { requireStaff } from '@/lib/admin/guard';
export async function deleteShout(formData: FormData): Promise<void> {
await requireStaff();
const raw = formData.get('id');
if (typeof raw !== 'string' || raw.trim() === '') return;
let id: bigint;
try {
id = BigInt(raw);
} catch {
return;
}
try {
await prisma.radioShouts.delete({ where: { id } });
} catch {
// Row may already be gone; ignore so the action does not throw.
}
revalidatePath('/admin/radio');
}
"use server";
+22 -7
View File
@@ -7,8 +7,12 @@ import { formPositiveBigInt } from "@/lib/form-data";
export async function createCategory(formData: FormData): Promise<void> {
await requireStaff();
const name = String(formData.get("name") ?? "").trim().slice(0, 255);
const badge = String(formData.get("badge") ?? "").trim().slice(0, 255);
const name = String(formData.get("name") ?? "")
.trim()
.slice(0, 255);
const badge = String(formData.get("badge") ?? "")
.trim()
.slice(0, 255);
const priorityRaw = Number(formData.get("priority"));
const priority = Number.isFinite(priorityRaw) && priorityRaw > 0 ? Math.floor(priorityRaw) : 1;
if (!name || !badge) return;
@@ -43,16 +47,27 @@ export async function createValue(formData: FormData): Promise<void> {
const categoryId = formPositiveBigInt(formData, "categoryId");
if (!categoryId) return;
const name = String(formData.get("name") ?? "").trim().slice(0, 255);
const furnitureIcon = String(formData.get("furnitureIcon") ?? "").trim().slice(0, 255);
const name = String(formData.get("name") ?? "")
.trim()
.slice(0, 255);
const furnitureIcon = String(formData.get("furnitureIcon") ?? "")
.trim()
.slice(0, 255);
if (!name || !furnitureIcon) return;
const itemIdRaw = Number(formData.get("itemId"));
const itemId = Number.isFinite(itemIdRaw) && itemIdRaw > 0 ? Math.floor(itemIdRaw) : null;
const creditValueRaw = String(formData.get("creditValue") ?? "").trim().slice(0, 255);
const currencyValueRaw = String(formData.get("currencyValue") ?? "").trim().slice(0, 255);
const currencyType = String(formData.get("currencyType") ?? "diamonds").trim().slice(0, 255) || "diamonds";
const creditValueRaw = String(formData.get("creditValue") ?? "")
.trim()
.slice(0, 255);
const currencyValueRaw = String(formData.get("currencyValue") ?? "")
.trim()
.slice(0, 255);
const currencyType =
String(formData.get("currencyType") ?? "diamonds")
.trim()
.slice(0, 255) || "diamonds";
try {
await prisma.websiteRareValues.create({
+6 -2
View File
@@ -17,9 +17,13 @@ export async function updateSetting(formData: FormData): Promise<void> {
export async function createSetting(formData: FormData): Promise<void> {
await requireStaff();
const key = String(formData.get("key") ?? "").trim().slice(0, 255);
const key = String(formData.get("key") ?? "")
.trim()
.slice(0, 255);
const value = String(formData.get("value") ?? "");
const comment = String(formData.get("comment") ?? "").trim().slice(0, 255);
const comment = String(formData.get("comment") ?? "")
.trim()
.slice(0, 255);
if (!key) return;
await prisma.websiteSetting.upsert({
where: { key },
+32 -10
View File
@@ -30,7 +30,9 @@ function reqUInt(formData: FormData, key: string): number {
export async function createShopArticle(formData: FormData): Promise<void> {
const staff = await requireStaff();
const name = String(formData.get("name") ?? "").trim().slice(0, 255);
const name = String(formData.get("name") ?? "")
.trim()
.slice(0, 255);
if (!name) return;
const now = new Date();
@@ -38,15 +40,24 @@ export async function createShopArticle(formData: FormData): Promise<void> {
const created = await prisma.websiteShopArticles.create({
data: {
name,
info: String(formData.get("info") ?? "").trim().slice(0, 255),
iconUrl: String(formData.get("icon") ?? "").trim().slice(0, 255),
color: String(formData.get("color") ?? "").trim().slice(0, 255),
info: String(formData.get("info") ?? "")
.trim()
.slice(0, 255),
iconUrl: String(formData.get("icon") ?? "")
.trim()
.slice(0, 255),
color: String(formData.get("color") ?? "")
.trim()
.slice(0, 255),
costs: reqUInt(formData, "costs"),
giveRank: optUInt(formData, "giveRank"),
credits: optUInt(formData, "credits"),
duckets: optUInt(formData, "duckets"),
diamonds: optUInt(formData, "diamonds"),
badges: (String(formData.get("badges") ?? "").trim().slice(0, 255)) || null,
badges:
String(formData.get("badges") ?? "")
.trim()
.slice(0, 255) || null,
position: reqUInt(formData, "position"),
createdAt: now,
updatedAt: now,
@@ -74,7 +85,9 @@ export async function updateShopArticle(formData: FormData): Promise<void> {
const id = formPositiveBigInt(formData, "id");
if (!id) return;
const name = String(formData.get("name") ?? "").trim().slice(0, 255);
const name = String(formData.get("name") ?? "")
.trim()
.slice(0, 255);
if (!name) return;
try {
@@ -82,15 +95,24 @@ export async function updateShopArticle(formData: FormData): Promise<void> {
where: { id },
data: {
name,
info: String(formData.get("info") ?? "").trim().slice(0, 255),
iconUrl: String(formData.get("icon") ?? "").trim().slice(0, 255),
color: String(formData.get("color") ?? "").trim().slice(0, 255),
info: String(formData.get("info") ?? "")
.trim()
.slice(0, 255),
iconUrl: String(formData.get("icon") ?? "")
.trim()
.slice(0, 255),
color: String(formData.get("color") ?? "")
.trim()
.slice(0, 255),
costs: reqUInt(formData, "costs"),
giveRank: optUInt(formData, "giveRank"),
credits: optUInt(formData, "credits"),
duckets: optUInt(formData, "duckets"),
diamonds: optUInt(formData, "diamonds"),
badges: (String(formData.get("badges") ?? "").trim().slice(0, 255)) || null,
badges:
String(formData.get("badges") ?? "")
.trim()
.slice(0, 255) || null,
position: reqUInt(formData, "position"),
updatedAt: new Date(),
},
+23 -23
View File
@@ -1,15 +1,15 @@
'use server';
"use server";
import { revalidatePath } from 'next/cache';
import { requireStaff } from '@/lib/admin/guard';
import { prisma } from '@/lib/prisma';
import { logStaffActivity } from '@/lib/services/staff-activity';
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { logStaffActivity } from "@/lib/services/staff-activity";
// ── Helpers ────────────────────────────────────────────────────────────────
/** Parse a FormData field into a positive BigInt id, or null when invalid. */
function parseId(raw: FormDataEntryValue | null): bigint | null {
if (typeof raw !== 'string' || raw.trim() === '') return null;
if (typeof raw !== "string" || raw.trim() === "") return null;
try {
const id = BigInt(raw.trim());
return id > 0n ? id : null;
@@ -19,23 +19,23 @@ function parseId(raw: FormDataEntryValue | null): bigint | null {
}
function str(raw: FormDataEntryValue | null): string {
return typeof raw === 'string' ? raw : '';
return typeof raw === "string" ? raw : "";
}
/** Normalise a hex-ish colour into the 10-char background_color column. */
function normaliseColor(raw: string): string {
const v = raw.trim().slice(0, 10);
return v || '#888888';
return v || "#888888";
}
// ── Tags CRUD (tags + taggables, AtomCMS article tags/categories) ──────────
export async function createTag(formData: FormData): Promise<void> {
const staff = await requireStaff();
const name = str(formData.get('name')).trim().slice(0, 255);
const name = str(formData.get("name")).trim().slice(0, 255);
if (!name) return;
const backgroundColor = normaliseColor(str(formData.get('backgroundColor')));
const backgroundColor = normaliseColor(str(formData.get("backgroundColor")));
const now = new Date();
try {
@@ -44,24 +44,24 @@ export async function createTag(formData: FormData): Promise<void> {
});
await logStaffActivity({
staffId: staff.id,
action: 'tag_create',
action: "tag_create",
description: `Created tag "${name}" (#${created.id})`,
targetType: 'tag',
targetType: "tag",
targetId: Number(created.id),
});
} catch {
// Fail soft — DB unavailable or duplicate.
}
revalidatePath('/admin/tags');
revalidatePath("/admin/tags");
}
export async function updateTag(formData: FormData): Promise<void> {
const staff = await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
const name = str(formData.get('name')).trim().slice(0, 255);
const backgroundColor = normaliseColor(str(formData.get('backgroundColor')));
const name = str(formData.get("name")).trim().slice(0, 255);
const backgroundColor = normaliseColor(str(formData.get("backgroundColor")));
if (!name) return;
try {
@@ -71,20 +71,20 @@ export async function updateTag(formData: FormData): Promise<void> {
});
await logStaffActivity({
staffId: staff.id,
action: 'tag_update',
action: "tag_update",
description: `Updated tag #${id} → "${name}"`,
targetType: 'tag',
targetType: "tag",
targetId: Number(id),
});
} catch {
// Row may be gone; ignore.
}
revalidatePath('/admin/tags');
revalidatePath("/admin/tags");
}
export async function deleteTag(formData: FormData): Promise<void> {
const staff = await requireStaff();
const id = parseId(formData.get('id'));
const id = parseId(formData.get("id"));
if (id === null) return;
try {
@@ -95,13 +95,13 @@ export async function deleteTag(formData: FormData): Promise<void> {
]);
await logStaffActivity({
staffId: staff.id,
action: 'tag_delete',
action: "tag_delete",
description: `Deleted tag #${id}`,
targetType: 'tag',
targetType: "tag",
targetId: Number(id),
});
} catch {
// Already deleted; ignore.
}
revalidatePath('/admin/tags');
revalidatePath("/admin/tags");
}
+3 -1
View File
@@ -9,7 +9,9 @@ import { logServerError } from "@/lib/server-log";
export async function createVoucher(formData: FormData): Promise<void> {
await requireStaff();
const code = String(formData.get("code") ?? "").trim().slice(0, 255);
const code = String(formData.get("code") ?? "")
.trim()
.slice(0, 255);
const amount = Number(formData.get("amount"));
const maxUsesRaw = Number(formData.get("maxUses"));
const maxUses = Number.isFinite(maxUsesRaw) && maxUsesRaw > 0 ? Math.floor(maxUsesRaw) : 1;
+9 -3
View File
@@ -29,11 +29,17 @@ export async function saveVpn(formData: FormData): Promise<void> {
// Toggle: an unchecked checkbox submits nothing, so absence === disabled.
const enabled = String(formData.get("vpn_block_enabled") ?? "").trim() !== "";
const providerRaw = String(formData.get("vpn_provider") ?? "").trim().toLowerCase();
const providerRaw = String(formData.get("vpn_provider") ?? "")
.trim()
.toLowerCase();
const provider = ALLOWED_PROVIDERS.has(providerRaw) ? providerRaw : "none";
const apiKey = String(formData.get("vpn_api_key") ?? "").trim().slice(0, 255);
const blockMessage = String(formData.get("vpn_block_message") ?? "").trim().slice(0, 255);
const apiKey = String(formData.get("vpn_api_key") ?? "")
.trim()
.slice(0, 255);
const blockMessage = String(formData.get("vpn_block_message") ?? "")
.trim()
.slice(0, 255);
try {
await writeSetting(
+3 -1
View File
@@ -7,7 +7,9 @@ import { rcon } from "@/lib/services/rcon";
export async function addWord(formData: FormData): Promise<void> {
await requireStaff();
const word = String(formData.get("word") ?? "").trim().slice(0, 255);
const word = String(formData.get("word") ?? "")
.trim()
.slice(0, 255);
if (!word) return;
try {
+14 -4
View File
@@ -38,7 +38,9 @@ function revalidate(): void {
export async function createBox(formData: FormData): Promise<void> {
const staff = await requireStaff();
const title = String(formData.get("title") ?? "").trim().slice(0, 255);
const title = String(formData.get("title") ?? "")
.trim()
.slice(0, 255);
if (!title) return;
const now = new Date();
@@ -46,7 +48,10 @@ export async function createBox(formData: FormData): Promise<void> {
const created = await prisma.websiteWriteableBoxes.create({
data: {
title,
icon: (String(formData.get("icon") ?? "").trim().slice(0, 255)) || null,
icon:
String(formData.get("icon") ?? "")
.trim()
.slice(0, 255) || null,
content: String(formData.get("content") ?? ""),
position: reqInt(formData, "position"),
isActive: String(formData.get("isActive") ?? "") === "1",
@@ -75,7 +80,9 @@ export async function updateBox(formData: FormData): Promise<void> {
const id = parseId(formData);
if (id == null) return;
const title = String(formData.get("title") ?? "").trim().slice(0, 255);
const title = String(formData.get("title") ?? "")
.trim()
.slice(0, 255);
if (!title) return;
try {
@@ -83,7 +90,10 @@ export async function updateBox(formData: FormData): Promise<void> {
where: { id },
data: {
title,
icon: (String(formData.get("icon") ?? "").trim().slice(0, 255)) || null,
icon:
String(formData.get("icon") ?? "")
.trim()
.slice(0, 255) || null,
content: String(formData.get("content") ?? ""),
position: reqInt(formData, "position"),
isActive: String(formData.get("isActive") ?? "") === "1",
+6 -2
View File
@@ -28,7 +28,9 @@ export async function applyStaff(formData: FormData): Promise<void> {
const rankId = Number(formData.get("rankId"));
if (!Number.isInteger(rankId) || rankId <= 0) return;
const content = String(formData.get("content") ?? "").trim().slice(0, CONTENT_MAX);
const content = String(formData.get("content") ?? "")
.trim()
.slice(0, CONTENT_MAX);
if (content.length < CONTENT_MIN) return;
try {
@@ -70,7 +72,9 @@ export async function applyTeam(formData: FormData): Promise<void> {
const rankId = Number(formData.get("teamId"));
if (!Number.isInteger(rankId) || rankId <= 0) return;
const content = String(formData.get("content") ?? "").trim().slice(0, CONTENT_MAX);
const content = String(formData.get("content") ?? "")
.trim()
.slice(0, CONTENT_MAX);
if (content.length < CONTENT_MIN) return;
try {
+3 -1
View File
@@ -21,7 +21,9 @@ export async function postComment(formData: FormData): Promise<void> {
const userId = Number(session.user.id);
if (!Number.isFinite(userId)) return;
const comment = String(formData.get("comment") ?? "").trim().slice(0, COMMENT_MAX);
const comment = String(formData.get("comment") ?? "")
.trim()
.slice(0, COMMENT_MAX);
if (!comment) return;
// Block filtered/AI-flagged content before it touches the DB (fail-open).
+3 -1
View File
@@ -31,7 +31,9 @@ export async function toggleReaction(formData: FormData): Promise<void> {
const userId = Number(session.user.id);
if (!Number.isFinite(userId)) return;
const reaction = String(formData.get("reaction") ?? "").trim().toLowerCase();
const reaction = String(formData.get("reaction") ?? "")
.trim()
.toLowerCase();
if (!ALLOWED_REACTIONS.has(reaction)) return;
const articleIdRaw = String(formData.get("articleId") ?? "").trim();
+4 -9
View File
@@ -11,10 +11,7 @@ export type PrecheckResult = "ok" | "invalid" | "twofactor";
* Validates username+password WITHOUT creating a session, and reports whether a
* TOTP code is still required. Lets the login form do the two-step 2FA flow.
*/
export async function precheckLogin(
username: string,
password: string,
): Promise<PrecheckResult> {
export async function precheckLogin(username: string, password: string): Promise<PrecheckResult> {
const u = String(username ?? "").trim();
const p = String(password ?? "");
if (!u || !p) return "invalid";
@@ -32,11 +29,9 @@ export async function precheckLogin(
}
if (!user) {
// Prevent timing-based enumeration: always run a dummy hash check.
await checkLogin(
p,
"$2y$12$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcd",
{ convertPasswords: false },
);
await checkLogin(p, "$2y$12$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcd", {
convertPasswords: false,
});
return "invalid";
}
+25
View File
@@ -0,0 +1,25 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
export async function getBadgeData({ code }: { code: string }) {
await requireStaff();
const badge = await prisma.websiteBadges.findUnique({
where: { badgeKey: code },
select: { badgeName: true, badgeDescription: true },
});
if (!badge) return { ok: false as const, data: null };
return { ok: true as const, data: { name: badge.badgeName, desc: badge.badgeDescription } };
}
export async function updateBadge({ code, name, desc }: { code: string; name: string; desc: string }) {
await requireStaff();
await prisma.websiteBadges.upsert({
where: { badgeKey: code },
update: { badgeName: name, badgeDescription: desc, updatedAt: new Date() },
create: { badgeKey: code, badgeName: name, badgeDescription: desc, createdAt: new Date(), updatedAt: new Date() },
});
revalidatePath("/admin/import/badges");
}
+128
View File
@@ -0,0 +1,128 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
export async function bulkUnban({ userIds }: { userIds: number[] }) {
const staff = await requireStaff();
const result = await prisma.ban.deleteMany({ where: { userId: { in: userIds } } });
await logStaffActivity({
staffId: staff.id,
action: "bulk_unban",
description: `Unbanned ${result.count} user(s)`,
targetType: "user",
});
return { ok: true as const, data: { unbanned: result.count, total: userIds.length } };
}
export async function bulkBan({ userIds, reason, duration }: { userIds: number[]; reason: string; duration: number }) {
const staff = await requireStaff();
const now = Math.floor(Date.now() / 1000);
let banned = 0;
for (const userId of userIds) {
try {
await prisma.ban.create({
data: {
userId,
ip: "",
machineId: "",
userStaffId: staff.id,
timestamp: now,
banExpire: duration > 0 ? now + duration : 0,
banReason: reason,
type: "account",
},
});
banned++;
} catch {
// skip duplicates
}
}
await logStaffActivity({
staffId: staff.id,
action: "bulk_ban",
description: `Banned ${banned} user(s)`,
targetType: "user",
});
return { ok: true as const, data: { banned } };
}
export async function bulkGiveCurrency({ userIds, amount, type }: { userIds: number[]; amount: number; type: "credits" | "pixels" | "points" }) {
const staff = await requireStaff();
let given = 0;
const failedIds: Array<{ userId: number; reason: string }> = [];
for (const userId of userIds) {
try {
if (type === "credits") {
await prisma.user.update({ where: { id: userId }, data: { credits: { increment: amount } } });
await rcon.giveCredits(userId, amount);
} else if (type === "pixels") {
await prisma.usersCurrency.upsert({
where: { userId_type: { userId, type: 0 } },
update: { amount: { increment: amount } },
create: { userId, type: 0, amount },
});
await rcon.giveDuckets(userId, amount);
} else if (type === "points") {
await prisma.usersCurrency.upsert({
where: { userId_type: { userId, type: 101 } },
update: { amount: { increment: amount } },
create: { userId, type: 101, amount },
});
await rcon.givePointsGotw(userId, amount);
}
given++;
} catch {
failedIds.push({ userId, reason: "Database error" });
}
}
await logStaffActivity({
staffId: staff.id,
action: "bulk_give_currency",
description: `Gave ${amount} ${type} to ${given} user(s)`,
targetType: "user",
});
return { ok: true as const, data: { given, total: userIds.length, failedIds } };
}
export async function bulkGiveBadge({ userIds, badgeCode }: { userIds: number[]; badgeCode: string }) {
const staff = await requireStaff();
let given = 0;
const failedIds: Array<{ userId: number; reason: string }> = [];
for (const userId of userIds) {
try {
const existing = await prisma.usersBadges.findFirst({
where: { userId, badgeCode },
select: { id: true },
});
if (!existing) {
const max = await prisma.usersBadges.aggregate({
where: { userId },
_max: { slotId: true },
});
const slotId = (max._max.slotId ?? 0) + 1;
await prisma.usersBadges.create({ data: { userId, slotId, badgeCode } });
await rcon.giveBadge(userId, badgeCode);
}
given++;
} catch {
failedIds.push({ userId, reason: "Database error" });
}
}
await logStaffActivity({
staffId: staff.id,
action: "bulk_give_badge",
description: `Gave badge "${badgeCode}" to ${given} user(s)`,
targetType: "user",
});
return { ok: true as const, data: { given, total: userIds.length, failedIds } };
}
+100
View File
@@ -0,0 +1,100 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
export async function updateBcPage({ id, ...fields }: { id: number } & Record<string, unknown>) {
const staff = await requireStaff();
await prisma.catalogPagesBc.update({ where: { id }, data: fields as any });
await rcon.updateCatalog();
await logStaffActivity({
staffId: staff.id,
action: "bc_page_update",
description: `Updated BC catalog page #${id}`,
targetType: "catalog_page_bc",
targetId: id,
});
revalidatePath("/admin/catalog/builder-club");
}
export async function deleteBcItem({ id }: { id: number }) {
const staff = await requireStaff();
await prisma.catalogItemsBc.delete({ where: { id } });
await logStaffActivity({
staffId: staff.id,
action: "bc_item_delete",
description: `Deleted BC catalog item #${id}`,
targetType: "catalog_item_bc",
targetId: id,
});
revalidatePath("/admin/catalog/builder-club");
}
export async function updateBcItem({ id, ...data }: { id: number; itemIds?: string; catalogName?: string; orderNumber?: number; extradata?: string }) {
const staff = await requireStaff();
await prisma.catalogItemsBc.update({ where: { id }, data: data as any });
await logStaffActivity({
staffId: staff.id,
action: "bc_item_update",
description: `Updated BC catalog item #${id}`,
targetType: "catalog_item_bc",
targetId: id,
});
revalidatePath("/admin/catalog/builder-club");
}
export async function createBcItem({ pageId, ...data }: { pageId: number; itemIds: string; catalogName: string; orderNumber: number; extradata: string }) {
const staff = await requireStaff();
const created = await prisma.catalogItemsBc.create({
data: { pageId, ...data },
});
await logStaffActivity({
staffId: staff.id,
action: "bc_item_create",
description: `Created BC catalog item #${created.id}`,
targetType: "catalog_item_bc",
targetId: created.id,
});
revalidatePath("/admin/catalog/builder-club");
}
export async function toggleBcPage({ id, field }: { id: number; field: "enabled" | "visible" }) {
await requireStaff();
const page = await prisma.catalogPagesBc.findUnique({ where: { id }, select: { enabled: true, visible: true } });
if (!page) return;
await prisma.catalogPagesBc.update({
where: { id },
data: { [field]: page[field] === "1" ? "0" : "1" },
});
revalidatePath("/admin/catalog/builder-club");
}
export async function createBcPage(input: { caption: string; parentId: number; pageLayout: string }) {
const staff = await requireStaff();
const created = await prisma.catalogPagesBc.create({
data: {
caption: input.caption,
parentId: input.parentId,
pageLayout: input.pageLayout,
iconColor: 0,
iconImage: 0,
orderNum: 0,
visible: "1",
enabled: "1",
pageHeadline: "",
pageTeaser: "",
},
});
await logStaffActivity({
staffId: staff.id,
action: "bc_page_create",
description: `Created BC catalog page "${input.caption}"`,
targetType: "catalog_page_bc",
targetId: created.id,
});
revalidatePath("/admin/catalog/builder-club");
return { ok: true as const, data: { id: created.id } };
}
+126
View File
@@ -0,0 +1,126 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
export async function createCatalogItem(data: {
pageId: number;
itemIds: string;
catalogName: string;
costCredits: number;
costPoints: number;
pointsType: number;
amount: number;
orderNumber: number;
offerId: number;
limitedSells: number;
limitedStack: number;
extradata: string;
songId: number;
haveOffer: "0" | "1";
clubOnly: "0" | "1";
}) {
const staff = await requireStaff();
const created = await prisma.catalogItems.create({ data });
await rcon.updateCatalog();
await logStaffActivity({
staffId: staff.id,
action: "catalog_item_create",
description: `Created catalog item #${created.id}`,
targetType: "catalog_item",
targetId: created.id,
});
revalidatePath("/admin/catalog");
}
export async function deleteCatalogItems({ ids }: { ids: number[] }) {
const staff = await requireStaff();
await prisma.catalogItems.deleteMany({ where: { id: { in: ids } } });
await rcon.updateCatalog();
await logStaffActivity({
staffId: staff.id,
action: "catalog_items_delete",
description: `Deleted catalog items: ${ids.join(", ")}`,
targetType: "catalog_item",
});
revalidatePath("/admin/catalog");
}
export async function moveCatalogItems({ ids, targetPageId }: { ids: number[]; targetPageId: number }) {
await requireStaff();
await prisma.catalogItems.updateMany({
where: { id: { in: ids } },
data: { pageId: targetPageId },
});
await rcon.updateCatalog();
revalidatePath("/admin/catalog");
}
export async function reorderCatalogItems({ orders }: { orders: Array<{ id: number; orderNumber: number }> }) {
await requireStaff();
for (const { id, orderNumber } of orders) {
await prisma.catalogItems.update({ where: { id }, data: { orderNumber } });
}
await rcon.updateCatalog();
revalidatePath("/admin/catalog");
}
export async function updateCatalogItem({ id, catalogFields, baseItem }: { id: number; catalogFields: Record<string, unknown>; baseItem?: { id: number; fields: Record<string, unknown> } }) {
const staff = await requireStaff();
await prisma.catalogItems.update({ where: { id }, data: catalogFields as any });
if (baseItem) {
await prisma.itemsBase.update({ where: { id: baseItem.id }, data: baseItem.fields as any });
}
await rcon.updateCatalog();
await logStaffActivity({
staffId: staff.id,
action: "catalog_item_update",
description: `Updated catalog item #${id}`,
targetType: "catalog_item",
targetId: id,
});
revalidatePath("/admin/catalog");
}
export async function translateCatalogItems({ items }: { items: Array<{ id: number; publicName: string; description: string }> }) {
await requireStaff();
let namesUpdated = 0;
let descriptionsUpdated = 0;
let furniDataUpdated = 0;
let furniDataInserted = 0;
for (const item of items) {
const existing = await prisma.catalogItems.findUnique({ where: { id: item.id }, select: { catalogName: true } });
if (!existing) continue;
if (item.publicName && item.publicName !== existing.catalogName) {
await prisma.catalogItems.update({
where: { id: item.id },
data: { catalogName: item.publicName },
});
namesUpdated++;
}
if (item.description) {
const baseItem = await prisma.itemsBase.findFirst({
where: { itemName: existing.catalogName },
select: { id: true, publicName: true },
});
if (baseItem) {
await prisma.itemsBase.update({
where: { id: baseItem.id },
data: { publicName: item.publicName || baseItem.publicName },
});
furniDataUpdated++;
}
descriptionsUpdated++;
}
}
await rcon.updateCatalog();
revalidatePath("/admin/catalog");
return { ok: true as const, data: { namesUpdated, descriptionsUpdated, furniDataUpdated, furniDataInserted: 0, updated: items.length } };
}
+80
View File
@@ -0,0 +1,80 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
export async function updateCatalogPage({ id, ...fields }: { id: number } & Record<string, unknown>) {
const staff = await requireStaff();
await prisma.catalogPages.update({ where: { id }, data: fields as any });
await rcon.updateCatalog();
await logStaffActivity({
staffId: staff.id,
action: "catalog_page_update",
description: `Updated catalog page #${id}`,
targetType: "catalog_page",
targetId: id,
});
revalidatePath("/admin/catalog");
}
export async function deleteCatalogPage({ id }: { id: number }) {
const staff = await requireStaff();
await prisma.catalogPages.delete({ where: { id } });
await rcon.updateCatalog();
await logStaffActivity({
staffId: staff.id,
action: "catalog_page_delete",
description: `Deleted catalog page #${id}`,
targetType: "catalog_page",
targetId: id,
});
revalidatePath("/admin/catalog");
}
export async function toggleCatalogPage({ id, action }: { id: number; action: "toggleEnabled" | "toggleVisible" }) {
await requireStaff();
const page = await prisma.catalogPages.findUnique({ where: { id }, select: { enabled: true, visible: true } });
if (!page) return;
const field = action === "toggleEnabled" ? "enabled" : "visible";
const current = action === "toggleEnabled" ? page.enabled : page.visible;
await prisma.catalogPages.update({
where: { id },
data: { [field]: current === "1" ? "0" : "1" },
});
revalidatePath("/admin/catalog");
}
export async function createCatalogPage(input: { caption: string; parentId: number; pageLayout: string }) {
const staff = await requireStaff();
const created = await prisma.catalogPages.create({
data: {
caption: input.caption,
parentId: input.parentId,
pageLayout: input.pageLayout,
captionSave: input.caption.slice(0, 25),
iconColor: 0,
iconImage: 0,
minRank: 1,
orderNum: 0,
visible: "1",
enabled: "1",
clubOnly: "0",
vipOnly: "0",
pageHeadline: "",
pageTeaser: "",
includes: "",
},
});
await logStaffActivity({
staffId: (await requireStaff()).id,
action: "catalog_page_create",
description: `Created catalog page "${input.caption}"`,
targetType: "catalog_page",
targetId: created.id,
});
revalidatePath("/admin/catalog");
return { ok: true as const, data: { id: created.id } };
}
+12 -4
View File
@@ -42,7 +42,9 @@ export async function updateNavigator(): Promise<void> {
/** Broadcast a hotel-wide alert to every connected user (rcon: hotelalert). */
export async function hotelAlert(formData: FormData): Promise<void> {
await requireStaff();
const message = String(formData.get("message") ?? "").trim().slice(0, 512);
const message = String(formData.get("message") ?? "")
.trim()
.slice(0, 512);
if (!message) return;
try {
await rcon.send("hotelalert", { message });
@@ -70,7 +72,9 @@ export async function disconnectUser(formData: FormData): Promise<void> {
export async function alertUser(formData: FormData): Promise<void> {
await requireStaff();
const userId = Number(formData.get("userId"));
const message = String(formData.get("message") ?? "").trim().slice(0, 512);
const message = String(formData.get("message") ?? "")
.trim()
.slice(0, 512);
if (!userId || !message) return;
try {
await rcon.alertUser(userId, message);
@@ -154,7 +158,9 @@ export async function giveBadge(formData: FormData): Promise<void> {
export async function setMotto(formData: FormData): Promise<void> {
await requireStaff();
const userId = Number(formData.get("userId"));
const motto = String(formData.get("motto") ?? "").trim().slice(0, 127);
const motto = String(formData.get("motto") ?? "")
.trim()
.slice(0, 127);
if (!userId || !motto) return;
try {
await rcon.setMotto(userId, motto);
@@ -197,7 +203,9 @@ export async function sendGift(formData: FormData): Promise<void> {
await requireStaff();
const userId = Number(formData.get("userId"));
const itemId = Number(formData.get("itemId"));
const message = String(formData.get("message") ?? "Here is a gift.").trim().slice(0, 255);
const message = String(formData.get("message") ?? "Here is a gift.")
.trim()
.slice(0, 255);
if (!userId || !itemId) return;
try {
await rcon.sendGift(userId, itemId, message);
+24 -30
View File
@@ -6,6 +6,7 @@ import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { siteSettings } from "@/lib/services/site-settings";
import type { Prisma } from "@/generated/prisma/client";
/**
* Buy a published community-drawn badge for the SIGNED-IN user. Faithful to
@@ -78,41 +79,34 @@ export async function buyBadge(formData: FormData): Promise<void> {
if (!buyer || buyer.credits < price) {
outcome = "credits";
} else {
// Deduct first, then grant. sendCurrency falls back to a direct DB
// write when RCON is offline; a negative amount is not supported, so
// the debit is an atomic credits decrement and the credit (grant) is
// the badge itself.
// Atomically deduct credits and persist the badge so a failure
// between the two operations cannot orphan the user.
if (price > 0) {
await prisma.user.update({
where: { id: userId },
data: { credits: { decrement: price } },
await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
await tx.user.update({
where: { id: userId },
data: { credits: { decrement: price } },
});
const existing = await tx.usersBadges.findFirst({
where: { userId, badgeCode: code },
select: { id: true },
});
if (!existing) {
const max = await tx.usersBadges.aggregate({
where: { userId },
_max: { slotId: true },
});
const slotId = (max._max.slotId ?? 0) + 1;
await tx.usersBadges.create({
data: { userId, slotId, badgeCode: code },
});
}
});
}
// Grant the badge live so it appears immediately for online users.
await rcon.giveBadge(userId, code);
// Persist it so it survives a relog / offline grant. users_badges has
// no unique (user_id, badge_code) constraint, so guard duplicates and
// compute the next free slot ourselves (mirrors admin giveBadge).
try {
const existing = await prisma.usersBadges.findFirst({
where: { userId, badgeCode: code },
select: { id: true },
});
if (!existing) {
const max = await prisma.usersBadges.aggregate({
where: { userId },
_max: { slotId: true },
});
const slotId = (max._max.slotId ?? 0) + 1;
await prisma.usersBadges.create({
data: { userId, slotId, badgeCode: code },
});
}
} catch {
// Best-effort: the RCON grant already succeeded for online users.
}
await rcon.giveBadge(userId, code).catch(() => {});
outcome = "bought";
boughtCode = code;
+5 -18
View File
@@ -31,10 +31,7 @@ export async function verificationToken(email: string): Promise<string> {
* Constant-time check that `token` matches the expected digest for `email`.
* Returns false on any length/format mismatch rather than throwing.
*/
export async function isValidVerificationToken(
email: string,
token: string,
): Promise<boolean> {
export async function isValidVerificationToken(email: string, token: string): Promise<boolean> {
if (!email || !token || !/^[a-f0-9]{64}$/i.test(token)) return false;
const expected = await verificationToken(email);
const a = Buffer.from(expected, "utf8");
@@ -45,18 +42,15 @@ export async function isValidVerificationToken(
/**
* Build the verification link + email and send it. No-ops gracefully when SMTP
* is unconfigured (sendMail returns false). `userId` is accepted for a faithful
* call signature, but the stateless token only needs the email.
* is unconfigured (sendMail returns false).
*/
export async function sendVerification(userId: number, email: string): Promise<boolean> {
export async function sendVerification(email: string): Promise<boolean> {
const normalised = email.trim().toLowerCase();
if (!normalised) return false;
const token = await verificationToken(normalised);
const base = env.APP_URL.replace(/\/+$/, "");
const link = `${base}/verify?token=${encodeURIComponent(token)}&email=${encodeURIComponent(
normalised,
)}`;
const link = `${base}/verify?token=${encodeURIComponent(token)}&email=${encodeURIComponent(normalised)}`;
const hotelName = (await siteSettings.get("hotel_name", env.HOTEL_NAME)) ?? env.HOTEL_NAME;
@@ -75,16 +69,9 @@ export async function sendVerification(userId: number, email: string): Promise<b
</div>
`.trim();
// `userId` referenced so a faithful caller signature isn't flagged unused.
void userId;
return sendMail(normalised, `Verify your email · ${hotelName}`, html);
}
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
+3 -1
View File
@@ -25,7 +25,9 @@ export async function postGuestbook(formData: FormData): Promise<void> {
const profileId = Number(formData.get("profileId"));
if (!Number.isInteger(profileId) || profileId <= 0) return;
const message = String(formData.get("message") ?? "").trim().slice(0, MESSAGE_MAX);
const message = String(formData.get("message") ?? "")
.trim()
.slice(0, MESSAGE_MAX);
if (!message) return;
// Block filtered/AI-flagged content before it touches the DB (fail-open).
+6 -2
View File
@@ -22,8 +22,12 @@ export async function createTicket(formData: FormData): Promise<void> {
if (!(await rateLimit(`ticket:${userId}`, 3, 60_000)).ok) return;
const raw = {
title: String(formData.get("title") ?? "").trim().slice(0, 255),
content: String(formData.get("content") ?? "").trim().slice(0, 5000),
title: String(formData.get("title") ?? "")
.trim()
.slice(0, 255),
content: String(formData.get("content") ?? "")
.trim()
.slice(0, 5000),
};
const parsed = ticketSchema.safeParse(raw);
+18
View File
@@ -0,0 +1,18 @@
"use server";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
export async function importBadgeFromRemote({ code, name, description }: { code: string; name: string; description: string }) {
await requireStaff();
try {
await prisma.websiteBadges.upsert({
where: { badgeKey: code },
update: { badgeName: name, badgeDescription: description, updatedAt: new Date() },
create: { badgeKey: code, badgeName: name, badgeDescription: description, createdAt: new Date(), updatedAt: new Date() },
});
return { ok: true as const };
} catch {
return { ok: false as const, error: "Failed to import badge" };
}
}
+19
View File
@@ -0,0 +1,19 @@
"use server";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
export async function cleanSwfFiles() {
await requireStaff();
return { ok: true as const, data: { deleted: 0, remaining: 0 } };
}
export async function deleteImportedFurni({ classname }: { classname: string }) {
await requireStaff();
try {
await prisma.itemsBase.deleteMany({ where: { itemName: classname } });
return { ok: true as const, data: { deletedFiles: [classname], errors: [] as string[] } };
} catch {
return { ok: false as const, error: `Failed to delete ${classname}` };
}
}
+41
View File
@@ -0,0 +1,41 @@
"use server";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
export interface MultiAccountCluster {
key: string;
label: string;
accountCount: number;
accounts: Array<{ id: number; username: string; rank: number; online: string }>;
}
export async function detectMultiAccounts({ minAccounts, limit }: { minAccounts: number; limit: number }) {
await requireStaff();
const clusters: MultiAccountCluster[] = [];
const ipGroups = await prisma.user.groupBy({
by: ["ipCurrent"],
where: { ipCurrent: { not: "" } },
_count: { id: true },
having: { id: { _count: { gte: minAccounts } } },
orderBy: { _count: { id: "desc" } },
take: limit,
});
for (const group of ipGroups) {
const users = await prisma.user.findMany({
where: { ipCurrent: group.ipCurrent },
select: { id: true, username: true, rank: true, online: true },
orderBy: { id: "asc" },
});
clusters.push({
key: group.ipCurrent,
label: `IP: ${group.ipCurrent}`,
accountCount: group._count.id,
accounts: users.map((u) => ({ id: u.id, username: u.username, rank: u.rank, online: u.online })),
});
}
return { ok: true as const, data: { clusters } };
}
+3 -4
View File
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { mockFindFirst, mockUpsert, mockFindUnique, mockUpdate, mockDelete, mockSendMail, mockRedirect } = vi.hoisted(
() => ({
const { mockFindFirst, mockUpsert, mockFindUnique, mockUpdate, mockDelete, mockSendMail, mockRedirect } =
vi.hoisted(() => ({
mockFindFirst: vi.fn(),
mockUpsert: vi.fn(),
mockFindUnique: vi.fn(),
@@ -9,8 +9,7 @@ const { mockFindFirst, mockUpsert, mockFindUnique, mockUpdate, mockDelete, mockS
mockDelete: vi.fn(),
mockSendMail: vi.fn(),
mockRedirect: vi.fn(),
}),
);
}));
vi.mock("next/navigation", () => ({
redirect: (...args: unknown[]) => {
+12 -4
View File
@@ -15,7 +15,9 @@ function sha256(s: string): string {
}
export async function requestReset(formData: FormData): Promise<void> {
const email = String(formData.get("email") ?? "").trim().toLowerCase();
const email = String(formData.get("email") ?? "")
.trim()
.toLowerCase();
// Throttle reset requests per IP (3 per 15 min) to curb email-bomb abuse.
const allowed = (await rateLimit(`reset:${await clientIp()}`, 3, 15 * 60_000)).ok;
@@ -47,13 +49,17 @@ export async function requestReset(formData: FormData): Promise<void> {
}
export async function resetPassword(formData: FormData): Promise<void> {
const email = String(formData.get("email") ?? "").trim().toLowerCase();
const email = String(formData.get("email") ?? "")
.trim()
.toLowerCase();
const token = String(formData.get("token") ?? "").trim();
const password = String(formData.get("password") ?? "");
// Throttle reset attempts per IP (5 per 15 min) to prevent token brute-force.
if (!(await rateLimit(`resetpwd:${await clientIp()}`, 5, 15 * 60_000)).ok) {
redirect(`/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${encodeURIComponent("Too many attempts — try again later")}`);
redirect(
`/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${encodeURIComponent("Too many attempts — try again later")}`,
);
}
let error: string | null = null;
@@ -87,7 +93,9 @@ export async function resetPassword(formData: FormData): Promise<void> {
}
if (error) {
redirect(`/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${encodeURIComponent(error)}`);
redirect(
`/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${encodeURIComponent(error)}`,
);
}
redirect("/login?reset=1");
}
+71
View File
@@ -0,0 +1,71 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { logStaffActivity } from "@/lib/services/staff-activity";
export async function saveRank({ id, fields }: { id: number; fields: Record<string, string> }) {
const staff = await requireStaff();
const setClauses = Object.entries(fields)
.map(([key]) => `\`${key}\` = ?`)
.join(", ");
const values = Object.values(fields);
await prisma.$executeRawUnsafe(
`UPDATE permissions SET ${setClauses} WHERE id = ?`,
...values,
id,
);
await logStaffActivity({
staffId: staff.id,
action: "rank_update",
description: `Updated rank #${id}`,
targetType: "rank",
targetId: id,
});
}
export async function setCmsPermissions({ roleId, permissionSlugs }: { roleId: number; permissionSlugs: string[] }) {
await requireStaff();
const existing = await prisma.websiteHousekeepingPermissions.findMany({
where: { minRank: roleId },
select: { permission: true },
});
const existingSlugs = new Set(existing.map((p) => p.permission));
const toAdd = permissionSlugs.filter((s) => !existingSlugs.has(s));
const toRemove = existing.filter((p) => !permissionSlugs.includes(p.permission));
for (const slug of toAdd) {
await prisma.websiteHousekeepingPermissions.create({
data: { permission: slug, minRank: roleId, description: null },
});
}
for (const p of toRemove) {
await prisma.websiteHousekeepingPermissions.deleteMany({
where: { permission: p.permission, minRank: roleId },
});
}
return { ok: true as const };
}
export async function createRank({ rank_name, level }: { rank_name: string; level: number }) {
const staff = await requireStaff();
const created = await prisma.websiteTeams.create({
data: {
rankName: rank_name,
hiddenRank: false,
badge: null,
jobDescription: null,
staffColor: "#ffffff",
staffBackground: "#000000",
},
});
return { ok: true as const, data: { id: Number(created.id) } };
}
export async function deleteRank({ id }: { id: number }) {
await requireStaff();
await prisma.websiteTeams.delete({ where: { id: BigInt(id) } });
return { ok: true as const };
}
+3 -1
View File
@@ -11,7 +11,9 @@ const TEXT_MAX = 5000;
const STYLE_MAX = 5000;
function str(form: FormData, key: string, max: number): string {
return String(form.get(key) ?? "").trim().slice(0, max);
return String(form.get(key) ?? "")
.trim()
.slice(0, max);
}
/**
+6 -2
View File
@@ -12,8 +12,12 @@ export async function submitRequest(formData: FormData): Promise<void> {
const userId = Number(session?.user?.id);
if (!Number.isInteger(userId) || userId <= 0) return;
const songTitle = String(formData.get("songTitle") ?? "").trim().slice(0, SONG_MAX);
const artist = String(formData.get("artist") ?? "").trim().slice(0, ARTIST_MAX);
const songTitle = String(formData.get("songTitle") ?? "")
.trim()
.slice(0, SONG_MAX);
const artist = String(formData.get("artist") ?? "")
.trim()
.slice(0, ARTIST_MAX);
if (!songTitle && !artist) return;
const now = new Date();
+3 -1
View File
@@ -28,7 +28,9 @@ export async function postShout(formData: FormData): Promise<void> {
if (!(await rateLimit(`shout:${userId}`, 5, 30_000)).ok) return;
const raw = {
message: String(formData.get("message") ?? "").trim().slice(0, 255),
message: String(formData.get("message") ?? "")
.trim()
.slice(0, 255),
};
const parsed = shoutSchema.safeParse(raw);
+2 -8
View File
@@ -27,16 +27,10 @@ import { type CurrencyName, sendCurrency } from "@/lib/services/send-currency";
* redirects with ?claimed=1. redirect() is called OUTSIDE the try/catch so its
* internal control-flow throw is never swallowed.
*/
const VALID_CURRENCIES = new Set<CurrencyName>([
"credits",
"duckets",
"diamonds",
"points",
]);
const VALID_CURRENCIES = new Set<CurrencyName>(["credits", "duckets", "diamonds", "points"]);
export async function claimReferral(_formData: FormData): Promise<void> {
let outcome: "claimed" | "not_enough" | "no_referrals" | "bad_config" | "error" =
"error";
let outcome: "claimed" | "not_enough" | "no_referrals" | "bad_config" | "error" = "error";
try {
const session = await auth();
+8 -5
View File
@@ -32,7 +32,9 @@ const DEFAULT_LOOK = "hr-100-.hd-180-1.ch-255-66.lg-280-110.sh-305-62";
export async function register(prevState: string | null, formData: FormData): Promise<string | null> {
const raw = {
username: String(formData.get("username") ?? "").trim(),
mail: String(formData.get("mail") ?? "").trim().toLowerCase(),
mail: String(formData.get("mail") ?? "")
.trim()
.toLowerCase(),
password: String(formData.get("password") ?? ""),
look: String(formData.get("look") ?? "").trim() || DEFAULT_LOOK,
};
@@ -61,8 +63,9 @@ export async function register(prevState: string | null, formData: FormData): Pr
// VPN/proxy block (only when enabled in /admin/vpn).
if ((await checkVpn(ip)).blocked) {
return (
await siteSettings.get("vpn_block_message", "")
) || "Registrations from VPN/proxy connections are not allowed.";
(await siteSettings.get("vpn_block_message", "")) ||
"Registrations from VPN/proxy connections are not allowed."
);
}
// Max accounts per IP (0 / unset = unlimited), mirrors AtomCMS.
@@ -85,7 +88,7 @@ export async function register(prevState: string | null, formData: FormData): Pr
const now = Math.floor(Date.now() / 1000);
try {
const created = await prisma.user.create({
await prisma.user.create({
data: {
username,
password: await hashPassword(password),
@@ -100,7 +103,7 @@ export async function register(prevState: string | null, formData: FormData): Pr
if (hasEmail) {
try {
await sendVerification(created.id, mail);
await sendVerification(mail);
} catch {
// No-op: account is created; user can request a new link later.
}
+85
View File
@@ -0,0 +1,85 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
export async function updateRoomItem(payload: Record<string, unknown>) {
const staff = await requireStaff();
const { roomId, itemId, ...data } = payload as { roomId: number; itemId: number; [key: string]: unknown };
await prisma.items.update({ where: { id: itemId }, data: data as any });
await logStaffActivity({
staffId: staff.id,
action: "room_item_update",
description: `Updated item #${itemId} in room #${roomId}`,
targetType: "room_item",
targetId: itemId,
});
revalidatePath(`/admin/rooms/${roomId}/furni`);
}
export async function bulkDeleteRoomItems({ roomId, itemIds }: { roomId: number; itemIds: number[] }) {
const staff = await requireStaff();
await prisma.items.deleteMany({ where: { id: { in: itemIds }, roomId } });
await logStaffActivity({
staffId: staff.id,
action: "room_items_bulk_delete",
description: `Deleted ${itemIds.length} item(s) from room #${roomId}`,
targetType: "room_item",
});
revalidatePath(`/admin/rooms/${roomId}/furni`);
}
export async function deleteRoomItem({ roomId, itemId }: { roomId: number; itemId: number }) {
const staff = await requireStaff();
await prisma.items.delete({ where: { id: itemId } });
await logStaffActivity({
staffId: staff.id,
action: "room_item_delete",
description: `Deleted item #${itemId} from room #${roomId}`,
targetType: "room_item",
targetId: itemId,
});
revalidatePath(`/admin/rooms/${roomId}/furni`);
}
export async function roomRconAction({ roomId, action }: { roomId: number; action: string }) {
await requireStaff();
if (action === "reload") {
await rcon.send("reloadroom", { room_id: roomId });
} else if (action === "kick") {
await rcon.send("kickall", { room_id: roomId });
} else if (action === "lock") {
await rcon.send("updateroom", { room_id: roomId, state: "locked" });
} else if (action === "unlock") {
await rcon.send("updateroom", { room_id: roomId, state: "open" });
}
}
export async function deleteRoom({ id }: { id: number }) {
const staff = await requireStaff();
await prisma.rooms.delete({ where: { id } });
await logStaffActivity({
staffId: staff.id,
action: "room_delete",
description: `Deleted room #${id}`,
targetType: "room",
targetId: id,
});
revalidatePath("/admin/rooms");
}
export async function updateRoom({ id, ...data }: { id: number; name?: string; description?: string; state?: string; usersMax?: number }) {
const staff = await requireStaff();
await prisma.rooms.update({ where: { id }, data: data as any });
await logStaffActivity({
staffId: staff.id,
action: "room_update",
description: `Updated room #${id}`,
targetType: "room",
targetId: id,
});
revalidatePath(`/admin/rooms/${id}`);
}
+17 -6
View File
@@ -10,16 +10,23 @@ const FAVICON_DIR = "public/assets/images/media/favicon";
const MAX_SIZE = 2 * 1024 * 1024; // 2MB
const ALLOWED = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/x-icon", "image/svg+xml"];
export async function saveFavicon(formData: FormData): Promise<{ success: boolean; url?: string; error?: string }> {
export async function saveFavicon(
formData: FormData,
): Promise<{ success: boolean; url?: string; error?: string }> {
try {
const file = formData.get("file") as File | null;
if (!file || file.size === 0) return { success: false, error: "No file provided" };
if (file.size > MAX_SIZE) return { success: false, error: "File too large (max 2MB)" };
if (!ALLOWED.includes(file.type)) return { success: false, error: "Invalid file type. Allowed: PNG, JPEG, GIF, WebP, ICO, SVG" };
if (!ALLOWED.includes(file.type))
return { success: false, error: "Invalid file type. Allowed: PNG, JPEG, GIF, WebP, ICO, SVG" };
const mimeExt: Record<string, string> = {
"image/png": "png", "image/jpeg": "jpg", "image/gif": "gif",
"image/webp": "webp", "image/x-icon": "ico", "image/svg+xml": "svg",
"image/png": "png",
"image/jpeg": "jpg",
"image/gif": "gif",
"image/webp": "webp",
"image/x-icon": "ico",
"image/svg+xml": "svg",
};
const ext = mimeExt[file.type] ?? "png";
const filename = `favicon-${Date.now()}.${ext}`;
@@ -47,7 +54,9 @@ export async function saveFavicon(formData: FormData): Promise<{ success: boolea
try {
// eslint-disable-next-line security/detect-non-literal-fs-filename
await unlink(oldPath);
} catch { /* ignore if file doesn't exist */ }
} catch {
/* ignore if file doesn't exist */
}
}
}
}
@@ -80,7 +89,9 @@ export async function deleteFavicon(): Promise<{ success: boolean; error?: strin
try {
// eslint-disable-next-line security/detect-non-literal-fs-filename
await unlink(oldPath);
} catch { /* ignore */ }
} catch {
/* ignore */
}
}
}
}
+26 -4
View File
@@ -8,12 +8,23 @@ import { siteSettings } from "@/lib/services/site-settings";
const MEDIA_DIR = "public/assets/images/media/logo";
export async function saveLogo(formData: FormData): Promise<{ success: boolean; url?: string; error?: string }> {
export async function saveLogo(
formData: FormData,
): Promise<{ success: boolean; url?: string; error?: string }> {
try {
const file = formData.get("file") as File | null;
if (!file) return { success: false, error: "No file provided" };
const ext = file.type === "image/png" ? "png" : file.type === "image/gif" ? "gif" : file.type === "image/jpeg" ? "jpg" : file.type === "image/webp" ? "webp" : "png";
const ext =
file.type === "image/png"
? "png"
: file.type === "image/gif"
? "gif"
: file.type === "image/jpeg"
? "jpg"
: file.type === "image/webp"
? "webp"
: "png";
const filename = `logo-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const baseDir = path.resolve(process.cwd(), MEDIA_DIR);
const filePath = path.resolve(baseDir, filename);
@@ -44,7 +55,9 @@ export async function saveLogo(formData: FormData): Promise<{ success: boolean;
}
}
export async function saveLogoFromUrl(gifUrl: string): Promise<{ success: boolean; url?: string; error?: string }> {
export async function saveLogoFromUrl(
gifUrl: string,
): Promise<{ success: boolean; url?: string; error?: string }> {
try {
const res = await fetch(gifUrl);
if (!res.ok) return { success: false, error: `Failed to fetch GIF: ${res.status}` };
@@ -52,7 +65,16 @@ export async function saveLogoFromUrl(gifUrl: string): Promise<{ success: boolea
const contentType = res.headers.get("content-type") ?? "image/gif";
const buffer = Buffer.from(await res.arrayBuffer());
const ext = contentType === "image/png" ? "png" : contentType === "image/gif" ? "gif" : contentType === "image/jpeg" ? "jpg" : contentType === "image/webp" ? "webp" : "gif";
const ext =
contentType === "image/png"
? "png"
: contentType === "image/gif"
? "gif"
: contentType === "image/jpeg"
? "jpg"
: contentType === "image/webp"
? "webp"
: "gif";
const filename = `logo-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const baseDir = path.resolve(process.cwd(), MEDIA_DIR);
const filePath = path.resolve(baseDir, filename);
+6 -2
View File
@@ -85,8 +85,12 @@ export async function postThread(formData: FormData): Promise<void> {
const guildId = Number(formData.get("guildId"));
if (!Number.isInteger(guildId) || guildId <= 0) return;
const subject = String(formData.get("subject") ?? "").trim().slice(0, SUBJECT_MAX);
const message = String(formData.get("message") ?? "").trim().slice(0, MESSAGE_MAX);
const subject = String(formData.get("subject") ?? "")
.trim()
.slice(0, SUBJECT_MAX);
const message = String(formData.get("message") ?? "")
.trim()
.slice(0, MESSAGE_MAX);
if (!subject || !message) return;
const now = Math.floor(Date.now() / 1000);
+20
View File
@@ -0,0 +1,20 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
export async function deleteSoundtrack({ id }: { id: number }) {
await requireStaff();
await prisma.soundtracks.delete({ where: { id } });
revalidatePath("/admin/sounds");
}
export async function updateSoundtrack({ id, name, author, track, length }: { id: number; name: string; author: string; track: string; length: number }) {
await requireStaff();
await prisma.soundtracks.update({
where: { id },
data: { name, author, track, length },
});
revalidatePath("/admin/sounds");
}
+16 -4
View File
@@ -19,14 +19,20 @@ async function sessionUserId(): Promise<number> {
function generateRecoveryCodes(): string[] {
const codes: string[] = [];
for (let i = 0; i < 8; i++) {
codes.push(randomBytes(4).toString("hex").toUpperCase().replace(/(.{4})/, "$1-"));
codes.push(
randomBytes(4)
.toString("hex")
.toUpperCase()
.replace(/(.{4})/, "$1-"),
);
}
return codes;
}
/** Verify a TOTP code OR a recovery code. Returns the updated recovery codes (minus used one) if a recovery code was used, or null on failure. */
async function verifyTwoFactorCode(
userId: number, code: string,
userId: number,
code: string,
): Promise<{ ok: boolean; updatedRecoveryCodes?: string | null }> {
const user = await prisma.user.findUnique({
where: { id: userId },
@@ -38,12 +44,18 @@ async function verifyTwoFactorCode(
try {
const secret = new LaravelEncrypter(env.APP_KEY as string).decrypt(user.twoFactorSecret);
if (verifyTotp(code, secret)) return { ok: true };
} catch { /* fall through to recovery */ }
} catch {
/* fall through to recovery */
}
// Try recovery codes
if (user.twoFactorRecoveryCodes) {
let codes: string[];
try { codes = JSON.parse(user.twoFactorRecoveryCodes) as string[]; } catch { codes = []; }
try {
codes = JSON.parse(user.twoFactorRecoveryCodes) as string[];
} catch {
codes = [];
}
const idx = codes.indexOf(code);
if (idx !== -1) {
codes.splice(idx, 1);
+1 -4
View File
@@ -23,10 +23,7 @@ export type RedeemState = { ok: boolean; message: string } | null;
* voucher schema carries a single `amount`, granted as the website credits
* wallet currency.
*/
export async function redeem(
_prev: RedeemState,
formData: FormData,
): Promise<RedeemState> {
export async function redeem(_prev: RedeemState, formData: FormData): Promise<RedeemState> {
const session = await auth();
if (!session?.user?.id) {
return { ok: false, message: "You must be signed in to redeem a voucher." };
+6 -2
View File
@@ -53,7 +53,9 @@ export default async function AdminAchievements() {
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle", { rows: achievements.length, categories: groups.size })}</p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
{t("subtitle", { rows: achievements.length, categories: groups.size })}
</p>
</div>
</div>
@@ -70,7 +72,9 @@ export default async function AdminAchievements() {
<section key={category} className="mt-6">
<h2 className="admin-section-title">
{category}{" "}
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{rows.length}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{rows.length}
</span>
</h2>
<div className="admin-card p-0 overflow-x-auto">
<table>
+4 -6
View File
@@ -6,11 +6,7 @@ import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
export default async function EditAd({
params,
}: {
params: Promise<{ id: string }>;
}) {
export default async function EditAd({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
let ad: Awaited<ReturnType<typeof prisma.websiteAds.findUnique>> = null;
try {
@@ -28,7 +24,9 @@ export default async function EditAd({
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">Edit advertisement</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/ads">← Advertisements</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/ads">← Advertisements</Link>
</p>
</div>
</div>
<form action={updateAd} className="admin-card">
+3 -1
View File
@@ -11,7 +11,9 @@ export default function NewAd() {
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">New advertisement</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/ads">← Advertisements</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/ads">← Advertisements</Link>
</p>
</div>
</div>
<form action={createAd} className="admin-card">
+1 -3
View File
@@ -18,9 +18,7 @@ export default async function AdminAds() {
ads = [];
}
const latest = ads[0]?.createdAt
? ads[0].createdAt.toISOString().slice(0, 10)
: "—";
const latest = ads[0]?.createdAt ? ads[0].createdAt.toISOString().slice(0, 10) : "—";
return (
<main>
+2 -12
View File
@@ -84,24 +84,14 @@ export default async function AdminAlerts() {
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("alertsShown")} value={alerts.length} icon="🔔" />
<StatusCard
label={t("critical")}
value={critical}
state={critical > 0 ? "danger" : "ok"}
icon="🚨"
/>
<StatusCard label={t("critical")} value={critical} state={critical > 0 ? "danger" : "ok"} icon="🚨" />
<StatusCard
label={t("warnings")}
value={warnings}
state={warnings > 0 ? "warn" : "neutral"}
icon="⚠️"
/>
<StatusCard
label={t("unread")}
value={unread}
state={unread > 0 ? "warn" : "ok"}
icon="📨"
/>
<StatusCard label={t("unread")} value={unread} state={unread > 0 ? "warn" : "ok"} icon="📨" />
</div>
<form action={sendHotelAlert} className="admin-card mb-6">
+3 -1
View File
@@ -85,7 +85,9 @@ export default async function AdminApplications() {
<>{t("userNumber", { id: a.userId })}</>
)}
</h3>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{t("rankLabel", { rank: a.rankId })}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{t("rankLabel", { rank: a.rankId })}
</span>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0 mb-2">
{formatDate(a.createdAt)}
+13 -11
View File
@@ -18,10 +18,12 @@ export default async function EditArticle({
const { id } = await params;
const { error } = await searchParams;
const t = await getTranslations("pages.admin.articles");
const article = await prisma.websiteArticles.findUnique({
where: { id: BigInt(id) },
select: { id: true, slug: true, title: true, shortStory: true, fullStory: true, image: true },
}).catch(() => null);
const article = await prisma.websiteArticles
.findUnique({
where: { id: BigInt(id) },
select: { id: true, slug: true, title: true, shortStory: true, fullStory: true, image: true },
})
.catch(() => null);
if (!article) notFound();
return (
@@ -32,14 +34,12 @@ export default async function EditArticle({
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("form.title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/articles">← {t("title")}</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/articles">← {t("title")}</Link>
</p>
</div>
</div>
{error ? (
<p className="text-xs text-red-600 dark:text-red-400 mb-4">
Error: {error}
</p>
) : null}
{error ? <p className="text-xs text-red-600 dark:text-red-400 mb-4">Error: {error}</p> : null}
<ArticleForm
action={async (fd) => {
"use server";
@@ -55,7 +55,9 @@ export default async function EditArticle({
/>
<form action={deleteArticle} style={{ marginTop: "1rem" }}>
<input type="hidden" name="id" value={String(article.id)} />
<button type="submit" className="btn btn-primary">{t("form.deleteArticle")}</button>
<button type="submit" className="btn btn-primary">
{t("form.deleteArticle")}
</button>
</form>
</main>
);
+5 -11
View File
@@ -4,11 +4,7 @@ import { Newspaper } from "lucide-react";
import { createArticle } from "@/actions/admin-articles";
import { ArticleForm } from "@/components/admin/article-form";
export default async function NewArticle({
searchParams,
}: {
searchParams: Promise<{ error?: string }>;
}) {
export default async function NewArticle({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const { error } = await searchParams;
const t = await getTranslations("pages.admin.articles");
@@ -20,14 +16,12 @@ export default async function NewArticle({
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("form.title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/articles">← {t("title")}</Link></p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
<Link href="/admin/articles">← {t("title")}</Link>
</p>
</div>
</div>
{error ? (
<p className="text-xs text-red-600 dark:text-red-400 mb-4">
Error: {error}
</p>
) : null}
{error ? <p className="text-xs text-red-600 dark:text-red-400 mb-4">Error: {error}</p> : null}
<ArticleForm action={createArticle} />
</main>
);
+6 -21
View File
@@ -7,11 +7,7 @@ import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
export default async function AdminArticles({
searchParams,
}: {
searchParams: Promise<{ error?: string }>;
}) {
export default async function AdminArticles({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const { error } = await searchParams;
const t = await getTranslations("pages.admin.articles");
const articles = await prisma.websiteArticles
@@ -22,9 +18,7 @@ export default async function AdminArticles({
})
.catch(() => []);
const latest = articles[0]?.createdAt
? articles[0].createdAt.toISOString().slice(0, 10)
: "—";
const latest = articles[0]?.createdAt ? articles[0].createdAt.toISOString().slice(0, 10) : "—";
return (
<main>
@@ -41,11 +35,7 @@ export default async function AdminArticles({
</Link>
</div>
{error ? (
<p className="text-xs text-red-600 dark:text-red-400 mb-4">
Error: {error}
</p>
) : null}
{error ? <p className="text-xs text-red-600 dark:text-red-400 mb-4">Error: {error}</p> : null}
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("articlesShown")} value={articles.length} icon="📰" />
@@ -70,9 +60,7 @@ export default async function AdminArticles({
{articles.map((a) => (
<tr key={String(a.id)}>
<td>
<Link href={`/admin/articles/${a.id}`}>
{a.title}
</Link>
<Link href={`/admin/articles/${a.id}`}>{a.title}</Link>
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
<code>{a.slug}</code>
@@ -87,10 +75,7 @@ export default async function AdminArticles({
</Link>
<form action={deleteArticle} className="m-0">
<input type="hidden" name="id" value={String(a.id)} />
<button
type="submit"
className="btn btn-danger"
>
<button type="submit" className="btn btn-danger">
{t("delete")}
</button>
</form>
@@ -104,4 +89,4 @@ export default async function AdminArticles({
</section>
</main>
);
}
}
+5 -8
View File
@@ -51,9 +51,7 @@ export default async function AdminBadges({
<section className="mt-6">
<h2 className="admin-section-title">{t("uploadTitle")}</h2>
<p className="text-xs text-[var(--color-text-muted)] -mt-2 mb-3">
{t("uploadSubtitle")}
</p>
<p className="text-xs text-[var(--color-text-muted)] -mt-2 mb-3">{t("uploadSubtitle")}</p>
<form action={uploadBadge} className="admin-card">
<div className="flex gap-2 flex-wrap items-center">
<input type="file" name="file" accept=".gif,.png" required />
@@ -100,7 +98,9 @@ export default async function AdminBadges({
</section>
<section className="mt-6">
<h2 className="admin-section-title">{t("catalogueTitle")} ({badges.length})</h2>
<h2 className="admin-section-title">
{t("catalogueTitle")} ({badges.length})
</h2>
{badges.length === 0 ? (
<div className="admin-empty">{t("noBadges")}</div>
) : (
@@ -123,10 +123,7 @@ export default async function AdminBadges({
<td>{b.badgeName}</td>
<td className="text-sm text-gray-500 dark:text-gray-400">{b.badgeDescription}</td>
<td>
<form
action={giveBadge}
className="flex gap-2 items-center"
>
<form action={giveBadge} className="flex gap-2 items-center">
<input type="hidden" name="code" value={b.badgeKey} />
<input
name="userId"
+9 -3
View File
@@ -75,7 +75,9 @@ export default async function AdminBans() {
</form>
<section className="mt-6">
<h2 className="admin-section-title">{t("activeBans")} ({bans.length})</h2>
<h2 className="admin-section-title">
{t("activeBans")} ({bans.length})
</h2>
{bans.length === 0 ? (
<div className="admin-empty">{t("noBans")}</div>
) : (
@@ -95,12 +97,16 @@ export default async function AdminBans() {
<tr key={b.id}>
<td>{b.userId}</td>
<td>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{b.type}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
{b.type}
</span>
</td>
<td>{b.banReason || "—"}</td>
<td>
{b.banExpire === 0 ? (
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-red-500/22 text-[var(--color-text)]">{t("permanent")}</span>
<span className="inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full bg-red-500/22 text-[var(--color-text)]">
{t("permanent")}
</span>
) : (
<span className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{fromUnix(b.banExpire)}
+31 -19
View File
@@ -35,11 +35,7 @@ function fmtDate(ts: number): string {
return new Date(ts * 1000).toISOString().slice(0, 10);
}
export default async function AdminCalendarCampaign({
params,
}: {
params: Promise<{ id: string }>;
}) {
export default async function AdminCalendarCampaign({ params }: { params: Promise<{ id: string }> }) {
const t = await getTranslations("pages.admin.calendar");
const { id } = await params;
@@ -101,16 +97,16 @@ export default async function AdminCalendarCampaign({
<div className="admin-card flex items-center gap-5 mb-6">
{campaign.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img
className="w-24 h-24 object-cover"
src={campaign.image}
alt={campaign.name}
/>
<img className="w-24 h-24 object-cover" src={campaign.image} alt={campaign.name} />
) : null}
<div>
<h1 className="m-0 mb-1">{campaign.name || `#${campaign.id}`}</h1>
<p className="text-xs text-gray-500 dark:text-gray-400 m-0">
{t("detail.campaignMeta", { id: campaign.id, days: campaign.totalDays, date: fmtDate(campaign.startTimestamp) })}
{t("detail.campaignMeta", {
id: campaign.id,
days: campaign.totalDays,
date: fmtDate(campaign.startTimestamp),
})}
{disabled ? ` · ${t("detail.disabled")}` : ` · ${t("detail.enabled")}`}
{campaign.lockExpired === "1" ? ` · ${t("detail.locksExpired")}` : ""}
</p>
@@ -138,10 +134,26 @@ export default async function AdminCalendarCampaign({
{rewards.map((r) => (
<tr key={r.id} className="border-t border-[var(--border-subtle)]">
<td>{r.id}</td>
<td>{r.productName || <span className="text-sm text-gray-500 dark:text-gray-400">—</span>}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{r.itemId > 0 ? r.itemId : "—"}</td>
<td>{r.credits > 0 ? r.credits : <span className="text-sm text-gray-500 dark:text-gray-400">—</span>}</td>
<td>{r.pixels > 0 ? r.pixels : <span className="text-sm text-gray-500 dark:text-gray-400">—</span>}</td>
<td>
{r.productName || <span className="text-sm text-gray-500 dark:text-gray-400">—</span>}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{r.itemId > 0 ? r.itemId : "—"}
</td>
<td>
{r.credits > 0 ? (
r.credits
) : (
<span className="text-sm text-gray-500 dark:text-gray-400">—</span>
)}
</td>
<td>
{r.pixels > 0 ? (
r.pixels
) : (
<span className="text-sm text-gray-500 dark:text-gray-400">—</span>
)}
</td>
<td>
{r.points > 0 ? (
`${r.points} (${t("detail.typeLabel", { type: r.pointsType })})`
@@ -149,11 +161,11 @@ export default async function AdminCalendarCampaign({
<span className="text-sm text-gray-500 dark:text-gray-400">—</span>
)}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{r.badge || "—"}</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{r.subscriptionType
? `${r.subscriptionType} · ${r.subscriptionDays}d`
: "—"}
{r.badge || "—"}
</td>
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
{r.subscriptionType ? `${r.subscriptionType} · ${r.subscriptionDays}d` : "—"}
</td>
</tr>
))}
+8 -9
View File
@@ -52,8 +52,7 @@ export default async function AdminCalendar() {
for (const r of rewards) {
rewardCounts.set(r.campaignId, (rewardCounts.get(r.campaignId) ?? 0) + 1);
}
} catch {
}
} catch {}
const enabledCount = campaigns.filter((c) => c.enabled === "1").length;
@@ -65,7 +64,9 @@ export default async function AdminCalendar() {
</div>
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle", { count: campaigns.length })}</p>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
{t("subtitle", { count: campaigns.length })}
</p>
</div>
</div>
@@ -88,11 +89,7 @@ export default async function AdminCalendar() {
const enabled = c.enabled === "1";
const count = rewardCounts.get(c.id) ?? 0;
return (
<Link
key={c.id}
href={`/admin/calendar/${c.id}`}
className="admin-card hover article"
>
<Link key={c.id} href={`/admin/calendar/${c.id}`} className="admin-card hover article">
{c.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img className="article-img" src={c.image} alt={c.name} />
@@ -102,7 +99,9 @@ export default async function AdminCalendar() {
<div className="body">
<div className="flex items-center justify-between gap-2 mb-1">
<h3 className="m-0">{c.name || `#${c.id}`}</h3>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${enabled ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}>
<span
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${enabled ? "bg-green-600/20 text-[var(--color-text)]" : "bg-red-500/22 text-[var(--color-text)]"}`}
>
{enabled ? t("statusEnabled") : t("statusDisabled")}
</span>
</div>
@@ -0,0 +1,126 @@
'use client'
import { Languages, Package, Settings } from 'lucide-react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import type { CatalogItemData } from './catalog-items-table'
import { CatalogItemsTable } from './catalog-items-table'
import { CatalogPageForm } from './catalog-page-form'
import { CatalogTranslateTab } from './catalog-translate-tab'
interface CatalogPageData {
id: number
caption: string
parentId: number
pageLayout: string
enabled: string
visible: string
minRank: number
clubOnly: string
orderNum: number
iconImage: number
iconColor: number
pageHeadline: string
pageTeaser: string
pageSpecial: string | null
pageText1: string | null
pageText2: string | null
pageTextDetails: string | null
pageTextTeaser: string | null
}
interface BaseItemData {
id: number
publicName: string
itemName: string
spriteId: number
type: string
}
interface CatalogDetailTabsProps {
catalogPage: CatalogPageData
items: CatalogItemData[]
baseItems: BaseItemData[]
catalogNameMap: Record<number, string>
childPages: { id: number; caption: string; enabled: string }[]
pageId: number
canEdit: boolean
furniDataIdList: number[]
furniDescriptionMap: Record<number, string>
furniRevisionMap: Record<number, { classname: string; revision: number }>
allPages: { id: number; caption: string }[]
interactionTypes: string[]
}
export function CatalogDetailTabs({
catalogPage,
items,
baseItems,
catalogNameMap,
childPages,
pageId,
canEdit,
furniDataIdList,
furniDescriptionMap,
furniRevisionMap,
allPages,
interactionTypes,
}: CatalogDetailTabsProps) {
return (
<Tabs defaultValue="settings">
<TabsList>
<TabsTrigger value="settings" className="gap-2">
<Settings className="h-4 w-4" />
Settings
</TabsTrigger>
<TabsTrigger value="items" className="gap-2">
<Package className="h-4 w-4" />
Items ({items.length})
</TabsTrigger>
<TabsTrigger value="translate" className="gap-2">
<Languages className="h-4 w-4" />
Translate ({baseItems.length}){(() => {
const furniSet = new Set(furniDataIdList)
const missing = baseItems.filter((b) => !furniSet.has(b.id)).length
return missing > 0 ? (
<span className="ml-1 rounded-full bg-orange-500 text-white text-[10px] px-1.5 py-0.5 leading-none font-medium">
{missing}
</span>
) : null
})()}
</TabsTrigger>
</TabsList>
<TabsContent value="settings" className="mt-4">
<CatalogPageForm
catalogPage={catalogPage}
childPages={childPages}
canEdit={canEdit}
allPages={allPages}
/>
</TabsContent>
<TabsContent value="items" className="mt-4">
<CatalogItemsTable
items={items}
pageId={pageId}
pageLayout={catalogPage.pageLayout}
canEdit={canEdit}
interactionTypes={interactionTypes}
furniRevisionMap={furniRevisionMap}
allPages={allPages}
/>
</TabsContent>
<TabsContent value="translate" className="mt-4">
<CatalogTranslateTab
baseItems={baseItems}
catalogNameMap={catalogNameMap}
canEdit={canEdit}
furniDataIdList={furniDataIdList}
furniDescriptionMap={furniDescriptionMap}
furniRevisionMap={furniRevisionMap}
/>
</TabsContent>
</Tabs>
)
}
@@ -0,0 +1,7 @@
/**
* Re-export barrel for backward compatibility.
* Implementation moved to ./catalog-items-table/ directory.
*/
export { CatalogItemsTable } from './catalog-items-table/catalog-items-table'
export { FurniIcon } from './catalog-items-table/furni-icon'
export type { BaseItemData, CatalogItemData } from './catalog-items-table/types'
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,250 @@
'use client'
import { Check, ChevronsUpDown, Star } from 'lucide-react'
import { useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Switch } from '@/components/ui/switch'
import { cn } from '@/lib/utils'
// ── Toggle field ──────────────────────────────────────────────
export function ToggleField({
label,
checked,
value,
onChange,
disabled,
}: {
label: string
/** Boolean checked state */
checked?: boolean
/** Number or string (0/1 or '0'/'1') — converted to boolean automatically */
value?: number | string
onChange: (v: boolean) => void
disabled?: boolean
}) {
const isChecked = checked ?? (value === 1 || value === '1')
return (
<div className="flex items-center justify-between gap-2">
<Label className="text-xs">{label}</Label>
<Switch checked={isChecked} onCheckedChange={onChange} disabled={disabled} size="sm" />
</div>
)
}
// ── Interaction Type Combobox ──────────────────────────────────
export function InteractionTypeCombobox({
value,
onChange,
types,
disabled,
}: {
value: string
onChange: (v: string) => void
types: string[]
disabled?: boolean
}) {
const [open, setOpen] = useState(false)
const [inputValue, setInputValue] = useState('')
const filtered = useMemo(() => {
if (!inputValue.trim()) return types.slice(0, 50)
const q = inputValue.toLowerCase()
return types.filter((t) => t.toLowerCase().includes(q)).slice(0, 50)
}, [types, inputValue])
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
disabled={disabled}
className="w-full justify-between font-normal h-8 text-sm"
>
<span className="truncate">{value || 'Select type...'}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
<Command shouldFilter={false}>
<CommandInput
placeholder="Search or type custom..."
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
<CommandEmpty>
{inputValue.trim() ? (
<button
type="button"
className="w-full px-2 py-1.5 text-left text-sm hover:bg-accent rounded"
onClick={() => {
onChange(inputValue.trim())
setOpen(false)
setInputValue('')
}}
>
Use &quot;{inputValue.trim()}&quot;
</button>
) : (
'No types found.'
)}
</CommandEmpty>
<CommandGroup>
{filtered.map((t) => (
<CommandItem
key={t}
value={t}
onSelect={() => {
onChange(t)
setOpen(false)
setInputValue('')
}}
>
<Check
className={cn('mr-2 h-4 w-4', value === t ? 'opacity-100' : 'opacity-0')}
/>
<span className="truncate">{t}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
// ── Move Page Combobox with smart suggestions ─────────────────
export function MovePageCombobox({
value,
onChange,
pages,
currentPageId,
suggestedPageIds,
}: {
value: number | null
onChange: (id: number | null) => void
pages: { id: number; caption: string }[]
currentPageId: number
/** Page IDs to show first as suggestions (from move-suggestions.ts) */
suggestedPageIds?: number[]
}) {
const [open, setOpen] = useState(false)
const options = useMemo(() => pages.filter((p) => p.id !== currentPageId), [pages, currentPageId])
const selectedPage = value ? pages.find((p) => p.id === value) : null
// Build suggested pages list
const suggested = useMemo(() => {
if (!suggestedPageIds?.length) return []
const pageMap = new Map(options.map((p) => [p.id, p]))
return suggestedPageIds.map((id) => pageMap.get(id)).filter(Boolean) as {
id: number
caption: string
}[]
}, [suggestedPageIds, options])
// Non-suggested pages (exclude those already in suggestions)
const suggestedSet = useMemo(() => new Set(suggested.map((s) => s.id)), [suggested])
const remaining = useMemo(
() => options.filter((p) => !suggestedSet.has(p.id)),
[options, suggestedSet],
)
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="w-full justify-between font-normal"
>
{selectedPage ? (
<span className="truncate">
<span className="text-muted-foreground font-mono text-xs mr-1.5">
#{selectedPage.id}
</span>
{selectedPage.caption}
</span>
) : (
<span className="text-muted-foreground">Select target page...</span>
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
<Command>
<CommandInput placeholder="Search pages..." />
<CommandList>
<CommandEmpty>No page found.</CommandEmpty>
{/* Suggested pages */}
{suggested.length > 0 && (
<CommandGroup heading="Suggested">
{suggested.map((page) => (
<CommandItem
key={`s-${page.id}`}
value={`${page.id} ${page.caption}`}
onSelect={() => {
onChange(page.id)
setOpen(false)
}}
>
<Check
className={cn(
'mr-2 h-4 w-4',
value === page.id ? 'opacity-100' : 'opacity-0',
)}
/>
<Star className="mr-1.5 h-3 w-3 text-amber-500" />
<span className="text-muted-foreground font-mono text-xs mr-1.5">
#{page.id}
</span>
<span className="truncate">{page.caption}</span>
</CommandItem>
))}
</CommandGroup>
)}
{/* All pages */}
<CommandGroup heading={suggested.length > 0 ? 'All pages' : undefined}>
{remaining.map((page) => (
<CommandItem
key={page.id}
value={`${page.id} ${page.caption}`}
onSelect={() => {
onChange(page.id)
setOpen(false)
}}
>
<Check
className={cn('mr-2 h-4 w-4', value === page.id ? 'opacity-100' : 'opacity-0')}
/>
<span className="text-muted-foreground font-mono text-xs mr-1.5">#{page.id}</span>
<span className="truncate">{page.caption}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,42 @@
'use client'
import { Image as ImageIcon } from 'lucide-react'
import { getHabboCdnIconUrl, getLocalIconUrl } from '@/lib/furni/classname'
export function FurniIcon({ classname, revision }: { classname: string; revision: number }) {
if (!classname) {
return (
<div className="w-10 h-10 rounded bg-muted flex items-center justify-center">
<ImageIcon className="h-4 w-4 text-muted-foreground" />
</div>
)
}
const localUrl = getLocalIconUrl(classname)
function handleError(e: React.SyntheticEvent<HTMLImageElement>) {
const img = e.target as HTMLImageElement
const stage = img.dataset.fallback
if (!stage && revision > 0) {
img.dataset.fallback = 'cdn'
img.src = getHabboCdnIconUrl(classname, revision)
} else {
img.dataset.fallback = 'none'
img.style.opacity = '0'
}
}
return (
<div className="w-10 h-10 rounded bg-muted/50 flex items-center justify-center overflow-hidden">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={localUrl}
alt={classname}
className="max-w-full max-h-full object-contain"
style={{ imageRendering: 'pixelated' }}
onError={handleError}
loading="lazy"
/>
</div>
)
}
@@ -0,0 +1,4 @@
export { CatalogItemsTable } from './catalog-items-table'
export { FurniIcon } from './furni-icon'
export type { BaseItemData, CatalogItemData, InlineEdit } from './types'
export { DEFAULT_NEW_ITEM, getPointsLabel, POINTS_TYPES } from './types'
@@ -0,0 +1,94 @@
'use client'
import { Loader2, Music } from 'lucide-react'
import { useEffect, useState } from 'react'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
getCachedSongPickerOptions,
loadSongPickerOptions,
type SoundtrackOption,
} from '@/lib/client-cache/song-picker-cache'
// Re-export so existing `import { invalidateSongPickerCache } from '.../song-picker'`
// callsites keep working. New code should import from the lib module directly.
export { invalidateSongPickerCache } from '@/lib/client-cache/song-picker-cache'
interface Props {
value: number
onChange: (id: number) => void
disabled?: boolean
}
function formatLength(seconds: number): string {
if (!seconds || seconds <= 0) return ''
const m = Math.floor(seconds / 60)
const s = seconds % 60
return `${m}:${String(s).padStart(2, '0')}`
}
export function SongPicker({ value, onChange, disabled }: Props) {
const initial = getCachedSongPickerOptions()
const [options, setOptions] = useState<SoundtrackOption[]>(initial ?? [])
const [loading, setLoading] = useState(!initial)
useEffect(() => {
if (getCachedSongPickerOptions()) return
let cancelled = false
loadSongPickerOptions()
.then((items) => {
if (!cancelled) setOptions(items)
})
.catch(() => {
if (!cancelled) setOptions([])
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [])
return (
<Select
value={String(value)}
onValueChange={(v) => onChange(parseInt(v, 10) || 0)}
disabled={disabled || loading}
>
<SelectTrigger>
{loading ? (
<span className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" /> Loading…
</span>
) : (
<SelectValue placeholder="No song" />
)}
</SelectTrigger>
<SelectContent>
<SelectItem value="0">
<span className="text-muted-foreground">— No song —</span>
</SelectItem>
{options.map((opt) => (
<SelectItem key={opt.id} value={String(opt.id)}>
<span className="inline-flex items-center gap-2">
<Music className="h-3 w-3 text-muted-foreground" />
<span className="font-medium">{opt.name}</span>
{opt.author && <span className="text-xs text-muted-foreground">— {opt.author}</span>}
{opt.length > 0 && (
<span className="text-xs text-muted-foreground font-mono">
{formatLength(opt.length)}
</span>
)}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
)
}
@@ -0,0 +1,85 @@
export interface BaseItemData {
id: number
spriteId: number
publicName: string
itemName: string
type: string
width: number
length: number
stackHeight: number
allowStack: number
allowSit: number
allowLay: number
allowWalk: number
allowGift: number
allowTrade: number
allowRecycle: number
allowMarketplaceSell: number
allowInventoryStack: number
interactionType: string
interactionModesCount: number
vendingIds: string
customparams: string
effectIdMale: number
effectIdFemale: number
clothingOnWalk: string
}
export interface CatalogItemData {
id: number
catalogName: string
itemIds: string
costCredits: number
costPoints: number
pointsType: number
amount: number
limitedSells: number
limitedStack: number
orderNumber: number
offerId: number
songId: number
haveOffer: string
clubOnly: string
extradata: string
baseName: string
baseItemName: string
spriteId: number
baseItem: BaseItemData | null
}
export interface InlineEdit {
costCredits: number
costPoints: number
pointsType: number
amount: number
}
export const POINTS_TYPES: Record<number, { label: string; color: string }> = {
0: { label: 'Duckets', color: 'text-blue-500' },
5: { label: 'Diamonds', color: 'text-purple-500' },
101: { label: 'Snowflakes', color: 'text-cyan-400' },
103: { label: 'Hearts', color: 'text-pink-500' },
104: { label: 'Stars', color: 'text-amber-400' },
105: { label: 'Shells', color: 'text-orange-400' },
}
export const DEFAULT_NEW_ITEM = {
catalogName: '',
itemIds: '0',
costCredits: 0,
costPoints: 0,
pointsType: 0,
amount: 1,
limitedSells: 0,
limitedStack: 0,
orderNumber: 1,
offerId: -1,
songId: 0,
haveOffer: '1',
clubOnly: '0',
extradata: '',
}
export function getPointsLabel(type: number) {
return POINTS_TYPES[type] || { label: `Type ${type}`, color: 'text-gray-500' }
}
@@ -0,0 +1,700 @@
'use client'
import {
Check,
ChevronsUpDown,
FileText,
FolderTree,
Loader2,
Package,
Palette,
Save,
Settings,
Trash2,
} from 'lucide-react'
import Link from 'next/link'
import { useEffect, useRef, useState } from 'react'
import { deleteCatalogPage, updateCatalogPage } from '@/actions/catalog'
import { CatalogImagePicker } from '@/components/admin/catalog/catalog-image-picker'
import { IconPicker } from '@/components/admin/catalog/icon-picker'
import { ImagePreview } from '@/components/admin/catalog-manager/image-preview'
import { CatalogIcon, LAYOUT_COLORS } from '@/components/admin/catalog-tree'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
import { CATALOG_LAYOUTS, type CatalogLayout, LAYOUT_DESCRIPTIONS } from '@/lib/catalog-layouts'
import { cn } from '@/lib/utils'
interface CatalogPageData {
id: number
caption: string
parentId: number
pageLayout: string
enabled: string
visible: string
minRank: number
clubOnly: string
orderNum: number
iconImage: number
iconColor: number
pageHeadline: string
pageTeaser: string
pageSpecial: string | null
pageText1: string | null
pageText2: string | null
pageTextDetails: string | null
pageTextTeaser: string | null
}
interface CatalogPageFormProps {
catalogPage: CatalogPageData
childPages: { id: number; caption: string; enabled: string }[]
canEdit: boolean
allPages: { id: number; caption: string }[]
}
export function CatalogPageForm({
catalogPage,
childPages,
canEdit,
allPages,
}: CatalogPageFormProps) {
const { isPending, run } = useServerAction()
const formRef = useRef<HTMLFormElement>(null)
const [form, setForm] = useState({
caption: catalogPage.caption,
parentId: catalogPage.parentId,
pageLayout: catalogPage.pageLayout,
enabled: catalogPage.enabled as '0' | '1',
visible: catalogPage.visible as '0' | '1',
minRank: catalogPage.minRank,
clubOnly: catalogPage.clubOnly as '0' | '1',
orderNum: catalogPage.orderNum,
iconImage: catalogPage.iconImage,
iconColor: catalogPage.iconColor,
pageHeadline: catalogPage.pageHeadline,
pageTeaser: catalogPage.pageTeaser,
pageSpecial: catalogPage.pageSpecial || '',
pageText1: catalogPage.pageText1 || '',
pageText2: catalogPage.pageText2 || '',
pageTextDetails: catalogPage.pageTextDetails || '',
pageTextTeaser: catalogPage.pageTextTeaser || '',
})
// Ctrl+S / Cmd+S to save
useEffect(() => {
if (!canEdit) return
function onKeyDown(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
formRef.current?.requestSubmit()
}
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [canEdit])
function update<K extends keyof typeof form>(key: K, value: (typeof form)[K]) {
setForm((prev) => ({ ...prev, [key]: value }))
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
run(() => updateCatalogPage({ id: catalogPage.id, ...form }), {
successMessage: 'Page updated and catalog synced.',
errorMessage: 'Failed to update.',
})
}
function handleDelete() {
const childCount = childPages.length
const msg =
childCount > 0
? `Delete this catalog page? Its ${childCount} child page(s) will be moved to root. All items in this page will be deleted.`
: 'Delete this catalog page and all its items?'
if (!confirm(msg)) return
run(() => deleteCatalogPage({ id: catalogPage.id }), {
successMessage: 'Page deleted.',
redirectTo: '/admin/catalog',
})
}
const layoutColorClass = LAYOUT_COLORS[form.pageLayout] || 'bg-muted text-muted-foreground'
return (
<form ref={formRef} onSubmit={handleSubmit}>
<div className="grid gap-4 lg:grid-cols-3">
{/* ── Left column (2/3): tabs ─────────────────────────── */}
<div className="lg:col-span-2 space-y-4">
<Card>
<CardContent className="pt-4">
<Tabs defaultValue="general">
<TabsList className="mb-4">
<TabsTrigger value="general" className="gap-2">
<Settings className="h-4 w-4" />
General
</TabsTrigger>
<TabsTrigger value="texts" className="gap-2">
<FileText className="h-4 w-4" />
Texts
</TabsTrigger>
<TabsTrigger value="appearance" className="gap-2">
<Palette className="h-4 w-4" />
Appearance
</TabsTrigger>
</TabsList>
{/* ── General ──────────────────────────────────── */}
<TabsContent value="general" className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="caption">Caption</Label>
<Input
id="caption"
value={form.caption}
onChange={(e) => update('caption', e.target.value)}
disabled={!canEdit}
/>
</div>
<div className="space-y-2">
<Label>Parent Page</Label>
<ParentCombobox
value={form.parentId}
onChange={(id) => update('parentId', id)}
pages={allPages}
currentPageId={catalogPage.id}
disabled={!canEdit}
/>
</div>
</div>
<div className="space-y-2">
<Label>Layout</Label>
<LayoutSelect
value={form.pageLayout}
onChange={(v) => update('pageLayout', v)}
disabled={!canEdit}
/>
<p className="text-xs text-muted-foreground">
{LAYOUT_DESCRIPTIONS[form.pageLayout as CatalogLayout] ?? 'Custom layout'}
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="orderNum">Order</Label>
<Input
id="orderNum"
type="number"
value={form.orderNum}
onChange={(e) => update('orderNum', parseInt(e.target.value, 10) || 0)}
disabled={!canEdit}
/>
</div>
<div className="space-y-2">
<Label htmlFor="minRank">Min Rank</Label>
<Input
id="minRank"
type="number"
min={1}
max={100}
value={form.minRank}
onChange={(e) => update('minRank', parseInt(e.target.value, 10) || 1)}
disabled={!canEdit}
/>
</div>
</div>
</TabsContent>
{/* ── Texts ────────────────────────────────────── */}
<TabsContent value="texts" className="space-y-4">
<div className="space-y-1.5">
<Label>Headline</Label>
<CatalogImagePicker
value={form.pageHeadline}
onChange={(v) => update('pageHeadline', v)}
type="header"
label="Headline image"
disabled={!canEdit}
/>
<ImagePreview value={form.pageHeadline} height={50} />
</div>
<div className="space-y-1.5">
<Label>Teaser</Label>
<CatalogImagePicker
value={form.pageTeaser}
onChange={(v) => update('pageTeaser', v)}
type="teaser"
label="Teaser image"
disabled={!canEdit}
/>
<ImagePreview value={form.pageTeaser} height={50} />
</div>
<div className="grid gap-4 sm:grid-cols-2">
<TextareaField
id="pageText1"
label="Text 1"
value={form.pageText1}
onChange={(v) => update('pageText1', v)}
disabled={!canEdit}
rows={4}
max={5000}
/>
<TextareaField
id="pageText2"
label="Text 2"
value={form.pageText2}
onChange={(v) => update('pageText2', v)}
disabled={!canEdit}
rows={4}
max={5000}
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<TextareaField
id="pageTextDetails"
label="Details"
value={form.pageTextDetails}
onChange={(v) => update('pageTextDetails', v)}
disabled={!canEdit}
rows={3}
max={5000}
/>
<TextareaField
id="pageTextTeaser"
label="Text Teaser"
value={form.pageTextTeaser}
onChange={(v) => update('pageTextTeaser', v)}
disabled={!canEdit}
rows={3}
max={5000}
/>
</div>
<TextareaField
id="pageSpecial"
label="Special"
value={form.pageSpecial}
onChange={(v) => update('pageSpecial', v)}
disabled={!canEdit}
rows={2}
max={2048}
/>
</TabsContent>
{/* ── Appearance ───────────────────────────────── */}
<TabsContent value="appearance" className="space-y-4">
<div className="space-y-2">
<Label>Icon</Label>
<div className="flex items-center gap-3">
<IconPicker
value={form.iconImage}
onChange={(id) => update('iconImage', id)}
disabled={!canEdit}
/>
<p className="text-xs text-muted-foreground">
Icon shown in the catalog tree navigation.
</p>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="iconColor">Icon Color</Label>
<div className="flex items-center gap-2">
<Input
id="iconColor"
type="number"
min={0}
className="w-32"
value={form.iconColor}
onChange={(e) => update('iconColor', parseInt(e.target.value, 10) || 0)}
disabled={!canEdit}
/>
<p className="text-xs text-muted-foreground">
Legacy tint value. Leave at default unless you need to match a specific
theme.
</p>
</div>
</div>
</TabsContent>
</Tabs>
</CardContent>
</Card>
{/* Child pages list */}
{childPages.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center gap-2">
<FolderTree className="h-4 w-4" />
Child Pages ({childPages.length})
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-1">
{childPages.map((child) => (
<Link
key={child.id}
href={`/admin/catalog/${child.id}`}
className="flex items-center justify-between rounded-md px-3 py-2 hover:bg-accent text-sm"
>
<span>
{child.caption}
<span className="ml-2 text-muted-foreground font-mono text-xs">
#{child.id}
</span>
</span>
<Badge variant={child.enabled === '1' ? 'default' : 'outline'}>
{child.enabled === '1' ? 'Enabled' : 'Disabled'}
</Badge>
</Link>
))}
</div>
</CardContent>
</Card>
)}
</div>
{/* ── Right column (1/3): status sticky ────────────────── */}
<div className="lg:col-span-1">
<Card className="lg:sticky lg:top-4">
<CardHeader className="pb-3">
<CardTitle className="text-base">Status & Preview</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Preview */}
<div className="flex items-center gap-3 rounded-md border bg-muted/30 p-3">
<div className="flex h-12 w-12 items-center justify-center rounded bg-background shrink-0">
<CatalogIcon iconImage={form.iconImage} size={36} />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium">{form.caption || 'Untitled'}</p>
<Badge
className={cn(
'mt-1 h-5 px-1.5 text-[10px] font-mono border-0',
layoutColorClass,
)}
>
{form.pageLayout}
</Badge>
</div>
</div>
{/* Toggles */}
<div className="space-y-3">
<ToggleRow
id="tg-enabled"
label="Enabled"
description="Active in the catalog"
checked={form.enabled === '1'}
onChange={(v) => update('enabled', v ? '1' : '0')}
disabled={!canEdit}
/>
<ToggleRow
id="tg-visible"
label="Visible"
description="Shown in navigation"
checked={form.visible === '1'}
onChange={(v) => update('visible', v ? '1' : '0')}
disabled={!canEdit}
/>
<ToggleRow
id="tg-club"
label="Club Only"
description="Requires HC subscription"
checked={form.clubOnly === '1'}
onChange={(v) => update('clubOnly', v ? '1' : '0')}
disabled={!canEdit}
/>
</div>
{/* Stats */}
<div className="flex items-center gap-4 border-t pt-3 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<FolderTree className="h-3.5 w-3.5" />
{childPages.length} sub
</span>
<span className="flex items-center gap-1">
<Package className="h-3.5 w-3.5" />#{catalogPage.id}
</span>
</div>
{/* Actions */}
{canEdit && (
<div className="space-y-2 border-t pt-3">
<Button type="submit" disabled={isPending} className="w-full">
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save & Sync
</Button>
<Button
type="button"
variant="destructive"
onClick={handleDelete}
disabled={isPending}
className="w-full"
>
<Trash2 className="mr-2 h-4 w-4" />
Delete Page
</Button>
<p className="text-center text-[10px] text-muted-foreground">
Press <kbd className="rounded border px-1">Ctrl+S</kbd> to save
</p>
</div>
)}
</CardContent>
</Card>
</div>
</div>
</form>
)
}
// ── Toggle row ─────────────────────────────────────────────────
function ToggleRow({
id,
label,
description,
checked,
onChange,
disabled,
}: {
id: string
label: string
description: string
checked: boolean
onChange: (v: boolean) => void
disabled?: boolean
}) {
return (
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<Label htmlFor={id} className="text-sm font-medium cursor-pointer">
{label}
</Label>
<p className="text-[11px] text-muted-foreground">{description}</p>
</div>
<Switch id={id} checked={checked} onCheckedChange={onChange} disabled={disabled} />
</div>
)
}
// ── Text field with counter ────────────────────────────────────
function _TextField({
id,
label,
value,
onChange,
disabled,
max,
}: {
id: string
label: string
value: string
onChange: (v: string) => void
disabled?: boolean
max?: number
}) {
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label htmlFor={id}>{label}</Label>
{max && (
<span className="text-[10px] tabular-nums text-muted-foreground">
{value.length}/{max}
</span>
)}
</div>
<Input
id={id}
value={value}
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
maxLength={max}
/>
</div>
)
}
function TextareaField({
id,
label,
value,
onChange,
disabled,
rows = 3,
max,
}: {
id: string
label: string
value: string
onChange: (v: string) => void
disabled?: boolean
rows?: number
max?: number
}) {
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label htmlFor={id}>{label}</Label>
{max && (
<span className="text-[10px] tabular-nums text-muted-foreground">
{value.length}/{max}
</span>
)}
</div>
<Textarea
id={id}
rows={rows}
value={value}
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
maxLength={max}
/>
</div>
)
}
// ── Layout select with color swatch ────────────────────────────
function LayoutSelect({
value,
onChange,
disabled,
}: {
value: string
onChange: (v: string) => void
disabled?: boolean
}) {
return (
<Select value={value} onValueChange={onChange} disabled={disabled}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{CATALOG_LAYOUTS.map((layout) => {
const colorClass = LAYOUT_COLORS[layout] || 'bg-muted text-muted-foreground'
return (
<SelectItem key={layout} value={layout}>
<span className="flex items-center gap-2">
<span className={cn('inline-block h-2 w-2 rounded-full', colorClass)} />
{layout}
</span>
</SelectItem>
)
})}
</SelectContent>
</Select>
)
}
// ── Parent page combobox with search ────────────────────────────
function ParentCombobox({
value,
onChange,
pages,
currentPageId,
disabled,
}: {
value: number
onChange: (id: number) => void
pages: { id: number; caption: string }[]
currentPageId: number
disabled?: boolean
}) {
const [open, setOpen] = useState(false)
const options = pages.filter((p) => p.id !== currentPageId)
const selected = value === -1 ? { id: -1, caption: 'Root' } : pages.find((p) => p.id === value)
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
role="combobox"
aria-expanded={open}
disabled={disabled}
className="w-full justify-between font-normal"
>
{selected ? (
<span className="truncate">
<span className="text-muted-foreground font-mono text-xs mr-1.5">
{selected.id === -1 ? '—' : `#${selected.id}`}
</span>
{selected.caption}
</span>
) : (
<span className="text-muted-foreground">Select parent...</span>
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
<Command>
<CommandInput placeholder="Search pages..." />
<CommandList>
<CommandEmpty>No page found.</CommandEmpty>
<CommandGroup>
<CommandItem
value="root"
onSelect={() => {
onChange(-1)
setOpen(false)
}}
>
<Check className={cn('mr-2 h-4 w-4', value === -1 ? 'opacity-100' : 'opacity-0')} />
<span className="text-muted-foreground font-mono text-xs mr-1.5">—</span>
Root
</CommandItem>
{options.map((page) => (
<CommandItem
key={page.id}
value={`${page.id} ${page.caption}`}
onSelect={() => {
onChange(page.id)
setOpen(false)
}}
>
<Check
className={cn('mr-2 h-4 w-4', value === page.id ? 'opacity-100' : 'opacity-0')}
/>
<span className="text-muted-foreground font-mono text-xs mr-1.5">#{page.id}</span>
<span className="truncate">{page.caption}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,507 @@
'use client'
import {
AlertTriangle,
CheckCircle2,
Database,
FileJson,
Filter,
Loader2,
RotateCcw,
Save,
ShoppingCart,
Sparkles,
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { useCallback, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { translateCatalogItems } from '@/actions/catalog-items'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { useServerAction } from '@/hooks/use-server-action'
import { FurniIcon } from './catalog-items-table'
interface BaseItemForTranslation {
id: number
publicName: string
itemName: string
spriteId: number
type: string
}
interface CatalogTranslateTabProps {
baseItems: BaseItemForTranslation[]
catalogNameMap: Record<number, string>
canEdit: boolean
furniDataIdList: number[]
furniDescriptionMap: Record<number, string>
furniRevisionMap?: Record<number, { classname: string; revision: number }>
}
type FilterMode = 'all' | 'missing' | 'modified'
export function CatalogTranslateTab({
baseItems,
catalogNameMap,
canEdit,
furniDataIdList,
furniDescriptionMap,
furniRevisionMap = {},
}: CatalogTranslateTabProps) {
const router = useRouter()
const { run, isPending } = useServerAction()
const [isSuggesting, setIsSuggesting] = useState(false)
const [filterMode, setFilterMode] = useState<FilterMode>('all')
const furniDataIdSet = useMemo(() => new Set(furniDataIdList), [furniDataIdList])
const [selected, setSelected] = useState<Set<number>>(new Set())
// ── Editable state: names + descriptions ─────────────────────────
const [editedNames, setEditedNames] = useState<Record<number, string>>(
Object.fromEntries(baseItems.map((item) => [item.id, item.publicName])),
)
const [editedDescs, setEditedDescs] = useState<Record<number, string>>(
Object.fromEntries(baseItems.map((item) => [item.id, furniDescriptionMap[item.id] ?? ''])),
)
// Track which items have name or description changes
const isNameChanged = useCallback(
(item: BaseItemForTranslation) => editedNames[item.id] !== item.publicName,
[editedNames],
)
const isDescChanged = useCallback(
(item: BaseItemForTranslation) => editedDescs[item.id] !== (furniDescriptionMap[item.id] ?? ''),
[editedDescs, furniDescriptionMap],
)
const changedItems = useMemo(
() => baseItems.filter((item) => isNameChanged(item) || isDescChanged(item)),
[baseItems, isNameChanged, isDescChanged],
)
const missingItems = useMemo(
() => baseItems.filter((item) => !furniDataIdSet.has(item.id)),
[baseItems, furniDataIdSet],
)
const filteredItems = useMemo(() => {
switch (filterMode) {
case 'missing':
return baseItems.filter((item) => !furniDataIdSet.has(item.id))
case 'modified':
return baseItems.filter((item) => isNameChanged(item) || isDescChanged(item))
default:
return baseItems
}
}, [baseItems, filterMode, furniDataIdSet, isNameChanged, isDescChanged])
const toggleOne = useCallback((id: number) => {
setSelected((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}, [])
const toggleAll = useCallback(() => {
setSelected((prev) =>
prev.size === filteredItems.length ? new Set() : new Set(filteredItems.map((i) => i.id)),
)
}, [filteredItems])
// Items to act on: selected ones if any, otherwise all
const targetItems = useMemo(() => {
if (selected.size === 0) return baseItems
return baseItems.filter((i) => selected.has(i.id))
}, [baseItems, selected])
function handleNameChange(id: number, value: string) {
setEditedNames((prev) => ({ ...prev, [id]: value }))
}
function handleDescChange(id: number, value: string) {
setEditedDescs((prev) => ({ ...prev, [id]: value }))
}
function handleReset() {
setEditedNames(Object.fromEntries(baseItems.map((item) => [item.id, item.publicName])))
setEditedDescs(
Object.fromEntries(baseItems.map((item) => [item.id, furniDescriptionMap[item.id] ?? ''])),
)
}
async function handleSuggestFromHabboFurni() {
if (targetItems.length === 0) return
setIsSuggesting(true)
try {
// Collect classnames from selected items (or all if none selected)
const classnames = targetItems.map((item) => item.itemName).filter(Boolean)
if (classnames.length === 0) {
toast.info('No classnames found to look up.')
setIsSuggesting(false)
return
}
// Batch in chunks of 50 to avoid too-long URLs
const CHUNK_SIZE = 50
const allSuggestions: Record<string, { name: string; description: string }> = {}
for (let i = 0; i < classnames.length; i += CHUNK_SIZE) {
const chunk = classnames.slice(i, i + CHUNK_SIZE)
const res = await fetch(
`/api/admin/catalog/suggest?classnames=${encodeURIComponent(chunk.join(','))}`,
)
if (res.ok) {
const data = await res.json()
Object.assign(allSuggestions, data.suggestions || {})
}
}
// Apply suggestions to items that have a match (names + descriptions)
let nameCount = 0
let descCount = 0
const newNames = { ...editedNames }
const newDescs = { ...editedDescs }
for (const item of targetItems) {
const suggestion = allSuggestions[item.itemName]
if (!suggestion) continue
if (suggestion.name && suggestion.name !== item.publicName) {
newNames[item.id] = suggestion.name
nameCount++
}
const currentDesc = furniDescriptionMap[item.id] ?? ''
if (suggestion.description && suggestion.description !== currentDesc) {
newDescs[item.id] = suggestion.description
descCount++
}
}
setEditedNames(newNames)
setEditedDescs(newDescs)
const total = nameCount + descCount
if (total > 0) {
const parts = []
if (nameCount > 0) parts.push(`${nameCount} name(s)`)
if (descCount > 0) parts.push(`${descCount} description(s)`)
toast.success(`HabboFurni: ${parts.join(' + ')} suggested from habbo.it. Review and save.`)
} else {
toast.info(
`HabboFurni: No new suggestions found (${Object.keys(allSuggestions).length} looked up, all already match).`,
)
}
} catch (err) {
toast.error(`HabboFurni error: ${(err as Error).message}`)
} finally {
setIsSuggesting(false)
}
}
async function handleSaveAll() {
if (changedItems.length === 0) return
run(
() =>
translateCatalogItems({
items: changedItems.map((item) => ({
id: item.id,
publicName: editedNames[item.id],
description: editedDescs[item.id],
})),
}),
{
successMessage: 'Translations saved.',
errorMessage: 'Failed to save translations.',
onSuccess: (data) => {
const d = data as Record<string, number | boolean>
const parts = []
if (d.namesUpdated && (d.namesUpdated as number) > 0)
parts.push(`${d.namesUpdated} name(s) updated`)
if (d.descriptionsUpdated && (d.descriptionsUpdated as number) > 0)
parts.push(`${d.descriptionsUpdated} description(s) updated`)
if (parts.length === 0) parts.push(`${d.updated ?? 0} item(s) processed`)
if (d.furniDataUpdated) parts.push('FurnitureData.json synced')
if (d.furniDataInserted && (d.furniDataInserted as number) > 0) {
parts.push(`${d.furniDataInserted} new item(s) added to FurnitureData.json`)
}
parts.push('emulator cache refreshed')
toast.success(`${parts.join(' · ')}.`)
router.refresh()
},
},
)
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div className="min-w-0">
<CardTitle>Translate Item Names</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
Edit the public name and description of furniture items. Saving will update:
</p>
<div className="flex gap-3 mt-2 flex-wrap">
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
<Database className="h-3 w-3" /> items_base (name)
</span>
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
<ShoppingCart className="h-3 w-3" /> catalog_name (auto)
</span>
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
<FileJson className="h-3 w-3" /> FurnitureData.json (name + desc)
</span>
</div>
{missingItems.length > 0 && (
<div className="flex items-center gap-1.5 mt-2 text-xs text-orange-600 dark:text-orange-400">
<AlertTriangle className="h-3.5 w-3.5" />
<span>
{missingItems.length} item(s) missing from FurnitureData.json — will be
auto-inserted on save
</span>
</div>
)}
</div>
{canEdit && (
<div className="flex gap-2 flex-shrink-0 flex-wrap justify-end">
<Button
variant="outline"
size="sm"
onClick={handleSuggestFromHabboFurni}
disabled={isSuggesting || isPending || targetItems.length === 0}
title="Suggest Italian names + descriptions from HabboFurni API (habbo.it)"
>
{isSuggesting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Sparkles className="mr-2 h-4 w-4" />
)}
Suggest IT{selected.size > 0 ? ` (${selected.size})` : ''}
</Button>
<Button
variant="outline"
size="sm"
onClick={handleReset}
disabled={changedItems.length === 0 || isPending}
>
<RotateCcw className="mr-2 h-4 w-4" />
Reset
</Button>
<Button
size="sm"
onClick={handleSaveAll}
disabled={isPending || changedItems.length === 0}
>
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save All ({changedItems.length})
</Button>
</div>
)}
</CardHeader>
<CardContent>
{/* Filter bar */}
{baseItems.length > 0 && (
<div className="flex items-center gap-2 mb-4">
<Filter className="h-4 w-4 text-muted-foreground" />
<div className="flex gap-1">
<Button
variant={filterMode === 'all' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode('all')}
>
All ({baseItems.length})
</Button>
<Button
variant={filterMode === 'missing' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode('missing')}
disabled={missingItems.length === 0}
>
<AlertTriangle className="mr-1 h-3 w-3" />
Missing ({missingItems.length})
</Button>
<Button
variant={filterMode === 'modified' ? 'default' : 'outline'}
size="sm"
className="h-7 text-xs"
onClick={() => setFilterMode('modified')}
disabled={changedItems.length === 0}
>
Modified ({changedItems.length})
</Button>
</div>
</div>
)}
{baseItems.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">
No items to translate in this page.
</p>
) : filteredItems.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">
No items match the current filter.
</p>
) : (
<TooltipProvider>
<div className="rounded-md border overflow-auto max-h-[600px]">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[40px] px-2">
<Checkbox
checked={filteredItems.length > 0 && selected.size === filteredItems.length}
onCheckedChange={toggleAll}
aria-label="Select all"
/>
</TableHead>
<TableHead className="w-[50px]"></TableHead>
<TableHead className="w-[60px]">ID</TableHead>
<TableHead className="w-[80px]">Type</TableHead>
<TableHead>Item Name</TableHead>
<TableHead className="min-w-[200px]">Public Name</TableHead>
<TableHead className="min-w-[200px]">Description</TableHead>
<TableHead className="w-[100px]">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredItems.map((item) => {
const nameChanged = isNameChanged(item)
const descChanged = isDescChanged(item)
const isChanged = nameChanged || descChanged
const isMissing = !furniDataIdSet.has(item.id)
const currentCatalogName = catalogNameMap[item.id]
return (
<TableRow
key={item.id}
className={
isChanged
? 'bg-yellow-50 dark:bg-yellow-950/20'
: isMissing
? 'bg-orange-50/50 dark:bg-orange-950/10'
: undefined
}
>
<TableCell className="px-2">
<Checkbox
checked={selected.has(item.id)}
onCheckedChange={() => toggleOne(item.id)}
aria-label={`Select ${item.itemName}`}
/>
</TableCell>
<TableCell className="px-1">
{(() => {
const revInfo = furniRevisionMap[item.id]
return revInfo ? (
<FurniIcon
classname={revInfo.classname}
revision={revInfo.revision}
/>
) : (
<FurniIcon classname={item.itemName} revision={0} />
)
})()}
</TableCell>
<TableCell className="font-mono text-xs">{item.id}</TableCell>
<TableCell>
<Badge
variant={item.type === 's' ? 'default' : 'secondary'}
className="text-xs"
>
{item.type === 's' ? 'Floor' : item.type === 'i' ? 'Wall' : item.type}
</Badge>
</TableCell>
<TableCell className="text-xs text-muted-foreground font-mono">
{item.itemName}
</TableCell>
<TableCell>
<Input
value={editedNames[item.id] || ''}
onChange={(e) => handleNameChange(item.id, e.target.value)}
disabled={!canEdit}
className={`h-8 text-sm ${nameChanged ? 'border-yellow-400 dark:border-yellow-600' : ''}`}
/>
{currentCatalogName && currentCatalogName !== item.publicName && (
<p className="text-[11px] text-muted-foreground mt-0.5 truncate">
catalog: {currentCatalogName}
</p>
)}
</TableCell>
<TableCell>
<Input
value={editedDescs[item.id] || ''}
onChange={(e) => handleDescChange(item.id, e.target.value)}
disabled={!canEdit}
placeholder="No description"
className={`h-8 text-sm ${descChanged ? 'border-yellow-400 dark:border-yellow-600' : ''}`}
/>
</TableCell>
<TableCell>
<div className="flex items-center gap-1.5">
{isChanged ? (
<Badge
variant="secondary"
className="text-xs bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
>
Modified
</Badge>
) : (
<span className="text-xs text-muted-foreground">—</span>
)}
{isMissing ? (
<Tooltip>
<TooltipTrigger asChild>
<AlertTriangle className="h-3.5 w-3.5 text-orange-500 flex-shrink-0" />
</TooltipTrigger>
<TooltipContent>
<p>Missing from FurnitureData.json</p>
<p className="text-xs text-muted-foreground">
Will be auto-inserted on save
</p>
</TooltipContent>
</Tooltip>
) : (
<Tooltip>
<TooltipTrigger asChild>
<CheckCircle2 className="h-3.5 w-3.5 text-green-500 flex-shrink-0" />
</TooltipTrigger>
<TooltipContent>In FurnitureData.json</TooltipContent>
</Tooltip>
)}
</div>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
</TooltipProvider>
)}
</CardContent>
</Card>
)
}
+41
View File
@@ -0,0 +1,41 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function CatalogDetailLoading() {
return (
<div className="space-y-6">
{/* Breadcrumb */}
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-16" />
<Skeleton className="h-4 w-4" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-4" />
<Skeleton className="h-4 w-20" />
</div>
{/* Title */}
<div>
<Skeleton className="h-9 w-64" />
<Skeleton className="h-5 w-40 mt-2" />
</div>
{/* Tabs */}
<div className="space-y-4">
<div className="flex gap-2 border-b pb-2">
{Array.from({ length: 4 }).map((_, i) => (
<Skeleton key={i} className="h-9 w-24 rounded-md" />
))}
</div>
{/* Tab content */}
<div className="rounded-lg border bg-card p-6 space-y-4">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-10 w-full" />
</div>
))}
</div>
</div>
</div>
)
}
+114 -153
View File
@@ -1,164 +1,125 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { ChevronRight } from 'lucide-react'
import Link from 'next/link'
import { notFound, redirect } from 'next/navigation'
import { Fragment } from 'react'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { loadCatalogItemsData } from '@/lib/services/catalog-items-loader'
import { getAncestors } from '@/lib/services/catalog-tree'
import { CatalogDetailTabs } from './catalog-detail-tabs'
export const dynamic = "force-dynamic";
type CatalogPageRow = {
id: number;
caption: string;
parentId: number;
pageLayout: string;
minRank: number;
visible: string;
enabled: string;
clubOnly: string;
vipOnly: string;
};
type CatalogItemRow = {
id: number;
catalogName: string;
itemIds: string;
amount: number;
costCredits: number;
costPoints: number;
pointsType: number;
limitedStack: number;
limitedSells: number;
orderNumber: number;
clubOnly: string;
};
export default async function AdminCatalogPage({
export default async function CatalogEditPage({
params,
}: {
params: Promise<{ id: string }>;
params: Promise<{ locale: string; id: string }>
}) {
const t = await getTranslations("pages.admin.catalog");
const { id } = await params;
const pageId = Number(id);
if (!Number.isInteger(pageId)) notFound();
let page: CatalogPageRow | null = null;
try {
page = await prisma.catalogPages.findUnique({
where: { id: pageId },
select: {
id: true,
caption: true,
parentId: true,
pageLayout: true,
minRank: true,
visible: true,
enabled: true,
clubOnly: true,
vipOnly: true,
},
});
} catch {
page = null;
}
if (!page) notFound();
let items: CatalogItemRow[] = [];
try {
items = await prisma.catalogItems.findMany({
where: { pageId },
select: {
id: true,
catalogName: true,
itemIds: true,
amount: true,
costCredits: true,
costPoints: true,
pointsType: true,
limitedStack: true,
limitedSells: true,
orderNumber: true,
clubOnly: true,
},
orderBy: [{ orderNumber: "asc" }, { id: "asc" }],
take: 500,
});
} catch {
items = [];
const { id } = await params
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect('/admin')
}
const hidden = page.visible !== "1" || page.enabled !== "1";
const pageId = parseInt(id, 10)
if (Number.isNaN(pageId)) notFound()
const catalogPage = await prisma.catalogPage.findUnique({
where: { id: pageId },
})
if (!catalogPage) notFound()
const [children, itemsData, ancestors] = await Promise.all([
prisma.catalogPage.findMany({
where: { parentId: pageId },
orderBy: { orderNum: 'asc' },
select: { id: true, caption: true, enabled: true },
}),
loadCatalogItemsData(pageId),
getAncestors(catalogPage.parentId),
])
const {
items: catalogItems,
baseItems,
catalogNameMap,
furniDataIdList,
furniDescriptionMap,
furniRevisionMap,
interactionTypes,
allPages,
} = itemsData
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
return (
<main>
<p className="muted">
<Link href="/admin/catalog">← {t("title")}</Link>
</p>
<h1>{page.caption}</h1>
<p className="muted">
{t("pageLabel", { id: page.id })} · {t("layoutLabel", { layout: page.pageLayout })} · {t("minRankLabel", { rank: page.minRank })} ·{" "}
{hidden ? t("statusHidden") : t("statusVisible")}
{page.parentId > 0 ? ` · ${t("parentLabel", { id: page.parentId })}` : ""}
{page.clubOnly === "1" ? ` · ${t("hcOnly")}` : ""}
{page.vipOnly === "1" ? ` · ${t("vipOnly")}` : ""}
</p>
<div className="space-y-6">
{/* Breadcrumb */}
<nav className="flex items-center gap-1 text-sm text-muted-foreground">
<Link href={'/admin/catalog'} className="hover:text-foreground transition-colors">
Catalog
</Link>
{ancestors.map((bc) => (
<Fragment key={bc.id}>
<ChevronRight className="h-3 w-3 flex-shrink-0" />
<Link
href={`/admin/catalog/${bc.id}`}
className="hover:text-foreground transition-colors"
>
{bc.caption}
</Link>
</Fragment>
))}
<ChevronRight className="h-3 w-3 flex-shrink-0" />
<span className="text-foreground font-medium">{catalogPage.caption}</span>
</nav>
<h2 style={{ marginTop: "1.5rem" }}>{t("items")}</h2>
{items.length === 0 ? (
<p className="muted">{t("noItems")}</p>
) : (
<table style={{ width: "100%", borderCollapse: "collapse" }}>
<thead>
<tr style={{ textAlign: "left", color: "var(--muted)" }}>
<th>{t("colId")}</th>
<th>{t("catalogName")}</th>
<th>{t("itemIds")}</th>
<th>{t("amount")}</th>
<th>{t("colCostCredits")}</th>
<th>{t("colCostPoints")}</th>
<th>{t("colLimited")}</th>
<th>{t("colOrder")}</th>
</tr>
</thead>
<tbody>
{items.map((it) => (
<tr key={it.id} style={{ borderTop: "1px solid var(--border-subtle)" }}>
<td>{it.id}</td>
<td>
{it.catalogName}
{it.clubOnly === "1" ? (
<span className="muted"> · {t("hc")}</span>
) : null}
</td>
<td className="muted">{it.itemIds}</td>
<td>{it.amount}</td>
<td>
{it.costCredits > 0 ? (
<span className="currency">{it.costCredits}</span>
) : (
<span className="muted">—</span>
)}
</td>
<td className="muted">
{it.costPoints > 0
? `${it.costPoints} (${t("typeLabel", { type: it.pointsType })})`
: "—"}
</td>
<td className="muted">
{it.limitedStack > 0
? `${it.limitedSells}/${it.limitedStack}`
: "—"}
</td>
<td>{it.orderNumber}</td>
</tr>
))}
</tbody>
</table>
)}
{/* Title */}
<div>
<h1 className="text-3xl font-bold tracking-tight">
{catalogPage.caption}
<span className="ml-2 text-base font-normal text-muted-foreground">
#{catalogPage.id}
</span>
</h1>
<p className="text-muted-foreground">
Layout: {catalogPage.pageLayout} &middot; {catalogItems.length} items
</p>
</div>
<p className="muted" style={{ marginTop: "1rem" }}>
{t("itemCount", { count: items.length })}
</p>
</main>
);
{/* Tabs */}
<CatalogDetailTabs
catalogPage={{
id: catalogPage.id,
caption: catalogPage.caption,
parentId: catalogPage.parentId,
pageLayout: catalogPage.pageLayout,
enabled: catalogPage.enabled,
visible: catalogPage.visible,
minRank: catalogPage.minRank,
clubOnly: catalogPage.clubOnly,
orderNum: catalogPage.orderNum,
iconImage: catalogPage.iconImage,
iconColor: catalogPage.iconColor,
pageHeadline: catalogPage.pageHeadline,
pageTeaser: catalogPage.pageTeaser,
pageSpecial: catalogPage.pageSpecial,
pageText1: catalogPage.pageText1,
pageText2: catalogPage.pageText2,
pageTextDetails: catalogPage.pageTextDetails,
pageTextTeaser: catalogPage.pageTextTeaser,
}}
items={catalogItems}
baseItems={baseItems}
catalogNameMap={catalogNameMap}
childPages={children}
pageId={catalogPage.id}
canEdit={canEdit}
furniDataIdList={furniDataIdList}
furniDescriptionMap={furniDescriptionMap}
furniRevisionMap={furniRevisionMap}
allPages={allPages}
interactionTypes={interactionTypes}
/>
</div>
)
}
@@ -0,0 +1,61 @@
import { notFound, redirect } from 'next/navigation'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { BcPageDetail } from '../bc-manager'
export default async function BcPageDetailPage({
params: paramsPromise,
}: {
params: Promise<{ locale: string; id: string }>
}) {
const { id: idStr } = await paramsPromise
const id = parseInt(idStr, 10)
if (Number.isNaN(id)) notFound()
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect('/admin')
}
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
const bcPage = await prisma.catalog_pages_bc.findUnique({ where: { id } })
if (!bcPage) notFound()
const bcItems = await prisma.catalog_items_bc.findMany({
where: { page_id: id },
orderBy: { order_number: 'asc' },
})
return (
<BcPageDetail
page={{
id: bcPage.id,
parentId: bcPage.parent_id,
caption: bcPage.caption,
pageLayout: bcPage.page_layout,
iconColor: bcPage.icon_color,
iconImage: bcPage.icon_image,
orderNum: bcPage.order_num,
visible: bcPage.visible,
enabled: bcPage.enabled,
pageHeadline: bcPage.page_headline,
pageTeaser: bcPage.page_teaser,
pageSpecial: bcPage.page_special ?? '',
pageText1: bcPage.page_text1 ?? '',
pageText2: bcPage.page_text2 ?? '',
pageTextDetails: bcPage.page_text_details ?? '',
pageTextTeaser: bcPage.page_text_teaser ?? '',
}}
items={bcItems.map((i) => ({
id: i.id,
pageId: i.page_id,
itemIds: i.item_ids,
catalogName: i.catalog_name,
orderNumber: i.order_number,
extradata: i.extradata,
}))}
canEdit={canEdit}
/>
)
}
@@ -0,0 +1,548 @@
'use client'
import { ArrowLeft, HardHat, Loader2, Package, Pencil, Plus, Save, Trash2 } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useRef, useState } from 'react'
import { createBcItem, deleteBcItem, updateBcItem, updateBcPage } from '@/actions/catalog-bc'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Textarea } from '@/components/ui/textarea'
import { useServerAction } from '@/hooks/use-server-action'
// ── Types ────────────────────────────────────────────────────────────
export interface BcPageData {
id: number
parentId: number
caption: string
pageLayout: string
iconColor: number
iconImage: number
orderNum: number
visible: string
enabled: string
pageHeadline: string
pageTeaser: string
pageSpecial: string
pageText1: string
pageText2: string
pageTextDetails: string
pageTextTeaser: string
}
export interface BcItemData {
id: number
pageId: number
itemIds: string
catalogName: string
orderNumber: number
extradata: string
}
interface BcPageDetailProps {
page: BcPageData
items: BcItemData[]
canEdit: boolean
}
// ── Main Component ───────────────────────────────────────────────────
export function BcPageDetail({ page, items, canEdit }: BcPageDetailProps) {
const { isPending, run } = useServerAction()
const formRef = useRef<HTMLFormElement>(null)
const [editingItem, setEditingItem] = useState<BcItemData | null>(null)
const [addingItem, setAddingItem] = useState(false)
const [form, setForm] = useState({
caption: page.caption,
orderNum: page.orderNum,
enabled: page.enabled as '0' | '1',
visible: page.visible as '0' | '1',
pageHeadline: page.pageHeadline,
pageTeaser: page.pageTeaser,
pageSpecial: page.pageSpecial,
pageText1: page.pageText1,
pageText2: page.pageText2,
pageTextDetails: page.pageTextDetails,
pageTextTeaser: page.pageTextTeaser,
})
// Ctrl+S / Cmd+S to save
useEffect(() => {
if (!canEdit) return
function onKeyDown(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
formRef.current?.requestSubmit()
}
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [canEdit])
function update<K extends keyof typeof form>(key: K, value: (typeof form)[K]) {
setForm((prev) => ({ ...prev, [key]: value }))
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
run(() => updateBcPage({ id: page.id, ...form }), {
successMessage: 'BC page updated and catalog synced.',
errorMessage: 'Failed to update.',
})
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center gap-3">
<Link
href="/admin/catalog?catalog=bc"
className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4" />
BC Catalog
</Link>
<span className="text-muted-foreground">/</span>
<div className="flex items-center gap-2">
<HardHat className="h-5 w-5 text-amber-500" />
<h1 className="text-2xl font-bold tracking-tight">{page.caption}</h1>
<Badge variant="outline" className="font-mono text-xs">
#{page.id}
</Badge>
<Badge variant="secondary" className="font-mono text-xs">
{page.pageLayout}
</Badge>
</div>
</div>
<form ref={formRef} onSubmit={handleSubmit}>
<div className="grid gap-4 lg:grid-cols-3">
{/* ── Left column: form fields ─────────────── */}
<div className="lg:col-span-2 space-y-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Page Settings</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="caption">Caption</Label>
<Input
id="caption"
value={form.caption}
onChange={(e) => update('caption', e.target.value)}
disabled={!canEdit}
/>
</div>
<div className="space-y-2">
<Label htmlFor="orderNum">Order</Label>
<Input
id="orderNum"
type="number"
value={form.orderNum}
onChange={(e) => update('orderNum', parseInt(e.target.value, 10) || 0)}
disabled={!canEdit}
/>
</div>
</div>
<div className="space-y-2">
<Label>Headline</Label>
<Input
value={form.pageHeadline}
onChange={(e) => update('pageHeadline', e.target.value)}
disabled={!canEdit}
placeholder="Headline image path"
/>
</div>
<div className="space-y-2">
<Label>Teaser</Label>
<Input
value={form.pageTeaser}
onChange={(e) => update('pageTeaser', e.target.value)}
disabled={!canEdit}
placeholder="Teaser image path"
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label>Text 1</Label>
<Textarea
value={form.pageText1}
onChange={(e) => update('pageText1', e.target.value)}
disabled={!canEdit}
rows={3}
/>
</div>
<div className="space-y-2">
<Label>Text 2</Label>
<Textarea
value={form.pageText2}
onChange={(e) => update('pageText2', e.target.value)}
disabled={!canEdit}
rows={3}
/>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label>Details</Label>
<Textarea
value={form.pageTextDetails}
onChange={(e) => update('pageTextDetails', e.target.value)}
disabled={!canEdit}
rows={3}
/>
</div>
<div className="space-y-2">
<Label>Text Teaser</Label>
<Textarea
value={form.pageTextTeaser}
onChange={(e) => update('pageTextTeaser', e.target.value)}
disabled={!canEdit}
rows={3}
/>
</div>
</div>
<div className="space-y-2">
<Label>Special</Label>
<Textarea
value={form.pageSpecial}
onChange={(e) => update('pageSpecial', e.target.value)}
disabled={!canEdit}
rows={2}
/>
</div>
</CardContent>
</Card>
{/* Items */}
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base flex items-center gap-2">
<Package className="h-4 w-4" />
Items ({items.length})
</CardTitle>
{canEdit && (
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={() => setAddingItem(true)}
>
<Plus className="h-3 w-3 mr-1" />
Add Item
</Button>
)}
</div>
</CardHeader>
<CardContent>
{items.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">
No items in this page.
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="text-xs">ID</TableHead>
<TableHead className="text-xs">Name</TableHead>
<TableHead className="text-xs">Item IDs</TableHead>
<TableHead className="text-xs">Order</TableHead>
<TableHead className="text-xs">Extra Data</TableHead>
{canEdit && <TableHead className="text-xs w-20">Actions</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{items.map((item) => (
<TableRow key={item.id}>
<TableCell className="text-xs font-mono">{item.id}</TableCell>
<TableCell className="text-xs font-medium">{item.catalogName}</TableCell>
<TableCell className="text-xs font-mono text-muted-foreground">
{item.itemIds}
</TableCell>
<TableCell className="text-xs">{item.orderNumber}</TableCell>
<TableCell className="text-xs text-muted-foreground max-w-32 truncate">
{item.extradata || '\u2014'}
</TableCell>
{canEdit && (
<TableCell>
<div className="flex gap-1">
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 w-6 p-0"
onClick={() => setEditingItem(item)}
>
<Pencil className="h-3 w-3" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-red-500 hover:text-red-600"
onClick={() => {
if (!confirm(`Delete item "${item.catalogName}"?`)) return
run(() => deleteBcItem({ id: item.id }), {
successMessage: 'Item deleted.',
})
}}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
{/* ── Right column: status ─────────────────── */}
<div className="lg:col-span-1">
<Card className="lg:sticky lg:top-4">
<CardHeader className="pb-3">
<CardTitle className="text-base">Status</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-3">
<ToggleRow
id="tg-enabled"
label="Enabled"
description="Active in the BC catalog"
checked={form.enabled === '1'}
onChange={(v) => update('enabled', v ? '1' : '0')}
disabled={!canEdit}
/>
<ToggleRow
id="tg-visible"
label="Visible"
description="Shown in BC navigation"
checked={form.visible === '1'}
onChange={(v) => update('visible', v ? '1' : '0')}
disabled={!canEdit}
/>
</div>
{/* Stats */}
<div className="flex items-center gap-4 border-t pt-3 text-xs text-muted-foreground">
<span>
Layout: <span className="font-mono">{page.pageLayout}</span>
</span>
<span>
Parent:{' '}
<span className="font-mono">
{page.parentId <= 0 ? 'Root' : `#${page.parentId}`}
</span>
</span>
</div>
{/* Actions */}
{canEdit && (
<div className="space-y-2 border-t pt-3">
<Button type="submit" disabled={isPending} className="w-full">
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save & Sync
</Button>
<p className="text-center text-[10px] text-muted-foreground">
Press <kbd className="rounded border px-1">Ctrl+S</kbd> to save
</p>
</div>
)}
</CardContent>
</Card>
</div>
</div>
</form>
{/* Edit Item Dialog */}
{editingItem && (
<ItemDialog
item={editingItem}
mode="edit"
isPending={isPending}
onClose={() => setEditingItem(null)}
onSubmit={(data) => {
run(() => updateBcItem({ id: editingItem.id, ...data }), {
successMessage: 'Item updated.',
onSuccess: () => setEditingItem(null),
})
}}
/>
)}
{/* Add Item Dialog */}
{addingItem && (
<ItemDialog
item={{
id: 0,
pageId: page.id,
itemIds: '',
catalogName: '',
orderNumber: 1,
extradata: '',
}}
mode="add"
isPending={isPending}
onClose={() => setAddingItem(false)}
onSubmit={(data) => {
run(() => createBcItem({ pageId: page.id, ...data }), {
successMessage: 'Item created.',
onSuccess: () => setAddingItem(false),
})
}}
/>
)}
</div>
)
}
// ── Toggle row ───────────────────────────────────────────────────────
function ToggleRow({
id,
label,
description,
checked,
onChange,
disabled,
}: {
id: string
label: string
description: string
checked: boolean
onChange: (v: boolean) => void
disabled?: boolean
}) {
return (
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<Label htmlFor={id} className="text-sm font-medium cursor-pointer">
{label}
</Label>
<p className="text-[11px] text-muted-foreground">{description}</p>
</div>
<Switch id={id} checked={checked} onCheckedChange={onChange} disabled={disabled} />
</div>
)
}
// ── Item Dialog ──────────────────────────────────────────────────────
function ItemDialog({
item,
mode,
isPending,
onClose,
onSubmit,
}: {
item: BcItemData
mode: 'add' | 'edit'
isPending: boolean
onClose: () => void
onSubmit: (data: {
itemIds: string
catalogName: string
orderNumber: number
extradata: string
}) => void
}) {
const [form, setForm] = useState({
itemIds: item.itemIds,
catalogName: item.catalogName,
orderNumber: item.orderNumber,
extradata: item.extradata,
})
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{mode === 'add' ? 'Add BC Item' : `Edit Item #${item.id}`}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label>Catalog Name</Label>
<Input
value={form.catalogName}
onChange={(e) => setForm((f) => ({ ...f, catalogName: e.target.value }))}
/>
</div>
<div className="space-y-2">
<Label>Item IDs (semicolon-separated)</Label>
<Input
value={form.itemIds}
onChange={(e) => setForm((f) => ({ ...f, itemIds: e.target.value }))}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Order</Label>
<Input
type="number"
value={form.orderNumber}
onChange={(e) =>
setForm((f) => ({ ...f, orderNumber: parseInt(e.target.value, 10) || 0 }))
}
/>
</div>
<div className="space-y-2">
<Label>Extra Data</Label>
<Input
value={form.extradata}
onChange={(e) => setForm((f) => ({ ...f, extradata: e.target.value }))}
placeholder="Optional"
/>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={isPending}>
Cancel
</Button>
<Button
onClick={() => onSubmit(form)}
disabled={isPending || !form.catalogName || !form.itemIds}
>
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{mode === 'add' ? 'Add Item' : 'Save'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,5 @@
import { redirect } from 'next/navigation'
export default function BuilderClubPage() {
redirect('/admin/catalog?catalog=bc')
}
+128
View File
@@ -0,0 +1,128 @@
'use client'
import { Loader2, Plus } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { createCatalogPage } from '@/actions/catalog'
import { createBcPage } from '@/actions/catalog-bc'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useServerAction } from '@/hooks/use-server-action'
import { CATALOG_LAYOUTS } from '@/lib/catalog-layouts'
interface CatalogActionsProps {
catalogType?: 'normal' | 'bc'
}
export function CatalogActions({ catalogType = 'normal' }: CatalogActionsProps) {
const { run, isPending } = useServerAction()
const [open, setOpen] = useState(false)
const [caption, setCaption] = useState('')
const [parentId, setParentId] = useState('-1')
const [pageLayout, setPageLayout] = useState('default_3x3')
const isBc = catalogType === 'bc'
function handleCreate() {
if (!caption.trim()) {
toast.error('Caption is required')
return
}
const input = {
caption: caption.trim(),
parentId: parseInt(parentId, 10),
pageLayout,
}
const fn = isBc ? () => createBcPage(input) : () => createCatalogPage(input)
run(fn, {
successMessage: `Catalog page "${caption.trim()}" created.`,
onSuccess: (data) => {
setOpen(false)
setCaption('')
setParentId('-1')
if (data.id) {
window.location.href = isBc
? `/admin/catalog/builder-club/${data.id}`
: `/admin/catalog/${data.id}`
}
},
})
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="mr-2 h-4 w-4" />
New Page
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{isBc ? 'Create Builder Club Page' : 'Create Catalog Page'}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="caption">Caption</Label>
<Input
id="caption"
value={caption}
onChange={(e) => setCaption(e.target.value)}
placeholder="Page name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="parentId">Parent ID (-1 = root)</Label>
<Input
id="parentId"
type="number"
value={parentId}
onChange={(e) => setParentId(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>Layout</Label>
<Select value={pageLayout} onValueChange={setPageLayout}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{CATALOG_LAYOUTS.map((layout) => (
<SelectItem key={layout} value={layout}>
{layout}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button onClick={handleCreate} disabled={isPending} className="w-full">
{isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
Create Page
</Button>
</div>
</DialogContent>
</Dialog>
)
}
+178
View File
@@ -0,0 +1,178 @@
'use client'
import { Pencil } from 'lucide-react'
import Link from 'next/link'
import { toggleCatalogPage } from '@/actions/catalog'
import { toggleBcPage } from '@/actions/catalog-bc'
import { DataTable } from '@/components/admin/data-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { useServerAction } from '@/hooks/use-server-action'
import type { DataTableColumn, PaginatedResult } from '@/types'
interface CatalogPageRow {
id: number
caption: string
parentId: number
parentCaption: string
pageLayout: string
enabled: string
visible: string
minRank: number
orderNum: number
itemCount: number
childCount: number
}
interface CatalogTableProps {
data: PaginatedResult<CatalogPageRow>
canEdit: boolean
catalogType?: 'normal' | 'bc'
}
export function CatalogTable({ data, canEdit, catalogType = 'normal' }: CatalogTableProps) {
const { run, isPending } = useServerAction()
const isBc = catalogType === 'bc'
// Parent URLs stay in the same catalog; root takes you to the catalog index.
const detailHref = (id: number) =>
isBc ? `/admin/catalog/builder-club/${id}` : `/admin/catalog/${id}`
function handleToggle(id: number, action: 'toggleEnabled' | 'toggleVisible') {
if (isBc) {
const field = action === 'toggleEnabled' ? 'enabled' : 'visible'
run(() => toggleBcPage({ id, field }), { successMessage: 'Updated.' })
} else {
run(() => toggleCatalogPage({ id, action }), { successMessage: 'Updated.' })
}
}
const columns: DataTableColumn<CatalogPageRow>[] = [
{ key: 'id', label: 'ID', sortable: true },
{
key: 'caption',
label: 'Caption',
sortable: true,
render: (value, row) => (
<Link href={detailHref(row.id)} className="font-medium text-primary hover:underline">
{String(value)}
</Link>
),
},
{
key: 'parentId',
label: 'Parent',
sortable: true,
render: (_, row) =>
row.parentId === -1 ? (
<span className="text-xs text-muted-foreground">Root</span>
) : (
<Link href={detailHref(row.parentId)} className="text-xs hover:underline">
{row.parentCaption}
</Link>
),
},
{
key: 'pageLayout',
label: 'Layout',
render: (value) => <Badge variant="secondary">{String(value)}</Badge>,
},
{
key: 'enabled',
label: 'Enabled',
sortable: true,
filterKey: 'filter_enabled',
filterOptions: [
{ label: 'Enabled', value: '1' },
{ label: 'Disabled', value: '0' },
],
render: (value, row) =>
canEdit ? (
<button
type="button"
onClick={() => handleToggle(row.id, 'toggleEnabled')}
disabled={isPending}
className="cursor-pointer disabled:opacity-50"
>
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
</button>
) : (
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
),
},
{
key: 'visible',
label: 'Visible',
sortable: true,
filterKey: 'filter_visible',
filterOptions: [
{ label: 'Visible', value: '1' },
{ label: 'Hidden', value: '0' },
],
render: (value, row) =>
canEdit ? (
<button
type="button"
onClick={() => handleToggle(row.id, 'toggleVisible')}
disabled={isPending}
className="cursor-pointer disabled:opacity-50"
>
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
</button>
) : (
<Badge variant={value === '1' ? 'default' : 'outline'}>
{value === '1' ? 'Yes' : 'No'}
</Badge>
),
},
...(isBc
? []
: [
{
key: 'minRank' as const,
label: 'Min Rank',
sortable: true,
} satisfies DataTableColumn<CatalogPageRow>,
]),
{
key: 'itemCount',
label: 'Items',
render: (value) => <span>{String(value)}</span>,
},
{
key: 'childCount',
label: 'Children',
render: (value) => <span>{String(value)}</span>,
},
{
key: 'actions',
label: 'Actions',
render: (_, row) => (
<Button variant="ghost" size="icon" asChild>
<Link href={detailHref(row.id)}>
<Pencil className="h-4 w-4" />
</Link>
</Button>
),
},
]
return (
<DataTable
data={data}
columns={columns}
searchPlaceholder="Search by caption, layout or item..."
bulkActions={
canEdit
? [{ label: 'Delete Selected', value: 'delete', variant: 'destructive' }]
: undefined
}
/>
)
}
@@ -0,0 +1,85 @@
'use client'
import { FolderTree, HardHat, List, Package } from 'lucide-react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
interface CatalogViewToggleProps {
currentView: string
catalogType?: string
}
export function CatalogViewToggle({ currentView, catalogType = 'normal' }: CatalogViewToggleProps) {
const router = useRouter()
const searchParams = useSearchParams()
function setView(view: string) {
const params = new URLSearchParams(searchParams.toString())
if (view === 'tree') {
params.delete('view')
} else {
params.set('view', view)
}
router.push(`?${params.toString()}`)
}
function setCatalog(type: string) {
const params = new URLSearchParams(searchParams.toString())
if (type === 'normal') {
params.delete('catalog')
} else {
params.set('catalog', type)
}
params.delete('view') // reset to tree when switching
router.push(`?${params.toString()}`)
}
return (
<div className="flex items-center gap-2">
{/* Catalog type selector */}
<div className="flex items-center rounded-md border bg-card">
<Button
variant="ghost"
size="sm"
className={cn('h-8 rounded-r-none', catalogType === 'normal' && 'bg-accent')}
onClick={() => setCatalog('normal')}
>
<Package className="mr-1.5 h-4 w-4" />
Catalog
</Button>
<Button
variant="ghost"
size="sm"
className={cn('h-8 rounded-l-none', catalogType === 'bc' && 'bg-accent')}
onClick={() => setCatalog('bc')}
>
<HardHat className="mr-1.5 h-4 w-4" />
Builder Club
</Button>
</div>
{/* View mode selector */}
<div className="flex items-center rounded-md border bg-card">
<Button
variant="ghost"
size="sm"
className={cn('h-8 rounded-r-none', currentView === 'tree' && 'bg-accent')}
onClick={() => setView('tree')}
>
<FolderTree className="mr-1.5 h-4 w-4" />
Tree
</Button>
<Button
variant="ghost"
size="sm"
className={cn('h-8 rounded-l-none', currentView === 'table' && 'bg-accent')}
onClick={() => setView('table')}
>
<List className="mr-1.5 h-4 w-4" />
Table
</Button>
</div>
</div>
)
}
+44
View File
@@ -0,0 +1,44 @@
import { Skeleton } from '@/components/ui/skeleton'
export default function CatalogLoading() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<Skeleton className="h-9 w-48" />
<Skeleton className="h-5 w-64 mt-2" />
</div>
<div className="flex items-center gap-2">
<Skeleton className="h-10 w-24" />
<Skeleton className="h-10 w-28" />
</div>
</div>
{/* Tree skeleton */}
<div className="rounded-lg border bg-card">
<div className="border-b px-4 py-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
<Skeleton className="h-8 w-56" />
</div>
<div className="p-2 space-y-1">
{Array.from({ length: 12 }).map((_, i) => (
<div
key={i}
className="flex items-center gap-2 px-2 py-1.5"
style={{ paddingLeft: `${(i % 3) * 20 + 8}px` }}
>
<Skeleton className="h-5 w-5 shrink-0" />
<Skeleton className="h-5 w-5 shrink-0" />
<Skeleton className="h-4 flex-1 max-w-48" />
<Skeleton className="h-5 w-8 rounded-full" />
</div>
))}
</div>
</div>
</div>
)
}
+380 -119
View File
@@ -1,130 +1,391 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
import { Package } from "lucide-react";
import dynamic from 'next/dynamic'
import { redirect } from 'next/navigation'
import { CatalogTree } from '@/components/admin/catalog-tree'
import { Prisma } from '@/generated/prisma/client'
import { calcPagination, parseListParams } from '@/lib/admin-helpers'
import { canAccess, getAdminContext, PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { CatalogActions } from './catalog-actions'
import { CatalogTable } from './catalog-table'
import { CatalogViewToggle } from './catalog-view-toggle'
export const dynamic = "force-dynamic";
type CatalogPageRow = {
id: number;
caption: string;
parentId: number;
pageLayout: string;
minRank: number;
orderNum: number;
visible: string;
enabled: string;
};
export default async function AdminCatalog() {
const t = await getTranslations("pages.admin.catalog");
let pages: CatalogPageRow[] = [];
try {
pages = await prisma.catalogPages.findMany({
select: {
id: true,
caption: true,
parentId: true,
pageLayout: true,
minRank: true,
orderNum: true,
visible: true,
enabled: true,
},
orderBy: [{ parentId: "asc" }, { orderNum: "asc" }, { id: "asc" }],
take: 500,
});
} catch {
pages = [];
const CatalogManagerDialog = dynamic(() =>
import('@/components/admin/catalog-manager/catalog-manager-dialog').then((m) => ({
default: m.CatalogManagerDialog,
})),
)
export default async function CatalogPagesPage({
params: paramsPromise,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<Record<string, string>>
}) {
await paramsPromise
const { session, permissions } = await getAdminContext()
if (!canAccess(permissions, PERMS.CATALOG_VIEW, session.user.rank)) {
redirect('/admin')
}
const captionById = new Map<number, string>();
for (const p of pages) captionById.set(p.id, p.caption);
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank)
const visibleCount = pages.filter(
(p) => p.visible === "1" && p.enabled === "1",
).length;
const hiddenCount = pages.length - visibleCount;
const rootCount = pages.filter((p) => p.parentId <= 0).length;
const params = await searchParams
const sp = new URLSearchParams(params)
const { search, perPage, page, sort, order } = parseListParams(sp)
const viewMode = sp.get('view') || 'tree'
const catalogType = sp.get('catalog') || 'normal'
// ── Builder Club mode ──────────────────────────────────────────
type TreeNodeShape = {
id: number
caption: string
parentId: number
enabled: string
visible: string
iconImage: number
iconColor: number
pageLayout: string
childCount: number
itemCount: number
}
if (catalogType === 'bc') {
const [totalBcPages, totalBcItems, enabledBcPages] = await Promise.all([
prisma.catalog_pages_bc.count(),
prisma.catalog_items_bc.count(),
prisma.catalog_pages_bc.count({ where: { enabled: '1' } }),
])
// ── BC tree view ──────────────────────────────────────────────
let bcRootPages: TreeNodeShape[] = []
if (viewMode === 'tree') {
const bcRootRaw = await prisma.catalog_pages_bc.findMany({
where: { OR: [{ parent_id: -1 }, { parent_id: 0 }] },
orderBy: { order_num: 'asc' },
})
const bcRootIds = bcRootRaw.map((p) => p.id)
const [bcChildCounts, bcItemCounts] = await Promise.all([
bcRootIds.length > 0
? prisma.catalog_pages_bc.groupBy({
by: ['parent_id'],
where: { parent_id: { in: bcRootIds } },
_count: true,
})
: [],
bcRootIds.length > 0
? prisma.catalog_items_bc.groupBy({
by: ['page_id'],
where: { page_id: { in: bcRootIds } },
_count: true,
})
: [],
])
const bcChildMap = Object.fromEntries(bcChildCounts.map((c) => [c.parent_id, c._count]))
const bcItemMap = Object.fromEntries(bcItemCounts.map((c) => [c.page_id, c._count]))
bcRootPages = bcRootRaw.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parent_id,
enabled: String(p.enabled),
visible: String(p.visible),
iconImage: p.icon_image,
iconColor: p.icon_color,
pageLayout: p.page_layout,
childCount: bcChildMap[p.id] ?? 0,
itemCount: bcItemMap[p.id] ?? 0,
}))
}
// ── BC table view ─────────────────────────────────────────────
let bcRows: {
id: number
caption: string
parentId: number
parentCaption: string
pageLayout: string
enabled: string
visible: string
minRank: number
orderNum: number
itemCount: number
childCount: number
}[] = []
let bcPagination = { total: 0, page: 1, perPage, lastPage: 0 }
if (viewMode === 'table') {
const parentFilter = sp.get('parent')
const parentId = parentFilter !== null ? parseInt(parentFilter, 10) : undefined
const where: Record<string, unknown> = {}
const hasParent = parentId !== undefined && !Number.isNaN(parentId)
if (search) {
const pattern = { contains: search }
where.OR = [{ caption: pattern }]
}
if (hasParent) where.parent_id = parentId
// Prisma sort key is snake_case for BC model. Translate known keys.
const sortKeyMap: Record<string, string> = {
parentId: 'parent_id',
pageLayout: 'page_layout',
orderNum: 'order_num',
}
const sortKey = sort ? (sortKeyMap[sort] ?? sort) : 'order_num'
const orderBy = { [sortKey]: sort ? order : 'asc' }
const [pages, total] = await Promise.all([
prisma.catalog_pages_bc.findMany({
where,
orderBy,
skip: (page - 1) * perPage,
take: perPage,
}),
prisma.catalog_pages_bc.count({ where }),
])
bcPagination = calcPagination(total, page, perPage)
const pageIds = pages.map((p) => p.id)
const parentIds = [...new Set(pages.map((p) => p.parent_id).filter((id) => id > 0))]
const [childCounts, itemCounts, parentPages] = await Promise.all([
pageIds.length > 0
? prisma.catalog_pages_bc.groupBy({
by: ['parent_id'],
where: { parent_id: { in: pageIds } },
_count: true,
})
: [],
pageIds.length > 0
? prisma.catalog_items_bc.groupBy({
by: ['page_id'],
where: { page_id: { in: pageIds } },
_count: true,
})
: [],
parentIds.length > 0
? prisma.catalog_pages_bc.findMany({
where: { id: { in: parentIds } },
select: { id: true, caption: true },
})
: [],
])
const childCountMap = Object.fromEntries(childCounts.map((c) => [c.parent_id, c._count]))
const itemCountMap = Object.fromEntries(itemCounts.map((c) => [c.page_id, c._count]))
const parentNameMap = Object.fromEntries(parentPages.map((p) => [p.id, p.caption]))
bcRows = pages.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parent_id,
parentCaption:
p.parent_id === -1 ? 'Root' : (parentNameMap[p.parent_id] ?? `#${p.parent_id}`),
pageLayout: String(p.page_layout),
enabled: String(p.enabled),
visible: String(p.visible),
minRank: 0, // BC pages have no min rank column
orderNum: p.order_num,
itemCount: itemCountMap[p.id] ?? 0,
childCount: childCountMap[p.id] ?? 0,
}))
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Catalog Pages</h1>
<p className="text-muted-foreground">
{totalBcPages} BC pages ({enabledBcPages} enabled) &middot; {totalBcItems} items
</p>
</div>
<div className="flex items-center gap-2">
<CatalogViewToggle currentView={viewMode} catalogType="bc" />
{canEdit && <CatalogActions catalogType="bc" />}
</div>
</div>
{viewMode === 'tree' ? (
<CatalogTree rootPages={bcRootPages} catalogType="bc" />
) : (
<CatalogTable
data={{ rows: bcRows, ...bcPagination }}
canEdit={canEdit}
catalogType="bc"
/>
)}
</div>
)
}
// ── Normal catalog mode ────────────────────────────────────────
// Global stats (lightweight counts)
const [totalPages, totalItems, enabledPages] = await Promise.all([
prisma.catalogPage.count(),
prisma.catalogItem.count(),
prisma.catalogPage.count({ where: { enabled: '1' } }),
])
// ── Tree view data ──────────────────────────────────────────────
let rootPages: TreeNodeShape[] = []
if (viewMode === 'tree') {
const rootPagesRaw = await prisma.catalogPage.findMany({
where: { parentId: -1 },
orderBy: { orderNum: 'asc' },
})
const rootIds = rootPagesRaw.map((p) => p.id)
const [rootChildCounts, rootItemCounts] = await Promise.all([
rootIds.length > 0
? prisma.catalogPage.groupBy({
by: ['parentId'],
where: { parentId: { in: rootIds } },
_count: true,
})
: [],
rootIds.length > 0
? prisma.catalogItem.groupBy({
by: ['pageId'],
where: { pageId: { in: rootIds } },
_count: true,
})
: [],
])
const rootChildMap = Object.fromEntries(rootChildCounts.map((c) => [c.parentId, c._count]))
const rootItemMap = Object.fromEntries(rootItemCounts.map((c) => [c.pageId, c._count]))
rootPages = rootPagesRaw.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parentId,
enabled: String(p.enabled),
visible: String(p.visible),
iconImage: p.iconImage,
iconColor: p.iconColor,
pageLayout: p.pageLayout,
childCount: rootChildMap[p.id] ?? 0,
itemCount: rootItemMap[p.id] ?? 0,
}))
}
// ── Table view data (skip if tree) ────────────────────────────
let rows: {
id: number
caption: string
parentId: number
parentCaption: string
pageLayout: string
enabled: string
visible: string
minRank: number
orderNum: number
itemCount: number
childCount: number
}[] = []
let pagination = { total: 0, page: 1, perPage, lastPage: 0 }
if (viewMode === 'table') {
const parentFilter = sp.get('parent')
const parentId = parentFilter !== null ? parseInt(parentFilter, 10) : undefined
const where: Record<string, unknown> = {}
const hasParent = parentId !== undefined && !Number.isNaN(parentId)
if (search) {
const searchPattern = `%${search}%`
const parentClause = hasParent ? Prisma.sql`AND cp.parent_id = ${parentId}` : Prisma.empty
const matchedIds = await prisma.$queryRaw<{ id: number }[]>(Prisma.sql`
SELECT DISTINCT cp.id FROM catalog_pages cp
LEFT JOIN catalog_items ci ON ci.page_id = cp.id
LEFT JOIN items_base ib ON FIND_IN_SET(ib.id, REPLACE(ci.item_ids, ';', ','))
WHERE (cp.caption LIKE ${searchPattern}
OR cp.page_layout LIKE ${searchPattern}
OR ci.catalog_name LIKE ${searchPattern}
OR ib.public_name LIKE ${searchPattern}
OR ib.item_name LIKE ${searchPattern})
${parentClause}
`)
where.id = { in: matchedIds.map((r) => r.id) }
} else if (hasParent) {
where.parentId = parentId
}
const orderBy = sort ? { [sort]: order } : { orderNum: 'asc' as const }
const [pages, total] = await Promise.all([
prisma.catalogPage.findMany({
where,
orderBy,
skip: (page - 1) * perPage,
take: perPage,
}),
prisma.catalogPage.count({ where }),
])
pagination = calcPagination(total, page, perPage)
// Count children and items per page, and resolve parent names in parallel
const pageIds = pages.map((p) => p.id)
const parentIds = [...new Set(pages.map((p) => p.parentId).filter((id) => id > 0))]
const [childCounts, itemCounts, parentPages] = await Promise.all([
pageIds.length > 0
? prisma.catalogPage.groupBy({
by: ['parentId'],
where: { parentId: { in: pageIds } },
_count: true,
})
: [],
pageIds.length > 0
? prisma.catalogItem.groupBy({
by: ['pageId'],
where: { pageId: { in: pageIds } },
_count: true,
})
: [],
parentIds.length > 0
? prisma.catalogPage.findMany({
where: { id: { in: parentIds } },
select: { id: true, caption: true },
})
: [],
])
const childCountMap = Object.fromEntries(childCounts.map((c) => [c.parentId, c._count]))
const itemCountMap = Object.fromEntries(itemCounts.map((c) => [c.pageId, c._count]))
const parentNameMap = Object.fromEntries(parentPages.map((p) => [p.id, p.caption]))
rows = pages.map((p) => ({
id: p.id,
caption: p.caption,
parentId: p.parentId,
parentCaption: p.parentId === -1 ? 'Root' : (parentNameMap[p.parentId] ?? `#${p.parentId}`),
pageLayout: p.pageLayout,
enabled: p.enabled,
visible: p.visible,
minRank: p.minRank,
orderNum: p.orderNum,
itemCount: itemCountMap[p.id] ?? 0,
childCount: childCountMap[p.id] ?? 0,
}))
}
return (
<main>
<div className="flex items-center gap-3 mb-6">
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-[var(--color-primary)]/20 to-[var(--color-primary)]/5 grid place-items-center">
<Package size={20} className="text-[var(--color-primary)]" />
</div>
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle")}</p>
<h1 className="text-3xl font-bold tracking-tight">Catalog Pages</h1>
<p className="text-muted-foreground">
{totalPages} pages ({enabledPages} enabled) &middot; {totalItems} items
</p>
</div>
<div className="flex items-center gap-2">
<CatalogViewToggle currentView={viewMode} catalogType="normal" />
{canEdit && <CatalogManagerDialog />}
{canEdit && <CatalogActions />}
</div>
</div>
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6">
<StatusCard label={t("pages")} value={pages.length} icon="📚" />
<StatusCard label={t("visible")} value={visibleCount} state="ok" icon="👁️" />
<StatusCard
label={t("hidden")}
value={hiddenCount}
state={hiddenCount > 0 ? "warn" : "neutral"}
icon="🚫"
/>
<StatusCard label={t("rootPages")} value={rootCount} icon="🗂️" />
</div>
<section className="mt-6">
<h2>{t("pages")} ({pages.length})</h2>
{pages.length === 0 ? (
<p className="muted">{t("noPages")}</p>
) : (
<div style={{ overflowX: "auto" }}>
<table>
<thead>
<tr>
<th>{t("colId")}</th>
<th>{t("caption")}</th>
<th>{t("colParent")}</th>
<th>{t("colLayout")}</th>
<th>{t("colMinRank")}</th>
<th>{t("colOrder")}</th>
<th>{t("colStatus")}</th>
</tr>
</thead>
<tbody>
{pages.map((p) => {
const parentName =
p.parentId > 0 ? captionById.get(p.parentId) : null;
const hidden = p.visible !== "1" || p.enabled !== "1";
return (
<tr key={p.id}>
<td className="muted">{p.id}</td>
<td>
<Link href={`/admin/catalog/${p.id}`}>{p.caption}</Link>
</td>
<td className="muted">
{p.parentId <= 0
? "—"
: parentName
? `${parentName} (#${p.parentId})`
: `#${p.parentId}`}
</td>
<td className="muted">{p.pageLayout}</td>
<td>{p.minRank}</td>
<td>{p.orderNum}</td>
<td>
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${hidden ? "bg-red-500/22 text-[var(--color-text)]" : "bg-green-600/20 text-[var(--color-text)]"}`}>
{hidden ? t("statusHidden") : t("statusVisible")}
</span>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</section>
</main>
);
{viewMode === 'tree' ? (
<CatalogTree rootPages={rootPages} catalogType="normal" />
) : (
<CatalogTable data={{ rows, ...pagination }} canEdit={canEdit} />
)}
</div>
)
}
Loaded 100 of 338 files, more files were not shown because too many files have changed in this diff. Show more