2026-11-19 09:57:01 +00:00
|
|
|
|
//! 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.
|
2026-11-19 09:45:42 +00:00
|
|
|
|
|
|
|
|
|
|
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};
|
2026-11-19 09:57:01 +00:00
|
|
|
|
use crate::credits::Unit;
|
2026-11-19 09:45:42 +00:00
|
|
|
|
use crate::error::{ApiError, ApiResult};
|
2026-11-19 09:57:01 +00:00
|
|
|
|
use crate::packages;
|
2026-11-19 09:45:42 +00:00
|
|
|
|
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.
|
2026-11-19 09:57:01 +00:00
|
|
|
|
pub(super) fn display(code: &str) -> String {
|
2026-11-19 09:45:42 +00:00
|
|
|
|
code.as_bytes().chunks(4).map(|c| String::from_utf8_lossy(c).into_owned()).collect::<Vec<_>>().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()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-19 09:57:01 +00:00
|
|
|
|
/// 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<Uuid>,
|
|
|
|
|
|
invitation_id: Option<Uuid>,
|
|
|
|
|
|
) -> Result<String, sqlx::Error> {
|
|
|
|
|
|
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<i64>,
|
|
|
|
|
|
) -> Result<Option<Vec<(Unit, i64)>>, 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))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-19 09:45:42 +00:00
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
|
|
#[serde(deny_unknown_fields)]
|
|
|
|
|
|
pub struct NewCodes {
|
|
|
|
|
|
package: String,
|
|
|
|
|
|
count: i64,
|
|
|
|
|
|
note: Option<String>,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Admin: makes `count` new codes for a package.
|
|
|
|
|
|
pub async fn create(
|
|
|
|
|
|
State(state): St,
|
|
|
|
|
|
admin: AdminUser,
|
|
|
|
|
|
WithRejection(Json(req), _): Body<NewCodes>,
|
|
|
|
|
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
|
|
|
|
|
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::<String>()).filter(|n| !n.is_empty());
|
|
|
|
|
|
let mut tx = state.db.begin().await?;
|
|
|
|
|
|
let mut codes = Vec::new();
|
2026-11-19 09:57:01 +00:00
|
|
|
|
for _ in 0..req.count {
|
|
|
|
|
|
codes.push(display(&new_code(&mut tx, package.id, note.as_deref(), Some(admin.0.id()), None).await?));
|
2026-11-19 09:45:42 +00:00
|
|
|
|
}
|
|
|
|
|
|
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<String>,
|
|
|
|
|
|
package: Option<String>,
|
|
|
|
|
|
/// Part of the code, the note or the redeemer's e-mail.
|
|
|
|
|
|
q: Option<String>,
|
|
|
|
|
|
limit: Option<i64>,
|
|
|
|
|
|
offset: Option<i64>,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type Row = (
|
|
|
|
|
|
Uuid,
|
|
|
|
|
|
String,
|
|
|
|
|
|
String,
|
|
|
|
|
|
Option<String>,
|
|
|
|
|
|
OffsetDateTime,
|
|
|
|
|
|
Option<OffsetDateTime>,
|
|
|
|
|
|
Option<OffsetDateTime>,
|
|
|
|
|
|
Option<String>,
|
|
|
|
|
|
Option<String>,
|
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
/// Admin: the codes, newest first, filtered.
|
|
|
|
|
|
pub async fn list(
|
|
|
|
|
|
State(state): St,
|
|
|
|
|
|
_admin: AdminUser,
|
|
|
|
|
|
WithRejection(Query(query), _): WithRejection<Query<CodeQuery>, ApiError>,
|
|
|
|
|
|
) -> ApiResult<Json<Value>> {
|
|
|
|
|
|
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<Row> = 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<Value> = 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<StatusCode> {
|
|
|
|
|
|
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<Redeem>,
|
|
|
|
|
|
) -> ApiResult<Json<Value>> {
|
|
|
|
|
|
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<OffsetDateTime>, Option<OffsetDateTime>)> =
|
|
|
|
|
|
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"))?;
|
2026-11-19 09:57:01 +00:00
|
|
|
|
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
|
|
|
|
|
|
),
|
|
|
|
|
|
));
|
|
|
|
|
|
};
|
2026-11-19 09:45:42 +00:00
|
|
|
|
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 });
|
2026-11-19 09:57:01 +00:00
|
|
|
|
body["added"] = added.iter().map(|(unit, n)| (unit.as_str().to_string(), json!(n))).collect();
|
2026-11-19 09:45:42 +00:00
|
|
|
|
Ok(Json(body))
|
|
|
|
|
|
}
|