Files
sorsfonalak/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx
T
fecoandClaude Opus 5.5 7272d0f1f3 Invitation-only sign-up, invitation e-mails and waitlist
- SIGNUP_MODE=invite (default): a new account needs an open invitation for
  its address, or the invitation link (then any Google account will do)
- admin page "Meghívók": invite many addresses at once, personal message,
  resend (max 3, 24 h apart), revoke, copy link, mail preview and test copy,
  waitlist
- invitation e-mail in HTML and plain text; Message-ID on the sender's
  domain, List-Unsubscribe with one-click POST, opt-out list (hashes only)
- e-mail texts moved to a shared crate (crates/email-templates)
- login page shows the invitation; waitlist for uninvited visitors;
  unsubscribe page; privacy policy updated
- docs/levelkuldes.md: Brevo, DNS (SPF, DKIM, DMARC) and the SMTP setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-17 18:37:15 +00:00

473 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { AdminInvitation, InvitationResult, WaitlistEntry } from "@/lib/types";
const MAX_MESSAGE = 300;
const STATUS: Record<AdminInvitation["status"], string> = {
pending: "Függőben",
accepted: "Elfogadva",
expired: "Lejárt",
revoked: "Visszavonva",
};
const MAIL: Record<AdminInvitation["mail"], string> = {
sent: "Elküldve",
queued: "Sorban vár",
failed: "Sikertelen",
archived: "Elküldve (archív)",
};
const RESULT: Record<InvitationResult["status"], string> = {
invited: "meghívva",
invalid: "érvénytelen cím",
already_user: "már felhasználó",
already_invited: "már van élő meghívója (újraküldés a listában)",
opted_out: "leiratkozott a meghívókról",
};
interface ListData {
invitations: AdminInvitation[];
waitlist: WaitlistEntry[];
signup_mode: "invite" | "open";
}
function CopyLink({ url }: { url: string }) {
const [copied, setCopied] = useState(false);
return (
<button
type="button"
className="btn btn-sm btn-ghost"
onClick={async () => {
try {
await navigator.clipboard.writeText(url);
setCopied(true);
} catch {
window.prompt("A meghívólink:", url);
}
}}
>
{copied ? "Kimásolva" : "Link másolása"}
</button>
);
}
/** Addresses from free text: one per line, or separated by commas, semicolons or spaces. */
function parseEmails(text: string): string[] {
return text
.split(/[\s,;]+/)
.map((s) => s.trim())
.filter(Boolean);
}
export function AdminInvitations() {
const [data, setData] = useState<ListData | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
try {
setData(await api<ListData>("/admin/invitations"));
setError(null);
} catch (e) {
setError(errorText(e));
}
}, []);
useEffect(() => {
load();
}, [load]);
return (
<div className="field" style={{ gap: 24 }}>
{data?.signup_mode === "open" && (
<p className="msg" role="status">
A regisztráció most nyitott (<code>SIGNUP_MODE=open</code>): bárki beléphet, a meghívó csak értesítés.
</p>
)}
<InviteForm onSent={load} />
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{data && <InvitationList invitations={data.invitations} onChange={load} />}
{data && <WaitlistTable waitlist={data.waitlist} onChange={load} />}
</div>
);
}
function InviteForm({ onSent }: { onSent: () => Promise<void> }) {
const [emails, setEmails] = useState("");
const [message, setMessage] = useState("");
const [locale, setLocale] = useState("hu");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [results, setResults] = useState<InvitationResult[] | null>(null);
const count = parseEmails(emails).length;
async function submit(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
setResults(null);
try {
const res = await api<{ results: InvitationResult[] }>("/admin/invitations", {
body: { emails: parseEmails(emails), message: message.trim() || null, locale },
});
setResults(res.results);
if (res.results.some((r) => r.status === "invited")) setEmails("");
await onSent();
} catch (err) {
setError(errorText(err));
} finally {
setBusy(false);
}
}
return (
<section className="card field" style={{ gap: 16 }} aria-labelledby="invite-title">
<h2 id="invite-title" style={{ margin: 0 }}>
Új meghívó
</h2>
<form onSubmit={submit} className="field" style={{ gap: 14 }}>
<div className="field">
<label htmlFor="invite-emails">E-mail-címek</label>
<textarea
id="invite-emails"
className="inp"
rows={3}
required
value={emails}
onChange={(e) => setEmails(e.target.value)}
placeholder={"kata@pelda.hu\nbela@pelda.hu"}
/>
<span className="hint">Soronként egy, vagy vesszővel elválasztva; egyszerre legfeljebb 50.</span>
</div>
<div className="field">
<label htmlFor="invite-message">Személyes üzenet (nem kötelező)</label>
<textarea
id="invite-message"
className="inp"
rows={3}
maxLength={MAX_MESSAGE}
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Szia! Ezt nézd meg, szerintem tetszeni fog."
/>
<span className="hint">
{message.length}/{MAX_MESSAGE} karakter. Link nem lehet benne (spamszűrők miatt).
</span>
</div>
<div className="row" style={{ gap: 12, alignItems: "flex-end", flexWrap: "wrap" }}>
<div className="field" style={{ width: 160 }}>
<label htmlFor="invite-locale">A levél nyelve</label>
<select id="invite-locale" className="inp" value={locale} onChange={(e) => setLocale(e.target.value)}>
<option value="hu">magyar</option>
<option value="en">angol</option>
</select>
</div>
<button type="submit" className="btn btn-primary" disabled={busy || count === 0}>
{busy ? "Küldés…" : count > 1 ? `${count} meghívó küldése` : "Meghívó küldése"}
</button>
</div>
</form>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{results && (
<ul className="invite-results" aria-label="Eredmény">
{results.map((r) => (
<li key={r.email}>
<span className={r.status === "invited" ? "msg-ok" : "muted"}>
{r.email}: {RESULT[r.status]}
</span>
{r.url && <CopyLink url={r.url} />}
</li>
))}
</ul>
)}
<MailPreview message={message} locale={locale} />
</section>
);
}
/** The invitation e-mail as the recipient sees it, and a test copy to the admin. */
function MailPreview({ message, locale }: { message: string; locale: string }) {
const [mail, setMail] = useState<{ subject: string; html: string; text: string } | null>(null);
const [view, setView] = useState<"html" | "text">("html");
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<{ ok: boolean; text: string } | null>(null);
async function show(sendToMe: boolean) {
setBusy(true);
setNote(null);
try {
const res = await api<{ subject: string; html: string; text: string; sent_to: string | null }>(
"/admin/invitations/preview",
{ body: { message: message.trim() || null, locale, send_to_me: sendToMe } },
);
setMail(res);
if (res.sent_to) setNote({ ok: true, text: `Tesztlevél a sorban: ${res.sent_to}. A linkjei nem működnek.` });
} catch (e) {
setNote({ ok: false, text: errorText(e) });
} finally {
setBusy(false);
}
}
return (
<div className="field mail-preview" style={{ gap: 10 }}>
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
<button type="button" className="btn btn-sm" onClick={() => show(false)} disabled={busy}>
{mail ? "Előnézet frissítése" : "Levél előnézete"}
</button>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => show(true)} disabled={busy}>
Teszt küldése magamnak
</button>
</div>
{note && (
<p className={note.ok ? "msg msg-ok" : "msg msg-error"} role={note.ok ? "status" : "alert"}>
{note.text}
</p>
)}
{mail && (
<>
<p style={{ margin: 0 }}>
<span className="muted">Tárgy:</span> <strong>{mail.subject}</strong>
</p>
<div className="row" role="group" aria-label="Változat" style={{ gap: 4 }}>
{(["html", "text"] as const).map((v) => (
<button
key={v}
type="button"
className={view === v ? "btn btn-sm" : "btn btn-sm btn-ghost"}
aria-pressed={view === v}
onClick={() => setView(v)}
>
{v === "html" ? "HTML" : "Szöveges"}
</button>
))}
</div>
{view === "html" ? (
<iframe title="A levél HTML-változata" className="mail-frame" srcDoc={mail.html} sandbox="" />
) : (
<pre className="mail-text">{mail.text}</pre>
)}
</>
)}
</div>
);
}
function InvitationList({ invitations, onChange }: { invitations: AdminInvitation[]; onChange: () => Promise<void> }) {
return (
<section className="card" aria-labelledby="invitations-title">
<h2 id="invitations-title" style={{ marginTop: 0 }}>
Meghívók
</h2>
{invitations.length === 0 ? (
<p className="muted">Még nincs meghívó.</p>
) : (
<div className="table-wrap">
<table>
<thead>
<tr>
<th scope="col">Cím</th>
<th scope="col">Állapot</th>
<th scope="col">Levél</th>
<th scope="col">Küldve</th>
<th scope="col">Lejár</th>
<th scope="col">
<span className="sr-only">Műveletek</span>
</th>
</tr>
</thead>
<tbody>
{invitations.map((i) => (
<InvitationRow key={i.id} invitation={i} onChange={onChange} />
))}
</tbody>
</table>
</div>
)}
</section>
);
}
function InvitationRow({ invitation: i, onChange }: { invitation: AdminInvitation; onChange: () => Promise<void> }) {
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<string | null>(null);
const [url, setUrl] = useState<string | null>(null);
async function act(kind: "resend" | "revoke") {
if (kind === "revoke" && !window.confirm(`Visszavonod a meghívót (${i.email})?`)) return;
setBusy(true);
setNote(null);
try {
if (kind === "resend") {
const res = await api<{ url: string }>(`/admin/invitations/${i.id}/resend`, { body: {} });
setUrl(res.url);
} else {
await api(`/admin/invitations/${i.id}`, { method: "DELETE" });
}
await onChange();
} catch (e) {
setNote(errorText(e));
} finally {
setBusy(false);
}
}
return (
<tr>
<td>
<div>{i.email}</div>
{i.message && (
<div className="hint invite-msg" title={i.message}>
„{i.message}”
</div>
)}
</td>
<td>
<span className={`badge invite-${i.status}`}>{STATUS[i.status]}</span>
{i.accepted_by && <div className="hint">{i.accepted_by}</div>}
</td>
<td>
<span className={i.mail === "failed" ? "msg-error" : i.mail === "queued" ? "muted" : undefined}>
{MAIL[i.mail]}
</span>
{i.mail_error && <div className="hint">{i.mail_error.slice(0, 120)}</div>}
</td>
<td className="num">
{formatDate(i.last_sent_at)}
{i.sent_count > 1 && <div className="hint">{i.sent_count}× küldve</div>}
</td>
<td className="num">{i.status === "pending" || i.status === "expired" ? formatDate(i.expires_at) : "–"}</td>
<td>
<div className="row" style={{ gap: 4, flexWrap: "nowrap", justifyContent: "flex-end" }}>
{url && <CopyLink url={url} />}
{i.can_resend && (
<button type="button" className="btn btn-sm" onClick={() => act("resend")} disabled={busy}>
Újraküldés
</button>
)}
{(i.status === "pending" || i.status === "expired") && (
<button type="button" className="btn btn-sm btn-ghost" onClick={() => act("revoke")} disabled={busy}>
Visszavonás
</button>
)}
</div>
{note && (
<div className="msg-error" role="alert" style={{ fontSize: 13 }}>
{note}
</div>
)}
</td>
</tr>
);
}
function WaitlistTable({ waitlist, onChange }: { waitlist: WaitlistEntry[]; onChange: () => Promise<void> }) {
const [busy, setBusy] = useState<string | null>(null);
const [note, setNote] = useState<string | null>(null);
async function invite(w: WaitlistEntry) {
setBusy(w.email);
setNote(null);
try {
const res = await api<{ results: InvitationResult[] }>("/admin/invitations", {
body: { emails: [w.email], locale: w.locale },
});
const r = res.results[0];
if (r && r.status !== "invited") setNote(`${r.email}: ${RESULT[r.status]}`);
await onChange();
} catch (e) {
setNote(errorText(e));
} finally {
setBusy(null);
}
}
async function remove(w: WaitlistEntry) {
setBusy(w.email);
setNote(null);
try {
await api(`/admin/waitlist/${encodeURIComponent(w.email)}`, { method: "DELETE" });
await onChange();
} catch (e) {
setNote(errorText(e));
} finally {
setBusy(null);
}
}
return (
<section className="card" aria-labelledby="waitlist-title">
<h2 id="waitlist-title" style={{ marginTop: 0 }}>
Várólista
</h2>
<p className="hint">Akik meghívó nélkül próbáltak belépni, és kérték, hogy szóljunk nekik.</p>
{note && (
<p className="msg msg-error" role="alert">
{note}
</p>
)}
{waitlist.length === 0 ? (
<p className="muted">Üres.</p>
) : (
<div className="table-wrap">
<table>
<thead>
<tr>
<th scope="col">Cím</th>
<th scope="col">Feliratkozott</th>
<th scope="col">Meghívó</th>
<th scope="col">
<span className="sr-only">Műveletek</span>
</th>
</tr>
</thead>
<tbody>
{waitlist.map((w) => (
<tr key={w.email}>
<td>{w.email}</td>
<td className="num">{formatDate(w.created_at)}</td>
<td>{w.invitation === "pending" ? "elküldve" : w.invitation === "accepted" ? "elfogadva" : "–"}</td>
<td>
<div className="row" style={{ gap: 4, flexWrap: "nowrap", justifyContent: "flex-end" }}>
{w.invitation === null && (
<button
type="button"
className="btn btn-sm"
onClick={() => invite(w)}
disabled={busy !== null}
>
Meghívás
</button>
)}
<button
type="button"
className="btn btn-sm btn-ghost"
onClick={() => remove(w)}
disabled={busy !== null}
>
Törlés
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}