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
@@ -0,0 +1,3 @@
-- An invitation can come with a package: a promo code made with it, sent in
-- the e-mail and redeemed by itself when the invitee signs up.
ALTER TABLE promo_codes ADD COLUMN invitation_id uuid UNIQUE REFERENCES invitations (id) ON DELETE SET NULL;
+30 -2
View File
@@ -173,6 +173,26 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
let until_hu = until.trim_end_matches('.');
let unsubscribe_url = field(payload, "unsubscribe_url")?;
let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
// A package that comes with the invitation, and its promo code.
let gift = name(payload, "package_name").zip(
payload["promo_code"]
.as_str()
.map(|c| c.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').take(40).collect::<String>())
.filter(|c| !c.is_empty()),
);
let gift_line = |hu: bool| {
gift.as_ref().map(|(package, code)| {
if hu {
format!(
" Ajándékba egy „{package}” csomagot is kapsz: a regisztrációval magától jóváíródik. Ha mégis kellene, a promókódod: {code}."
)
} else {
format!(
" You also get the “{package}” package as a gift: it is added when you sign up. Should you need it, your promo code is {code}."
)
}
})
};
Ok(match lang {
Lang::Hu => Content {
subject: match &inviter {
@@ -188,7 +208,7 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
None => {
"Meghívót kaptál a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.".into()
}
},
} + &gift_line(true).unwrap_or_default(),
quote: message,
points: Some((
"Mit találsz ott?",
@@ -226,7 +246,7 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
intro: match &inviter {
Some(n) => format!("{n} invited you to Sorsfonalak. The site is invitation-only for now."),
None => "You are invited to Sorsfonalak. The site is invitation-only for now.".into(),
},
} + &gift_line(false).unwrap_or_default(),
quote: message,
points: Some((
"What you will find there:",
@@ -468,6 +488,14 @@ mod tests {
assert!(en.text.contains("valid until 17 December 2026") && !en.text.contains("> "));
assert!(!en.html.contains("border-left"));
let mut gift = invitation_payload();
gift["package_name"] = json!("Páros");
gift["promo_code"] = json!("ABCD-EFGH-JKLM");
let hu = render("invitation", "hu", &gift).unwrap();
assert!(hu.text.contains("Ajándékba egy „Páros” csomagot is kapsz"), "{}", hu.text);
assert!(hu.html.contains("ABCD-EFGH-JKLM"));
assert!(!render("invitation", "hu", &invitation_payload()).unwrap().text.contains("Ajándék"));
let mut broken = invitation_payload();
broken["unsubscribe_url"] = Value::Null;
assert_eq!(render("invitation", "hu", &broken), Err(TemplateError::MissingField("unsubscribe_url")));
+17 -2
View File
@@ -22,10 +22,24 @@ Amíg a fizetés nincs bekötve, a csomagokat promókóddal (és admin ajándék
- a részletes elemzés ajánlata és a kérdés-válasz rész is ide vezet, ha nincs felhasználható egység.
- **Kitöltött link:** a `sorsfonalak.hu/bevaltas?kod=ABCD-EFGH-JKLM` link kitöltve nyitja meg a kódot. Aki nincs belépve, a belépés után ide tér vissza. Elég ezt a linket elküldeni a meghívottaknak.
- **Beírás:** a kód kis- vagy nagybetűvel, kötőjellel vagy anélkül is beírható.
- **Beváltás:** a csomag azonnal jóváíródik. Ez egy `package_orders` sor `promo` forrással, 0 Ft-tal, és mellette a szokásos `credit_ledger` sorok.
- **Beváltás = feltöltés:** a kód nem hozzáad, hanem **feltölti** az egyenleget a csomag szintjéig. Minden egységnél (képletelemzés, kapcsolati elemzés, előrejelzés, kérdés, szabad személyhely) az új egyenleg a csomag mennyisége lesz, ha addig kevesebb volt.
- Ami elhasznált belőle, visszajön; ami ennél több van (például vett hozzá), megmarad.
- Példa: a „Páros” csomag 2 képletelemzést ad. Ha valakinek 0 maradt, 2 lesz; ha 5 van, 5 marad.
- Ha a felhasználónak már mindenből megvan a csomag mennyisége, a kódot nem váltjuk be (megmarad későbbre), és ezt üzenetben meg is mondjuk.
- Könyvelés: egy `package_orders` sor `promo` forrással, 0 Ft-tal, és `credit_ledger` sorok csak a ténylegesen hozzáadott mennyiségekkel. A válaszban az `added` mező mondja meg, mi került hozzá.
- **Egyszer:** egy kód egyszer váltható be. A „már felhasználták”, „már nem érvényes” és „nincs ilyen kód” esetekre külön üzenet van.
- **Találgatás ellen:** 10 sikertelen próbálkozás után a felhasználó negyed óráig nem próbálkozhat.
## Meghívó csomaggal
Az Admin → Meghívók oldalon az „Ajándék csomag” választóval minden meghívott kap egy promókódot a választott csomagra (megjegyzés: „meghívó: <cím>”).
- **A levélben** benne van a csomag neve és a kód. A levél előnézete is mutatja (minta kóddal).
- **Regisztrációkor** a kód magától beváltódik, ugyanazzal a feltöltéssel, mint a kézi beváltásnál. Ha mégsem, a kód kézzel is beváltható.
- **Újraküldéskor** a levélben ugyanaz a kód marad.
- **Visszavonás:** a meghívó visszavonása a még fel nem használt kódot is visszavonja.
- **A meghívók listájában** látszik a csomag, és hogy beváltották-e.
## API
| Végpont | Ki | Mit csinál |
@@ -33,4 +47,5 @@ Amíg a fizetés nincs bekötve, a csomagokat promókóddal (és admin ajándék
| `POST /v1/admin/promo-codes` `{package, count, note?}` | admin | kódok készítése |
| `GET /v1/admin/promo-codes?status=unused\|used\|revoked\|all&package=&q=&limit=&offset=` | admin | lista |
| `POST /v1/admin/promo-codes/{id}/revoke` | admin | visszavonás |
| `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | beváltás; a válaszban az új egyenleg és a csomag |
| `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | beváltás (feltöltés); a válaszban az új egyenleg, a csomag és az `added` |
| `POST /v1/admin/invitations` `{emails, message?, locale?, package?}` | admin | meghívó, opcionálisan csomaggal |
+60 -9
View File
@@ -198,7 +198,20 @@ impl Source {
}
}
/// Records an order and gives its contents, inside the caller's transaction.
impl Package {
/// What the package gives, unit by unit.
pub fn contents(&self) -> [(Unit, i64); 5] {
[
(Unit::Natal, self.natal),
(Unit::Synastry, self.synastry),
(Unit::Forecast, self.forecast),
(Unit::Person, self.persons),
(Unit::Question, self.questions),
]
}
}
/// Records an order and adds its contents, inside the caller's transaction.
pub async fn grant(
tx: &mut PgConnection,
user_id: Uuid,
@@ -206,6 +219,51 @@ pub async fn grant(
source: Source,
created_by: Option<Uuid>,
note: Option<&str>,
) -> Result<Uuid, ApiError> {
record(tx, user_id, package, source, created_by, note, &package.contents()).await
}
/// Fills the user's units up to what the package gives (promo codes): a unit
/// below the package's amount is raised to it, used units come back, more
/// than that stays as it is. `persons_left` is the free person slots now
/// (`None`: unlimited, nothing to add). Returns the order and what was added
/// (nothing at all: no order is recorded).
pub async fn top_up(
tx: &mut PgConnection,
user_id: Uuid,
package: &Package,
persons_left: Option<i64>,
note: Option<&str>,
) -> Result<Option<(Uuid, Vec<(Unit, i64)>)>, ApiError> {
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user_id).execute(&mut *tx).await?;
let balance = crate::credits::balance(tx, user_id).await?;
let added: Vec<(Unit, i64)> = package
.contents()
.into_iter()
.map(|(unit, n)| {
let have = match unit {
Unit::Person => persons_left.unwrap_or(i64::MAX),
unit => balance.of(unit),
};
(unit, (n - have).max(0))
})
.filter(|&(_, n)| n > 0)
.collect();
if added.is_empty() {
return Ok(None);
}
let order = record(tx, user_id, package, Source::Promo, None, note, &added).await?;
Ok(Some((order, added)))
}
async fn record(
tx: &mut PgConnection,
user_id: Uuid,
package: &Package,
source: Source,
created_by: Option<Uuid>,
note: Option<&str>,
contents: &[(Unit, i64)],
) -> Result<Uuid, ApiError> {
let order = Uuid::now_v7();
let price = match source {
@@ -225,14 +283,7 @@ pub async fn grant(
.bind(created_by)
.execute(&mut *tx)
.await?;
let contents = [
(Unit::Natal, package.natal),
(Unit::Synastry, package.synastry),
(Unit::Forecast, package.forecast),
(Unit::Person, package.persons),
(Unit::Question, package.questions),
];
for (unit, n) in contents {
for &(unit, n) in contents {
if n == 0 {
continue;
}
+14
View File
@@ -62,6 +62,20 @@ pub async fn slots(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Resul
Ok(Slots { used, granted: free + bought, unlimited: entitled || auth.user.has_role(Role::Admin) })
}
/// The free person slots of a user without unlimited slots (for topping up).
pub async fn left(conn: &mut PgConnection, user_id: Uuid, free: i64) -> Result<i64, ApiError> {
let (used, bought): (i64, i64) = sqlx::query_as(
"SELECT \
(SELECT COUNT(*) FROM credit_ledger WHERE user_id = $1 AND unit = 'person' AND reason = 'person'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger \
WHERE user_id = $1 AND unit = 'person' AND reason <> 'person')",
)
.bind(user_id)
.fetch_one(conn)
.await?;
Ok((free + bought - used).max(0))
}
/// Fails when no slot is left (a quick check before calculating a chart).
pub async fn check(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Result<(), ApiError> {
if slots(conn, auth, free).await?.left() == Some(0) {
+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))
}
+82
View File
@@ -1913,3 +1913,85 @@ async fn promo_codes_are_made_by_admins_and_redeemed_once(pool: PgPool) {
let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": codes[2]})).await;
assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn an_invitation_brings_its_package_and_codes_fill_up(pool: PgPool) {
let app = TestApp::with_config(pool.clone(), |c| c.signup_mode = crate::config::SignupMode::Invite).await;
let admin = app.register("admin@example.com", "Admin").await;
let r = app
.post(
"/v1/admin/invitations",
Some(&admin),
json!({"emails": ["guest@example.com", "other@example.com"], "package": "couple"}),
)
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let guest = &r.body["results"][0];
let guest_token = invite_token(guest["url"].as_str().unwrap());
let other_id = r.body["results"][1]["id"].as_str().unwrap().to_string();
// the e-mail shows the package and its code
let (payload,): (Value,) = sqlx::query_as(
"SELECT payload FROM email_outbox WHERE to_email = 'guest@example.com' AND template = 'invitation'",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(payload["package_name"], "Páros");
assert_eq!(payload["promo_code"], guest["promo_code"]);
assert!(
payload["redeem_url"]
.as_str()
.unwrap()
.ends_with(&format!("/bevaltas?kod={}", guest["promo_code"].as_str().unwrap()))
);
let list = app.get("/v1/admin/invitations", Some(&admin)).await.body;
assert_eq!(list["invitations"][0]["package"]["name"], "Páros");
// revoking an invitation withdraws its code
let r = app.call("DELETE", &format!("/v1/admin/invitations/{other_id}"), Some(&admin), None).await;
assert_eq!(r.status, StatusCode::NO_CONTENT);
let codes = app.get("/v1/admin/promo-codes?status=revoked", Some(&admin)).await.body;
assert_eq!((codes["total"].as_i64(), &codes["codes"][0]["note"]), (Some(1), &json!("meghívó: other@example.com")));
// signing up redeems it by itself
let r = google_signup(&app, "g-guest", "guest@example.com", Some(&guest_token)).await;
assert!(r.status.is_success(), "{}", r.body);
let token = r.body["token"].as_str().map(str::to_string).unwrap_or_else(|| {
let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap();
cookie.split(';').next().unwrap().split('=').nth(1).unwrap().to_string()
});
let me = app.get("/v1/me", Some(&token)).await.body;
let left = &me["analyses_left"];
assert_eq!(
(left["natal"].as_i64(), left["synastry"].as_i64(), left["forecast"].as_i64()),
(Some(2), Some(1), Some(2)),
"{me}"
);
assert_eq!(me["package"]["id"], "couple");
let used = app.get("/v1/admin/promo-codes?status=used", Some(&admin)).await.body;
assert_eq!(used["codes"][0]["redeemed_by"]["email"], "guest@example.com");
// a code fills up: nothing to add while everything is there…
let r = app.post("/v1/admin/promo-codes", Some(&admin), json!({"package": "couple", "count": 1})).await;
let spare = r.body["codes"][0].as_str().unwrap().to_string();
let r = app.post("/v1/promo-codes/redeem", Some(&token), json!({"code": spare})).await;
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("promo_nothing_to_add")));
// …used units come back, extra ones stay
sqlx::query(
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason) \
SELECT gen_random_uuid(), id, unit, delta, 'admin_adjust' FROM users, \
(VALUES ('natal', -2), ('forecast', 3)) AS v(unit, delta) WHERE email = 'guest@example.com'",
)
.execute(&pool)
.await
.unwrap();
let r = app.post("/v1/promo-codes/redeem", Some(&token), json!({"code": spare})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(r.body["added"], json!({"natal": 2}));
let left = &app.get("/v1/me", Some(&token)).await.body["analyses_left"];
assert_eq!(
(left["natal"].as_i64(), left["synastry"].as_i64(), left["forecast"].as_i64()),
(Some(2), Some(1), Some(5))
);
}
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useState } from "react";
import { usePackages } from "@/components/PackageCards";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { AdminInvitation, InvitationResult, WaitlistEntry } from "@/lib/types";
@@ -104,6 +105,8 @@ function InviteForm({ onSent }: { onSent: () => Promise<void> }) {
const [emails, setEmails] = useState("");
const [message, setMessage] = useState("");
const [locale, setLocale] = useState("hu");
const [pkg, setPkg] = useState("");
const packages = usePackages();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [results, setResults] = useState<InvitationResult[] | null>(null);
@@ -116,7 +119,7 @@ function InviteForm({ onSent }: { onSent: () => Promise<void> }) {
setResults(null);
try {
const res = await api<{ results: InvitationResult[] }>("/admin/invitations", {
body: { emails: parseEmails(emails), message: message.trim() || null, locale },
body: { emails: parseEmails(emails), message: message.trim() || null, locale, package: pkg || null },
});
setResults(res.results);
if (res.results.some((r) => r.status === "invited")) setEmails("");
@@ -163,6 +166,17 @@ function InviteForm({ onSent }: { onSent: () => Promise<void> }) {
</span>
</div>
<div className="row" style={{ gap: 12, alignItems: "flex-end", flexWrap: "wrap" }}>
<div className="field" style={{ minWidth: 220 }}>
<label htmlFor="invite-package">Ajándék csomag</label>
<select id="invite-package" className="inp" value={pkg} onChange={(e) => setPkg(e.target.value)}>
<option value="">nincs</option>
{(packages ?? []).map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
<div className="field" style={{ width: 160 }}>
<label htmlFor="invite-locale">A levél nyelve</label>
<select id="invite-locale" className="inp" value={locale} onChange={(e) => setLocale(e.target.value)}>
@@ -175,6 +189,12 @@ function InviteForm({ onSent }: { onSent: () => Promise<void> }) {
</button>
</div>
</form>
{pkg && (
<p className="hint" style={{ margin: 0 }}>
Minden meghívott kap egy promókódot erre a csomagra. A levélben benne lesz, és a regisztrációkor magától
beváltódik. A meghívó visszavonása a kódot is visszavonja.
</p>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
@@ -187,18 +207,19 @@ function InviteForm({ onSent }: { onSent: () => Promise<void> }) {
<span className={r.status === "invited" ? "msg-ok" : "muted"}>
{r.email}: {RESULT[r.status]}
</span>
{r.promo_code && <code className="promo-code">{r.promo_code}</code>}
{r.url && <CopyLink url={r.url} />}
</li>
))}
</ul>
)}
<MailPreview message={message} locale={locale} />
<MailPreview message={message} locale={locale} pkg={pkg} />
</section>
);
}
/** The invitation e-mail as the recipient sees it, and a test copy to the admin. */
function MailPreview({ message, locale }: { message: string; locale: string }) {
function MailPreview({ message, locale, pkg }: { message: string; locale: string; pkg: string }) {
const [mail, setMail] = useState<{ subject: string; html: string; text: string } | null>(null);
const [view, setView] = useState<"html" | "text">("html");
const [busy, setBusy] = useState(false);
@@ -210,7 +231,7 @@ function MailPreview({ message, locale }: { message: string; locale: string }) {
try {
const res = await api<{ subject: string; html: string; text: string; sent_to: string | null }>(
"/admin/invitations/preview",
{ body: { message: message.trim() || null, locale, send_to_me: sendToMe } },
{ body: { message: message.trim() || null, locale, send_to_me: sendToMe, package: pkg || null } },
);
setMail(res);
if (res.sent_to) setNote({ ok: true, text: `Tesztlevél a sorban: ${res.sent_to}. A linkjei nem működnek.` });
@@ -337,6 +358,12 @@ function InvitationRow({ invitation: i, onChange }: { invitation: AdminInvitatio
<td>
<span className={`badge invite-${i.status}`}>{STATUS[i.status]}</span>
{i.accepted_by && <div className="hint">{i.accepted_by}</div>}
{i.package && (
<div className="hint" title={i.package.code ?? undefined}>
Ajándék: {i.package.name ?? i.package.id}
{i.package.redeemed_at ? " (beváltva)" : ""}
</div>
)}
</td>
<td>
<span className={i.mail === "failed" ? "msg-error" : i.mail === "queued" ? "muted" : undefined}>
+2 -2
View File
@@ -17,8 +17,8 @@ export default async function RedeemPage({ searchParams }: Props) {
<span className="eyebrow">Promókód</span>
<h1>Promókód beváltása</h1>
<p className="muted">
Írd be a kapott kódot. A hozzá tartozó csomag azonnal a tiéd, az elemzései nem járnak le. Egy kód egyszer
váltható be.
Írd be a kapott kódot. Az egyenlegedet azonnal feltöltjük a csomag szintjéig: amit már elhasználtál belőle,
visszakapod, ami ennél több van, megmarad. Egy kód egyszer váltható be.
</p>
</div>
<section className="card">
@@ -12,22 +12,42 @@ function format(input: string): string {
return clean.match(/.{1,4}/g)?.join("-") ?? "";
}
/** Redeeming a promo code: the package arrives at once. */
const UNITS: Record<string, string> = {
natal: "képletelemzés",
synastry: "kapcsolati elemzés",
forecast: "éves előrejelzés",
person: "személyhely",
question: "kérdés",
};
/** "+2 képletelemzés, +3 kérdés" */
function addedText(added: Record<string, number>): string {
return Object.entries(added)
.map(([unit, n]) => `+${n} ${UNITS[unit] ?? unit}`)
.join(", ");
}
/**
* Redeeming a promo code. It fills the units up to the package's amounts
* (used ones come back, more than that stays).
*/
export function RedeemCode({ initial = "", compact = false }: { initial?: string; compact?: boolean }) {
const router = useRouter();
const id = useId();
const [code, setCode] = useState(format(initial));
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [got, setGot] = useState<string | null>(null);
const [got, setGot] = useState<{ name: string; added: string } | null>(null);
async function redeem(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const r = await api<{ package: { name: string } }>("/promo-codes/redeem", { body: { code } });
setGot(r.package.name);
const r = await api<{ package: { name: string }; added: Record<string, number> }>("/promo-codes/redeem", {
body: { code },
});
setGot({ name: r.package.name, added: addedText(r.added ?? {}) });
setCode("");
router.refresh();
} catch (err) {
@@ -67,8 +87,8 @@ export function RedeemCode({ initial = "", compact = false }: { initial?: string
{error && <p className="msg msg-error">{error}</p>}
{got && (
<p className="msg msg-ok">
Megkaptad: <strong>{got}</strong>. Az elemzéseid már felhasználhatók,{" "}
<Link href="/keplet">indulhat a képleted</Link>.
Beváltva: <strong>{got.name}</strong>. Feltöltöttük az egyenlegedet: {got.added}.{" "}
<Link href="/keplet">Tovább a képletedhez</Link>
</p>
)}
</div>
+4
View File
@@ -413,6 +413,8 @@ export interface AdminInvitation {
mail: "sent" | "queued" | "failed" | "archived";
mail_error: string | null;
can_resend: boolean;
/** The package it comes with (a promo code, redeemed at sign-up). */
package: { id: string; name: string | null; code: string | null; redeemed_at: string | null } | null;
}
export interface WaitlistEntry {
@@ -428,6 +430,8 @@ export interface InvitationResult {
status: "invited" | "invalid" | "already_user" | "already_invited" | "opted_out";
id?: string;
url?: string;
/** The promo code of the package sent with it. */
promo_code?: string | null;
}
/** A calculated year in a list (`GET /v1/charts/{id}/forecasts`). */