Compare commits

..
Author SHA1 Message Date
fecoandClaude Opus 5.5 71177f749c Merge main into prod: invoice test payments, admins use units
CI / test (push) Successful in 1m26s
CI / build (push) Successful in 22s
CI / deploy (push) Successful in 52s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 10:59:17 +00:00
fecoandClaude Opus 5.5 ac5e7fa4fd Admins use analysis units and questions too
CI / test (push) Successful in 1m41s
CI / build (push) Successful in 5m52s
CI / deploy (push) Skipped
They add their own units on the admin page when they need more, and
testing shows the same balance as users see. Regenerating and prompt
previews stay free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 10:54:24 +00:00
sagifer bbfa5b28c3 Merge pull request 'Invoice every payment again, test payments included' (#29) from main into prod
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 1m50s
CI / deploy (push) Successful in 55s
Reviewed-on: #29
2026-11-20 11:09:30 +01:00
fecoandClaude Opus 5.5 e741f9b491 Invoice every payment again, test payments included
CI / test (push) Successful in 1m27s
CI / build (push) Successful in 4m36s
CI / deploy (push) Skipped
The Billingo account is a test one for now, and the whole flow is being
tested; skipping test payments was not asked for. Stripe and Billingo
go live together at the opening.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 10:00:48 +00:00
fecoandClaude Opus 5.5 ba11eda64c Merge main into prod: invoice fixes
CI / test (push) Successful in 1m28s
CI / build (push) Successful in 19s
CI / deploy (push) Successful in 34s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 08:56:08 +00:00
fecoandClaude Opus 5.5 e4905ec5f1 Invoice items: online content service, not astrology
CI / test (push) Successful in 1m32s
CI / build (push) Successful in 4m58s
CI / deploy (push) Skipped
The item reads e.g. 'Online tartalomszolgáltatás – Páros csomag', with
access to the site's software-made, personalised texts as its comment:
no profession is implied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 08:55:55 +00:00
fecoandClaude Opus 5.5 f578e84b3f Invoice items say what the service is
CI / test (push) Successful in 1m32s
CI / build (push) Successful in 5m50s
CI / deploy (push) Skipped
'Sorsfonalak – Páros' does not identify the service, as the VAT act
(169. § e) asks. The item is now e.g. 'Asztrológiai elemzéscsomag –
Páros', unit 'csomag', with the package's contents as its comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 08:34:08 +00:00
fecoandClaude Opus 5.5 76bc965537 No invoice for test payments
CI / test (push) Successful in 1m28s
CI / build (push) Successful in 6m16s
CI / deploy (push) Skipped
Billingo's invoices are real (reported to the tax authority), so a
payment made with a Stripe test key grants the package but queues no
invoice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 08:30:54 +00:00
11 changed files with 99 additions and 40 deletions
@@ -0,0 +1,5 @@
-- The invoice item must identify the service (Áfa tv. 169. § e): what the
-- package contains goes under the item, and the unit is "csomag".
ALTER TABLE invoices
ADD COLUMN item_comment text,
ADD COLUMN item_unit text NOT NULL DEFAULT 'csomag';
+3 -1
View File
@@ -26,7 +26,9 @@ 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, 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.
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%`. A tétel a törvény szerint azonosítja a szolgáltatást (Áfa tv. 169. § e): megnevezése pl. „Online tartalomszolgáltatás – Páros csomag”, egysége `csomag`, megjegyzése a tartalom („Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: 2 képletelemzés, … Digitális tartalom.”; `Package::invoice_item`). Szándékosan nem „asztrológiai”: a szolgáltatás egy weboldal programmal előállított tartalma, nem személyes szakmai tanácsadás. 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.
Minden igazolt fizetéshez készül számla, a teszt módúakhoz (`sk_test_…`) is: így a teljes folyamat próbálható egy teszt Billingo-fiókkal. Éles Billingo-fiók mellett ezért prodon már ne legyen teszt Stripe-kulcs (a kettőt megnyitáskor együtt kell élesre cserélni).
A worker `invoices` feladata (`WORKER_TASKS`, prodon a `worker` konténerben) a Billingo API v3-mal:
+4 -3
View File
@@ -100,7 +100,7 @@ pub async fn queue(
checkout_id: &str,
user_id: Option<Uuid>,
buyer: &Buyer,
item_name: &str,
(item_name, item_comment): (&str, &str),
gross_huf: i64,
vat: Vat,
) -> Result<Uuid, ApiError> {
@@ -108,8 +108,8 @@ pub async fn queue(
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) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) \
buyer_city, buyer_address, buyer_tax_type, buyer_tax_number, item_name, gross_huf, net_huf, vat_huf, vat_rate, \
item_comment) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) \
ON CONFLICT (checkout_id) DO NOTHING",
)
.bind(id)
@@ -128,6 +128,7 @@ pub async fn queue(
.bind(net as i32)
.bind(vat_huf as i32)
.bind(vat.code())
.bind(item_comment)
.execute(&mut *tx)
.await?;
Ok(id)
+44
View File
@@ -202,6 +202,33 @@ impl Source {
}
impl Package {
/// The invoice item: a name that says what the service is (online,
/// software-made content; no profession implied), and what the package
/// contains (Áfa tv. 169. § e).
pub fn invoice_item(&self) -> (String, String) {
let name = match self.tier {
Tier::Main => format!("Online tartalomszolgáltatás – {} csomag", self.name),
Tier::Addon => format!("Online tartalomszolgáltatás – {} kiegészítő", self.name),
};
let lines: Vec<String> = [
(self.natal, "képletelemzés"),
(self.synastry, "kapcsolati elemzés"),
(self.forecast, "éves előrejelzés"),
(self.persons, "további személy felvétele"),
(self.questions, "kérdés"),
]
.into_iter()
.filter(|&(n, _)| n > 0)
.map(|(n, what)| format!("{n} {what}"))
.collect();
let comment = format!(
"Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: {}. \
Digitális tartalom.",
lines.join(", ")
);
(name, comment)
}
/// What the package gives, unit by unit.
pub fn contents(&self) -> [(Unit, i64); 5] {
[
@@ -341,4 +368,21 @@ mod tests {
assert!(CATALOG.iter().filter(|p| p.tier == Tier::Main).all(|p| p.questions == QUESTIONS_INCLUDED));
assert_eq!(find("addon_questions").unwrap().questions, 5);
}
#[test]
fn invoice_items_say_what_was_bought() {
let (name, comment) = find("couple").unwrap().invoice_item();
assert_eq!(name, "Online tartalomszolgáltatás – Páros csomag");
assert_eq!(
comment,
"Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: \
2 képletelemzés, 1 kapcsolati elemzés, 2 éves előrejelzés, 1 további személy felvétele, 3 kérdés. \
Digitális tartalom."
);
let (name, comment) = find("addon_persons").unwrap().invoice_item();
assert_eq!(name, "Online tartalomszolgáltatás – +5 személy kiegészítő");
assert!(comment.ends_with("tartalmaihoz: 5 további személy felvétele. Digitális tartalom."), "{comment}");
// No profession is implied.
assert!(CATALOG.iter().all(|p| !format!("{:?}", p.invoice_item()).to_lowercase().contains("asztrol")));
}
}
+1 -4
View File
@@ -31,7 +31,6 @@ use crate::auth::AuthUser;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
use db::Role;
#[derive(Debug, Clone, sqlx::FromRow)]
/// An analysis as users see it; the model is left out on purpose (a business secret).
@@ -136,10 +135,8 @@ async fn request(
req: AnalysisRequest,
) -> ApiResult<(StatusCode, Json<Value>)> {
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
// Admins use no unit.
let admin = auth.user.has_role(Role::Admin);
// Admins use units too (they can add more on the admin page).
let unit = match target {
_ if admin => None,
Target::Synastry { .. } => Some(Unit::Synastry),
Target::Forecast { .. } => Some(Unit::Forecast),
_ => Some(Unit::Natal),
+4 -3
View File
@@ -170,7 +170,8 @@ pub async fn checkout(
/// grants its package and queues the invoice, once. `false`: not our session.
async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, ApiError> {
let mut tx = state.db.begin().await?;
let row: Option<(Option<Uuid>, String, i32, Option<OffsetDateTime>)> = sqlx::query_as(
type Checkout = (Option<Uuid>, String, i32, Option<OffsetDateTime>);
let row: Option<Checkout> = sqlx::query_as(
"SELECT user_id, package, price_huf, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE",
)
.bind(&session.id)
@@ -206,9 +207,9 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, A
.execute(&mut *tx)
.await?;
let buyer = invoices::Buyer::from_stripe(session.customer_details.as_ref().unwrap_or(&Value::Null), None);
let item = format!("Sorsfonalak – {}", package.name);
let (item, comment) = package.invoice_item();
let gross = amount_huf.unwrap_or(i64::from(price_huf));
invoices::queue(&mut tx, &session.id, user_id, &buyer, &item, gross, state.config.invoice_vat).await?;
invoices::queue(&mut tx, &session.id, user_id, &buyer, (&item, &comment), gross, state.config.invoice_vat).await?;
tx.commit().await?;
tracing::info!(user = ?user_id, package = %package_id, session = %session.id, "package paid");
Ok(true)
+2 -5
View File
@@ -9,7 +9,6 @@ use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use db::Role;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
@@ -145,7 +144,6 @@ pub async fn ask(
));
}
let admin = auth.user.has_role(Role::Admin);
let (model, fallback, prompt_version) = model_and_version(&state, &analysis.language).await?;
let question_id = Uuid::now_v7();
let mut tx = state.db.begin().await?;
@@ -161,13 +159,12 @@ pub async fn ask(
.bind(&analysis.language)
.bind(&model)
.bind(&prompt_version)
.bind(i32::from(!admin))
.bind(1i32)
.bind(&fallback)
.fetch_one(&mut *tx)
.await?;
if !admin {
// Admins use questions too (they can add more on the admin page).
credits::spend_question(&mut tx, auth.id(), question_id).await?;
}
tx.commit().await?;
Ok((StatusCode::ACCEPTED, Json(row.view())))
}
+21 -5
View File
@@ -277,6 +277,15 @@ impl TestApp {
r.body["session"]["token"].as_str().unwrap().to_string()
}
/// An admin adds units to their own account (admins use units too).
async fn add_own_units(&self, admin: &str, unit: &str, delta: i32) {
let id = self.get("/v1/me", Some(admin)).await.body["user"]["id"].as_str().unwrap().to_string();
let r = self
.post(&format!("/v1/admin/users/{id}/credits"), Some(admin), json!({"unit": unit, "delta": delta}))
.await;
assert!(r.status.is_success(), "{}", r.body);
}
async fn chart(&self, token: &str, label: &str, primary: bool, date: &str) -> Value {
let r = self
.post(
@@ -1061,13 +1070,18 @@ async fn birth_data_changes_are_limited(pool: PgPool) {
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn admins_get_free_analyses_and_mock_payments_add_units(pool: PgPool) {
async fn admins_use_units_too_and_mock_payments_add_units(pool: PgPool) {
let app = TestApp::new(pool).await;
let admin = app.register("admin@example.com", "Admin").await;
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
let r =
app.call("POST", &format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()), Some(&admin), None).await;
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(0)), "{}", r.body);
let analyses = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap());
// Admins pay with units like everyone (they add their own on the admin page).
let r = app.call("POST", &analyses, Some(&admin), None).await;
assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED, "{}", r.body);
app.add_own_units(&admin, "natal", 2).await;
let r = app.call("POST", &analyses, Some(&admin), None).await;
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(1)), "{}", r.body);
assert_eq!(app.get("/v1/credits", Some(&admin)).await.body["balance"]["natal"], 1);
// a user "pays", which adds a unit, then requests the analysis
let anna = app.register("anna@example.com", "Anna").await;
@@ -1750,6 +1764,7 @@ async fn admins_choose_the_model_of_each_function(pool: PgPool) {
assert_eq!((r.status, &r.body["model"], &r.body["custom"]), (StatusCode::OK, &json!("openai/gpt-x"), &json!(true)));
// new analyses use it; regenerating writes it again in place with the current model
app.add_own_units(&admin, "natal", 1).await;
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
let chart_id = chart["id"].as_str().unwrap();
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
@@ -1880,6 +1895,7 @@ async fn admins_restart_open_generations_with_the_current_models(pool: PgPool) {
async move { app.call("PUT", "/v1/admin/models/analysis", Some(admin), Some(body)).await }
};
assert_eq!(put("openai/gpt-x").await.status, StatusCode::OK);
app.add_own_units(&admin, "natal", 1).await;
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
let chart_id = chart["id"].as_str().unwrap();
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
@@ -2404,7 +2420,7 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
(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.item_name, "Online tartalomszolgáltatás – Páros csomag");
// Alanyi adómentes (the default): no VAT.
assert_eq!((invoice.gross_huf, invoice.net_huf, invoice.vat_huf), (6000, 6000, 0));
@@ -132,7 +132,7 @@ export function AnalysisQuestions({
setBuying(false);
}
const canAsk = isAdmin || left > 0;
const canAsk = left > 0;
return (
<section className="questions" aria-labelledby={`${fieldId}-title`}>
<h3 id={`${fieldId}-title`}>{TEXTS[about].title}</h3>
@@ -196,11 +196,7 @@ export function AnalysisQuestions({
{busy ? "Küldés…" : "Kérdés küldése"}
</button>
<span className="hint">
{waiting
? "Várd meg az előző válaszát."
: isAdmin
? "Adminként ingyenes."
: `Még ${left} kérdésed van.`}{" "}
{waiting ? "Várd meg az előző válaszát." : `Még ${left} kérdésed van.`}{" "}
{text.length > MAX_CHARS - 100 && `${text.length}/${MAX_CHARS}`}
</span>
</div>
@@ -198,7 +198,7 @@ export function DetailedAnalysis({
<div className="msg msg-error" role="alert">
<p style={{ margin: 0 }}>
Az elemzés többszöri próbálkozás után sem készült el.
{isAdmin || analysis.credits_charged === 0
{analysis.credits_charged === 0
? " Próbáld újra."
: " A felhasznált egységet visszaadtuk, így ingyen újra kérheted."}
</p>
@@ -211,14 +211,7 @@ export function DetailedAnalysis({
</p>
)}
{isAdmin ? (
<div className="form-actions">
<button type="button" className="btn btn-primary" onClick={start} disabled={busy}>
{busy ? "Indítás…" : `${t.item} készítése`}
</button>
<span className="hint">Adminként ingyenes.</span>
</div>
) : left > 0 ? (
{left > 0 ? (
step === "confirm" ? (
<div className="form-actions">
<button type="button" className="btn btn-primary" onClick={start} disabled={busy}>
+10 -3
View File
@@ -86,6 +86,8 @@ struct Due {
buyer_tax_type: String,
buyer_tax_number: Option<String>,
item_name: String,
item_comment: Option<String>,
item_unit: String,
gross_huf: i32,
vat_rate: String,
payment_method: String,
@@ -128,7 +130,7 @@ pub async fn run_once(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Re
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.buyer_city, i.buyer_address, i.buyer_tax_type, i.buyer_tax_number, i.item_name, i.item_comment, i.item_unit, i.gross_huf, \
i.vat_rate, i.payment_method, i.billingo_partner_id, i.billingo_document_id, i.sent_at, \
coalesce(c.completed_at, i.created_at) AS paid_at"
))
@@ -240,8 +242,9 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
"unit_price": due.gross_huf,
"unit_price_type": "gross",
"quantity": 1,
"unit": "db",
"unit": due.item_unit,
"vat": due.vat_rate,
"comment": due.item_comment.clone().unwrap_or_default(),
}],
"comment": if due.vat_rate == "AAM" {
"Bankkártyával kifizetve (Stripe). Alanyi adómentes."
@@ -399,7 +402,7 @@ mod tests {
"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, 6000, 0)",
'Online tartalomszolgáltatás – Páros csomag', 6000, 6000, 0)",
)
.bind(id)
.bind(&checkout)
@@ -449,6 +452,10 @@ mod tests {
(&json!(true), &json!("online_bankcard"), &json!("HUF"))
);
assert_eq!(doc["items"][0]["unit_price"], 6000);
assert_eq!(
(&doc["items"][0]["name"], &doc["items"][0]["unit"]),
(&json!("Online tartalomszolgáltatás – Páros csomag"), &json!("csomag"))
);
assert_eq!(
(&doc["items"][0]["unit_price_type"], &doc["items"][0]["vat"]),
(&json!("gross"), &json!("AAM"))