Files
sorsfonalak/services/backend/src/routes/promo.rs
T
fecoandClaude Opus 5.5 c90232f40c Gift packages: buy a main package for someone, with a printable gift card
- /ajandek: the package, whom it is for and from whom, the recipient's
  address typed twice (or "I hand it over"), a message; paid on Stripe
  like any package, the invoice is the buyer's
- On payment the gift gets its own code (not a promo code: it cannot be
  withdrawn, and it adds the whole package); redeemed on /bevaltas
- The recipient's e-mail carries the message and the code, with the gift
  card attached as a PDF; the buyer's confirmation says it was a gift
- /ajandekaim: codes, state, the card to download, sending it by e-mail
  (again, or to another address) up to three times
- crates/gift-card draws the A4 card (example chart, questions avatar,
  QR code) as SVG and makes a PDF with krilla, fonts compiled in; the
  backend draws downloads on a blocking thread, the worker the e-mails
- Telegram notices say "(ajándék)"; unpaid gifts go after a week

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-23 20:28:11 +00:00

309 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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. Gift codes (packages someone paid for, see `gifts`) are
//! redeemed here too, but they are not promo codes.
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).
pub(super) 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::<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()
}
/// 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 (with another code or a gift's) 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) \
SELECT $1, $2, $3, $4, $5, $6 WHERE NOT EXISTS (SELECT 1 FROM gifts WHERE code = $2) \
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(&note)).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<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();
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<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. A gift code
/// adds the whole package.
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),
None => return redeem_gift(&state, &auth, &key, tx, &code).await,
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."));
}
};
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))
}
/// Redeems a gift code, if `code` is one (see `redeem`).
async fn redeem_gift(
state: &crate::AppState,
auth: &AuthUser,
key: &str,
mut tx: sqlx::Transaction<'_, sqlx::Postgres>,
code: &str,
) -> ApiResult<Json<Value>> {
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?;
let redeemed = match super::gifts::redeem(&mut tx, code, auth.id()).await {
Ok(Some(redeemed)) => redeemed,
Ok(None) => {
state.login_limiter.failed(key);
return Err(ApiError::conflict("promo_unknown", "Nincs ilyen kód. Ellenőrizd, hogy pontosan írtad-e be."));
}
Err(e) => {
state.login_limiter.failed(key);
return Err(e);
}
};
tx.commit().await?;
state.login_limiter.succeeded(key);
tracing::info!(user = %auth.id(), package = redeemed.package.id, "gift code redeemed");
let mut body = holdings(state, auth).await?;
body["package"] = json!({ "id": redeemed.package.id, "name": redeemed.package.name });
body["added"] = redeemed.added.iter().map(|(unit, n)| (unit.as_str().to_string(), json!(n))).collect();
body["gift"] = json!({ "from_name": redeemed.from_name });
Ok(Json(body))
}