Files
sorsfonalak/services/backend/src/routes/gifts.rs
T

637 lines
26 KiB
Rust
Raw Normal View History

//! 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_to};
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::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>,
refunded_at: Option<OffsetDateTime>,
refund_id: Option<String>,
}
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";
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 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());
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),
"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);
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 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."));
}
gift.refused_if_refunded()?;
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."));
}
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(&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 }))
}
// --- 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<String>,
recipient_name: Option<String>,
recipient_email: Option<String>,
paid_at: Option<OffsetDateTime>,
code: Option<String>,
redeemed_at: Option<OffsetDateTime>,
redeemed_by: Option<String>,
refunded_at: Option<OffsetDateTime>,
refund_id: Option<String>,
refund_error: Option<String>,
checkout_id: Option<String>,
live: Option<bool>,
amount_huf: Option<i32>,
invoice_number: Option<String>,
invoice_status: Option<String>,
storno_status: Option<String>,
storno_number: Option<String>,
storno_error: Option<String>,
}
#[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<String>,
}
/// 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<axum::extract::Query<AdminQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
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::<String>().to_uppercase();
let rows: Vec<AdminGift> = 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 \
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<Value> = 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 })),
})
})
.collect();
Ok(Json(json!({ "gifts": gifts, "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<Json<Value>> {
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<String>)> = 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?;
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) }),
))
}