Add register + logout auth flows, and batch-5 resources

Auth (hand-built, uses the auth core):
- /register + register() action: validates, hashes with argon2id (hashPassword),
  creates an emulator-compatible users row (accountCreated/ipRegister/ipCurrent/
  look), redirect kept outside try so NEXT_REDIRECT propagates. Login/register
  cross-links; header shows Register (logged-out) and a Logout (signOut) button.

Batch 5 (parallel agents): /admin/rooms (+[id]) search+detail, /admin/vouchers
(CRUD), /admin/subscriptions (read), /admin/calendar (campaigns+rewards read),
/marketplace (public). Header + admin nav extended.

Verified: tsc exit 0, vitest 48/48, next build exit 0 (52 page routes).
This commit is contained in:
Simo committed 2026-06-28 13:52:32 +02:00
1 parent e8be0461d8
commit 08a9882be8
13 files changed
+1001 -4

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
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 amount = Number(formData.get("amount"));
const maxUsesRaw = Number(formData.get("maxUses"));
const maxUses = Number.isFinite(maxUsesRaw) && maxUsesRaw > 0 ? Math.floor(maxUsesRaw) : 1;
if (!code || !(amount > 0)) return;
const expiresRaw = String(formData.get("expiresAt") ?? "").trim();
let expiresAt: Date | null = null;
if (expiresRaw) {
const parsed = new Date(expiresRaw);
if (!Number.isNaN(parsed.getTime())) expiresAt = parsed;
}
const now = new Date();
try {
await prisma.websiteShopVouchers.create({
data: {
code,
amount: Math.floor(amount),
maxUses,
useCount: 0,
expiresAt,
createdAt: now,
updatedAt: now,
},
});
} catch {
// Unique constraint on `code` (or DB unavailable) — swallow and re-render.
return;
}
revalidatePath("/admin/vouchers");
}
export async function deleteVoucher(formData: FormData): Promise<void> {
await requireStaff();
const raw = String(formData.get("id") ?? "").trim();
if (!raw) return;
let id: bigint;
try {
id = BigInt(raw);
} catch {
return;
}
try {
await prisma.websiteShopVouchers.delete({ where: { id } });
} catch {
return;
}
revalidatePath("/admin/vouchers");
}
+61
View File
@@ -0,0 +1,61 @@
"use server";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { hashPassword } from "@/lib/auth/password";
import { prisma } from "@/lib/prisma";
const USERNAME_RE = /^[A-Za-z0-9_\-=?!@:.,]{3,25}$/;
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
// A valid starter Habbo figure so the avatar renders in-client immediately.
const DEFAULT_LOOK = "hr-100-.hd-180-1.ch-255-66.lg-280-110.sh-305-62";
export async function register(formData: FormData): Promise<void> {
const username = String(formData.get("username") ?? "").trim();
const mail = String(formData.get("mail") ?? "").trim().toLowerCase();
const password = String(formData.get("password") ?? "");
let error: string | null = null;
if (!USERNAME_RE.test(username)) error = "Username must be 3-25 valid characters";
else if (password.length < 6) error = "Password must be at least 6 characters";
else if (!EMAIL_RE.test(mail)) error = "Enter a valid email address";
// Uniqueness check (kept out of the success path's try so NEXT_REDIRECT propagates).
if (!error) {
try {
const existing = await prisma.user.findUnique({
where: { username },
select: { id: true },
});
if (existing) error = "That username is already taken";
} catch {
error = "Registration is temporarily unavailable";
}
}
if (!error) {
const h = await headers();
const ip =
h.get("x-forwarded-for")?.split(",")[0]?.trim() ?? h.get("x-real-ip") ?? "0.0.0.0";
const now = Math.floor(Date.now() / 1000);
try {
await prisma.user.create({
data: {
username,
password: await hashPassword(password),
mail,
accountCreated: now,
ipRegister: ip,
ipCurrent: ip,
look: DEFAULT_LOOK,
},
});
} catch {
error = "Could not create the account (is the username unique?)";
}
}
// redirect() throws NEXT_REDIRECT — must be OUTSIDE any try/catch.
if (error) redirect(`/register?error=${encodeURIComponent(error)}`);
redirect("/login?registered=1");
}
+168
View File
@@ -0,0 +1,168 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
type Campaign = {
id: number;
name: string;
image: string;
startTimestamp: number;
totalDays: number;
lockExpired: string;
enabled: string;
};
type Reward = {
id: number;
campaignId: number;
productName: string;
customImage: string;
credits: number;
pixels: number;
points: number;
pointsType: number;
badge: string;
itemId: number;
subscriptionType: string | null;
subscriptionDays: number;
};
function fmtDate(ts: number): string {
if (!ts) return "—";
return new Date(ts * 1000).toISOString().slice(0, 10);
}
export default async function AdminCalendarCampaign({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const campaignId = Number(id);
if (!Number.isInteger(campaignId)) notFound();
let campaign: Campaign | null = null;
try {
campaign = await prisma.calendarCampaigns.findUnique({
where: { id: campaignId },
select: {
id: true,
name: true,
image: true,
startTimestamp: true,
totalDays: true,
lockExpired: true,
enabled: true,
},
});
} catch {
campaign = null;
}
if (!campaign) notFound();
let rewards: Reward[] = [];
try {
rewards = await prisma.calendarRewards.findMany({
where: { campaignId },
select: {
id: true,
campaignId: true,
productName: true,
customImage: true,
credits: true,
pixels: true,
points: true,
pointsType: true,
badge: true,
itemId: true,
subscriptionType: true,
subscriptionDays: true,
},
orderBy: { id: "asc" },
take: 500,
});
} catch {
rewards = [];
}
const disabled = campaign.enabled !== "1";
return (
<main>
<p className="muted">
<Link href="/admin/calendar">← Calendar campaigns</Link>
</p>
<div className="card" style={{ display: "flex", gap: "1.25rem", alignItems: "center", marginBottom: "1.5rem" }}>
{campaign.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img
className="avatar"
src={campaign.image}
alt={campaign.name}
style={{ width: 96, height: 96, objectFit: "cover" }}
/>
) : null}
<div>
<h1 style={{ margin: "0 0 0.25rem" }}>{campaign.name || `Campaign #${campaign.id}`}</h1>
<p className="muted" style={{ margin: 0 }}>
#{campaign.id} · {campaign.totalDays} day{campaign.totalDays === 1 ? "" : "s"} · starts{" "}
{fmtDate(campaign.startTimestamp)}
{disabled ? " · Disabled" : " · Enabled"}
{campaign.lockExpired === "1" ? " · Locks expired days" : ""}
</p>
</div>
</div>
<h2 style={{ marginTop: "1.5rem" }}>Rewards</h2>
{rewards.length === 0 ? (
<p className="muted">No rewards configured for this campaign.</p>
) : (
<table style={{ width: "100%", borderCollapse: "collapse" }}>
<thead>
<tr style={{ textAlign: "left", color: "var(--muted)" }}>
<th>ID</th>
<th>Product</th>
<th>Item</th>
<th>Credits</th>
<th>Pixels</th>
<th>Points</th>
<th>Badge</th>
<th>Subscription</th>
</tr>
</thead>
<tbody>
{rewards.map((r) => (
<tr key={r.id} style={{ borderTop: "1px solid var(--border)" }}>
<td>{r.id}</td>
<td>{r.productName || <span className="muted">—</span>}</td>
<td className="muted">{r.itemId > 0 ? r.itemId : "—"}</td>
<td>{r.credits > 0 ? r.credits : <span className="muted">—</span>}</td>
<td>{r.pixels > 0 ? r.pixels : <span className="muted">—</span>}</td>
<td>
{r.points > 0 ? (
`${r.points} (type ${r.pointsType})`
) : (
<span className="muted">—</span>
)}
</td>
<td className="muted">{r.badge || "—"}</td>
<td className="muted">
{r.subscriptionType
? `${r.subscriptionType} · ${r.subscriptionDays}d`
: "—"}
</td>
</tr>
))}
</tbody>
</table>
)}
<p className="muted" style={{ marginTop: "1rem" }}>
{rewards.length} reward{rewards.length === 1 ? "" : "s"}
</p>
</main>
);
}
+99
View File
@@ -0,0 +1,99 @@
import Link from "next/link";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
type Campaign = {
id: number;
name: string;
image: string;
startTimestamp: number;
totalDays: number;
lockExpired: string;
enabled: string;
};
function fmtDate(ts: number): string {
if (!ts) return "—";
return new Date(ts * 1000).toISOString().slice(0, 10);
}
export default async function AdminCalendar() {
let campaigns: Campaign[] = [];
try {
campaigns = await prisma.calendarCampaigns.findMany({
select: {
id: true,
name: true,
image: true,
startTimestamp: true,
totalDays: true,
lockExpired: true,
enabled: true,
},
orderBy: { id: "desc" },
});
} catch {
campaigns = [];
}
// Tally reward counts per campaign in JS (avoid prisma.groupBy).
const rewardCounts = new Map<number, number>();
try {
const rewards = await prisma.calendarRewards.findMany({
select: { campaignId: true },
});
for (const r of rewards) {
rewardCounts.set(r.campaignId, (rewardCounts.get(r.campaignId) ?? 0) + 1);
}
} catch {
// leave map empty on failure
}
return (
<main>
<h1>Calendar campaigns</h1>
<p className="muted" style={{ marginTop: 0 }}>
Read-only · {campaigns.length} campaign{campaigns.length === 1 ? "" : "s"}.
</p>
{campaigns.length === 0 ? (
<p className="muted">No calendar campaigns found.</p>
) : (
<div className="grid cols-3">
{campaigns.map((c) => {
const disabled = c.enabled !== "1";
const count = rewardCounts.get(c.id) ?? 0;
return (
<Link
key={c.id}
href={`/admin/calendar/${c.id}`}
className="card hover article"
style={{ color: "inherit" }}
>
{c.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img className="article-img" src={c.image} alt={c.name} />
) : (
<div className="article-img" />
)}
<div className="body">
<h3 style={{ margin: "0 0 0.35rem" }}>{c.name || `Campaign #${c.id}`}</h3>
<p className="muted" style={{ margin: 0 }}>
#{c.id} · {c.totalDays} day{c.totalDays === 1 ? "" : "s"} · {count} reward
{count === 1 ? "" : "s"}
</p>
<p className="muted" style={{ margin: "0.35rem 0 0" }}>
Starts {fmtDate(c.startTimestamp)}
{disabled ? " · Disabled" : ""}
{c.lockExpired === "1" ? " · Locks expired" : ""}
</p>
</div>
</Link>
);
})}
</div>
)}
</main>
);
}
+4
View File
@@ -16,11 +16,15 @@ export default async function AdminLayout({ children }: { children: ReactNode })
<nav style={{ display: "grid", gap: "0.45rem" }}> <nav style={{ display: "grid", gap: "0.45rem" }}>
<Link href="/admin">Dashboard</Link> <Link href="/admin">Dashboard</Link>
<Link href="/admin/users">Users</Link> <Link href="/admin/users">Users</Link>
<Link href="/admin/rooms">Rooms</Link>
<Link href="/admin/articles">Articles</Link> <Link href="/admin/articles">Articles</Link>
<Link href="/admin/catalog">Catalog</Link> <Link href="/admin/catalog">Catalog</Link>
<Link href="/admin/vouchers">Vouchers</Link>
<Link href="/admin/badges">Badges</Link> <Link href="/admin/badges">Badges</Link>
<Link href="/admin/radio">Radio</Link> <Link href="/admin/radio">Radio</Link>
<Link href="/admin/achievements">Achievements</Link> <Link href="/admin/achievements">Achievements</Link>
<Link href="/admin/subscriptions">Subscriptions</Link>
<Link href="/admin/calendar">Calendar</Link>
<Link href="/admin/rare-values">Rare Values</Link> <Link href="/admin/rare-values">Rare Values</Link>
<Link href="/admin/photos">Photos</Link> <Link href="/admin/photos">Photos</Link>
<Link href="/admin/bans">Bans</Link> <Link href="/admin/bans">Bans</Link>
+76
View File
@@ -0,0 +1,76 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
export default async function AdminRoomDetail({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
// rooms is an emulator-owned table → Int id.
const roomId = Number(id);
if (!Number.isInteger(roomId) || roomId <= 0) notFound();
let room: Awaited<ReturnType<typeof prisma.rooms.findUnique>> = null;
try {
room = await prisma.rooms.findUnique({ where: { id: roomId } });
} catch {
room = null;
}
if (!room) notFound();
const fields: Array<[string, string]> = [
["ID", String(room.id)],
["Name", room.name || "(unnamed)"],
["Description", room.description || "—"],
["Owner", `${room.ownerName || "—"} (#${room.ownerId})`],
["State", room.state],
["Users", `${room.users} / ${room.usersMax}`],
["Category", String(room.category)],
["Score", String(room.score)],
["Model", room.model],
["Guild ID", room.guildId ? String(room.guildId) : "—"],
["Tags", room.tags || "—"],
["Password", room.password ? "yes" : "—"],
["Public", room.isPublic === "1" ? "yes" : "no"],
["Staff picked", room.isStaffPicked === "1" ? "yes" : "no"],
["For sale", room.isForSale === "1" ? "yes" : "no"],
["Trade mode", String(room.tradeMode)],
];
return (
<main>
<p className="muted">
<Link href="/admin/rooms">← Rooms</Link>
</p>
<h1>{room.name || "(unnamed)"}</h1>
<p className="muted">
ID {room.id} · owner {room.ownerName || "—"} · {room.users}/{room.usersMax}{" "}
users · {room.state}
</p>
<div className="card">
<table>
<tbody>
{fields.map(([label, value]) => (
<tr key={label}>
<th style={{ width: "35%", whiteSpace: "nowrap" }}>{label}</th>
<td>{value}</td>
</tr>
))}
</tbody>
</table>
</div>
{room.ownerId ? (
<p className="muted" style={{ marginTop: "1rem" }}>
<Link href={`/admin/users/${room.ownerId}`}>View owner →</Link>
</p>
) : null}
</main>
);
}
+128
View File
@@ -0,0 +1,128 @@
import Link from "next/link";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
const PER_PAGE = 25;
type RoomRow = {
id: number;
name: string;
ownerName: string;
users: number;
usersMax: number;
state: string;
category: number;
};
export default async function AdminRooms({
searchParams,
}: {
searchParams: Promise<{ q?: string; page?: string }>;
}) {
const sp = await searchParams;
const q = (sp.q ?? "").trim();
const page = Math.max(1, Number(sp.page ?? "1") || 1);
// Search matches room name OR owner username (ownerName is denormalised on the
// emulator rooms table, so no join is needed).
const where = q
? { OR: [{ name: { contains: q } }, { ownerName: { contains: q } }] }
: {};
let rooms: RoomRow[] = [];
let total = 0;
try {
[rooms, total] = await Promise.all([
prisma.rooms.findMany({
where,
select: {
id: true,
name: true,
ownerName: true,
users: true,
usersMax: true,
state: true,
category: true,
},
orderBy: { id: "desc" },
skip: (page - 1) * PER_PAGE,
take: PER_PAGE,
}),
prisma.rooms.count({ where }),
]);
} catch {
rooms = [];
total = 0;
}
const pages = Math.max(1, Math.ceil(total / PER_PAGE));
const qs = (p: number) =>
`/admin/rooms?q=${encodeURIComponent(q)}&page=${p}`;
return (
<main>
<h1>Rooms</h1>
<form style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}>
<input name="q" defaultValue={q} placeholder="Search room or owner" />
<button type="submit" className="btn btn-primary">
Search
</button>
</form>
<div className="card" style={{ padding: 0, overflowX: "auto" }}>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Owner</th>
<th>Users</th>
<th>State</th>
<th>Cat</th>
</tr>
</thead>
<tbody>
{rooms.map((r) => (
<tr key={r.id}>
<td>{r.id}</td>
<td>
<Link href={`/admin/rooms/${r.id}`}>{r.name || "(unnamed)"}</Link>
</td>
<td>{r.ownerName || "—"}</td>
<td>
{r.users} / {r.usersMax}
</td>
<td>{r.state}</td>
<td>{r.category}</td>
</tr>
))}
</tbody>
</table>
</div>
{rooms.length === 0 ? (
<p className="muted" style={{ marginTop: "1rem" }}>
No rooms found.
</p>
) : null}
<p className="muted" style={{ marginTop: "1rem" }}>
Page {page} / {pages} · {total} rooms
{page > 1 ? (
<>
{" · "}
<Link href={qs(page - 1)}>← Prev</Link>
</>
) : null}
{page < pages ? (
<>
{" · "}
<Link href={qs(page + 1)}>Next →</Link>
</>
) : null}
</p>
</main>
);
}
+74
View File
@@ -0,0 +1,74 @@
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
type SubRow = {
id: number;
userId: number | null;
subscriptionType: string | null;
expiresAt: number;
};
function fmt(ts: number): string {
return new Date(ts * 1000).toISOString().slice(0, 16).replace("T", " ");
}
export default async function AdminSubscriptions() {
const now = Math.floor(Date.now() / 1000);
let active: SubRow[] = [];
try {
// Schema has no timestamp_end column; expiry = timestamp_start + duration.
// Active subs are active=1 with a computed expiry still in the future.
const rows = await prisma.usersSubscriptions.findMany({
where: { active: 1 },
orderBy: { id: "desc" },
take: 500,
});
active = rows
.map((r) => ({
id: r.id,
userId: r.userId,
subscriptionType: r.subscriptionType,
expiresAt: (r.timestampStart ?? 0) + (r.duration ?? 0),
}))
.filter((r) => r.expiresAt > now)
.sort((a, b) => a.expiresAt - b.expiresAt);
} catch {
active = [];
}
return (
<main>
<h1>Subscriptions</h1>
<p className="muted" style={{ marginTop: "-0.25rem", marginBottom: "1rem" }}>
Active Habbo Club / VIP subscriptions (expiry &gt; now). Read-only.
</p>
<div className="card">
<table>
<thead>
<tr>
<th>Sub ID</th>
<th>User ID</th>
<th>Type</th>
<th>Expires</th>
</tr>
</thead>
<tbody>
{active.map((s) => (
<tr key={s.id}>
<td>{s.id}</td>
<td>{s.userId ?? "—"}</td>
<td>{s.subscriptionType ?? "—"}</td>
<td className="muted">{fmt(s.expiresAt)}</td>
</tr>
))}
</tbody>
</table>
{active.length === 0 ? <p className="muted">No active subscriptions.</p> : null}
</div>
</main>
);
}
+123
View File
@@ -0,0 +1,123 @@
import { createVoucher, deleteVoucher } from "@/actions/admin-vouchers";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
type VoucherRow = {
id: bigint;
code: string;
amount: number;
maxUses: number;
useCount: number;
expiresAt: Date | null;
createdAt: Date | null;
};
function fmtDate(d: Date | null): string {
if (!d) return "—";
return d.toISOString().slice(0, 16).replace("T", " ");
}
export default async function AdminVouchers() {
const now = Date.now();
let vouchers: VoucherRow[] = [];
try {
vouchers = await prisma.websiteShopVouchers.findMany({
select: {
id: true,
code: true,
amount: true,
maxUses: true,
useCount: true,
expiresAt: true,
createdAt: true,
},
orderBy: { id: "desc" },
take: 200,
});
} catch {
vouchers = [];
}
return (
<main>
<h1>Shop Vouchers</h1>
<p className="muted">
Codes redeemable on the website shop for a balance top-up. Each user can
use a given voucher once, up to its max uses.
</p>
<form action={createVoucher} className="card" style={{ marginBottom: "1.5rem" }}>
<h3 style={{ marginTop: 0 }}>New voucher</h3>
<div className="grid cols-2" style={{ marginBottom: "0.75rem" }}>
<label style={{ display: "flex", flexDirection: "column", gap: "0.3rem" }}>
<span className="muted">Code</span>
<input name="code" placeholder="SUMMER2026" maxLength={255} required />
</label>
<label style={{ display: "flex", flexDirection: "column", gap: "0.3rem" }}>
<span className="muted">Amount (balance added)</span>
<input name="amount" type="number" min={1} placeholder="50" required />
</label>
<label style={{ display: "flex", flexDirection: "column", gap: "0.3rem" }}>
<span className="muted">Max uses</span>
<input name="maxUses" type="number" min={1} defaultValue={1} required />
</label>
<label style={{ display: "flex", flexDirection: "column", gap: "0.3rem" }}>
<span className="muted">Expires at (optional)</span>
<input name="expiresAt" type="datetime-local" />
</label>
</div>
<button type="submit" className="btn btn-primary">Create voucher</button>
</form>
<div className="card">
<table>
<thead>
<tr>
<th>Code</th>
<th>Amount</th>
<th>Uses</th>
<th>Expires</th>
<th>Created</th>
<th />
</tr>
</thead>
<tbody>
{vouchers.map((v) => {
const expired = v.expiresAt ? v.expiresAt.getTime() <= now : false;
const usedUp = v.maxUses > 0 && v.useCount >= v.maxUses;
return (
<tr key={v.id.toString()}>
<td>
<code>{v.code}</code>
{expired ? (
<span className="muted"> · expired</span>
) : usedUp ? (
<span className="muted"> · used up</span>
) : null}
</td>
<td>{v.amount}</td>
<td>
{v.useCount} / {v.maxUses}
</td>
<td className="muted">{fmtDate(v.expiresAt)}</td>
<td className="muted">{fmtDate(v.createdAt)}</td>
<td>
<form action={deleteVoucher}>
<input type="hidden" name="id" value={v.id.toString()} />
<button type="submit" className="btn btn-danger">
Delete
</button>
</form>
</td>
</tr>
);
})}
</tbody>
</table>
{vouchers.length === 0 ? <p className="muted">No vouchers yet.</p> : null}
</div>
</main>
);
}
+4
View File
@@ -1,5 +1,6 @@
"use client"; "use client";
import Link from "next/link";
import { signIn } from "next-auth/react"; import { signIn } from "next-auth/react";
import { type FormEvent, useState } from "react"; import { type FormEvent, useState } from "react";
@@ -50,6 +51,9 @@ export default function LoginPage() {
{error ? ( {error ? (
<p style={{ color: "var(--color-danger)", textAlign: "center", marginBottom: 0 }}>{error}</p> <p style={{ color: "var(--color-danger)", textAlign: "center", marginBottom: 0 }}>{error}</p>
) : null} ) : null}
<p className="muted" style={{ textAlign: "center", marginBottom: 0, marginTop: "1rem" }}>
No account? <Link href="/register">Create one</Link>
</p>
</div> </div>
</main> </main>
); );
+133
View File
@@ -0,0 +1,133 @@
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
// state == 1 → an active, unsold offer in the Arcturus marketplace.
const STATE_ACTIVE = 1;
function listedAgo(ts: number): string {
const now = Math.floor(Date.now() / 1000);
const diff = Math.max(0, now - ts);
if (diff < 60) return "just now";
const mins = Math.floor(diff / 60);
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
function listedAt(ts: number): string {
return new Date(ts * 1000).toISOString().slice(0, 16).replace("T", " ");
}
export default async function MarketplacePage() {
let offers: {
id: number;
itemId: number;
userId: number;
price: number;
timestamp: number;
}[] = [];
try {
offers = await prisma.marketplaceItems.findMany({
where: { state: STATE_ACTIVE },
select: { id: true, itemId: true, userId: true, price: true, timestamp: true },
orderBy: { timestamp: "desc" },
take: 100,
});
} catch {
offers = [];
}
// Resolve seller usernames in a single query (read-only display join).
let sellers = new Map<number, string>();
try {
const ids = [...new Set(offers.map((o) => o.userId))];
if (ids.length > 0) {
const users = await prisma.user.findMany({
where: { id: { in: ids } },
select: { id: true, username: true },
});
sellers = new Map(users.map((u) => [u.id, u.username]));
}
} catch {
sellers = new Map();
}
const total = offers.reduce((sum, o) => sum + o.price, 0);
return (
<main>
<section className="hero">
<h1 style={{ marginTop: 0 }}>Marketplace</h1>
<p className="muted" style={{ marginBottom: 0 }}>
Browse furniture and rares listed by players. Listings are placed in-game
and update live &mdash; head into the hotel to make an offer.
</p>
</section>
<div className="grid cols-3" style={{ marginBottom: "1.5rem" }}>
<div className="card">
<p className="muted" style={{ margin: 0 }}>
Active offers
</p>
<p style={{ fontSize: "1.6rem", fontWeight: 800, margin: "0.15rem 0 0" }}>
{offers.length}
</p>
</div>
<div className="card">
<p className="muted" style={{ margin: 0 }}>
Sellers
</p>
<p style={{ fontSize: "1.6rem", fontWeight: 800, margin: "0.15rem 0 0" }}>
{new Set(offers.map((o) => o.userId)).size}
</p>
</div>
<div className="card">
<p className="muted" style={{ margin: 0 }}>
Total value
</p>
<p style={{ fontSize: "1.6rem", fontWeight: 800, margin: "0.15rem 0 0" }}>
{total.toLocaleString()} cr
</p>
</div>
</div>
{offers.length === 0 ? (
<div className="card">
<p className="muted" style={{ margin: 0 }}>
There are no active marketplace offers right now. Check back later.
</p>
</div>
) : (
<div className="card" style={{ padding: "0.5rem 1.25rem 0.75rem" }}>
<table>
<thead>
<tr>
<th>Offer</th>
<th>Item</th>
<th>Seller</th>
<th>Price</th>
<th>Listed</th>
</tr>
</thead>
<tbody>
{offers.map((o) => (
<tr key={o.id}>
<td className="muted">#{o.id}</td>
<td>Item #{o.itemId}</td>
<td>{sellers.get(o.userId) ?? `User #${o.userId}`}</td>
<td style={{ fontWeight: 700 }}>{o.price.toLocaleString()} cr</td>
<td className="muted" title={listedAt(o.timestamp)}>
{listedAgo(o.timestamp)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</main>
);
}
+43
View File
@@ -0,0 +1,43 @@
import Link from "next/link";
import { register } from "@/actions/register";
export default async function RegisterPage({
searchParams,
}: {
searchParams: Promise<{ error?: string }>;
}) {
const { error } = await searchParams;
return (
<main style={{ maxWidth: 400, margin: "2rem auto" }}>
<div className="card" style={{ padding: "1.75rem" }}>
<h1 style={{ marginTop: 0, textAlign: "center" }}>Create account</h1>
<p className="muted" style={{ textAlign: "center", marginTop: 0 }}>
Join the hotel — it only takes a moment.
</p>
<form action={register} style={{ display: "grid", gap: "0.7rem", marginTop: "1rem" }}>
<input name="username" placeholder="Username" autoComplete="username" required />
<input name="mail" type="email" placeholder="Email" autoComplete="email" required />
<input
name="password"
type="password"
placeholder="Password (min 6 chars)"
autoComplete="new-password"
required
/>
<button type="submit" className="btn btn-primary">
Register
</button>
</form>
{error ? (
<p style={{ color: "var(--color-danger)", textAlign: "center", marginBottom: 0 }}>
{error}
</p>
) : null}
<p className="muted" style={{ textAlign: "center", marginBottom: 0, marginTop: "1rem" }}>
Already have an account? <Link href="/login">Sign in</Link>
</p>
</div>
</main>
);
}
+22 -4
View File
@@ -1,5 +1,5 @@
import Link from "next/link"; import Link from "next/link";
import { auth } from "@/lib/auth"; import { auth, signOut } from "@/lib/auth";
import { prisma } from "@/lib/prisma"; import { prisma } from "@/lib/prisma";
import { siteSettings } from "@/lib/services/site-settings"; import { siteSettings } from "@/lib/services/site-settings";
@@ -48,6 +48,9 @@ export async function SiteHeader() {
<Link className="nav-item" href="/shop"> <Link className="nav-item" href="/shop">
Shop Shop
</Link> </Link>
<Link className="nav-item" href="/marketplace">
Market
</Link>
<Link className="nav-item" href="/community"> <Link className="nav-item" href="/community">
Community Community
</Link> </Link>
@@ -103,11 +106,26 @@ export async function SiteHeader() {
<Link className="nav-item" href={`/u/${session.user.name}`}> <Link className="nav-item" href={`/u/${session.user.name}`}>
{session.user.name} {session.user.name}
</Link> </Link>
<form
action={async () => {
"use server";
await signOut({ redirectTo: "/" });
}}
>
<button type="submit" className="btn btn-outline">
Logout
</button>
</form>
</> </>
) : ( ) : (
<Link className="btn btn-outline" href="/login"> <>
Login <Link className="nav-item" href="/register">
</Link> Register
</Link>
<Link className="btn btn-outline" href="/login">
Login
</Link>
</>
)} )}
</div> </div>
</header> </header>