Gift withdrawal: admin refund (Stripe) and invoice storno (Billingo)
CI / test (push) Successful in 3m25s
CI / build (push) Skipped
CI / deploy (push) Skipped

- 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:
feco
2026-11-23 21:22:46 +00:00
co-authored by Claude Opus 5.5
parent c90232f40c
commit 0d62888831
18 changed files with 1014 additions and 46 deletions
+229 -6
View File
@@ -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(&note)).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) }),
))
}
+2
View File
@@ -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))
+16 -9
View File
@@ -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)))?;
+45 -1
View File
@@ -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() {
+170
View File
@@ -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");
}
@@ -0,0 +1,176 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { AdminGift } from "@/lib/types";
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
const STORNO: Record<string, string> = { pending: "sztornó folyamatban", done: "sztornózva", failed: "sztornó hiba" };
/** The gifts with their payment, invoice and storno, and the refund button. */
export function AdminGifts() {
const [gifts, setGifts] = useState<AdminGift[] | null>(null);
const [q, setQ] = useState("");
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState<string | null>(null);
const load = useCallback(async (search: string) => {
try {
const r = await api<{ gifts: AdminGift[] }>(`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`);
setGifts(r.gifts);
} catch (e) {
setError(errorText(e));
}
}, []);
useEffect(() => {
const t = setTimeout(() => load(q.trim()), 250);
return () => clearTimeout(t);
}, [q, load]);
async function refund(g: AdminGift) {
const late = g.within_withdrawal ? "" : "\n\nFigyelem: a 14 napos elállási idő már letelt.";
const money = g.checkout?.amount_huf ? ` (${huf(g.checkout.amount_huf)})` : "";
if (
!window.confirm(
`Visszatéríted a(z) „${g.package.name}” ajándékot${money}? A ${g.code} kód érvénytelen lesz, a Stripe visszautalja az árát, a számla sztornózódik.${late}`,
)
)
return;
setBusy(g.id);
setError(null);
setDone(null);
try {
await api(`/admin/gifts/${g.id}/refund`, { method: "POST", body: {} });
setDone(`Visszatérítve: ${g.code}.`);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(null);
await load(q.trim());
}
}
return (
<section className="card">
<div className="field">
<label htmlFor="gift-search">Keresés</label>
<input
id="gift-search"
className="inp"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{done && (
<p className="msg msg-ok" role="status">
{done}
</p>
)}
{gifts === null ? (
<p className="muted">Betöltés…</p>
) : gifts.length === 0 ? (
<p className="muted">Nincs ilyen ajándék.</p>
) : (
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Kód</th>
<th>Csomag</th>
<th>Vásárló → címzett</th>
<th>Fizetve</th>
<th>Állapot</th>
<th>Számla</th>
<th />
</tr>
</thead>
<tbody>
{gifts.map((g) => (
<tr key={g.id}>
<td>
<code className="promo-code">{g.code}</code>
</td>
<td>
{g.package.name ?? g.package.id}
{g.checkout?.amount_huf ? <span className="hint">{huf(g.checkout.amount_huf)}</span> : null}
{g.checkout && g.checkout.live === false && <span className="hint">teszt fizetés</span>}
</td>
<td>
{g.buyer_email ?? <span className="muted">törölt fiók</span>}
<span className="hint">
→ {g.recipient_name ?? "?"}
{g.recipient_email ? ` (${g.recipient_email})` : " (maga adja át)"}
</span>
</td>
<td className="num">{formatDate(g.paid_at, true)}</td>
<td>
{g.status === "redeemed" ? (
<>
beváltva {g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
{g.redeemed_by && <span className="hint">{g.redeemed_by}</span>}
</>
) : g.status === "refunded" ? (
<>
{g.refund_pending ? (
<span className="msg-error">visszatérítés félbemaradt</span>
) : (
"visszatérítve"
)}{" "}
{g.refunded_at ? formatDate(g.refunded_at, true) : ""}
{g.refund_pending && g.refund_error && <span className="hint">{g.refund_error}</span>}
</>
) : (
<>
<span className="promo-open">beváltatlan</span>
<span className="hint">{g.within_withdrawal ? "14 napon belül" : "14 nap letelt"}</span>
</>
)}
</td>
<td>
{g.invoice ? (
<>
{g.invoice.number ?? (g.invoice.status === "pending" ? "kiállítás alatt" : g.invoice.status)}
{g.storno && (
<span className={g.storno.status === "failed" ? "hint msg-error" : "hint"}>
{STORNO[g.storno.status] ?? g.storno.status}
{g.storno.number ? `: ${g.storno.number}` : ""}
{g.storno.error ? ` – ${g.storno.error}` : ""}
</span>
)}
</>
) : (
<span className="muted">–</span>
)}
</td>
<td>
{(g.status === "open" || g.refund_pending) && (
<button
type="button"
className="btn btn-sm"
onClick={() => refund(g)}
disabled={busy !== null}
>
{busy === g.id ? "Folyamatban…" : g.status === "refunded" ? "Újrapróbálás" : "Visszatérítés"}
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
@@ -0,0 +1,29 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { AdminNav } from "@/components/AdminNav";
import { requireMe } from "@/lib/server";
import { AdminGifts } from "./AdminGifts";
export const metadata: Metadata = { title: "Ajándékok" };
export default async function AdminGiftsPage() {
const me = await requireMe("/admin/ajandekok");
if (!me.user.roles.includes("admin")) notFound();
return (
<main className="page" style={{ maxWidth: 1180 }}>
<AdminNav current="/admin/ajandekok" />
<div className="page-head">
<h1>Ajándékok</h1>
<p className="muted">
Az ajándékba vett csomagok. A vásárló a vásárlástól számított 14 napon belül, amíg a kódot nem váltották be,
elállhat (ÁSZF 6.). Ilyenkor a „Visszatérítés” gomb érvényteleníti a kódot, a Stripe-on visszatéríti az árát,
és a számlát sztornózza a Billingóban (a worker, a számla kiállítása után; a sztornót a Billingo e-mailben
elküldi a vásárlónak). Beváltott ajándékot nem lehet visszatéríteni.
</p>
</div>
<AdminGifts />
</main>
);
}
@@ -235,8 +235,8 @@ export function GiftForm({
{termsConsent && (
<>
{" "}
Az ajándékkód a fizetés után azonnal elkészül, ezért a fizetésnél kéred a teljesítés megkezdését, és ezzel
lemondasz a 14 napos elállási jogról. <Link href="/aszf">ÁSZF</Link>
A vásárlástól számított 14 napon belül, amíg a kódot nem váltották be, elállhatsz, és visszatérítjük az
árát. A kód beváltásával az elállási jog megszűnik. <Link href="/aszf">ÁSZF</Link>
</>
)}
</p>
+4 -1
View File
@@ -66,7 +66,10 @@ export default async function GiftPage({ searchParams }: Props) {
<li>E-mailben elküldjük neki, vagy letöltöd a PDF-et, és te adod át.</li>
<li>Belép vagy regisztrál, beváltja a kódot, és a csomag az övé.</li>
</ol>
<p className="hint">A kód nem jár le, és egyszer váltható be. A számlát te kapod.</p>
<p className="hint">
A kód nem jár le, és egyszer váltható be. A számlát te kapod. Ha meggondolod magad, 14 napon belül,
beváltás előtt visszakérheted az árát: írj az info@sorsfonalak.hu címre.
</p>
</section>
</aside>
</div>
@@ -75,6 +75,8 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
</div>
{gift.status === "redeemed" ? (
<span className="badge">Beváltva{gift.redeemed_at ? `: ${day(gift.redeemed_at)}` : ""}</span>
) : gift.status === "refunded" ? (
<span className="badge">Visszatérítve{gift.refunded_at ? `: ${day(gift.refunded_at)}` : ""}</span>
) : (
<span className="badge badge-gold">Még nincs beváltva</span>
)}
@@ -94,23 +96,29 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
E-mailben elküldve ide: <strong>{gift.recipient_email}</strong>
{gift.sendings > 1 ? ` (${gift.sendings}×)` : ""}
</>
) : (
) : open ? (
"Te adod át: töltsd le az utalványt."
) : (
"Nem e-mailben ment."
)}
{gift.from_name && <span className="hint"> · Kitől: {gift.from_name}</span>}
</p>
{gift.message && <blockquote className="gift-message">{gift.message}</blockquote>}
<div className="form-actions">
<a className="btn btn-primary btn-sm" href={`/api/v1/gifts/${gift.id}/card.pdf`} download>
Utalvány letöltése (PDF)
</a>
{open && gift.can_send && !sending && (
<button type="button" className="btn btn-sm" onClick={() => setSending(true)}>
{gift.recipient_email ? "Újraküldés e-mailben" : "Küldés e-mailben"}
</button>
)}
</div>
{gift.status === "refunded" ? (
<p className="hint">Elálltál a vásárlástól: a kód már nem érvényes, az árát visszatérítettük.</p>
) : (
<div className="form-actions">
<a className="btn btn-primary btn-sm" href={`/api/v1/gifts/${gift.id}/card.pdf`} download>
Utalvány letöltése (PDF)
</a>
{open && gift.can_send && !sending && (
<button type="button" className="btn btn-sm" onClick={() => setSending(true)}>
{gift.recipient_email ? "Újraküldés e-mailben" : "Küldés e-mailben"}
</button>
)}
</div>
)}
{open && !gift.can_send && gift.sendings > 0 && (
<p className="hint">E-mailben már többször elküldtük. Ha nem érkezett meg, töltsd le az utalványt, és küldd el te.</p>
)}
+19 -3
View File
@@ -64,10 +64,13 @@ export default async function TermsPage() {
is) és a fizetési adatokat. Az adatokat a fizetés előtt ott javíthatja.
</li>
<li>
A fizetés előtt elfogadja ezt az ÁSZF-et, kéri a szolgáltatás azonnali megkezdését, és tudomásul veszi,
hogy ezzel elveszíti az elállási jogát (6. pont).
A fizetés előtt elfogadja ezt az ÁSZF-et, kéri a szolgáltatás azonnali megkezdését (ajándékcsomagnál: a
kód beváltásakor), és tudomásul veszi, hogy ezzel elveszíti az elállási jogát (6. pont).
</li>
<li>
A fizetéssel a szerződés létrejön. A csomagot azonnal jóváírjuk (ajándékcsomagnál az ajándékkódot azonnal
kiállítjuk), és e-mailben visszaigazoljuk.
</li>
<li>A fizetéssel a szerződés létrejön. A csomagot azonnal jóváírjuk, és e-mailben visszaigazoljuk.</li>
</ol>
<p>
A szerződés elektronikus úton jön létre, írásba foglalt szerződésnek nem minősül, külön nem iktatjuk. A
@@ -96,6 +99,11 @@ export default async function TermsPage() {
fiókban vannak. Nem járnak le, nem ruházhatók át, és pénzre nem válthatók vissza. Egy elemzés elkészítése
általában néhány perc.
</p>
<p>
Ajándékcsomagnál a vásárló egy ajándékkódot kap: a kódot és a nyomtatható utalványt e-mailben elküldjük a
megadott címzettnek, vagy a vásárló letölti, és maga adja át. A csomag egységei a kód beváltásakor kerülnek a
beváltó fiókjába. A kód nem jár le, és egyszer váltható be.
</p>
</section>
<section>
@@ -108,6 +116,14 @@ export default async function TermsPage() {
csomagjait azonnal teljesítjük: a fizetési oldalon ezt kéri a vásárló, és a visszaigazoló e-mailben ezt
megerősítjük, ezért a vásárlástól elállni nem lehet.
</p>
<p>
Ajándékcsomagnál a teljesítés a kód beváltásával kezdődik meg. A vásárló a vásárlástól számított 14 napon
belül, amíg a kódot nem váltották be, indoklás nélkül elállhat a vásárlástól. Ezt bármilyen egyértelmű
nyilatkozattal, például az {OPERATOR.email} címre írt e-mailben jelezheti. Ilyenkor a kódot érvénytelenítjük,
a vételárat legkésőbb 14 napon belül ugyanarra a fizetési módra visszatérítjük, és a számlát sztornózzuk. A
kód beváltásával az elállási jog megszűnik: a vásárló a fizetés előtt kéri, hogy a teljesítés a beváltáskor
azonnal megkezdődjön, és tudomásul veszi, hogy ezzel elveszíti az elállási jogát.
</p>
</section>
<section>
@@ -6,6 +6,7 @@ const PAGES = [
{ href: "/admin", label: "Felhasználók" },
{ href: "/admin/meghivok", label: "Meghívók" },
{ href: "/admin/promokodok", label: "Promókódok" },
{ href: "/admin/ajandekok", label: "Ajándékok" },
{ href: "/admin/hires-emberek", label: "Híres emberek", creator: true },
{ href: "/admin/promptok", label: "Promptok" },
{ href: "/admin/modellek", label: "Modellek" },
+1 -1
View File
@@ -22,4 +22,4 @@ export const PRIVACY_UPDATED = "2026. november 22.";
export const PRIVACY_UPDATED_EN = "22 November 2026";
/** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */
export const TERMS_UPDATED = "2026. november 22.";
export const TERMS_UPDATED = "2026. november 23.";
+27 -1
View File
@@ -633,6 +633,31 @@ export interface PromoCode {
redeemed_by: { email: string; name: string | null } | null;
}
/** A gift as admins see it (`GET /v1/admin/gifts`). */
export interface AdminGift {
id: string;
package: { id: string; name: string | null };
buyer_email: string | null;
recipient_name: string | null;
recipient_email: string | null;
paid_at: string;
code: string;
status: "open" | "redeemed" | "refunded";
redeemed_at: string | null;
redeemed_by: string | null;
refunded_at: string | null;
/** Withdrawn, but Stripe has not paid back yet (it refused: see refund_error; try again). */
refund_pending: boolean;
/** Stripe's refund id. */
refund_id: string | null;
refund_error: string | null;
/** Within the 14 days the buyer may withdraw. */
within_withdrawal: boolean;
checkout: { id: string; live: boolean | null; amount_huf: number | null } | null;
invoice: { number: string | null; status: string } | null;
storno: { status: string; number: string | null; error: string | null } | null;
}
/** A package the user bought as a gift (`GET /v1/gifts`). */
export interface Gift {
id: string;
@@ -646,8 +671,9 @@ export interface Gift {
paid_at: string;
/** ABCD-EFGH-JKLM */
code: string;
status: "open" | "redeemed";
status: "open" | "redeemed" | "refunded";
redeemed_at: string | null;
refunded_at: string | null;
/** E-mails sent so far. */
sendings: number;
/** Whether it can be sent by e-mail (again). */
+210
View File
@@ -10,6 +10,13 @@
//! one. An invoice that was issued but could not be e-mailed still counts as
//! issued (it can be downloaded). Billingo's whole answer is kept; the PDF is
//! not (the backend fetches it when the user downloads it).
//!
//! A refunded payment's invoice gets a storno: the backend queues an
//! `invoice_cancellations` row, and once the invoice is issued this job asks
//! Billingo to cancel it (the cancellation document is the storno invoice,
//! e-mailed to the buyer). The request is marked before it is sent; when the
//! answer is lost, it is not asked for again (cancelling twice is worse):
//! the row fails, and an admin checks it in Billingo.
use std::time::Duration;
@@ -60,6 +67,32 @@ impl Billingo {
serde_json::from_str(&text).map_err(|e| format!("{method} {path}: not JSON: {e}"))
}
/// Cancels a document (storno) and returns the cancellation document. The
/// error says whether Billingo surely did nothing (it refused the request):
/// after a lost answer or a server error the document may be cancelled.
async fn cancel(&self, document: i64, body: &Value) -> Result<Value, (bool, String)> {
let path = format!("/documents/{document}/cancel");
let res = self
.http
.post(format!("{}{path}", self.base))
.header("X-API-KEY", &self.key)
.header("Accept", "application/json")
.json(body)
.send()
.await
.map_err(|e| (false, format!("POST {path}: {e}")))?;
let status = res.status();
let text = res.text().await.unwrap_or_default();
if !status.is_success() {
let refused = status.is_client_error();
return Err((
refused,
format!("POST {path}: HTTP {status}: {}", text.chars().take(500).collect::<String>()),
));
}
serde_json::from_str(&text).map_err(|e| (false, format!("POST {path}: not JSON: {e}")))
}
async fn block(&self) -> Result<i64, String> {
let mut block = self.block.lock().await;
if let Some(id) = *block {
@@ -363,11 +396,107 @@ async fn find_document(billingo: &Billingo, partner: i64) -> Result<Option<Value
.cloned())
}
#[derive(sqlx::FromRow)]
struct DueCancellation {
id: Uuid,
attempts: i32,
reason: String,
requested_at: Option<OffsetDateTime>,
/// The invoice to cancel.
document_id: i64,
buyer_email: Option<String>,
}
/// Cancels the invoices of refunded payments (storno); returns how many were finished.
pub async fn cancel_due(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Result<usize, sqlx::Error> {
let mut done = 0;
loop {
// Only issued invoices can be cancelled: the others wait.
let due: Option<DueCancellation> = sqlx::query_as(&format!(
"UPDATE invoice_cancellations x SET attempts = x.attempts + 1, next_attempt_at = now() + interval '{LEASE}' \
FROM invoices i \
WHERE i.id = x.invoice_id AND x.id = (SELECT x2.id FROM invoice_cancellations x2 \
JOIN invoices i2 ON i2.id = x2.invoice_id \
WHERE x2.status = 'pending' AND x2.next_attempt_at <= now() AND i2.billingo_document_id IS NOT NULL \
AND i2.status = 'issued' \
ORDER BY x2.next_attempt_at FOR UPDATE OF x2 SKIP LOCKED LIMIT 1) \
RETURNING x.id, x.attempts, x.reason, x.requested_at, i.billingo_document_id AS document_id, i.buyer_email"
))
.fetch_optional(db)
.await?;
let Some(due) = due else { return Ok(done) };
let fail = |error: String| {
sqlx::query("UPDATE invoice_cancellations SET status = 'failed', last_error = $2 WHERE id = $1")
.bind(due.id)
.bind(error)
.execute(db)
};
if due.requested_at.is_some() {
tracing::error!(cancellation = %due.id, "storno asked for before without an answer; an admin has to check it");
fail("Korábban már kértük a sztornót, de nem jött válasz: ellenőrizd a Billingóban.".into()).await?;
done += 1;
continue;
}
sqlx::query("UPDATE invoice_cancellations SET requested_at = now() WHERE id = $1")
.bind(due.id)
.execute(db)
.await?;
let mut body = json!({ "cancellation_reason": due.reason });
if let Some(email) = &due.buyer_email {
body["cancellation_recipients"] = json!(email);
}
match billingo.cancel(due.document_id, &body).await {
Ok(document) => {
let number = document["invoice_number"].as_str().map(str::to_owned);
sqlx::query(
"UPDATE invoice_cancellations SET status = 'done', done_at = now(), last_error = NULL, \
billingo_document_id = $2, invoice_number = $3, document = $4 WHERE id = $1",
)
.bind(due.id)
.bind(document["id"].as_i64())
.bind(&number)
.bind(&document)
.execute(db)
.await?;
tracing::info!(cancellation = %due.id, number = ?number, "invoice cancelled (storno)");
done += 1;
}
// Refused: nothing happened, it may be asked again.
Err((true, error)) if due.attempts < max_attempts => {
let wait = backoff(due.attempts);
tracing::warn!(cancellation = %due.id, %error, retry_in = ?wait, "storno not made yet");
sqlx::query(
"UPDATE invoice_cancellations SET requested_at = NULL, last_error = $2, \
next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1",
)
.bind(due.id)
.bind(&error)
.bind(wait.as_secs_f64())
.execute(db)
.await?;
}
Err((refused, error)) => {
tracing::error!(cancellation = %due.id, %error, refused, "storno failed; an admin has to look at it");
let error = if refused {
error
} else {
format!("Nem tudni, megtörtént-e (ellenőrizd a Billingóban): {error}")
};
fail(error).await?;
done += 1;
}
}
}
}
pub async fn run(db: PgPool, billingo: Billingo, max_attempts: i32, interval: Duration, stop: watch::Receiver<bool>) {
loop {
if let Err(e) = run_once(&db, &billingo, max_attempts).await {
tracing::error!(error = %e, "invoices");
}
if let Err(e) = cancel_due(&db, &billingo, max_attempts).await {
tracing::error!(error = %e, "invoice cancellations");
}
tokio::select! {
() = tokio::time::sleep(interval) => {}
() = crate::stopped(stop.clone()) => break,
@@ -412,6 +541,8 @@ mod tests {
lose_document_answer: std::sync::atomic::AtomicBool,
/// The invoices made so far, for the list.
made: std::sync::Mutex<Vec<Value>>,
/// Cancelling answers this status first (then 200).
cancel_status: std::sync::Mutex<Vec<StatusCode>>,
}
async fn fake_billingo(fake: Arc<Fake>) -> String {
@@ -461,7 +592,23 @@ mod tests {
}
(StatusCode::OK, Json(body))
}
async fn cancel(
State(f): State<Arc<Fake>>,
Path(id): Path<i64>,
Json(body): Json<Value>,
) -> (StatusCode, Json<Value>) {
f.requests.lock().unwrap().push((format!("cancel {id}"), body));
let status = f.cancel_status.lock().unwrap().pop();
match status {
Some(status) => (status, Json(json!({"message": "no"}))),
None => (
StatusCode::OK,
Json(json!({"id": 5000 + id, "invoice_number": "SF-2026-S1", "type": "cancellation"})),
),
}
}
let app = Router::new()
.route("/documents/{id}/cancel", post(cancel))
.route("/document-blocks", get(blocks))
.route("/partners", post(partner))
.route("/documents", post(document).get(documents))
@@ -511,6 +658,69 @@ mod tests {
.unwrap()
}
async fn cancellation(db: &PgPool, invoice: Uuid) -> Uuid {
let id = Uuid::now_v7();
sqlx::query("INSERT INTO invoice_cancellations (id, invoice_id, reason) VALUES ($1, $2, 'Elállás')")
.bind(id)
.bind(invoice)
.execute(db)
.await
.unwrap();
id
}
async fn cancellation_state(db: &PgPool, id: Uuid) -> (String, Option<String>, Option<i64>, Option<String>) {
sqlx::query_as(
"SELECT status, invoice_number, billingo_document_id, last_error FROM invoice_cancellations WHERE id = $1",
)
.bind(id)
.fetch_one(db)
.await
.unwrap()
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn refunded_invoices_get_a_storno_once(db: PgPool) {
let fake = Arc::new(Fake::default());
let billingo = Billingo::new(&fake_billingo(fake.clone()).await, "key", None);
let invoice = paid(&db, None).await;
let storno = cancellation(&db, invoice).await;
// The invoice is not issued yet: the storno waits.
assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 0);
assert_eq!(cancellation_state(&db, storno).await.0, "pending");
run_once(&db, &billingo, 3).await.unwrap();
let document = state(&db, invoice).await.2.unwrap();
// Refused once (nothing happened): asked again later, then made.
fake.cancel_status.lock().unwrap().push(StatusCode::TOO_MANY_REQUESTS);
assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 0);
let (status, _, _, error) = cancellation_state(&db, storno).await;
assert!(status == "pending" && error.unwrap().contains("429"));
sqlx::query("UPDATE invoice_cancellations SET next_attempt_at = now()").execute(&db).await.unwrap();
assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 1);
assert_eq!(
cancellation_state(&db, storno).await,
("done".into(), Some("SF-2026-S1".into()), Some(5000 + document), None)
);
let requests = fake.requests.lock().unwrap().clone();
let cancels: Vec<&Value> = requests.iter().filter(|(r, _)| r.starts_with("cancel ")).map(|(_, b)| b).collect();
assert_eq!(cancels.len(), 2);
assert_eq!(
cancels[1],
&json!({"cancellation_reason": "Elállás", "cancellation_recipients": "anna@example.com"})
);
assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 0);
// A server error: maybe it was cancelled, so it is not asked again.
let other = paid(&db, None).await;
run_once(&db, &billingo, 3).await.unwrap();
let storno = cancellation(&db, other).await;
fake.cancel_status.lock().unwrap().push(StatusCode::BAD_GATEWAY);
assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 1);
let (status, _, _, error) = cancellation_state(&db, storno).await;
assert!(status == "failed" && error.unwrap().contains("ellenőrizd a Billingóban"));
assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 0);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn invoices_are_issued_and_sent_once(db: PgPool) {
let fake = Arc::new(Fake::default());