414 lines
16 KiB
Rust
414 lines
16 KiB
Rust
//! 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(¬e)).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 }))
|
||
|
|
}
|