78 lines
2.5 KiB
TypeScript
78 lines
2.5 KiB
TypeScript
"use client";
|
|||
|
|
|
||
|
|
import Link from "next/link";
|
||
|
|
import { useRouter } from "next/navigation";
|
||
|
|
import { useId, useState } from "react";
|
||
|
|
|
||
|
|
import { api, ApiError, errorText } from "@/lib/api";
|
||
|
|
|
||
|
|
/** Typing help: upper case, groups of four (ABCD-EFGH-JKLM). */
|
||
|
|
function format(input: string): string {
|
||
|
|
const clean = input.toUpperCase().replace(/[^0-9A-Z]/g, "").slice(0, 32);
|
||
|
|
return clean.match(/.{1,4}/g)?.join("-") ?? "";
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Redeeming a promo code: the package arrives at once. */
|
||
|
|
export function RedeemCode({ initial = "", compact = false }: { initial?: string; compact?: boolean }) {
|
||
|
|
const router = useRouter();
|
||
|
|
const id = useId();
|
||
|
|
const [code, setCode] = useState(format(initial));
|
||
|
|
const [busy, setBusy] = useState(false);
|
||
|
|
const [error, setError] = useState<string | null>(null);
|
||
|
|
const [got, setGot] = useState<string | null>(null);
|
||
|
|
|
||
|
|
async function redeem(e: React.FormEvent) {
|
||
|
|
e.preventDefault();
|
||
|
|
setBusy(true);
|
||
|
|
setError(null);
|
||
|
|
try {
|
||
|
|
const r = await api<{ package: { name: string } }>("/promo-codes/redeem", { body: { code } });
|
||
|
|
setGot(r.package.name);
|
||
|
|
setCode("");
|
||
|
|
router.refresh();
|
||
|
|
} catch (err) {
|
||
|
|
setError(
|
||
|
|
err instanceof ApiError && err.status === 429
|
||
|
|
? "Túl sok sikertelen próbálkozás. Várj negyed órát, és próbáld újra."
|
||
|
|
: errorText(err),
|
||
|
|
);
|
||
|
|
} finally {
|
||
|
|
setBusy(false);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return (
|
||
|
|
<form className={compact ? "redeem redeem-compact" : "redeem"} onSubmit={redeem}>
|
||
|
|
<label htmlFor={id} className={compact ? "label" : "sr-only"}>
|
||
|
|
Promókód
|
||
|
|
</label>
|
||
|
|
<div className="redeem-row">
|
||
|
|
<input
|
||
|
|
id={id}
|
||
|
|
className="inp redeem-input"
|
||
|
|
value={code}
|
||
|
|
onChange={(e) => setCode(format(e.target.value))}
|
||
|
|
placeholder="XXXX-XXXX-XXXX"
|
||
|
|
autoComplete="off"
|
||
|
|
autoCapitalize="characters"
|
||
|
|
spellCheck={false}
|
||
|
|
inputMode="text"
|
||
|
|
aria-describedby={`${id}-msg`}
|
||
|
|
/>
|
||
|
|
<button type="submit" className="btn btn-primary" disabled={busy || code.replace(/-/g, "").length < 8}>
|
||
|
|
{busy ? "Beváltás…" : "Beváltom"}
|
||
|
|
</button>
|
||
|
|
</div>
|
||
|
|
<div id={`${id}-msg`} aria-live="polite">
|
||
|
|
{error && <p className="msg msg-error">{error}</p>}
|
||
|
|
{got && (
|
||
|
|
<p className="msg msg-ok">
|
||
|
|
Megkaptad: <strong>{got}</strong>. Az elemzéseid már felhasználhatók,{" "}
|
||
|
|
<Link href="/keplet">indulhat a képleted</Link>.
|
||
|
|
</p>
|
||
|
|
)}
|
||
|
|
</div>
|
||
|
|
</form>
|
||
|
|
);
|
||
|
|
}
|