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:
@@ -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(¬e), 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}")))?;
|
||||
|
||||
Reference in New Issue
Block a user