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
+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());