Review fixes: no duplicate invoices, safer logins and redirects, one charge per click
Invoicing: the invoice request is marked before it goes to Billingo; a retry after a lost answer looks the invoice up under the invoice's own partner instead of issuing a second one. An invoice issued but never e-mailed counts as issued (downloadable). A Hungarian company with only an EU VAT number is invoiced without a domestic tax number, the EU number in the comment. Security: the login redirect takes only plain local paths (no backslash); the waitlist rate limit and share visits use X-Real-IP, which Caddy sets from Cloudflare's address, not the spoofable first X-Forwarded-For entry; a Google/Apple sign-in to an unconfirmed password account removes its password and sessions; a person's birth data can no longer be published through a share. Credits and jobs: analysis requests are serialized per user, so a double click queues and pays once; a forecast analysis also fixes a person's birth data; admins can restart stuck tarot readings; a worker forgets an attempt an admin restarted, so a stop does not requeue it; two people accepting one comparison invite at once get one comparison. Expired invitations are no longer accepted by e-mail, and unsubscribing revokes the invitation's promo codes too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
+147
-25
@@ -4,9 +4,12 @@
|
||||
//! the item as they go on the invoice. This job takes the due rows and, step
|
||||
//! by step, creates the Billingo partner, the invoice (paid by card,
|
||||
//! electronic) and e-mails it to the buyer. Each step's result is saved before
|
||||
//! the next one, so a retry continues where it stopped and never issues a
|
||||
//! second invoice. Billingo's whole answer is kept; the PDF is not (the
|
||||
//! backend fetches it when the user downloads it).
|
||||
//! the next one, so a retry continues where it stopped. The invoice request is
|
||||
//! marked before it is sent: when Billingo's answer was lost, the retry finds
|
||||
//! the invoice under the invoice's own partner instead of issuing a second
|
||||
//! 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).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -93,6 +96,7 @@ struct Due {
|
||||
payment_method: String,
|
||||
billingo_partner_id: Option<i64>,
|
||||
billingo_document_id: Option<i64>,
|
||||
document_requested_at: Option<OffsetDateTime>,
|
||||
sent_at: Option<OffsetDateTime>,
|
||||
paid_at: OffsetDateTime,
|
||||
}
|
||||
@@ -131,7 +135,8 @@ pub async fn run_once(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Re
|
||||
AND next_attempt_at <= now() ORDER BY next_attempt_at FOR UPDATE SKIP LOCKED LIMIT 1) \
|
||||
RETURNING i.id, i.attempts, i.buyer_name, i.buyer_email, i.buyer_country, i.buyer_post_code, \
|
||||
i.buyer_city, i.buyer_address, i.buyer_tax_type, i.buyer_tax_number, i.item_name, i.item_comment, i.item_unit, i.gross_huf, \
|
||||
i.vat_rate, i.payment_method, i.billingo_partner_id, i.billingo_document_id, i.sent_at, \
|
||||
i.vat_rate, i.payment_method, i.billingo_partner_id, i.billingo_document_id, \
|
||||
i.document_requested_at, i.sent_at, \
|
||||
coalesce(c.completed_at, i.created_at) AS paid_at"
|
||||
))
|
||||
.fetch_optional(db)
|
||||
@@ -144,12 +149,28 @@ pub async fn run_once(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Re
|
||||
}
|
||||
Err(Failure::Db(e)) => return Err(e),
|
||||
Err(Failure::Billingo(error)) if due.attempts >= max_attempts => {
|
||||
tracing::error!(invoice = %due.id, %error, "invoice failed; an admin has to look at it");
|
||||
sqlx::query("UPDATE invoices SET status = 'failed', last_error = $2 WHERE id = $1")
|
||||
.bind(due.id)
|
||||
.bind(&error)
|
||||
.execute(db)
|
||||
.await?;
|
||||
// Issued but never e-mailed: it is still an invoice (the user downloads it).
|
||||
let issued: Option<(Option<String>,)> = sqlx::query_as(
|
||||
"UPDATE invoices SET status = 'issued', issued_at = now(), last_error = $2 \
|
||||
WHERE id = $1 AND billingo_document_id IS NOT NULL RETURNING invoice_number",
|
||||
)
|
||||
.bind(due.id)
|
||||
.bind(format!("issued, not e-mailed: {error}"))
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
match issued {
|
||||
Some((number,)) => {
|
||||
tracing::warn!(invoice = %due.id, number = ?number, %error, "invoice issued but not e-mailed")
|
||||
}
|
||||
None => {
|
||||
tracing::error!(invoice = %due.id, %error, "invoice failed; an admin has to look at it");
|
||||
sqlx::query("UPDATE invoices SET status = 'failed', last_error = $2 WHERE id = $1")
|
||||
.bind(due.id)
|
||||
.bind(&error)
|
||||
.execute(db)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
done += 1;
|
||||
}
|
||||
Err(Failure::Billingo(error)) => {
|
||||
@@ -208,7 +229,13 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
|
||||
"address": due.buyer_address,
|
||||
},
|
||||
"emails": due.buyer_email.iter().collect::<Vec<_>>(),
|
||||
"taxcode": due.buyer_tax_number.clone().unwrap_or_default(),
|
||||
// Without a tax type number (a Hungarian company with only an
|
||||
// EU VAT number) the number goes into the invoice's comment.
|
||||
"taxcode": if due.buyer_tax_type == "NO_TAX_NUMBER" {
|
||||
String::new()
|
||||
} else {
|
||||
due.buyer_tax_number.clone().unwrap_or_default()
|
||||
},
|
||||
"tax_type": due.buyer_tax_type,
|
||||
});
|
||||
let partner = billingo.call(Method::POST, "/partners", Some(&body)).await?;
|
||||
@@ -246,13 +273,28 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
|
||||
"vat": due.vat_rate,
|
||||
"comment": due.item_comment.clone().unwrap_or_default(),
|
||||
}],
|
||||
"comment": if due.vat_rate == "AAM" {
|
||||
"Bankkártyával kifizetve (Stripe). Alanyi adómentes."
|
||||
} else {
|
||||
"Bankkártyával kifizetve (Stripe)."
|
||||
},
|
||||
"comment": document_comment(due),
|
||||
});
|
||||
let doc = billingo.call(Method::POST, "/documents", Some(&body)).await?;
|
||||
// An earlier attempt asked already: its invoice may exist although
|
||||
// the answer never came. The partner is this invoice's own, so any
|
||||
// invoice of it is ours.
|
||||
let earlier = match due.document_requested_at {
|
||||
Some(_) => find_document(billingo, partner).await?,
|
||||
None => None,
|
||||
};
|
||||
let doc = match earlier {
|
||||
Some(doc) => {
|
||||
tracing::warn!(invoice = %due.id, number = ?doc["invoice_number"], "found the invoice of an earlier attempt");
|
||||
doc
|
||||
}
|
||||
None => {
|
||||
sqlx::query("UPDATE invoices SET document_requested_at = now() WHERE id = $1")
|
||||
.bind(due.id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
billingo.call(Method::POST, "/documents", Some(&body)).await?
|
||||
}
|
||||
};
|
||||
let id = doc["id"].as_i64().ok_or("Billingo invoice without id")?;
|
||||
let item = &doc["items"][0];
|
||||
sqlx::query(
|
||||
@@ -293,6 +335,34 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
|
||||
Ok(number.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The invoice's comment: how it was paid, the VAT exemption, and a
|
||||
/// Hungarian company's EU VAT number when it gave no domestic one.
|
||||
fn document_comment(due: &Due) -> String {
|
||||
let mut comment = String::from("Bankkártyával kifizetve (Stripe).");
|
||||
if due.vat_rate == "AAM" {
|
||||
comment.push_str(" Alanyi adómentes.");
|
||||
}
|
||||
if due.buyer_tax_type == "NO_TAX_NUMBER"
|
||||
&& let Some(eu) = &due.buyer_tax_number
|
||||
{
|
||||
comment.push_str(&format!(" A vevő közösségi adószáma: {eu}."));
|
||||
}
|
||||
comment
|
||||
}
|
||||
|
||||
/// The invoice already issued to `partner`, if any (an error is a failed
|
||||
/// attempt: an invoice is never made without knowing there is none).
|
||||
async fn find_document(billingo: &Billingo, partner: i64) -> Result<Option<Value>, Failure> {
|
||||
let list = billingo
|
||||
.call(reqwest::Method::GET, &format!("/documents?partner_id={partner}&type=invoice&per_page=10"), None)
|
||||
.await?;
|
||||
let items = list["data"].as_array().or_else(|| list.as_array()).ok_or("Billingo document list without data")?;
|
||||
Ok(items
|
||||
.iter()
|
||||
.find(|d| d["id"].as_i64().is_some() && d["partner"]["id"].as_i64().is_none_or(|p| p == partner))
|
||||
.cloned())
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -338,6 +408,10 @@ mod tests {
|
||||
send_failures: AtomicUsize,
|
||||
/// Partners are refused (a permanent error).
|
||||
refuse_partners: std::sync::atomic::AtomicBool,
|
||||
/// The next invoice is made, but its answer is lost (an error instead).
|
||||
lose_document_answer: std::sync::atomic::AtomicBool,
|
||||
/// The invoices made so far, for the list.
|
||||
made: std::sync::Mutex<Vec<Value>>,
|
||||
}
|
||||
|
||||
async fn fake_billingo(fake: Arc<Fake>) -> String {
|
||||
@@ -355,13 +429,25 @@ mod tests {
|
||||
async fn document(State(f): State<Arc<Fake>>, Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
|
||||
f.requests.lock().unwrap().push(("document".into(), body.clone()));
|
||||
let n = f.documents.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
(
|
||||
StatusCode::CREATED,
|
||||
Json(json!({"id": 900 + n, "invoice_number": format!("SF-2026-{n}"), "invoice_date": "2026-11-20",
|
||||
"fulfillment_date": body["fulfillment_date"], "due_date": body["due_date"],
|
||||
"gross_total": 6000.0,
|
||||
"items": [{"name": "x", "net_amount": 6000.0, "vat_amount": 0.0, "gross_amount": 6000.0}]})),
|
||||
)
|
||||
let doc = json!({"id": 900 + n, "invoice_number": format!("SF-2026-{n}"), "invoice_date": "2026-11-20",
|
||||
"fulfillment_date": body["fulfillment_date"], "due_date": body["due_date"],
|
||||
"gross_total": 6000.0, "partner": {"id": body["partner_id"]},
|
||||
"items": [{"name": "x", "net_amount": 6000.0, "vat_amount": 0.0, "gross_amount": 6000.0}]});
|
||||
f.made.lock().unwrap().push(doc.clone());
|
||||
if f.lose_document_answer.swap(false, Ordering::SeqCst) {
|
||||
return (StatusCode::GATEWAY_TIMEOUT, Json(json!({"error": "timeout"})));
|
||||
}
|
||||
(StatusCode::CREATED, Json(doc))
|
||||
}
|
||||
async fn documents(
|
||||
State(f): State<Arc<Fake>>,
|
||||
axum::extract::Query(q): axum::extract::Query<std::collections::HashMap<String, String>>,
|
||||
) -> Json<Value> {
|
||||
f.requests.lock().unwrap().push(("list".into(), json!(q)));
|
||||
let partner: i64 = q.get("partner_id").and_then(|p| p.parse().ok()).unwrap_or(-1);
|
||||
let data: Vec<Value> =
|
||||
f.made.lock().unwrap().iter().filter(|d| d["partner"]["id"] == partner).cloned().collect();
|
||||
Json(json!({"data": data, "total": data.len()}))
|
||||
}
|
||||
async fn send(
|
||||
State(f): State<Arc<Fake>>,
|
||||
@@ -378,7 +464,7 @@ mod tests {
|
||||
let app = Router::new()
|
||||
.route("/document-blocks", get(blocks))
|
||||
.route("/partners", post(partner))
|
||||
.route("/documents", post(document))
|
||||
.route("/documents", post(document).get(documents))
|
||||
.route("/documents/{id}/send", post(send))
|
||||
.with_state(fake);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
@@ -497,4 +583,40 @@ mod tests {
|
||||
assert!(error.contains("422") && error.contains("invalid tax code"), "{error}");
|
||||
assert_eq!(fake.documents.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn a_lost_answer_does_not_make_a_second_invoice(db: PgPool) {
|
||||
let fake = Arc::new(Fake::default());
|
||||
fake.lose_document_answer.store(true, Ordering::SeqCst);
|
||||
let billingo = Billingo::new(&fake_billingo(fake.clone()).await, "key", Some(7));
|
||||
let id = paid(&db, None).await;
|
||||
// Billingo makes the invoice, but its answer is lost.
|
||||
assert_eq!(run_once(&db, &billingo, 5).await.unwrap(), 0);
|
||||
assert_eq!(state(&db, id).await.2, None);
|
||||
// The retry finds it instead of making another.
|
||||
sqlx::query("UPDATE invoices SET next_attempt_at = now()").execute(&db).await.unwrap();
|
||||
assert_eq!(run_once(&db, &billingo, 5).await.unwrap(), 1);
|
||||
let (status, number, document, sent, _) = state(&db, id).await;
|
||||
assert_eq!(
|
||||
(status.as_str(), number.as_deref(), document, sent),
|
||||
("issued", Some("SF-2026-1"), Some(901), true)
|
||||
);
|
||||
assert_eq!(fake.documents.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn an_invoice_that_cannot_be_emailed_still_counts_as_issued(db: PgPool) {
|
||||
let fake = Arc::new(Fake::default());
|
||||
fake.send_failures.store(100, Ordering::SeqCst);
|
||||
let billingo = Billingo::new(&fake_billingo(fake.clone()).await, "key", Some(7));
|
||||
let id = paid(&db, None).await;
|
||||
run_once(&db, &billingo, 2).await.unwrap();
|
||||
sqlx::query("UPDATE invoices SET next_attempt_at = now()").execute(&db).await.unwrap();
|
||||
assert_eq!(run_once(&db, &billingo, 2).await.unwrap(), 1);
|
||||
let (status, number, _, sent, _) = state(&db, id).await;
|
||||
assert_eq!((status.as_str(), number.as_deref(), sent), ("issued", Some("SF-2026-1"), false));
|
||||
let (error,): (String,) =
|
||||
sqlx::query_as("SELECT last_error FROM invoices WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
|
||||
assert!(error.starts_with("issued, not e-mailed"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user