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
This commit is contained in:
@@ -3,7 +3,8 @@
|
||||
//! 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.
|
||||
//! 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};
|
||||
@@ -23,7 +24,7 @@ use crate::packages;
|
||||
use crate::views::{rfc3339, rfc3339_opt};
|
||||
|
||||
/// Characters of a code (12 × ~5 bits: not guessable within the rate limit).
|
||||
const CODE_LEN: usize = 12;
|
||||
pub(super) const CODE_LEN: usize = 12;
|
||||
const MAX_BATCH: i64 = 500;
|
||||
|
||||
/// `ABCD-EFGH-JKLM`: the stored code in groups of four.
|
||||
@@ -46,10 +47,12 @@ pub(super) async fn new_code(
|
||||
) -> Result<String, sqlx::Error> {
|
||||
loop {
|
||||
let code = db::random_code(CODE_LEN);
|
||||
// A clash is practically impossible; another code is drawn if it happens.
|
||||
// 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) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (code) DO NOTHING",
|
||||
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)
|
||||
@@ -225,7 +228,8 @@ pub struct Redeem {
|
||||
code: String,
|
||||
}
|
||||
|
||||
/// Redeems a code: the user gets its package. One use per code.
|
||||
/// 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,
|
||||
@@ -242,6 +246,7 @@ pub async fn redeem(
|
||||
.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."));
|
||||
@@ -250,10 +255,6 @@ pub async fn redeem(
|
||||
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"))?;
|
||||
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?;
|
||||
@@ -275,3 +276,33 @@ pub async fn redeem(
|
||||
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))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user