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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -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::<Vec<_>>().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<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))
|
||||
}
|
||||
|
||||
#[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::<String>()).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))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user