From 7b23d71526ccec739d83410e0fd2624da5d10a49 Mon Sep 17 00:00:00 2001 From: feco Date: Thu, 19 Nov 2026 09:57:01 +0000 Subject: [PATCH] Invitations with a package; promo codes fill up the balance An admin can pick a package when inviting: each invitee gets a promo code (in the e-mail and its preview, kept on resend), redeemed by itself at sign up; revoking the invitation withdraws it, and the list shows the package. Redeeming a promo code now fills the units up to the package's amounts: used units come back, more than that stays. A code that would add nothing stays open, with a message saying so; the answer tells what was added. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- .../db/migrations/0023_invitation_package.sql | 3 + crates/email-templates/src/lib.rs | 32 ++++- docs/promokodok.md | 19 ++- services/backend/src/packages.rs | 69 +++++++++-- services/backend/src/persons.rs | 14 +++ services/backend/src/routes/auth.rs | 18 ++- services/backend/src/routes/invitations.rs | 103 +++++++++++++++-- services/backend/src/routes/promo.rs | 109 +++++++++++++----- services/backend/src/tests.rs | 82 +++++++++++++ .../app/admin/meghivok/AdminInvitations.tsx | 35 +++++- services/frontend/src/app/bevaltas/page.tsx | 4 +- .../frontend/src/components/RedeemCode.tsx | 32 ++++- services/frontend/src/lib/types.ts | 4 + 13 files changed, 458 insertions(+), 66 deletions(-) create mode 100644 crates/db/migrations/0023_invitation_package.sql diff --git a/crates/db/migrations/0023_invitation_package.sql b/crates/db/migrations/0023_invitation_package.sql new file mode 100644 index 0000000..7336315 --- /dev/null +++ b/crates/db/migrations/0023_invitation_package.sql @@ -0,0 +1,3 @@ +-- An invitation can come with a package: a promo code made with it, sent in +-- the e-mail and redeemed by itself when the invitee signs up. +ALTER TABLE promo_codes ADD COLUMN invitation_id uuid UNIQUE REFERENCES invitations (id) ON DELETE SET NULL; diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index a5305ea..320fbf6 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -173,6 +173,26 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result()) + .filter(|c| !c.is_empty()), + ); + let gift_line = |hu: bool| { + gift.as_ref().map(|(package, code)| { + if hu { + format!( + " Ajándékba egy „{package}” csomagot is kapsz: a regisztrációval magától jóváíródik. Ha mégis kellene, a promókódod: {code}." + ) + } else { + format!( + " You also get the “{package}” package as a gift: it is added when you sign up. Should you need it, your promo code is {code}." + ) + } + }) + }; Ok(match lang { Lang::Hu => Content { subject: match &inviter { @@ -188,7 +208,7 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result { "Meghívót kaptál a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.".into() } - }, + } + &gift_line(true).unwrap_or_default(), quote: message, points: Some(( "Mit találsz ott?", @@ -226,7 +246,7 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result format!("{n} invited you to Sorsfonalak. The site is invitation-only for now."), None => "You are invited to Sorsfonalak. The site is invitation-only for now.".into(), - }, + } + &gift_line(false).unwrap_or_default(), quote: message, points: Some(( "What you will find there:", @@ -468,6 +488,14 @@ mod tests { assert!(en.text.contains("valid until 17 December 2026") && !en.text.contains("> ")); assert!(!en.html.contains("border-left")); + let mut gift = invitation_payload(); + gift["package_name"] = json!("Páros"); + gift["promo_code"] = json!("ABCD-EFGH-JKLM"); + let hu = render("invitation", "hu", &gift).unwrap(); + assert!(hu.text.contains("Ajándékba egy „Páros” csomagot is kapsz"), "{}", hu.text); + assert!(hu.html.contains("ABCD-EFGH-JKLM")); + assert!(!render("invitation", "hu", &invitation_payload()).unwrap().text.contains("Ajándék")); + let mut broken = invitation_payload(); broken["unsubscribe_url"] = Value::Null; assert_eq!(render("invitation", "hu", &broken), Err(TemplateError::MissingField("unsubscribe_url"))); diff --git a/docs/promokodok.md b/docs/promokodok.md index 0205d0e..4a9b4d4 100644 --- a/docs/promokodok.md +++ b/docs/promokodok.md @@ -22,10 +22,24 @@ Amíg a fizetés nincs bekötve, a csomagokat promókóddal (és admin ajándék - 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. +- **Beváltás = feltöltés:** a kód nem hozzáad, hanem **feltölti** az egyenleget a csomag szintjéig. Minden egységnél (képletelemzés, kapcsolati elemzés, előrejelzés, kérdés, szabad személyhely) az új egyenleg a csomag mennyisége lesz, ha addig kevesebb volt. + - Ami elhasznált belőle, visszajön; ami ennél több van (például vett hozzá), megmarad. + - Példa: a „Páros” csomag 2 képletelemzést ad. Ha valakinek 0 maradt, 2 lesz; ha 5 van, 5 marad. + - Ha a felhasználónak már mindenből megvan a csomag mennyisége, a kódot nem váltjuk be (megmarad későbbre), és ezt üzenetben meg is mondjuk. + - Könyvelés: egy `package_orders` sor `promo` forrással, 0 Ft-tal, és `credit_ledger` sorok csak a ténylegesen hozzáadott mennyiségekkel. A válaszban az `added` mező mondja meg, mi került hozzá. - **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. +## Meghívó csomaggal + +Az Admin → Meghívók oldalon az „Ajándék csomag” választóval minden meghívott kap egy promókódot a választott csomagra (megjegyzés: „meghívó: ”). + +- **A levélben** benne van a csomag neve és a kód. A levél előnézete is mutatja (minta kóddal). +- **Regisztrációkor** a kód magától beváltódik, ugyanazzal a feltöltéssel, mint a kézi beváltásnál. Ha mégsem, a kód kézzel is beváltható. +- **Újraküldéskor** a levélben ugyanaz a kód marad. +- **Visszavonás:** a meghívó visszavonása a még fel nem használt kódot is visszavonja. +- **A meghívók listájában** látszik a csomag, és hogy beváltották-e. + ## API | Végpont | Ki | Mit csinál | @@ -33,4 +47,5 @@ Amíg a fizetés nincs bekötve, a csomagokat promókóddal (és admin ajándék | `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 | +| `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | beváltás (feltöltés); a válaszban az új egyenleg, a csomag és az `added` | +| `POST /v1/admin/invitations` `{emails, message?, locale?, package?}` | admin | meghívó, opcionálisan csomaggal | diff --git a/services/backend/src/packages.rs b/services/backend/src/packages.rs index 30c3466..939a277 100644 --- a/services/backend/src/packages.rs +++ b/services/backend/src/packages.rs @@ -198,7 +198,20 @@ impl Source { } } -/// Records an order and gives its contents, inside the caller's transaction. +impl Package { + /// What the package gives, unit by unit. + pub fn contents(&self) -> [(Unit, i64); 5] { + [ + (Unit::Natal, self.natal), + (Unit::Synastry, self.synastry), + (Unit::Forecast, self.forecast), + (Unit::Person, self.persons), + (Unit::Question, self.questions), + ] + } +} + +/// Records an order and adds its contents, inside the caller's transaction. pub async fn grant( tx: &mut PgConnection, user_id: Uuid, @@ -206,6 +219,51 @@ pub async fn grant( source: Source, created_by: Option, note: Option<&str>, +) -> Result { + record(tx, user_id, package, source, created_by, note, &package.contents()).await +} + +/// Fills the user's units up to what the package gives (promo codes): a unit +/// below the package's amount is raised to it, used units come back, more +/// than that stays as it is. `persons_left` is the free person slots now +/// (`None`: unlimited, nothing to add). Returns the order and what was added +/// (nothing at all: no order is recorded). +pub async fn top_up( + tx: &mut PgConnection, + user_id: Uuid, + package: &Package, + persons_left: Option, + note: Option<&str>, +) -> Result)>, ApiError> { + sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user_id).execute(&mut *tx).await?; + let balance = crate::credits::balance(tx, user_id).await?; + let added: Vec<(Unit, i64)> = package + .contents() + .into_iter() + .map(|(unit, n)| { + let have = match unit { + Unit::Person => persons_left.unwrap_or(i64::MAX), + unit => balance.of(unit), + }; + (unit, (n - have).max(0)) + }) + .filter(|&(_, n)| n > 0) + .collect(); + if added.is_empty() { + return Ok(None); + } + let order = record(tx, user_id, package, Source::Promo, None, note, &added).await?; + Ok(Some((order, added))) +} + +async fn record( + tx: &mut PgConnection, + user_id: Uuid, + package: &Package, + source: Source, + created_by: Option, + note: Option<&str>, + contents: &[(Unit, i64)], ) -> Result { let order = Uuid::now_v7(); let price = match source { @@ -225,14 +283,7 @@ pub async fn grant( .bind(created_by) .execute(&mut *tx) .await?; - let contents = [ - (Unit::Natal, package.natal), - (Unit::Synastry, package.synastry), - (Unit::Forecast, package.forecast), - (Unit::Person, package.persons), - (Unit::Question, package.questions), - ]; - for (unit, n) in contents { + for &(unit, n) in contents { if n == 0 { continue; } diff --git a/services/backend/src/persons.rs b/services/backend/src/persons.rs index 266abca..6de5ae7 100644 --- a/services/backend/src/persons.rs +++ b/services/backend/src/persons.rs @@ -62,6 +62,20 @@ pub async fn slots(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Resul Ok(Slots { used, granted: free + bought, unlimited: entitled || auth.user.has_role(Role::Admin) }) } +/// The free person slots of a user without unlimited slots (for topping up). +pub async fn left(conn: &mut PgConnection, user_id: Uuid, free: i64) -> Result { + let (used, bought): (i64, i64) = sqlx::query_as( + "SELECT \ + (SELECT COUNT(*) FROM credit_ledger WHERE user_id = $1 AND unit = 'person' AND reason = 'person'), \ + (SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger \ + WHERE user_id = $1 AND unit = 'person' AND reason <> 'person')", + ) + .bind(user_id) + .fetch_one(conn) + .await?; + Ok((free + bought - used).max(0)) +} + /// Fails when no slot is left (a quick check before calculating a chart). pub async fn check(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Result<(), ApiError> { if slots(conn, auth, free).await?.left() == Some(0) { diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs index 9ac9888..e0576bc 100644 --- a/services/backend/src/routes/auth.rs +++ b/services/backend/src/routes/auth.rs @@ -216,7 +216,14 @@ pub async fn register( .bind(&email) .execute(&mut *tx) .await?; - super::invitations::mark_accepted(&mut tx, user_id, &email, req.invite_token.as_deref()).await?; + super::invitations::mark_accepted( + &mut tx, + user_id, + &email, + req.invite_token.as_deref(), + state.config.free_person_slots, + ) + .await?; let mut user = load_user(&mut tx, user_id).await?; apply_bootstrap_admin(&state, &mut tx, &mut user).await?; queue_verification(&state, &mut tx, &user).await?; @@ -347,7 +354,14 @@ pub async fn google( .bind(locale) .execute(&mut *tx) .await?; - super::invitations::mark_accepted(&mut tx, id, &email, req.invite_token.as_deref()).await?; + super::invitations::mark_accepted( + &mut tx, + id, + &email, + req.invite_token.as_deref(), + state.config.free_person_slots, + ) + .await?; (id, true) } }; diff --git a/services/backend/src/routes/invitations.rs b/services/backend/src/routes/invitations.rs index 9440dd9..e62b731 100644 --- a/services/backend/src/routes/invitations.rs +++ b/services/backend/src/routes/invitations.rs @@ -7,6 +7,10 @@ //! //! People who asked for no more invitations are kept as the hash of their //! address. People without an invitation can join the waitlist. +//! +//! An invitation can come with a package: a promo code is made with it, the +//! e-mail shows it with its redeem link, and it is redeemed by itself when +//! the invitee signs up (revoking the invitation withdraws it). use axum::Json; use axum::extract::{Path, Query, State}; @@ -24,8 +28,12 @@ use crate::AppState; use crate::auth::AdminUser; use crate::config::SignupMode; use crate::error::{ApiError, ApiResult}; +use crate::packages; use crate::views::{rfc3339, rfc3339_opt}; +/// The package of an invitation, as shown in its e-mail: (code as shown, package name). +type Gift = (String, &'static str); + pub const INVITATION_TTL: time::Duration = time::Duration::days(30); /// A resend is possible this often, and at most this many sendings in all. const RESEND_GAP: time::Duration = time::Duration::hours(24); @@ -68,12 +76,15 @@ pub async fn admit( } } -/// After a new account is created: its invitations count as accepted, and it leaves the waitlist. +/// After a new account is created: its invitations count as accepted, it +/// leaves the waitlist, and the packages of those invitations are redeemed +/// (`free_slots`: the person slots everyone gets). pub async fn mark_accepted( conn: &mut PgConnection, user_id: Uuid, email: &str, token: Option<&str>, + free_slots: i64, ) -> Result<(), ApiError> { let hash = token.map(|t| db::token_hash(t.trim())); sqlx::query( @@ -87,9 +98,33 @@ pub async fn mark_accepted( .execute(&mut *conn) .await?; sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(email).execute(&mut *conn).await?; + let codes: Vec<(Uuid, String, String)> = sqlx::query_as( + "SELECT p.id, p.code, p.package FROM promo_codes p JOIN invitations i ON i.id = p.invitation_id \ + WHERE i.accepted_by = $1 AND p.redeemed_at IS NULL AND p.revoked_at IS NULL FOR UPDATE OF p", + ) + .bind(user_id) + .fetch_all(&mut *conn) + .await?; + for (id, code, package) in codes { + let Some(package) = packages::find(&package) else { continue }; + let persons_left = crate::persons::left(conn, user_id, free_slots).await?; + super::promo::redeem_code(conn, id, &code, package, user_id, Some(persons_left)).await?; + tracing::info!(user = %user_id, package = package.id, "invitation package redeemed"); + } Ok(()) } +/// The open promo code of an invitation, for its e-mail. +async fn gift_of(conn: &mut PgConnection, invitation_id: Uuid) -> Result, sqlx::Error> { + let row: Option<(String, String)> = sqlx::query_as( + "SELECT code, package FROM promo_codes WHERE invitation_id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL", + ) + .bind(invitation_id) + .fetch_optional(conn) + .await?; + Ok(row.and_then(|(code, package)| packages::find(&package).map(|p| (super::promo::display(&code), p.name)))) +} + // --- sending --------------------------------------------------------------------------------- fn clean_message(message: Option) -> Result, ApiError> { @@ -122,9 +157,14 @@ fn payload( inviter: Option<&str>, message: Option<&str>, expires: OffsetDateTime, + gift: Option<&Gift>, ) -> Value { let (url, unsubscribe_url, unsubscribe_post_url) = links(state, token); + let base = &state.config.public_base_url; json!({ + "package_name": gift.map(|g| g.1), + "promo_code": gift.map(|g| g.0.as_str()), + "redeem_url": gift.map(|g| format!("{base}/bevaltas?kod={}", g.0)), "url": url, "unsubscribe_url": unsubscribe_url, "unsubscribe_post_url": unsubscribe_post_url, @@ -145,6 +185,7 @@ async fn send( inviter: Option<&str>, message: Option<&str>, expires: OffsetDateTime, + gift: Option<&Gift>, ) -> Result { let token = db::new_token(); sqlx::query("INSERT INTO invitation_tokens (token_hash, invitation_id) VALUES ($1, $2)") @@ -152,7 +193,7 @@ async fn send( .bind(id) .execute(&mut *conn) .await?; - let payload = payload(state, &token, inviter, message, expires); + let payload = payload(state, &token, inviter, message, expires, gift); let url = payload["url"].as_str().unwrap_or_default().to_owned(); queue_email_to(conn, None, email, "invitation", locale, payload).await?; Ok(url) @@ -173,6 +214,8 @@ pub struct CreateInvitations { emails: Vec, message: Option, locale: Option, + /// A package from the catalog the invitees get (as a promo code). + package: Option, } /// Invites a list of addresses. Each gets a result: `invited` (with the @@ -188,6 +231,10 @@ pub async fn create( } let message = clean_message(req.message)?; let locale = validate_locale(&state, req.locale.as_deref())?; + let package = match req.package.as_deref().filter(|p| !p.is_empty()) { + Some(id) => Some(packages::find(id).ok_or(ApiError::NotFound("package"))?), + None => None, + }; let inviter = admin.user.display_name.clone(); let mut results = Vec::new(); let mut seen = std::collections::HashSet::new(); @@ -240,8 +287,20 @@ pub async fn create( results.push(json!({ "email": email, "status": "already_invited" })); continue; } - let url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires).await?; - results.push(json!({ "email": email, "status": "invited", "id": id, "url": url })); + let gift = match package { + Some(p) => { + let note = format!("meghívó: {email}"); + let code = super::promo::new_code(&mut tx, p.id, Some(¬e), Some(admin.id()), Some(id)).await?; + Some((super::promo::display(&code), p.name)) + } + None => None, + }; + let url = + send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires, gift.as_ref()) + .await?; + results.push(json!({ + "email": email, "status": "invited", "id": id, "url": url, "promo_code": gift.as_ref().map(|g| &g.0), + })); } tx.commit().await?; Ok((StatusCode::CREATED, Json(json!({ "results": results })))) @@ -265,6 +324,9 @@ struct Row { mail_sent_at: Option, mail_failed_at: Option, mail_error: Option, + promo_code: Option, + promo_package: Option, + promo_redeemed_at: Option, } fn status(accepted: Option, revoked: Option, expires: OffsetDateTime) -> &'static str { @@ -285,8 +347,10 @@ pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> "SELECT i.id, i.email, i.message, i.locale, i.created_at, i.expires_at, i.sent_count, i.last_sent_at, \ i.accepted_at, i.revoked_at, inv.display_name AS invited_by_name, \ coalesce(acc.display_name, acc.email) AS accepted_by_name, \ - m.created_at AS mail_created_at, m.sent_at AS mail_sent_at, m.failed_at AS mail_failed_at, m.last_error AS mail_error \ + m.created_at AS mail_created_at, m.sent_at AS mail_sent_at, m.failed_at AS mail_failed_at, m.last_error AS mail_error, \ + pc.code AS promo_code, pc.package AS promo_package, pc.redeemed_at AS promo_redeemed_at \ FROM invitations i \ + LEFT JOIN promo_codes pc ON pc.invitation_id = i.id \ LEFT JOIN users inv ON inv.id = i.invited_by \ LEFT JOIN users acc ON acc.id = i.accepted_by \ LEFT JOIN LATERAL (SELECT created_at, sent_at, failed_at, last_error FROM email_outbox \ @@ -318,6 +382,12 @@ pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> "accepted_at": rfc3339_opt(r.accepted_at), "accepted_by": r.accepted_by_name, "invited_by": r.invited_by_name, "mail": mail, "mail_error": r.mail_error, "can_resend": can_resend, + "package": r.promo_package.as_deref().map(|p| json!({ + "id": p, + "name": packages::find(p).map(|p| p.name), + "code": r.promo_code.as_deref().map(super::promo::display), + "redeemed_at": rfc3339_opt(r.promo_redeemed_at), + })), }) }) .collect(); @@ -391,22 +461,34 @@ pub async fn resend( .execute(&mut *tx) .await?; let inviter = admin.user.display_name.clone(); - let url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires).await?; + let gift = gift_of(&mut tx, id).await?; + let url = + send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires, gift.as_ref()) + .await?; tx.commit().await?; Ok(Json(json!({ "id": id, "url": url, "expires_at": rfc3339(expires) }))) } pub async fn revoke(State(state): St, _admin: AdminUser, WithRejection(Path(id), _): IdPath) -> ApiResult { + let mut tx = state.db.begin().await?; let done = sqlx::query( "UPDATE invitations SET revoked_at = now() WHERE id = $1 AND accepted_at IS NULL AND revoked_at IS NULL", ) .bind(id) - .execute(&state.db) + .execute(&mut *tx) .await? .rows_affected(); if done == 0 { return Err(ApiError::NotFound("open invitation")); } + // Its package goes with it. + sqlx::query( + "UPDATE promo_codes SET revoked_at = now() WHERE invitation_id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL", + ) + .bind(id) + .execute(&mut *tx) + .await?; + tx.commit().await?; Ok(StatusCode::NO_CONTENT) } @@ -427,6 +509,8 @@ pub struct PreviewRequest { /// Also send it to the admin's own address. #[serde(default)] send_to_me: bool, + /// Show it with this package (a sample code). + package: Option, } /// The invitation e-mail with sample links (they lead nowhere), and @@ -438,12 +522,17 @@ pub async fn preview( ) -> ApiResult> { let message = clean_message(req.message)?; let locale = validate_locale(&state, req.locale.as_deref())?; + let gift = match req.package.as_deref().filter(|p| !p.is_empty()) { + Some(id) => Some(("MINT-AKOD-XXXX".to_string(), packages::find(id).ok_or(ApiError::NotFound("package"))?.name)), + None => None, + }; let payload = payload( &state, "minta", admin.user.display_name.as_deref(), message.as_deref(), OffsetDateTime::now_utc() + INVITATION_TTL, + gift.as_ref(), ); let mail = email_templates::render("invitation", &locale, &payload) .map_err(|e| ApiError::Internal(format!("invitation template: {e}")))?; diff --git a/services/backend/src/routes/promo.rs b/services/backend/src/routes/promo.rs index 8ddfd40..060ecb4 100644 --- a/services/backend/src/routes/promo.rs +++ b/services/backend/src/routes/promo.rs @@ -1,7 +1,9 @@ -//! 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. +//! Promo codes. An admin makes a batch for one package (or one comes with an +//! invitation); a logged-in user redeems a code once. Redeeming fills the +//! user's units up to the package's amounts (used ones come back, more than +//! that stays), recorded as 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}; @@ -15,8 +17,9 @@ use uuid::Uuid; use super::payments::holdings; use super::{Body, IdPath, St}; use crate::auth::{AdminUser, AuthUser}; +use crate::credits::Unit; use crate::error::{ApiError, ApiResult}; -use crate::packages::{self, Source}; +use crate::packages; use crate::views::{rfc3339, rfc3339_opt}; /// Characters of a code (12 × ~5 bits: not guessable within the rate limit). @@ -24,7 +27,7 @@ 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 { +pub(super) fn display(code: &str) -> String { code.as_bytes().chunks(4).map(|c| String::from_utf8_lossy(c).into_owned()).collect::>().join("-") } @@ -33,6 +36,60 @@ fn normalize(input: &str) -> String { input.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_uppercase()).collect() } +/// Makes one code for a package inside the caller's transaction; returns the stored code. +pub(super) async fn new_code( + tx: &mut sqlx::PgConnection, + package: &str, + note: Option<&str>, + created_by: Option, + invitation_id: Option, +) -> Result { + loop { + let code = db::random_code(CODE_LEN); + // A clash is practically impossible; another code is drawn if it happens. + let inserted = sqlx::query( + "INSERT INTO promo_codes (id, code, package, note, created_by, invitation_id) \ + VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (code) DO NOTHING", + ) + .bind(Uuid::now_v7()) + .bind(&code) + .bind(package) + .bind(note) + .bind(created_by) + .bind(invitation_id) + .execute(&mut *tx) + .await? + .rows_affected(); + if inserted == 1 { + return Ok(code); + } + } +} + +/// Redeems an open code for the user inside the caller's transaction (the +/// code row must be locked). Returns what was added; `None`: the user already +/// has everything the package gives, the code stays open. +pub(super) async fn redeem_code( + tx: &mut sqlx::PgConnection, + code_id: Uuid, + code: &str, + package: &packages::Package, + user_id: Uuid, + persons_left: Option, +) -> Result>, ApiError> { + let note = format!("promo code {}", display(code)); + let Some((order, added)) = packages::top_up(tx, user_id, package, persons_left, Some(¬e)).await? else { + return Ok(None); + }; + sqlx::query("UPDATE promo_codes SET redeemed_by = $2, redeemed_at = now(), order_id = $3 WHERE id = $1") + .bind(code_id) + .bind(user_id) + .bind(order) + .execute(&mut *tx) + .await?; + Ok(Some(added)) +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct NewCodes { @@ -54,24 +111,8 @@ pub async fn create( 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)); - } + for _ in 0..req.count { + codes.push(display(&new_code(&mut tx, package.id, note.as_deref(), Some(admin.0.id()), None).await?)); } tx.commit().await?; tracing::info!(admin = %admin.0.id(), package = package.id, count = codes.len(), "promo codes created"); @@ -215,18 +256,22 @@ pub async fn redeem( } }; 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?; + sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?; + let persons_left = crate::persons::slots(&mut tx, &auth, state.config.free_person_slots).await?.left(); + let Some(added) = redeem_code(&mut tx, id, &code, package, auth.id(), persons_left).await? else { + return Err(ApiError::conflict( + "promo_nothing_to_add", + format!( + "Most is megvan minden, amit ez a kód adna ({}), ezért nem váltottuk be. Tedd el későbbre.", + package.name + ), + )); + }; 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 }); + body["added"] = added.iter().map(|(unit, n)| (unit.as_str().to_string(), json!(n))).collect(); Ok(Json(body)) } diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 2bf17cf..0a63774 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -1913,3 +1913,85 @@ async fn promo_codes_are_made_by_admins_and_redeemed_once(pool: PgPool) { let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": codes[2]})).await; assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn an_invitation_brings_its_package_and_codes_fill_up(pool: PgPool) { + let app = TestApp::with_config(pool.clone(), |c| c.signup_mode = crate::config::SignupMode::Invite).await; + let admin = app.register("admin@example.com", "Admin").await; + let r = app + .post( + "/v1/admin/invitations", + Some(&admin), + json!({"emails": ["guest@example.com", "other@example.com"], "package": "couple"}), + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + let guest = &r.body["results"][0]; + let guest_token = invite_token(guest["url"].as_str().unwrap()); + let other_id = r.body["results"][1]["id"].as_str().unwrap().to_string(); + + // the e-mail shows the package and its code + let (payload,): (Value,) = sqlx::query_as( + "SELECT payload FROM email_outbox WHERE to_email = 'guest@example.com' AND template = 'invitation'", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(payload["package_name"], "Páros"); + assert_eq!(payload["promo_code"], guest["promo_code"]); + assert!( + payload["redeem_url"] + .as_str() + .unwrap() + .ends_with(&format!("/bevaltas?kod={}", guest["promo_code"].as_str().unwrap())) + ); + let list = app.get("/v1/admin/invitations", Some(&admin)).await.body; + assert_eq!(list["invitations"][0]["package"]["name"], "Páros"); + + // revoking an invitation withdraws its code + let r = app.call("DELETE", &format!("/v1/admin/invitations/{other_id}"), Some(&admin), None).await; + assert_eq!(r.status, StatusCode::NO_CONTENT); + let codes = app.get("/v1/admin/promo-codes?status=revoked", Some(&admin)).await.body; + assert_eq!((codes["total"].as_i64(), &codes["codes"][0]["note"]), (Some(1), &json!("meghívó: other@example.com"))); + + // signing up redeems it by itself + let r = google_signup(&app, "g-guest", "guest@example.com", Some(&guest_token)).await; + assert!(r.status.is_success(), "{}", r.body); + let token = r.body["token"].as_str().map(str::to_string).unwrap_or_else(|| { + let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap(); + cookie.split(';').next().unwrap().split('=').nth(1).unwrap().to_string() + }); + let me = app.get("/v1/me", Some(&token)).await.body; + let left = &me["analyses_left"]; + assert_eq!( + (left["natal"].as_i64(), left["synastry"].as_i64(), left["forecast"].as_i64()), + (Some(2), Some(1), Some(2)), + "{me}" + ); + assert_eq!(me["package"]["id"], "couple"); + let used = app.get("/v1/admin/promo-codes?status=used", Some(&admin)).await.body; + assert_eq!(used["codes"][0]["redeemed_by"]["email"], "guest@example.com"); + + // a code fills up: nothing to add while everything is there… + let r = app.post("/v1/admin/promo-codes", Some(&admin), json!({"package": "couple", "count": 1})).await; + let spare = r.body["codes"][0].as_str().unwrap().to_string(); + let r = app.post("/v1/promo-codes/redeem", Some(&token), json!({"code": spare})).await; + assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("promo_nothing_to_add"))); + // …used units come back, extra ones stay + sqlx::query( + "INSERT INTO credit_ledger (id, user_id, unit, delta, reason) \ + SELECT gen_random_uuid(), id, unit, delta, 'admin_adjust' FROM users, \ + (VALUES ('natal', -2), ('forecast', 3)) AS v(unit, delta) WHERE email = 'guest@example.com'", + ) + .execute(&pool) + .await + .unwrap(); + let r = app.post("/v1/promo-codes/redeem", Some(&token), json!({"code": spare})).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(r.body["added"], json!({"natal": 2})); + let left = &app.get("/v1/me", Some(&token)).await.body["analyses_left"]; + assert_eq!( + (left["natal"].as_i64(), left["synastry"].as_i64(), left["forecast"].as_i64()), + (Some(2), Some(1), Some(5)) + ); +} diff --git a/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx b/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx index 3bcba3a..90b281c 100644 --- a/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx +++ b/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react"; +import { usePackages } from "@/components/PackageCards"; import { api, errorText } from "@/lib/api"; import { formatDate } from "@/lib/astro"; import type { AdminInvitation, InvitationResult, WaitlistEntry } from "@/lib/types"; @@ -104,6 +105,8 @@ function InviteForm({ onSent }: { onSent: () => Promise }) { const [emails, setEmails] = useState(""); const [message, setMessage] = useState(""); const [locale, setLocale] = useState("hu"); + const [pkg, setPkg] = useState(""); + const packages = usePackages(); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [results, setResults] = useState(null); @@ -116,7 +119,7 @@ function InviteForm({ onSent }: { onSent: () => Promise }) { setResults(null); try { const res = await api<{ results: InvitationResult[] }>("/admin/invitations", { - body: { emails: parseEmails(emails), message: message.trim() || null, locale }, + body: { emails: parseEmails(emails), message: message.trim() || null, locale, package: pkg || null }, }); setResults(res.results); if (res.results.some((r) => r.status === "invited")) setEmails(""); @@ -163,6 +166,17 @@ function InviteForm({ onSent }: { onSent: () => Promise }) {
+
+ + +