//! 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}; 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::credits::Unit; use crate::error::{ApiError, ApiResult}; use crate::packages; 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. pub(super) 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() } /// 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 { 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(); 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"); 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"))?; 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)) }