Invitations with a package; promo codes fill up the balance
CI / test (push) Successful in 1m15s
CI / build (push) Successful in 5m15s
CI / deploy (push) Skipped

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:
feco
2026-11-19 09:57:01 +00:00
co-authored by Claude Opus 5.5
parent 054fb930f5
commit 7b23d71526
13 changed files with 458 additions and 66 deletions
+16 -2
View File
@@ -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)
}
};
+96 -7
View File
@@ -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<Option<Gift>, 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<String>) -> Result<Option<String>, 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<String, ApiError> {
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<String>,
message: Option<String>,
locale: Option<String>,
/// A package from the catalog the invitees get (as a promo code).
package: Option<String>,
}
/// 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(&note), 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<OffsetDateTime>,
mail_failed_at: Option<OffsetDateTime>,
mail_error: Option<String>,
promo_code: Option<String>,
promo_package: Option<String>,
promo_redeemed_at: Option<OffsetDateTime>,
}
fn status(accepted: Option<OffsetDateTime>, revoked: Option<OffsetDateTime>, expires: OffsetDateTime) -> &'static str {
@@ -285,8 +347,10 @@ pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>>
"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<Json<Value>>
"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<StatusCode> {
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<String>,
}
/// The invitation e-mail with sample links (they lead nowhere), and
@@ -438,12 +522,17 @@ pub async fn preview(
) -> ApiResult<Json<Value>> {
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}")))?;
+77 -32
View File
@@ -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(&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 {
@@ -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(&note)
.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(&note)).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))
}