//! 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 adds the whole package, while a promo //! code only fills the units up to the package's (both are redeemed in the //! same place). It is not withdrawn like a promo code either: only when the //! buyer withdraws from the purchase (within 14 days, while it is not //! redeemed). Then an admin refunds it: the code is withdrawn, Stripe pays //! the money back, and the worker cancels the invoice in Billingo (storno). 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_at}; use super::promo::{CODE_LEN, display}; use super::{Body, IdPath, St, payments}; use crate::AppState; use crate::auth::{AdminUser, 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::on_sale(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, 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) -> Result, ApiError> { let name: Option = name .map(|n| n.chars().filter(|c| !c.is_control()).collect::().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, package: String, recipient_name: Option, recipient_email: Option, from_name: Option, message: Option, paid_at: Option, code: Option, redeemed_at: Option, sendings: i32, last_sent_at: Option, refunded_at: Option, refund_id: Option, /// E-mailed not before this (none: at once). send_at: Option, /// The last e-mail queued for it. email_id: Option, /// That e-mail: `scheduled`, `sending`, `sent` or `failed` (none: no /// e-mail, or cleaned up a week after it went out). email_state: Option, } const COLUMNS: &str = "id, buyer_id, package, recipient_name, recipient_email, from_name, message, paid_at, code, \ redeemed_at, sendings, last_sent_at, refunded_at, refund_id, send_at, email_id, \ (SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \ WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \ FROM email_outbox o WHERE o.id = gifts.email_id) AS email_state"; /// The year a Christmas gift wishes for ("csillagos 2027-et"), if bought /// between 15 November and 6 January (Budapest time; no summer time then). fn christmas_year(paid: OffsetDateTime) -> Option { let local = paid.to_offset(time::UtcOffset::from_hms(1, 0, 0).expect("an offset")); match (local.month(), local.day()) { (time::Month::November, 15..) | (time::Month::December, _) => Some(local.year() + 1), (time::Month::January, ..=6) => Some(local.year()), _ => None, } } 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 { 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, "christmas_year": self.christmas(), })) } /// The year a Christmas gift wishes for (see `christmas_year`). fn christmas(&self) -> Option { christmas_year(self.paid_at.unwrap_or_else(OffsetDateTime::now_utc)) } fn status(&self) -> &'static str { match (self.redeemed_at, self.refunded_at) { (Some(_), _) => "redeemed", (_, Some(_)) => "refunded", _ => "open", } } /// Withdrawn by a refund: it cannot be redeemed, sent or downloaded. fn refused_if_refunded(&self) -> Result<(), ApiError> { match self.refunded_at { Some(_) => { Err(ApiError::conflict("gift_refunded", "Ezt az ajándékot visszatérítettük, a kód már nem érvényes.")) } None => Ok(()), } } fn view(&self) -> Value { let status = self.status(); let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc()); // A timed e-mail still waiting can be sent now instead. let waiting = self.email_state.as_deref() == Some("scheduled"); 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), "refunded_at": rfc3339_opt(self.refunded_at), "send_at": rfc3339_opt(self.send_at), "email_state": self.email_state, "christmas": self.christmas().is_some(), "sendings": self.sendings, "can_send": status == "open" && self.sendings - i32::from(waiting) < MAX_SENDINGS, "send_again_at": rfc3339_opt(next_send.filter(|_| !waiting)), }) } } /// 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 { 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, /// Who gets the gift by e-mail; none: the buyer hands it over. recipient_email: Option, /// The address typed again. recipient_email_confirm: Option, from_name: Option, message: Option, /// E-mail it then (RFC 3339; none: right after paying), e.g. on Christmas morning. send_at: Option, } /// How far ahead a gift e-mail can be timed. const MAX_SCHEDULE: time::Duration = time::Duration::days(366); /// A time to e-mail a gift: in the future (a few minutes at least), within a year. fn schedule(at: Option<&str>) -> Result, ApiError> { let Some(at) = at.map(str::trim).filter(|a| !a.is_empty()) else { return Ok(None) }; let at = OffsetDateTime::parse(at, &time::format_description::well_known::Rfc3339) .map_err(|_| ApiError::BadRequest("send_at must be an RFC 3339 time".into()))?; let now = OffsetDateTime::now_utc(); if at < now + time::Duration::minutes(5) { return Err(ApiError::BadRequest("Az időzítés legyen a jövőben.".into())); } if at > now + MAX_SCHEDULE { return Err(ApiError::BadRequest("Legfeljebb egy évre előre lehet időzíteni.".into())); } Ok(Some(at)) } /// 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, ) -> ApiResult> { 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)?; let send_at = schedule(req.send_at.as_deref())?; if send_at.is_some() && to.is_none() { return Err(ApiError::BadRequest("Időzíteni csak az e-mailben küldött ajándékot lehet.".into())); } // 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, send_at) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", ) .bind(id) .bind(auth.id()) .bind(package.id) .bind(&name) .bind(&to) .bind(&from) .bind(&message) .bind(send_at) .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, pub recipient_email: Option, pub card: Value, /// When it is e-mailed, on the Budapest clock (`2026-12-24 08:00`); none: at once. pub send_at_local: Option, } /// A new gift code, never the same as a promo code or another gift's. async fn new_code(tx: &mut PgConnection) -> Result { 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 { 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() { // Timed for a moment already past (paid late): at once. let at = gift.send_at.filter(|t| *t > OffsetDateTime::now_utc()); send(tx, state, &gift, &to, at).await?; } tracing::info!(gift = %id, package = %gift.package, by_email = gift.recipient_email.is_some(), "gift paid"); } let send_at_local: Option = sqlx::query_scalar( "SELECT to_char(send_at AT TIME ZONE 'Europe/Budapest', 'YYYY-MM-DD HH24:MI') FROM gifts \ WHERE id = $1 AND send_at > now()", ) .bind(id) .fetch_optional(&mut *tx) .await? .flatten(); Ok(Paid { code: display(gift.code()?), card: gift.card_payload(state)?, recipient_name: gift.recipient_name, recipient_email: gift.recipient_email, send_at_local, }) } /// Queues the gift e-mail (with the card) to `to`, in the buyer's language, /// not before `at` (none: at once). async fn send( tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str, at: Option, ) -> Result<(), ApiError> { let locale: Option = 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)?, "christmas_year": gift.christmas(), }); // Not the recipient's account (if they have one): no user id. let email = queue_email_at(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload, at).await?; sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now(), email_id = $2 WHERE id = $1") .bind(gift.id) .bind(email) .execute(&mut *tx) .await?; Ok(()) } /// Takes back the gift's e-mail if it has not gone out yet (sent now /// instead, or refunded): a timed one would come later otherwise. It does /// not count as a sending then. async fn cancel_pending_email(conn: &mut PgConnection, gift: &Gift) -> Result { let Some(email) = gift.email_id else { return Ok(false) }; let taken = sqlx::query("DELETE FROM email_outbox WHERE id = $1 AND sent_at IS NULL AND failed_at IS NULL") .bind(email) .execute(&mut *conn) .await? .rows_affected() == 1; if taken { sqlx::query("UPDATE gifts SET sendings = greatest(sendings - 1, 0) WHERE id = $1") .bind(gift.id) .execute(&mut *conn) .await?; } Ok(taken) } /// The user's paid gifts, newest first. pub async fn list(State(state): St, auth: AuthUser) -> ApiResult> { let gifts: Vec = 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::>(), "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 { let mut conn = state.db.acquire().await?; let gift = own_gift(&mut conn, id, auth.id(), false).await?; drop(conn); gift.refused_if_refunded()?; let package = gift.package()?; let code = display(gift.code()?); let url = redeem_url(&state, gift.code()?); let filename = format!("sorsfonalak-ajandek-{code}.pdf"); let christmas = gift.christmas(); 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(), christmas, }) }) .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, ) -> ApiResult> { 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.")); } gift.refused_if_refunded()?; // A timed e-mail still waiting is replaced by this one, not added to it. let waiting = gift.email_state.as_deref() == Some("scheduled"); if gift.sendings - i32::from(waiting) >= 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 !waiting && 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.")); } // Now, instead of a timed e-mail still waiting. cancel_pending_email(&mut tx, &gift).await?; sqlx::query("UPDATE gifts SET recipient_email = $2, send_at = NULL WHERE id = $1") .bind(id) .bind(&to) .execute(&mut *tx) .await?; gift.recipient_email = Some(to.clone()); send(&mut tx, &state, &gift, &to, None).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, } /// 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, ApiError> { let gift: Option = 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.")); } if gift.refunded_at.is_some() { return Err(ApiError::conflict("promo_revoked", "Ez a kód már nem érvényes.")); } 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 })) } // --- admin ------------------------------------------------------------------------------------- /// The buyer may withdraw from a gift purchase this long (ÁSZF 6.). const WITHDRAWAL_DAYS: i64 = 14; /// A gift as admins see it, with its payment, invoice and storno. #[derive(sqlx::FromRow)] struct AdminGift { id: Uuid, package: String, buyer_email: Option, recipient_name: Option, recipient_email: Option, paid_at: Option, code: Option, redeemed_at: Option, redeemed_by: Option, refunded_at: Option, refund_id: Option, refund_error: Option, checkout_id: Option, live: Option, amount_huf: Option, invoice_number: Option, invoice_status: Option, storno_status: Option, storno_number: Option, storno_error: Option, send_at: Option, email_state: Option, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct AdminQuery { /// Part of the code, the buyer's or the recipient's address, or the recipient's name. q: Option, } /// Admin: the paid gifts, newest first (at most 200). pub async fn admin_list( State(state): St, _admin: AdminUser, WithRejection(axum::extract::Query(query), _): WithRejection, ApiError>, ) -> ApiResult> { let search = query.q.map(|q| q.trim().to_string()).filter(|q| !q.is_empty()); // A code is searched for without its dashes. let code: String = search.as_deref().unwrap_or("").chars().filter(char::is_ascii_alphanumeric).collect::().to_uppercase(); let rows: Vec = sqlx::query_as( "SELECT g.id, g.package, b.email AS buyer_email, g.recipient_name, g.recipient_email, g.paid_at, g.code, \ g.redeemed_at, r.email AS redeemed_by, g.refunded_at, g.refund_id, g.refund_error, \ c.id AS checkout_id, c.live, coalesce(c.amount_huf, c.price_huf) AS amount_huf, \ i.invoice_number, i.status AS invoice_status, \ x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error, \ g.send_at, \ (SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \ WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \ FROM email_outbox o WHERE o.id = g.email_id) AS email_state \ FROM gifts g LEFT JOIN users b ON b.id = g.buyer_id LEFT JOIN users r ON r.id = g.redeemed_by \ LEFT JOIN stripe_checkouts c ON c.gift_id = g.id LEFT JOIN invoices i ON i.checkout_id = c.id \ LEFT JOIN invoice_cancellations x ON x.invoice_id = i.id \ WHERE g.paid_at IS NOT NULL \ AND ($1::text IS NULL OR b.email ILIKE '%' || $1 || '%' OR g.recipient_email ILIKE '%' || $1 || '%' \ OR g.recipient_name ILIKE '%' || $1 || '%' OR ($2 <> '' AND g.code LIKE '%' || $2 || '%')) \ ORDER BY g.paid_at DESC LIMIT 200", ) .bind(&search) .bind(&code) .fetch_all(&state.db) .await?; let now = OffsetDateTime::now_utc(); let gifts: Vec = rows .into_iter() .map(|g| { let status = match (g.redeemed_at, g.refunded_at) { (Some(_), _) => "redeemed", (_, Some(_)) => "refunded", _ => "open", }; json!({ "id": g.id, "package": { "id": g.package, "name": packages::find(&g.package).map(|p| p.name) }, "buyer_email": g.buyer_email, "recipient_name": g.recipient_name, "recipient_email": g.recipient_email, "paid_at": rfc3339_opt(g.paid_at), "code": g.code.as_deref().map(display), "status": status, "redeemed_at": rfc3339_opt(g.redeemed_at), "redeemed_by": g.redeemed_by, "refunded_at": rfc3339_opt(g.refunded_at), // Withdrawn, but Stripe has not paid back yet (it refused: try again). "refund_pending": g.refunded_at.is_some() && g.refund_id.is_none() && g.checkout_id.is_some(), "refund_id": g.refund_id, "refund_error": g.refund_error, "within_withdrawal": g.paid_at.is_some_and(|t| now - t <= time::Duration::days(WITHDRAWAL_DAYS)), "checkout": g.checkout_id.map(|id| json!({ "id": id, "live": g.live, "amount_huf": g.amount_huf })), "invoice": g.invoice_status.map(|s| json!({ "number": g.invoice_number, "status": s })), "storno": g.storno_status.map(|s| json!({ "status": s, "number": g.storno_number, "error": g.storno_error })), "send_at": rfc3339_opt(g.send_at), "email_state": g.email_state, }) }) .collect(); // The timed e-mails by hour (Budapest clock): how many wait, went out or failed. let schedule: Vec<(String, i64, i64, i64)> = sqlx::query_as( "SELECT to_char(date_trunc('hour', g.send_at AT TIME ZONE 'Europe/Budapest'), 'YYYY-MM-DD HH24:MI'), \ count(*) FILTER (WHERE o.id IS NOT NULL AND o.sent_at IS NULL AND o.failed_at IS NULL), \ count(*) FILTER (WHERE o.sent_at IS NOT NULL OR (o.id IS NULL AND g.send_at <= now())), \ count(*) FILTER (WHERE o.failed_at IS NOT NULL) \ FROM gifts g LEFT JOIN email_outbox o ON o.id = g.email_id \ WHERE g.send_at IS NOT NULL AND g.paid_at IS NOT NULL AND g.refunded_at IS NULL \ AND g.send_at > now() - interval '30 days' \ GROUP BY 1 ORDER BY 1", ) .fetch_all(&state.db) .await?; let schedule: Vec = schedule .into_iter() .map(|(at, waiting, sent, failed)| json!({ "at": at, "waiting": waiting, "sent": sent, "failed": failed })) .collect(); Ok(Json(json!({ "gifts": gifts, "schedule": schedule, "withdrawal_days": WITHDRAWAL_DAYS }))) } /// Admin: refunds a gift the buyer withdrew from. Refused once it is /// redeemed (checked under the row's lock, as redeeming is). The code is /// withdrawn first, then Stripe pays the money back (one refund per gift, /// however often this is pressed), and the invoice's storno is queued for the /// worker. If Stripe refuses, the gift stays withdrawn and this can be tried /// again. pub async fn admin_refund( State(state): St, admin: AdminUser, WithRejection(Path(id), _): IdPath, ) -> ApiResult> { let mut tx = state.db.begin().await?; let gift: Gift = sqlx::query_as(&format!("SELECT {COLUMNS} FROM gifts WHERE id = $1 AND paid_at IS NOT NULL FOR UPDATE")) .bind(id) .fetch_optional(&mut *tx) .await? .ok_or(ApiError::NotFound("gift"))?; if gift.redeemed_at.is_some() { return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották, nem téríthető vissza.")); } let checkout: Option<(String, Option)> = sqlx::query_as( "SELECT id, payment_intent FROM stripe_checkouts WHERE gift_id = $1 AND completed_at IS NOT NULL", ) .bind(id) .fetch_optional(&mut *tx) .await?; // Done: Stripe paid back, or there was nothing to pay back (a stand-in payment). if gift.refund_id.is_some() || (gift.refunded_at.is_some() && checkout.is_none()) { return Err(ApiError::conflict("gift_refunded", "Ezt az ajándékot már visszatérítettük.")); } sqlx::query("UPDATE gifts SET refunded_at = coalesce(refunded_at, now()), refunded_by = $2 WHERE id = $1") .bind(id) .bind(admin.0.id()) .execute(&mut *tx) .await?; // A timed e-mail not gone out yet stays unsent. cancel_pending_email(&mut tx, &gift).await?; if let Some((checkout_id, _)) = &checkout { let reason = format!("Elállás az ajándékcsomag vásárlásától (beváltás előtt), kód: {}", display(gift.code()?)); sqlx::query( "INSERT INTO invoice_cancellations (id, invoice_id, reason) \ SELECT $1, i.id, $2 FROM invoices i WHERE i.checkout_id = $3 ON CONFLICT (invoice_id) DO NOTHING", ) .bind(Uuid::now_v7()) .bind(&reason) .bind(checkout_id) .execute(&mut *tx) .await?; } tx.commit().await?; tracing::info!(admin = %admin.0.id(), gift = %id, "gift withdrawn for a refund"); // The money back (a stand-in payment has none). if let Some((checkout_id, payment_intent)) = checkout { let refunded = match (state.config.stripe.as_ref(), payment_intent.as_deref()) { (Some(config), Some(intent)) => { let gift_id = id.to_string(); state .stripe .refund( config, intent, &format!("gift-refund-{id}"), &[("gift_id", &gift_id), ("checkout", &checkout_id)], ) .await } _ => Err(ApiError::conflict("refund_failed", "Ehhez a fizetéshez nem érhető el a Stripe.")), }; match refunded { Ok(refund) => { sqlx::query("UPDATE gifts SET refund_id = $2, refund_error = NULL WHERE id = $1") .bind(id) .bind(&refund.id) .execute(&state.db) .await?; tracing::info!(gift = %id, refund = %refund.id, status = ?refund.status, "gift refunded"); } Err(e) => { sqlx::query("UPDATE gifts SET refund_error = $2 WHERE id = $1") .bind(id) .bind(e.to_string()) .execute(&state.db) .await?; return Err(e); } } } let gift: Gift = sqlx::query_as(&format!("SELECT {COLUMNS} FROM gifts WHERE id = $1")).bind(id).fetch_one(&state.db).await?; Ok(Json( json!({ "status": gift.status(), "refund_id": gift.refund_id, "refunded_at": rfc3339_opt(gift.refunded_at) }), )) } #[cfg(test)] mod tests { use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; use super::christmas_year; fn at(s: &str) -> OffsetDateTime { OffsetDateTime::parse(s, &Rfc3339).unwrap() } #[test] fn christmas_runs_from_mid_november_to_epiphany() { assert_eq!(christmas_year(at("2026-11-14T22:59:00Z")), None); assert_eq!(christmas_year(at("2026-11-14T23:00:00Z")), Some(2027)); assert_eq!(christmas_year(at("2026-12-31T23:30:00Z")), Some(2027)); assert_eq!(christmas_year(at("2027-01-06T22:59:00Z")), Some(2027)); assert_eq!(christmas_year(at("2027-01-06T23:00:00Z")), None); assert_eq!(christmas_year(at("2027-07-01T12:00:00Z")), None); } }