worker: Telegram notice about every purchase (notify task)
CI / test (push) Successful in 1m49s
CI / build (push) Successful in 8m27s
CI / deploy (push) Skipped

A separate worker task, apart from invoicing: each paid checkout is
announced once to the operator's Telegram chat ('Páros csomag, 6 000 Ft',
marked when it was a test payment), without the buyer's data. Outages
and rate limits are retried; a wrong token or chat is logged, not
retried. Needs TELEGRAM_BOT_TOKEN (.env.secrets) and TELEGRAM_CHAT_ID.

Also fixes the worker test that still expected the old sign-up e-mail
subject (CI failed on it since 7d6a6c3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-21 19:04:20 +00:00
co-authored by Claude Opus 5.5
parent 55048ed828
commit a571abdb65
10 changed files with 294 additions and 7 deletions
+176
View File
@@ -0,0 +1,176 @@
//! The `notify` task: a Telegram notice to the operator about every paid
//! checkout ("Páros csomag, 6 000 Ft"), once. It runs on its own, apart from
//! invoicing, and carries no personal data of the buyer.
//!
//! A purchase counts as notified when Telegram took the message, or refused
//! it for good (a wrong token or chat: logged as an error); after an outage
//! or a rate limit it is tried again on the next round.
use std::time::Duration;
use sqlx::PgPool;
use tokio::sync::watch;
use crate::telegram::{Telegram, huf};
/// At most this many notices a round.
const BATCH: i64 = 20;
/// The notice of one purchase.
fn text(item: &str, price_huf: i32, live: bool) -> String {
// The invoice item without its service prefix ("Online tartalomszolgáltatás – ").
let item = item.rsplit(" – ").next().unwrap_or(item);
format!("🛒 Vásárlás: {item}, {}{}", huf(price_huf), if live { "" } else { " (teszt fizetés)" })
}
/// Sends the notices of the purchases not notified yet; returns how many went out.
pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result<usize, sqlx::Error> {
let mut tx = db.begin().await?;
let due: Vec<(String, String, i32, bool)> = sqlx::query_as(
"SELECT c.id, coalesce(i.item_name, c.package), coalesce(c.amount_huf, c.price_huf), c.live \
FROM stripe_checkouts c LEFT JOIN invoices i ON i.checkout_id = c.id \
WHERE c.completed_at IS NOT NULL AND c.notified_at IS NULL \
ORDER BY c.completed_at LIMIT $1 FOR UPDATE OF c SKIP LOCKED",
)
.bind(BATCH)
.fetch_all(&mut *tx)
.await?;
let mut sent = 0;
for (id, item, price, live) in due {
match telegram.send(&text(&item, price, live)).await {
Ok(()) => sent += 1,
Err(e) if e.permanent => {
tracing::error!(checkout = %id, error = %e.message, "telegram refused the purchase notice; check TELEGRAM_*");
}
Err(e) => {
tracing::warn!(checkout = %id, error = %e.message, "purchase notice not sent yet");
break;
}
}
sqlx::query("UPDATE stripe_checkouts SET notified_at = now() WHERE id = $1")
.bind(&id)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(sent)
}
pub async fn run(db: PgPool, telegram: Telegram, interval: Duration, stop: watch::Receiver<bool>) {
loop {
if let Err(e) = run_once(&db, &telegram).await {
tracing::error!(error = %e, "purchase notices");
}
tokio::select! {
() = tokio::time::sleep(interval) => {}
() = crate::stopped(stop.clone()) => break,
}
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use axum::extract::State;
use axum::http::StatusCode;
use axum::routing::post;
use axum::{Json, Router};
use serde_json::Value;
use super::*;
#[derive(Default)]
struct Fake {
messages: Mutex<Vec<Value>>,
/// The answer to give; `None`: 200.
status: Mutex<Option<StatusCode>>,
}
async fn fake_telegram(fake: Arc<Fake>) -> String {
async fn send(State(f): State<Arc<Fake>>, Json(body): Json<Value>) -> StatusCode {
let status = *f.status.lock().unwrap();
if status.is_none() {
f.messages.lock().unwrap().push(body);
}
status.unwrap_or(StatusCode::OK)
}
let app = Router::new().route("/botTOKEN/sendMessage", post(send)).with_state(fake);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
async fn checkout(db: &PgPool, package: &str, price: i32, live: bool, paid: bool) -> String {
let id = format!("cs_{}", uuid::Uuid::now_v7());
sqlx::query(
"INSERT INTO stripe_checkouts (id, package, price_huf, live, completed_at) \
VALUES ($1, $2, $3, $4, CASE WHEN $5 THEN now() END)",
)
.bind(&id)
.bind(package)
.bind(price)
.bind(live)
.bind(paid)
.execute(db)
.await
.unwrap();
id
}
#[test]
fn notice_texts() {
assert_eq!(
text("Online tartalomszolgáltatás – Páros csomag", 6000, true),
"🛒 Vásárlás: Páros csomag, 6\u{a0}000\u{a0}Ft"
);
assert_eq!(
text("addon_questions", 1000, false),
"🛒 Vásárlás: addon_questions, 1\u{a0}000\u{a0}Ft (teszt fizetés)"
);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn each_purchase_is_announced_once(db: PgPool) {
let fake = Arc::new(Fake::default());
let telegram = Telegram::new(&fake_telegram(fake.clone()).await, "TOKEN", "42");
let paid = checkout(&db, "couple", 6000, false, true).await;
sqlx::query(
"INSERT INTO invoices (id, checkout_id, buyer_name, buyer_country, buyer_post_code, buyer_city, \
buyer_address, buyer_tax_type, item_name, gross_huf, net_huf, vat_huf) \
VALUES ($1, $2, 'Anna', 'HU', '6720', 'Szeged', 'Fő utca 1.', 'NO_TAX_NUMBER', \
'Online tartalomszolgáltatás – Páros csomag', 6000, 6000, 0)",
)
.bind(uuid::Uuid::now_v7())
.bind(&paid)
.execute(&db)
.await
.unwrap();
checkout(&db, "single", 2000, true, false).await; // not paid (yet)
// An outage: nothing is lost, it comes on the next round.
*fake.status.lock().unwrap() = Some(StatusCode::BAD_GATEWAY);
assert_eq!(run_once(&db, &telegram).await.unwrap(), 0);
*fake.status.lock().unwrap() = None;
assert_eq!(run_once(&db, &telegram).await.unwrap(), 1);
assert_eq!(run_once(&db, &telegram).await.unwrap(), 0);
let messages = fake.messages.lock().unwrap().clone();
assert_eq!(messages.len(), 1);
assert_eq!(messages[0]["chat_id"], "42");
assert_eq!(messages[0]["text"], "🛒 Vásárlás: Páros csomag, 6\u{a0}000\u{a0}Ft (teszt fizetés)");
assert!(!messages[0]["text"].as_str().unwrap().contains("Anna"), "no personal data");
// A wrong chat is not retried for ever.
checkout(&db, "addon_questions", 1000, true, true).await;
*fake.status.lock().unwrap() = Some(StatusCode::BAD_REQUEST);
assert_eq!(run_once(&db, &telegram).await.unwrap(), 0);
let left: i64 = sqlx::query_scalar(
"SELECT count(*) FROM stripe_checkouts WHERE completed_at IS NOT NULL AND notified_at IS NULL",
)
.fetch_one(&db)
.await
.unwrap();
assert_eq!(left, 0);
}
}