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:
feco
2026-11-23 20:28:11 +00:00
co-authored by Claude Opus 5.5
parent 699ce2abbd
commit c90232f40c
46 changed files with 3647 additions and 88 deletions
+1
View File
@@ -10,6 +10,7 @@ publish.workspace = true
db.workspace = true
analysis-prompt.workspace = true
email-templates.workspace = true
gift-card.workspace = true
hmac.workspace = true
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
rand.workspace = true
+11 -3
View File
@@ -210,6 +210,8 @@ pub enum Source {
Mock,
/// A redeemed promo code.
Promo,
/// A redeemed gift code (someone else paid for it).
Gift,
/// Paid through Stripe Checkout.
Stripe,
}
@@ -220,6 +222,7 @@ impl Source {
Source::Admin => "admin",
Source::Mock => "mock",
Source::Promo => "promo",
Source::Gift => "gift",
Source::Stripe => "stripe",
}
}
@@ -228,6 +231,11 @@ impl Source {
impl Package {
/// What the package gives, as a phrase: "2 részletes képletelemzés, 1 kapcsolati elemzés, …".
pub fn contents_text(&self) -> String {
self.contents_items().join(", ")
}
/// What the package gives, item by item ("2 részletes képletelemzés").
pub fn contents_items(&self) -> Vec<String> {
[
(self.natal, "részletes képletelemzés"),
(self.synastry, "kapcsolati elemzés"),
@@ -239,8 +247,7 @@ impl Package {
.into_iter()
.filter(|&(n, _)| n > 0)
.map(|(n, what)| format!("{n} {what}"))
.collect::<Vec<_>>()
.join(", ")
.collect()
}
/// The invoice item: a name that says what the service is (online,
@@ -349,7 +356,8 @@ async fn record(
) -> Result<Uuid, ApiError> {
let order = Uuid::now_v7();
let price = match source {
Source::Admin | Source::Promo => 0,
// A gift's price is on the buyer's checkout.
Source::Admin | Source::Promo | Source::Gift => 0,
Source::Mock | Source::Stripe => package.price_huf,
};
sqlx::query(
+8
View File
@@ -226,6 +226,14 @@ pub async fn delete_me(
.bind(auth.id())
.execute(&mut *tx)
.await?;
// Gifts stay redeemable, but whom they were for and the message go.
sqlx::query(
"UPDATE gifts SET recipient_name = NULL, recipient_email = NULL, from_name = NULL, message = NULL \
WHERE buyer_id = $1",
)
.bind(auth.id())
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), "account deleted");
+413
View File
@@ -0,0 +1,413 @@
//! Gifts: a package of the main ladder bought for someone else.
//!
//! The buyer says whom it is for (a name, and an e-mail address typed twice,
//! or no address: they hand it over themselves), their own name and a
//! message, and pays on Stripe as for any package. When the payment is
//! confirmed the gift gets its code and, with an address, it is e-mailed to
//! the recipient; the worker attaches the gift card (PDF). The buyer can
//! download the card, and send it by e-mail (again, or to another address)
//! while it is not redeemed.
//!
//! A gift code is not a promo code: it cannot be withdrawn (it was paid
//! for), and it adds the whole package, while a promo code only fills the
//! units up to the package's. Both are redeemed in the same place.
use axum::Json;
use axum::extract::{Path, State};
use axum::http::header;
use axum::response::IntoResponse;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
use super::auth::{normalize_email, queue_email_to};
use super::promo::{CODE_LEN, display};
use super::{Body, IdPath, St, payments};
use crate::AppState;
use crate::auth::AuthUser;
use crate::credits::Unit;
use crate::error::{ApiError, ApiResult};
use crate::packages::{self, Package, Source, Tier};
use crate::views::rfc3339_opt;
const MAX_NAME_CHARS: usize = 60;
/// E-mails of one gift: at most this many in all, at least this far apart.
const MAX_SENDINGS: i32 = 3;
const SEND_GAP: time::Duration = time::Duration::minutes(10);
/// The packages that can be given (the main ladder: a good first package).
fn giftable(id: &str) -> Option<&'static Package> {
packages::find(id).filter(|p| p.tier == Tier::Main)
}
/// The recipient's address, typed twice (both the same); `None`: no address.
fn recipient(email: Option<&str>, confirm: Option<&str>) -> Result<Option<String>, ApiError> {
let Some(email) = email.map(str::trim).filter(|e| !e.is_empty()) else { return Ok(None) };
let email = normalize_email(email)?;
if confirm.map(|c| c.trim().to_lowercase()).as_deref() != Some(email.as_str()) {
return Err(ApiError::BadRequest("A két e-mail-cím nem egyezik.".into()));
}
Ok(Some(email))
}
/// A name as shown on the card and in the e-mail (the recipient's or the giver's).
fn clean_name(name: Option<String>) -> Result<Option<String>, ApiError> {
let name: Option<String> = name
.map(|n| n.chars().filter(|c| !c.is_control()).collect::<String>().trim().to_string())
.filter(|n| !n.is_empty());
let Some(name) = name else { return Ok(None) };
if name.chars().count() > MAX_NAME_CHARS {
return Err(ApiError::BadRequest(format!("A név legfeljebb {MAX_NAME_CHARS} karakter lehet.")));
}
let lower = name.to_lowercase();
if lower.contains("://") || lower.contains("www.") {
return Err(ApiError::BadRequest("A névben nem lehet link.".into()));
}
Ok(Some(name))
}
fn redeem_url(state: &AppState, code: &str) -> String {
format!("{}/bevaltas?kod={}", state.config.public_base_url, display(code))
}
#[derive(sqlx::FromRow)]
struct Gift {
id: Uuid,
buyer_id: Option<Uuid>,
package: String,
recipient_name: Option<String>,
recipient_email: Option<String>,
from_name: Option<String>,
message: Option<String>,
paid_at: Option<OffsetDateTime>,
code: Option<String>,
redeemed_at: Option<OffsetDateTime>,
sendings: i32,
last_sent_at: Option<OffsetDateTime>,
}
const COLUMNS: &str = "id, buyer_id, package, recipient_name, recipient_email, from_name, message, paid_at, code, \
redeemed_at, sendings, last_sent_at";
impl Gift {
fn package(&self) -> Result<&'static Package, ApiError> {
packages::find(&self.package).ok_or_else(|| ApiError::Internal(format!("unknown package {}", self.package)))
}
fn code(&self) -> Result<&str, ApiError> {
self.code.as_deref().ok_or_else(|| ApiError::Internal(format!("gift {} has no code", self.id)))
}
/// What the worker needs to draw the gift card for an e-mail.
fn card_payload(&self, state: &AppState) -> Result<Value, ApiError> {
let (package, code) = (self.package()?, self.code()?);
Ok(json!({
"package": package.name,
"contents": package.contents_items(),
"code": display(code),
"redeem_url": redeem_url(state, code),
"recipient_name": self.recipient_name,
"from_name": self.from_name,
"message": self.message,
}))
}
fn view(&self) -> Value {
let status = if self.redeemed_at.is_some() { "redeemed" } else { "open" };
let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc());
json!({
"id": self.id,
"package": { "id": self.package, "name": packages::find(&self.package).map(|p| p.name) },
"recipient_name": self.recipient_name,
"recipient_email": self.recipient_email,
"from_name": self.from_name,
"message": self.message,
"paid_at": rfc3339_opt(self.paid_at),
"code": self.code.as_deref().map(display),
"status": status,
"redeemed_at": rfc3339_opt(self.redeemed_at),
"sendings": self.sendings,
"can_send": status == "open" && self.sendings < MAX_SENDINGS,
"send_again_at": rfc3339_opt(next_send),
})
}
}
/// The buyer's paid gift, locked for an update if `lock`.
async fn own_gift(conn: &mut PgConnection, id: Uuid, buyer: Uuid, lock: bool) -> Result<Gift, ApiError> {
let lock = if lock { " FOR UPDATE" } else { "" };
sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM gifts WHERE id = $1 AND buyer_id = $2 AND paid_at IS NOT NULL{lock}"
))
.bind(id)
.bind(buyer)
.fetch_optional(conn)
.await?
.ok_or(ApiError::NotFound("gift"))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GiftCheckout {
package: String,
/// Whom it is for.
recipient_name: Option<String>,
/// Who gets the gift by e-mail; none: the buyer hands it over.
recipient_email: Option<String>,
/// The address typed again.
recipient_email_confirm: Option<String>,
from_name: Option<String>,
message: Option<String>,
}
/// Starts paying for a gift: returns the address of Stripe's payment page.
/// With the stand-in payment the gift is paid at once (`url` is null).
pub async fn checkout(
State(state): St,
auth: AuthUser,
WithRejection(Json(req), _): Body<GiftCheckout>,
) -> ApiResult<Json<Value>> {
let package = giftable(&req.package).ok_or(ApiError::NotFound("package"))?;
let name = clean_name(req.recipient_name)?
.ok_or_else(|| ApiError::BadRequest("Add meg, kinek szól az ajándék.".into()))?;
let to = recipient(req.recipient_email.as_deref(), req.recipient_email_confirm.as_deref())?;
let from = clean_name(req.from_name)?;
let message = super::invitations::clean_message(req.message)?;
// Whether this user may pay, before anything is written.
let stripe = match payments::method(&state.config) {
Some("stripe") => Some(payments::stripe_for(&state, &auth)?),
Some(_) => None,
None => return Err(ApiError::NotFound("payment method")),
};
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message) \
VALUES ($1, $2, $3, $4, $5, $6, $7)",
)
.bind(id)
.bind(auth.id())
.bind(package.id)
.bind(&name)
.bind(&to)
.bind(&from)
.bind(&message)
.execute(&state.db)
.await?;
let url = match stripe {
Some(config) => {
Some(payments::start_checkout(&state, config, &auth, package, Some("/ajandekaim"), Some(id)).await?)
}
None => {
let mut tx = state.db.begin().await?;
fulfil(&mut tx, &state, id).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), package = package.id, "mock gift payment");
None
}
};
Ok(Json(json!({ "id": id, "url": url })))
}
/// A paid gift: its code as shown, whom it is for, where it went, and its
/// card for an e-mail.
pub struct Paid {
pub code: String,
pub recipient_name: Option<String>,
pub recipient_email: Option<String>,
pub card: Value,
}
/// A new gift code, never the same as a promo code or another gift's.
async fn new_code(tx: &mut PgConnection) -> Result<String, sqlx::Error> {
loop {
let code = db::random_code(CODE_LEN);
let taken: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM promo_codes WHERE code = $1) OR EXISTS (SELECT 1 FROM gifts WHERE code = $1)",
)
.bind(&code)
.fetch_one(&mut *tx)
.await?;
if !taken {
return Ok(code);
}
}
}
/// Makes the code of a paid gift and e-mails it to the recipient, inside the
/// caller's transaction. Once: a gift paid already returns what it has.
pub async fn fulfil(tx: &mut PgConnection, state: &AppState, id: Uuid) -> Result<Paid, ApiError> {
let mut gift: Gift = sqlx::query_as(&format!("SELECT {COLUMNS} FROM gifts WHERE id = $1 FOR UPDATE"))
.bind(id)
.fetch_one(&mut *tx)
.await?;
if gift.paid_at.is_none() {
let code = new_code(tx).await?;
sqlx::query("UPDATE gifts SET code = $2, paid_at = now() WHERE id = $1")
.bind(id)
.bind(&code)
.execute(&mut *tx)
.await?;
gift.code = Some(code);
if let Some(to) = gift.recipient_email.clone() {
send(tx, state, &gift, &to).await?;
}
tracing::info!(gift = %id, package = %gift.package, by_email = gift.recipient_email.is_some(), "gift paid");
}
Ok(Paid {
code: display(gift.code()?),
card: gift.card_payload(state)?,
recipient_name: gift.recipient_name,
recipient_email: gift.recipient_email,
})
}
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language.
async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) -> Result<(), ApiError> {
let locale: Option<String> = sqlx::query_scalar("SELECT locale FROM users WHERE id = $1")
.bind(gift.buyer_id)
.fetch_optional(&mut *tx)
.await?;
let (package, code) = (gift.package()?, gift.code()?);
let payload = json!({
"url": redeem_url(state, code),
"package_name": package.name,
"contents": package.contents_text(),
"promo_code": display(code),
"recipient_name": gift.recipient_name,
"from_name": gift.from_name,
"message": gift.message,
"gift_card": gift.card_payload(state)?,
});
// Not the recipient's account (if they have one): no user id.
queue_email_to(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload).await?;
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now() WHERE id = $1")
.bind(gift.id)
.execute(&mut *tx)
.await?;
Ok(())
}
/// The user's paid gifts, newest first.
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let gifts: Vec<Gift> = sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM gifts WHERE buyer_id = $1 AND paid_at IS NOT NULL ORDER BY paid_at DESC, id DESC"
))
.bind(auth.id())
.fetch_all(&state.db)
.await?;
Ok(Json(json!({ "gifts": gifts.iter().map(Gift::view).collect::<Vec<_>>(), "max_sendings": MAX_SENDINGS })))
}
/// The gift card as a PDF, for the buyer (drawn on a blocking thread).
pub async fn card(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<impl IntoResponse> {
let mut conn = state.db.acquire().await?;
let gift = own_gift(&mut conn, id, auth.id(), false).await?;
drop(conn);
let package = gift.package()?;
let code = display(gift.code()?);
let url = redeem_url(&state, gift.code()?);
let filename = format!("sorsfonalak-ajandek-{code}.pdf");
let pdf = tokio::task::spawn_blocking(move || {
let contents = package.contents_items();
gift_card::pdf(&gift_card::Card {
package: package.name,
contents: &contents,
code: &code,
redeem_url: &url,
recipient_name: gift.recipient_name.as_deref(),
from_name: gift.from_name.as_deref(),
message: gift.message.as_deref(),
})
})
.await
.map_err(|e| ApiError::Internal(e.to_string()))?
.map_err(|e| ApiError::Internal(e.to_string()))?;
Ok((
[
(header::CONTENT_TYPE, "application/pdf".to_string()),
(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{filename}\"")),
(header::CACHE_CONTROL, "private, no-store".to_string()),
],
pdf,
))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SendGift {
recipient_email: String,
recipient_email_confirm: String,
}
/// Sends the gift by e-mail: again, or to another address, or for the first
/// time when the buyer meant to hand it over. Only while it is not redeemed.
pub async fn send_again(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<SendGift>,
) -> ApiResult<Json<Value>> {
let to = recipient(Some(&req.recipient_email), Some(&req.recipient_email_confirm))?
.ok_or_else(|| ApiError::BadRequest("Add meg, kinek küldjük az ajándékot.".into()))?;
let mut tx = state.db.begin().await?;
let mut gift = own_gift(&mut tx, id, auth.id(), true).await?;
if gift.redeemed_at.is_some() {
return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották."));
}
if gift.sendings >= MAX_SENDINGS {
return Err(ApiError::conflict(
"gift_send_limit",
"Ezt az ajándékot már háromszor elküldtük e-mailben. Töltsd le az utalványt, és küldd el te magad.",
));
}
if gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
return Err(ApiError::conflict("gift_send_wait", "Pár perc múlva küldheted el újra."));
}
sqlx::query("UPDATE gifts SET recipient_email = $2 WHERE id = $1").bind(id).bind(&to).execute(&mut *tx).await?;
gift.recipient_email = Some(to.clone());
send(&mut tx, &state, &gift, &to).await?;
let gift = own_gift(&mut tx, id, auth.id(), false).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), gift = %id, "gift sent by e-mail");
Ok(Json(gift.view()))
}
/// A redeemed gift code: the package, what was added and who gave it.
pub(super) struct Redeemed {
pub package: &'static Package,
pub added: Vec<(Unit, i64)>,
pub from_name: Option<String>,
}
/// Redeems a gift code (stored form) for the user, inside the caller's
/// transaction: the whole package, recorded as an order with source `gift`.
/// `None`: not a gift code.
pub(super) async fn redeem(tx: &mut PgConnection, code: &str, user_id: Uuid) -> Result<Option<Redeemed>, ApiError> {
let gift: Option<Gift> =
sqlx::query_as(&format!("SELECT {COLUMNS} FROM gifts WHERE code = $1 AND paid_at IS NOT NULL FOR UPDATE"))
.bind(code)
.fetch_optional(&mut *tx)
.await?;
let Some(gift) = gift else { return Ok(None) };
if gift.redeemed_at.is_some() {
return Err(ApiError::conflict("promo_used", "Ezt a kódot már felhasználták."));
}
let package = gift.package()?;
let note = format!("ajándékkód {}", display(code));
let order = packages::grant(tx, user_id, package, Source::Gift, None, Some(&note)).await?;
sqlx::query("UPDATE gifts SET redeemed_by = $2, redeemed_at = now(), order_id = $3 WHERE id = $1")
.bind(gift.id)
.bind(user_id)
.bind(order)
.execute(&mut *tx)
.await?;
let added = package.contents().into_iter().filter(|&(_, n)| n > 0).collect();
Ok(Some(Redeemed { package, added, from_name: gift.from_name }))
}
+5
View File
@@ -14,6 +14,7 @@ mod celebrities;
mod charts;
mod errors;
mod forecasts;
mod gifts;
mod invitations;
mod invoices_user;
mod jobs;
@@ -117,6 +118,10 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/tarot/readings/{id}", get(tarot::get_one))
// sharing
.route("/v1/promo-codes/redeem", post(promo::redeem))
.route("/v1/gifts", get(gifts::list))
.route("/v1/gifts/checkout", post(gifts::checkout))
.route("/v1/gifts/{id}/card.pdf", get(gifts::card))
.route("/v1/gifts/{id}/send", post(gifts::send_again))
.route("/v1/admin/promo-codes", get(promo::list).post(promo::create))
.route("/v1/admin/promo-codes/{id}/revoke", post(promo::revoke))
.route("/v1/shares", get(shares::list).post(shares::create))
+82 -25
View File
@@ -96,7 +96,7 @@ pub fn admins_only(config: &crate::config::Config) -> bool {
}
/// Stripe, if this user may pay through it.
fn stripe_for<'a>(state: &'a AppState, auth: &AuthUser) -> Result<&'a StripeConfig, ApiError> {
pub(super) fn stripe_for<'a>(state: &'a AppState, auth: &AuthUser) -> Result<&'a StripeConfig, ApiError> {
let config = state.config.stripe.as_ref().ok_or(ApiError::NotFound("payment method"))?;
if admins_only(&state.config) && !auth.user.has_role(Role::Admin) {
return Err(ApiError::Forbidden("purchases are being tested; they open soon".into()));
@@ -131,8 +131,25 @@ pub async fn checkout(
) -> ApiResult<Json<Value>> {
let config = stripe_for(&state, &auth)?;
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
let back = format!("{}{}", state.config.public_base_url, return_path(req.return_path.as_deref()));
let (checkout_name, checkout_description) = package.checkout_text();
let url = start_checkout(&state, config, &auth, package, req.return_path.as_deref(), None).await?;
Ok(Json(json!({ "url": url })))
}
/// Creates the Stripe Checkout session of a package (for the buyer, or a
/// `gift` for someone else) and records it; returns the payment page.
pub(super) async fn start_checkout(
state: &AppState,
config: &StripeConfig,
auth: &AuthUser,
package: &packages::Package,
return_path: Option<&str>,
gift: Option<Uuid>,
) -> Result<String, ApiError> {
let back = format!("{}{}", state.config.public_base_url, self::return_path(return_path));
let (mut checkout_name, checkout_description) = package.checkout_text();
if gift.is_some() {
checkout_name.push_str(" (ajándék)");
}
let field = |k: &str, v: &str| (k.to_string(), v.to_string());
let mut form = vec![
field("mode", "payment"),
@@ -157,6 +174,9 @@ pub async fn checkout(
field("success_url", &format!("{back}?fizetes={{CHECKOUT_SESSION_ID}}")),
field("cancel_url", &format!("{back}?fizetes=megszakitva")),
];
if let Some(gift) = gift {
form.push(field("metadata[gift_id]", &gift.to_string()));
}
if state.config.terms_consent {
// Every purchase accepts the terms and asks for immediate delivery,
// giving up the 14-day withdrawal right (45/2014. Korm. rendelet 29. §).
@@ -173,30 +193,33 @@ pub async fn checkout(
}
let session = state.stripe.create_session(config, &form).await?;
let url = session.url.ok_or_else(|| ApiError::Internal(format!("checkout session {} has no url", session.id)))?;
sqlx::query("INSERT INTO stripe_checkouts (id, user_id, package, price_huf, live) VALUES ($1, $2, $3, $4, $5)")
.bind(&session.id)
.bind(auth.id())
.bind(package.id)
.bind(package.price_huf as i32)
.bind(!config.test_mode())
.execute(&state.db)
.await?;
tracing::info!(user = %auth.id(), package = package.id, session = %session.id, "checkout started");
Ok(Json(json!({ "url": url })))
sqlx::query(
"INSERT INTO stripe_checkouts (id, user_id, package, price_huf, live, gift_id) VALUES ($1, $2, $3, $4, $5, $6)",
)
.bind(&session.id)
.bind(auth.id())
.bind(package.id)
.bind(package.price_huf as i32)
.bind(!config.test_mode())
.bind(gift)
.execute(&state.db)
.await?;
tracing::info!(user = %auth.id(), package = package.id, session = %session.id, gift = gift.is_some(), "checkout started");
Ok(url)
}
/// Records a paid session (what was charged, the buyer's billing details),
/// grants its package and queues the invoice, once. `false`: not our session.
async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, ApiError> {
let mut tx = state.db.begin().await?;
type Checkout = (Option<Uuid>, String, i32, Option<OffsetDateTime>);
type Checkout = (Option<Uuid>, String, i32, Option<OffsetDateTime>, Option<Uuid>);
let row: Option<Checkout> = sqlx::query_as(
"SELECT user_id, package, price_huf, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE",
"SELECT user_id, package, price_huf, completed_at, gift_id FROM stripe_checkouts WHERE id = $1 FOR UPDATE",
)
.bind(&session.id)
.fetch_optional(&mut *tx)
.await?;
let Some((user_id, package_id, price_huf, completed_at)) = row else { return Ok(false) };
let Some((user_id, package_id, price_huf, completed_at, gift_id)) = row else { return Ok(false) };
if completed_at.is_some() {
return Ok(true);
}
@@ -206,13 +229,20 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, A
}
let package =
packages::find(&package_id).ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?;
// A deleted account still gets its invoice, but no package.
let order = match user_id {
Some(user_id) => {
// A gift gets its code (and goes to its recipient); the package is
// granted when the code is redeemed. A deleted account still gets its
// invoice, but no package.
let mut gift = None;
let order = match (gift_id, user_id) {
(Some(gift_id), _) => {
gift = Some(super::gifts::fulfil(&mut tx, state, gift_id).await?);
None
}
(None, Some(user_id)) => {
let note = format!("Stripe {}", session.id);
Some(packages::grant(&mut tx, user_id, package, Source::Stripe, Some(user_id), Some(&note)).await?)
}
None => None,
(None, None) => None,
};
if state.config.terms_consent && !session.terms_accepted() {
tracing::warn!(session = %session.id, "paid without the terms consent");
@@ -233,7 +263,8 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, A
.await?;
// The confirmation confirms the withdrawal waiver: only when it was given.
if session.terms_accepted() {
confirm_by_email(&mut tx, state, session, user_id, package, amount_huf.unwrap_or(i64::from(price_huf))).await?;
let amount = amount_huf.unwrap_or(i64::from(price_huf));
confirm_by_email(&mut tx, state, session, user_id, package, amount, gift.as_ref()).await?;
}
let buyer = invoices::Buyer::from_stripe(session.customer_details.as_ref().unwrap_or(&Value::Null), None);
let (item, comment) = package.invoice_item();
@@ -253,6 +284,7 @@ async fn confirm_by_email(
user_id: Option<Uuid>,
package: &packages::Package,
amount_huf: i64,
gift: Option<&super::gifts::Paid>,
) -> Result<(), ApiError> {
let account: Option<(String, String, Option<String>)> = match user_id {
Some(id) => {
@@ -272,7 +304,7 @@ async fn confirm_by_email(
},
};
let base = &state.config.public_base_url;
let payload = json!({
let mut payload = json!({
"url": format!("{base}/csomagok"),
"display_name": name,
"package_name": package.name,
@@ -282,6 +314,18 @@ async fn confirm_by_email(
"terms_url": format!("{base}/aszf"),
"invoices_url": format!("{base}/szamlak"),
});
if let Some(gift) = gift {
payload["url"] = json!(format!("{base}/ajandekaim"));
payload["gift"] = json!({
"promo_code": gift.code,
"recipient_name": gift.recipient_name,
"recipient_email": gift.recipient_email,
});
// Handed over by the buyer: the card comes with the confirmation.
if gift.recipient_email.is_none() {
payload["gift_card"] = gift.card.clone();
}
}
super::auth::queue_email_to(tx, user_id, &to, "purchase_confirmation", &locale, payload).await
}
@@ -305,13 +349,13 @@ pub async fn checkout_status(
auth: AuthUser,
WithRejection(Path(id), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<Json<Value>> {
let row: Option<(String, Option<OffsetDateTime>)> =
sqlx::query_as("SELECT package, completed_at FROM stripe_checkouts WHERE id = $1 AND user_id = $2")
let row: Option<(String, Option<OffsetDateTime>, Option<Uuid>)> =
sqlx::query_as("SELECT package, completed_at, gift_id FROM stripe_checkouts WHERE id = $1 AND user_id = $2")
.bind(&id)
.bind(auth.id())
.fetch_optional(&state.db)
.await?;
let (package_id, completed_at) = row.ok_or(ApiError::NotFound("payment"))?;
let (package_id, completed_at, gift_id) = row.ok_or(ApiError::NotFound("payment"))?;
let mut status = if completed_at.is_some() { "paid" } else { "pending" };
if let (None, Some(config)) = (completed_at, &state.config.stripe) {
let session = state.stripe.get_session(config, &id).await?;
@@ -322,10 +366,23 @@ pub async fn checkout_status(
status = "expired";
}
}
let gift = match gift_id {
Some(id) => {
let (name, to): (Option<String>, Option<String>) =
sqlx::query_as("SELECT recipient_name, recipient_email FROM gifts WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?
.unwrap_or_default();
Some(json!({ "id": id, "recipient_name": name, "recipient_email": to }))
}
None => None,
};
Ok(Json(json!({
"status": status,
"package": package_id,
"name": packages::find(&package_id).map(|p| p.name),
"gift": gift,
})))
}
+40 -9
View File
@@ -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))
}
+254
View File
@@ -3283,3 +3283,257 @@ async fn the_sky_is_shared_and_kept(pool: PgPool) {
}
assert_eq!(calls() - before, 2);
}
// --- gifts -----------------------------------------------------------------------------------
async fn natal_left(app: &TestApp, token: &str) -> i64 {
app.get("/v1/me", Some(token)).await.body["analyses_left"]["natal"].as_i64().unwrap()
}
async fn gift_card_pdf(app: &TestApp, token: &str, id: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
let req = Request::builder()
.uri(format!("/v1/gifts/{id}/card.pdf"))
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())
.unwrap();
let resp = app.router.clone().oneshot(req).await.unwrap();
let (status, headers) = (resp.status(), resp.headers().clone());
(status, headers, resp.into_body().collect().await.unwrap().to_bytes().to_vec())
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPool) {
let app = TestApp::with_config(pool, |c| with_stripe(c, "sk_live_fake")).await;
let anna = app.register("anna@example.com", "Anna").await;
let checkout = |body: Value| app.post("/v1/gifts/checkout", Some(&anna), body);
// Only the main packages, for someone with a name, the address typed twice, no links.
let r = checkout(json!({"package": "addon_tarot", "recipient_name": "Bea"})).await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
let r = checkout(json!({"package": "couple", "recipient_name": " "})).await;
assert_eq!(
(r.status, r.body["error"]["message"].as_str()),
(StatusCode::BAD_REQUEST, Some("Add meg, kinek szól az ajándék."))
);
let r = checkout(json!({"package": "couple", "recipient_name": "Bea", "recipient_email": "bea@example.com", "recipient_email_confirm": "bia@example.com"})).await;
assert_eq!(
(r.status, r.body["error"]["message"].as_str()),
(StatusCode::BAD_REQUEST, Some("A két e-mail-cím nem egyezik."))
);
let r =
checkout(json!({"package": "couple", "recipient_name": "Bea", "message": "Nézd: https://evil.example"})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
let r = checkout(json!({"package": "couple", "recipient_name": "Bea", "from_name": "x".repeat(61)})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
assert_eq!(sqlx::query_scalar::<_, i64>("SELECT count(*) FROM gifts").fetch_one(&app.pool).await.unwrap(), 0);
let r = checkout(json!({"package": "couple", "recipient_name": " Bea ", "recipient_email": " Bea@Example.com", "recipient_email_confirm": "bea@example.com ",
"from_name": "Anna", "message": "Boldog születésnapot!\nÖlel: Anna"}))
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let gift_id = r.body["id"].as_str().unwrap().to_string();
let session = r.body["url"].as_str().unwrap().rsplit('/').next().unwrap().to_string();
assert_eq!(
stripe_form(&session, "line_items[0][price_data][product_data][name]").as_deref(),
Some("Sorsfonalak – Páros (ajándék)")
);
assert_eq!(stripe_form(&session, "metadata[gift_id]").as_deref(), Some(gift_id.as_str()));
assert_eq!(
stripe_form(&session, "success_url").as_deref(),
Some("https://sorsfonalak.test/ajandekaim?fizetes={CHECKOUT_SESSION_ID}")
);
// Not paid: not listed, nothing sent.
assert_eq!(app.get("/v1/gifts", Some(&anna)).await.body["gifts"], json!([]));
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 0);
let event = json!({"id": "evt_g", "type": "checkout.session.completed",
"data": {"object": {"id": session, "payment_status": "paid", "status": "complete",
"consent": {"terms_of_service": "accepted"},
"amount_total": 600000, "currency": "huf", "payment_intent": "pi_g",
"customer_details": {"name": "Kovács Anna", "email": "anna@example.com",
"address": {"line1": "Fő utca 1.", "city": "Szeged", "postal_code": "6720", "country": "HU"},
"tax_ids": []}}}});
let body = event.to_string();
let signature =
crate::stripe::sign("whsec_fake", body.as_bytes(), time::OffsetDateTime::now_utc().unix_timestamp());
for _ in 0..2 {
let r = app
.call_with(
"POST",
"/v1/payments/stripe/webhook",
None,
Some(event.clone()),
&[("stripe-signature", &signature)],
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
// The buyer gets no package, the recipient one e-mail with the card, the
// buyer a confirmation that says it was a gift.
assert!(stripe_orders(&app.pool, "anna@example.com").await.is_empty());
assert_eq!(natal_left(&app, &anna).await, 0);
let (mail,): (Value,) = sqlx::query_as(
"SELECT payload FROM email_outbox WHERE to_email = 'bea@example.com' AND template = 'gift_package'",
)
.fetch_one(&app.pool)
.await
.unwrap();
let code = mail["promo_code"].as_str().unwrap().to_string();
assert_eq!(mail["url"], format!("https://sorsfonalak.test/bevaltas?kod={code}"));
assert_eq!((&mail["from_name"], &mail["message"]), (&json!("Anna"), &json!("Boldog születésnapot!\nÖlel: Anna")));
assert_eq!(mail["gift_card"]["contents"][0], "2 részletes képletelemzés");
assert!(email_templates::render("gift_package", "hu", &mail).unwrap().text.contains(&code));
let (confirmation,): (Value,) = sqlx::query_as(
"SELECT payload FROM email_outbox WHERE to_email = 'anna@example.com' AND template = 'purchase_confirmation'",
)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(
confirmation["gift"],
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com"})
);
assert!(confirmation["gift_card"].is_null(), "the recipient has the card");
assert_eq!(confirmation["url"], "https://sorsfonalak.test/ajandekaim");
email_templates::render("purchase_confirmation", "hu", &confirmation).unwrap();
// The invoice is the buyer's, as for any purchase.
let invoices: i64 = sqlx::query_scalar("SELECT count(*) FROM invoices WHERE checkout_id = $1")
.bind(&session)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(invoices, 1);
let r = app.get(&format!("/v1/payments/checkout/{session}"), Some(&anna)).await;
assert_eq!(r.body["gift"], json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com"}));
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
assert_eq!((&gift["code"], &gift["status"], &gift["sendings"]), (&json!(code), &json!("open"), &json!(1)));
assert_eq!((&gift["package"]["name"], &gift["can_send"]), (&json!("Páros"), &json!(true)));
assert_eq!(
(&gift["recipient_name"], &mail["recipient_name"], &mail["gift_card"]["recipient_name"]),
(&json!("Bea"), &json!("Bea"), &json!("Bea"))
);
// A gift code is not a promo code: admins cannot withdraw it.
let promo: i64 = sqlx::query_scalar("SELECT count(*) FROM promo_codes").fetch_one(&app.pool).await.unwrap();
assert_eq!(promo, 0);
// The card, for the buyer only.
let (status, headers, pdf) = gift_card_pdf(&app, &anna, &gift_id).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(headers["content-type"], "application/pdf");
assert_eq!(headers["content-disposition"], format!("attachment; filename=\"sorsfonalak-ajandek-{code}.pdf\""));
assert!(pdf.starts_with(b"%PDF-"));
let bela = app.register("bela@example.com", "Béla").await;
assert_eq!(gift_card_pdf(&app, &bela, &gift_id).await.0, StatusCode::NOT_FOUND);
assert_eq!(app.get("/v1/gifts", Some(&bela)).await.body["gifts"], json!([]));
// Sending again: not at once, then to a corrected address.
let send_url = format!("/v1/gifts/{gift_id}/send");
let send =
|to: &str| app.post(&send_url, Some(&anna), json!({"recipient_email": to, "recipient_email_confirm": to}));
let r = send("cili@example.com").await;
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("gift_send_wait")));
sqlx::query("UPDATE gifts SET last_sent_at = now() - interval '11 minutes'").execute(&app.pool).await.unwrap();
let r = send("cili@example.com").await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(2)));
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
let r = app
.post(
&format!("/v1/gifts/{gift_id}/send"),
Some(&bela),
json!({"recipient_email": "x@example.com", "recipient_email_confirm": "x@example.com"}),
)
.await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
// Redeemed by someone who has the package's units already: the whole
// package is added (a promo code would only fill up to it).
let admin = app.register("admin@example.com", "Admin").await;
let r = app.post("/v1/admin/promo-codes", Some(&admin), json!({"package": "couple", "count": 1})).await;
let promo = r.body["codes"][0].as_str().unwrap().to_string();
assert_eq!(app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": promo})).await.status, StatusCode::OK);
assert_eq!(natal_left(&app, &bela).await, 2);
let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": code.to_lowercase()})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!((&r.body["gift"]["from_name"], &r.body["added"]["natal"]), (&json!("Anna"), &json!(2)));
assert_eq!(natal_left(&app, &bela).await, 4);
let source: (String, i32) = sqlx::query_as(
"SELECT o.source, o.price_huf FROM package_orders o JOIN users u ON u.id = o.user_id \
WHERE u.email = 'bela@example.com' AND o.source = 'gift'",
)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(source, ("gift".to_string(), 0));
let r = app.get("/v1/gifts", Some(&anna)).await;
assert_eq!((&r.body["gifts"][0]["status"], &r.body["gifts"][0]["can_send"]), (&json!("redeemed"), &json!(false)));
sqlx::query("UPDATE gifts SET last_sent_at = now() - interval '11 minutes'").execute(&app.pool).await.unwrap();
assert_eq!(send("dora@example.com").await.body["error"]["code"], "gift_redeemed");
// Used once, like any code.
let r = app.post("/v1/promo-codes/redeem", Some(&admin), json!({"code": code})).await;
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("promo_used")));
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_gift_handed_over_by_the_buyer(pool: PgPool) {
// The stand-in payment: paid at once.
let app = TestApp::new(pool).await;
let anna = app.register("anna@example.com", "Anna").await;
let r = app
.post(
"/v1/gifts/checkout",
Some(&anna),
json!({"package": "family", "recipient_name": "Bea", "from_name": "Anna"}),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert!(r.body["url"].is_null());
let id = r.body["id"].as_str().unwrap().to_string();
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
assert_eq!(
(&gift["recipient_email"], &gift["sendings"], &gift["can_send"]),
(&Value::Null, &json!(0), &json!(true))
);
let sent: i64 = sqlx::query_scalar("SELECT count(*) FROM email_outbox WHERE template = 'gift_package'")
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(sent, 0);
assert!(gift_card_pdf(&app, &anna, &id).await.2.starts_with(b"%PDF-"));
// Sent by e-mail later after all.
let r = app
.post(
&format!("/v1/gifts/{id}/send"),
Some(&anna),
json!({"recipient_email": "bea@example.com", "recipient_email_confirm": "bea@example.hu"}),
)
.await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
let r = app
.post(
&format!("/v1/gifts/{id}/send"),
Some(&anna),
json!({"recipient_email": "bea@example.com", "recipient_email_confirm": "bea@example.com"}),
)
.await;
assert_eq!((r.status, &r.body["sendings"]), (StatusCode::OK, &json!(1)));
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 1);
// The buyer's account goes: the gift stays redeemable, without its personal parts.
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "DELETE"}))).await;
assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body);
let left: (Option<uuid::Uuid>, Option<String>, Option<String>, Option<String>) =
sqlx::query_as("SELECT buyer_id, recipient_name, recipient_email, from_name FROM gifts")
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(left, (None, None, None, None));
let code: String = sqlx::query_scalar("SELECT code FROM gifts").fetch_one(&app.pool).await.unwrap();
let bea = app.register("bea@example.com", "Bea").await;
let r = app.post("/v1/promo-codes/redeem", Some(&bea), json!({"code": code})).await;
assert_eq!((r.status, &r.body["added"]["natal"]), (StatusCode::OK, &json!(6)));
}