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:
@@ -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