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
+240 -8
View File
@@ -51,6 +51,8 @@ struct Content {
quote: Option<String>,
/// A short list after the intro, with its heading.
points: Option<(&'static str, Vec<&'static str>)>,
/// A code to type in, shown large in a box, with its label.
code: Option<(&'static str, String)>,
button: &'static str,
url: String,
note: String,
@@ -76,6 +78,7 @@ impl Content {
reason: None,
unsubscribe: None,
unsubscribe_post_url: None,
code: None,
}
}
}
@@ -178,6 +181,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
("waitlist_joined", _) => waitlist_joined(lang, payload, url)?,
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
("gift", _) => gift(lang, payload, url)?,
("gift_package", _) => gift_package(lang, payload, url)?,
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
};
Ok(content.render(lang))
@@ -253,6 +257,7 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
}),
unsubscribe: Some(("Nem kérek több meghívót", unsubscribe_url)),
unsubscribe_post_url: Some(unsubscribe_post_url),
code: None,
},
Lang::En => Content {
subject: match &inviter {
@@ -287,6 +292,7 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
}),
unsubscribe: Some(("No more invitations, please", unsubscribe_url)),
unsubscribe_post_url: Some(unsubscribe_post_url),
code: None,
},
})
}
@@ -320,20 +326,30 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
(false, Some(n)) => format!("Hi {n},"),
(false, None) => "Hi,".to_owned(),
};
Ok(match lang {
Lang::Hu => Content {
// A package bought as a gift: its code, and where it went (none: the
// buyer hands it over, the card is attached).
let gift = payload["gift"].is_object().then(|| {
let code = clean_code(&payload["gift"]["promo_code"]);
let to = payload["gift"]["recipient_email"]
.as_str()
.map(|e| e.chars().filter(|c| !c.is_control()).take(254).collect::<String>());
let whom = name(&payload["gift"], "recipient_name");
(code, to, whom)
});
let contents_hu = contents.as_ref().map(|c| format!(" Tartalma: {c}.")).unwrap_or_default();
let contents_en = contents.as_ref().map(|c| format!(" It contains: {c}.")).unwrap_or_default();
Ok(match (lang, gift) {
(Lang::Hu, None) => Content {
subject: format!("Köszönjük a vásárlást: {package}"),
preheader: Some(format!("A(z) {package} csomag a tiéd.")),
greeting: greeting(true),
intro: format!(
"Megkaptuk a fizetésed ({amount}, {paid_on}), és jóváírtuk a(z) „{package}” csomagot.{}",
contents.map(|c| format!(" Tartalma: {c}.")).unwrap_or_default()
),
intro: format!("Megkaptuk a fizetésed ({amount}, {paid_on}), és jóváírtuk a(z) „{package}” csomagot.{contents_hu}"),
quote: Some(
"A fizetés előtt kérted a szolgáltatás azonnali megkezdését, és tudomásul vetted, hogy ezzel elveszíted a 14 napos elállási jogodat. A csomagot ennek megfelelően azonnal teljesítettük."
.into(),
),
points: None,
code: None,
button: "Megnézem a csomagjaimat",
url,
note: format!(
@@ -343,7 +359,37 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
unsubscribe: None,
unsubscribe_post_url: None,
},
Lang::En => Content {
(Lang::Hu, Some((code, to, whom))) => Content {
subject: format!("Köszönjük a vásárlást: {package} (ajándék)"),
preheader: Some(match &to {
Some(e) => format!("Az ajándékot elküldtük ide: {e}."),
None => "Az ajándékutalványt csatoltuk ehhez a levélhez.".into(),
}),
greeting: greeting(true),
intro: format!(
"Megkaptuk a fizetésed ({amount}, {paid_on}): a(z) „{package}” csomagot ajándékba vetted{}.{contents_hu} {}",
whom.as_ref().map(|w| format!(" {w} részére")).unwrap_or_default(),
match &to {
Some(e) => format!("Az ajándékkódot az utalvánnyal együtt elküldtük ide: {e}. Ha nem e-mailben adnád át, az Ajándékaim oldalon letöltheted az utalványt PDF-ben."),
None => "Az ajándékutalványt PDF-ben csatoltuk ehhez a levélhez, és az Ajándékaim oldalon is letöltheted: kinyomtathatod, vagy továbbküldheted annak, akinek szánod.".into(),
}
),
quote: Some(
"A fizetés előtt kérted a szolgáltatás azonnali megkezdését, és tudomásul vetted, hogy ezzel elveszíted a 14 napos elállási jogodat. Az ajándékkódot ennek megfelelően azonnal kiállítottuk."
.into(),
),
points: None,
code: code.map(|c| ("AJÁNDÉKKÓD", c)),
button: "Ajándékaim",
url,
note: format!(
"A kód egyszer váltható be, és nem jár le. A számlát külön e-mailben küldjük, és a Számláim oldalon is letöltheted: {invoices_url}. A vásárlás feltételei (ÁSZF): {terms_url}. Ha valami nem működik, írj nekünk az info@sorsfonalak.hu címre."
),
reason: Some("Ezt a levelet a vásárlásod visszaigazolásaként kaptad.".into()),
unsubscribe: None,
unsubscribe_post_url: None,
},
(Lang::En, None) => Content {
subject: format!("Thank you for your purchase: {package}"),
preheader: Some(format!("The {package} package is yours.")),
greeting: greeting(false),
@@ -353,6 +399,7 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
.into(),
),
points: None,
code: None,
button: "See my packages",
url,
note: format!(
@@ -362,6 +409,127 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
unsubscribe: None,
unsubscribe_post_url: None,
},
(Lang::En, Some((code, to, whom))) => Content {
subject: format!("Thank you for your purchase: {package} (gift)"),
preheader: Some(match &to {
Some(e) => format!("We sent the gift to {e}."),
None => "The gift card is attached to this e-mail.".into(),
}),
greeting: greeting(false),
intro: format!(
"We received your payment ({amount}, {paid_on}): you bought the “{package}” package as a gift{}.{contents_en} {}",
whom.as_ref().map(|w| format!(" for {w}")).unwrap_or_default(),
match &to {
Some(e) => format!("We sent the gift code with the gift card to {e}. To hand it over another way, download the card as a PDF on the My gifts page."),
None => "The gift card is attached to this e-mail as a PDF, and you can download it on the My gifts page: print it, or forward it to the person it is for.".into(),
}
),
quote: Some(
"Before paying you asked us to start the service at once and acknowledged that you thereby lose your 14-day right of withdrawal. The gift code was issued at once accordingly."
.into(),
),
points: None,
code: code.map(|c| ("GIFT CODE", c)),
button: "My gifts",
url,
note: format!(
"The code can be redeemed once and does not expire. The invoice comes in a separate e-mail and can be downloaded on the Invoices page: {invoices_url}. Terms of purchase (ÁSZF): {terms_url}. If something does not work, write to info@sorsfonalak.hu."
),
reason: Some("You got this e-mail as the confirmation of your purchase.".into()),
unsubscribe: None,
unsubscribe_post_url: None,
},
})
}
/// A promo code from a payload, as shown: letters, digits and dashes only.
fn clean_code(value: &Value) -> Option<String> {
value
.as_str()
.map(|c| c.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').take(40).collect::<String>())
.filter(|c| !c.is_empty())
}
/// A package someone bought for the recipient: who sends it, their message,
/// the code and its redeem link (the worker attaches the gift card as a PDF).
fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
let package = name(payload, "package_name").ok_or(TemplateError::MissingField("package_name"))?;
let code = clean_code(&payload["promo_code"]).ok_or(TemplateError::MissingField("promo_code"))?;
let contents =
payload["contents"].as_str().map(|c| c.chars().filter(|c| !c.is_control()).take(300).collect::<String>());
let from = name(payload, "from_name");
let to = name(payload, "recipient_name");
Ok(match lang {
Lang::Hu => Content {
subject: match &from {
Some(f) => format!("{f} ajándékot küldött neked: „{package}” csomag"),
None => format!("Ajándékot kaptál: „{package}” csomag a Sorsfonalakon"),
},
preheader: Some("Születési képlet és személyre szóló elemzések: a kód beváltásával a tiéd.".into()),
greeting: to.as_ref().map_or_else(|| "Szia!".into(), |t| format!("Szia {t}!")),
intro: format!(
"{} egy „{package}” csomagot a Sorsfonalakon.{}",
match &from {
Some(f) => format!("{f} ajándékozott neked"),
None => "Ajándékba kaptál".into(),
},
contents.map(|c| format!(" Tartalma: {c}.")).unwrap_or_default()
),
quote: message(payload),
code: Some(("AJÁNDÉKKÓD", code)),
points: Some((
"Így váltod be:",
vec![
"kattints a gombra, és lépj be, vagy regisztrálj, ha még nincs fiókod;",
"a kód már ki lesz töltve, csak a beváltásra kell kattintanod;",
"utána a csomag a tiéd: elkészítheted a képleted és az elemzéseidet.",
],
)),
button: "Ajándék beváltása",
url,
note: "A kód egyszer váltható be, és nem jár le. Az ajándékutalványt PDF-ben is csatoltuk: kinyomtathatod vagy elteheted.".into(),
reason: Some(match &from {
Some(f) => format!("Ezt a levelet azért kaptad, mert {f} a Sorsfonalakon ajándékot vásárolt neked erre a címre."),
None => "Ezt a levelet azért kaptad, mert valaki a Sorsfonalakon ajándékot vásárolt neked erre a címre.".into(),
}),
unsubscribe: None,
unsubscribe_post_url: None,
},
Lang::En => Content {
subject: match &from {
Some(f) => format!("{f} sent you a gift: the “{package}” package"),
None => format!("A gift for you: the “{package}” package on Sorsfonalak"),
},
preheader: Some("Your birth chart and personal readings: redeem the code and they are yours.".into()),
greeting: to.as_ref().map_or_else(|| "Hi,".into(), |t| format!("Hi {t},")),
intro: format!(
"{} the “{package}” package on Sorsfonalak.{}",
match &from {
Some(f) => format!("{f} gave you"),
None => "You got".into(),
},
contents.map(|c| format!(" It contains: {c}.")).unwrap_or_default()
),
quote: message(payload),
code: Some(("GIFT CODE", code)),
points: Some((
"How to redeem it:",
vec![
"click the button and log in, or sign up if you have no account yet;",
"the code is filled in for you: just click Redeem;",
"the package is yours: make your chart and your readings.",
],
)),
button: "Redeem the gift",
url,
note: "The code can be redeemed once and does not expire. The gift card is attached as a PDF: print it or keep it.".into(),
reason: Some(match &from {
Some(f) => format!("You got this e-mail because {f} bought you a gift on Sorsfonalak for this address."),
None => "You got this e-mail because someone bought you a gift on Sorsfonalak for this address.".into(),
}),
unsubscribe: None,
unsubscribe_post_url: None,
},
})
}
@@ -397,6 +565,7 @@ fn gift(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateErr
reason: Some("Ezt a levelet azért kaptad, mert ajándékot írtunk jóvá a Sorsfonalak-fiókodban.".into()),
unsubscribe: None,
unsubscribe_post_url: None,
code: None,
},
Lang::En => Content {
subject: "A gift from Sorsfonalak".into(),
@@ -414,6 +583,7 @@ fn gift(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateErr
reason: Some("You got this e-mail because a gift was added to your Sorsfonalak account.".into()),
unsubscribe: None,
unsubscribe_post_url: None,
code: None,
},
})
}
@@ -442,6 +612,7 @@ fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result<Content,
reason: Some("Ezt a levelet azért kaptad, mert ezt a címet megadták a Sorsfonalak várólistáján.".into()),
unsubscribe: Some(("Leiratkozás a várólistáról", unsubscribe_url)),
unsubscribe_post_url: Some(unsubscribe_post_url),
code: None,
},
Lang::En => Content {
subject: "You are on the Sorsfonalak waitlist".into(),
@@ -463,6 +634,7 @@ fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result<Content,
reason: Some("You got this e-mail because this address was entered on the Sorsfonalak waitlist.".into()),
unsubscribe: Some(("Leave the waitlist", unsubscribe_url)),
unsubscribe_post_url: Some(unsubscribe_post_url),
code: None,
},
})
}
@@ -506,6 +678,7 @@ fn synastry_invite(lang: Lang, payload: &Value, url: String) -> Result<Content,
)),
unsubscribe: Some(("Nem kérek több meghívót", unsubscribe_url)),
unsubscribe_post_url: Some(unsubscribe_post_url),
code: None,
}
}
Lang::En => {
@@ -535,6 +708,7 @@ fn synastry_invite(lang: Lang, payload: &Value, url: String) -> Result<Content,
reason: Some(format!("You got this e-mail because {who} entered your address on Sorsfonalak.")),
unsubscribe: Some(("No more invitations, please", unsubscribe_url)),
unsubscribe_post_url: Some(unsubscribe_post_url),
code: None,
}
}
})
@@ -622,6 +796,9 @@ impl Content {
}
text.push('\n');
}
if let Some((label, code)) = &self.code {
text.push_str(&format!("{label}: {code}\n\n"));
}
if let Some((heading, items)) = &self.points {
text.push_str(heading);
text.push('\n');
@@ -662,6 +839,14 @@ impl Content {
escape(heading)
)
});
let code = self.code.as_ref().map_or(String::new(), |(label, code)| {
format!(
r#"<tr><td style="padding-bottom:24px"><div style="border:1px solid {GOLD};border-radius:8px;padding:14px 18px;text-align:center"><div style="font-size:12px;letter-spacing:2px;color:{GOLD}">{}</div><div style="font-family:'Courier New',Courier,monospace;font-size:24px;font-weight:bold;letter-spacing:2px;color:{TEXT};padding-top:6px">{}</div></div></td></tr>
"#,
escape(label),
escape(code)
)
});
let mut small = Vec::new();
if let Some(reason) = &self.reason {
small.push(escape(reason));
@@ -683,7 +868,7 @@ impl Content {
<tr><td style="font-size:20px;letter-spacing:2px;color:{GOLD};padding-bottom:24px">SORSFONALAK</td></tr>
<tr><td style="font-size:16px;line-height:1.6;padding-bottom:12px">{greeting}</td></tr>
<tr><td style="font-size:16px;line-height:1.6;padding-bottom:24px">{intro}</td></tr>
{quote}{points}<tr><td style="padding-bottom:24px"><a href="{url}" style="display:inline-block;background:{GOLD};color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-size:16px">{button}</a></td></tr>
{quote}{code}{points}<tr><td style="padding-bottom:24px"><a href="{url}" style="display:inline-block;background:{GOLD};color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-size:16px">{button}</a></td></tr>
<tr><td style="font-size:14px;line-height:1.6;color:{MUTED};padding-bottom:16px">{note}</td></tr>
<tr><td style="font-size:12px;line-height:1.5;color:{FAINT};word-break:break-all">{url_text}</td></tr>
</table>
@@ -819,6 +1004,53 @@ mod tests {
assert_eq!(render("purchase_confirmation", "hu", &missing), Err(TemplateError::MissingField("amount")));
}
#[test]
fn gift_packages_carry_the_message_and_the_code() {
let payload = serde_json::json!({
"url": "https://sorsfonalak.hu/bevaltas?kod=ABCD-EFGH-JKMN", "package_name": "Páros",
"contents": "2 részletes képletelemzés, 1 kapcsolati elemzés", "promo_code": "ABCD-EFGH-JKMN",
"recipient_name": "Bea", "from_name": "Ági", "message": "Boldog születésnapot!\n<b>Ölel</b>"
});
let hu = render("gift_package", "hu", &payload).unwrap();
assert!(hu.text.starts_with("Szia Bea!"));
assert_eq!(hu.subject, "Ági ajándékot küldött neked: „Páros” csomag");
assert!(hu.text.contains("Ági ajándékozott neked egy „Páros” csomagot a Sorsfonalakon. Tartalma: 2 részletes"));
assert!(
hu.text.contains("> Boldog születésnapot!\n> <b>Ölel</b>")
&& hu.text.contains("AJÁNDÉKKÓD: ABCD-EFGH-JKMN")
);
assert!(hu.html.contains("&lt;b&gt;Ölel&lt;/b&gt;") && hu.html.contains(">ABCD-EFGH-JKMN</div>"));
assert!(hu.text.contains("PDF-ben is csatoltuk") && hu.text.contains("mert Ági a Sorsfonalakon"));
let anonymous = serde_json::json!({"url": "u", "package_name": "Család", "promo_code": "X1-<script>"});
let hu = render("gift_package", "hu", &anonymous).unwrap();
assert_eq!(hu.subject, "Ajándékot kaptál: „Család” csomag a Sorsfonalakon");
assert!(hu.text.contains("AJÁNDÉKKÓD: X1-script") && !hu.text.contains("> ") && hu.text.starts_with("Szia!"));
assert!(render("gift_package", "en", &payload).unwrap().text.contains("Ági gave you the “Páros” package"));
let missing = serde_json::json!({"url": "u", "package_name": "Páros"});
assert_eq!(render("gift_package", "hu", &missing), Err(TemplateError::MissingField("promo_code")));
}
#[test]
fn a_gift_purchase_is_confirmed_as_a_gift() {
let mut payload = serde_json::json!({
"url": "https://sorsfonalak.hu/ajandekaim", "display_name": "Anna", "package_name": "Páros",
"contents": "2 részletes képletelemzés", "amount": "6\u{a0}000\u{a0}Ft", "paid_on": "2026-11-20",
"terms_url": "https://sorsfonalak.hu/aszf", "invoices_url": "https://sorsfonalak.hu/szamlak",
"gift": {"promo_code": "ABCD-EFGH-JKMN", "recipient_name": "Bea", "recipient_email": "bea@example.com"}
});
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
assert_eq!(hu.subject, "Köszönjük a vásárlást: Páros (ajándék)");
assert!(
hu.text.contains("ajándékba vetted Bea részére.") && hu.text.contains("elküldtük ide: bea@example.com")
);
assert!(hu.text.contains("AJÁNDÉKKÓD: ABCD-EFGH-JKMN") && hu.text.contains("14 napos elállási jogodat"));
assert!(!hu.text.contains("jóváírtuk"));
payload["gift"]["recipient_email"] = Value::Null;
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
assert!(hu.text.contains("PDF-ben csatoltuk ehhez a levélhez"));
assert!(render("purchase_confirmation", "en", &payload).unwrap().text.contains("as a gift"));
}
#[test]
fn dates() {
assert_eq!(date(Lang::Hu, "2027-01-05").as_deref(), Some("2027. január 5."));