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:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user