This commit is contained in:
1 parent
8efd032cc6
commit
df38dccbf1
735 files changed
+128321
-120870
No files matched your search
+222
-205
@@ -1,5 +1,5 @@
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import Link from "next/link";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||
import { excerpt } from "@/lib/format";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
@@ -11,228 +11,245 @@ export const metadata = { title: "Shop" };
|
||||
// Faithful to AtomCMS WebsiteShopArticle::price(): costs are stored in cents,
|
||||
// the displayed price is costs/100 with a floor of 1.
|
||||
function priceLabel(costs: number): string {
|
||||
const price = costs < 100 ? 1 : costs / 100;
|
||||
return `$${price.toFixed(2)}`;
|
||||
const price = costs < 100 ? 1 : costs / 100;
|
||||
return `$${price.toFixed(2)}`;
|
||||
}
|
||||
|
||||
type ShopArticle = {
|
||||
id: bigint;
|
||||
name: string;
|
||||
info: string;
|
||||
iconUrl: string;
|
||||
color: string;
|
||||
costs: number;
|
||||
credits: number | null;
|
||||
duckets: number | null;
|
||||
diamonds: number | null;
|
||||
badges: string | null;
|
||||
position: number;
|
||||
id: bigint;
|
||||
name: string;
|
||||
info: string;
|
||||
iconUrl: string;
|
||||
color: string;
|
||||
costs: number;
|
||||
credits: number | null;
|
||||
duckets: number | null;
|
||||
diamonds: number | null;
|
||||
badges: string | null;
|
||||
position: number;
|
||||
};
|
||||
|
||||
type ShopCategory = {
|
||||
id: bigint;
|
||||
name: string;
|
||||
icon: string | null;
|
||||
id: bigint;
|
||||
name: string;
|
||||
icon: string | null;
|
||||
};
|
||||
|
||||
const ARTICLE_SELECT = {
|
||||
id: true,
|
||||
name: true,
|
||||
info: true,
|
||||
iconUrl: true,
|
||||
color: true,
|
||||
costs: true,
|
||||
credits: true,
|
||||
duckets: true,
|
||||
diamonds: true,
|
||||
badges: true,
|
||||
position: true,
|
||||
id: true,
|
||||
name: true,
|
||||
info: true,
|
||||
iconUrl: true,
|
||||
color: true,
|
||||
costs: true,
|
||||
credits: true,
|
||||
duckets: true,
|
||||
diamonds: true,
|
||||
badges: true,
|
||||
position: true,
|
||||
} as const;
|
||||
|
||||
export default async function ShopPage({ searchParams }: { searchParams: Promise<{ category?: string }> }) {
|
||||
const t = await getTranslations("pages.shop");
|
||||
const sp = await searchParams;
|
||||
const rawCategory = (sp.category ?? "").trim();
|
||||
const categoryId = /^\d+$/.test(rawCategory) ? rawCategory : "";
|
||||
export default async function ShopPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ category?: string }>;
|
||||
}) {
|
||||
const t = await getTranslations("pages.shop");
|
||||
const sp = await searchParams;
|
||||
const rawCategory = (sp.category ?? "").trim();
|
||||
const categoryId = /^\d+$/.test(rawCategory) ? rawCategory : "";
|
||||
|
||||
// Categories for the filter bar.
|
||||
let categories: ShopCategory[] = [];
|
||||
try {
|
||||
categories = await prisma.websiteShopCategories.findMany({
|
||||
select: { id: true, name: true, icon: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
} catch {
|
||||
categories = [];
|
||||
}
|
||||
// Categories for the filter bar.
|
||||
let categories: ShopCategory[] = [];
|
||||
try {
|
||||
categories = await prisma.websiteShopCategories.findMany({
|
||||
select: { id: true, name: true, icon: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
} catch {
|
||||
categories = [];
|
||||
}
|
||||
|
||||
// Articles. The category foreign key (website_shop_category_id) is not modelled
|
||||
// in the typed Prisma client, so when filtering we resolve the matching ids via
|
||||
// a guarded raw query, then load the rows through the typed client.
|
||||
let articles: ShopArticle[] = [];
|
||||
try {
|
||||
if (categoryId) {
|
||||
let ids: bigint[] = [];
|
||||
try {
|
||||
const rows = await prisma.$queryRawUnsafe<{ id: bigint }[]>(
|
||||
"SELECT id FROM website_shop_articles WHERE website_shop_category_id = ?",
|
||||
BigInt(categoryId),
|
||||
);
|
||||
ids = rows.map((r) => r.id);
|
||||
} catch {
|
||||
ids = [];
|
||||
}
|
||||
// Articles. The category foreign key (website_shop_category_id) is not modelled
|
||||
// in the typed Prisma client, so when filtering we resolve the matching ids via
|
||||
// a guarded raw query, then load the rows through the typed client.
|
||||
let articles: ShopArticle[] = [];
|
||||
try {
|
||||
if (categoryId) {
|
||||
let ids: bigint[] = [];
|
||||
try {
|
||||
const rows = await prisma.$queryRawUnsafe<{ id: bigint }[]>(
|
||||
"SELECT id FROM website_shop_articles WHERE website_shop_category_id = ?",
|
||||
BigInt(categoryId),
|
||||
);
|
||||
ids = rows.map((r) => r.id);
|
||||
} catch {
|
||||
ids = [];
|
||||
}
|
||||
|
||||
articles = ids.length
|
||||
? await prisma.websiteShopArticles.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: ARTICLE_SELECT,
|
||||
orderBy: { position: "asc" },
|
||||
})
|
||||
: [];
|
||||
} else {
|
||||
articles = await prisma.websiteShopArticles.findMany({
|
||||
select: ARTICLE_SELECT,
|
||||
orderBy: { position: "asc" },
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
articles = [];
|
||||
}
|
||||
articles = ids.length
|
||||
? await prisma.websiteShopArticles.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: ARTICLE_SELECT,
|
||||
orderBy: { position: "asc" },
|
||||
})
|
||||
: [];
|
||||
} else {
|
||||
articles = await prisma.websiteShopArticles.findMany({
|
||||
select: ARTICLE_SELECT,
|
||||
orderBy: { position: "asc" },
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
articles = [];
|
||||
}
|
||||
|
||||
const activeCategory = categoryId ? categories.find((c) => String(c.id) === categoryId) : undefined;
|
||||
const activeCategory = categoryId
|
||||
? categories.find((c) => String(c.id) === categoryId)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<main style={{ display: "grid", gap: "1.5rem" }}>
|
||||
<ContentCard
|
||||
icon="🛒"
|
||||
title={t("title")}
|
||||
subtitle={activeCategory ? t("browsingCategory", { category: activeCategory.name }) : t("subtitle")}
|
||||
>
|
||||
{categories.length > 0 ? (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<Link href="/shop" className={`btn ${categoryId ? "btn-outline" : "btn-primary"}`}>
|
||||
{t("all")}
|
||||
</Link>
|
||||
{categories.map((c) => (
|
||||
<Link
|
||||
key={String(c.id)}
|
||||
href={`/shop?category=${String(c.id)}`}
|
||||
className={`btn ${categoryId === String(c.id) ? "btn-primary" : "btn-outline"}`}
|
||||
>
|
||||
{c.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</ContentCard>
|
||||
return (
|
||||
<main style={{ display: "grid", gap: "1.5rem" }}>
|
||||
<ContentCard
|
||||
icon="🛒"
|
||||
title={t("title")}
|
||||
subtitle={
|
||||
activeCategory
|
||||
? t("browsingCategory", { category: activeCategory.name })
|
||||
: t("subtitle")
|
||||
}
|
||||
>
|
||||
{categories.length > 0 ? (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<Link
|
||||
href="/shop"
|
||||
className={`btn ${categoryId ? "btn-outline" : "btn-primary"}`}
|
||||
>
|
||||
{t("all")}
|
||||
</Link>
|
||||
{categories.map((c) => (
|
||||
<Link
|
||||
key={String(c.id)}
|
||||
href={`/shop?category=${String(c.id)}`}
|
||||
className={`btn ${categoryId === String(c.id) ? "btn-primary" : "btn-outline"}`}
|
||||
>
|
||||
{c.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</ContentCard>
|
||||
|
||||
<ContentCard
|
||||
icon="📦"
|
||||
title={activeCategory ? activeCategory.name : t("allPackages")}
|
||||
subtitle={articles.length > 0 ? t("packagesAvailable", { count: articles.length }) : undefined}
|
||||
padded={articles.length === 0}
|
||||
>
|
||||
{articles.length === 0 ? (
|
||||
<EmptyState icon="🛒">{t("empty")}</EmptyState>
|
||||
) : (
|
||||
<div className="card-grid sm-2 lg-3" style={{ padding: "1rem" }}>
|
||||
{articles.map((a) => (
|
||||
<article key={String(a.id)} className="card hover">
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.75rem",
|
||||
marginBottom: "0.6rem",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 56,
|
||||
height: 56,
|
||||
borderRadius: "var(--radius-sm)",
|
||||
display: "grid",
|
||||
placeItems: "center",
|
||||
background: "#f8fafc",
|
||||
border: `2px solid ${a.color || "var(--border-color)"}`,
|
||||
flexShrink: 0,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
{a.iconUrl ? (
|
||||
// Article icons are arbitrary external/Imgur URLs from the
|
||||
// emulator data, so a plain <img> is correct here.
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={a.iconUrl}
|
||||
alt=""
|
||||
width={48}
|
||||
height={48}
|
||||
style={{ objectFit: "contain", display: "block" }}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<h3 style={{ margin: 0 }}>{a.name}</h3>
|
||||
<span className="muted">{priceLabel(a.costs)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<ContentCard
|
||||
icon="📦"
|
||||
title={activeCategory ? activeCategory.name : t("allPackages")}
|
||||
subtitle={
|
||||
articles.length > 0
|
||||
? t("packagesAvailable", { count: articles.length })
|
||||
: undefined
|
||||
}
|
||||
padded={articles.length === 0}
|
||||
>
|
||||
{articles.length === 0 ? (
|
||||
<EmptyState icon="🛒">{t("empty")}</EmptyState>
|
||||
) : (
|
||||
<div className="card-grid sm-2 lg-3" style={{ padding: "1rem" }}>
|
||||
{articles.map((a) => (
|
||||
<article key={String(a.id)} className="card hover">
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.75rem",
|
||||
marginBottom: "0.6rem",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 56,
|
||||
height: 56,
|
||||
borderRadius: "var(--radius-sm)",
|
||||
display: "grid",
|
||||
placeItems: "center",
|
||||
background: "#f8fafc",
|
||||
border: `2px solid ${a.color || "var(--border-color)"}`,
|
||||
flexShrink: 0,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
{a.iconUrl ? (
|
||||
// Article icons are arbitrary external/Imgur URLs from the
|
||||
// emulator data, so a plain <img> is correct here.
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={a.iconUrl}
|
||||
alt=""
|
||||
width={48}
|
||||
height={48}
|
||||
style={{ objectFit: "contain", display: "block" }}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<h3 style={{ margin: 0 }}>{a.name}</h3>
|
||||
<span className="muted">{priceLabel(a.costs)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p style={{ margin: "0 0 0.75rem" }}>{excerpt(a.info, 160)}</p>
|
||||
<p style={{ margin: "0 0 0.75rem" }}>{excerpt(a.info, 160)}</p>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "0.4rem",
|
||||
marginBottom: "0.85rem",
|
||||
}}
|
||||
>
|
||||
{a.credits ? (
|
||||
<span className="currency">
|
||||
<span className="coin credits">cr</span>
|
||||
{a.credits.toLocaleString()}
|
||||
</span>
|
||||
) : null}
|
||||
{a.duckets ? (
|
||||
<span className="currency">
|
||||
<span className="coin duckets">du</span>
|
||||
{a.duckets.toLocaleString()}
|
||||
</span>
|
||||
) : null}
|
||||
{a.diamonds ? (
|
||||
<span className="currency">
|
||||
<span className="coin diamonds">di</span>
|
||||
{a.diamonds.toLocaleString()}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "0.4rem",
|
||||
marginBottom: "0.85rem",
|
||||
}}
|
||||
>
|
||||
{a.credits ? (
|
||||
<span className="currency">
|
||||
<span className="coin credits">cr</span>
|
||||
{a.credits.toLocaleString()}
|
||||
</span>
|
||||
) : null}
|
||||
{a.duckets ? (
|
||||
<span className="currency">
|
||||
<span className="coin duckets">du</span>
|
||||
{a.duckets.toLocaleString()}
|
||||
</span>
|
||||
) : null}
|
||||
{a.diamonds ? (
|
||||
<span className="currency">
|
||||
<span className="coin diamonds">di</span>
|
||||
{a.diamonds.toLocaleString()}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<span style={{ fontWeight: 800 }}>{priceLabel(a.costs)}</span>
|
||||
<span className="btn btn-primary" aria-disabled="true">
|
||||
{t("buy")}
|
||||
</span>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ContentCard>
|
||||
</main>
|
||||
);
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<span style={{ fontWeight: 800 }}>{priceLabel(a.costs)}</span>
|
||||
<span className="btn btn-primary" aria-disabled="true">
|
||||
{t("buy")}
|
||||
</span>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ContentCard>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+164
-144
@@ -8,159 +8,179 @@ import { useState } from "react";
|
||||
* /shop/topup?token=<orderId>&status=success, it captures via /api/paypal/capture.
|
||||
*/
|
||||
export default function TopUpForm({
|
||||
currency,
|
||||
creditsPerUnit,
|
||||
currency,
|
||||
creditsPerUnit,
|
||||
}: {
|
||||
currency: string;
|
||||
creditsPerUnit: number;
|
||||
currency: string;
|
||||
creditsPerUnit: number;
|
||||
}) {
|
||||
const [amount, setAmount] = useState("5.00");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
const [amount, setAmount] = useState("5.00");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
|
||||
const numeric = Number(amount);
|
||||
const credits = Number.isFinite(numeric) && numeric > 0 ? Math.floor(numeric * creditsPerUnit) : 0;
|
||||
const numeric = Number(amount);
|
||||
const credits =
|
||||
Number.isFinite(numeric) && numeric > 0
|
||||
? Math.floor(numeric * creditsPerUnit)
|
||||
: 0;
|
||||
|
||||
async function startCheckout(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setPending(true);
|
||||
try {
|
||||
const res = await fetch("/api/paypal/create", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ amount: numeric }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
approveUrl?: string;
|
||||
error?: string;
|
||||
};
|
||||
if (!res.ok || !data.approveUrl) {
|
||||
setError(data.error ?? "Could not start the PayPal checkout.");
|
||||
setPending(false);
|
||||
return;
|
||||
}
|
||||
// Hand off to PayPal for approval.
|
||||
const redirectUrl = new URL(data.approveUrl);
|
||||
if (redirectUrl.protocol !== "https:") {
|
||||
throw new Error("Invalid redirect URL: must be HTTPS");
|
||||
}
|
||||
if (!redirectUrl.hostname.endsWith(".paypal.com") && redirectUrl.hostname !== "paypal.com") {
|
||||
throw new Error("Invalid redirect URL: must be a PayPal domain");
|
||||
}
|
||||
window.location.href = redirectUrl.href;
|
||||
} catch {
|
||||
setError("Network error — please try again.");
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
async function startCheckout(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setPending(true);
|
||||
try {
|
||||
const res = await fetch("/api/paypal/create", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ amount: numeric }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
approveUrl?: string;
|
||||
error?: string;
|
||||
};
|
||||
if (!res.ok || !data.approveUrl) {
|
||||
setError(data.error ?? "Could not start the PayPal checkout.");
|
||||
setPending(false);
|
||||
return;
|
||||
}
|
||||
// Hand off to PayPal for approval.
|
||||
const redirectUrl = new URL(data.approveUrl);
|
||||
if (redirectUrl.protocol !== "https:") {
|
||||
throw new Error("Invalid redirect URL: must be HTTPS");
|
||||
}
|
||||
if (
|
||||
!redirectUrl.hostname.endsWith(".paypal.com") &&
|
||||
redirectUrl.hostname !== "paypal.com"
|
||||
) {
|
||||
throw new Error("Invalid redirect URL: must be a PayPal domain");
|
||||
}
|
||||
window.location.href = redirectUrl.href;
|
||||
} catch {
|
||||
setError("Network error — please try again.");
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function capture(orderId: string) {
|
||||
setPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/paypal/capture", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ orderId }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
ok?: boolean;
|
||||
credits?: number;
|
||||
error?: string;
|
||||
};
|
||||
if (res.ok && data.ok) {
|
||||
setSuccess(`Payment complete! ${(data.credits ?? 0).toLocaleString()} credits were added.`);
|
||||
} else {
|
||||
setError(data.error ?? "We couldn't confirm your payment. Contact staff if charged.");
|
||||
}
|
||||
} catch {
|
||||
setError("Network error confirming payment — contact staff if you were charged.");
|
||||
} finally {
|
||||
setPending(false);
|
||||
// Clean the token/status query so a refresh doesn't re-capture.
|
||||
window.history.replaceState(null, "", "/shop/topup");
|
||||
}
|
||||
}
|
||||
async function capture(orderId: string) {
|
||||
setPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/paypal/capture", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ orderId }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
ok?: boolean;
|
||||
credits?: number;
|
||||
error?: string;
|
||||
};
|
||||
if (res.ok && data.ok) {
|
||||
setSuccess(
|
||||
`Payment complete! ${(data.credits ?? 0).toLocaleString()} credits were added.`,
|
||||
);
|
||||
} else {
|
||||
setError(
|
||||
data.error ??
|
||||
"We couldn't confirm your payment. Contact staff if charged.",
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
setError(
|
||||
"Network error confirming payment — contact staff if you were charged.",
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
// Clean the token/status query so a refresh doesn't re-capture.
|
||||
window.history.replaceState(null, "", "/shop/topup");
|
||||
}
|
||||
}
|
||||
|
||||
// On return from PayPal (?token=<orderId>&status=success), auto-capture once.
|
||||
if (typeof window !== "undefined" && !pending && !success) {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const token = params.get("token");
|
||||
if (token && params.get("status") === "success") {
|
||||
// Defer to avoid setState during render.
|
||||
queueMicrotask(() => capture(token));
|
||||
}
|
||||
}
|
||||
// On return from PayPal (?token=<orderId>&status=success), auto-capture once.
|
||||
if (typeof window !== "undefined" && !pending && !success) {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const token = params.get("token");
|
||||
if (token && params.get("status") === "success") {
|
||||
// Defer to avoid setState during render.
|
||||
queueMicrotask(() => capture(token));
|
||||
}
|
||||
}
|
||||
|
||||
if (success) {
|
||||
return (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
style={{ margin: 0, fontWeight: 700, color: "var(--color-accent)" }}
|
||||
>
|
||||
{success}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (success) {
|
||||
return (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
style={{ margin: 0, fontWeight: 700, color: "var(--color-accent)" }}
|
||||
>
|
||||
{success}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={startCheckout} style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
|
||||
<label htmlFor="amount" style={{ fontWeight: 700 }}>
|
||||
Amount ({currency})
|
||||
</label>
|
||||
<input
|
||||
id="amount"
|
||||
name="amount"
|
||||
type="number"
|
||||
min={1}
|
||||
max={500}
|
||||
step={0.01}
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
aria-label={`Amount in ${currency}`}
|
||||
required
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "0.4rem",
|
||||
}}
|
||||
>
|
||||
{["2.00", "5.00", "10.00", "25.00"].map((v) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
className={`btn ${amount === v ? "btn-primary" : "btn-outline"}`}
|
||||
onClick={() => setAmount(v)}
|
||||
>
|
||||
{currency} {v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
return (
|
||||
<form
|
||||
onSubmit={startCheckout}
|
||||
style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}
|
||||
>
|
||||
<label htmlFor="amount" style={{ fontWeight: 700 }}>
|
||||
Amount ({currency})
|
||||
</label>
|
||||
<input
|
||||
id="amount"
|
||||
name="amount"
|
||||
type="number"
|
||||
min={1}
|
||||
max={500}
|
||||
step={0.01}
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
aria-label={`Amount in ${currency}`}
|
||||
required
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "0.4rem",
|
||||
}}
|
||||
>
|
||||
{["2.00", "5.00", "10.00", "25.00"].map((v) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
className={`btn ${amount === v ? "btn-primary" : "btn-outline"}`}
|
||||
onClick={() => setAmount(v)}
|
||||
>
|
||||
{currency} {v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="muted" style={{ margin: 0 }}>
|
||||
You'll receive <strong>{credits.toLocaleString()}</strong> credits.
|
||||
</p>
|
||||
<p className="muted" style={{ margin: 0 }}>
|
||||
You'll receive <strong>{credits.toLocaleString()}</strong> credits.
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<button type="submit" className="btn btn-primary" disabled={pending || credits <= 0}>
|
||||
{pending ? "Redirecting…" : "Pay with PayPal"}
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary"
|
||||
disabled={pending || credits <= 0}
|
||||
>
|
||||
{pending ? "Redirecting…" : "Pay with PayPal"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
style={{ margin: 0, fontWeight: 700, color: "var(--color-danger)" }}
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
);
|
||||
{error ? (
|
||||
<p
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
style={{ margin: 0, fontWeight: 700, color: "var(--color-danger)" }}
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
+81
-65
@@ -1,80 +1,96 @@
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { redirect } from "next/navigation";
|
||||
import TopUpForm from "./TopUpForm";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { ContentCard, StatBlock } from "@/components/public/ui";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { creditsPerUnit, isPayPalConfigured, PAYPAL_CURRENCY } from "@/lib/services/paypal";
|
||||
import {
|
||||
creditsPerUnit,
|
||||
isPayPalConfigured,
|
||||
PAYPAL_CURRENCY,
|
||||
} from "@/lib/services/paypal";
|
||||
import TopUpForm from "./TopUpForm";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function TopUpPage({ searchParams }: { searchParams: Promise<{ status?: string }> }) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
export default async function TopUpPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ status?: string }>;
|
||||
}) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const t = await getTranslations("pages.topup");
|
||||
const sp = await searchParams;
|
||||
const id = Number(session.user.id);
|
||||
const t = await getTranslations("pages.topup");
|
||||
const sp = await searchParams;
|
||||
const id = Number(session.user.id);
|
||||
|
||||
// Current credits balance for context (fail soft).
|
||||
let user: { username: string; credits: number } | null = null;
|
||||
try {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: { username: true, credits: true },
|
||||
});
|
||||
} catch {
|
||||
user = null;
|
||||
}
|
||||
if (!user) redirect("/login");
|
||||
// Current credits balance for context (fail soft).
|
||||
let user: { username: string; credits: number } | null = null;
|
||||
try {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: { username: true, credits: true },
|
||||
});
|
||||
} catch {
|
||||
user = null;
|
||||
}
|
||||
if (!user) redirect("/login");
|
||||
|
||||
const configured = isPayPalConfigured();
|
||||
const rate = creditsPerUnit();
|
||||
const configured = isPayPalConfigured();
|
||||
const rate = creditsPerUnit();
|
||||
|
||||
return (
|
||||
<main style={{ display: "grid", gap: "1.5rem" }}>
|
||||
<ContentCard icon="💳" title={t("title")} subtitle={t("subtitle")} />
|
||||
return (
|
||||
<main style={{ display: "grid", gap: "1.5rem" }}>
|
||||
<ContentCard icon="💳" title={t("title")} subtitle={t("subtitle")} />
|
||||
|
||||
{sp.status === "cancel" ? (
|
||||
<div className="card" style={{ borderColor: "var(--color-danger)" }}>
|
||||
<p style={{ margin: 0 }}>{t("cancelled")}</p>
|
||||
</div>
|
||||
) : null}
|
||||
{sp.status === "cancel" ? (
|
||||
<div className="card" style={{ borderColor: "var(--color-danger)" }}>
|
||||
<p style={{ margin: 0 }}>{t("cancelled")}</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="card-grid sm-2">
|
||||
<ContentCard icon="🪙" title={t("chooseAmount")}>
|
||||
{configured ? (
|
||||
<TopUpForm currency={PAYPAL_CURRENCY} creditsPerUnit={rate} />
|
||||
) : (
|
||||
<p className="muted" style={{ margin: 0 }}>
|
||||
{t("notConfiguredPre")} <code>PAYPAL_CLIENT_ID</code> {t("notConfiguredAnd")}{" "}
|
||||
<code>PAYPAL_SECRET</code> {t("notConfiguredOptional")} <code>PAYPAL_API</code>{" "}
|
||||
{t("notConfiguredPost")}
|
||||
</p>
|
||||
)}
|
||||
</ContentCard>
|
||||
<div className="card-grid sm-2">
|
||||
<ContentCard icon="🪙" title={t("chooseAmount")}>
|
||||
{configured ? (
|
||||
<TopUpForm currency={PAYPAL_CURRENCY} creditsPerUnit={rate} />
|
||||
) : (
|
||||
<p className="muted" style={{ margin: 0 }}>
|
||||
{t("notConfiguredPre")} <code>PAYPAL_CLIENT_ID</code>{" "}
|
||||
{t("notConfiguredAnd")} <code>PAYPAL_SECRET</code>{" "}
|
||||
{t("notConfiguredOptional")} <code>PAYPAL_API</code>{" "}
|
||||
{t("notConfiguredPost")}
|
||||
</p>
|
||||
)}
|
||||
</ContentCard>
|
||||
|
||||
<ContentCard
|
||||
icon="💰"
|
||||
title={t("balanceTitle")}
|
||||
subtitle={t("signedInAs", { username: user.username })}
|
||||
>
|
||||
<div className="stat-grid">
|
||||
<StatBlock value={user.credits.toLocaleString()} label={t("credits")} icon="🪙" />
|
||||
<StatBlock
|
||||
value={rate.toLocaleString()}
|
||||
label={t("creditsPerUnit", { currency: PAYPAL_CURRENCY })}
|
||||
/>
|
||||
</div>
|
||||
<p className="muted" style={{ marginBottom: 0, marginTop: "0.85rem" }}>
|
||||
{t.rich("rateLine", {
|
||||
amount: rate.toLocaleString(),
|
||||
currency: PAYPAL_CURRENCY,
|
||||
strong: (chunks) => <strong>{chunks}</strong>,
|
||||
})}
|
||||
</p>
|
||||
</ContentCard>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
<ContentCard
|
||||
icon="💰"
|
||||
title={t("balanceTitle")}
|
||||
subtitle={t("signedInAs", { username: user.username })}
|
||||
>
|
||||
<div className="stat-grid">
|
||||
<StatBlock
|
||||
value={user.credits.toLocaleString()}
|
||||
label={t("credits")}
|
||||
icon="🪙"
|
||||
/>
|
||||
<StatBlock
|
||||
value={rate.toLocaleString()}
|
||||
label={t("creditsPerUnit", { currency: PAYPAL_CURRENCY })}
|
||||
/>
|
||||
</div>
|
||||
<p
|
||||
className="muted"
|
||||
style={{ marginBottom: 0, marginTop: "0.85rem" }}
|
||||
>
|
||||
{t.rich("rateLine", {
|
||||
amount: rate.toLocaleString(),
|
||||
currency: PAYPAL_CURRENCY,
|
||||
strong: (chunks) => <strong>{chunks}</strong>,
|
||||
})}
|
||||
</p>
|
||||
</ContentCard>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user