Compare commits

...
Author SHA1 Message Date
feco 810de0cb24 Merge main into prod: review fixes
CI / test (push) Successful in 1m38s
CI / build (push) Successful in 2m6s
CI / deploy (push) Successful in 52s
2026-11-20 20:43:51 +00:00
fecoandClaude Opus 5.5 4676f7860f Review fixes: no duplicate invoices, safer logins and redirects, one charge per click
CI / test (push) Successful in 1m38s
CI / build (push) Successful in 5m50s
CI / deploy (push) Skipped
Invoicing: the invoice request is marked before it goes to Billingo; a
retry after a lost answer looks the invoice up under the invoice's own
partner instead of issuing a second one. An invoice issued but never
e-mailed counts as issued (downloadable). A Hungarian company with only
an EU VAT number is invoiced without a domestic tax number, the EU
number in the comment.

Security: the login redirect takes only plain local paths (no
backslash); the waitlist rate limit and share visits use X-Real-IP,
which Caddy sets from Cloudflare's address, not the spoofable first
X-Forwarded-For entry; a Google/Apple sign-in to an unconfirmed
password account removes its password and sessions; a person's birth
data can no longer be published through a share.

Credits and jobs: analysis requests are serialized per user, so a
double click queues and pays once; a forecast analysis also fixes a
person's birth data; admins can restart stuck tarot readings; a worker
forgets an attempt an admin restarted, so a stop does not requeue it;
two people accepting one comparison invite at once get one comparison.
Expired invitations are no longer accepted by e-mail, and unsubscribing
revokes the invitation's promo codes too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 20:17:13 +00:00
17 changed files with 335 additions and 67 deletions
@@ -0,0 +1,4 @@
-- 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;
+7 -2
View File
@@ -4,7 +4,8 @@
{ {
servers { servers {
# Cloudflare ranges (https://www.cloudflare.com/ips): the visitor's # Cloudflare ranges (https://www.cloudflare.com/ips): the visitor's
# address is taken from CF-Connecting-IP and passed on in X-Forwarded-For. # address ({client_ip}) is taken from CF-Connecting-IP, only when the
# request comes from Cloudflare.
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 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 client_ip_headers CF-Connecting-IP
} }
@@ -14,7 +15,11 @@
# No basic auth any more: the site is open, and new accounts need an # No basic auth any more: the site is open, and new accounts need an
# invitation (SIGNUP_MODE=invite in the backend). # invitation (SIGNUP_MODE=invite in the backend).
encode zstd gzip encode zstd gzip
reverse_proxy frontend:3000 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}
}
} }
www.{$DOMAIN} { www.{$DOMAIN} {
+15 -3
View File
@@ -65,7 +65,11 @@ fn text(v: &Value) -> Option<String> {
impl Buyer { impl Buyer {
/// A company ("buying as a business") gives its name and tax id: a /// 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. /// 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).
pub fn from_stripe(details: &Value, fallback_email: Option<&str>) -> Self { pub fn from_stripe(details: &Value, fallback_email: Option<&str>) -> Self {
let address = &details["address"]; let address = &details["address"];
let tax_ids = details["tax_ids"].as_array().map(Vec::as_slice).unwrap_or_default(); let tax_ids = details["tax_ids"].as_array().map(Vec::as_slice).unwrap_or_default();
@@ -74,8 +78,8 @@ impl Buyer {
let country = text(&address["country"]).unwrap_or_else(|| "HU".into()).to_uppercase(); let country = text(&address["country"]).unwrap_or_else(|| "HU".into()).to_uppercase();
let tax_type = match (&tax_number, country.as_str()) { let tax_type = match (&tax_number, country.as_str()) {
(_, c) if c != "HU" => "FOREIGN", (_, c) if c != "HU" => "FOREIGN",
(Some(_), _) => "HAS_TAX_NUMBER", (Some(_), _) if tax_id("hu_tin").is_some() => "HAS_TAX_NUMBER",
(None, _) => "NO_TAX_NUMBER", _ => "NO_TAX_NUMBER",
}; };
let street = [text(&address["line1"]), text(&address["line2"])].into_iter().flatten().collect::<Vec<_>>(); let street = [text(&address["line1"]), text(&address["line2"])].into_iter().flatten().collect::<Vec<_>>();
Self { Self {
@@ -176,6 +180,14 @@ mod tests {
assert_eq!(company.email.as_deref(), Some("anna@example.com")); 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"))); 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); let abroad = Buyer::from_stripe(&json!({"name": "Anna", "address": {"country": "at"}}), None);
assert_eq!((abroad.country.as_str(), abroad.tax_type), ("AT", "FOREIGN")); assert_eq!((abroad.country.as_str(), abroad.tax_type), ("AT", "FOREIGN"));
} }
+9 -4
View File
@@ -183,6 +183,11 @@ pub(super) async fn queue(
let (model, fallback) = &crate::models::models_for(state, Kind::parse(kind).expect("known kind")).await?; 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?; 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. // Already requested for this chart/synastry: return it.
let existing: Option<AnalysisRow> = sqlx::query_as(&format!( let existing: Option<AnalysisRow> = sqlx::query_as(&format!(
"SELECT {ANALYSIS_COLUMNS} FROM analyses \ "SELECT {ANALYSIS_COLUMNS} FROM analyses \
@@ -193,7 +198,7 @@ pub(super) async fn queue(
.bind(synastry_id) .bind(synastry_id)
.bind(cache_key) .bind(cache_key)
.bind(forecast_id) .bind(forecast_id)
.fetch_optional(&state.db) .fetch_optional(&mut *tx)
.await?; .await?;
if let Some(row) = existing { if let Some(row) = existing {
return Ok((StatusCode::OK, row)); return Ok((StatusCode::OK, row));
@@ -214,7 +219,7 @@ pub(super) async fn queue(
) )
.bind(cache_key) .bind(cache_key)
.bind(prompt_version) .bind(prompt_version)
.fetch_optional(&state.db) .fetch_optional(&mut *tx)
.await?; .await?;
if let Some((content, input_tokens, output_tokens)) = cached { if let Some((content, input_tokens, output_tokens)) = cached {
let row: AnalysisRow = sqlx::query_as(&insert) let row: AnalysisRow = sqlx::query_as(&insert)
@@ -235,13 +240,13 @@ pub(super) async fn queue(
.bind(OffsetDateTime::now_utc()) .bind(OffsetDateTime::now_utc())
.bind(forecast_id) .bind(forecast_id)
.bind(fallback) .bind(fallback)
.fetch_one(&state.db) .fetch_one(&mut *tx)
.await?; .await?;
tx.commit().await?;
return Ok((StatusCode::CREATED, row)); return Ok((StatusCode::CREATED, row));
} }
// New analysis: spend a unit and queue it for the worker. // 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) let row: AnalysisRow = sqlx::query_as(&insert)
.bind(id) .bind(id)
.bind(kind) .bind(kind)
+17
View File
@@ -389,6 +389,23 @@ async fn social_login(
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?; sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
let (id, created) = match existing { let (id, created) = match existing {
Some((id,)) => { 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. // The provider has verified the address, so it counts as verified here too.
sqlx::query( sqlx::query(
"UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1", "UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1",
+3 -1
View File
@@ -342,7 +342,9 @@ async fn corrected_birth(
let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as( 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') \ "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 \ 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'), \ 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'), \
EXISTS (SELECT 1 FROM synastries WHERE (chart1_id = $1 OR chart2_id = $1) AND owner_id <> $2)", EXISTS (SELECT 1 FROM synastries WHERE (chart1_id = $1 OR chart2_id = $1) AND owner_id <> $2)",
) )
.bind(chart.id) .bind(chart.id)
+14 -10
View File
@@ -89,8 +89,8 @@ pub async fn mark_accepted(
let hash = token.map(|t| db::token_hash(t.trim())); let hash = token.map(|t| db::token_hash(t.trim()));
sqlx::query( sqlx::query(
"UPDATE invitations SET accepted_at = now(), accepted_by = $1 \ "UPDATE invitations SET accepted_at = now(), accepted_by = $1 \
WHERE accepted_at IS NULL AND revoked_at IS NULL \ WHERE accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now() \
AND (email = $2 OR (expires_at > now() AND id IN (SELECT invitation_id FROM invitation_tokens WHERE token_hash = $3)))", AND (email = $2 OR id IN (SELECT invitation_id FROM invitation_tokens WHERE token_hash = $3))",
) )
.bind(user_id) .bind(user_id)
.bind(email) .bind(email)
@@ -603,10 +603,19 @@ pub async fn unsubscribe(
.bind(db::token_hash(&email)) .bind(db::token_hash(&email))
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
sqlx::query( 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", "UPDATE invitations SET revoked_at = now() WHERE email = $1 AND accepted_at IS NULL AND revoked_at IS NULL \
RETURNING id",
) )
.bind(&email) .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) .execute(&mut *tx)
.await?; .await?;
sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(&email).execute(&mut *tx).await?; sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(&email).execute(&mut *tx).await?;
@@ -630,12 +639,7 @@ pub async fn join_waitlist(
let email = normalize_email(&req.email)?; let email = normalize_email(&req.email)?;
let locale = validate_locale(&state, req.locale.as_deref())?; 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. // Every sign-up sends an e-mail: a few per address, so the form cannot be used to flood someone.
let ip = headers let ip = super::client_ip(&headers).unwrap_or_else(|| "unknown".into());
.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}"); let key = format!("waitlist:{ip}");
state.login_limiter.check(&key)?; state.login_limiter.check(&key)?;
let token = db::new_token(); let token = db::new_token();
+7
View File
@@ -122,9 +122,16 @@ pub async fn restart(
.rows_affected() .rows_affected()
} else { } else {
let Some(row) = find_analysis(&state.db, id).await? else { continue }; 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 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 (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?; let (cache_key, prompt_version) = versions(&state, &kind, &hash, &model, &row.language).await?;
(model, fallback, cache_key, prompt_version)
};
sqlx::query( sqlx::query(
"UPDATE analyses SET status = 'pending', model = $2, fallback_model = $3, on_fallback = false, \ "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, \ cache_key = $4, prompt_version = $5, attempts = 0, next_attempt_at = now(), started_at = NULL, \
+9
View File
@@ -57,6 +57,15 @@ where
serde::Deserialize::deserialize(d).map(Some) 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 { pub fn router(state: Arc<AppState>) -> Router {
Router::new() Router::new()
.route("/healthz", get(health)) .route("/healthz", get(health))
+4 -8
View File
@@ -61,12 +61,7 @@ struct ShareRow {
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \ 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"; view_count, created_at, revoked_at, owner_ip_hash";
/// The visitor's address: the first `X-Forwarded-For` entry (Caddy writes it use super::client_ip;
/// 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. /// An address salted with the slug, so the stored value says nothing by itself.
fn ip_hash(slug: &str, ip: &str) -> Vec<u8> { fn ip_hash(slug: &str, ip: &str) -> Vec<u8> {
@@ -231,8 +226,9 @@ pub async fn revoke(State(state): St, auth: AuthUser, WithRejection(Path(id), _)
// --- public view ------------------------------------------------------------------------------- // --- public view -------------------------------------------------------------------------------
fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value { fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value {
// Birth data only of the sharer's own chart, never of a partner's. // Birth data only of the sharer's own chart, never of a partner's or of a
let show = share.show_birth_data && chart.owner_id == share.owner_id; // person they added (that is someone else's data).
let show = share.show_birth_data && chart.owner_id == share.owner_id && chart.kind == "own";
json!({ "label": chart.label, "chart": public_chart(&chart.result, show) }) json!({ "label": chart.label, "chart": public_chart(&chart.result, show) })
} }
+13 -3
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 my_chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
let inviter_chart = let inviter_chart =
find_chart(&state.db, invite.inviter_chart_id).await?.ok_or(ApiError::NotFound("invitation"))?; find_chart(&state.db, invite.inviter_chart_id).await?.ok_or(ApiError::NotFound("invitation"))?;
let (row, _) = compute_synastry(&state, invite.inviter_id, &inviter_chart, &my_chart).await?; let (row, created) = compute_synastry(&state, invite.inviter_id, &inviter_chart, &my_chart).await?;
let mut tx = state.db.begin().await?; let mut tx = state.db.begin().await?;
sqlx::query( let accepted = sqlx::query(
"UPDATE synastry_invites SET accepted_at = now(), accepted_by = $1, synastry_id = $2 \ "UPDATE synastry_invites SET accepted_at = now(), accepted_by = $1, synastry_id = $2 \
WHERE id = $3 AND accepted_at IS NULL", WHERE id = $3 AND accepted_at IS NULL",
) )
@@ -480,7 +480,17 @@ pub async fn accept_invite(
.bind(row.id) .bind(row.id)
.bind(invite.id) .bind(invite.id)
.execute(&mut *tx) .execute(&mut *tx)
.await?; .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()));
}
let inviter: Option<db::User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1")) let inviter: Option<db::User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1"))
.bind(invite.inviter_id) .bind(invite.inviter_id)
.fetch_optional(&mut *tx) .fetch_optional(&mut *tx)
+69 -4
View File
@@ -430,14 +430,31 @@ async fn google_login_creates_links_and_rejects(pool: PgPool) {
.await; .await;
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false))); assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
// an existing password account with the same address gets Google linked // an existing, confirmed password account with the same address gets Google linked
let token = app.register("anna@example.com", "Anna").await; 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 let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-2", "anna@example.com", GOOGLE_CLIENT)})) .post("/v1/auth/google", None, json!({"id_token": google_token("g-2", "anna@example.com", GOOGLE_CLIENT)}))
.await; .await;
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false))); 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"])); 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 let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-3", "x@gmail.com", "other-client")})) .post("/v1/auth/google", None, json!({"id_token": google_token("g-3", "x@gmail.com", "other-client")}))
.await; .await;
@@ -890,7 +907,7 @@ async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) {
let anna = app.register("anna@example.com", "Anna").await; let anna = app.register("anna@example.com", "Anna").await;
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await; let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
let share = json!({"kind": "chart", "target_id": chart["id"]}); let share = json!({"kind": "chart", "target_id": chart["id"]});
let home = ("x-forwarded-for", "203.0.113.7"); let home = ("x-real-ip", "203.0.113.7");
let r = app.call_with("POST", "/v1/shares", Some(&anna), Some(share), &[home]).await; let r = app.call_with("POST", "/v1/shares", Some(&anna), Some(share), &[home]).await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let visit = format!("/v1/public/shares/{}/visit", r.body["slug"].as_str().unwrap()); let visit = format!("/v1/public/shares/{}/visit", r.body["slug"].as_str().unwrap());
@@ -899,7 +916,9 @@ async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) {
let before = me().await["analyses_left"]["question"].as_i64().unwrap(); 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 // robots, a missing user agent, the sharer's address and the sharer do not count
let elsewhere = ("x-forwarded-for", "198.51.100.1, 172.70.1.1"); // 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");
for (token, headers) in [ for (token, headers) in [
(None, vec![("user-agent", "facebookexternalhit/1.1"), elsewhere]), (None, vec![("user-agent", "facebookexternalhit/1.1"), elsewhere]),
(None, vec![elsewhere]), (None, vec![elsewhere]),
@@ -1968,6 +1987,18 @@ async fn admins_restart_open_generations_with_the_current_models(pool: PgPool) {
(status.as_str(), model.as_str(), fallback, started, attempts), (status.as_str(), model.as_str(), fallback, started, attempts),
("pending", "anthropic/claude-test", None, None, 0) ("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 // finished ones are left alone
sqlx::query("UPDATE analyses SET status = 'done', content = '{}'").execute(&pool).await.unwrap(); 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); assert_eq!(app.post("/v1/admin/jobs/restart", Some(&admin), json!({})).await.body["restarted"], 0);
@@ -2174,7 +2205,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) { 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 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 admin = app.register("admin@example.com", "Admin").await;
let from = |ip: &'static str| [("x-forwarded-for", ip)]; let from = |ip: &'static str| [("x-real-ip", ip)];
// one confirmation per address, even when sent again // one confirmation per address, even when sent again
for _ in 0..2 { for _ in 0..2 {
@@ -2742,3 +2773,37 @@ async fn apple_login_can_be_off(pool: PgPool) {
.await; .await;
assert_eq!(r.status, StatusCode::FORBIDDEN); 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,8 +28,10 @@ async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[]
const value = req.headers.get(name); const value = req.headers.get(name);
if (value) headers.set(name, value); if (value) headers.set(name, value);
} }
const forwardedFor = req.headers.get("x-forwarded-for"); // The visitor's address as Caddy set it (from Cloudflare's CF-Connecting-IP,
if (forwardedFor) headers.set("x-forwarded-for", forwardedFor); // overwriting any the browser sent).
const realIp = req.headers.get("x-real-ip");
if (realIp) headers.set("x-real-ip", realIp);
let res: Response; let res: Response;
try { try {
+6 -2
View File
@@ -13,10 +13,14 @@ import { GoogleLogin } from "./GoogleLogin";
export const metadata: Metadata = { title: "Belépés" }; export const metadata: Metadata = { title: "Belépés" };
/** Only local paths, so the login cannot redirect to another site. */ /**
* 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.
*/
function safeTarget(value: string | string[] | undefined): string { function safeTarget(value: string | string[] | undefined): string {
const v = Array.isArray(value) ? value[0] : value; const v = Array.isArray(value) ? value[0] : value;
return v && v.startsWith("/") && !v.startsWith("//") ? v : "/"; return v && /^\/(?![/\\])[^\\\u0000-\u001f]*$/.test(v) ? v : "/";
} }
async function loadConfig(): Promise<PublicConfig | null> { async function loadConfig(): Promise<PublicConfig | null> {
+2
View File
@@ -334,6 +334,8 @@ impl Analyzer {
result = work => result, result = work => result,
() = self.superseded("analyses", job.id, job.started_at) => { () = self.superseded("analyses", job.id, job.started_at) => {
tracing::info!(id = %job.id, "analysis restarted by an admin; this attempt is dropped"); 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; return;
} }
}; };
@@ -111,6 +111,8 @@ impl Analyzer {
result = work => result, result = work => result,
() = self.superseded("questions", job.id, job.started_at) => { () = self.superseded("questions", job.id, job.started_at) => {
tracing::info!(id = %job.id, "answer restarted by an admin; this attempt is dropped"); 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; return;
} }
}; };
+140 -18
View File
@@ -4,9 +4,12 @@
//! the item as they go on the invoice. This job takes the due rows and, step //! 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, //! 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 //! 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 //! the next one, so a retry continues where it stopped. The invoice request is
//! second invoice. Billingo's whole answer is kept; the PDF is not (the //! marked before it is sent: when Billingo's answer was lost, the retry finds
//! backend fetches it when the user downloads it). //! the invoice under the invoice's own partner instead of issuing a second
//! one. An invoice that was issued but could not be e-mailed still counts as
//! issued (it can be downloaded). Billingo's whole answer is kept; the PDF is
//! not (the backend fetches it when the user downloads it).
use std::time::Duration; use std::time::Duration;
@@ -93,6 +96,7 @@ struct Due {
payment_method: String, payment_method: String,
billingo_partner_id: Option<i64>, billingo_partner_id: Option<i64>,
billingo_document_id: Option<i64>, billingo_document_id: Option<i64>,
document_requested_at: Option<OffsetDateTime>,
sent_at: Option<OffsetDateTime>, sent_at: Option<OffsetDateTime>,
paid_at: OffsetDateTime, paid_at: OffsetDateTime,
} }
@@ -131,7 +135,8 @@ pub async fn run_once(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Re
AND next_attempt_at <= now() ORDER BY next_attempt_at FOR UPDATE SKIP LOCKED LIMIT 1) \ 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, \ 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.buyer_city, i.buyer_address, i.buyer_tax_type, i.buyer_tax_number, i.item_name, i.item_comment, i.item_unit, i.gross_huf, \
i.vat_rate, i.payment_method, i.billingo_partner_id, i.billingo_document_id, i.sent_at, \ i.vat_rate, i.payment_method, i.billingo_partner_id, i.billingo_document_id, \
i.document_requested_at, i.sent_at, \
coalesce(c.completed_at, i.created_at) AS paid_at" coalesce(c.completed_at, i.created_at) AS paid_at"
)) ))
.fetch_optional(db) .fetch_optional(db)
@@ -144,12 +149,28 @@ pub async fn run_once(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Re
} }
Err(Failure::Db(e)) => return Err(e), Err(Failure::Db(e)) => return Err(e),
Err(Failure::Billingo(error)) if due.attempts >= max_attempts => { 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"); 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") sqlx::query("UPDATE invoices SET status = 'failed', last_error = $2 WHERE id = $1")
.bind(due.id) .bind(due.id)
.bind(&error) .bind(&error)
.execute(db) .execute(db)
.await?; .await?;
}
}
done += 1; done += 1;
} }
Err(Failure::Billingo(error)) => { Err(Failure::Billingo(error)) => {
@@ -208,7 +229,13 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
"address": due.buyer_address, "address": due.buyer_address,
}, },
"emails": due.buyer_email.iter().collect::<Vec<_>>(), "emails": due.buyer_email.iter().collect::<Vec<_>>(),
"taxcode": due.buyer_tax_number.clone().unwrap_or_default(), // Without a tax type number (a Hungarian company with only an
// EU VAT number) the number goes into the invoice's comment.
"taxcode": if due.buyer_tax_type == "NO_TAX_NUMBER" {
String::new()
} else {
due.buyer_tax_number.clone().unwrap_or_default()
},
"tax_type": due.buyer_tax_type, "tax_type": due.buyer_tax_type,
}); });
let partner = billingo.call(Method::POST, "/partners", Some(&body)).await?; let partner = billingo.call(Method::POST, "/partners", Some(&body)).await?;
@@ -246,13 +273,28 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
"vat": due.vat_rate, "vat": due.vat_rate,
"comment": due.item_comment.clone().unwrap_or_default(), "comment": due.item_comment.clone().unwrap_or_default(),
}], }],
"comment": if due.vat_rate == "AAM" { "comment": document_comment(due),
"Bankkártyával kifizetve (Stripe). Alanyi adómentes."
} else {
"Bankkártyával kifizetve (Stripe)."
},
}); });
let doc = billingo.call(Method::POST, "/documents", Some(&body)).await?; // An earlier attempt asked already: its invoice may exist although
// the answer never came. The partner is this invoice's own, so any
// invoice of it is ours.
let earlier = match due.document_requested_at {
Some(_) => find_document(billingo, partner).await?,
None => None,
};
let doc = match earlier {
Some(doc) => {
tracing::warn!(invoice = %due.id, number = ?doc["invoice_number"], "found the invoice of an earlier attempt");
doc
}
None => {
sqlx::query("UPDATE invoices SET document_requested_at = now() WHERE id = $1")
.bind(due.id)
.execute(db)
.await?;
billingo.call(Method::POST, "/documents", Some(&body)).await?
}
};
let id = doc["id"].as_i64().ok_or("Billingo invoice without id")?; let id = doc["id"].as_i64().ok_or("Billingo invoice without id")?;
let item = &doc["items"][0]; let item = &doc["items"][0];
sqlx::query( sqlx::query(
@@ -293,6 +335,34 @@ async fn issue(db: &PgPool, billingo: &Billingo, due: &Due) -> Result<String, Fa
Ok(number.unwrap_or_default()) 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>) { pub async fn run(db: PgPool, billingo: Billingo, max_attempts: i32, interval: Duration, stop: watch::Receiver<bool>) {
loop { loop {
if let Err(e) = run_once(&db, &billingo, max_attempts).await { if let Err(e) = run_once(&db, &billingo, max_attempts).await {
@@ -338,6 +408,10 @@ mod tests {
send_failures: AtomicUsize, send_failures: AtomicUsize,
/// Partners are refused (a permanent error). /// Partners are refused (a permanent error).
refuse_partners: std::sync::atomic::AtomicBool, 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 { async fn fake_billingo(fake: Arc<Fake>) -> String {
@@ -355,13 +429,25 @@ mod tests {
async fn document(State(f): State<Arc<Fake>>, Json(body): Json<Value>) -> (StatusCode, Json<Value>) { async fn document(State(f): State<Arc<Fake>>, Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
f.requests.lock().unwrap().push(("document".into(), body.clone())); f.requests.lock().unwrap().push(("document".into(), body.clone()));
let n = f.documents.fetch_add(1, Ordering::SeqCst) + 1; 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"], "fulfillment_date": body["fulfillment_date"], "due_date": body["due_date"],
"gross_total": 6000.0, "gross_total": 6000.0, "partner": {"id": body["partner_id"]},
"items": [{"name": "x", "net_amount": 6000.0, "vat_amount": 0.0, "gross_amount": 6000.0}]})), "items": [{"name": "x", "net_amount": 6000.0, "vat_amount": 0.0, "gross_amount": 6000.0}]});
) f.made.lock().unwrap().push(doc.clone());
if f.lose_document_answer.swap(false, Ordering::SeqCst) {
return (StatusCode::GATEWAY_TIMEOUT, Json(json!({"error": "timeout"})));
}
(StatusCode::CREATED, Json(doc))
}
async fn documents(
State(f): State<Arc<Fake>>,
axum::extract::Query(q): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> Json<Value> {
f.requests.lock().unwrap().push(("list".into(), json!(q)));
let partner: i64 = q.get("partner_id").and_then(|p| p.parse().ok()).unwrap_or(-1);
let data: Vec<Value> =
f.made.lock().unwrap().iter().filter(|d| d["partner"]["id"] == partner).cloned().collect();
Json(json!({"data": data, "total": data.len()}))
} }
async fn send( async fn send(
State(f): State<Arc<Fake>>, State(f): State<Arc<Fake>>,
@@ -378,7 +464,7 @@ mod tests {
let app = Router::new() let app = Router::new()
.route("/document-blocks", get(blocks)) .route("/document-blocks", get(blocks))
.route("/partners", post(partner)) .route("/partners", post(partner))
.route("/documents", post(document)) .route("/documents", post(document).get(documents))
.route("/documents/{id}/send", post(send)) .route("/documents/{id}/send", post(send))
.with_state(fake); .with_state(fake);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -497,4 +583,40 @@ mod tests {
assert!(error.contains("422") && error.contains("invalid tax code"), "{error}"); assert!(error.contains("422") && error.contains("invalid tax code"), "{error}");
assert_eq!(fake.documents.load(Ordering::SeqCst), 0); 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}");
}
} }