Add missing admin action files and navigation links
- Add 11 missing server action files: badges, bulk-users, catalog, catalog-bc, catalog-items, import-badges, import-furni, multi-account-detect, permissions, rooms, soundtracks - Add missing admin navigation links: tickets, sounds, translations, import, radio sub-pages - Add translation keys for all new navigation items
This commit is contained in:
1 parent
7e1ae17a3b
commit
41be6835bf
347 files changed
+28378
-6091
No files matched your search
@@ -11,7 +11,9 @@ import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||
|
||||
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();
|
||||
@@ -39,7 +41,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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -52,10 +52,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(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -6,8 +6,12 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
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;
|
||||
@@ -35,7 +39,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;
|
||||
|
||||
@@ -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
@@ -16,16 +16,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> {
|
||||
if (!/^\d+$/.test(raw)) return;
|
||||
const id = BigInt(raw);
|
||||
|
||||
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({
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -17,7 +17,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;
|
||||
@@ -46,7 +48,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;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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 +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";
|
||||
@@ -6,8 +6,12 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
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;
|
||||
@@ -44,16 +48,27 @@ export async function createValue(formData: FormData): Promise<void> {
|
||||
if (!/^\d+$/.test(categoryRaw)) return;
|
||||
const categoryId = BigInt(categoryRaw);
|
||||
|
||||
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({
|
||||
|
||||
@@ -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
@@ -28,7 +28,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();
|
||||
@@ -36,15 +38,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,
|
||||
@@ -77,7 +88,9 @@ export async function updateShopArticle(formData: FormData): Promise<void> {
|
||||
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 {
|
||||
@@ -85,15 +98,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
@@ -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");
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import { prisma } from "@/lib/prisma";
|
||||
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;
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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 } };
|
||||
}
|
||||
@@ -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 } };
|
||||
}
|
||||
@@ -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 } };
|
||||
}
|
||||
@@ -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 } };
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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" };
|
||||
}
|
||||
}
|
||||
@@ -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}` };
|
||||
}
|
||||
}
|
||||
@@ -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 } };
|
||||
}
|
||||
@@ -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[]) => {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
}
|
||||
|
||||
@@ -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}`);
|
||||
}
|
||||
@@ -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 */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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." };
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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>
|
||||
))}
|
||||
|
||||
@@ -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 "{inputValue.trim()}"
|
||||
</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>
|
||||
)
|
||||
}
|
||||
@@ -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
@@ -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} · {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')
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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
@@ -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) · {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) · {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>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import os from "node:os";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { Activity } from 'lucide-react';
|
||||
import { Activity } from "lucide-react";
|
||||
import {
|
||||
hotelAlert,
|
||||
updateCatalog,
|
||||
@@ -58,21 +58,20 @@ function uptime(seconds: number): string {
|
||||
export default async function CommandoCentrum() {
|
||||
const t = await getTranslations("pages.admin.commandocentrum");
|
||||
|
||||
const [onlineCount, totalUsers, errors, dbOk, emulatorOnline, maintenance, activity] =
|
||||
await Promise.all([
|
||||
prisma.user.count({ where: { online: "1" } }).catch(() => 0),
|
||||
prisma.user.count().catch(() => -1),
|
||||
prisma.emulatorErrors.findMany({ orderBy: { timestamp: "desc" }, take: 50 }).catch(() => []),
|
||||
prisma.websiteSetting
|
||||
.count()
|
||||
.then(() => true)
|
||||
.catch(() => false),
|
||||
rcon.send("ping", null).catch(() => false),
|
||||
siteSettings.getBool("maintenance_enabled", false),
|
||||
prisma.staffActivities
|
||||
.findMany({ orderBy: { createdAt: "desc" }, take: 12 })
|
||||
.catch(() => [] as Awaited<ReturnType<typeof prisma.staffActivities.findMany>>),
|
||||
]);
|
||||
const [onlineCount, totalUsers, errors, dbOk, emulatorOnline, maintenance, activity] = await Promise.all([
|
||||
prisma.user.count({ where: { online: "1" } }).catch(() => 0),
|
||||
prisma.user.count().catch(() => -1),
|
||||
prisma.emulatorErrors.findMany({ orderBy: { timestamp: "desc" }, take: 50 }).catch(() => []),
|
||||
prisma.websiteSetting
|
||||
.count()
|
||||
.then(() => true)
|
||||
.catch(() => false),
|
||||
rcon.send("ping", null).catch(() => false),
|
||||
siteSettings.getBool("maintenance_enabled", false),
|
||||
prisma.staffActivities
|
||||
.findMany({ orderBy: { createdAt: "desc" }, take: 12 })
|
||||
.catch(() => [] as Awaited<ReturnType<typeof prisma.staffActivities.findMany>>),
|
||||
]);
|
||||
|
||||
const staffIds = Array.from(new Set(activity.map((a) => Number(a.userId)))).filter((n) => n > 0);
|
||||
let nameById = new Map<number, string>();
|
||||
@@ -100,7 +99,10 @@ export default async function CommandoCentrum() {
|
||||
</div>
|
||||
|
||||
{/* ── Live status ────────────────────────────────────────── */}
|
||||
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6" style={{ marginTop: "1.1rem" }}>
|
||||
<div
|
||||
className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6"
|
||||
style={{ marginTop: "1.1rem" }}
|
||||
>
|
||||
<StatusCard
|
||||
label={t("playersOnline")}
|
||||
value={onlineCount}
|
||||
@@ -134,10 +136,7 @@ export default async function CommandoCentrum() {
|
||||
{/* ── Online users widget ───────────────────────────────── */}
|
||||
<section className="admin-card mb-6">
|
||||
<h2 className="admin-section-title">{t("onlineUsers")}</h2>
|
||||
<OnlineUsersWidget
|
||||
users={[]}
|
||||
isLoading={false}
|
||||
/>
|
||||
<OnlineUsersWidget users={[]} isLoading={false} />
|
||||
</section>
|
||||
|
||||
{/* ── Server info + diagnostics ──────────────────────────── */}
|
||||
@@ -198,9 +197,7 @@ export default async function CommandoCentrum() {
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<form action={updateCatalog} className="admin-card">
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("updateCatalog")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-4">
|
||||
{t("updateCatalogDesc")}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-4">{t("updateCatalogDesc")}</p>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("updateCatalog")}
|
||||
</button>
|
||||
@@ -208,9 +205,7 @@ export default async function CommandoCentrum() {
|
||||
|
||||
<form action={updateWordFilter} className="admin-card">
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("updateWordFilter")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-4">
|
||||
{t("updateWordFilterDesc")}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-4">{t("updateWordFilterDesc")}</p>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("updateWordFilter")}
|
||||
</button>
|
||||
@@ -218,9 +213,7 @@ export default async function CommandoCentrum() {
|
||||
|
||||
<form action={updateNavigator} className="admin-card">
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("updateNavigator")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-4">
|
||||
{t("updateNavigatorDesc")}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-4">{t("updateNavigatorDesc")}</p>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("updateNavigator")}
|
||||
</button>
|
||||
@@ -229,9 +222,7 @@ export default async function CommandoCentrum() {
|
||||
|
||||
<form action={hotelAlert} className="admin-card mt-6">
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("hotelAlert")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">
|
||||
{t("hotelAlertDesc")}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("hotelAlertDesc")}</p>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
name="message"
|
||||
@@ -250,18 +241,31 @@ export default async function CommandoCentrum() {
|
||||
{/* ── User RCON actions ──────────────────────────────────── */}
|
||||
<section className="mt-6">
|
||||
<h2 className="admin-section-title">{t("userActions")}</h2>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-4">
|
||||
{t("userActionsDesc")}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-4">{t("userActionsDesc")}</p>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<form action={disconnectUser} className="admin-card">
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("actions.disconnect")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("disconnectDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="username" type="text" placeholder={t("usernameRequired")} required className="w-full" />
|
||||
<button type="submit" className="btn btn-danger w-full">{t("actions.disconnect")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="username"
|
||||
type="text"
|
||||
placeholder={t("usernameRequired")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-danger w-full">
|
||||
{t("actions.disconnect")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -269,9 +273,25 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("actions.alert")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("alertDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="message" type="text" placeholder={t("alertMessage")} required maxLength={512} className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("actions.alert")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="message"
|
||||
type="text"
|
||||
placeholder={t("alertMessage")}
|
||||
required
|
||||
maxLength={512}
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("actions.alert")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -279,9 +299,25 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("forwardToRoom")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("forwardDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="roomId" type="number" min={1} placeholder={t("roomId")} required className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("forwardUser")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="roomId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("roomId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("forwardUser")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -291,9 +327,25 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("giveCredits")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("giveCreditsDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="credits" type="number" min={1} placeholder={t("amount")} required className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("giveCredits")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="credits"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("amount")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("giveCredits")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -301,9 +353,25 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("giveDuckets")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("giveDucketsDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="amount" type="number" min={1} placeholder={t("amount")} required className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("giveDuckets")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="amount"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("amount")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("giveDuckets")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -311,9 +379,25 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("giveDiamonds")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("giveDiamondsDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="amount" type="number" min={1} placeholder={t("amount")} required className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("giveDiamonds")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="amount"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("amount")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("giveDiamonds")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -323,9 +407,25 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("giveBadge")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("giveBadgeDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="badge" type="text" placeholder={t("badgeCode")} required maxLength={32} className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("giveBadge")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="badge"
|
||||
type="text"
|
||||
placeholder={t("badgeCode")}
|
||||
required
|
||||
maxLength={32}
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("giveBadge")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -333,9 +433,25 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("setMotto")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("setMottoDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="motto" type="text" placeholder={t("newMotto")} required maxLength={127} className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("setMotto")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="motto"
|
||||
type="text"
|
||||
placeholder={t("newMotto")}
|
||||
required
|
||||
maxLength={127}
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("setMotto")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -343,9 +459,26 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("setRank")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("setRankDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="rank" type="number" min={0} max={10} placeholder={t("rankPlaceholder")} required className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("setRank")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="rank"
|
||||
type="number"
|
||||
min={0}
|
||||
max={10}
|
||||
placeholder={t("rankPlaceholder")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("setRank")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -355,9 +488,25 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("executeCommand")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("executeCommandDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="command" type="text" placeholder={t("commandPlaceholder")} required maxLength={100} className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("execute")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="command"
|
||||
type="text"
|
||||
placeholder={t("commandPlaceholder")}
|
||||
required
|
||||
maxLength={100}
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("execute")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -365,10 +514,33 @@ export default async function CommandoCentrum() {
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("sendGift")}</h3>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mb-3">{t("sendGiftDesc")}</p>
|
||||
<div className="space-y-2">
|
||||
<input name="userId" type="number" min={1} placeholder={t("userId")} required className="w-full" />
|
||||
<input name="itemId" type="number" min={1} placeholder={t("furniId")} required className="w-full" />
|
||||
<input name="message" type="text" placeholder={t("giftMessage")} maxLength={255} defaultValue={t("defaultGiftMessage")} className="w-full" />
|
||||
<button type="submit" className="btn btn-primary w-full">{t("sendGift")}</button>
|
||||
<input
|
||||
name="userId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("userId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="itemId"
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t("furniId")}
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
<input
|
||||
name="message"
|
||||
type="text"
|
||||
placeholder={t("giftMessage")}
|
||||
maxLength={255}
|
||||
defaultValue={t("defaultGiftMessage")}
|
||||
className="w-full"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary w-full">
|
||||
{t("sendGift")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -398,7 +570,9 @@ export default async function CommandoCentrum() {
|
||||
</td>
|
||||
<td>{nameById.get(Number(a.userId)) ?? `#${a.userId}`}</td>
|
||||
<td>
|
||||
<span className="inline-block text-[0.6rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">{a.action}</span>
|
||||
<span className="inline-block text-[0.6rem] font-bold px-2 py-0.5 rounded-full bg-[var(--color-primary)]/18 text-[var(--color-text)]">
|
||||
{a.action}
|
||||
</span>
|
||||
</td>
|
||||
<td className="text-sm text-gray-500 dark:text-gray-400">{a.description}</td>
|
||||
</tr>
|
||||
@@ -426,7 +600,7 @@ export default async function CommandoCentrum() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{errors.map((e) => {
|
||||
{errors.map((e) => {
|
||||
const trace = decodeStacktrace(e.stacktrace);
|
||||
const snippet = trace
|
||||
? trace.split("\n").slice(0, 20).join("\n") +
|
||||
|
||||
@@ -32,13 +32,15 @@ export default async function AdminEmailTemplates() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form
|
||||
action={createEmailTemplate}
|
||||
className="admin-card mb-6"
|
||||
>
|
||||
<form action={createEmailTemplate} className="admin-card mb-6">
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] mb-2">{t("newTemplate")}</h3>
|
||||
<div className="flex gap-2 flex-wrap items-center mb-3">
|
||||
<input name="name" placeholder={t("form.namePlaceholder")} required className="flex-1 min-w-[180px]" />
|
||||
<input
|
||||
name="name"
|
||||
placeholder={t("form.namePlaceholder")}
|
||||
required
|
||||
className="flex-1 min-w-[180px]"
|
||||
/>
|
||||
<input
|
||||
name="subject"
|
||||
placeholder={t("form.subjectPlaceholder")}
|
||||
@@ -108,7 +110,9 @@ export default async function AdminEmailTemplates() {
|
||||
</button>
|
||||
{template.updatedAt ? (
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{t("updated", { date: new Date(template.updatedAt).toISOString().slice(0, 16).replace("T", " ") })}
|
||||
{t("updated", {
|
||||
date: new Date(template.updatedAt).toISOString().slice(0, 16).replace("T", " "),
|
||||
})}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
+77
-113
@@ -55,62 +55,46 @@ export default async function AdminEmulator() {
|
||||
{t("keysCount", { count: settings.length })}
|
||||
</p>
|
||||
|
||||
<form
|
||||
action={updateEmulatorSetting}
|
||||
className="admin-card mb-6"
|
||||
>
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addOverwriteSetting")}</h3>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<input name="key" placeholder={t("key")} maxLength={100} required />
|
||||
<input
|
||||
name="value"
|
||||
placeholder={t("value")}
|
||||
maxLength={512}
|
||||
className="flex-1 min-w-[200px]"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<form action={updateEmulatorSetting} className="admin-card mb-6">
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addOverwriteSetting")}</h3>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<input name="key" placeholder={t("key")} maxLength={100} required />
|
||||
<input name="value" placeholder={t("value")} maxLength={512} className="flex-1 min-w-[200px]" />
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-[320px]">{t("colKey")}</th>
|
||||
<th>{t("colValue")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{settings.map((s) => (
|
||||
<tr key={s.key}>
|
||||
<td>
|
||||
<strong>{s.key}</strong>
|
||||
</td>
|
||||
<td>
|
||||
<form
|
||||
action={updateEmulatorSetting}
|
||||
className="flex gap-2"
|
||||
>
|
||||
<input type="hidden" name="key" value={s.key} />
|
||||
<input
|
||||
name="value"
|
||||
defaultValue={s.value}
|
||||
maxLength={512}
|
||||
className="flex-1"
|
||||
/>
|
||||
<button type="submit" className="btn btn-outline">
|
||||
{t("save")}
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-[320px]">{t("colKey")}</th>
|
||||
<th>{t("colValue")}</th>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{settings.length === 0 ? (
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">{t("noSettings")}</p>
|
||||
) : null}
|
||||
</thead>
|
||||
<tbody>
|
||||
{settings.map((s) => (
|
||||
<tr key={s.key}>
|
||||
<td>
|
||||
<strong>{s.key}</strong>
|
||||
</td>
|
||||
<td>
|
||||
<form action={updateEmulatorSetting} className="flex gap-2">
|
||||
<input type="hidden" name="key" value={s.key} />
|
||||
<input name="value" defaultValue={s.value} maxLength={512} className="flex-1" />
|
||||
<button type="submit" className="btn btn-outline">
|
||||
{t("save")}
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{settings.length === 0 ? (
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">{t("noSettings")}</p>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="mt-6">
|
||||
@@ -120,67 +104,47 @@ export default async function AdminEmulator() {
|
||||
{textsTruncated ? ` (${t("showingFirst", { count: texts.length })})` : ""}.
|
||||
</p>
|
||||
|
||||
<form
|
||||
action={updateEmulatorText}
|
||||
className="admin-card mb-6"
|
||||
>
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addOverwriteText")}</h3>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<input name="key" placeholder={t("key")} maxLength={100} required />
|
||||
<input
|
||||
name="value"
|
||||
placeholder={t("value")}
|
||||
maxLength={4096}
|
||||
className="flex-1 min-w-[200px]"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<form action={updateEmulatorText} className="admin-card mb-6">
|
||||
<h3 className="text-sm font-bold text-[var(--color-text)] m-0 mb-3">{t("addOverwriteText")}</h3>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<input name="key" placeholder={t("key")} maxLength={100} required />
|
||||
<input name="value" placeholder={t("value")} maxLength={4096} className="flex-1 min-w-[200px]" />
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-[320px]">{t("colKey")}</th>
|
||||
<th>{t("colValue")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{texts.map((txt) => (
|
||||
<tr key={txt.key}>
|
||||
<td>
|
||||
<strong>{txt.key}</strong>
|
||||
</td>
|
||||
<td>
|
||||
<form
|
||||
action={updateEmulatorText}
|
||||
className="flex gap-2"
|
||||
>
|
||||
<input type="hidden" name="key" value={txt.key} />
|
||||
<input
|
||||
name="value"
|
||||
defaultValue={txt.value}
|
||||
maxLength={4096}
|
||||
className="flex-1"
|
||||
/>
|
||||
<button type="submit" className="btn btn-outline">
|
||||
{t("save")}
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-[320px]">{t("colKey")}</th>
|
||||
<th>{t("colValue")}</th>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{texts.length === 0 ? (
|
||||
<div className="admin-empty">{t("noTexts")}</div>
|
||||
) : null}
|
||||
{textsTruncated ? (
|
||||
<p className="muted">
|
||||
{t("truncatedHint", { shown: texts.length, total: textsCount })}
|
||||
</p>
|
||||
) : null}
|
||||
</thead>
|
||||
<tbody>
|
||||
{texts.map((txt) => (
|
||||
<tr key={txt.key}>
|
||||
<td>
|
||||
<strong>{txt.key}</strong>
|
||||
</td>
|
||||
<td>
|
||||
<form action={updateEmulatorText} className="flex gap-2">
|
||||
<input type="hidden" name="key" value={txt.key} />
|
||||
<input name="value" defaultValue={txt.value} maxLength={4096} className="flex-1" />
|
||||
<button type="submit" className="btn btn-outline">
|
||||
{t("save")}
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{texts.length === 0 ? <div className="admin-empty">{t("noTexts")}</div> : null}
|
||||
{textsTruncated ? (
|
||||
<p className="muted">{t("truncatedHint", { shown: texts.length, total: textsCount })}</p>
|
||||
) : null}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -71,9 +71,18 @@ export function FaviconGenerator({ onSave }: Props) {
|
||||
}
|
||||
|
||||
const swatches = [
|
||||
"#6366f1", "#3b82f6", "#06b6d4", "#10b981",
|
||||
"#f59e0b", "#ef4444", "#ec4899", "#8b5cf6",
|
||||
"#1e1b4b", "#1f2937", "#000000", "#ffffff",
|
||||
"#6366f1",
|
||||
"#3b82f6",
|
||||
"#06b6d4",
|
||||
"#10b981",
|
||||
"#f59e0b",
|
||||
"#ef4444",
|
||||
"#ec4899",
|
||||
"#8b5cf6",
|
||||
"#1e1b4b",
|
||||
"#1f2937",
|
||||
"#000000",
|
||||
"#ffffff",
|
||||
];
|
||||
|
||||
return (
|
||||
|
||||
@@ -15,9 +15,7 @@ export default async function EditHelpQuestion({
|
||||
}) {
|
||||
const { id } = await params;
|
||||
const { error } = await searchParams;
|
||||
let entry: Awaited<
|
||||
ReturnType<typeof prisma.websiteHelpCenterCategories.findUnique>
|
||||
> = null;
|
||||
let entry: Awaited<ReturnType<typeof prisma.websiteHelpCenterCategories.findUnique>> = null;
|
||||
try {
|
||||
entry = await prisma.websiteHelpCenterCategories.findUnique({
|
||||
where: { id: BigInt(id) },
|
||||
@@ -35,7 +33,9 @@ export default async function EditHelpQuestion({
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">Edit help-center entry</h1>
|
||||
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/help-questions">← Help Center</Link></p>
|
||||
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
|
||||
<Link href="/admin/help-questions">← Help Center</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{error ? (
|
||||
@@ -47,13 +47,7 @@ export default async function EditHelpQuestion({
|
||||
<input type="hidden" name="id" value={String(entry.id)} />
|
||||
<input name="name" defaultValue={entry.name} placeholder="Name / title" required maxLength={255} />
|
||||
<textarea name="content" defaultValue={entry.content} placeholder="Content" rows={6} required />
|
||||
<input
|
||||
name="position"
|
||||
type="number"
|
||||
min={1}
|
||||
defaultValue={entry.position}
|
||||
placeholder="Position"
|
||||
/>
|
||||
<input name="position" type="number" min={1} defaultValue={entry.position} placeholder="Position" />
|
||||
<input
|
||||
name="imageUrl"
|
||||
defaultValue={entry.imageUrl ?? ""}
|
||||
|
||||
@@ -17,7 +17,9 @@ export default async function NewHelpQuestion({
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">New help-center entry</h1>
|
||||
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5"><Link href="/admin/help-questions">← Help Center</Link></p>
|
||||
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">
|
||||
<Link href="/admin/help-questions">← Help Center</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{error ? (
|
||||
|
||||
@@ -8,9 +8,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AdminHelpQuestions() {
|
||||
const t = await getTranslations("pages.admin.helpCenter");
|
||||
let entries: Awaited<
|
||||
ReturnType<typeof prisma.websiteHelpCenterCategories.findMany>
|
||||
> = [];
|
||||
let entries: Awaited<ReturnType<typeof prisma.websiteHelpCenterCategories.findMany>> = [];
|
||||
try {
|
||||
entries = await prisma.websiteHelpCenterCategories.findMany({
|
||||
orderBy: [{ position: "asc" }, { id: "asc" }],
|
||||
@@ -66,9 +64,13 @@ export default async function AdminHelpQuestions() {
|
||||
<td>
|
||||
<Link href={`/admin/help-questions/${e.id}`}>{e.name}</Link>
|
||||
</td>
|
||||
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">{e.buttonText || "—"}</td>
|
||||
<td className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
|
||||
{e.buttonText || "—"}
|
||||
</td>
|
||||
<td>
|
||||
<span className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${e.smallBox ? "bg-green-600/20 text-[var(--color-text)]" : "bg-[var(--color-primary)]/18 text-[var(--color-text)]"}`}>
|
||||
<span
|
||||
className={`inline-block text-[0.72rem] font-bold px-2 py-0.5 rounded-full ${e.smallBox ? "bg-green-600/20 text-[var(--color-text)]" : "bg-[var(--color-primary)]/18 text-[var(--color-text)]"}`}
|
||||
>
|
||||
{e.smallBox ? "Yes" : "No"}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
@@ -16,9 +16,7 @@ export default async function AdminHousekeeping({
|
||||
const q = (sp.q ?? "").trim();
|
||||
const mode = sp.mode === "import" ? "import" : "manage";
|
||||
|
||||
let permissions: Awaited<
|
||||
ReturnType<typeof prisma.websiteHousekeepingPermissions.findMany>
|
||||
> = [];
|
||||
let permissions: Awaited<ReturnType<typeof prisma.websiteHousekeepingPermissions.findMany>> = [];
|
||||
try {
|
||||
permissions = await prisma.websiteHousekeepingPermissions.findMany({
|
||||
orderBy: [{ permission: "asc" }],
|
||||
@@ -39,7 +37,10 @@ export default async function AdminHousekeeping({
|
||||
if (mode === "import") {
|
||||
const importRaw = String(sp.q ?? "");
|
||||
if (importRaw) {
|
||||
const importIds = importRaw.split(",").map((i) => Number(i.trim())).filter((i) => !isNaN(i));
|
||||
const importIds = importRaw
|
||||
.split(",")
|
||||
.map((i) => Number(i.trim()))
|
||||
.filter((i) => !isNaN(i));
|
||||
importIds.forEach((id) => selectedIds.add(id));
|
||||
}
|
||||
}
|
||||
@@ -64,11 +65,22 @@ export default async function AdminHousekeeping({
|
||||
|
||||
<div className="admin-filter-bar">
|
||||
<form className="flex gap-2 flex-1">
|
||||
<input name="q" defaultValue={q} placeholder={t("searchPermission")} className="flex-1 min-w-[200px]" />
|
||||
<button type="submit" className="btn btn-primary">{t("search")}</button>
|
||||
<input
|
||||
name="q"
|
||||
defaultValue={q}
|
||||
placeholder={t("searchPermission")}
|
||||
className="flex-1 min-w-[200px]"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("search")}
|
||||
</button>
|
||||
</form>
|
||||
<Link href="/admin/housekeeping?mode=manage" className="btn btn-outline">{t("manage")}</Link>
|
||||
<Link href="/admin/housekeeping?mode=import&form=selected_ids" className="btn btn-outline">{t("importSelection")}</Link>
|
||||
<Link href="/admin/housekeeping?mode=manage" className="btn btn-outline">
|
||||
{t("manage")}
|
||||
</Link>
|
||||
<Link href="/admin/housekeeping?mode=import&form=selected_ids" className="btn btn-outline">
|
||||
{t("importSelection")}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{mode === "manage" ? (
|
||||
@@ -77,22 +89,36 @@ export default async function AdminHousekeeping({
|
||||
<form action={upsertPermission} className="admin-card">
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<input name="permission" placeholder={t("permissionKey")} required className="min-w-[200px]" />
|
||||
<input name="minRank" type="number" min={0} placeholder={t("minRank")} required className="w-[110px]" />
|
||||
<input
|
||||
name="minRank"
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder={t("minRank")}
|
||||
required
|
||||
className="w-[110px]"
|
||||
/>
|
||||
<input name="description" placeholder={t("description")} className="flex-1 min-w-[160px]" />
|
||||
<button type="submit" className="btn btn-primary">{t("save")}</button>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
) : (
|
||||
<section>
|
||||
<h2 className="admin-section-title">{t("importPermissions")}</h2>
|
||||
<p className="text-xs text-[var(--color-text-muted)] -mt-2 mb-3">
|
||||
{t("importHint")}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-text-muted)] -mt-2 mb-3">{t("importHint")}</p>
|
||||
<form action={upsertPermission} className="admin-card">
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<input name="q" placeholder={t("importPlaceholder")} required className="flex-1 min-w-[200px]" />
|
||||
<button type="submit" className="btn btn-primary">{t("import")}</button>
|
||||
<input
|
||||
name="q"
|
||||
placeholder={t("importPlaceholder")}
|
||||
required
|
||||
className="flex-1 min-w-[200px]"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("import")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
@@ -100,7 +126,10 @@ export default async function AdminHousekeeping({
|
||||
|
||||
<section>
|
||||
<h2 className="admin-section-title">
|
||||
{t("permissions")} <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)]">{filtered.length}</span>
|
||||
{t("permissions")}{" "}
|
||||
<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)]">
|
||||
{filtered.length}
|
||||
</span>
|
||||
</h2>
|
||||
{filtered.length === 0 ? (
|
||||
<div className="admin-empty">{t("noPermissions")}</div>
|
||||
@@ -118,8 +147,17 @@ export default async function AdminHousekeeping({
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((p, i) => (
|
||||
<tr key={String(p.id)} style={mode === "import" && selectedIds.has(i) ? { backgroundColor: "color-mix(in srgb, var(--color-primary) 5%, transparent)" } : {}}>
|
||||
<td className="muted" style={{ width: "40px" }}>{i + 1}</td>
|
||||
<tr
|
||||
key={String(p.id)}
|
||||
style={
|
||||
mode === "import" && selectedIds.has(i)
|
||||
? { backgroundColor: "color-mix(in srgb, var(--color-primary) 5%, transparent)" }
|
||||
: {}
|
||||
}
|
||||
>
|
||||
<td className="muted" style={{ width: "40px" }}>
|
||||
{i + 1}
|
||||
</td>
|
||||
<td>
|
||||
<strong>{p.permission}</strong>
|
||||
</td>
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
'use client'
|
||||
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { getBadgeData, updateBadge } from '@/actions/badges'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useServerAction } from '@/hooks/use-server-action'
|
||||
|
||||
interface BadgeEditorDialogProps {
|
||||
code: string
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** Called after a successful save so the parent can refresh state */
|
||||
onSaved?: () => void
|
||||
}
|
||||
|
||||
export function BadgeEditorDialog({ code, open, onOpenChange, onSaved }: BadgeEditorDialogProps) {
|
||||
const [name, setName] = useState('')
|
||||
const [desc, setDesc] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { run, isPending: saving } = useServerAction()
|
||||
|
||||
// Fetch current values when dialog opens
|
||||
useEffect(() => {
|
||||
if (!open || !code) return
|
||||
setLoading(true)
|
||||
getBadgeData({ code })
|
||||
.then((result) => {
|
||||
if (result.ok) {
|
||||
const data = result.data as { name: string; desc: string }
|
||||
setName(data.name ?? '')
|
||||
setDesc(data.desc ?? '')
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error('Failed to load badge data')
|
||||
})
|
||||
.finally(() => setLoading(false))
|
||||
}, [open, code])
|
||||
|
||||
function handleSave() {
|
||||
run(() => updateBadge({ code, name, desc }), {
|
||||
successMessage: `Badge ${code} updated`,
|
||||
errorMessage: 'Save failed',
|
||||
onSuccess: () => {
|
||||
onSaved?.()
|
||||
onOpenChange(false)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">Edit Badge — {code}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="badge-name">Name</Label>
|
||||
<Input
|
||||
id="badge-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Badge name"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="badge-desc">Description</Label>
|
||||
<Input
|
||||
id="badge-desc"
|
||||
value={desc}
|
||||
onChange={(e) => setDesc(e.target.value)}
|
||||
placeholder="Badge description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={loading || saving}>
|
||||
{saving && <Loader2 className="w-4 h-4 animate-spin mr-1" />}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
AlertCircle,
|
||||
BadgeCheck,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
Download,
|
||||
Globe,
|
||||
Loader2,
|
||||
Package,
|
||||
Pencil,
|
||||
Search,
|
||||
X,
|
||||
} from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { importBadgeFromRemote } from '@/actions/import-badges'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { BadgeEditorDialog } from './badge-editor-dialog'
|
||||
|
||||
interface BadgeItem {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
description: string
|
||||
hotel: string
|
||||
url_habbo: string
|
||||
url_habboassets: string
|
||||
alreadyImported: boolean
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 100
|
||||
|
||||
export function ImportBadgesClient() {
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const [activeSearch, setActiveSearch] = useState('')
|
||||
const [badges, setBadges] = useState<BadgeItem[]>([])
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [hasMore, setHasMore] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [importingCode, setImportingCode] = useState<string | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [allHotels, setAllHotels] = useState(true)
|
||||
const [editingCode, setEditingCode] = useState<string | null>(null)
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [batchImporting, setBatchImporting] = useState(false)
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const fetchBadges = useCallback(async (search: string, off: number, all: boolean) => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const params = new URLSearchParams({ offset: String(off) })
|
||||
if (search) params.set('search', search)
|
||||
if (all) params.set('allHotels', '1')
|
||||
const res = await fetch(`/api/admin/import/badges?${params}`)
|
||||
const data = await res.json()
|
||||
if (!res.ok) {
|
||||
setError(data.error || 'Failed to load')
|
||||
return
|
||||
}
|
||||
const list = data.badges || []
|
||||
setBadges(list)
|
||||
setHasMore(list.length >= PAGE_SIZE)
|
||||
setSelected(new Set())
|
||||
} catch {
|
||||
setError('Network error')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Auto-load on mount and when allHotels changes
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: explicitly chosen here, see surrounding code
|
||||
useEffect(() => {
|
||||
setOffset(0)
|
||||
fetchBadges(activeSearch, 0, allHotels)
|
||||
}, [fetchBadges, allHotels])
|
||||
|
||||
// "/" keyboard shortcut to focus search
|
||||
useEffect(() => {
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === '/' && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||||
const tag = (e.target as HTMLElement)?.tagName
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return
|
||||
e.preventDefault()
|
||||
searchRef.current?.focus()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', onKeyDown)
|
||||
return () => document.removeEventListener('keydown', onKeyDown)
|
||||
}, [])
|
||||
|
||||
function doSearch() {
|
||||
setActiveSearch(searchTerm)
|
||||
setOffset(0)
|
||||
fetchBadges(searchTerm, 0, allHotels)
|
||||
}
|
||||
|
||||
function goPage(direction: 'prev' | 'next') {
|
||||
const newOffset = direction === 'next' ? offset + PAGE_SIZE : Math.max(0, offset - PAGE_SIZE)
|
||||
setOffset(newOffset)
|
||||
fetchBadges(activeSearch, newOffset, allHotels)
|
||||
}
|
||||
|
||||
async function doImport(badge: BadgeItem) {
|
||||
setImportingCode(badge.code)
|
||||
try {
|
||||
const result = await importBadgeFromRemote({
|
||||
code: badge.code,
|
||||
name: badge.name,
|
||||
description: badge.description,
|
||||
})
|
||||
if (result.ok) {
|
||||
toast.success(`${badge.code} imported`)
|
||||
setBadges((prev) =>
|
||||
prev.map((b) => (b.code === badge.code ? { ...b, alreadyImported: true } : b)),
|
||||
)
|
||||
setSelected((prev) => {
|
||||
const n = new Set(prev)
|
||||
n.delete(badge.code)
|
||||
return n
|
||||
})
|
||||
} else {
|
||||
toast.error(result.error || `Failed to import ${badge.code}`)
|
||||
}
|
||||
} catch {
|
||||
toast.error(`Network error importing ${badge.code}`)
|
||||
} finally {
|
||||
setImportingCode(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function doBatchImport() {
|
||||
const toImport = badges.filter((b) => selected.has(b.code) && !b.alreadyImported)
|
||||
if (toImport.length === 0) return
|
||||
setBatchImporting(true)
|
||||
let ok = 0,
|
||||
fail = 0
|
||||
for (const badge of toImport) {
|
||||
try {
|
||||
const result = await importBadgeFromRemote({
|
||||
code: badge.code,
|
||||
name: badge.name,
|
||||
description: badge.description,
|
||||
})
|
||||
if (result.ok) {
|
||||
ok++
|
||||
setBadges((prev) =>
|
||||
prev.map((b) => (b.code === badge.code ? { ...b, alreadyImported: true } : b)),
|
||||
)
|
||||
} else {
|
||||
fail++
|
||||
}
|
||||
} catch {
|
||||
fail++
|
||||
}
|
||||
}
|
||||
setBatchImporting(false)
|
||||
setSelected(new Set())
|
||||
if (ok > 0) toast.success(`${ok} badge(s) imported`)
|
||||
if (fail > 0) toast.error(`${fail} failed`)
|
||||
}
|
||||
|
||||
function toggleSelect(code: string) {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(code)) next.delete(code)
|
||||
else next.add(code)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const importableBadges = useMemo(() => badges.filter((b) => !b.alreadyImported), [badges])
|
||||
|
||||
function toggleSelectAll() {
|
||||
if (selected.size === importableBadges.length) {
|
||||
setSelected(new Set())
|
||||
} else {
|
||||
setSelected(new Set(importableBadges.map((b) => b.code)))
|
||||
}
|
||||
}
|
||||
|
||||
// Stats
|
||||
const importedCount = useMemo(() => badges.filter((b) => b.alreadyImported).length, [badges])
|
||||
const currentPage = Math.floor(offset / PAGE_SIZE) + 1
|
||||
|
||||
return (
|
||||
<TooltipProvider delayDuration={300}>
|
||||
<div className="space-y-4">
|
||||
{/* Stats bar */}
|
||||
{badges.length > 0 && (
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<div className="flex items-center gap-1.5 text-sm">
|
||||
<Package className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">{badges.length}</span>
|
||||
<span className="text-muted-foreground">results</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 text-sm">
|
||||
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
|
||||
<span className="font-medium text-emerald-600">{importedCount}</span>
|
||||
<span className="text-muted-foreground">imported</span>
|
||||
</div>
|
||||
{importableBadges.length > 0 && (
|
||||
<div className="flex items-center gap-1.5 text-sm">
|
||||
<Download className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">{importableBadges.length}</span>
|
||||
<span className="text-muted-foreground">available</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search bar */}
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
ref={searchRef}
|
||||
placeholder="Search badges by name... /"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') doSearch()
|
||||
if (e.key === 'Escape') {
|
||||
setSearchTerm('')
|
||||
searchRef.current?.blur()
|
||||
}
|
||||
}}
|
||||
className="pl-9 pr-8"
|
||||
/>
|
||||
{searchTerm && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSearchTerm('')
|
||||
setActiveSearch('')
|
||||
fetchBadges('', 0, allHotels)
|
||||
}}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<Button onClick={doSearch} size="sm" disabled={loading}>
|
||||
{loading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Search className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant={allHotels ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setAllHotels((v) => !v)}
|
||||
>
|
||||
<Globe className="w-4 h-4 mr-1" />
|
||||
{allHotels ? 'All' : 'IT'}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>
|
||||
{allHotels
|
||||
? 'Showing all hotels — click for Italian only'
|
||||
: 'Showing Italian only — click for all hotels'}
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{/* Bulk actions */}
|
||||
{importableBadges.length > 0 && (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={toggleSelectAll}
|
||||
className="text-xs h-8"
|
||||
disabled={batchImporting}
|
||||
>
|
||||
{selected.size === importableBadges.length
|
||||
? 'Deselect All'
|
||||
: `Select All (${importableBadges.length})`}
|
||||
</Button>
|
||||
{selected.size > 0 && (
|
||||
<Button size="sm" className="h-8" onClick={doBatchImport} disabled={batchImporting}>
|
||||
{batchImporting ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
||||
) : (
|
||||
<Download className="w-4 h-4 mr-1" />
|
||||
)}
|
||||
Import {selected.size} selected
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Loading skeleton */}
|
||||
{loading && badges.length === 0 && (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
||||
{Array.from({ length: 18 }).map((_, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: static skeleton placeholders
|
||||
<div key={i} className="rounded-lg border bg-card p-3 animate-pulse">
|
||||
<div className="h-12 w-12 bg-muted rounded mx-auto mb-2" />
|
||||
<div className="h-4 bg-muted rounded w-3/4 mx-auto mb-1" />
|
||||
<div className="h-3 bg-muted rounded w-1/2 mx-auto mb-2" />
|
||||
<div className="h-7 bg-muted rounded" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty state */}
|
||||
{!loading && badges.length === 0 && !error && (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<BadgeCheck className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p className="text-sm">No badges found{activeSearch ? ` for "${activeSearch}"` : ''}</p>
|
||||
{!activeSearch && <p className="text-xs mt-1">Try searching by badge name or code</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Badge grid */}
|
||||
{badges.length > 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
'grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3',
|
||||
loading && 'opacity-50',
|
||||
)}
|
||||
>
|
||||
{badges.map((badge) => {
|
||||
const isSelected = selected.has(badge.code)
|
||||
return (
|
||||
<div
|
||||
key={badge.code}
|
||||
className={cn(
|
||||
'rounded-lg border overflow-hidden bg-card group relative hover:border-border transition-all',
|
||||
badge.alreadyImported && 'shadow-[0_0_6px_rgba(34,197,94,0.15)]',
|
||||
isSelected && 'ring-2 ring-primary border-primary',
|
||||
)}
|
||||
>
|
||||
{/* Checkbox for non-imported */}
|
||||
{!badge.alreadyImported && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleSelect(badge.code)}
|
||||
className={cn(
|
||||
'absolute top-1.5 left-1.5 z-10 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors',
|
||||
isSelected
|
||||
? 'bg-primary border-primary text-primary-foreground'
|
||||
: 'bg-background/80 border-muted-foreground/30 hover:border-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{isSelected && <Check className="w-3 h-3" />}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Badge image area */}
|
||||
<div className="flex items-center justify-center h-20 bg-accent/20">
|
||||
<img
|
||||
src={badge.url_habbo}
|
||||
alt={badge.code}
|
||||
className="image-pixelated drop-shadow-sm"
|
||||
style={{ maxHeight: 48, maxWidth: 48 }}
|
||||
onError={(e) => {
|
||||
const img = e.target as HTMLImageElement
|
||||
if (!img.dataset.fallback) {
|
||||
img.dataset.fallback = '1'
|
||||
img.src = badge.url_habboassets
|
||||
} else {
|
||||
img.style.opacity = '0.3'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="px-2.5 py-2 border-t space-y-1">
|
||||
<div className="text-xs font-bold truncate">{badge.code}</div>
|
||||
{badge.name && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="text-[11px] text-muted-foreground truncate cursor-default">
|
||||
{badge.name}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" className="max-w-64">
|
||||
<p className="font-medium">{badge.name}</p>
|
||||
{badge.description && (
|
||||
<p className="text-muted-foreground text-xs mt-1">
|
||||
{badge.description}
|
||||
</p>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{allHotels && badge.hotel && (
|
||||
<Badge variant="outline" className="text-[9px] px-1 h-4">
|
||||
{badge.hotel.toUpperCase()}
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{/* Action */}
|
||||
<div className="pt-1">
|
||||
{badge.alreadyImported ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<Badge className="text-[10px] px-1.5 py-0 bg-emerald-500/15 text-emerald-500 border-0 gap-0.5 flex-1 justify-center">
|
||||
<Check className="w-2.5 h-2.5" />
|
||||
Imported
|
||||
</Badge>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-5 w-5 p-0 shrink-0"
|
||||
title="Edit badge name/description"
|
||||
onClick={() => setEditingCode(badge.code)}
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="w-full text-xs h-7"
|
||||
onClick={() => doImport(badge)}
|
||||
disabled={importingCode === badge.code || batchImporting}
|
||||
>
|
||||
{importingCode === badge.code ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<Download className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Import
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{(offset > 0 || hasMore) && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Page {currentPage}</span>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={offset <= 0 || loading}
|
||||
onClick={() => goPage('prev')}
|
||||
>
|
||||
← Prev
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!hasMore || loading}
|
||||
onClick={() => goPage('next')}
|
||||
>
|
||||
Next →
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Badge Editor Dialog */}
|
||||
<BadgeEditorDialog
|
||||
code={editingCode ?? ''}
|
||||
open={!!editingCode}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setEditingCode(null)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 347 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user