diff --git a/crates/db/migrations/0022_promo_codes.sql b/crates/db/migrations/0022_promo_codes.sql
new file mode 100644
index 0000000..816e00e
--- /dev/null
+++ b/crates/db/migrations/0022_promo_codes.sql
@@ -0,0 +1,23 @@
+-- Promo codes: an admin makes them for a package, a user redeems one once
+-- and gets the package (a `package_orders` row with source `promo`).
+CREATE TABLE promo_codes (
+ id uuid PRIMARY KEY,
+ -- Upper case, without separators (shown in groups of four).
+ code text NOT NULL UNIQUE CHECK (code ~ '^[2-9A-HJKMNP-Z]{8,32}$'),
+ package text NOT NULL,
+ -- Who it is for or which campaign (admin only).
+ note text,
+ created_by uuid REFERENCES users (id) ON DELETE SET NULL,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ redeemed_by uuid REFERENCES users (id) ON DELETE SET NULL,
+ redeemed_at timestamptz,
+ order_id uuid REFERENCES package_orders (id) ON DELETE SET NULL,
+ -- An unused code can be withdrawn.
+ revoked_at timestamptz,
+ CHECK (redeemed_at IS NULL OR revoked_at IS NULL)
+);
+CREATE INDEX promo_codes_created_idx ON promo_codes (created_at DESC);
+
+ALTER TABLE package_orders DROP CONSTRAINT package_orders_source_check;
+ALTER TABLE package_orders ADD CONSTRAINT package_orders_source_check
+ CHECK (source IN ('admin', 'mock', 'stripe', 'promo'));
diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs
index 0f73e30..f34e6ac 100644
--- a/crates/db/src/lib.rs
+++ b/crates/db/src/lib.rs
@@ -104,6 +104,15 @@ pub fn random_token(bytes: usize) -> String {
URL_SAFE_NO_PAD.encode(buf)
}
+/// Letters and digits that cannot be mixed up when typed (no 0/O, 1/I/L).
+pub const CODE_ALPHABET: &[u8] = b"23456789ABCDEFGHJKMNPQRSTUVWXYZ";
+
+/// A random code of `len` characters from [`CODE_ALPHABET`] (about 5 bits each).
+pub fn random_code(len: usize) -> String {
+ let mut rng = rand::rng();
+ (0..len).map(|_| CODE_ALPHABET[rand::Rng::random_range(&mut rng, 0..CODE_ALPHABET.len())] as char).collect()
+}
+
/// Stored form of a secret token.
pub fn token_hash(token: &str) -> Vec {
Sha256::digest(token.as_bytes()).to_vec()
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index f4a3aa3..265e99c 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -85,8 +85,9 @@ services:
ANALYSIS_MODEL: ${ANALYSIS_MODEL:-}
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
- # Stand-in payment (adds an analysis unit at once) until Stripe is connected.
- MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
+ # Purchases are off until real payments are connected; packages come
+ # from promo codes and admins (MOCK_PAYMENTS=true: pretend purchases).
+ MOCK_PAYMENTS: ${MOCK_PAYMENTS:-false}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
diff --git a/docs/promokodok.md b/docs/promokodok.md
new file mode 100644
index 0000000..0205d0e
--- /dev/null
+++ b/docs/promokodok.md
@@ -0,0 +1,36 @@
+# Promókódok
+
+Amíg a fizetés nincs bekötve, a csomagokat promókóddal (és admin ajándékkal) lehet megkapni. Élesben a vásárlás ki van kapcsolva: a `MOCK_PAYMENTS` alapértéke a `deploy/docker-compose.yml`-ben `false`. A csomagkártyákon ilyenkor „Hamarosan” felirat áll.
+
+## Admin: Admin → Promókódok
+
+- **Kódkészítés:**
+ - Csomag (a fő csomagok és a kiegészítők közül), darab (1–500) és egy megjegyzés: kinek szól, melyik kampány.
+ - Az elkészült kódok egy listában jelennek meg, a „Mind másolása” gombbal kimásolhatók.
+ - A kód formája `ABCD-EFGH-JKLM`: 12 karakter, összetéveszthető betűk és számok nélkül (nincs 0/O, 1/I/L).
+- **Lista:**
+ - Szűrhető állapotra: **fel nem használt** (ez az alapértelmezés), beváltott, visszavont, mind.
+ - Szűrhető csomagra, és kereshető kódrészletre, megjegyzésre vagy a beváltó e-mail-címére.
+ - A beváltott kódnál látszik, ki és mikor váltotta be.
+- **Visszavonás:** fel nem használt kódot vissza lehet vonni. Utána nem váltható be.
+
+## Felhasználó: beváltás
+
+- **Hol lehet beváltani:**
+ - a fejléc „Kód beváltása” linkje (`/bevaltas`);
+ - a Csomagok oldal „Van promókódod?” doboza;
+ - a részletes elemzés ajánlata és a kérdés-válasz rész is ide vezet, ha nincs felhasználható egység.
+- **Kitöltött link:** a `sorsfonalak.hu/bevaltas?kod=ABCD-EFGH-JKLM` link kitöltve nyitja meg a kódot. Aki nincs belépve, a belépés után ide tér vissza. Elég ezt a linket elküldeni a meghívottaknak.
+- **Beírás:** a kód kis- vagy nagybetűvel, kötőjellel vagy anélkül is beírható.
+- **Beváltás:** a csomag azonnal jóváíródik. Ez egy `package_orders` sor `promo` forrással, 0 Ft-tal, és mellette a szokásos `credit_ledger` sorok.
+- **Egyszer:** egy kód egyszer váltható be. A „már felhasználták”, „már nem érvényes” és „nincs ilyen kód” esetekre külön üzenet van.
+- **Találgatás ellen:** 10 sikertelen próbálkozás után a felhasználó negyed óráig nem próbálkozhat.
+
+## API
+
+| Végpont | Ki | Mit csinál |
+|---|---|---|
+| `POST /v1/admin/promo-codes` `{package, count, note?}` | admin | kódok készítése |
+| `GET /v1/admin/promo-codes?status=unused\|used\|revoked\|all&package=&q=&limit=&offset=` | admin | lista |
+| `POST /v1/admin/promo-codes/{id}/revoke` | admin | visszavonás |
+| `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | beváltás; a válaszban az új egyenleg és a csomag |
diff --git a/services/backend/src/packages.rs b/services/backend/src/packages.rs
index fc757c2..30c3466 100644
--- a/services/backend/src/packages.rs
+++ b/services/backend/src/packages.rs
@@ -184,6 +184,8 @@ impl Package {
pub enum Source {
Admin,
Mock,
+ /// A redeemed promo code.
+ Promo,
}
impl Source {
@@ -191,6 +193,7 @@ impl Source {
match self {
Source::Admin => "admin",
Source::Mock => "mock",
+ Source::Promo => "promo",
}
}
}
@@ -206,7 +209,7 @@ pub async fn grant(
) -> Result {
let order = Uuid::now_v7();
let price = match source {
- Source::Admin => 0,
+ Source::Admin | Source::Promo => 0,
Source::Mock => package.price_huf,
};
sqlx::query(
diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs
index baea8bd..3336334 100644
--- a/services/backend/src/routes/mod.rs
+++ b/services/backend/src/routes/mod.rs
@@ -16,6 +16,7 @@ mod invitations;
mod jobs;
mod models;
mod payments;
+mod promo;
mod prompts;
mod questions;
mod recalculate;
@@ -96,6 +97,9 @@ pub fn router(state: Arc) -> Router {
.route("/v1/analyses/{id}/questions", get(questions::list).post(questions::ask))
.route("/v1/questions/{id}", get(questions::get_one))
// sharing
+ .route("/v1/promo-codes/redeem", post(promo::redeem))
+ .route("/v1/admin/promo-codes", get(promo::list).post(promo::create))
+ .route("/v1/admin/promo-codes/{id}/revoke", post(promo::revoke))
.route("/v1/shares", get(shares::list).post(shares::create))
.route("/v1/shares/{id}", delete(shares::revoke))
// public, no login
diff --git a/services/backend/src/routes/promo.rs b/services/backend/src/routes/promo.rs
new file mode 100644
index 0000000..8ddfd40
--- /dev/null
+++ b/services/backend/src/routes/promo.rs
@@ -0,0 +1,232 @@
+//! Promo codes. An admin makes a batch for one package; a logged-in user
+//! redeems a code once and gets that package (an order with source `promo`).
+//! Unused codes can be withdrawn. Failed redemptions are rate limited per
+//! user, so codes cannot be guessed.
+
+use axum::Json;
+use axum::extract::{Path, Query, State};
+use axum::http::StatusCode;
+use axum_extra::extract::WithRejection;
+use serde::Deserialize;
+use serde_json::{Value, json};
+use time::OffsetDateTime;
+use uuid::Uuid;
+
+use super::payments::holdings;
+use super::{Body, IdPath, St};
+use crate::auth::{AdminUser, AuthUser};
+use crate::error::{ApiError, ApiResult};
+use crate::packages::{self, Source};
+use crate::views::{rfc3339, rfc3339_opt};
+
+/// Characters of a code (12 × ~5 bits: not guessable within the rate limit).
+const CODE_LEN: usize = 12;
+const MAX_BATCH: i64 = 500;
+
+/// `ABCD-EFGH-JKLM`: the stored code in groups of four.
+fn display(code: &str) -> String {
+ code.as_bytes().chunks(4).map(|c| String::from_utf8_lossy(c).into_owned()).collect::>().join("-")
+}
+
+/// What the user typed, as stored: upper case, without spaces and dashes.
+fn normalize(input: &str) -> String {
+ input.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_uppercase()).collect()
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct NewCodes {
+ package: String,
+ count: i64,
+ note: Option,
+}
+
+/// Admin: makes `count` new codes for a package.
+pub async fn create(
+ State(state): St,
+ admin: AdminUser,
+ WithRejection(Json(req), _): Body,
+) -> ApiResult<(StatusCode, Json)> {
+ let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
+ if !(1..=MAX_BATCH).contains(&req.count) {
+ return Err(ApiError::BadRequest(format!("count must be 1 to {MAX_BATCH}")));
+ }
+ let note = req.note.map(|n| n.trim().chars().take(200).collect::()).filter(|n| !n.is_empty());
+ let mut tx = state.db.begin().await?;
+ let mut codes = Vec::new();
+ while (codes.len() as i64) < req.count {
+ let code = db::random_code(CODE_LEN);
+ // A clash is practically impossible; skipped if it happens.
+ let inserted = sqlx::query(
+ "INSERT INTO promo_codes (id, code, package, note, created_by) VALUES ($1, $2, $3, $4, $5) \
+ ON CONFLICT (code) DO NOTHING",
+ )
+ .bind(Uuid::now_v7())
+ .bind(&code)
+ .bind(package.id)
+ .bind(¬e)
+ .bind(admin.0.id())
+ .execute(&mut *tx)
+ .await?
+ .rows_affected();
+ if inserted == 1 {
+ codes.push(display(&code));
+ }
+ }
+ tx.commit().await?;
+ tracing::info!(admin = %admin.0.id(), package = package.id, count = codes.len(), "promo codes created");
+ Ok((StatusCode::CREATED, Json(json!({ "package": package.id, "note": note, "codes": codes }))))
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct CodeQuery {
+ /// `unused` (default), `used`, `revoked` or `all`.
+ status: Option,
+ package: Option,
+ /// Part of the code, the note or the redeemer's e-mail.
+ q: Option,
+ limit: Option,
+ offset: Option,
+}
+
+type Row = (
+ Uuid,
+ String,
+ String,
+ Option,
+ OffsetDateTime,
+ Option,
+ Option,
+ Option,
+ Option,
+);
+
+/// Admin: the codes, newest first, filtered.
+pub async fn list(
+ State(state): St,
+ _admin: AdminUser,
+ WithRejection(Query(query), _): WithRejection, ApiError>,
+) -> ApiResult> {
+ let status = query.status.as_deref().unwrap_or("unused");
+ let condition = match status {
+ "unused" => "p.redeemed_at IS NULL AND p.revoked_at IS NULL",
+ "used" => "p.redeemed_at IS NOT NULL",
+ "revoked" => "p.revoked_at IS NOT NULL",
+ "all" => "true",
+ other => return Err(ApiError::BadRequest(format!("unknown status '{other}'"))),
+ };
+ let limit = query.limit.unwrap_or(100).clamp(1, 500);
+ let offset = query.offset.unwrap_or(0).max(0);
+ let package = query.package.filter(|p| !p.is_empty());
+ let search = query.q.map(|q| q.trim().to_string()).filter(|q| !q.is_empty());
+ // A code is searched for without its dashes.
+ let code_search = search.as_deref().map(normalize).filter(|c| !c.is_empty());
+ let filter = format!(
+ "FROM promo_codes p LEFT JOIN users u ON u.id = p.redeemed_by \
+ WHERE {condition} AND ($1::text IS NULL OR p.package = $1) \
+ AND ($2::text IS NULL OR p.note ILIKE '%' || $2 || '%' OR u.email ILIKE '%' || $2 || '%' \
+ OR ($3::text IS NOT NULL AND p.code LIKE '%' || $3 || '%'))"
+ );
+ let rows: Vec = sqlx::query_as(&format!(
+ "SELECT p.id, p.code, p.package, p.note, p.created_at, p.redeemed_at, p.revoked_at, u.email, u.display_name \
+ {filter} ORDER BY p.created_at DESC, p.id DESC LIMIT $4 OFFSET $5"
+ ))
+ .bind(&package)
+ .bind(&search)
+ .bind(&code_search)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(&state.db)
+ .await?;
+ let total: i64 = sqlx::query_scalar(&format!("SELECT count(*) {filter}"))
+ .bind(&package)
+ .bind(&search)
+ .bind(&code_search)
+ .fetch_one(&state.db)
+ .await?;
+ let codes: Vec = rows
+ .into_iter()
+ .map(|(id, code, package, note, created, redeemed, revoked, email, name)| {
+ json!({
+ "id": id,
+ "code": display(&code),
+ "package": package,
+ "package_name": packages::find(&package).map(|p| p.name),
+ "note": note,
+ "created_at": rfc3339(created),
+ "redeemed_at": rfc3339_opt(redeemed),
+ "revoked_at": rfc3339_opt(revoked),
+ "redeemed_by": email.map(|e| json!({ "email": e, "name": name })),
+ })
+ })
+ .collect();
+ Ok(Json(json!({ "codes": codes, "total": total, "status": status, "limit": limit, "offset": offset })))
+}
+
+/// Admin: withdraws an unused code.
+pub async fn revoke(State(state): St, _admin: AdminUser, WithRejection(Path(id), _): IdPath) -> ApiResult {
+ let result = sqlx::query(
+ "UPDATE promo_codes SET revoked_at = now() WHERE id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL",
+ )
+ .bind(id)
+ .execute(&state.db)
+ .await?;
+ if result.rows_affected() == 0 {
+ return Err(ApiError::conflict("promo_not_open", "Csak fel nem használt kódot lehet visszavonni."));
+ }
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Redeem {
+ code: String,
+}
+
+/// Redeems a code: the user gets its package. One use per code.
+pub async fn redeem(
+ State(state): St,
+ auth: AuthUser,
+ WithRejection(Json(req), _): Body,
+) -> ApiResult> {
+ let key = format!("promo:{}", auth.id());
+ state.login_limiter.check(&key)?;
+ let code = normalize(&req.code);
+ let mut tx = state.db.begin().await?;
+ let found: Option<(Uuid, String, Option, Option)> =
+ sqlx::query_as("SELECT id, package, redeemed_at, revoked_at FROM promo_codes WHERE code = $1 FOR UPDATE")
+ .bind(&code)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let (id, package_id) = match found {
+ Some((id, package, None, None)) => (id, package),
+ Some((_, _, Some(_), _)) => {
+ state.login_limiter.failed(&key);
+ return Err(ApiError::conflict("promo_used", "Ezt a kódot már felhasználták."));
+ }
+ Some((_, _, _, Some(_))) => {
+ state.login_limiter.failed(&key);
+ return Err(ApiError::conflict("promo_revoked", "Ez a kód már nem érvényes."));
+ }
+ None => {
+ state.login_limiter.failed(&key);
+ return Err(ApiError::conflict("promo_unknown", "Nincs ilyen kód. Ellenőrizd, hogy pontosan írtad-e be."));
+ }
+ };
+ let package = packages::find(&package_id).ok_or(ApiError::NotFound("package"))?;
+ let note = format!("promo code {}", display(&code));
+ let order = packages::grant(&mut tx, auth.id(), package, Source::Promo, None, Some(¬e)).await?;
+ sqlx::query("UPDATE promo_codes SET redeemed_by = $2, redeemed_at = now(), order_id = $3 WHERE id = $1")
+ .bind(id)
+ .bind(auth.id())
+ .bind(order)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ state.login_limiter.succeeded(&key);
+ tracing::info!(user = %auth.id(), package = package.id, "promo code redeemed");
+ let mut body = holdings(&state, &auth).await?;
+ body["package"] = json!({ "id": package.id, "name": package.name });
+ Ok(Json(body))
+}
diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs
index f3aab45..2bf17cf 100644
--- a/services/backend/src/tests.rs
+++ b/services/backend/src/tests.rs
@@ -1839,3 +1839,77 @@ async fn admins_read_the_error_log(pool: PgPool) {
assert_eq!(r.body["attempts"], 0);
assert!(r.body["next_attempt_at"].is_string());
}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn promo_codes_are_made_by_admins_and_redeemed_once(pool: PgPool) {
+ let app = TestApp::new(pool).await;
+ let admin = app.register("admin@example.com", "Admin").await; // BOOTSTRAP_ADMIN_EMAILS
+ let anna = app.register("anna@example.com", "Anna").await;
+ let bela = app.register("bela@example.com", "Béla").await;
+
+ // only admins make codes
+ let r = app.post("/v1/admin/promo-codes", Some(&anna), json!({"package": "single", "count": 1})).await;
+ assert_eq!(r.status, StatusCode::FORBIDDEN);
+ let r = app.post("/v1/admin/promo-codes", Some(&admin), json!({"package": "nincs", "count": 1})).await;
+ assert_eq!(r.status, StatusCode::NOT_FOUND);
+ let r = app
+ .post("/v1/admin/promo-codes", Some(&admin), json!({"package": "single", "count": 3, "note": "meghívottak"}))
+ .await;
+ assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
+ let codes: Vec = r.body["codes"].as_array().unwrap().iter().map(|c| c.as_str().unwrap().into()).collect();
+ assert_eq!(codes.len(), 3);
+ assert!(codes.iter().all(|c| c.len() == 14 && c.matches('-').count() == 2), "{codes:?}");
+
+ // redeemed in any spelling: the package arrives
+ let before = app.get("/v1/me", Some(&anna)).await.body["analyses_left"]["natal"].as_i64().unwrap();
+ let typed = format!(" {} ", codes[0].replace('-', " ").to_lowercase());
+ let r = app.post("/v1/promo-codes/redeem", Some(&anna), json!({"code": typed})).await;
+ assert_eq!(r.status, StatusCode::OK, "{}", r.body);
+ assert_eq!(r.body["package"]["id"], "single");
+ let me = app.get("/v1/me", Some(&anna)).await.body;
+ assert_eq!(me["analyses_left"]["natal"].as_i64(), Some(before + 1));
+ assert_eq!(me["package"]["id"], "single");
+
+ // once only, also for someone else
+ let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": codes[0]})).await;
+ assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("promo_used")));
+ // a withdrawn code and an unknown one do not work
+ let list = app.get("/v1/admin/promo-codes", Some(&admin)).await.body;
+ assert_eq!(list["total"], 2, "unused is the default filter: {list}");
+ let withdrawn = list["codes"].as_array().unwrap().iter().find(|c| c["code"] == codes[1].as_str()).unwrap().clone();
+ let r = app
+ .post(&format!("/v1/admin/promo-codes/{}/revoke", withdrawn["id"].as_str().unwrap()), Some(&admin), json!({}))
+ .await;
+ assert_eq!(r.status, StatusCode::NO_CONTENT);
+ let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": codes[1]})).await;
+ assert_eq!(r.body["error"]["code"], "promo_revoked");
+ let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": "AAAA-BBBB-CCCC"})).await;
+ assert_eq!(r.body["error"]["code"], "promo_unknown");
+
+ // the filters
+ let get = |q: &str| {
+ let uri = format!("/v1/admin/promo-codes?{q}");
+ let app = &app;
+ let admin = &admin;
+ async move { app.get(&uri, Some(admin)).await }
+ };
+ let used = get("status=used").await.body;
+ assert_eq!(
+ (used["total"].as_i64(), &used["codes"][0]["redeemed_by"]["email"]),
+ (Some(1), &json!("anna@example.com"))
+ );
+ assert_eq!(get("status=revoked").await.body["total"], 1);
+ assert_eq!(get("status=all").await.body["total"], 3);
+ assert_eq!(get("status=all&package=addon_questions").await.body["total"], 0);
+ assert_eq!(get("status=all&q=anna@").await.body["total"], 1);
+ assert_eq!(get("status=all&q=megh").await.body["total"], 3);
+ let part = codes[2].split('-').nth(1).unwrap().to_lowercase();
+ assert_eq!(get(&format!("status=unused&q={part}")).await.body["total"], 1);
+
+ // guessing is cut off
+ for _ in 0..10 {
+ app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": "ZZZZ-ZZZZ-ZZZZ"})).await;
+ }
+ let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": codes[2]})).await;
+ assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
+}
diff --git a/services/frontend/src/app/admin/promokodok/PromoCodes.tsx b/services/frontend/src/app/admin/promokodok/PromoCodes.tsx
new file mode 100644
index 0000000..174fa5f
--- /dev/null
+++ b/services/frontend/src/app/admin/promokodok/PromoCodes.tsx
@@ -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 = {
+ 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 (
+ <>
+
+
+ >
+ );
+}
+
+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(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 (
+
+ Új kódok
+
+ {error && (
+
+ {error}
+
+ )}
+ {made && (
+
+
+ {made.codes.length} új kód: {packages.find((p) => p.id === made.package)?.name ?? made.package}
+
+
+
+ {copied ? "Kimásolva" : "Mind másolása"}
+
+
+ )}
+
+ );
+}
+
+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(null);
+ const [total, setTotal] = useState(0);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(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(`/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 (
+
+ Kódok
+
+
+ Állapot
+ setStatus(e.target.value)}>
+ {Object.entries(STATUSES).map(([v, l]) => (
+
+ {l}
+
+ ))}
+
+
+
+ Csomag
+ setPkg(e.target.value)}>
+ mind
+ {packages.map((p) => (
+
+ {p.name}
+
+ ))}
+
+
+
+ Keresés
+ setQ(e.target.value)}
+ placeholder="kód, megjegyzés vagy e-mail"
+ />
+
+
+ {total} kód
+
+
+ {error && (
+
+ {error}
+
+ )}
+ {codes === null ? (
+ Betöltés…
+ ) : codes.length === 0 ? (
+ Nincs ilyen kód.
+ ) : (
+
+
+
+
+ Kód
+ Csomag
+ Megjegyzés
+ Készült
+ Állapot
+
+
+
+
+ {codes.map((c) => (
+
+
+ {c.code}
+
+ {c.package_name ?? c.package}
+ {c.note ?? – }
+ {formatDate(c.created_at)}
+
+ {c.redeemed_at ? (
+ <>
+ beváltva {formatDate(c.redeemed_at, true)}
+ {c.redeemed_by && (
+ {c.redeemed_by.name ? `${c.redeemed_by.name} · ` : ""}{c.redeemed_by.email}
+ )}
+ >
+ ) : c.revoked_at ? (
+ visszavonva {formatDate(c.revoked_at)}
+ ) : (
+ szabad
+ )}
+
+
+ {!c.redeemed_at && !c.revoked_at && (
+ revoke(c)}>
+ Visszavonás
+
+ )}
+
+
+ ))}
+
+
+
+ )}
+ {codes && codes.length < total && (
+ load(codes.length)} disabled={busy}>
+ {busy ? "Betöltés…" : "Továbbiak"}
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/admin/promokodok/page.tsx b/services/frontend/src/app/admin/promokodok/page.tsx
new file mode 100644
index 0000000..e6b77aa
--- /dev/null
+++ b/services/frontend/src/app/admin/promokodok/page.tsx
@@ -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 (
+
+
+
+
Promókódok
+
+ 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.
+
+
+
+
+ );
+}
diff --git a/services/frontend/src/app/bevaltas/page.tsx b/services/frontend/src/app/bevaltas/page.tsx
new file mode 100644
index 0000000..3e6ab0e
--- /dev/null
+++ b/services/frontend/src/app/bevaltas/page.tsx
@@ -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 (
+
+
+
Promókód
+
Promókód beváltása
+
+ Í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.
+
+
+
+
+ );
+}
diff --git a/services/frontend/src/app/csomagok/page.tsx b/services/frontend/src/app/csomagok/page.tsx
index 37b66e1..62b539a 100644
--- a/services/frontend/src/app/csomagok/page.tsx
+++ b/services/frontend/src/app/csomagok/page.tsx
@@ -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() {
+
+ Van promókódod?
+
+ {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."}
+
+
+
+
diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css
index 7a4ac72..b8edad2 100644
--- a/services/frontend/src/app/globals.css
+++ b/services/frontend/src/app/globals.css
@@ -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; } }
diff --git a/services/frontend/src/components/AdminNav.tsx b/services/frontend/src/components/AdminNav.tsx
index 7d646fd..ad8a491 100644
--- a/services/frontend/src/components/AdminNav.tsx
+++ b/services/frontend/src/components/AdminNav.tsx
@@ -3,6 +3,7 @@ import Link from "next/link";
const PAGES = [
{ href: "/admin", label: "Felhasználók" },
{ href: "/admin/meghivok", label: "Meghívók" },
+ { href: "/admin/promokodok", label: "Promókódok" },
{ href: "/admin/promptok", label: "Promptok" },
{ href: "/admin/modellek", label: "Modellek" },
{ href: "/admin/hibak", label: "Hibanapló" },
diff --git a/services/frontend/src/components/AnalysisQuestions.tsx b/services/frontend/src/components/AnalysisQuestions.tsx
index 917be9c..b06aef5 100644
--- a/services/frontend/src/components/AnalysisQuestions.tsx
+++ b/services/frontend/src/components/AnalysisQuestions.tsx
@@ -1,5 +1,6 @@
"use client";
+import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { api, ApiError, errorText } from "@/lib/api";
@@ -218,7 +219,9 @@ export function AnalysisQuestions({
) : (
- Most nincs felhasználható kérdésed. Kérdéseket hamarosan vásárolhatsz.
+
+ Most nincs felhasználható kérdésed. Ha kaptál promókódot, váltsd be.
+
)}
);
diff --git a/services/frontend/src/components/DetailedAnalysis.tsx b/services/frontend/src/components/DetailedAnalysis.tsx
index 7b340d0..6dfe4e0 100644
--- a/services/frontend/src/components/DetailedAnalysis.tsx
+++ b/services/frontend/src/components/DetailedAnalysis.tsx
@@ -273,7 +273,10 @@ export function DetailedAnalysis({
Példa megtekintése
)}
- A részletes elemzés fizetős; a csomagok hamarosan elérhetők.
+
+ Promókód beváltása
+
+ A részletes elemzéshez csomag kell. Ha kaptál promókódot, váltsd be.
)}
diff --git a/services/frontend/src/components/RedeemCode.tsx b/services/frontend/src/components/RedeemCode.tsx
new file mode 100644
index 0000000..cc89021
--- /dev/null
+++ b/services/frontend/src/components/RedeemCode.tsx
@@ -0,0 +1,77 @@
+"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(null);
+ const [got, setGot] = useState(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 (
+
+ );
+}
diff --git a/services/frontend/src/components/SiteHeader.tsx b/services/frontend/src/components/SiteHeader.tsx
index c367baf..e625797 100644
--- a/services/frontend/src/components/SiteHeader.tsx
+++ b/services/frontend/src/components/SiteHeader.tsx
@@ -58,6 +58,9 @@ export function SiteHeader({ me }: { me: Me }) {
+
+ Kód beváltása
+
{me.user.display_name || me.user.email}
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index 2d3ce28..b0aa94b 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -526,3 +526,17 @@ export interface ForecastDetail extends ForecastSummary {
location: { country: string; place?: string; geonames_id?: number } | null;
result: { year: number; solar_return: SolarReturn | null; forecast: Forecast };
}
+
+/** A promo code on the admin page (`GET /v1/admin/promo-codes`). */
+export interface PromoCode {
+ id: string;
+ /** ABCD-EFGH-JKLM */
+ code: string;
+ package: string;
+ package_name: string | null;
+ note: string | null;
+ created_at: string;
+ redeemed_at: string | null;
+ revoked_at: string | null;
+ redeemed_by: { email: string; name: string | null } | null;
+}