//! 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 { 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) { 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>, /// The answer to give; `None`: 200. status: Mutex>, } async fn fake_telegram(fake: Arc) -> String { async fn send(State(f): State>, Json(body): Json) -> 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); } }