Gift packages: buy a main package for someone, with a printable gift card

- /ajandek: the package, whom it is for and from whom, the recipient's
  address typed twice (or "I hand it over"), a message; paid on Stripe
  like any package, the invoice is the buyer's
- On payment the gift gets its own code (not a promo code: it cannot be
  withdrawn, and it adds the whole package); redeemed on /bevaltas
- The recipient's e-mail carries the message and the code, with the gift
  card attached as a PDF; the buyer's confirmation says it was a gift
- /ajandekaim: codes, state, the card to download, sending it by e-mail
  (again, or to another address) up to three times
- crates/gift-card draws the A4 card (example chart, questions avatar,
  QR code) as SVG and makes a PDF with krilla, fonts compiled in; the
  backend draws downloads on a blocking thread, the worker the e-mails
- Telegram notices say "(ajándék)"; unpaid gifts go after a week

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-23 20:28:11 +00:00
co-authored by Claude Opus 5.5
parent 699ce2abbd
commit c90232f40c
46 changed files with 3647 additions and 88 deletions
+1
View File
@@ -10,6 +10,7 @@ publish.workspace = true
db.workspace = true
analysis-prompt.workspace = true
email-templates.workspace = true
gift-card.workspace = true
service-kit.workspace = true
anyhow.workspace = true
axum.workspace = true
+4 -1
View File
@@ -8,7 +8,7 @@ use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows.
const STATEMENTS: [(&str, &str); 7] = [
const STATEMENTS: [(&str, &str); 8] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support.
@@ -27,6 +27,9 @@ const STATEMENTS: [(&str, &str); 7] = [
),
("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
("generation_errors", "DELETE FROM generation_errors WHERE created_at < now() - interval '90 days'"),
// Gifts never paid (Stripe's payment page is long closed by then), with
// the recipient's address in them.
("gifts", "DELETE FROM gifts WHERE paid_at IS NULL AND created_at < now() - interval '7 days'"),
];
pub async fn run_once(db: &PgPool) -> Result<Vec<(&'static str, u64)>, sqlx::Error> {
+72 -7
View File
@@ -3,11 +3,14 @@
//! New rows wake the job at once (`NOTIFY email_outbox`, see migration 0002);
//! a slow poll picks up retries. Rows are claimed with `FOR UPDATE SKIP LOCKED`,
//! so several workers can run side by side. Delivery is at-least-once.
//!
//! An e-mail whose payload has a `gift_card` gets the gift card as a PDF
//! attachment, drawn here (it is not stored anywhere).
use std::time::Duration;
use lettre::message::header::{Header, HeaderName, HeaderValue};
use lettre::message::{Mailbox, MultiPart};
use lettre::message::header::{ContentType, Header, HeaderName, HeaderValue};
use lettre::message::{Attachment, Mailbox, MultiPart};
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use serde_json::Value;
use sqlx::PgPool;
@@ -60,7 +63,14 @@ impl Mailer {
Ok(Mailer::Smtp(transport))
}
async fn send(&self, id: Uuid, from: &Mailbox, to: &str, mail: &Rendered) -> Result<(), SendError> {
async fn send(
&self,
id: Uuid,
from: &Mailbox,
to: &str,
mail: &Rendered,
attachment: Option<&Pdf>,
) -> Result<(), SendError> {
let to_mailbox: Mailbox = to.parse().map_err(SendError::permanent)?;
// A Message-ID on our own domain (lettre would use the container's
// host name, which spam filters dislike); the same on every retry.
@@ -72,9 +82,15 @@ impl Mailer {
if let Some(url) = &mail.unsubscribe_post_url {
builder = builder.header(ListUnsubscribe(url.clone())).header(ListUnsubscribePost);
}
let message = builder
.multipart(MultiPart::alternative_plain_html(mail.text.clone(), mail.html.clone()))
.map_err(SendError::permanent)?;
let body = MultiPart::alternative_plain_html(mail.text.clone(), mail.html.clone());
let body = match attachment {
Some(pdf) => MultiPart::mixed().multipart(body).singlepart(
Attachment::new(pdf.filename.clone())
.body(pdf.bytes.clone(), ContentType::parse("application/pdf").expect("a content type")),
),
None => body,
};
let message = builder.multipart(body).map_err(SendError::permanent)?;
match self {
Mailer::Smtp(transport) => transport
.send(message)
@@ -94,6 +110,52 @@ impl Mailer {
}
}
/// A PDF to attach.
pub struct Pdf {
pub filename: String,
pub bytes: Vec<u8>,
}
/// The gift card of a payload's `gift_card`, if it has one. A card that
/// cannot be drawn is logged, and the e-mail goes without it (the code is in
/// the text too).
async fn gift_card(id: Uuid, payload: &Value) -> Option<Pdf> {
let card = payload.get("gift_card").filter(|c| c.is_object())?.clone();
let drawn = tokio::task::spawn_blocking(move || {
let text = |k: &str| card[k].as_str().map(str::to_owned);
let contents: Vec<String> =
card["contents"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_owned)).collect();
let (Some(package), Some(code), Some(url)) = (text("package"), text("code"), text("redeem_url")) else {
return Err("the gift card has no package, code or link".to_string());
};
let (to, from, message) = (text("recipient_name"), text("from_name"), text("message"));
let bytes = gift_card::pdf(&gift_card::Card {
package: &package,
contents: &contents,
code: &code,
redeem_url: &url,
recipient_name: to.as_deref(),
from_name: from.as_deref(),
message: message.as_deref(),
})
.map_err(|e| e.to_string())?;
let code: String = code.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
Ok(Pdf { filename: format!("sorsfonalak-ajandek-{code}.pdf"), bytes })
})
.await;
match drawn {
Ok(Ok(pdf)) => Some(pdf),
Ok(Err(e)) => {
tracing::error!(%id, error = %e, "gift card not drawn; the e-mail goes without it");
None
}
Err(e) => {
tracing::error!(%id, error = %e, "gift card not drawn; the e-mail goes without it");
None
}
}
}
/// `List-Unsubscribe: <url>`: mail clients show an unsubscribe button.
#[derive(Clone)]
struct ListUnsubscribe(String);
@@ -169,7 +231,10 @@ impl Delivery {
for row in &rows {
let attempts = row.attempts + 1;
let result = match templates::render(&row.template, &row.locale, &row.payload) {
Ok(mail) => self.mailer.send(row.id, &self.from, &row.to_email, &mail).await,
Ok(mail) => {
let pdf = gift_card(row.id, &row.payload).await;
self.mailer.send(row.id, &self.from, &row.to_email, &mail, pdf.as_ref()).await
}
Err(e) => Err(SendError::permanent(e)),
};
match result {
+20 -9
View File
@@ -17,20 +17,26 @@ use crate::telegram::{Telegram, huf};
const BATCH: i64 = 20;
/// The notice of one purchase.
fn text(item: &str, package: &str, price_huf: i32, live: bool) -> String {
fn text(item: &str, package: &str, price_huf: i32, live: bool, gift: bool) -> String {
// The invoice item without its service prefix ("Online tartalomszolgáltatás – ").
let item = item.rsplit(" – ").next().unwrap_or(item);
// The add-ons share one neutral invoice name; their id tells them apart.
let what =
if package.starts_with("addon_") && item != package { format!("{item} ({package})") } else { item.into() };
format!("🛒 Vásárlás: {what}, {}{}", huf(price_huf), if live { "" } else { " (teszt fizetés)" })
format!(
"🛒 Vásárlás: {what}{}, {}{}",
if gift { " (ajándék)" } else { "" },
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, String, i32, bool)> = sqlx::query_as(
"SELECT c.id, coalesce(i.item_name, c.package), c.package, coalesce(c.amount_huf, c.price_huf), c.live \
let due: Vec<(String, String, String, i32, bool, bool)> = sqlx::query_as(
"SELECT c.id, coalesce(i.item_name, c.package), c.package, coalesce(c.amount_huf, c.price_huf), c.live, \
c.gift_id IS NOT NULL \
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",
@@ -39,8 +45,8 @@ pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result<usize, sqlx::E
.fetch_all(&mut *tx)
.await?;
let mut sent = 0;
for (id, item, package, price, live) in due {
match telegram.send(&text(&item, &package, price, live)).await {
for (id, item, package, price, live, gift) in due {
match telegram.send(&text(&item, &package, price, live, gift)).await {
Ok(()) => sent += 1,
Err(e) if e.permanent => {
tracing::error!(checkout = %id, error = %e.message, "telegram refused the purchase notice; check TELEGRAM_*");
@@ -125,17 +131,22 @@ mod tests {
#[test]
fn notice_texts() {
assert_eq!(
text("Online tartalomszolgáltatás – Páros csomag", "couple", 6000, true),
text("Online tartalomszolgáltatás – Páros csomag", "couple", 6000, true, false),
"🛒 Vásárlás: Páros csomag, 6\u{a0}000\u{a0}Ft"
);
// Bought for someone else.
assert_eq!(
text("Online tartalomszolgáltatás – Család csomag", "family", 11000, true, true),
"🛒 Vásárlás: Család csomag (ajándék), 11\u{a0}000\u{a0}Ft"
);
// The add-ons share one invoice name: the id says which one it was.
assert_eq!(
text("Online tartalomszolgáltatás – kiegészítő csomag", "addon_tarot", 1000, true),
text("Online tartalomszolgáltatás – kiegészítő csomag", "addon_tarot", 1000, true, false),
"🛒 Vásárlás: kiegészítő csomag (addon_tarot), 1\u{a0}000\u{a0}Ft"
);
// No invoice yet: the id alone.
assert_eq!(
text("addon_questions", "addon_questions", 1000, false),
text("addon_questions", "addon_questions", 1000, false, false),
"🛒 Vásárlás: addon_questions, 1\u{a0}000\u{a0}Ft (teszt fizetés)"
);
}
+61 -1
View File
@@ -153,6 +153,48 @@ async fn invitation_headers_for_spam_filters(db: PgPool) {
assert!(raw.contains("multipart/alternative") && raw.contains("text/plain") && raw.contains("text/html"));
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn gift_e_mails_carry_the_gift_card(db: PgPool) {
let card = json!({
"package": "Páros", "contents": ["2 részletes képletelemzés", "3 kérdés"], "code": "ABCD-EFGH-JKMN",
"redeem_url": "https://example.com/bevaltas?kod=ABCD-EFGH-JKMN", "recipient_name": "Bea", "from_name": "Ági",
"message": "Boldog szülinapot!",
});
for (to, template, card) in [
("bea@example.com", "gift_package", card.clone()),
// A broken card: the e-mail still goes, without it.
("cili@example.com", "gift_package", json!({"package": "Páros"})),
] {
sqlx::query("INSERT INTO email_outbox (id, to_email, template, locale, payload) VALUES ($1, $2, $3, 'hu', $4)")
.bind(Uuid::now_v7())
.bind(to)
.bind(template)
.bind(json!({
"url": "https://example.com/bevaltas?kod=ABCD-EFGH-JKMN", "package_name": "Páros",
"contents": "2 részletes képletelemzés, 3 kérdés", "promo_code": "ABCD-EFGH-JKMN",
"from_name": "Ági", "message": "Boldog szülinapot!", "gift_card": card,
}))
.execute(&db)
.await
.unwrap();
}
queue(&db, "anna@example.com", "verify_email").await;
let d = delivery(db.clone(), vec![]);
assert_eq!(d.deliver_due().await.unwrap(), 3);
let Mailer::Memory { sent, .. } = &d.mailer else { unreachable!() };
let sent = sent.lock().unwrap();
let raw = |to: &str| sent.iter().find(|(t, _, _)| t == to).unwrap().2.clone();
let bea = raw("bea@example.com");
assert!(bea.contains("multipart/mixed") && bea.contains("multipart/alternative"), "{bea}");
assert!(bea.contains("Content-Type: application/pdf"));
assert!(bea.contains("sorsfonalak-ajandek-ABCD-EFGH-JKMN.pdf"), "{}", &bea[..bea.find("JVBERi0").unwrap_or(0)]);
// The PDF itself, base64 ("%PDF-" is "JVBERi0").
assert!(bea.contains("JVBERi0"));
for plain in [raw("cili@example.com"), raw("anna@example.com")] {
assert!(!plain.contains("application/pdf") && !plain.contains("multipart/mixed"));
}
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn concurrent_workers_do_not_send_twice(db: PgPool) {
for i in 0..15 {
@@ -203,6 +245,21 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
.await
.unwrap();
sqlx::query("UPDATE email_outbox SET sent_at = now() WHERE id = $1").bind(recent).execute(&db).await.unwrap();
// Gifts: one never paid (gone after a week), one just started, one paid long ago.
let gifts = [("8 days", false), ("1 hour", false), ("30 days", true)].map(|g| (Uuid::now_v7(), g));
for (id, (age, paid)) in &gifts {
sqlx::query(
"INSERT INTO gifts (id, package, recipient_email, created_at, paid_at, code) \
VALUES ($1, 'couple', 'bea@example.com', now() - $2::interval, CASE WHEN $3 THEN now() END, \
CASE WHEN $3 THEN 'ABCDEFGHJKMN' END)",
)
.bind(id)
.bind(age)
.bind(paid)
.execute(&db)
.await
.unwrap();
}
let deleted = crate::cleanup::run_once(&db).await.unwrap();
assert_eq!(
@@ -214,9 +271,12 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
("invites", 0),
("invitations", 0),
("prompt_previews", 0),
("generation_errors", 0)
("generation_errors", 0),
("gifts", 1),
]
);
let kept: Vec<Uuid> = sqlx::query_scalar("SELECT id FROM gifts ORDER BY id").fetch_all(&db).await.unwrap();
assert_eq!(kept, vec![gifts[1].0, gifts[2].0]);
let (left,): (Vec<Uuid>,) =
sqlx::query_as("SELECT array_agg(id ORDER BY id) FROM email_outbox").fetch_one(&db).await.unwrap();
assert_eq!(left, vec![recent, unsent]);