Gift withdrawal: admin refund (Stripe) and invoice storno (Billingo)
- The buyer may withdraw from a gift purchase within 14 days while the
code is not redeemed (ÁSZF 3., 5., 6.; terms version 2026-11-23); the
consent on Stripe's page and the confirmation e-mail say so
- Admin → Ajándékok: the gifts with payment, invoice and storno; the
refund button locks the gift and refuses a redeemed one, withdraws the
code, refunds the PaymentIntent on Stripe (one refund per gift via the
Idempotency-Key, retry when Stripe refuses) and queues the storno
- Worker: cancels the issued invoice in Billingo (POST /documents/{id}/
cancel, e-mailed to the buyer), keeps the storno invoice's id and
number; a lost answer is not asked again but left for an admin
- A withdrawn code cannot be redeemed, sent or downloaded; "My gifts"
shows it as refunded
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -8,9 +8,12 @@
|
||||
//! 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.
|
||||
//! 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};
|
||||
@@ -27,7 +30,7 @@ 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::auth::{AdminUser, AuthUser};
|
||||
use crate::credits::Unit;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::packages::{self, Package, Source, Tier};
|
||||
@@ -87,10 +90,12 @@ struct Gift {
|
||||
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";
|
||||
redeemed_at, sendings, last_sent_at, refunded_at, refund_id";
|
||||
|
||||
impl Gift {
|
||||
fn package(&self) -> Result<&'static Package, ApiError> {
|
||||
@@ -115,8 +120,26 @@ impl Gift {
|
||||
}))
|
||||
}
|
||||
|
||||
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 = if self.redeemed_at.is_some() { "redeemed" } else { "open" };
|
||||
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,
|
||||
@@ -129,6 +152,7 @@ impl Gift {
|
||||
"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),
|
||||
@@ -310,6 +334,7 @@ pub async fn card(
|
||||
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()?);
|
||||
@@ -361,6 +386,7 @@ pub async fn send_again(
|
||||
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",
|
||||
@@ -399,6 +425,9 @@ pub(super) async fn redeem(tx: &mut PgConnection, code: &str, user_id: Uuid) ->
|
||||
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?;
|
||||
@@ -411,3 +440,197 @@ pub(super) async fn redeem(tx: &mut PgConnection, code: &str, user_id: Uuid) ->
|
||||
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) }),
|
||||
))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user