Invoices: issued in Billingo by the worker, downloadable on Számláim
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 9m7s
CI / deploy (push) Skipped

A paid checkout queues an invoice row with every invoice detail (buyer,
tax type and number, item, net, VAT, gross). The worker's new 'invoices'
task creates the Billingo partner and the paid card invoice and e-mails
it (API v3), saving each step so a retry never issues a second invoice,
and keeps Billingo's whole answer; the PDF is fetched from Billingo when
the user downloads it from the new Számláim page (in the menu once there
is an invoice). Payments and invoices outlive a deleted account.

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-20 07:52:34 +00:00
co-authored by Claude Opus 5.5
parent e530e78c54
commit 2a0830fda0
24 changed files with 1090 additions and 35 deletions
+11
View File
@@ -48,6 +48,10 @@ pub struct Config {
/// Stripe Checkout, when `STRIPE_SECRET_KEY` is set (it wins over
/// `MOCK_PAYMENTS`).
pub stripe: Option<StripeConfig>,
/// `BILLINGO_API_KEY`: downloading invoices (the worker issues them).
pub billingo_api_key: Option<String>,
/// `BILLINGO_API_URL` (default `https://api.billingo.hu/v3`).
pub billingo_api_url: String,
/// `PURCHASES_OPEN` (default `false`): everyone may buy through Stripe.
/// Until the opening only admins can (and with a test key always only
/// admins), so nobody types a real card into a test or unfinished setup.
@@ -170,6 +174,11 @@ impl Config {
.trim_end_matches('/')
.to_string(),
}),
billingo_api_key: var("BILLINGO_API_KEY"),
billingo_api_url: var("BILLINGO_API_URL")
.unwrap_or_else(|| "https://api.billingo.hu/v3".into())
.trim_end_matches('/')
.to_string(),
purchases_open: parsed("PURCHASES_OPEN", false)?,
user_invites: parsed("USER_INVITES", false)?,
referral_rewards: parsed("REFERRAL_REWARDS", false)?,
@@ -211,6 +220,8 @@ impl Config {
password_login: true,
mock_payments: true,
stripe: None,
billingo_api_key: Some("billingo-fake".into()),
billingo_api_url: format!("{horoscope_api_url}/billingo"),
purchases_open: true,
user_invites: true,
referral_rewards: true,
+146
View File
@@ -0,0 +1,146 @@
//! Invoices of the Stripe payments. When a payment is confirmed, an invoice
//! row is queued with the buyer and the item as they go on the invoice; the
//! worker issues it in Billingo (`services/worker/src/invoices.rs`). Users
//! download the PDF through the backend, which fetches it from Billingo.
use serde_json::Value;
use sqlx::PgConnection;
use uuid::Uuid;
use crate::error::ApiError;
/// VAT of every package, in percent.
pub const VAT_PERCENT: i64 = 27;
/// The buyer as invoiced, from Stripe's `customer_details`.
#[derive(Debug, PartialEq, Eq)]
pub struct Buyer {
pub name: String,
pub email: Option<String>,
pub country: String,
pub post_code: String,
pub city: String,
pub address: String,
/// Billingo's partner tax type: `HAS_TAX_NUMBER`, `NO_TAX_NUMBER` or `FOREIGN`.
pub tax_type: &'static str,
pub tax_number: Option<String>,
}
fn text(v: &Value) -> Option<String> {
v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)
}
impl Buyer {
/// A company ("buying as a business") gives its name and tax id: a
/// Hungarian tax number (`hu_tin`) is preferred to an EU VAT number.
pub fn from_stripe(details: &Value, fallback_email: Option<&str>) -> Self {
let address = &details["address"];
let tax_ids = details["tax_ids"].as_array().map(Vec::as_slice).unwrap_or_default();
let tax_id = |kind: &str| tax_ids.iter().find(|t| t["type"] == kind).and_then(|t| text(&t["value"]));
let tax_number = tax_id("hu_tin").or_else(|| tax_id("eu_vat"));
let country = text(&address["country"]).unwrap_or_else(|| "HU".into()).to_uppercase();
let tax_type = match (&tax_number, country.as_str()) {
(_, c) if c != "HU" => "FOREIGN",
(Some(_), _) => "HAS_TAX_NUMBER",
(None, _) => "NO_TAX_NUMBER",
};
let street = [text(&address["line1"]), text(&address["line2"])].into_iter().flatten().collect::<Vec<_>>();
Self {
name: text(&details["business_name"])
.filter(|_| tax_number.is_some())
.or_else(|| text(&details["name"]))
.unwrap_or_else(|| "Vevő".into()),
email: text(&details["email"]).or_else(|| fallback_email.map(str::to_string)),
country,
post_code: text(&address["postal_code"]).unwrap_or_default(),
city: text(&address["city"]).unwrap_or_default(),
address: street.join(", "),
tax_type,
tax_number,
}
}
}
/// Net and VAT parts of a gross price (rounded to forints, as Billingo does).
pub fn split_gross(gross: i64) -> (i64, i64) {
let net = (gross * 200 + 100 + VAT_PERCENT) / (200 + 2 * VAT_PERCENT);
(net, gross - net)
}
/// Queues the invoice of a paid checkout, inside the caller's transaction.
pub async fn queue(
tx: &mut PgConnection,
checkout_id: &str,
user_id: Option<Uuid>,
buyer: &Buyer,
item_name: &str,
gross_huf: i64,
) -> Result<Uuid, ApiError> {
let id = Uuid::now_v7();
let (net, vat) = split_gross(gross_huf);
sqlx::query(
"INSERT INTO invoices (id, checkout_id, user_id, buyer_name, buyer_email, buyer_country, buyer_post_code, \
buyer_city, buyer_address, buyer_tax_type, buyer_tax_number, item_name, gross_huf, net_huf, vat_huf, vat_rate) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) \
ON CONFLICT (checkout_id) DO NOTHING",
)
.bind(id)
.bind(checkout_id)
.bind(user_id)
.bind(&buyer.name)
.bind(&buyer.email)
.bind(&buyer.country)
.bind(&buyer.post_code)
.bind(&buyer.city)
.bind(&buyer.address)
.bind(buyer.tax_type)
.bind(&buyer.tax_number)
.bind(item_name)
.bind(gross_huf as i32)
.bind(net as i32)
.bind(vat as i32)
.bind(format!("{VAT_PERCENT}%"))
.execute(&mut *tx)
.await?;
Ok(id)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn gross_prices_split_into_net_and_vat() {
assert_eq!(split_gross(2000), (1575, 425));
assert_eq!(split_gross(6000), (4724, 1276));
assert_eq!(split_gross(127), (100, 27));
}
#[test]
fn buyers_from_stripe() {
let person = Buyer::from_stripe(
&json!({"name": "Kovács Anna", "email": "anna@example.com",
"address": {"line1": "Fő utca 1.", "line2": "2/3", "postal_code": "6720", "city": "Szeged", "country": "HU"},
"tax_ids": []}),
None,
);
assert_eq!(person.name, "Kovács Anna");
assert_eq!(person.address, "Fő utca 1., 2/3");
assert_eq!((person.tax_type, person.tax_number), ("NO_TAX_NUMBER", None));
let company = Buyer::from_stripe(
&json!({"name": "Kovács Anna", "business_name": "Csillag Kft.",
"address": {"line1": "Kossuth tér 2.", "postal_code": "1055", "city": "Budapest", "country": "HU"},
"tax_ids": [{"type": "eu_vat", "value": "HU12345678"}, {"type": "hu_tin", "value": "12345678-1-23"}]}),
Some("anna@example.com"),
);
assert_eq!(company.name, "Csillag Kft.");
assert_eq!(company.email.as_deref(), Some("anna@example.com"));
assert_eq!((company.tax_type, company.tax_number.as_deref()), ("HAS_TAX_NUMBER", Some("12345678-1-23")));
let abroad = Buyer::from_stripe(&json!({"name": "Anna", "address": {"country": "at"}}), None);
assert_eq!((abroad.country.as_str(), abroad.tax_type), ("AT", "FOREIGN"));
}
}
+1
View File
@@ -13,6 +13,7 @@ mod config;
mod credits;
mod error;
mod google;
mod invoices;
mod models;
mod packages;
mod persons;
+6
View File
@@ -35,6 +35,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let package = crate::packages::current(&mut conn, auth.id()).await?;
let share_reward = super::shares::reward_granted(&state.db, auth.id()).await?;
let referrals = super::shares::referral_rewards(&mut conn, auth.id()).await?;
let (invoices,): (i64,) = sqlx::query_as("SELECT count(*) FROM invoices WHERE user_id = $1")
.bind(auth.id())
.fetch_one(&mut *conn)
.await?;
Ok(Json(json!({
"user": UserView::from(&auth.user),
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
@@ -47,6 +51,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
"share_reward_granted": share_reward,
// Natal analyses earned by bringing new users, and how many can be.
"referral_rewards": { "earned": referrals, "limit": super::shares::REFERRAL_LIMIT },
// The "Számláim" menu shows up with the first invoice.
"invoice_count": invoices,
})))
}
@@ -0,0 +1,100 @@
//! The user's invoices: the list, and the PDF fetched from Billingo on
//! download (we keep every invoice detail, but not the PDF itself).
use std::time::Duration;
use axum::Json;
use axum::extract::{Path, State};
use axum::http::{HeaderValue, header};
use axum::response::{IntoResponse, Response};
use axum_extra::extract::WithRejection;
use serde_json::{Value, json};
use time::{Date, OffsetDateTime};
use uuid::Uuid;
use super::{IdPath, St};
use crate::auth::AuthUser;
use crate::error::{ApiError, ApiResult};
type Row = (Uuid, String, Option<String>, Option<Date>, String, i32, OffsetDateTime);
/// The user's invoices, newest first. Until Billingo has issued one it is
/// shown as being prepared.
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let rows: Vec<Row> = sqlx::query_as(
"SELECT id, status, invoice_number, invoice_date, item_name, gross_huf, created_at FROM invoices \
WHERE user_id = $1 ORDER BY created_at DESC",
)
.bind(auth.id())
.fetch_all(&state.db)
.await?;
let invoices: Vec<Value> = rows
.into_iter()
.map(|(id, status, number, date, item, gross, created_at)| {
json!({
"id": id,
"ready": status == "issued",
"invoice_number": number,
"invoice_date": date.map(|d| d.to_string()),
"item": item,
"gross_huf": gross,
"paid_at": created_at.format(&time::format_description::well_known::Rfc3339).ok(),
})
})
.collect();
Ok(Json(json!({ "invoices": invoices })))
}
/// The invoice's PDF, from Billingo.
pub async fn pdf(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Response> {
let row: Option<(i64, Option<String>)> = sqlx::query_as(
"SELECT billingo_document_id, invoice_number FROM invoices \
WHERE id = $1 AND user_id = $2 AND status = 'issued' AND billingo_document_id IS NOT NULL",
)
.bind(id)
.bind(auth.id())
.fetch_optional(&state.db)
.await?;
let (document, number) = row.ok_or(ApiError::NotFound("invoice"))?;
let unavailable = |detail: String| {
tracing::error!(error = %detail, invoice = %id, "invoice download failed");
ApiError::conflict("invoice_unavailable", "A számla letöltése most nem sikerült. Próbáld újra pár perc múlva.")
};
let key =
state.config.billingo_api_key.as_deref().ok_or_else(|| unavailable("BILLINGO_API_KEY is not set".into()))?;
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("static configuration");
let res = http
.get(format!("{}/documents/{document}/download", state.config.billingo_api_url))
.header("X-API-KEY", key)
.header("Accept", "application/pdf")
.send()
.await
.map_err(|e| unavailable(e.to_string()))?;
let is_pdf = res
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|t| t.starts_with("application/pdf"));
if !res.status().is_success() || !is_pdf {
let status = res.status();
let body = res.text().await.unwrap_or_default();
return Err(unavailable(format!("HTTP {status}: {}", body.chars().take(300).collect::<String>())));
}
let bytes = res.bytes().await.map_err(|e| unavailable(e.to_string()))?;
let name: String = number
.unwrap_or_else(|| document.to_string())
.chars()
.map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '-' })
.collect();
let disposition = HeaderValue::from_str(&format!("attachment; filename=\"szamla-{name}.pdf\""))
.unwrap_or_else(|_| HeaderValue::from_static("attachment; filename=\"szamla.pdf\""));
Ok((
[
(header::CONTENT_TYPE, HeaderValue::from_static("application/pdf")),
(header::CONTENT_DISPOSITION, disposition),
(header::CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
],
bytes,
)
.into_response())
}
+3
View File
@@ -13,6 +13,7 @@ mod charts;
mod errors;
mod forecasts;
mod invitations;
mod invoices_user;
mod jobs;
mod models;
mod payments;
@@ -80,6 +81,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/payments/checkout", post(payments::checkout))
.route("/v1/payments/checkout/{id}", get(payments::checkout_status))
.route("/v1/payments/stripe/webhook", post(payments::stripe_webhook))
.route("/v1/invoices", get(invoices_user::list))
.route("/v1/invoices/{id}/pdf", get(invoices_user::pdf))
// charts
.route("/v1/charts", get(charts::list).post(charts::create))
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
+7 -4
View File
@@ -21,7 +21,7 @@ use crate::config::StripeConfig;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::packages::{self, CATALOG, Source};
use crate::{persons, stripe};
use crate::{invoices, persons, stripe};
/// The package catalog (public).
pub async fn catalog() -> Json<Value> {
@@ -184,11 +184,11 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, A
if amount_huf != Some(i64::from(price_huf)) || session.currency.as_deref() != Some("huf") {
tracing::error!(session = %session.id, ?amount_huf, currency = ?session.currency, price_huf, "paid amount differs from the price");
}
let package =
packages::find(&package_id).ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?;
// A deleted account still gets its invoice, but no package.
let order = match user_id {
Some(user_id) => {
let package = packages::find(&package_id)
.ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?;
let note = format!("Stripe {}", session.id);
Some(packages::grant(&mut tx, user_id, package, Source::Stripe, Some(user_id), Some(&note)).await?)
}
@@ -196,7 +196,7 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, A
};
sqlx::query(
"UPDATE stripe_checkouts SET completed_at = now(), order_id = $2, payment_intent = $3, amount_huf = $4, \
customer = $5, invoice_status = 'pending' WHERE id = $1",
customer = $5 WHERE id = $1",
)
.bind(&session.id)
.bind(order)
@@ -205,6 +205,9 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, A
.bind(&session.customer_details)
.execute(&mut *tx)
.await?;
let buyer = invoices::Buyer::from_stripe(session.customer_details.as_ref().unwrap_or(&Value::Null), None);
let item = format!("Sorsfonalak – {}", package.name);
invoices::queue(&mut tx, &session.id, user_id, &buyer, &item, amount_huf.unwrap_or(i64::from(price_huf))).await?;
tx.commit().await?;
tracing::info!(user = ?user_id, package = %package_id, session = %session.id, "package paid");
Ok(true)
+88 -8
View File
@@ -157,8 +157,20 @@ async fn fake_stripe_get(axum::extract::Path(id): axum::extract::Path<String>) -
}
}
async fn fake_billingo_pdf(
headers: HeaderMap,
axum::extract::Path(id): axum::extract::Path<i64>,
) -> axum::response::Response {
use axum::response::IntoResponse;
if headers.get("x-api-key").and_then(|v| v.to_str().ok()) != Some("billingo-fake") || id != 777 {
return (StatusCode::NOT_FOUND, Json(json!({"error": {"message": "no such document"}}))).into_response();
}
([("content-type", "application/pdf")], "%PDF-1.4 fake").into_response()
}
async fn fake_services() -> String {
let app = Router::new()
.route("/billingo/documents/{id}/download", get(fake_billingo_pdf))
.route("/openrouter/models", get(fake_openrouter_models))
.route("/v1/checkout/sessions", post(fake_stripe_create))
.route("/v1/checkout/sessions/{id}", get(fake_stripe_get))
@@ -2355,16 +2367,81 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
}
assert_eq!(stripe_orders(&app.pool, "anna@example.com").await, vec![("couple".to_string(), 6000)]);
// What the invoice needs is kept, and the invoice is queued.
let (intent, amount, customer, invoice): (String, i32, Value, String) = sqlx::query_as(
"SELECT payment_intent, amount_huf, customer, invoice_status FROM stripe_checkouts WHERE id = $1",
let (intent, amount, customer): (String, i32, Value) =
sqlx::query_as("SELECT payment_intent, amount_huf, customer FROM stripe_checkouts WHERE id = $1")
.bind(&id)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!((intent.as_str(), amount), ("pi_1", 6000));
assert_eq!(customer["tax_ids"][0]["value"], "12345678-1-23");
#[derive(sqlx::FromRow, Debug)]
struct Queued {
status: String,
buyer_name: String,
buyer_address: String,
buyer_post_code: String,
buyer_tax_type: String,
buyer_tax_number: Option<String>,
item_name: String,
gross_huf: i32,
net_huf: i32,
vat_huf: i32,
}
let invoice: Queued = sqlx::query_as(
"SELECT status, buyer_name, buyer_address, buyer_post_code, buyer_tax_type, buyer_tax_number, item_name, \
gross_huf, net_huf, vat_huf FROM invoices WHERE checkout_id = $1",
)
.bind(&id)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!((intent.as_str(), amount, invoice.as_str()), ("pi_1", 6000, "pending"));
assert_eq!(customer["tax_ids"][0]["value"], "12345678-1-23");
assert_eq!(customer["address"]["postal_code"], "6720");
assert_eq!(invoice.status, "pending");
assert_eq!((invoice.buyer_name.as_str(), invoice.buyer_address.as_str()), ("Csillag Kft.", "Fő utca 1."));
assert_eq!(invoice.buyer_post_code, "6720");
assert_eq!(
(invoice.buyer_tax_type.as_str(), invoice.buyer_tax_number.as_deref()),
("HAS_TAX_NUMBER", Some("12345678-1-23"))
);
assert_eq!(invoice.item_name, "Sorsfonalak – Páros");
assert_eq!((invoice.gross_huf, invoice.net_huf, invoice.vat_huf), (6000, 4724, 1276));
// The user's invoices: being prepared until Billingo issues it, then the
// PDF comes from Billingo.
let r = app.get("/v1/invoices", Some(&anna)).await;
assert_eq!(r.body["invoices"].as_array().unwrap().len(), 1);
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["invoice_count"], 1);
assert_eq!(r.body["invoices"][0]["ready"], false);
let invoice_id = r.body["invoices"][0]["id"].as_str().unwrap().to_string();
let r = app.get(&format!("/v1/invoices/{invoice_id}/pdf"), Some(&anna)).await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
sqlx::query(
"UPDATE invoices SET status = 'issued', billingo_document_id = 777, invoice_number = 'SF-2026/1', \
invoice_date = '2026-11-20' WHERE id = $1::uuid",
)
.bind(&invoice_id)
.execute(&app.pool)
.await
.unwrap();
let r = app.get("/v1/invoices", Some(&anna)).await;
assert_eq!(
(&r.body["invoices"][0]["ready"], &r.body["invoices"][0]["invoice_number"]),
(&json!(true), &json!("SF-2026/1"))
);
let req = Request::builder()
.uri(format!("/v1/invoices/{invoice_id}/pdf"))
.header("authorization", format!("Bearer {anna}"))
.body(Body::empty())
.unwrap();
let resp = app.router.clone().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers()["content-type"], "application/pdf");
assert_eq!(resp.headers()["content-disposition"], "attachment; filename=\"szamla-SF-2026-1.pdf\"");
assert!(resp.into_body().collect().await.unwrap().to_bytes().starts_with(b"%PDF"));
// Nobody else's.
let r = app.get(&format!("/v1/invoices/{invoice_id}/pdf"), Some(&bela)).await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
assert_eq!(app.get("/v1/invoices", Some(&bela)).await.body["invoices"], json!([]));
let r = app.get(&format!("/v1/payments/checkout/{id}"), Some(&anna)).await;
assert_eq!(r.body["status"], "paid");
assert_eq!(r.body["name"], "Páros");
@@ -2388,13 +2465,13 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
stripe_orders(&app.pool, "anna@example.com").await,
vec![("couple".to_string(), 6000), ("single".to_string(), 2000)]
);
let (name, invoice): (String, String) =
sqlx::query_as("SELECT customer->>'name', invoice_status FROM stripe_checkouts WHERE id = $1")
let (name, tax_type): (String, String) =
sqlx::query_as("SELECT buyer_name, buyer_tax_type FROM invoices WHERE checkout_id = $1")
.bind(&other)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!((name.as_str(), invoice.as_str()), ("Anna Teszt", "pending"));
assert_eq!((name.as_str(), tax_type.as_str()), ("Anna Teszt", "NO_TAX_NUMBER"));
// Deleting the account keeps the payments (accounting law).
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "DELETE"}))).await;
@@ -2405,6 +2482,9 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
.await
.unwrap();
assert_eq!(kept, 2);
let (kept,): (i64,) =
sqlx::query_as("SELECT count(*) FROM invoices WHERE user_id IS NULL").fetch_one(&app.pool).await.unwrap();
assert_eq!(kept, 2);
}
#[sqlx::test(migrator = "db::MIGRATOR")]