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) }),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -122,6 +122,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.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/gifts", get(gifts::admin_list))
|
||||
.route("/v1/admin/gifts/{id}/refund", post(gifts::admin_refund))
|
||||
.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))
|
||||
|
||||
@@ -86,7 +86,7 @@ pub fn method(config: &crate::config::Config) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
/// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`.
|
||||
pub const TERMS_VERSION: &str = "2026-11-22";
|
||||
pub const TERMS_VERSION: &str = "2026-11-23";
|
||||
|
||||
/// Only admins can buy through Stripe: until purchases open, and always with a
|
||||
/// test key (nobody gets packages with Stripe's test cards, nobody types a
|
||||
@@ -181,15 +181,22 @@ pub(super) async fn start_checkout(
|
||||
// Every purchase accepts the terms and asks for immediate delivery,
|
||||
// giving up the 14-day withdrawal right (45/2014. Korm. rendelet 29. §).
|
||||
// Stripe needs the terms URL in its dashboard (Public details) for this.
|
||||
// A gift is performed when its code is redeemed: until then (within
|
||||
// the 14 days) the buyer may withdraw.
|
||||
let terms = format!("{}/aszf", state.config.public_base_url);
|
||||
let message = if gift.is_some() {
|
||||
format!(
|
||||
"Elfogadom az [ÁSZF-et]({terms}), és kérem, hogy az ajándékkód beváltásakor a szolgáltatás azonnal \
|
||||
megkezdődjön. Tudomásul veszem, hogy a beváltással a 14 napos elállási jog megszűnik."
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Elfogadom az [ÁSZF-et]({terms}), kérem a szolgáltatás azonnali megkezdését, és tudomásul veszem, \
|
||||
hogy ezzel elveszítem a 14 napos elállási jogomat."
|
||||
)
|
||||
};
|
||||
form.push(field("consent_collection[terms_of_service]", "required"));
|
||||
form.push(field(
|
||||
"custom_text[terms_of_service_acceptance][message]",
|
||||
&format!(
|
||||
"Elfogadom az [ÁSZF-et]({}/aszf), kérem a szolgáltatás azonnali megkezdését, és tudomásul veszem, \
|
||||
hogy ezzel elveszítem a 14 napos elállási jogomat.",
|
||||
state.config.public_base_url
|
||||
),
|
||||
));
|
||||
form.push(field("custom_text[terms_of_service_acceptance][message]", &message));
|
||||
}
|
||||
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)))?;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The little of Stripe's API we use: Checkout Sessions (a hosted payment
|
||||
//! page for one package) and webhook signature checking. The package catalog
|
||||
//! page for one package), refunds (a gift given back) and webhook signature
|
||||
//! checking. The package catalog
|
||||
//! stays in `packages.rs`; each session carries its name and price, so no
|
||||
//! products have to be kept in the Stripe dashboard.
|
||||
|
||||
@@ -54,6 +55,15 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// A refund (`re_…`).
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Refund {
|
||||
pub id: String,
|
||||
/// `pending`, `succeeded`, `failed`, …
|
||||
#[serde(default)]
|
||||
pub status: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Client {
|
||||
http: reqwest::Client,
|
||||
}
|
||||
@@ -100,6 +110,40 @@ impl Client {
|
||||
Self::session(res).await
|
||||
}
|
||||
|
||||
/// Pays a PaymentIntent back in full. The same `key` (Stripe's
|
||||
/// Idempotency-Key, kept for a day) never refunds twice.
|
||||
pub async fn refund(
|
||||
&self,
|
||||
config: &StripeConfig,
|
||||
payment_intent: &str,
|
||||
key: &str,
|
||||
metadata: &[(&str, &str)],
|
||||
) -> Result<Refund, ApiError> {
|
||||
let mut form = vec![
|
||||
("payment_intent".to_string(), payment_intent.to_string()),
|
||||
("reason".to_string(), "requested_by_customer".to_string()),
|
||||
];
|
||||
form.extend(metadata.iter().map(|(k, v)| (format!("metadata[{k}]"), (*v).to_string())));
|
||||
let res = self
|
||||
.http
|
||||
.post(format!("{}/v1/refunds", config.api_url))
|
||||
.bearer_auth(&config.secret_key)
|
||||
.header("Idempotency-Key", key)
|
||||
.form(&form)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| unavailable(e.to_string()))?;
|
||||
let status = res.status();
|
||||
if !status.is_success() {
|
||||
// Stripe says why (e.g. already refunded): the admin sees it.
|
||||
let body: Value = res.json().await.unwrap_or_default();
|
||||
let message = body["error"]["message"].as_str().unwrap_or("ismeretlen hiba").to_string();
|
||||
tracing::error!(%status, %message, "stripe refund refused");
|
||||
return Err(ApiError::conflict("refund_failed", format!("A Stripe nem téríti vissza: {message}")));
|
||||
}
|
||||
res.json().await.map_err(|e| unavailable(format!("unexpected response: {e}")))
|
||||
}
|
||||
|
||||
async fn session(res: reqwest::Response) -> Result<Session, ApiError> {
|
||||
let status = res.status();
|
||||
if !status.is_success() {
|
||||
|
||||
@@ -160,6 +160,27 @@ async fn fake_stripe_get(axum::extract::Path(id): axum::extract::Path<String>) -
|
||||
}
|
||||
}
|
||||
|
||||
/// Refunds the fake Stripe made: Idempotency-Key and form; a PaymentIntent in
|
||||
/// REFUND_FAILS is refused once.
|
||||
type FakeRefunds = std::sync::Mutex<Vec<(String, Vec<(String, String)>)>>;
|
||||
static STRIPE_REFUNDS: std::sync::LazyLock<FakeRefunds> = std::sync::LazyLock::new(Default::default);
|
||||
static REFUND_FAILS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
|
||||
std::sync::LazyLock::new(Default::default);
|
||||
|
||||
async fn fake_stripe_refund(
|
||||
headers: HeaderMap,
|
||||
axum::Form(form): axum::Form<Vec<(String, String)>>,
|
||||
) -> (StatusCode, Json<Value>) {
|
||||
let intent = form.iter().find(|(k, _)| k == "payment_intent").map(|(_, v)| v.clone()).unwrap_or_default();
|
||||
if REFUND_FAILS.lock().unwrap().remove(&intent) {
|
||||
return (StatusCode::BAD_REQUEST, Json(json!({"error": {"message": "Charge has a dispute."}})));
|
||||
}
|
||||
let key = headers.get("idempotency-key").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string();
|
||||
let mut refunds = STRIPE_REFUNDS.lock().unwrap();
|
||||
refunds.push((key, form));
|
||||
(StatusCode::OK, Json(json!({"id": format!("re_fake_{}", refunds.len()), "status": "succeeded"})))
|
||||
}
|
||||
|
||||
async fn fake_billingo_pdf(
|
||||
headers: HeaderMap,
|
||||
axum::extract::Path(id): axum::extract::Path<i64>,
|
||||
@@ -213,6 +234,7 @@ async fn fake_services_with(s3: FakeS3) -> String {
|
||||
.route("/openrouter/models", get(fake_openrouter_models))
|
||||
.route("/v1/checkout/sessions", post(fake_stripe_create))
|
||||
.route("/v1/checkout/sessions/{id}", get(fake_stripe_get))
|
||||
.route("/v1/refunds", post(fake_stripe_refund))
|
||||
.route("/v1/natal", post(fake_natal))
|
||||
.route("/v1/countries", get(|| async { Json(json!({"countries": [{"iso2": "HU", "name": "Hungary"}]})) }))
|
||||
.route(
|
||||
@@ -3537,3 +3559,151 @@ async fn a_gift_handed_over_by_the_buyer(pool: PgPool) {
|
||||
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)));
|
||||
}
|
||||
|
||||
/// Buys a gift as `token` through the fake Stripe and its webhook; returns
|
||||
/// the gift's id, its code and the checkout.
|
||||
async fn paid_gift(app: &TestApp, token: &str, package: &str, intent: &str) -> (String, String, String) {
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/gifts/checkout",
|
||||
Some(token),
|
||||
json!({"package": package, "recipient_name": "Bea", "recipient_email": "bea@example.com",
|
||||
"recipient_email_confirm": "bea@example.com"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let gift = r.body["id"].as_str().unwrap().to_string();
|
||||
let session = r.body["url"].as_str().unwrap().rsplit('/').next().unwrap().to_string();
|
||||
let event = json!({"id": format!("evt_{session}"), "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": intent,
|
||||
"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 signature = crate::stripe::sign(
|
||||
"whsec_fake",
|
||||
event.to_string().as_bytes(),
|
||||
time::OffsetDateTime::now_utc().unix_timestamp(),
|
||||
);
|
||||
let r = app
|
||||
.call_with("POST", "/v1/payments/stripe/webhook", None, Some(event), &[("stripe-signature", &signature)])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let code: String = sqlx::query_scalar("SELECT code FROM gifts WHERE id = $1::uuid")
|
||||
.bind(&gift)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
(gift, code, session)
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn a_gift_is_refunded_only_while_it_is_not_redeemed(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 admin = app.register("admin@example.com", "Admin").await;
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let (gift, code, session) = paid_gift(&app, &anna, "couple", "pi_refund_1").await;
|
||||
// The buyer's consent says the gift is performed when it is redeemed.
|
||||
let consent = stripe_form(&session, "custom_text[terms_of_service_acceptance][message]").unwrap();
|
||||
assert!(
|
||||
consent.contains("az ajándékkód beváltásakor") && consent.contains("a beváltással a 14 napos"),
|
||||
"{consent}"
|
||||
);
|
||||
|
||||
let r = app.get("/v1/admin/gifts", Some(&admin)).await;
|
||||
let row = &r.body["gifts"][0];
|
||||
assert_eq!(
|
||||
(&row["status"], &row["within_withdrawal"], &row["buyer_email"]),
|
||||
(&json!("open"), &json!(true), &json!("anna@example.com"))
|
||||
);
|
||||
assert_eq!((&row["invoice"]["status"], &row["checkout"]["amount_huf"]), (&json!("pending"), &json!(6000)));
|
||||
let refund_url = format!("/v1/admin/gifts/{gift}/refund");
|
||||
assert_eq!(app.post(&refund_url, Some(&anna), json!({})).await.status, StatusCode::FORBIDDEN);
|
||||
|
||||
// Refunded: Stripe pays back once, the invoice's storno is queued, the code is withdrawn.
|
||||
let r = app.post(&refund_url, Some(&admin), json!({})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(r.body["status"], "refunded");
|
||||
let refund_id = r.body["refund_id"].as_str().unwrap().to_string();
|
||||
let (key, form) = STRIPE_REFUNDS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|(_, f)| f.iter().any(|(k, v)| k == "payment_intent" && v == "pi_refund_1"))
|
||||
.cloned()
|
||||
.unwrap();
|
||||
assert_eq!(key, format!("gift-refund-{gift}"));
|
||||
assert!(form.contains(&("metadata[gift_id]".to_string(), gift.clone())));
|
||||
let r = app.post(&refund_url, Some(&admin), json!({})).await;
|
||||
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("gift_refunded")));
|
||||
let (reason, status): (String, String) = sqlx::query_as(
|
||||
"SELECT x.reason, x.status FROM invoice_cancellations x JOIN invoices i ON i.id = x.invoice_id WHERE i.checkout_id = $1",
|
||||
)
|
||||
.bind(&session)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(reason.contains("Elállás") && reason.contains(&code[..4]) && status == "pending", "{reason}");
|
||||
let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": code})).await;
|
||||
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("promo_revoked")));
|
||||
let r = app.get("/v1/gifts", Some(&anna)).await;
|
||||
assert_eq!((&r.body["gifts"][0]["status"], &r.body["gifts"][0]["can_send"]), (&json!("refunded"), &json!(false)));
|
||||
assert_eq!(gift_card_pdf(&app, &anna, &gift).await.0, StatusCode::CONFLICT);
|
||||
let r = app.get("/v1/admin/gifts", Some(&admin)).await;
|
||||
assert_eq!(
|
||||
(&r.body["gifts"][0]["refund_id"], &r.body["gifts"][0]["storno"]["status"]),
|
||||
(&json!(refund_id), &json!("pending"))
|
||||
);
|
||||
|
||||
// Redeemed first: no refund, nothing changes.
|
||||
let (redeemed, code, _) = paid_gift(&app, &anna, "single", "pi_refund_2").await;
|
||||
assert_eq!(app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": code})).await.status, StatusCode::OK);
|
||||
let r = app.post(&format!("/v1/admin/gifts/{redeemed}/refund"), Some(&admin), json!({})).await;
|
||||
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("gift_redeemed")));
|
||||
let refunded: Option<time::OffsetDateTime> =
|
||||
sqlx::query_scalar("SELECT refunded_at FROM gifts WHERE id = $1::uuid")
|
||||
.bind(&redeemed)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(refunded.is_none());
|
||||
|
||||
// Stripe refuses: the code stays withdrawn, the admin sees why and tries again.
|
||||
REFUND_FAILS.lock().unwrap().insert("pi_refund_3".into());
|
||||
let (flaky, code, _) = paid_gift(&app, &anna, "family", "pi_refund_3").await;
|
||||
let r = app.post(&format!("/v1/admin/gifts/{flaky}/refund"), Some(&admin), json!({})).await;
|
||||
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("refund_failed")));
|
||||
assert!(r.body["error"]["message"].as_str().unwrap().contains("Charge has a dispute."));
|
||||
let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": code})).await;
|
||||
assert_eq!(r.body["error"]["code"], "promo_revoked");
|
||||
let r = app.get("/v1/admin/gifts", Some(&admin)).await;
|
||||
let row = r.body["gifts"].as_array().unwrap().iter().find(|g| g["id"] == json!(flaky)).unwrap().clone();
|
||||
assert!(row["refund_error"].as_str().unwrap().contains("dispute") && row["refund_pending"] == json!(true));
|
||||
let r = app.post(&format!("/v1/admin/gifts/{flaky}/refund"), Some(&admin), json!({})).await;
|
||||
assert_eq!((r.status, &r.body["status"]), (StatusCode::OK, &json!("refunded")), "{}", r.body);
|
||||
|
||||
// Searching by the code (with or without dashes).
|
||||
let r = app.get(&format!("/v1/admin/gifts?q={}", display_code(&code).to_lowercase()), Some(&admin)).await;
|
||||
assert_eq!(r.body["gifts"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
fn display_code(code: &str) -> String {
|
||||
code.as_bytes().chunks(4).map(|c| String::from_utf8_lossy(c).into_owned()).collect::<Vec<_>>().join("-")
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn a_gift_paid_with_the_stand_in_is_refunded_without_stripe(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let r = app.post("/v1/gifts/checkout", Some(&anna), json!({"package": "single", "recipient_name": "Bea"})).await;
|
||||
let id = r.body["id"].as_str().unwrap().to_string();
|
||||
let url = format!("/v1/admin/gifts/{id}/refund");
|
||||
let r = app.post(&url, Some(&admin), json!({})).await;
|
||||
assert_eq!((r.status, &r.body["status"]), (StatusCode::OK, &json!("refunded")), "{}", r.body);
|
||||
let r = app.get("/v1/admin/gifts", Some(&admin)).await;
|
||||
assert_eq!((&r.body["gifts"][0]["refund_pending"], &r.body["gifts"][0]["checkout"]), (&json!(false), &Value::Null));
|
||||
assert_eq!(app.post(&url, Some(&admin), json!({})).await.body["error"]["code"], "gift_refunded");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user