Compare commits

..
Author SHA1 Message Date
feco e68f7407f3 Merge main into prod: Sign in with Apple
CI / build (push) Successful in 24s
CI / deploy (push) Successful in 43s
CI / test (push) Successful in 1m34s
2026-11-20 19:42:27 +00:00
feco ad436f786c Merge main into prod: log review fixes, graceful worker stop
CI / deploy (push) Successful in 42s
CI / test (push) Successful in 1m32s
CI / build (push) Successful in 24s
2026-11-20 19:09:37 +00:00
feco a2649fddeb Merge main into prod: account menu, persistent logs, softer copy
CI / test (push) Successful in 1m33s
CI / build (push) Successful in 25s
CI / deploy (push) Successful in 1m20s
2026-11-20 17:51:25 +00:00
feco f69f76a05a Merge main into prod: tarot on the home page, footer and description
CI / build (push) Successful in 23s
CI / deploy (push) Successful in 1m0s
CI / test (push) Successful in 1m31s
2026-11-20 17:11:18 +00:00
feco 1a75dec59a Merge main into prod: tarot topics, Párkapcsolat example tab
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 22s
CI / deploy (push) Successful in 40s
2026-11-20 16:25:13 +00:00
sagifer 663ceaca16 Merge pull request 'Tarot example: the draw played as an animation, and a love reading' (#31) from main into prod
CI / build (push) Successful in 1m35s
CI / deploy (push) Successful in 52s
CI / test (push) Successful in 1m29s
Reviewed-on: #31
2026-11-20 16:54:03 +01:00
feco 22d2484cab Merge main into prod: tarot readings, ÁSZF consent off until the opening
CI / test (push) Successful in 1m34s
CI / build (push) Successful in 23s
CI / deploy (push) Successful in 39s
2026-11-20 14:54:53 +00:00
sagifer 1af7415add Merge pull request 'ÁSZF: terms page, consent on every purchase, confirmation e-mail' (#30) from main into prod
CI / test (push) Successful in 1m30s
CI / build (push) Successful in 2m8s
CI / deploy (push) Successful in 48s
Reviewed-on: #30
2026-11-20 13:17:15 +01:00
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
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 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 174ec31351 Merge main into prod: migration fix (site down)
CI / test (push) Successful in 1m28s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 33s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 08:18:56 +00:00
fecoandClaude Opus 5.5 27ecdf386e Merge main into prod
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 2m2s
CI / deploy (push) Failing after 34s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 08:05:38 +00:00
sagifer 5e633b959d Merge pull request 'Main' (#28) from main into prod
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 2m29s
CI / deploy (push) Successful in 50s
Reviewed-on: #28
2026-11-20 08:01:11 +01:00
sagifer a4df094191 Merge pull request 'Sitemap for the public pages, linked from robots.txt' (#27) from main into prod
CI / test (push) Successful in 1m18s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 37s
Reviewed-on: #27
2026-11-20 03:15:22 +01:00
sagifer 15c88fc6be Merge pull request 'Form fields: room in text areas, our own select chevron' (#26) from main into prod
CI / test (push) Successful in 1m21s
CI / build (push) Successful in 22s
CI / deploy (push) Successful in 36s
Reviewed-on: #26
2026-11-19 21:38:23 +01:00
sagifer ddca7acbd4 Merge pull request 'Chart page: a balanced layout around the wheel' (#25) from main into prod
CI / test (push) Successful in 1m18s
CI / build (push) Successful in 20s
CI / deploy (push) Successful in 38s
Reviewed-on: #25
2026-11-19 19:36:31 +01:00
sagifer fd655952b6 Merge pull request 'The logo mark next to the wordmark' (#24) from main into prod
CI / test (push) Successful in 1m19s
CI / build (push) Successful in 22s
CI / deploy (push) Successful in 37s
Reviewed-on: #24
2026-11-19 18:41:57 +01:00
feco b672b1cefa Merge main into prod: favicon and footer logos
CI / test (push) Successful in 1m19s
CI / build (push) Successful in 20s
CI / deploy (push) Successful in 38s
2026-11-19 15:37:37 +00:00
sagifer f2953dd18f Merge pull request 'Main' (#23) from main into prod
CI / test (push) Successful in 1m15s
CI / build (push) Successful in 24s
CI / deploy (push) Successful in 37s
Reviewed-on: #23
2026-11-19 14:31:47 +01:00
feco 0c4274d87b Merge main into prod: home page AI note
CI / test (push) Successful in 1m22s
CI / build (push) Successful in 20s
CI / deploy (push) Successful in 37s
2026-11-19 12:09:01 +00:00
sagifer 4a2a84b36f Merge pull request 'Logging out (and deleting the account) leads to the home page' (#22) from main into prod
CI / test (push) Successful in 1m19s
CI / build (push) Successful in 1m36s
CI / deploy (push) Successful in 37s
Reviewed-on: #22
2026-11-19 13:05:05 +01:00
sagifer 3944c6a4b0 Merge pull request 'Main' (#21) from main into prod
CI / test (push) Successful in 1m15s
CI / build (push) Successful in 22s
CI / deploy (push) Successful in 37s
Reviewed-on: #21
2026-11-19 12:54:15 +01:00
sagifer a352e359c4 Merge pull request 'Main' (#20) from main into prod
CI / test (push) Successful in 1m23s
CI / build (push) Successful in 22s
CI / deploy (push) Successful in 36s
Reviewed-on: #20
2026-11-19 12:29:51 +01:00
sagifer d9ca806d50 Merge pull request 'a' (#19) from main into prod
CI / test (push) Successful in 1m11s
CI / build (push) Successful in 20s
CI / deploy (push) Successful in 38s
Reviewed-on: #19
2026-11-19 10:35:29 +01:00
sagifer f037522052 Merge pull request 'Sharing a chart with its short summary, with link previews' (#18) from main into prod
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 41s
Reviewed-on: #18
2026-11-19 09:11:59 +01:00
sagifer e476117c77 Merge pull request 'Main' (#17) from main into prod
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 56s
CI / deploy (push) Successful in 34s
Reviewed-on: #17
2026-11-19 08:13:18 +01:00
sagifer d758f5bf12 Merge pull request 'Frontend: justified generated text, mobile layout without sideways scrolling' (#16) from main into prod
CI / test (push) Successful in 1m7s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 51s
Reviewed-on: #16
2026-11-19 07:15:09 +01:00
fecoandClaude Opus 5.5 8b2c4310ba Merge main into prod: restart running generations, error log, retry notice, questions on relationship analyses
CI / test (push) Successful in 1m7s
CI / build (push) Successful in 19s
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-18 21:51:39 +00:00
fecoandClaude Opus 5.5 1c24b9a23f Merge main into prod: model functions (analyses, answers, summary), Opus 5.5 default and fallback
CI / test (push) Successful in 1m0s
CI / build (push) Successful in 19s
CI / deploy (push) Successful in 53s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:14:13 +00:00
fecoandClaude Opus 5.5 86758cf848 Merge main into prod: worker room and time for reasoning models
CI / test (push) Successful in 1m0s
CI / build (push) Successful in 20s
CI / deploy (push) Successful in 35s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 19:52:02 +00:00
sagifer 39d75eddbd Merge pull request 'Main' (#15) from main into prod
CI / test (push) Successful in 1m3s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 44s
Reviewed-on: #15
2026-11-18 20:02:23 +01:00
sagifer f4ee40f45d Merge pull request 'Hungarian prompts in Hungarian, model choice per analysis kind, admin regenerate' (#14) from main into prod
CI / test (push) Successful in 58s
CI / build (push) Successful in 15s
CI / deploy (push) Successful in 39s
Reviewed-on: #14
2026-11-18 18:48:09 +01:00
sagifer 422078545e Merge pull request 'Quincunx in the default aspects, sign-based moon phases, backend recalculate command' (#13) from main into prod
CI / test (push) Successful in 57s
CI / build (push) Successful in 23s
CI / deploy (push) Successful in 39s
Reviewed-on: #13
2026-11-18 13:20:31 +01:00
sagifer 2a7cb467cf Merge pull request 'Main' (#12) from main into prod
CI / test (push) Successful in 55s
CI / build (push) Successful in 13s
CI / deploy (push) Successful in 36s
Reviewed-on: #12
2026-11-18 12:41:13 +01:00
sagifer c20ab45c9d Merge pull request 'Yearly forecast: solar return, transits, progressions, profection, eclipses' (#11) from main into prod
CI / test (push) Successful in 58s
CI / build (push) Successful in 43s
CI / deploy (push) Successful in 50s
Reviewed-on: #11
2026-11-18 09:45:53 +01:00
sagifer cf625abff2 Merge pull request 'Main' (#10) from main into prod
CI / test (push) Successful in 51s
CI / build (push) Successful in 12s
CI / deploy (push) Successful in 40s
Reviewed-on: #10
2026-11-18 07:35:17 +01:00
sagifer 85977cb7af Merge pull request 'Header shows the user's package and what is left of it' (#9) from main into prod
CI / test (push) Successful in 50s
CI / build (push) Successful in 13s
CI / deploy (push) Successful in 38s
Reviewed-on: #9
2026-11-17 21:05:49 +01:00
sagifer 2032837aad Merge pull request 'Main' (#7) from main into prod
CI / test (push) Successful in 57s
CI / build (push) Successful in 1m20s
CI / deploy (push) Successful in 42s
Reviewed-on: #7
2026-11-17 19:58:35 +01:00
sagifer a097cf4311 Merge pull request 'Main' (#6) from main into prod
CI / test (push) Successful in 45s
CI / build (push) Successful in 13s
CI / deploy (push) Successful in 41s
Reviewed-on: #6
2026-11-17 17:45:40 +01:00
sagifer bf7fb937d2 Merge pull request 'Worker tests: set the chart kind (charts_primary_is_own)' (#5) from main into prod
CI / test (push) Successful in 44s
CI / build (push) Successful in 13s
CI / deploy (push) Successful in 38s
Reviewed-on: #5
2026-11-17 13:25:02 +01:00
sagifer a8ce5490c8 Merge pull request 'Main' (#4) from main into prod
CI / test (push) Failing after 43s
CI / build (push) Skipped
CI / deploy (push) Skipped
Reviewed-on: #4
2026-11-17 13:15:24 +01:00
sagifer b0b0347b04 Merge pull request 'Main' (#3) from main into prod
CI / test (push) Successful in 39s
CI / build (push) Successful in 39s
CI / deploy (push) Successful in 42s
Reviewed-on: #3
2026-11-17 11:24:13 +01:00
sagifer a75712a60a Merge pull request 'Aspect grid: the usual triangular matrix, values in collapsible details' (#2) from main into prod
CI / test (push) Successful in 40s
CI / build (push) Successful in 13s
CI / deploy (push) Successful in 44s
Reviewed-on: #2
2026-11-17 10:51:21 +01:00
sagifer e08b6121a2 Merge pull request 'Main' (#1) from main into prod
CI / test (push) Successful in 39s
CI / build (push) Successful in 13s
CI / deploy (push) Successful in 38s
Reviewed-on: #1
2026-11-17 08:04:09 +01:00
19 changed files with 98 additions and 491 deletions
@@ -1,4 +0,0 @@
-- When the worker asked Billingo for the invoice. Set before the request: if
-- the answer is lost (a timeout after Billingo made it), the next attempt
-- looks the invoice up instead of making a second one.
ALTER TABLE invoices ADD COLUMN document_requested_at timestamptz;
+2 -7
View File
@@ -4,8 +4,7 @@
{
servers {
# Cloudflare ranges (https://www.cloudflare.com/ips): the visitor's
# address ({client_ip}) is taken from CF-Connecting-IP, only when the
# request comes from Cloudflare.
# address is taken from CF-Connecting-IP and passed on in X-Forwarded-For.
trusted_proxies static 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32
client_ip_headers CF-Connecting-IP
}
@@ -15,11 +14,7 @@
# No basic auth any more: the site is open, and new accounts need an
# invitation (SIGNUP_MODE=invite in the backend).
encode zstd gzip
reverse_proxy frontend:3000 {
# The address the backend trusts (rate limits, share visits); it
# overwrites whatever the browser sent in this header.
header_up X-Real-IP {client_ip}
}
reverse_proxy frontend:3000
}
www.{$DOMAIN} {
+3 -15
View File
@@ -65,11 +65,7 @@ fn text(v: &Value) -> Option<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. A
/// Hungarian company with only an EU VAT number (`HU12345678`) is invoiced
/// without a tax type number: Billingo takes only the full domestic
/// number (`12345678-1-23`) for HAS_TAX_NUMBER; the EU number still goes
/// on the invoice, in its comment (the worker adds it).
/// 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();
@@ -78,8 +74,8 @@ impl Buyer {
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(_), _) if tax_id("hu_tin").is_some() => "HAS_TAX_NUMBER",
_ => "NO_TAX_NUMBER",
(Some(_), _) => "HAS_TAX_NUMBER",
(None, _) => "NO_TAX_NUMBER",
};
let street = [text(&address["line1"]), text(&address["line2"])].into_iter().flatten().collect::<Vec<_>>();
Self {
@@ -180,14 +176,6 @@ mod tests {
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 eu_only = Buyer::from_stripe(
&json!({"name": "Kovács Anna", "business_name": "Csillag Kft.", "address": {"country": "HU"},
"tax_ids": [{"type": "eu_vat", "value": "HU12345678"}]}),
None,
);
assert_eq!(eu_only.name, "Csillag Kft.");
assert_eq!((eu_only.tax_type, eu_only.tax_number.as_deref()), ("NO_TAX_NUMBER", Some("HU12345678")));
let abroad = Buyer::from_stripe(&json!({"name": "Anna", "address": {"country": "at"}}), None);
assert_eq!((abroad.country.as_str(), abroad.tax_type), ("AT", "FOREIGN"));
}
+4 -9
View File
@@ -183,11 +183,6 @@ pub(super) async fn queue(
let (model, fallback) = &crate::models::models_for(state, Kind::parse(kind).expect("known kind")).await?;
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
// One request at a time per user (a double click must not queue and pay
// for the same analysis twice): the user row is locked until commit.
let mut tx = state.db.begin().await?;
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user).execute(&mut *tx).await?;
// Already requested for this chart/synastry: return it.
let existing: Option<AnalysisRow> = sqlx::query_as(&format!(
"SELECT {ANALYSIS_COLUMNS} FROM analyses \
@@ -198,7 +193,7 @@ pub(super) async fn queue(
.bind(synastry_id)
.bind(cache_key)
.bind(forecast_id)
.fetch_optional(&mut *tx)
.fetch_optional(&state.db)
.await?;
if let Some(row) = existing {
return Ok((StatusCode::OK, row));
@@ -219,7 +214,7 @@ pub(super) async fn queue(
)
.bind(cache_key)
.bind(prompt_version)
.fetch_optional(&mut *tx)
.fetch_optional(&state.db)
.await?;
if let Some((content, input_tokens, output_tokens)) = cached {
let row: AnalysisRow = sqlx::query_as(&insert)
@@ -240,13 +235,13 @@ pub(super) async fn queue(
.bind(OffsetDateTime::now_utc())
.bind(forecast_id)
.bind(fallback)
.fetch_one(&mut *tx)
.fetch_one(&state.db)
.await?;
tx.commit().await?;
return Ok((StatusCode::CREATED, row));
}
// New analysis: spend a unit and queue it for the worker.
let mut tx = state.db.begin().await?;
let row: AnalysisRow = sqlx::query_as(&insert)
.bind(id)
.bind(kind)
-17
View File
@@ -389,23 +389,6 @@ async fn social_login(
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
let (id, created) = match existing {
Some((id,)) => {
// An account whose address was never confirmed may have
// been made by someone else with this address: its
// password and sessions go, the provider has proven who
// owns the address.
let unverified: bool =
sqlx::query_scalar("SELECT email_verified_at IS NULL FROM users WHERE id = $1 FOR UPDATE")
.bind(id)
.fetch_one(&mut *tx)
.await?;
if unverified {
sqlx::query("DELETE FROM auth_identities WHERE user_id = $1 AND provider = 'password'")
.bind(id)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(id).execute(&mut *tx).await?;
tracing::warn!(user = %id, provider, "unconfirmed password account taken over by its address's owner");
}
// The provider has verified the address, so it counts as verified here too.
sqlx::query(
"UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1",
+1 -3
View File
@@ -342,9 +342,7 @@ async fn corrected_birth(
let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as(
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed') \
OR EXISTS (SELECT 1 FROM analyses a JOIN synastries s ON s.id = a.synastry_id \
WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed') \
OR EXISTS (SELECT 1 FROM analyses a JOIN forecasts f ON f.id = a.forecast_id \
WHERE f.chart_id = $1 AND a.status <> 'failed'), \
WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed'), \
EXISTS (SELECT 1 FROM synastries WHERE (chart1_id = $1 OR chart2_id = $1) AND owner_id <> $2)",
)
.bind(chart.id)
+10 -14
View File
@@ -89,8 +89,8 @@ pub async fn mark_accepted(
let hash = token.map(|t| db::token_hash(t.trim()));
sqlx::query(
"UPDATE invitations SET accepted_at = now(), accepted_by = $1 \
WHERE accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now() \
AND (email = $2 OR id IN (SELECT invitation_id FROM invitation_tokens WHERE token_hash = $3))",
WHERE accepted_at IS NULL AND revoked_at IS NULL \
AND (email = $2 OR (expires_at > now() AND id IN (SELECT invitation_id FROM invitation_tokens WHERE token_hash = $3)))",
)
.bind(user_id)
.bind(email)
@@ -603,19 +603,10 @@ pub async fn unsubscribe(
.bind(db::token_hash(&email))
.execute(&mut *tx)
.await?;
let revoked: Vec<Uuid> = sqlx::query_scalar(
"UPDATE invitations SET revoked_at = now() WHERE email = $1 AND accepted_at IS NULL AND revoked_at IS NULL \
RETURNING id",
sqlx::query(
"UPDATE invitations SET revoked_at = now() WHERE email = $1 AND accepted_at IS NULL AND revoked_at IS NULL",
)
.bind(&email)
.fetch_all(&mut *tx)
.await?;
// Their packages go with them, as when an admin revokes an invitation.
sqlx::query(
"UPDATE promo_codes SET revoked_at = now() \
WHERE invitation_id = ANY($1) AND redeemed_at IS NULL AND revoked_at IS NULL",
)
.bind(&revoked)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(&email).execute(&mut *tx).await?;
@@ -639,7 +630,12 @@ pub async fn join_waitlist(
let email = normalize_email(&req.email)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
// Every sign-up sends an e-mail: a few per address, so the form cannot be used to flood someone.
let ip = super::client_ip(&headers).unwrap_or_else(|| "unknown".into());
let ip = headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split(',').next())
.map(str::trim)
.unwrap_or("unknown");
let key = format!("waitlist:{ip}");
state.login_limiter.check(&key)?;
let token = db::new_token();
-7
View File
@@ -122,16 +122,9 @@ pub async fn restart(
.rows_affected()
} else {
let Some(row) = find_analysis(&state.db, id).await? else { continue };
let (model, fallback, cache_key, prompt_version) = if kind == "tarot" {
// A tarot reading: the analysis model, the same cards, never cached.
let (model, fallback) = models_for(&state, Kind::Natal).await?;
(model, fallback, format!("tarot|{id}"), state.config.prompt_version.clone())
} else {
let Some(hash) = target_hash(&state.db, &row).await? else { continue };
let (model, fallback) = models_for(&state, Kind::parse(&kind).unwrap_or(Kind::Natal)).await?;
let (cache_key, prompt_version) = versions(&state, &kind, &hash, &model, &row.language).await?;
(model, fallback, cache_key, prompt_version)
};
sqlx::query(
"UPDATE analyses SET status = 'pending', model = $2, fallback_model = $3, on_fallback = false, \
cache_key = $4, prompt_version = $5, attempts = 0, next_attempt_at = now(), started_at = NULL, \
-9
View File
@@ -57,15 +57,6 @@ where
serde::Deserialize::deserialize(d).map(Some)
}
/// The visitor's address from `X-Real-IP`: Caddy sets it (overwriting what
/// the browser sent) from Cloudflare's `CF-Connecting-IP`, trusted only from
/// Cloudflare's ranges, and the frontend's proxy passes it on. Not
/// `X-Forwarded-For`, whose first entry the browser can write.
pub(crate) fn client_ip(headers: &axum::http::HeaderMap) -> Option<String> {
let ip = headers.get("x-real-ip")?.to_str().ok()?.trim();
(!ip.is_empty()).then(|| ip.to_string())
}
pub fn router(state: Arc<AppState>) -> Router {
Router::new()
.route("/healthz", get(health))
+8 -4
View File
@@ -61,7 +61,12 @@ struct ShareRow {
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
view_count, created_at, revoked_at, owner_ip_hash";
use super::client_ip;
/// The visitor's address: the first `X-Forwarded-For` entry (Caddy writes it
/// from Cloudflare's, the frontend passes it on).
fn client_ip(headers: &HeaderMap) -> Option<String> {
let first = headers.get("x-forwarded-for")?.to_str().ok()?.split(',').next()?.trim();
(!first.is_empty()).then(|| first.to_string())
}
/// An address salted with the slug, so the stored value says nothing by itself.
fn ip_hash(slug: &str, ip: &str) -> Vec<u8> {
@@ -226,9 +231,8 @@ pub async fn revoke(State(state): St, auth: AuthUser, WithRejection(Path(id), _)
// --- public view -------------------------------------------------------------------------------
fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value {
// Birth data only of the sharer's own chart, never of a partner's or of a
// person they added (that is someone else's data).
let show = share.show_birth_data && chart.owner_id == share.owner_id && chart.kind == "own";
// Birth data only of the sharer's own chart, never of a partner's.
let show = share.show_birth_data && chart.owner_id == share.owner_id;
json!({ "label": chart.label, "chart": public_chart(&chart.result, show) })
}
+3 -13
View File
@@ -469,10 +469,10 @@ pub async fn accept_invite(
let my_chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
let inviter_chart =
find_chart(&state.db, invite.inviter_chart_id).await?.ok_or(ApiError::NotFound("invitation"))?;
let (row, created) = compute_synastry(&state, invite.inviter_id, &inviter_chart, &my_chart).await?;
let (row, _) = compute_synastry(&state, invite.inviter_id, &inviter_chart, &my_chart).await?;
let mut tx = state.db.begin().await?;
let accepted = sqlx::query(
sqlx::query(
"UPDATE synastry_invites SET accepted_at = now(), accepted_by = $1, synastry_id = $2 \
WHERE id = $3 AND accepted_at IS NULL",
)
@@ -480,17 +480,7 @@ pub async fn accept_invite(
.bind(row.id)
.bind(invite.id)
.execute(&mut *tx)
.await?
.rows_affected();
if accepted == 0 {
// Someone else accepted it at the same moment: the comparison made
// for this attempt goes, the link is used up.
drop(tx);
if created {
sqlx::query("DELETE FROM synastries WHERE id = $1").bind(row.id).execute(&state.db).await?;
}
return Err(ApiError::Gone("this invitation has already been accepted".into()));
}
.await?;
let inviter: Option<db::User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1"))
.bind(invite.inviter_id)
.fetch_optional(&mut *tx)
+4 -69
View File
@@ -430,31 +430,14 @@ async fn google_login_creates_links_and_rejects(pool: PgPool) {
.await;
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
// an existing, confirmed password account with the same address gets Google linked
// an existing password account with the same address gets Google linked
let token = app.register("anna@example.com", "Anna").await;
sqlx::query("UPDATE users SET email_verified_at = now() WHERE email = 'anna@example.com'")
.execute(&app.pool)
.await
.unwrap();
let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-2", "anna@example.com", GOOGLE_CLIENT)}))
.await;
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
assert_eq!(app.get("/v1/me", Some(&token)).await.body["providers"], json!(["password", "google"]));
// an unconfirmed one may be someone else's: its password and sessions go
let squatter = app.register("victim@example.com", "Valaki").await;
let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-4", "victim@example.com", GOOGLE_CLIENT)}))
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let owner = r.body["session"]["token"].as_str().unwrap().to_string();
assert_eq!(app.get("/v1/me", Some(&squatter)).await.status, StatusCode::UNAUTHORIZED);
assert_eq!(app.get("/v1/me", Some(&owner)).await.body["providers"], json!(["google"]));
let r =
app.post("/v1/auth/login", None, json!({"email": "victim@example.com", "password": "titkos-jelszo-123"})).await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-3", "x@gmail.com", "other-client")}))
.await;
@@ -907,7 +890,7 @@ async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) {
let anna = app.register("anna@example.com", "Anna").await;
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
let share = json!({"kind": "chart", "target_id": chart["id"]});
let home = ("x-real-ip", "203.0.113.7");
let home = ("x-forwarded-for", "203.0.113.7");
let r = app.call_with("POST", "/v1/shares", Some(&anna), Some(share), &[home]).await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let visit = format!("/v1/public/shares/{}/visit", r.body["slug"].as_str().unwrap());
@@ -916,9 +899,7 @@ async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) {
let before = me().await["analyses_left"]["question"].as_i64().unwrap();
// robots, a missing user agent, the sharer's address and the sharer do not count
// A browser cannot pose as the sharer through X-Forwarded-For: only X-Real-IP
// (set by Caddy) counts.
let elsewhere = ("x-real-ip", "198.51.100.1");
let elsewhere = ("x-forwarded-for", "198.51.100.1, 172.70.1.1");
for (token, headers) in [
(None, vec![("user-agent", "facebookexternalhit/1.1"), elsewhere]),
(None, vec![elsewhere]),
@@ -1987,18 +1968,6 @@ async fn admins_restart_open_generations_with_the_current_models(pool: PgPool) {
(status.as_str(), model.as_str(), fallback, started, attempts),
("pending", "anthropic/claude-test", None, None, 0)
);
// a stuck tarot reading restarts too
app.add_own_units(&admin, "tarot", 1).await;
let reading = app.post("/v1/tarot/readings", Some(&admin), json!({"spread": "daily"})).await;
let reading_id = reading.body["id"].as_str().unwrap().to_string();
sqlx::query("UPDATE analyses SET status = 'running', started_at = now() WHERE id = $1::uuid")
.bind(&reading_id)
.execute(&pool)
.await
.unwrap();
let r = app.post("/v1/admin/jobs/restart", Some(&admin), json!({ "ids": [reading_id] })).await;
assert_eq!(r.body["restarted"], 1, "{}", r.body);
// finished ones are left alone
sqlx::query("UPDATE analyses SET status = 'done', content = '{}'").execute(&pool).await.unwrap();
assert_eq!(app.post("/v1/admin/jobs/restart", Some(&admin), json!({})).await.body["restarted"], 0);
@@ -2205,7 +2174,7 @@ async fn an_invitation_brings_its_package_and_codes_fill_up(pool: PgPool) {
async fn the_waitlist_confirms_and_can_be_left(pool: PgPool) {
let app = TestApp::with_config(pool.clone(), |c| c.signup_mode = crate::config::SignupMode::Invite).await;
let admin = app.register("admin@example.com", "Admin").await;
let from = |ip: &'static str| [("x-real-ip", ip)];
let from = |ip: &'static str| [("x-forwarded-for", ip)];
// one confirmation per address, even when sent again
for _ in 0..2 {
@@ -2773,37 +2742,3 @@ async fn apple_login_can_be_off(pool: PgPool) {
.await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_double_click_queues_and_pays_one_analysis(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let anna = app.register("anna@example.com", "Anna").await;
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
grant_units(&app, &anna, "natal", 2).await;
let url = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap());
let (a, b) = tokio::join!(app.call("POST", &url, Some(&anna), None), app.call("POST", &url, Some(&anna), None));
assert!(a.status.is_success() && b.status.is_success(), "{} {}", a.body, b.body);
assert_eq!(a.body["id"], b.body["id"]);
let count: i64 =
sqlx::query_scalar("SELECT count(*) FROM analyses WHERE kind = 'natal'").fetch_one(&pool).await.unwrap();
assert_eq!(count, 1);
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["analyses_left"]["natal"], 1);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_paid_forecast_fixes_the_person(pool: PgPool) {
let app = TestApp::new(pool).await;
let anna = app.register("anna@example.com", "Anna").await;
app.chart(&anna, "Saját", true, "1990-03-15").await;
let bela = app.chart(&anna, "Béla", false, "1985-08-02").await;
let bela_id = bela["id"].as_str().unwrap();
let forecast = app.post(&format!("/v1/charts/{bela_id}/forecasts"), Some(&anna), json!({})).await;
assert_eq!(forecast.status, StatusCode::CREATED, "{}", forecast.body);
grant_units(&app, &anna, "forecast", 1).await;
let id = forecast.body["id"].as_str().unwrap();
let r = app.call("POST", &format!("/v1/forecasts/{id}/analyses"), Some(&anna), None).await;
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
let corrected = json!({"birth": {"date": "1985-08-03", "time": "10:00", "country": "HU", "place": "Szeged"}});
let r = app.call("PATCH", &format!("/v1/charts/{bela_id}"), Some(&anna), Some(corrected)).await;
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_analysed")));
}
@@ -28,10 +28,8 @@ async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[]
const value = req.headers.get(name);
if (value) headers.set(name, value);
}
// The visitor's address as Caddy set it (from Cloudflare's CF-Connecting-IP,
// overwriting any the browser sent).
const realIp = req.headers.get("x-real-ip");
if (realIp) headers.set("x-real-ip", realIp);
const forwardedFor = req.headers.get("x-forwarded-for");
if (forwardedFor) headers.set("x-forwarded-for", forwardedFor);
let res: Response;
try {
+2 -6
View File
@@ -13,14 +13,10 @@ import { GoogleLogin } from "./GoogleLogin";
export const metadata: Metadata = { title: "Belépés" };
/**
* Only local paths, so the login cannot redirect to another site: one leading
* slash, no backslash (browsers read "/\\evil.com" as "//evil.com") and no
* control characters.
*/
/** Only local paths, so the login cannot redirect to another site. */
function safeTarget(value: string | string[] | undefined): string {
const v = Array.isArray(value) ? value[0] : value;
return v && /^\/(?![/\\])[^\\\u0000-\u001f]*$/.test(v) ? v : "/";
return v && v.startsWith("/") && !v.startsWith("//") ? v : "/";
}
async function loadConfig(): Promise<PublicConfig | null> {
-10
View File
@@ -1104,13 +1104,3 @@ span.tarot-fan-card { cursor: default; }
@media (prefers-reduced-motion: reduce) {
.tarot-flip-inner, .tarot-fan-card, .tarot-demo-text { transition: none; animation: none; }
}
/* Birth date and time: our own Hungarian fields (not the browser's date and time inputs) */
.birth-fields { border: 0; margin: 0; padding: 0; min-width: 0; }
.birth-fields legend { padding: 0; margin-bottom: 8px; }
.birth-row { display: flex; align-items: center; gap: 8px; }
.birth-year { width: 5.5em; flex: none; }
.birth-month { flex: 1 1 auto; min-width: 0; }
.birth-day { width: 5.2em; flex: none; }
.birth-time { width: 4.4em; flex: none; text-align: center; }
.birth-colon { color: var(--muted); font-weight: 600; }
+22 -137
View File
@@ -16,41 +16,6 @@ const ERRORS: Record<string, string> = {
invalid_date: "Érvénytelen dátum.",
};
const MONTHS = [
"január",
"február",
"március",
"április",
"május",
"június",
"július",
"augusztus",
"szeptember",
"október",
"november",
"december",
];
const pad = (n: number) => String(n).padStart(2, "0");
const daysIn = (year: number, month: number) => new Date(Date.UTC(year || 2000, month, 0)).getUTCDate();
/** "YYYY-MM-DD" from the three fields, or null while it is not a real date. */
function composeDate(year: string, month: string, day: string): string | null {
const y = Number(year);
const m = Number(month);
const d = Number(day);
if (!/^\d{4}$/.test(year) || y < 1000 || !m || !d || d > daysIn(y, m)) return null;
return `${year}-${pad(m)}-${pad(d)}`;
}
/** "HH:MM" from the two fields, or null while it is not a real time. */
function composeTime(hour: string, minute: string): string | null {
if (!/^\d{1,2}$/.test(hour) || !/^\d{1,2}$/.test(minute)) return null;
const h = Number(hour);
const m = Number(minute);
return h <= 23 && m <= 59 ? `${pad(h)}:${pad(m)}` : null;
}
/** Someone else's chart: added with a name, or (with `chartId`) corrected. */
export type PersonTarget = { chartId?: string; name?: string };
@@ -67,16 +32,8 @@ export function BirthForm({
onSaved: (chartId: string) => void;
}) {
const [name, setName] = useState(person?.name ?? "");
// Our own fields, not the browser's date and time inputs: those follow the
// operating system's or the browser's region (US order, AM/PM in Safari).
const [year, setYear] = useState(initial?.date?.slice(0, 4) ?? "");
const [month, setMonth] = useState(initial?.date ? String(Number(initial.date.slice(5, 7))) : "");
const [day, setDay] = useState(initial?.date ? String(Number(initial.date.slice(8, 10))) : "");
const [hour, setHour] = useState(initial?.time?.slice(0, 2) ?? "");
const [minute, setMinute] = useState(initial?.time?.slice(3, 5) ?? "");
const minuteRef = useRef<HTMLInputElement>(null);
const date = composeDate(year, month, day) ?? "";
const time = composeTime(hour, minute) ?? "";
const [date, setDate] = useState(initial?.date ?? "");
const [time, setTime] = useState(initial?.time?.slice(0, 5) ?? "");
const [timeUnknown, setTimeUnknown] = useState(initial ? !initial.time : false);
const [country, setCountry] = useState(initial?.country ?? "HU");
const [place, setPlace] = useState<Place | null>(
@@ -100,11 +57,8 @@ export function BirthForm({
e.preventDefault();
setError(null);
if (person && !name.trim()) return setError("Add meg a nevét.");
if (!year && !month && !day) return setError("Add meg a születési dátumot.");
if (!date) return setError("Ellenőrizd a dátumot: az év négy számjegy, és a nap legyen az adott hónapban.");
if (date > today) return setError("A születési dátum nem lehet a jövőben.");
if (!timeUnknown && !hour && !minute) return setError("Add meg a születési időt, vagy jelöld, hogy nem tudod.");
if (!timeUnknown && !time) return setError("Ellenőrizd az időt: óra 0–23, perc 0–59.");
if (!date) return setError("Add meg a születési dátumot.");
if (!timeUnknown && !time) return setError("Add meg a születési időt, vagy jelöld, hogy nem tudod.");
if (!place) return setError("Válaszd ki a születési helyet a listából.");
setBusy(true);
try {
@@ -166,106 +120,37 @@ export function BirthForm({
</div>
)}
<div className="grid-2">
<fieldset className="field birth-fields">
<legend className="label">Születési dátum</legend>
<div className="birth-row">
<label className="sr-only" htmlFor="birth-year">
Év
</label>
<div className="field">
<label htmlFor="birth-date">Születési dátum</label>
<input
id="birth-year"
className="inp birth-year"
inputMode="numeric"
autoComplete="bday-year"
placeholder="év"
maxLength={4}
value={year}
onChange={(e) => setYear(e.target.value.replace(/\D/g, ""))}
id="birth-date"
type="date"
className="inp"
min="1000-01-01"
max={today}
value={date}
onChange={(e) => setDate(e.target.value)}
required
/>
<label className="sr-only" htmlFor="birth-month">
Hónap
</label>
<select
id="birth-month"
className="inp birth-month"
autoComplete="bday-month"
value={month}
onChange={(e) => setMonth(e.target.value)}
>
<option value="">hónap</option>
{MONTHS.map((m, i) => (
<option key={m} value={i + 1}>
{m}
</option>
))}
</select>
<label className="sr-only" htmlFor="birth-day">
Nap
</label>
<select
id="birth-day"
className="inp birth-day"
autoComplete="bday-day"
value={day}
onChange={(e) => setDay(e.target.value)}
>
<option value="">nap</option>
{Array.from({ length: month ? daysIn(Number(year), Number(month)) : 31 }, (_, i) => (
<option key={i + 1} value={i + 1}>
{i + 1}.
</option>
))}
</select>
</div>
</fieldset>
<fieldset className="field birth-fields">
<legend className="label">Születési idő (helyi idő)</legend>
<div className="birth-row">
<label className="sr-only" htmlFor="birth-hour">
Óra
</label>
<div className="field">
<label htmlFor="birth-time">Születési idő (helyi idő)</label>
<input
id="birth-hour"
className="inp birth-time"
inputMode="numeric"
placeholder="óra"
maxLength={2}
value={timeUnknown ? "" : hour}
id="birth-time"
type="time"
className="inp"
value={timeUnknown ? "" : time}
disabled={timeUnknown}
onChange={(e) => {
const v = e.target.value.replace(/\D/g, "");
setHour(v);
setAmbiguous(false);
// Two digits (or one that cannot start a valid hour): on to the minutes.
if (v.length === 2 || (v.length === 1 && Number(v) > 2)) minuteRef.current?.focus();
}}
/>
<span className="birth-colon" aria-hidden="true">
:
</span>
<label className="sr-only" htmlFor="birth-minute">
Perc
</label>
<input
id="birth-minute"
ref={minuteRef}
className="inp birth-time"
inputMode="numeric"
placeholder="perc"
maxLength={2}
value={timeUnknown ? "" : minute}
disabled={timeUnknown}
onChange={(e) => {
setMinute(e.target.value.replace(/\D/g, ""));
setTime(e.target.value);
setAmbiguous(false);
}}
/>
</div>
<label className="check">
<input type="checkbox" checked={timeUnknown} onChange={(e) => setTimeUnknown(e.target.checked)} />
Nem tudom a születési időt
</label>
</fieldset>
</div>
</div>
<div className="grid-2">
-2
View File
@@ -334,8 +334,6 @@ impl Analyzer {
result = work => result,
() = self.superseded("analyses", job.id, job.started_at) => {
tracing::info!(id = %job.id, "analysis restarted by an admin; this attempt is dropped");
// Not ours any more: a stop must not hand it back to the queue.
self.running.lock().unwrap().remove(&job.id);
return;
}
};
@@ -111,8 +111,6 @@ impl Analyzer {
result = work => result,
() = self.superseded("questions", job.id, job.started_at) => {
tracing::info!(id = %job.id, "answer restarted by an admin; this attempt is dropped");
// Not ours any more: a stop must not hand it back to the queue.
self.running.lock().unwrap().remove(&job.id);
return;
}
};
+18 -140
View File
@@ -4,12 +4,9 @@
//! 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. The invoice request is
//! marked before it is sent: when Billingo's answer was lost, the retry finds
//! the invoice under the invoice's own partner instead of issuing a second
//! one. An invoice that was issued but could not be e-mailed still counts as
//! issued (it can be downloaded). Billingo's whole answer is kept; the PDF is
//! not (the backend fetches it when the user downloads it).
//! 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;
@@ -96,7 +93,6 @@ struct Due {
payment_method: String,
billingo_partner_id: Option<i64>,
billingo_document_id: Option<i64>,
document_requested_at: Option<OffsetDateTime>,
sent_at: Option<OffsetDateTime>,
paid_at: OffsetDateTime,
}
@@ -135,8 +131,7 @@ pub async fn run_once(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Re
AND next_attempt_at <= now() ORDER BY next_attempt_at FOR UPDATE SKIP LOCKED LIMIT 1) \
RETURNING i.id, i.attempts, i.buyer_name, i.buyer_email, i.buyer_country, i.buyer_post_code, \
i.buyer_city, i.buyer_address, i.buyer_tax_type, i.buyer_tax_number, i.item_name, i.item_comment, i.item_unit, i.gross_huf, \
i.vat_rate, i.payment_method, i.billingo_partner_id, i.billingo_document_id, \
i.document_requested_at, i.sent_at, \
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)
@@ -149,28 +144,12 @@ pub async fn run_once(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Re
}
Err(Failure::Db(e)) => return Err(e),
Err(Failure::Billingo(error)) if due.attempts >= max_attempts => {
// Issued but never e-mailed: it is still an invoice (the user downloads it).
let issued: Option<(Option<String>,)> = sqlx::query_as(
"UPDATE invoices SET status = 'issued', issued_at = now(), last_error = $2 \
WHERE id = $1 AND billingo_document_id IS NOT NULL RETURNING invoice_number",
)
.bind(due.id)
.bind(format!("issued, not e-mailed: {error}"))
.fetch_optional(db)
.await?;
match issued {
Some((number,)) => {
tracing::warn!(invoice = %due.id, number = ?number, %error, "invoice issued but not e-mailed")
}
None => {
tracing::error!(invoice = %due.id, %error, "invoice failed; an admin has to look at it");
sqlx::query("UPDATE invoices SET status = 'failed', last_error = $2 WHERE id = $1")
.bind(due.id)
.bind(&error)
.execute(db)
.await?;
}
}
done += 1;
}
Err(Failure::Billingo(error)) => {
@@ -229,13 +208,7 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
"address": due.buyer_address,
},
"emails": due.buyer_email.iter().collect::<Vec<_>>(),
// Without a tax type number (a Hungarian company with only an
// EU VAT number) the number goes into the invoice's comment.
"taxcode": if due.buyer_tax_type == "NO_TAX_NUMBER" {
String::new()
} else {
due.buyer_tax_number.clone().unwrap_or_default()
},
"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?;
@@ -273,28 +246,13 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
"vat": due.vat_rate,
"comment": due.item_comment.clone().unwrap_or_default(),
}],
"comment": document_comment(due),
"comment": if due.vat_rate == "AAM" {
"Bankkártyával kifizetve (Stripe). Alanyi adómentes."
} else {
"Bankkártyával kifizetve (Stripe)."
},
});
// An earlier attempt asked already: its invoice may exist although
// the answer never came. The partner is this invoice's own, so any
// invoice of it is ours.
let earlier = match due.document_requested_at {
Some(_) => find_document(billingo, partner).await?,
None => None,
};
let doc = match earlier {
Some(doc) => {
tracing::warn!(invoice = %due.id, number = ?doc["invoice_number"], "found the invoice of an earlier attempt");
doc
}
None => {
sqlx::query("UPDATE invoices SET document_requested_at = now() WHERE id = $1")
.bind(due.id)
.execute(db)
.await?;
billingo.call(Method::POST, "/documents", Some(&body)).await?
}
};
let 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(
@@ -335,34 +293,6 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
Ok(number.unwrap_or_default())
}
/// The invoice's comment: how it was paid, the VAT exemption, and a
/// Hungarian company's EU VAT number when it gave no domestic one.
fn document_comment(due: &Due) -> String {
let mut comment = String::from("Bankkártyával kifizetve (Stripe).");
if due.vat_rate == "AAM" {
comment.push_str(" Alanyi adómentes.");
}
if due.buyer_tax_type == "NO_TAX_NUMBER"
&& let Some(eu) = &due.buyer_tax_number
{
comment.push_str(&format!(" A vevő közösségi adószáma: {eu}."));
}
comment
}
/// The invoice already issued to `partner`, if any (an error is a failed
/// attempt: an invoice is never made without knowing there is none).
async fn find_document(billingo: &Billingo, partner: i64) -> Result<Option<Value>, Failure> {
let list = billingo
.call(reqwest::Method::GET, &format!("/documents?partner_id={partner}&type=invoice&per_page=10"), None)
.await?;
let items = list["data"].as_array().or_else(|| list.as_array()).ok_or("Billingo document list without data")?;
Ok(items
.iter()
.find(|d| d["id"].as_i64().is_some() && d["partner"]["id"].as_i64().is_none_or(|p| p == partner))
.cloned())
}
pub async fn run(db: PgPool, billingo: Billingo, max_attempts: i32, interval: Duration, stop: watch::Receiver<bool>) {
loop {
if let Err(e) = run_once(&db, &billingo, max_attempts).await {
@@ -408,10 +338,6 @@ mod tests {
send_failures: AtomicUsize,
/// Partners are refused (a permanent error).
refuse_partners: std::sync::atomic::AtomicBool,
/// The next invoice is made, but its answer is lost (an error instead).
lose_document_answer: std::sync::atomic::AtomicBool,
/// The invoices made so far, for the list.
made: std::sync::Mutex<Vec<Value>>,
}
async fn fake_billingo(fake: Arc<Fake>) -> String {
@@ -429,25 +355,13 @@ mod tests {
async fn document(State(f): State<Arc<Fake>>, Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
f.requests.lock().unwrap().push(("document".into(), body.clone()));
let n = f.documents.fetch_add(1, Ordering::SeqCst) + 1;
let doc = json!({"id": 900 + n, "invoice_number": format!("SF-2026-{n}"), "invoice_date": "2026-11-20",
(
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, "partner": {"id": body["partner_id"]},
"items": [{"name": "x", "net_amount": 6000.0, "vat_amount": 0.0, "gross_amount": 6000.0}]});
f.made.lock().unwrap().push(doc.clone());
if f.lose_document_answer.swap(false, Ordering::SeqCst) {
return (StatusCode::GATEWAY_TIMEOUT, Json(json!({"error": "timeout"})));
}
(StatusCode::CREATED, Json(doc))
}
async fn documents(
State(f): State<Arc<Fake>>,
axum::extract::Query(q): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> Json<Value> {
f.requests.lock().unwrap().push(("list".into(), json!(q)));
let partner: i64 = q.get("partner_id").and_then(|p| p.parse().ok()).unwrap_or(-1);
let data: Vec<Value> =
f.made.lock().unwrap().iter().filter(|d| d["partner"]["id"] == partner).cloned().collect();
Json(json!({"data": data, "total": data.len()}))
"gross_total": 6000.0,
"items": [{"name": "x", "net_amount": 6000.0, "vat_amount": 0.0, "gross_amount": 6000.0}]})),
)
}
async fn send(
State(f): State<Arc<Fake>>,
@@ -464,7 +378,7 @@ mod tests {
let app = Router::new()
.route("/document-blocks", get(blocks))
.route("/partners", post(partner))
.route("/documents", post(document).get(documents))
.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();
@@ -583,40 +497,4 @@ mod tests {
assert!(error.contains("422") && error.contains("invalid tax code"), "{error}");
assert_eq!(fake.documents.load(Ordering::SeqCst), 0);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_lost_answer_does_not_make_a_second_invoice(db: PgPool) {
let fake = Arc::new(Fake::default());
fake.lose_document_answer.store(true, Ordering::SeqCst);
let billingo = Billingo::new(&fake_billingo(fake.clone()).await, "key", Some(7));
let id = paid(&db, None).await;
// Billingo makes the invoice, but its answer is lost.
assert_eq!(run_once(&db, &billingo, 5).await.unwrap(), 0);
assert_eq!(state(&db, id).await.2, None);
// The retry finds it instead of making another.
sqlx::query("UPDATE invoices SET next_attempt_at = now()").execute(&db).await.unwrap();
assert_eq!(run_once(&db, &billingo, 5).await.unwrap(), 1);
let (status, number, document, sent, _) = state(&db, id).await;
assert_eq!(
(status.as_str(), number.as_deref(), document, sent),
("issued", Some("SF-2026-1"), Some(901), true)
);
assert_eq!(fake.documents.load(Ordering::SeqCst), 1);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn an_invoice_that_cannot_be_emailed_still_counts_as_issued(db: PgPool) {
let fake = Arc::new(Fake::default());
fake.send_failures.store(100, Ordering::SeqCst);
let billingo = Billingo::new(&fake_billingo(fake.clone()).await, "key", Some(7));
let id = paid(&db, None).await;
run_once(&db, &billingo, 2).await.unwrap();
sqlx::query("UPDATE invoices SET next_attempt_at = now()").execute(&db).await.unwrap();
assert_eq!(run_once(&db, &billingo, 2).await.unwrap(), 1);
let (status, number, _, sent, _) = state(&db, id).await;
assert_eq!((status.as_str(), number.as_deref(), sent), ("issued", Some("SF-2026-1"), false));
let (error,): (String,) =
sqlx::query_as("SELECT last_error FROM invoices WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
assert!(error.starts_with("issued, not e-mailed"), "{error}");
}
}