From e530e78c542841717dbef5710b8859869e15fe1d Mon Sep 17 00:00:00 2001 From: feco Date: Fri, 20 Nov 2026 07:26:03 +0000 Subject: [PATCH 1/3] Stripe: company purchases, payment details kept for the invoice The checkout offers buying as a company (name, tax number). A confirmed payment keeps Stripe's payment id, the amount charged and the buyer's billing details, and queues the invoice for a background job (Billingo, once the company exists). Payments outlive a deleted account for the accounting law's 8 years. The package cards, the FAQ and the privacy policy say that card details go to Stripe only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- .../db/migrations/0027_stripe_checkouts.sql | 35 +++++++-- docs/fizetes.md | 17 ++++- services/backend/src/routes/payments.rs | 75 ++++++++++++------- services/backend/src/stripe.rs | 12 +++ services/backend/src/tests.rs | 42 ++++++++++- .../frontend/src/app/adatvedelem/page.tsx | 18 ++++- services/frontend/src/app/csomagok/page.tsx | 4 + services/frontend/src/app/privacy/page.tsx | 15 +++- .../frontend/src/components/PackageCards.tsx | 6 +- services/frontend/src/lib/legal.ts | 4 +- 10 files changed, 180 insertions(+), 48 deletions(-) diff --git a/crates/db/migrations/0027_stripe_checkouts.sql b/crates/db/migrations/0027_stripe_checkouts.sql index f7d2114..40212d4 100644 --- a/crates/db/migrations/0027_stripe_checkouts.sql +++ b/crates/db/migrations/0027_stripe_checkouts.sql @@ -1,16 +1,35 @@ -- Stripe Checkout sessions started from the package cards. The package is -- granted once, when the payment is confirmed (webhook, or the return page -- asking Stripe), and the session id keeps that from happening twice. +-- Card details never reach us: only what Stripe reports about the payment and +-- the buyer's billing details for the invoice. CREATE TABLE stripe_checkouts ( -- Stripe's Checkout Session id (cs_test_… / cs_live_…). - id text PRIMARY KEY, - user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, - package text NOT NULL, - price_huf integer NOT NULL CHECK (price_huf > 0), - live boolean NOT NULL, - created_at timestamptz NOT NULL DEFAULT now(), - completed_at timestamptz, - order_id uuid REFERENCES package_orders ON DELETE SET NULL + id text PRIMARY KEY, + -- Kept when the account is deleted: payments and invoices must be kept + -- for the accounting law's 8 years. + user_id uuid REFERENCES users ON DELETE SET NULL, + package text NOT NULL, + price_huf integer NOT NULL CHECK (price_huf > 0), + live boolean NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + -- Filled when the payment is confirmed. + completed_at timestamptz, + order_id uuid REFERENCES package_orders ON DELETE SET NULL, + payment_intent text, + -- What Stripe charged, in forints. + amount_huf integer, + -- Stripe's customer_details: name, e-mail, address, and for a company + -- its name and tax ids. + customer jsonb, + -- The invoice (a background job issues it): pending → issued, or failed + -- after retries (an admin looks at it). + invoice_status text CHECK (invoice_status IN ('pending', 'issued', 'failed')), + invoice_attempts integer NOT NULL DEFAULT 0, + invoice_error text, + invoice_number text, + invoiced_at timestamptz ); CREATE INDEX stripe_checkouts_user_idx ON stripe_checkouts (user_id, created_at DESC); +CREATE INDEX stripe_checkouts_invoice_idx ON stripe_checkouts (completed_at) WHERE invoice_status = 'pending'; diff --git a/docs/fizetes.md b/docs/fizetes.md index 33bbf3c..49dcf92 100644 --- a/docs/fizetes.md +++ b/docs/fizetes.md @@ -13,6 +13,21 @@ A csomagokat a Stripe Checkout fizetési oldalán lehet megvenni. A csomagok nev A session id miatt egy fizetés csak egyszer ír jóvá (`package_orders.source = 'stripe'`). +## Mit tárolunk + +Bankkártyaadatot soha: a vásárló a Stripe oldalán adja meg, hozzánk nem jut el. A `stripe_checkouts` sorban a fizetés igazolásakor eltároljuk: + +- a Stripe fizetés azonosítóját (`payment_intent`) és a ténylegesen fizetett összeget (`amount_huf`; ha eltér az ártól, hibát naplózunk), +- a vevő számlázási adatait (`customer`: a Stripe `customer_details` objektuma: név, e-mail, cím, céges vásárlásnál `business_name` és `tax_ids`, pl. `hu_tin` / `eu_vat`). + +A fizetési oldal kötelezően bekéri a számlázási címet, és felkínálja a céges vásárlást (cégnév, adószám; `tax_id_collection`). + +A sorok a fiók törlése után is megmaradnak (`user_id` → NULL), mert a számviteli törvény 8 évig megőrzést ír elő; ilyenkor csomag már nem jár, de a számla elkészül. + +## Számla + +Minden igazolt fizetés `invoice_status = 'pending'` állapotba kerül: ez a számlázási sor. A számlát egy háttérfeladat (worker) állítja ki a Billingo API-val, újrapróbálással (`invoice_attempts`, `invoice_error`), siker után `issued` + `invoice_number`, végleges hiba után `failed` (admin nézi meg). A Billingo-rész a cég és a Billingo-fiók után készül el; addig a sorok `pending` állapotban várnak. + ## Beállítás A kulcsok a `.env.secrets` fájlba kerülnek (helyben a repó gyökerében, a szerveren a `/opt/sorsfonalak` mappában), git-be soha: @@ -41,5 +56,5 @@ Helyben a webhook nem ér el a géphez; nem is kell, mert a visszatérő oldal a ## Megnyitás előtt - A Stripe-fiók aktiválása (céges adatok, bankszámla), élő kulcsok és élő webhook. -- Számla: Billingo API-val, minden sikeres fizetés után (a vásárló neve és címe a Checkoutból jön). A Stripe nyugtája nem magyar számla. +- Számla: a worker Billingo-feladata (lásd fent). A Stripe nyugtája nem magyar számla: a Stripe felületén a Customer emails → Successful payments legyen kikapcsolva. - Visszatérítés: egyelőre a Stripe felületén, a csomagot pedig az admin oldalon kell kézzel csökkenteni. diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index 4b85734..cfebe0a 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -134,8 +134,11 @@ pub async fn checkout( field("locale", "hu"), field("client_reference_id", &auth.id().to_string()), field("customer_email", &auth.user.email), - // Name and address go on the invoice. + // Name and address go on the invoice; a company also gives its name + // and tax number ("I'm buying as a business"). field("billing_address_collection", "required"), + field("tax_id_collection[enabled]", "true"), + field("customer_creation", "always"), field("line_items[0][quantity]", "1"), field("line_items[0][price_data][currency]", "huf"), // Stripe counts forints in fillér. @@ -163,29 +166,47 @@ pub async fn checkout( Ok(Json(json!({ "url": url }))) } -/// Grants the package of a paid session, once. `false`: not our session. -async fn complete(state: &AppState, session_id: &str) -> Result { +/// Records a paid session (what was charged, the buyer's billing details), +/// grants its package and queues the invoice, once. `false`: not our session. +async fn complete(state: &AppState, session: &stripe::Session) -> Result { let mut tx = state.db.begin().await?; - let row: Option<(Uuid, String, Option)> = - sqlx::query_as("SELECT user_id, package, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE") - .bind(session_id) - .fetch_optional(&mut *tx) - .await?; - let Some((user_id, package_id, completed_at)) = row else { return Ok(false) }; + let row: Option<(Option, String, i32, Option)> = sqlx::query_as( + "SELECT user_id, package, price_huf, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE", + ) + .bind(&session.id) + .fetch_optional(&mut *tx) + .await?; + let Some((user_id, package_id, price_huf, completed_at)) = row else { return Ok(false) }; if completed_at.is_some() { return Ok(true); } - let package = - packages::find(&package_id).ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?; - let note = format!("Stripe {session_id}"); - let order = packages::grant(&mut tx, user_id, package, Source::Stripe, Some(user_id), Some(¬e)).await?; - sqlx::query("UPDATE stripe_checkouts SET completed_at = now(), order_id = $2 WHERE id = $1") - .bind(session_id) - .bind(order) - .execute(&mut *tx) - .await?; + let amount_huf = session.amount_total.map(|minor| minor / 100); + 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"); + } + // 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(¬e)).await?) + } + None => None, + }; + 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", + ) + .bind(&session.id) + .bind(order) + .bind(&session.payment_intent) + .bind(amount_huf.map(|a| a as i32)) + .bind(&session.customer_details) + .execute(&mut *tx) + .await?; tx.commit().await?; - tracing::info!(user = %user_id, package = package.id, session = session_id, "package paid"); + tracing::info!(user = ?user_id, package = %package_id, session = %session.id, "package paid"); Ok(true) } @@ -207,7 +228,7 @@ pub async fn checkout_status( if let (None, Some(config)) = (completed_at, &state.config.stripe) { let session = state.stripe.get_session(config, &id).await?; if session.paid() { - complete(&state, &id).await?; + complete(&state, &session).await?; status = "paid"; } else if session.status.as_deref() == Some("expired") { status = "expired"; @@ -235,15 +256,13 @@ pub async fn stripe_webhook(State(state): St, headers: HeaderMap, body: Bytes) - tracing::warn!("stripe webhook with a bad signature"); return Err(ApiError::BadRequest("invalid signature".into())); } - let event: Value = serde_json::from_slice(&body).map_err(|e| ApiError::BadRequest(e.to_string()))?; + let mut event: Value = serde_json::from_slice(&body).map_err(|e| ApiError::BadRequest(e.to_string()))?; let kind = event["type"].as_str().unwrap_or_default(); - let session = &event["data"]["object"]; - if matches!(kind, "checkout.session.completed" | "checkout.session.async_payment_succeeded") - && session["payment_status"] == "paid" - { - let id = session["id"].as_str().unwrap_or_default(); - if !complete(&state, id).await? { - tracing::warn!(session = id, "stripe webhook for a session we did not start"); + if matches!(kind, "checkout.session.completed" | "checkout.session.async_payment_succeeded") { + let session: stripe::Session = serde_json::from_value(event["data"]["object"].take()) + .map_err(|e| ApiError::BadRequest(format!("checkout session: {e}")))?; + if session.paid() && !complete(&state, &session).await? { + tracing::warn!(session = %session.id, "stripe webhook for a session we did not start"); } } Ok(Json(json!({ "received": true }))) diff --git a/services/backend/src/stripe.rs b/services/backend/src/stripe.rs index 98f6439..8d27c9d 100644 --- a/services/backend/src/stripe.rs +++ b/services/backend/src/stripe.rs @@ -7,6 +7,7 @@ use std::time::Duration; use hmac::{Hmac, Mac}; use serde::Deserialize; +use serde_json::Value; use sha2::Sha256; use crate::config::StripeConfig; @@ -24,6 +25,17 @@ pub struct Session { pub payment_status: String, /// `open`, `complete` or `expired`. pub status: Option, + /// In the smallest unit (fillér for forints). + #[serde(default)] + pub amount_total: Option, + #[serde(default)] + pub currency: Option, + /// The PaymentIntent's id. + #[serde(default)] + pub payment_intent: Option, + /// Name, e-mail, billing address; for a company its name and tax ids. + #[serde(default)] + pub customer_details: Option, } impl Session { diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 2017f13..04e526e 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -148,7 +148,10 @@ async fn fake_stripe_get(axum::extract::Path(id): axum::extract::Path) - StatusCode::OK, Json(json!({"id": id, "url": null, "payment_status": if *paid { "paid" } else { "unpaid" }, - "status": if *paid { "complete" } else { "open" }})), + "status": if *paid { "complete" } else { "open" }, + "amount_total": 200000, "currency": "huf", "payment_intent": "pi_fake", + "customer_details": {"name": "Anna Teszt", "email": "anna@example.com", + "address": {"city": "Szeged", "country": "HU"}, "tax_ids": []}})), ), None => (StatusCode::NOT_FOUND, Json(json!({"error": {"message": "no such session"}}))), } @@ -2301,6 +2304,8 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) { Some("Sorsfonalak – Páros") ); assert_eq!(stripe_form(&id, "customer_email").as_deref(), Some("anna@example.com")); + assert_eq!(stripe_form(&id, "tax_id_collection[enabled]").as_deref(), Some("true")); + assert_eq!(stripe_form(&id, "billing_address_collection").as_deref(), Some("required")); assert_eq!( stripe_form(&id, "success_url").as_deref(), Some("https://sorsfonalak.test/kepletek/abc?fizetes={CHECKOUT_SESSION_ID}") @@ -2327,7 +2332,12 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) { // The webhook: a bad signature is refused, a good one grants the package, // and Stripe's retries do not grant it again. let event = json!({"id": "evt_1", "type": "checkout.session.completed", - "data": {"object": {"id": id, "payment_status": "paid"}}}); + "data": {"object": {"id": id, "payment_status": "paid", "status": "complete", + "amount_total": 600000, "currency": "huf", "payment_intent": "pi_1", + "customer_details": {"name": "Kovács Anna", "email": "anna@example.com", + "business_name": "Csillag Kft.", + "address": {"line1": "Fő utca 1.", "city": "Szeged", "postal_code": "6720", "country": "HU"}, + "tax_ids": [{"type": "hu_tin", "value": "12345678-1-23"}]}}}}); let body = event.to_string(); let now = time::OffsetDateTime::now_utc().unix_timestamp(); let bad = crate::stripe::sign("whsec_other", body.as_bytes(), now); @@ -2344,6 +2354,17 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) { assert_eq!(r.status, StatusCode::OK, "{}", r.body); } 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", + ) + .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"); 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"); @@ -2367,6 +2388,23 @@ 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") + .bind(&other) + .fetch_one(&app.pool) + .await + .unwrap(); + assert_eq!((name.as_str(), invoice.as_str()), ("Anna Teszt", "pending")); + + // Deleting the account keeps the payments (accounting law). + let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "DELETE"}))).await; + assert!(r.status.is_success(), "{}", r.body); + let (kept,): (i64,) = + sqlx::query_as("SELECT count(*) FROM stripe_checkouts WHERE user_id IS NULL AND completed_at IS NOT NULL") + .fetch_one(&app.pool) + .await + .unwrap(); + assert_eq!(kept, 2); } #[sqlx::test(migrator = "db::MIGRATOR")] diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index 3b71040..6c399d3 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -86,6 +86,14 @@ export default async function PrivacyPage() { A megvásárolt szolgáltatás nyújtása, elszámolás Szerződés teljesítése; számviteli kötelezettség (6. cikk (1) c) + + + Fizetéseid adatai: a Stripe fizetési azonosítója, a fizetett összeg, a számlázási neved, címed és + e-mail-címed, céges vásárlásnál a cégnév és az adószám + + A fizetés igazolása, a számla kiállítása + Szerződés teljesítése; számviteli kötelezettség (6. cikk (1) c) + Meghívott e-mail-címe, a meghívó neve és személyes üzenete A meghívó elküldése; amíg az oldal zártkörű, csak meghívottak regisztrálhatnak @@ -110,8 +118,10 @@ export default async function PrivacyPage() {

- Bankkártyaadatot nem kezelünk és nem tárolunk; a fizetést, amikor elindul, külső fizetési szolgáltató - végzi, akinek a neve itt lesz feltüntetve. + Bankkártyaadatot nem kezelünk és nem tárolunk. A fizetés a Stripe biztonságos fizetési + oldalán történik: a kártyaadataidat közvetlenül a Stripe-nak adod meg, hozzánk nem jutnak el. A Stripe-tól + csak a fizetés azonosítóját, összegét és a számlázási adataidat kapjuk meg. Ezeket a fiókod törlése után is + megőrizzük a számviteli törvény szerinti ideig (8 évig).

@@ -198,6 +208,10 @@ export default async function PrivacyPage() { Amazon Web Services EMEA SARL (Amazon SES) – a rendszerlevelek és a meghívók kézbesítése; az Európai Unióban (Frankfurt). +
  • + Stripe Payments Europe, Ltd. (Írország) – a bankkártyás fizetés lebonyolítása és a + visszaélések kiszűrése; a kártyaadatokat csak a Stripe kezeli. +
  • OpenRouter, Inc. és az általa elért mesterségesintelligencia-szolgáltatók – az elemzések megírása, kizárólag a 4. pontban leírt csillagászati adatokból (személyes adat nem jut el hozzájuk). diff --git a/services/frontend/src/app/csomagok/page.tsx b/services/frontend/src/app/csomagok/page.tsx index dc42293..4a62180 100644 --- a/services/frontend/src/app/csomagok/page.tsx +++ b/services/frontend/src/app/csomagok/page.tsx @@ -10,6 +10,10 @@ import type { Package, PublicConfig } from "@/lib/types"; export const metadata: Metadata = { title: "Csomagok" }; const FAQ: [string, string][] = [ + [ + "Biztonságos a fizetés?", + "Igen. A fizetés a Stripe biztonságos fizetési oldalán történik, bankkártyával, Apple Payjel vagy Google Payjel. A kártyaadataidat közvetlenül a Stripe-nak adod meg: hozzánk nem jutnak el, és nem is tároljuk őket. Cégként is vásárolhatsz, ilyenkor a cégnevet és az adószámot is megadhatod a számlához.", + ], [ "Lejárnak a megvett elemzések?", "Nem. A csomagokban kapott elemzések és személyhelyek addig megmaradnak, amíg fel nem használod őket.", diff --git a/services/frontend/src/app/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index 144af53..7571f0e 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -33,6 +33,11 @@ const DATA: [string, string, string][] = [ "Providing the purchased service, accounting", "Performance of a contract; legal obligation (Art. 6(1)(c))", ], + [ + "Your payments: Stripe's payment ID, the amount paid, your billing name, address and e-mail address, and for a company purchase the company name and tax number", + "Proof of payment, issuing the invoice", + "Performance of a contract; legal obligation (Art. 6(1)(c))", + ], [ "An invitee's e-mail address, the inviter's name and personal message", "Sending the invitation; while the site is invitation-only, only invitees can sign up", @@ -113,8 +118,10 @@ export default async function PrivacyPolicyPage() {

    - We do not process or store card details; payments, once available, will be handled by an external payment - provider, named here. + We do not process or store card details. Payments are made on Stripe's secure payment + page: you give your card details directly to Stripe, and they never reach us. From Stripe we only receive + the payment's ID, the amount and your billing details, which we keep for the period required by + accounting law (8 years), even after your account is deleted.

    @@ -200,6 +207,10 @@ export default async function PrivacyPolicyPage() { Amazon Web Services EMEA SARL (Amazon SES): delivering service e-mails and invitations; in the European Union (Frankfurt).
  • +
  • + Stripe Payments Europe, Ltd. (Ireland): processing card payments and preventing fraud; + only Stripe handles card details. +
  • OpenRouter, Inc. and the artificial intelligence providers it reaches: writing the readings, only from the astronomical data described in section 4 (no personal data reaches them). diff --git a/services/frontend/src/components/PackageCards.tsx b/services/frontend/src/components/PackageCards.tsx index 6017449..79c9720 100644 --- a/services/frontend/src/components/PackageCards.tsx +++ b/services/frontend/src/components/PackageCards.tsx @@ -149,10 +149,10 @@ export function PackageCards({

    )} {canPay === "mock" &&

    Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.

    } - {canPay === "stripe" && !compact && ( + {(canPay === "stripe" || canPay === "stripe_test") && (

    - A fizetés a Stripe biztonságos oldalán történik (bankkártya, Apple Pay, Google Pay); a kártyaadataidat mi nem - látjuk. + A fizetés a Stripe biztonságos oldalán történik (bankkártya, Apple Pay, + Google Pay). A kártyaadataidat közvetlenül a Stripe-nak adod meg: mi nem látjuk és nem tároljuk őket.

    )} {canPay === "stripe_test" && ( diff --git a/services/frontend/src/lib/legal.ts b/services/frontend/src/lib/legal.ts index daebda4..7d6119a 100644 --- a/services/frontend/src/lib/legal.ts +++ b/services/frontend/src/lib/legal.ts @@ -15,5 +15,5 @@ export function operatorDetails(): string | null { return parts.length > 0 ? parts.join(", ") : null; } -export const PRIVACY_UPDATED = "2026. november 19."; -export const PRIVACY_UPDATED_EN = "19 November 2026"; +export const PRIVACY_UPDATED = "2026. november 20."; +export const PRIVACY_UPDATED_EN = "20 November 2026"; From 2a0830fda06d0221c8bdb568a8ebb96168aa6f39 Mon Sep 17 00:00:00 2001 From: feco Date: Fri, 20 Nov 2026 07:52:34 +0000 Subject: [PATCH 2/3] =?UTF-8?q?Invoices:=20issued=20in=20Billingo=20by=20t?= =?UTF-8?q?he=20worker,=20downloadable=20on=20Sz=C3=A1ml=C3=A1im?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- .../db/migrations/0027_stripe_checkouts.sql | 60 ++- deploy/README.md | 2 +- deploy/docker-compose.yml | 2 +- docs/fizetes.md | 22 +- services/backend/src/config.rs | 11 + services/backend/src/invoices.rs | 146 ++++++ services/backend/src/main.rs | 1 + services/backend/src/routes/account.rs | 6 + services/backend/src/routes/invoices_user.rs | 100 ++++ services/backend/src/routes/mod.rs | 3 + services/backend/src/routes/payments.rs | 11 +- services/backend/src/tests.rs | 96 +++- .../frontend/src/app/adatvedelem/page.tsx | 4 + services/frontend/src/app/csomagok/page.tsx | 7 + services/frontend/src/app/globals.css | 7 + services/frontend/src/app/privacy/page.tsx | 4 + services/frontend/src/app/robots.ts | 2 +- services/frontend/src/app/szamlak/page.tsx | 77 +++ .../frontend/src/components/SiteHeader.tsx | 1 + services/frontend/src/lib/types.ts | 13 + services/worker/src/config.rs | 28 +- services/worker/src/invoices.rs | 489 ++++++++++++++++++ services/worker/src/main.rs | 25 +- services/worker/src/tests.rs | 8 +- 24 files changed, 1090 insertions(+), 35 deletions(-) create mode 100644 services/backend/src/invoices.rs create mode 100644 services/backend/src/routes/invoices_user.rs create mode 100644 services/frontend/src/app/szamlak/page.tsx create mode 100644 services/worker/src/invoices.rs diff --git a/crates/db/migrations/0027_stripe_checkouts.sql b/crates/db/migrations/0027_stripe_checkouts.sql index 40212d4..c26c0ff 100644 --- a/crates/db/migrations/0027_stripe_checkouts.sql +++ b/crates/db/migrations/0027_stripe_checkouts.sql @@ -19,17 +19,55 @@ CREATE TABLE stripe_checkouts ( payment_intent text, -- What Stripe charged, in forints. amount_huf integer, - -- Stripe's customer_details: name, e-mail, address, and for a company - -- its name and tax ids. - customer jsonb, - -- The invoice (a background job issues it): pending → issued, or failed - -- after retries (an admin looks at it). - invoice_status text CHECK (invoice_status IN ('pending', 'issued', 'failed')), - invoice_attempts integer NOT NULL DEFAULT 0, - invoice_error text, - invoice_number text, - invoiced_at timestamptz + -- Stripe's customer_details as it came: name, e-mail, address, and for a + -- company its name and tax ids. + customer jsonb ); CREATE INDEX stripe_checkouts_user_idx ON stripe_checkouts (user_id, created_at DESC); -CREATE INDEX stripe_checkouts_invoice_idx ON stripe_checkouts (completed_at) WHERE invoice_status = 'pending'; + +-- One invoice per paid checkout, issued in Billingo by the worker. Every +-- invoice detail is kept here (the buyer and the item as invoiced, Billingo's +-- whole answer); the PDF itself is fetched from Billingo when downloaded. +CREATE TABLE invoices ( + id uuid PRIMARY KEY, + checkout_id text NOT NULL UNIQUE REFERENCES stripe_checkouts ON DELETE RESTRICT, + user_id uuid REFERENCES users ON DELETE SET NULL, + -- pending → issued; failed after the last retry (an admin looks at it). + status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'issued', 'failed')), + attempts integer NOT NULL DEFAULT 0, + next_attempt_at timestamptz NOT NULL DEFAULT now(), + last_error text, + -- The buyer as invoiced. + buyer_name text NOT NULL, + buyer_email text, + buyer_country text NOT NULL, + buyer_post_code text NOT NULL, + buyer_city text NOT NULL, + buyer_address text NOT NULL, + -- Billingo's partner tax type: HAS_TAX_NUMBER, NO_TAX_NUMBER or FOREIGN. + buyer_tax_type text NOT NULL CHECK (buyer_tax_type IN ('HAS_TAX_NUMBER', 'NO_TAX_NUMBER', 'FOREIGN')), + buyer_tax_number text, + -- The single item, gross price with 27% VAT. + item_name text NOT NULL, + gross_huf integer NOT NULL CHECK (gross_huf > 0), + net_huf integer NOT NULL, + vat_huf integer NOT NULL, + vat_rate text NOT NULL DEFAULT '27%', + payment_method text NOT NULL DEFAULT 'online_bankcard', + -- From Billingo. + billingo_partner_id bigint, + billingo_document_id bigint UNIQUE, + invoice_number text, + invoice_date date, + fulfillment_date date, + due_date date, + document jsonb, + -- When Billingo e-mailed it to the buyer. + sent_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + issued_at timestamptz +); + +CREATE INDEX invoices_user_idx ON invoices (user_id, created_at DESC); +CREATE INDEX invoices_due_idx ON invoices (next_attempt_at) WHERE status = 'pending'; diff --git a/deploy/README.md b/deploy/README.md index f871589..ae4ad03 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -68,7 +68,7 @@ A Docker által kinyitott portokat az ufw magától nem szűri, ezért a 80-as `deploy` felhasználóként, a `/opt/sorsfonalak` mappában: - `.env`: az itteni `.env.example` kitöltve. -- `.env.secrets`: `OPENROUTER_API_KEY=...`, a levélküldés adatai, és ha van, `STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET` (`docs/fizetes.md`). +- `.env.secrets`: `OPENROUTER_API_KEY=...`, a levélküldés adatai, és ha van, `STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET` és `BILLINGO_API_KEY` (`docs/fizetes.md`). - `docker login registry.sagifer.com` egy `read:package` jogú tokennel. Amíg a `sagifer` fiók nyilvános, erre nincs szükség. ### Cloudflare (sorsfonalak.hu) diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 20d4a33..4f730fe 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -117,7 +117,7 @@ services: image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest} environment: DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak - WORKER_TASKS: email,cleanup + WORKER_TASKS: email,cleanup,invoices # SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md); # listing them here with an empty default would override that file. SES_REGION: ${SES_REGION:-eu-central-1} diff --git a/docs/fizetes.md b/docs/fizetes.md index 49dcf92..0b7cc27 100644 --- a/docs/fizetes.md +++ b/docs/fizetes.md @@ -26,7 +26,25 @@ A sorok a fiók törlése után is megmaradnak (`user_id` → NULL), mert a szá ## Számla -Minden igazolt fizetés `invoice_status = 'pending'` állapotba kerül: ez a számlázási sor. A számlát egy háttérfeladat (worker) állítja ki a Billingo API-val, újrapróbálással (`invoice_attempts`, `invoice_error`), siker után `issued` + `invoice_number`, végleges hiba után `failed` (admin nézi meg). A Billingo-rész a cég és a Billingo-fiók után készül el; addig a sorok `pending` állapotban várnak. +Fizetéskor a backend egy `invoices` sort is létrehoz a számla minden adatával: a vevő (név, e-mail, ország, irányítószám, város, cím, Billingo-adótípus: `HAS_TAX_NUMBER` / `NO_TAX_NUMBER` / `FOREIGN`, adószám) és a tétel (név, bruttó, nettó, áfa, 27%). Cégnél a `business_name` és a magyar adószám (`hu_tin`, ennek híján `eu_vat`) kerül a számlára. + +A worker `invoices` feladata (`WORKER_TASKS`, prodon a `worker` konténerben) a Billingo API v3-mal: + +1. létrehozza a partnert (`POST /partners`), +2. kiállítja a számlát (`POST /documents`: `type=invoice`, `paid=true`, `electronic=true`, `payment_method=online_bankcard`, bruttó egységár, teljesítés = a fizetés napja magyar idő szerint), +3. e-mailben elküldi a vevőnek (`POST /documents/{id}/send`). + +Minden lépés eredményét elmenti a következő előtt, így újrapróbáláskor ott folytatja, ahol abbamaradt, és nem állít ki két számlát. A Billingo teljes válasza a `document` oszlopba kerül (a PDF nem: azt letöltéskor a backend kéri le, `GET /documents/{id}/download`). Hibánál növekvő várakozással újrapróbál (`MAX_INVOICE_ATTEMPTS`, alapból 10, kb. egy nap), utána `failed` lesz, és a `last_error` mondja meg, mi a baj. + +A felhasználó a **Számláim** oldalon (`/szamlak`; a menüpont az első számlával jelenik meg) töltheti le a számláit. + +Beállítás (`.env.secrets`, a backend és a worker is olvassa): + +``` +BILLINGO_API_KEY=... +``` + +A számlatömb alapból a fiók első számlatömbje; másikhoz `BILLINGO_BLOCK_ID` a `.env`-ben vagy a `.env.secrets`-ben. ## Beállítás @@ -56,5 +74,5 @@ Helyben a webhook nem ér el a géphez; nem is kell, mert a visszatérő oldal a ## Megnyitás előtt - A Stripe-fiók aktiválása (céges adatok, bankszámla), élő kulcsok és élő webhook. -- Számla: a worker Billingo-feladata (lásd fent). A Stripe nyugtája nem magyar számla: a Stripe felületén a Customer emails → Successful payments legyen kikapcsolva. +- Az első éles számlát nézd át a Billingóban (vevő, adószám, áfa, teljesítési dátum). A Stripe nyugtája nem magyar számla: a Stripe felületén a Customer emails → Successful payments legyen kikapcsolva. - Visszatérítés: egyelőre a Stripe felületén, a csomagot pedig az admin oldalon kell kézzel csökkenteni. diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index 996ed3b..49163c4 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -48,6 +48,10 @@ pub struct Config { /// Stripe Checkout, when `STRIPE_SECRET_KEY` is set (it wins over /// `MOCK_PAYMENTS`). pub stripe: Option, + /// `BILLINGO_API_KEY`: downloading invoices (the worker issues them). + pub billingo_api_key: Option, + /// `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, diff --git a/services/backend/src/invoices.rs b/services/backend/src/invoices.rs new file mode 100644 index 0000000..66bf59f --- /dev/null +++ b/services/backend/src/invoices.rs @@ -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, + 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, +} + +fn text(v: &Value) -> Option { + 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::>(); + 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, + buyer: &Buyer, + item_name: &str, + gross_huf: i64, +) -> Result { + 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")); + } +} diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index 56cf9e3..c0989bc 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -13,6 +13,7 @@ mod config; mod credits; mod error; mod google; +mod invoices; mod models; mod packages; mod persons; diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs index 46951f3..17c0b6d 100644 --- a/services/backend/src/routes/account.rs +++ b/services/backend/src/routes/account.rs @@ -35,6 +35,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> { 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::>(), @@ -47,6 +51,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> { "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, }))) } diff --git a/services/backend/src/routes/invoices_user.rs b/services/backend/src/routes/invoices_user.rs new file mode 100644 index 0000000..203bf26 --- /dev/null +++ b/services/backend/src/routes/invoices_user.rs @@ -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, Option, 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> { + let rows: Vec = 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 = 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 { + let row: Option<(i64, Option)> = 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::()))); + } + 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()) +} diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index f6a4fb1..fe3558d 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -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) -> 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)) diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index cfebe0a..79d76b0 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -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 { @@ -184,11 +184,11 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result { - 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(¬e)).await?) } @@ -196,7 +196,7 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result Result) - } } +async fn fake_billingo_pdf( + headers: HeaderMap, + axum::extract::Path(id): axum::extract::Path, +) -> 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, + 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")] diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index 6c399d3..051249b 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -212,6 +212,10 @@ export default async function PrivacyPage() { Stripe Payments Europe, Ltd. (Írország) – a bankkártyás fizetés lebonyolítása és a visszaélések kiszűrése; a kártyaadatokat csak a Stripe kezeli.
  • +
  • + Billingo Technologies Zrt. (Billingo) – a számlák kiállítása, megküldése és megőrzése; a + számlázási adataidat (név, cím, e-mail-cím, céges vásárlásnál cégnév és adószám) kapja meg. +
  • OpenRouter, Inc. és az általa elért mesterségesintelligencia-szolgáltatók – az elemzések megírása, kizárólag a 4. pontban leírt csillagászati adatokból (személyes adat nem jut el hozzájuk). diff --git a/services/frontend/src/app/csomagok/page.tsx b/services/frontend/src/app/csomagok/page.tsx index 4a62180..0238e33 100644 --- a/services/frontend/src/app/csomagok/page.tsx +++ b/services/frontend/src/app/csomagok/page.tsx @@ -1,4 +1,5 @@ import type { Metadata } from "next"; +import Link from "next/link"; import { AiNote } from "@/components/AiNote"; import { PackageCards } from "@/components/PackageCards"; @@ -84,6 +85,12 @@ export default async function PackagesPage() { + {me.invoice_count > 0 && ( +

    + A korábbi vásárlásaid számlái: Számláim → +

    + )} +
    diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 0770685..dbe7f75 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -957,3 +957,10 @@ a.pair-row:hover strong { color: var(--gold); } } .pay-return .msg-ok { border-color: color-mix(in srgb, var(--ok) 55%, var(--line)); } .pay-return .msg-error { border-color: color-mix(in srgb, var(--danger) 55%, var(--line)); } + +/* Számláim */ +.invoice-table th.num, .invoice-table td.num { text-align: right; } +.invoice-table td.act { text-align: right; white-space: nowrap; } +@media (max-width: 640px) { + .invoice-table th:nth-child(3), .invoice-table td:nth-child(3) { display: none; } +} diff --git a/services/frontend/src/app/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index 7571f0e..4927c32 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -211,6 +211,10 @@ export default async function PrivacyPolicyPage() { Stripe Payments Europe, Ltd. (Ireland): processing card payments and preventing fraud; only Stripe handles card details.
  • +
  • + Billingo Technologies Zrt. (Billingo): issuing, sending and keeping the invoices; it + receives your billing details (name, address, e-mail address, and for a company its name and tax number). +
  • OpenRouter, Inc. and the artificial intelligence providers it reaches: writing the readings, only from the astronomical data described in section 4 (no personal data reaches them). diff --git a/services/frontend/src/app/robots.ts b/services/frontend/src/app/robots.ts index ed6d5f6..c8348ac 100644 --- a/services/frontend/src/app/robots.ts +++ b/services/frontend/src/app/robots.ts @@ -46,7 +46,7 @@ export default async function robots(): Promise { rules: [ { userAgent: AI_CRAWLERS, disallow: "/" }, // Logged-in pages redirect anyway; shared links carry noindex. - { userAgent: "*", allow: "/", disallow: ["/api/", "/admin", "/profil", "/kepletek", "/osszevetesek", "/szemelyek"] }, + { userAgent: "*", allow: "/", disallow: ["/api/", "/admin", "/profil", "/kepletek", "/osszevetesek", "/szemelyek", "/szamlak"] }, ], }; } diff --git a/services/frontend/src/app/szamlak/page.tsx b/services/frontend/src/app/szamlak/page.tsx new file mode 100644 index 0000000..14b542c --- /dev/null +++ b/services/frontend/src/app/szamlak/page.tsx @@ -0,0 +1,77 @@ +import type { Metadata } from "next"; +import Link from "next/link"; + +import { backendGet, requireMe } from "@/lib/server"; +import type { Invoice } from "@/lib/types"; + +export const metadata: Metadata = { title: "Számláim" }; + +const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`; +const day = (iso: string) => new Date(iso).toLocaleDateString("hu-HU", { timeZone: "Europe/Budapest" }); + +/** The invoices of the user's purchases, with the PDF to download. */ +export default async function InvoicesPage() { + await requireMe("/szamlak"); + const invoices = (await backendGet<{ invoices: Invoice[] }>("/v1/invoices"))?.invoices ?? []; + + return ( +
    +
    +

    Számláim

    +

    + A vásárlásaid számlái. A számlát e-mailben is elküldjük a fizetéskor megadott címre; itt bármikor újra + letöltheted. +

    +
    + + {invoices.length === 0 ? ( +
    +

    + Még nincs számlád. Ha csomagot vásárolsz, a számlája itt jelenik meg. Csomagok → +

    +
    + ) : ( +
    +
    + + + + + + + + + + + + {invoices.map((inv) => ( + + + + + + + + ))} + +
    DátumSzámlaszámTételÖsszeg + Letöltés +
    {day(inv.invoice_date ?? inv.paid_at)}{inv.invoice_number ?? "–"}{inv.item}{huf(inv.gross_huf)} + {inv.ready ? ( + + PDF letöltése + + ) : ( + Készül… + )} +
    +
    +

    + A számlákat a Billingo állítja ki. Ha egy számla adatai hibásak (például a cégnév vagy az adószám), írj nekünk, + és helyesbítjük. +

    +
    + )} +
    + ); +} diff --git a/services/frontend/src/components/SiteHeader.tsx b/services/frontend/src/components/SiteHeader.tsx index 34ed12a..86d1a63 100644 --- a/services/frontend/src/components/SiteHeader.tsx +++ b/services/frontend/src/components/SiteHeader.tsx @@ -90,6 +90,7 @@ export function SiteHeader({ me }: { me: Me }) { { href: "/szemelyek", label: "Személyek" }, { href: "/osszevetesek", label: "Összevetések" }, { href: "/csomagok", label: "Csomagok" }, + ...(me.invoice_count > 0 ? [{ href: "/szamlak", label: "Számláim" }] : []), { href: "/profil", label: "Profil" }, ]; if (me.user.roles.includes("admin")) links.push({ href: "/admin", label: "Admin" }); diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index bb1559b..19ca01e 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -23,6 +23,8 @@ export interface Me { package: { id: string; name: string; since: string } | null; /** The free question for a shared link is used up (once per user). */ share_reward_granted: boolean; + /** Invoices of the user's payments (the "Számláim" menu shows from the first). */ + invoice_count: number; /** Natal analyses earned by bringing new users through shared links. */ referral_rewards: { earned: number; limit: number }; } @@ -582,3 +584,14 @@ export interface PersonInviteLanding { /** How this user can buy a package; `null`: purchases are off. */ export type PayMethod = "stripe" | "stripe_test" | "mock"; + +export interface Invoice { + id: string; + /** Issued in Billingo: the PDF can be downloaded. */ + ready: boolean; + invoice_number: string | null; + invoice_date: string | null; + item: string; + gross_huf: number; + paid_at: string; +} diff --git a/services/worker/src/config.rs b/services/worker/src/config.rs index 27030cb..30caa2a 100644 --- a/services/worker/src/config.rs +++ b/services/worker/src/config.rs @@ -14,22 +14,26 @@ pub struct Tasks { pub cleanup: bool, /// Writing the analyses and answers with the LLM (both lanes). pub analyses: bool, + /// Issuing the invoices of the payments in Billingo. + pub invoices: bool, } impl Tasks { - pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true }; + pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true, invoices: true }; + const NONE: Tasks = Tasks { email: false, cleanup: false, analyses: false, invoices: false }; pub fn parse(raw: &str) -> anyhow::Result { - let mut tasks = Tasks { email: false, cleanup: false, analyses: false }; + let mut tasks = Self::NONE; for name in raw.split(',').map(str::trim).filter(|n| !n.is_empty()) { match name { "email" => tasks.email = true, "cleanup" => tasks.cleanup = true, "analyses" => tasks.analyses = true, - other => anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses)"), + "invoices" => tasks.invoices = true, + other => anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices)"), } } - anyhow::ensure!(tasks != Tasks { email: false, cleanup: false, analyses: false }, "WORKER_TASKS names no task"); + anyhow::ensure!(tasks != Self::NONE, "WORKER_TASKS names no task"); Ok(tasks) } } @@ -61,6 +65,15 @@ pub struct Config { pub quick_concurrency: usize, /// After this many failed attempts an analysis fails and is refunded. pub max_analysis_attempts: i32, + /// `BILLINGO_API_KEY`; unset: invoices stay pending. + pub billingo_api_key: Option, + /// `BILLINGO_API_URL` (default `https://api.billingo.hu/v3`). + pub billingo_api_url: String, + /// `BILLINGO_BLOCK_ID`: the invoice pad (default: the account's first one). + pub billingo_block_id: Option, + /// `MAX_INVOICE_ATTEMPTS` (default 10, about a day with the backoff): + /// then the invoice is marked failed for an admin. + pub max_invoice_attempts: i32, } fn var(name: &str) -> Option { @@ -103,6 +116,13 @@ impl Config { analysis_concurrency: parsed("ANALYSIS_CONCURRENCY", 4)?, quick_concurrency: parsed("QUICK_CONCURRENCY", 2)?, max_analysis_attempts: parsed("MAX_ANALYSIS_ATTEMPTS", 3)?, + billingo_api_key: var("BILLINGO_API_KEY"), + billingo_api_url: var("BILLINGO_API_URL").unwrap_or_else(|| crate::invoices::DEFAULT_BASE_URL.into()), + billingo_block_id: var("BILLINGO_BLOCK_ID") + .map(|v| v.parse()) + .transpose() + .context("invalid BILLINGO_BLOCK_ID")?, + max_invoice_attempts: parsed("MAX_INVOICE_ATTEMPTS", 10)?, }) } } diff --git a/services/worker/src/invoices.rs b/services/worker/src/invoices.rs new file mode 100644 index 0000000..5fc8300 --- /dev/null +++ b/services/worker/src/invoices.rs @@ -0,0 +1,489 @@ +//! Issuing the invoices of the Stripe payments in Billingo (API v3). +//! +//! The backend queues one `invoices` row per paid checkout, with the buyer and +//! 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). + +use std::time::Duration; + +use serde_json::{Value, json}; +use sqlx::PgPool; +use time::{Date, Month, OffsetDateTime, UtcOffset, Weekday}; +use tokio::sync::{Mutex, watch}; +use uuid::Uuid; + +use crate::email::backoff; + +pub const DEFAULT_BASE_URL: &str = "https://api.billingo.hu/v3"; +/// How long a claimed invoice is left alone (a crashed worker's row comes back). +const LEASE: &str = "10 minutes"; + +pub struct Billingo { + http: reqwest::Client, + base: String, + key: String, + /// The invoice pad (`BILLINGO_BLOCK_ID`, or the account's first invoice pad). + block: Mutex>, +} + +impl Billingo { + pub fn new(base: &str, key: &str, block: Option) -> Self { + let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("static configuration"); + Self { http, base: base.trim_end_matches('/').to_owned(), key: key.to_owned(), block: Mutex::new(block) } + } + + async fn call(&self, method: reqwest::Method, path: &str, body: Option<&Value>) -> Result { + let mut req = self + .http + .request(method.clone(), format!("{}{path}", self.base)) + .header("X-API-KEY", &self.key) + .header("Accept", "application/json"); + if let Some(body) = body { + req = req.json(body); + } + let res = req.send().await.map_err(|e| format!("{method} {path}: {e}"))?; + let status = res.status(); + let text = res.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(format!("{method} {path}: HTTP {status}: {}", text.chars().take(500).collect::())); + } + if text.trim().is_empty() { + return Ok(Value::Null); + } + serde_json::from_str(&text).map_err(|e| format!("{method} {path}: not JSON: {e}")) + } + + async fn block(&self) -> Result { + let mut block = self.block.lock().await; + if let Some(id) = *block { + return Ok(id); + } + let list = self.call(reqwest::Method::GET, "/document-blocks?type=invoice&per_page=100", None).await?; + let id = list["data"] + .as_array() + .and_then(|pads| pads.iter().find(|p| p["type"] == "invoice" || p["type"].is_null())) + .and_then(|p| p["id"].as_i64()) + .ok_or("Billingo has no invoice pad (document block); set BILLINGO_BLOCK_ID")?; + *block = Some(id); + Ok(id) + } +} + +#[derive(sqlx::FromRow)] +struct Due { + id: Uuid, + attempts: i32, + buyer_name: String, + buyer_email: Option, + buyer_country: String, + buyer_post_code: String, + buyer_city: String, + buyer_address: String, + buyer_tax_type: String, + buyer_tax_number: Option, + item_name: String, + gross_huf: i32, + vat_rate: String, + payment_method: String, + billingo_partner_id: Option, + billingo_document_id: Option, + sent_at: Option, + paid_at: OffsetDateTime, +} + +/// The date in Hungary (CET, CEST from the last Sunday of March to the last +/// Sunday of October, 01:00 UTC): the invoice's fulfilment date. +pub fn hungarian_date(t: OffsetDateTime) -> Date { + let last_sunday = |month| { + let mut d = Date::from_calendar_date(t.year(), month, 31).expect("March and October have 31 days"); + while d.weekday() != Weekday::Sunday { + d = d.previous_day().expect("not the first day"); + } + d.with_hms(1, 0, 0).expect("valid time").assume_utc() + }; + let summer = t >= last_sunday(Month::March) && t < last_sunday(Month::October); + t.to_offset(UtcOffset::from_hms(if summer { 2 } else { 1 }, 0, 0).expect("valid offset")).date() +} + +/// A `YYYY-MM-DD…` value of Billingo's answer. +fn date(v: &Value) -> Option { + let s = v.as_str()?.get(..10)?; + let mut parts = s.split('-'); + let year = parts.next()?.parse().ok()?; + let month = Month::try_from(parts.next()?.parse::().ok()?).ok()?; + Date::from_calendar_date(year, month, parts.next()?.parse().ok()?).ok() +} + +/// Issues the due invoices; returns how many were finished. +pub async fn run_once(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Result { + let mut done = 0; + loop { + let due: Option = sqlx::query_as(&format!( + "UPDATE invoices i SET attempts = i.attempts + 1, next_attempt_at = now() + interval '{LEASE}' \ + FROM stripe_checkouts c \ + WHERE c.id = i.checkout_id AND i.id = (SELECT id FROM invoices WHERE status = 'pending' \ + 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.gross_huf, \ + i.vat_rate, i.payment_method, i.billingo_partner_id, i.billingo_document_id, i.sent_at, \ + coalesce(c.completed_at, i.created_at) AS paid_at" + )) + .fetch_optional(db) + .await?; + let Some(due) = due else { return Ok(done) }; + match issue(db, billingo, &due).await { + Ok(number) => { + tracing::info!(invoice = %due.id, number = %number, "invoice issued"); + done += 1; + } + 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?; + done += 1; + } + Err(Failure::Billingo(error)) => { + let wait = backoff(due.attempts); + tracing::warn!(invoice = %due.id, %error, retry_in = ?wait, "invoice not issued yet"); + sqlx::query( + "UPDATE invoices SET 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?; + } + } + } +} + +enum Failure { + Billingo(String), + Db(sqlx::Error), +} + +impl From for Failure { + fn from(e: sqlx::Error) -> Self { + Failure::Db(e) + } +} + +impl From for Failure { + fn from(e: String) -> Self { + Failure::Billingo(e) + } +} + +impl From<&str> for Failure { + fn from(e: &str) -> Self { + Failure::Billingo(e.to_owned()) + } +} + +/// Partner, invoice, e-mail: whatever is still missing. Returns the number. +async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result { + use reqwest::Method; + + let partner = match due.billingo_partner_id { + Some(id) => id, + None => { + let body = json!({ + "name": due.buyer_name, + "address": { + "country_code": due.buyer_country, + "post_code": due.buyer_post_code, + "city": due.buyer_city, + "address": due.buyer_address, + }, + "emails": due.buyer_email.iter().collect::>(), + "taxcode": due.buyer_tax_number.clone().unwrap_or_default(), + "tax_type": due.buyer_tax_type, + }); + let partner = billingo.call(Method::POST, "/partners", Some(&body)).await?; + let id = partner["id"].as_i64().ok_or("Billingo partner without id")?; + sqlx::query("UPDATE invoices SET billingo_partner_id = $2 WHERE id = $1") + .bind(due.id) + .bind(id) + .execute(db) + .await?; + id + } + }; + + let document = match due.billingo_document_id { + Some(id) => id, + None => { + let day = hungarian_date(due.paid_at).to_string(); + let body = json!({ + "partner_id": partner, + "block_id": billingo.block().await?, + "type": "invoice", + "fulfillment_date": day, + "due_date": day, + "payment_method": due.payment_method, + "language": "hu", + "currency": "HUF", + "electronic": true, + "paid": true, + "items": [{ + "name": due.item_name, + "unit_price": due.gross_huf, + "unit_price_type": "gross", + "quantity": 1, + "unit": "db", + "vat": due.vat_rate, + }], + "comment": "Bankkártyával kifizetve (Stripe).", + }); + let doc = 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( + "UPDATE invoices SET billingo_document_id = $2, invoice_number = $3, invoice_date = $4, \ + fulfillment_date = $5, due_date = $6, document = $7, \ + net_huf = coalesce($8, net_huf), vat_huf = coalesce($9, vat_huf) WHERE id = $1", + ) + .bind(due.id) + .bind(id) + .bind(doc["invoice_number"].as_str()) + .bind(date(&doc["invoice_date"])) + .bind(date(&doc["fulfillment_date"])) + .bind(date(&doc["due_date"])) + .bind(&doc) + .bind(item["net_amount"].as_f64().map(|n| n.round() as i32)) + .bind(item["vat_amount"].as_f64().map(|n| n.round() as i32)) + .execute(db) + .await?; + id + } + }; + + if due.sent_at.is_none() + && let Some(email) = &due.buyer_email + { + let body = json!({ "emails": [email] }); + billingo.call(Method::POST, &format!("/documents/{document}/send"), Some(&body)).await?; + sqlx::query("UPDATE invoices SET sent_at = now() WHERE id = $1").bind(due.id).execute(db).await?; + } + + let (number,): (Option,) = sqlx::query_as( + "UPDATE invoices SET status = 'issued', issued_at = now(), last_error = NULL WHERE id = $1 \ + RETURNING invoice_number", + ) + .bind(due.id) + .fetch_one(db) + .await?; + Ok(number.unwrap_or_default()) +} + +pub async fn run(db: PgPool, billingo: Billingo, max_attempts: i32, interval: Duration, stop: watch::Receiver) { + loop { + if let Err(e) = run_once(&db, &billingo, max_attempts).await { + tracing::error!(error = %e, "invoices"); + } + tokio::select! { + () = tokio::time::sleep(interval) => {} + () = crate::stopped(stop.clone()) => break, + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + use axum::extract::{Path, State}; + use axum::http::StatusCode; + use axum::routing::{get, post}; + use axum::{Json, Router}; + + fn at(s: &str) -> OffsetDateTime { + OffsetDateTime::parse(s, &time::format_description::well_known::Rfc3339).unwrap() + } + + #[test] + fn fulfilment_dates_are_hungarian() { + // 23:30 UTC is already the next day in Budapest, in winter and summer. + assert_eq!(hungarian_date(at("2026-11-20T23:30:00Z")).to_string(), "2026-11-21"); + assert_eq!(hungarian_date(at("2026-11-20T22:59:00Z")).to_string(), "2026-11-20"); + assert_eq!(hungarian_date(at("2026-07-01T22:30:00Z")).to_string(), "2026-07-02"); + assert_eq!(hungarian_date(at("2026-07-01T21:59:00Z")).to_string(), "2026-07-01"); + assert_eq!(date(&json!("2026-11-21T00:00:00+01:00")).unwrap().to_string(), "2026-11-21"); + } + + #[derive(Default)] + struct Fake { + requests: std::sync::Mutex>, + documents: AtomicUsize, + /// Sending fails this many times first. + send_failures: AtomicUsize, + /// Partners are refused (a permanent error). + refuse_partners: std::sync::atomic::AtomicBool, + } + + async fn fake_billingo(fake: Arc) -> String { + async fn blocks(State(f): State>) -> Json { + f.requests.lock().unwrap().push(("blocks".into(), Value::Null)); + Json(json!({"data": [{"id": 5, "name": "Számlák", "type": "invoice"}], "total": 1})) + } + async fn partner(State(f): State>, Json(body): Json) -> (StatusCode, Json) { + f.requests.lock().unwrap().push(("partner".into(), body.clone())); + if f.refuse_partners.load(Ordering::SeqCst) { + return (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({"message": "invalid tax code"}))); + } + (StatusCode::CREATED, Json(json!({"id": 42, "name": body["name"]}))) + } + async fn document(State(f): State>, Json(body): Json) -> (StatusCode, Json) { + 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": 4724.41, "vat_amount": 1275.59, "gross_amount": 6000.0}]})), + ) + } + async fn send( + State(f): State>, + Path(id): Path, + Json(body): Json, + ) -> (StatusCode, Json) { + f.requests.lock().unwrap().push((format!("send {id}"), body.clone())); + if f.send_failures.load(Ordering::SeqCst) > 0 { + f.send_failures.fetch_sub(1, Ordering::SeqCst); + return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "mail down"}))); + } + (StatusCode::OK, Json(body)) + } + let app = Router::new() + .route("/document-blocks", get(blocks)) + .route("/partners", post(partner)) + .route("/documents", post(document)) + .route("/documents/{id}/send", post(send)) + .with_state(fake); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + async fn paid(db: &PgPool, tax: Option<&str>) -> Uuid { + let checkout = format!("cs_{}", Uuid::now_v7()); + sqlx::query( + "INSERT INTO stripe_checkouts (id, package, price_huf, live, completed_at) \ + VALUES ($1, 'couple', 6000, false, '2026-11-20T23:30:00Z')", + ) + .bind(&checkout) + .execute(db) + .await + .unwrap(); + let id = Uuid::now_v7(); + sqlx::query( + "INSERT INTO invoices (id, checkout_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) \ + VALUES ($1, $2, 'Csillag Kft.', 'anna@example.com', 'HU', '6720', 'Szeged', 'Fő utca 1.', $3, $4, \ + 'Sorsfonalak – Páros', 6000, 4724, 1276)", + ) + .bind(id) + .bind(&checkout) + .bind(if tax.is_some() { "HAS_TAX_NUMBER" } else { "NO_TAX_NUMBER" }) + .bind(tax) + .execute(db) + .await + .unwrap(); + id + } + + async fn state(db: &PgPool, id: Uuid) -> (String, Option, Option, bool, i32) { + sqlx::query_as( + "SELECT status, invoice_number, billingo_document_id, sent_at IS NOT NULL, attempts FROM invoices \ + WHERE id = $1", + ) + .bind(id) + .fetch_one(db) + .await + .unwrap() + } + + #[sqlx::test(migrator = "db::MIGRATOR")] + async fn invoices_are_issued_and_sent_once(db: PgPool) { + let fake = Arc::new(Fake::default()); + let billingo = Billingo::new(&fake_billingo(fake.clone()).await, "key", None); + let id = paid(&db, Some("12345678-1-23")).await; + fake.send_failures.store(1, Ordering::SeqCst); + + // The invoice is made, but the e-mail fails: it is retried later. + assert_eq!(run_once(&db, &billingo, 5).await.unwrap(), 0); + let (status, number, document, sent, attempts) = state(&db, id).await; + assert_eq!( + (status.as_str(), number.as_deref(), document, sent, attempts), + ("pending", Some("SF-2026-1"), Some(901), false, 1) + ); + { + let requests = fake.requests.lock().unwrap(); + let partner = &requests.iter().find(|(k, _)| k == "partner").unwrap().1; + assert_eq!(partner["taxcode"], "12345678-1-23"); + assert_eq!(partner["tax_type"], "HAS_TAX_NUMBER"); + assert_eq!(partner["address"]["post_code"], "6720"); + let doc = &requests.iter().find(|(k, _)| k == "document").unwrap().1; + assert_eq!((&doc["partner_id"], &doc["block_id"]), (&json!(42), &json!(5))); + assert_eq!( + (&doc["paid"], &doc["payment_method"], &doc["currency"]), + (&json!(true), &json!("online_bankcard"), &json!("HUF")) + ); + assert_eq!(doc["items"][0]["unit_price"], 6000); + assert_eq!( + (&doc["items"][0]["unit_price_type"], &doc["items"][0]["vat"]), + (&json!("gross"), &json!("27%")) + ); + // Paid at 00:30 in Budapest. + assert_eq!(doc["fulfillment_date"], "2026-11-21"); + } + // Not before its time. + assert_eq!(run_once(&db, &billingo, 5).await.unwrap(), 0); + 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, _, _, sent, _) = state(&db, id).await; + assert_eq!((status.as_str(), sent), ("issued", true)); + // One partner and one invoice, even with the retry. + assert_eq!(fake.documents.load(Ordering::SeqCst), 1); + let (net, vat, kept): (i32, i32, Value) = + sqlx::query_as("SELECT net_huf, vat_huf, document FROM invoices WHERE id = $1") + .bind(id) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!((net, vat, &kept["invoice_number"]), (4724, 1276, &json!("SF-2026-1"))); + assert_eq!(run_once(&db, &billingo, 5).await.unwrap(), 0); + } + + #[sqlx::test(migrator = "db::MIGRATOR")] + async fn invoices_fail_after_the_last_attempt(db: PgPool) { + let fake = Arc::new(Fake::default()); + fake.refuse_partners.store(true, 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, ..) = state(&db, id).await; + assert_eq!(status, "failed"); + let (error,): (String,) = + sqlx::query_as("SELECT last_error FROM invoices WHERE id = $1").bind(id).fetch_one(&db).await.unwrap(); + assert!(error.contains("422") && error.contains("invalid tax code"), "{error}"); + assert_eq!(fake.documents.load(Ordering::SeqCst), 0); + } +} diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 9594684..506febe 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -4,6 +4,7 @@ //! * e-mail delivery from `email_outbox` over SMTP (Mailpit in development) //! * hourly cleanup of expired sessions, tokens, invites and old e-mails //! * writing the requested text analyses with an LLM (OpenRouter) +//! * issuing the invoices of the payments in Billingo //! //! `WORKER_TASKS` (e.g. `email,cleanup` or `analyses`) picks the jobs of one //! process, so they can run in separate containers; all of them by default. @@ -18,6 +19,7 @@ mod cleanup; mod compare; mod config; mod email; +mod invoices; mod ses; mod templates { pub use email_templates::*; @@ -95,7 +97,13 @@ async fn main() -> anyhow::Result<()> { let (stop_tx, stop) = watch::channel(false); let mut jobs = tokio::task::JoinSet::new(); let tasks = config.tasks; - tracing::info!(email = tasks.email, cleanup = tasks.cleanup, analyses = tasks.analyses, "worker tasks"); + tracing::info!( + email = tasks.email, + cleanup = tasks.cleanup, + analyses = tasks.analyses, + invoices = tasks.invoices, + "worker tasks" + ); match &config.smtp_url { _ if !tasks.email => {} Some(url) => { @@ -125,6 +133,21 @@ async fn main() -> anyhow::Result<()> { if tasks.cleanup { jobs.spawn(cleanup::run(pool.clone(), stop.clone())); } + match &config.billingo_api_key { + _ if !tasks.invoices => {} + Some(key) => { + let billingo = invoices::Billingo::new(&config.billingo_api_url, key, config.billingo_block_id); + tracing::info!("invoicing enabled (Billingo)"); + jobs.spawn(invoices::run( + pool.clone(), + billingo, + config.max_invoice_attempts, + config.poll_interval, + stop.clone(), + )); + } + None => tracing::warn!("BILLINGO_API_KEY is not set: invoices stay pending"), + } let app = Router::new().route("/healthz", get(healthz)).with_state(pool); let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?; diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs index 7581279..90e4504 100644 --- a/services/worker/src/tests.rs +++ b/services/worker/src/tests.rs @@ -227,8 +227,12 @@ async fn cleanup_removes_only_expired_data(db: PgPool) { fn worker_tasks_are_chosen_by_name() { use crate::config::Tasks; let mail = Tasks::parse("email, cleanup").unwrap(); - assert_eq!(mail, Tasks { email: true, cleanup: true, analyses: false }); - assert_eq!(Tasks::parse("analyses").unwrap(), Tasks { email: false, cleanup: false, analyses: true }); + assert_eq!(mail, Tasks { email: true, cleanup: true, analyses: false, invoices: false }); + assert_eq!( + Tasks::parse("analyses").unwrap(), + Tasks { email: false, cleanup: false, analyses: true, invoices: false } + ); + assert!(Tasks::parse("email,invoices").unwrap().invoices); assert!(Tasks::parse("emails").is_err()); assert!(Tasks::parse(" , ").is_err()); } From 4338a352029dfc8696d97f21d2c36ea7f2ab544a Mon Sep 17 00:00:00 2001 From: feco Date: Fri, 20 Nov 2026 08:03:04 +0000 Subject: [PATCH 3/3] =?UTF-8?q?Invoices:=20alanyi=20ad=C3=B3mentes=20(AAM)?= =?UTF-8?q?=20by=20default?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit INVOICE_VAT picks the VAT of the invoices: AAM (no VAT, net = gross, the invoice says so) or a rate like 27% once the exemption limit is passed. The packages page tells which. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- .../db/migrations/0027_stripe_checkouts.sql | 5 +- deploy/docker-compose.yml | 2 + docker-compose.yml | 2 + docs/csomagok.md | 2 +- docs/fizetes.md | 2 +- services/backend/src/config.rs | 8 +++ services/backend/src/invoices.rs | 63 ++++++++++++++----- services/backend/src/packages.rs | 2 +- services/backend/src/routes/mod.rs | 2 + services/backend/src/routes/payments.rs | 3 +- services/backend/src/tests.rs | 4 +- services/frontend/src/app/csomagok/page.tsx | 6 +- services/frontend/src/lib/types.ts | 2 + services/worker/src/invoices.rs | 14 +++-- 14 files changed, 90 insertions(+), 27 deletions(-) diff --git a/crates/db/migrations/0027_stripe_checkouts.sql b/crates/db/migrations/0027_stripe_checkouts.sql index c26c0ff..bd5e4b0 100644 --- a/crates/db/migrations/0027_stripe_checkouts.sql +++ b/crates/db/migrations/0027_stripe_checkouts.sql @@ -48,12 +48,13 @@ CREATE TABLE invoices ( -- Billingo's partner tax type: HAS_TAX_NUMBER, NO_TAX_NUMBER or FOREIGN. buyer_tax_type text NOT NULL CHECK (buyer_tax_type IN ('HAS_TAX_NUMBER', 'NO_TAX_NUMBER', 'FOREIGN')), buyer_tax_number text, - -- The single item, gross price with 27% VAT. + -- The single item. vat_rate is Billingo's VAT value: AAM (alanyi + -- adómentes: net = gross, no VAT) or a rate like 27%. item_name text NOT NULL, gross_huf integer NOT NULL CHECK (gross_huf > 0), net_huf integer NOT NULL, vat_huf integer NOT NULL, - vat_rate text NOT NULL DEFAULT '27%', + vat_rate text NOT NULL DEFAULT 'AAM', payment_method text NOT NULL DEFAULT 'online_bankcard', -- From Billingo. billingo_partner_id bigint, diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 4f730fe..e2d30d2 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -91,6 +91,8 @@ services: # Stripe purchases for everyone (false: admins only, until the opening; # with a test key always admins only). PURCHASES_OPEN: ${PURCHASES_OPEN:-false} + # VAT on the invoices: AAM (alanyi adómentes) or a rate like 27%. + INVOICE_VAT: ${INVOICE_VAT:-AAM} # Users inviting others ("Meghívom"): shown but off until the launch. USER_INVITES: ${USER_INVITES:-false} # A new user from a shared link earns the sharer an analysis: off until sign-up opens. diff --git a/docker-compose.yml b/docker-compose.yml index 43267c0..f19fd64 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -58,6 +58,8 @@ services: # Stripe purchases for everyone (false: admins only, until the opening; # with a test key always admins only). PURCHASES_OPEN: ${PURCHASES_OPEN:-false} + # VAT on the invoices: AAM (alanyi adómentes) or a rate like 27%. + INVOICE_VAT: ${INVOICE_VAT:-AAM} FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0} # invite: new accounts need an invitation (admin page "Meghívók"); open: anyone. SIGNUP_MODE: ${SIGNUP_MODE:-invite} diff --git a/docs/csomagok.md b/docs/csomagok.md index 71b7afe..1eaddc2 100644 --- a/docs/csomagok.md +++ b/docs/csomagok.md @@ -4,7 +4,7 @@ A katalógus a kódban van: `services/backend/src/packages.rs` (`CATALOG`). Ár- ## Költség -Egy részletes képletelemzés és egy kapcsolati elemzés is kb. **$0,21 (≈ 80 Ft)** Opus 5.5-tel, az éves előrejelzés a hosszabb adatsor miatt valamivel több; a rövid összefoglaló kb. $0,01. A fizetési szolgáltató díja kb. 1,5% + 85 Ft tranzakciónként. Az árak bruttók (27% áfa). +Egy részletes képletelemzés és egy kapcsolati elemzés is kb. **$0,21 (≈ 80 Ft)** Opus 5.5-tel, az éves előrejelzés a hosszabb adatsor miatt valamivel több; a rövid összefoglaló kb. $0,01. A fizetési szolgáltató díja kb. 1,5% + 85 Ft tranzakciónként. Az árak végső árak: alanyi adómentesek vagyunk (`INVOICE_VAT=AAM`), áfát nem számítunk fel; ha átlépjük az alanyi adómentesség határát, `INVOICE_VAT=27%`, és az árak bruttóként értendők. ## A lépcső diff --git a/docs/fizetes.md b/docs/fizetes.md index 0b7cc27..a21e9e6 100644 --- a/docs/fizetes.md +++ b/docs/fizetes.md @@ -26,7 +26,7 @@ A sorok a fiók törlése után is megmaradnak (`user_id` → NULL), mert a szá ## Számla -Fizetéskor a backend egy `invoices` sort is létrehoz a számla minden adatával: a vevő (név, e-mail, ország, irányítószám, város, cím, Billingo-adótípus: `HAS_TAX_NUMBER` / `NO_TAX_NUMBER` / `FOREIGN`, adószám) és a tétel (név, bruttó, nettó, áfa, 27%). Cégnél a `business_name` és a magyar adószám (`hu_tin`, ennek híján `eu_vat`) kerül a számlára. +Fizetéskor a backend egy `invoices` sort is létrehoz a számla minden adatával: a vevő (név, e-mail, ország, irányítószám, város, cím, Billingo-adótípus: `HAS_TAX_NUMBER` / `NO_TAX_NUMBER` / `FOREIGN`, adószám) és a tétel (név, végösszeg, nettó, áfa, áfakód). Az áfakód az `INVOICE_VAT` (a backend `.env`-je): alapból `AAM` (alanyi adómentes: nettó = végösszeg, áfa 0, a számla megjegyzésében „Alanyi adómentes.”), vagy egy kulcs, pl. `27%`. Cégnél a `business_name` és a magyar adószám (`hu_tin`, ennek híján `eu_vat`) kerül a számlára. A worker `invoices` feladata (`WORKER_TASKS`, prodon a `worker` konténerben) a Billingo API v3-mal: diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index 49163c4..1c76bb1 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -48,6 +48,8 @@ pub struct Config { /// Stripe Checkout, when `STRIPE_SECRET_KEY` is set (it wins over /// `MOCK_PAYMENTS`). pub stripe: Option, + /// `INVOICE_VAT` (default `AAM`, alanyi adómentes; or e.g. `27%`). + pub invoice_vat: crate::invoices::Vat, /// `BILLINGO_API_KEY`: downloading invoices (the worker issues them). pub billingo_api_key: Option, /// `BILLINGO_API_URL` (default `https://api.billingo.hu/v3`). @@ -174,6 +176,11 @@ impl Config { .trim_end_matches('/') .to_string(), }), + invoice_vat: match var("INVOICE_VAT") { + None => crate::invoices::Vat::Exempt, + Some(raw) => crate::invoices::Vat::parse(&raw) + .with_context(|| format!("invalid INVOICE_VAT '{raw}': use AAM or a rate like 27%"))?, + }, billingo_api_key: var("BILLINGO_API_KEY"), billingo_api_url: var("BILLINGO_API_URL") .unwrap_or_else(|| "https://api.billingo.hu/v3".into()) @@ -220,6 +227,7 @@ impl Config { password_login: true, mock_payments: true, stripe: None, + invoice_vat: crate::invoices::Vat::Exempt, billingo_api_key: Some("billingo-fake".into()), billingo_api_url: format!("{horoscope_api_url}/billingo"), purchases_open: true, diff --git a/services/backend/src/invoices.rs b/services/backend/src/invoices.rs index 66bf59f..ccba08d 100644 --- a/services/backend/src/invoices.rs +++ b/services/backend/src/invoices.rs @@ -9,8 +9,41 @@ use uuid::Uuid; use crate::error::ApiError; -/// VAT of every package, in percent. -pub const VAT_PERCENT: i64 = 27; +/// The VAT on the invoices (`INVOICE_VAT`): `AAM` (alanyi adómentes, subject +/// to the small business exemption: no VAT, net = gross) or a rate like `27%`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Vat { + Exempt, + Percent(i64), +} + +impl Vat { + pub fn parse(raw: &str) -> Option { + match raw.trim() { + "AAM" => Some(Vat::Exempt), + rate => rate.strip_suffix('%')?.trim().parse().ok().filter(|p| (1..=27).contains(p)).map(Vat::Percent), + } + } + + /// Billingo's VAT value. + pub fn code(self) -> String { + match self { + Vat::Exempt => "AAM".into(), + Vat::Percent(p) => format!("{p}%"), + } + } + + /// Net and VAT parts of a gross price (rounded to forints, as Billingo does). + pub fn split(self, gross: i64) -> (i64, i64) { + match self { + Vat::Exempt => (gross, 0), + Vat::Percent(p) => { + let net = (gross * 200 + 100 + p) / (200 + 2 * p); + (net, gross - net) + } + } + } +} /// The buyer as invoiced, from Stripe's `customer_details`. #[derive(Debug, PartialEq, Eq)] @@ -61,12 +94,6 @@ impl Buyer { } } -/// 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, @@ -75,9 +102,10 @@ pub async fn queue( buyer: &Buyer, item_name: &str, gross_huf: i64, + vat: Vat, ) -> Result { let id = Uuid::now_v7(); - let (net, vat) = split_gross(gross_huf); + let (net, vat_huf) = vat.split(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) \ @@ -98,8 +126,8 @@ pub async fn queue( .bind(item_name) .bind(gross_huf as i32) .bind(net as i32) - .bind(vat as i32) - .bind(format!("{VAT_PERCENT}%")) + .bind(vat_huf as i32) + .bind(vat.code()) .execute(&mut *tx) .await?; Ok(id) @@ -113,9 +141,16 @@ mod tests { #[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)); + let vat = Vat::parse("27%").unwrap(); + assert_eq!(vat.split(2000), (1575, 425)); + assert_eq!(vat.split(6000), (4724, 1276)); + assert_eq!(vat.split(127), (100, 27)); + assert_eq!(vat.code(), "27%"); + // Alanyi adómentes: no VAT at all. + assert_eq!(Vat::parse("AAM"), Some(Vat::Exempt)); + assert_eq!(Vat::Exempt.split(6000), (6000, 0)); + assert_eq!(Vat::parse("huszonhét"), None); + assert_eq!(Vat::parse("99%"), None); } #[test] diff --git a/services/backend/src/packages.rs b/services/backend/src/packages.rs index 8511eec..91f1341 100644 --- a/services/backend/src/packages.rs +++ b/services/backend/src/packages.rs @@ -37,7 +37,7 @@ pub struct Package { pub name: &'static str, pub tagline: &'static str, pub tier: Tier, - /// Gross price (27% VAT included). + /// The price paid (with VAT if `INVOICE_VAT` is a rate; none under AAM). pub price_huf: i64, pub natal: i64, pub synastry: i64, diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index fe3558d..64381c4 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -173,6 +173,8 @@ async fn public_config(State(state): St) -> Json { "payments": payments::method(c), "payments_admins_only": payments::admins_only(c), "payments_test": c.stripe.as_ref().is_some_and(|s| s.test_mode()), + // "AAM" (alanyi adómentes: the prices carry no VAT) or a rate like "27%". + "vat": c.invoice_vat.code(), "user_invites": c.user_invites, "referral_rewards": c.referral_rewards, "signup_mode": c.signup_mode.as_str(), diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index 79d76b0..e53d602 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -207,7 +207,8 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result ))} -

    Az árak bruttó árak, az áfát tartalmazzák.

    +

    + {config?.vat === "AAM" || !config + ? "Az árak végső árak: alanyi adómentesek vagyunk, áfát nem számítunk fel." + : `Az árak bruttó árak, a ${config.vat} áfát tartalmazzák.`} +

    ); diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index 19ca01e..aa5b334 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -100,6 +100,8 @@ export interface PublicConfig { payments_admins_only: boolean; /** Stripe has a test key (test cards work, no real money). */ payments_test: boolean; + /** "AAM": alanyi adómentes, the prices carry no VAT; otherwise the rate, e.g. "27%". */ + vat: string; /** "invite": new accounts need an invitation. */ signup_mode: "invite" | "open"; /** Users may invite others (off until the launch; admins always may). */ diff --git a/services/worker/src/invoices.rs b/services/worker/src/invoices.rs index 5fc8300..e263a39 100644 --- a/services/worker/src/invoices.rs +++ b/services/worker/src/invoices.rs @@ -243,7 +243,11 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result