Promo codes; purchases off in production
CI / test (push) Successful in 1m11s
CI / build (push) Successful in 5m38s
CI / deploy (push) Skipped

Admins make promo codes for a package (Admin → Promókódok: batch, note, copy
all), list them filtered (unused by default, used, revoked; by package; by
code, note or redeemer) and withdraw unused ones. A logged-in user redeems a
code once (header link, /bevaltas?kod=... prefilled, packages page, and the
analysis and question offers point there) and gets the package as an order
with source 'promo'. Failed redemptions are rate limited.

Production purchases are off: MOCK_PAYMENTS now defaults to false in the
deploy compose, so package cards say 'Hamarosan'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-19 09:45:42 +00:00
co-authored by Claude Opus 5.5
parent 19df36369c
commit 054fb930f5
19 changed files with 863 additions and 5 deletions
@@ -0,0 +1,285 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { Package, PromoCode } from "@/lib/types";
const PAGE = 100;
const STATUSES: Record<string, string> = {
unused: "fel nem használt",
used: "beváltott",
revoked: "visszavont",
all: "mind",
};
interface Page {
codes: PromoCode[];
total: number;
}
/** Making promo codes and the filtered list of them. */
export function PromoCodes({ packages }: { packages: Package[] }) {
return (
<>
<NewCodes packages={packages} />
<CodeList packages={packages} />
</>
);
}
function NewCodes({ packages }: { packages: Package[] }) {
const [pkg, setPkg] = useState(packages.find((p) => p.id === "single")?.id ?? packages[0]?.id ?? "");
const [count, setCount] = useState(1);
const [note, setNote] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [made, setMade] = useState<{ codes: string[]; package: string } | null>(null);
const [copied, setCopied] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const r = await api<{ codes: string[]; package: string }>("/admin/promo-codes", {
body: { package: pkg, count, note: note || null },
});
setMade(r);
setCopied(false);
window.dispatchEvent(new Event("promo-codes-changed"));
} catch (err) {
setError(errorText(err));
} finally {
setBusy(false);
}
}
async function copy() {
if (!made) return;
await navigator.clipboard.writeText(made.codes.join("\n"));
setCopied(true);
}
return (
<section className="card" aria-labelledby="new-codes" style={{ gap: 14 }}>
<h2 id="new-codes">Új kódok</h2>
<form className="promo-form" onSubmit={create}>
<div className="field">
<label htmlFor="promo-package">Csomag</label>
<select id="promo-package" className="inp" value={pkg} onChange={(e) => setPkg(e.target.value)}>
{packages.map((p) => (
<option key={p.id} value={p.id}>
{p.name} ({p.tier === "main" ? "csomag" : "kiegészítő"})
</option>
))}
</select>
</div>
<div className="field">
<label htmlFor="promo-count">Darab</label>
<input
id="promo-count"
className="inp"
type="number"
min={1}
max={500}
value={count}
onChange={(e) => setCount(Math.max(1, Math.min(500, Number(e.target.value) || 1)))}
/>
</div>
<div className="field promo-note">
<label htmlFor="promo-note">Megjegyzés (kinek, melyik kampány)</label>
<input
id="promo-note"
className="inp"
value={note}
maxLength={200}
onChange={(e) => setNote(e.target.value)}
placeholder="pl. meghívottak, első kör"
/>
</div>
<button type="submit" className="btn btn-primary" disabled={busy || !pkg}>
{busy ? "Készül…" : "Kódok készítése"}
</button>
</form>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{made && (
<div className="promo-made">
<p className="msg msg-ok" role="status">
{made.codes.length} új kód: {packages.find((p) => p.id === made.package)?.name ?? made.package}
</p>
<textarea className="inp promo-codes" readOnly rows={Math.min(made.codes.length, 10)} value={made.codes.join("\n")} />
<button type="button" className="btn btn-sm" onClick={copy}>
{copied ? "Kimásolva" : "Mind másolása"}
</button>
</div>
)}
</section>
);
}
function CodeList({ packages }: { packages: Package[] }) {
const [status, setStatus] = useState("unused");
const [pkg, setPkg] = useState("");
const [q, setQ] = useState("");
const [query, setQuery] = useState("");
const [codes, setCodes] = useState<PromoCode[] | null>(null);
const [total, setTotal] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(
async (offset: number) => {
setBusy(true);
setError(null);
const params = new URLSearchParams({ status, limit: String(PAGE), offset: String(offset) });
if (pkg) params.set("package", pkg);
if (query) params.set("q", query);
try {
const page = await api<Page>(`/admin/promo-codes?${params}`);
setCodes((all) => (offset === 0 ? page.codes : [...(all ?? []), ...page.codes]));
setTotal(page.total);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
},
[status, pkg, query],
);
useEffect(() => {
load(0);
const reload = () => load(0);
window.addEventListener("promo-codes-changed", reload);
return () => window.removeEventListener("promo-codes-changed", reload);
}, [load]);
// Searching after a short pause in typing.
useEffect(() => {
const t = setTimeout(() => setQuery(q.trim()), 300);
return () => clearTimeout(t);
}, [q]);
async function revoke(c: PromoCode) {
if (!window.confirm(`Visszavonod a(z) ${c.code} kódot? Utána nem váltható be.`)) return;
try {
await api(`/admin/promo-codes/${c.id}/revoke`, { body: {} });
load(0);
} catch (e) {
setError(errorText(e));
}
}
return (
<section className="card" aria-labelledby="code-list" style={{ gap: 12 }}>
<h2 id="code-list">Kódok</h2>
<div className="row" style={{ gap: 12, alignItems: "flex-end" }}>
<div className="field">
<label htmlFor="code-status">Állapot</label>
<select id="code-status" className="inp" value={status} onChange={(e) => setStatus(e.target.value)}>
{Object.entries(STATUSES).map(([v, l]) => (
<option key={v} value={v}>
{l}
</option>
))}
</select>
</div>
<div className="field">
<label htmlFor="code-package">Csomag</label>
<select id="code-package" className="inp" value={pkg} onChange={(e) => setPkg(e.target.value)}>
<option value="">mind</option>
{packages.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
<div className="field" style={{ flex: "1 1 220px" }}>
<label htmlFor="code-search">Keresés</label>
<input
id="code-search"
className="inp"
type="search"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="kód, megjegyzés vagy e-mail"
/>
</div>
<p className="hint" style={{ margin: 0 }}>
{total} kód
</p>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{codes === null ? (
<p className="muted">Betöltés…</p>
) : codes.length === 0 ? (
<p className="muted">Nincs ilyen kód.</p>
) : (
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Kód</th>
<th>Csomag</th>
<th>Megjegyzés</th>
<th>Készült</th>
<th>Állapot</th>
<th />
</tr>
</thead>
<tbody>
{codes.map((c) => (
<tr key={c.id}>
<td>
<code className="promo-code">{c.code}</code>
</td>
<td>{c.package_name ?? c.package}</td>
<td>{c.note ?? <span className="muted">–</span>}</td>
<td className="num">{formatDate(c.created_at)}</td>
<td>
{c.redeemed_at ? (
<>
beváltva {formatDate(c.redeemed_at, true)}
{c.redeemed_by && (
<span className="hint">{c.redeemed_by.name ? `${c.redeemed_by.name} · ` : ""}{c.redeemed_by.email}</span>
)}
</>
) : c.revoked_at ? (
<span className="muted">visszavonva {formatDate(c.revoked_at)}</span>
) : (
<span className="promo-open">szabad</span>
)}
</td>
<td>
{!c.redeemed_at && !c.revoked_at && (
<button type="button" className="btn btn-sm btn-ghost" onClick={() => revoke(c)}>
Visszavonás
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{codes && codes.length < total && (
<button type="button" className="btn btn-sm" onClick={() => load(codes.length)} disabled={busy}>
{busy ? "Betöltés…" : "Továbbiak"}
</button>
)}
</section>
);
}
@@ -0,0 +1,29 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { AdminNav } from "@/components/AdminNav";
import { backendGet, requireMe } from "@/lib/server";
import type { Package } from "@/lib/types";
import { PromoCodes } from "./PromoCodes";
export const metadata: Metadata = { title: "Promókódok" };
export default async function AdminPromoPage() {
const me = await requireMe("/admin/promokodok");
if (!me.user.roles.includes("admin")) notFound();
const catalog = await backendGet<{ packages: Package[] }>("/v1/packages");
return (
<main className="page" style={{ maxWidth: 1180 }}>
<AdminNav current="/admin/promokodok" />
<div className="page-head">
<h1>Promókódok</h1>
<p className="muted">
Egy kód egy csomagot ad, és egyszer váltható be a „Kód beváltása” oldalon (a fejlécben). A beváltó link:
sorsfonalak.hu/bevaltas?kod=KÓD — ezt elég elküldeni, belépés után kitöltve várja.
</p>
</div>
<PromoCodes packages={catalog?.packages ?? []} />
</main>
);
}
@@ -0,0 +1,29 @@
import type { Metadata } from "next";
import { RedeemCode } from "@/components/RedeemCode";
import { requireMe } from "@/lib/server";
export const metadata: Metadata = { title: "Promókód beváltása", robots: { index: false } };
type Props = { searchParams: Promise<{ kod?: string }> };
/** Redeeming a promo code; `?kod=` fills it in (links in invitations). */
export default async function RedeemPage({ searchParams }: Props) {
const { kod } = await searchParams;
await requireMe(kod ? `/bevaltas?kod=${encodeURIComponent(kod)}` : "/bevaltas");
return (
<main className="page" style={{ maxWidth: 640 }}>
<div className="page-head">
<span className="eyebrow">Promókód</span>
<h1>Promókód beváltása</h1>
<p className="muted">
Írd be a kapott kódot. A hozzá tartozó csomag azonnal a tiéd, az elemzései nem járnak le. Egy kód egyszer
váltható be.
</p>
</div>
<section className="card">
<RedeemCode initial={kod ?? ""} />
</section>
</main>
);
}
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { AiNote } from "@/components/AiNote";
import { PackageCards } from "@/components/PackageCards";
import { RedeemCode } from "@/components/RedeemCode";
import { backendGet, requireMe } from "@/lib/server";
import type { Package, PublicConfig } from "@/lib/types";
@@ -68,6 +69,16 @@ export default async function PackagesPage() {
</p>
</section>
<section className="card redeem-card" aria-labelledby="redeem-title">
<h2 id="redeem-title">Van promókódod?</h2>
<p className="muted">
{canPay
? "Váltsd be itt: a hozzá tartozó csomag azonnal a tiéd."
: "A csomagok hamarosan megvásárolhatók. Addig promókóddal juthatsz hozzájuk: a hozzá tartozó csomag azonnal a tiéd."}
</p>
<RedeemCode />
</section>
<PackageCards packages={packages} canPay={canPay} />
<section className="field" aria-labelledby="addon-title" style={{ gap: 12 }}>
+21
View File
@@ -722,3 +722,24 @@ a.pair-row:hover strong { color: var(--gold); }
.share-cta { gap: 12px; }
.share-cta h2 { font-size: 24px; }
.share-cta .btn { align-self: flex-start; }
/* Promo codes: redeeming (header, packages page, /bevaltas) and the admin page */
.redeem-link { color: var(--ink-2); font-size: 13px; text-decoration: none; white-space: nowrap; }
.redeem-link:hover { color: var(--gold); text-decoration: underline; text-underline-offset: 3px; }
.redeem { display: flex; flex-direction: column; gap: 8px; }
.redeem-row { display: flex; gap: 8px; flex-wrap: wrap; }
.redeem-input { flex: 1 1 220px; width: auto; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: 1.5px; text-transform: uppercase; }
.redeem-card { gap: 10px; border-color: rgba(217, 180, 106, 0.35); }
.redeem-card h2 { font-size: 24px; }
.promo-form { display: grid; grid-template-columns: minmax(0, 1.4fr) 110px minmax(0, 2fr) auto; gap: 12px; align-items: end; }
.promo-made { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; }
.promo-codes { min-height: 0; padding: 10px 14px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; line-height: 1.6; resize: vertical; }
.promo-code { font-size: 14px; letter-spacing: 1px; white-space: nowrap; }
.promo-table td { vertical-align: top; }
.promo-table td .hint { display: block; }
.promo-open { color: var(--ok); }
@media (max-width: 760px) {
.promo-form { grid-template-columns: minmax(0, 1fr) 100px; }
.promo-form .promo-note, .promo-form .btn { grid-column: 1 / -1; }
}
@media (max-width: 640px) { .who { flex-wrap: wrap; gap: 8px 12px; } }