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:
@@ -0,0 +1,40 @@
|
||||
-- Gifts: a package of the main ladder paid for someone else. The buyer pays
|
||||
-- as for any package (stripe_checkouts.gift_id); when the payment is
|
||||
-- confirmed the gift gets its code, which is e-mailed to the recipient, or
|
||||
-- the buyer hands it over (the gift card can be downloaded as a PDF).
|
||||
-- A gift code is not a promo code: it cannot be withdrawn (it was paid for),
|
||||
-- and it adds the whole package.
|
||||
CREATE TABLE gifts (
|
||||
id uuid PRIMARY KEY,
|
||||
buyer_id uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
package text NOT NULL,
|
||||
-- Whom it is for (on the card and in the e-mail); cleared with the buyer's account.
|
||||
recipient_name text,
|
||||
-- Who gets it by e-mail; NULL: the buyer hands the card over.
|
||||
recipient_email text,
|
||||
-- The giver's name and message, on the card and in the e-mail.
|
||||
from_name text,
|
||||
message text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
-- Paid: the code is made (and sent).
|
||||
paid_at timestamptz,
|
||||
-- Upper case, without separators (shown in groups of four), like promo
|
||||
-- codes, and never the same as one.
|
||||
code text UNIQUE CHECK (code ~ '^[2-9A-HJKMNP-Z]{8,32}$'),
|
||||
redeemed_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
redeemed_at timestamptz,
|
||||
order_id uuid REFERENCES package_orders (id) ON DELETE SET NULL,
|
||||
-- E-mails to the recipient so far (sending again is limited).
|
||||
sendings integer NOT NULL DEFAULT 0,
|
||||
last_sent_at timestamptz,
|
||||
CHECK (paid_at IS NULL OR code IS NOT NULL),
|
||||
CHECK (redeemed_at IS NULL OR paid_at IS NOT NULL)
|
||||
);
|
||||
CREATE INDEX gifts_buyer_idx ON gifts (buyer_id, created_at DESC);
|
||||
|
||||
ALTER TABLE stripe_checkouts ADD COLUMN gift_id uuid UNIQUE REFERENCES gifts (id) ON DELETE SET NULL;
|
||||
|
||||
-- A redeemed gift is recorded as an order with source `gift`.
|
||||
ALTER TABLE package_orders DROP CONSTRAINT package_orders_source_check;
|
||||
ALTER TABLE package_orders ADD CONSTRAINT package_orders_source_check
|
||||
CHECK (source IN ('admin', 'mock', 'stripe', 'promo', 'gift'));
|
||||
@@ -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("<b>Ölel</b>") && 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."));
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "gift-card"
|
||||
description = "The printable gift card (PDF) of a gifted package"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
|
||||
krilla-svg = "0.8"
|
||||
qrcode = { version = "0.14", default-features = false }
|
||||
ttf-parser = "0.25"
|
||||
usvg = { version = "0.47", default-features = false, features = ["text"] }
|
||||
|
||||
[dev-dependencies]
|
||||
resvg = { version = "0.47", default-features = false, features = ["text", "raster-images"] }
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 42 KiB |
@@ -0,0 +1,44 @@
|
||||
//! Writes a sample card as PDF and PNG: `cargo run -p gift-card --example preview -- <dir>`.
|
||||
|
||||
fn main() {
|
||||
let dir = std::env::args().nth(1).unwrap_or_else(|| ".".into());
|
||||
let contents: Vec<String> = [
|
||||
"2 részletes képletelemzés",
|
||||
"1 kapcsolati elemzés",
|
||||
"2 éves előrejelzés",
|
||||
"1 személyhely",
|
||||
"3 kérdés",
|
||||
"5 kártyajóslás",
|
||||
]
|
||||
.map(String::from)
|
||||
.to_vec();
|
||||
let message = std::env::var("MESSAGE").unwrap_or_else(|_| {
|
||||
"Boldog születésnapot! Remélem, legalább annyira élvezni fogod, mint én. Nézd meg a kettőnk képletét is, \
|
||||
kíváncsi vagyok, mit mond rólunk. Ölel: Ági"
|
||||
.into()
|
||||
});
|
||||
let from = std::env::var("FROM").unwrap_or_else(|_| "Ági".into());
|
||||
let to = std::env::var("TO").unwrap_or_else(|_| "Bea".into());
|
||||
// A sample code can use letters real codes never have (I, O, 0).
|
||||
let code = std::env::var("CODE").unwrap_or_else(|_| "ABCD-EFGH-JKMN".into());
|
||||
let url = format!("https://sorsfonalak.hu/bevaltas?kod={code}");
|
||||
let card = gift_card::Card {
|
||||
package: "Páros",
|
||||
contents: &contents,
|
||||
code: &code,
|
||||
redeem_url: &url,
|
||||
recipient_name: Some(to.as_str()),
|
||||
from_name: Some(from.as_str()),
|
||||
message: (!message.is_empty()).then_some(message.as_str()),
|
||||
};
|
||||
let started = std::time::Instant::now();
|
||||
let pdf = gift_card::pdf(&card).unwrap();
|
||||
println!("pdf: {} bytes in {:?}", pdf.len(), started.elapsed());
|
||||
std::fs::write(format!("{dir}/card.pdf"), pdf).unwrap();
|
||||
let tree = gift_card::tree(&card).unwrap();
|
||||
let scale: f32 = std::env::var("SCALE").ok().and_then(|s| s.parse().ok()).unwrap_or(2.0);
|
||||
let size = tree.size().to_int_size().scale_by(scale).unwrap();
|
||||
let mut pixmap = resvg::tiny_skia::Pixmap::new(size.width(), size.height()).unwrap();
|
||||
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut());
|
||||
pixmap.save_png(format!("{dir}/card.png")).unwrap();
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,187 @@
|
||||
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
|
||||
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
|
||||
|
||||
|
||||
Bitstream Vera Fonts Copyright
|
||||
------------------------------
|
||||
|
||||
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
|
||||
a trademark of Bitstream, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of the fonts accompanying this license ("Fonts") and associated
|
||||
documentation files (the "Font Software"), to reproduce and distribute the
|
||||
Font Software, including without limitation the rights to use, copy, merge,
|
||||
publish, distribute, and/or sell copies of the Font Software, and to permit
|
||||
persons to whom the Font Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright and trademark notices and this permission notice shall
|
||||
be included in all copies of one or more of the Font Software typefaces.
|
||||
|
||||
The Font Software may be modified, altered, or added to, and in particular
|
||||
the designs of glyphs or characters in the Fonts may be modified and
|
||||
additional glyphs or characters may be added to the Fonts, only if the fonts
|
||||
are renamed to names not containing either the words "Bitstream" or the word
|
||||
"Vera".
|
||||
|
||||
This License becomes null and void to the extent applicable to Fonts or Font
|
||||
Software that has been modified and is distributed under the "Bitstream
|
||||
Vera" names.
|
||||
|
||||
The Font Software may be sold as part of a larger software package but no
|
||||
copy of one or more of the Font Software typefaces may be sold by itself.
|
||||
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
|
||||
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
|
||||
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
|
||||
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
|
||||
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
|
||||
FONT SOFTWARE.
|
||||
|
||||
Except as contained in this notice, the names of Gnome, the Gnome
|
||||
Foundation, and Bitstream Inc., shall not be used in advertising or
|
||||
otherwise to promote the sale, use or other dealings in this Font Software
|
||||
without prior written authorization from the Gnome Foundation or Bitstream
|
||||
Inc., respectively. For further information, contact: fonts at gnome dot
|
||||
org.
|
||||
|
||||
Arev Fonts Copyright
|
||||
------------------------------
|
||||
|
||||
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the fonts accompanying this license ("Fonts") and
|
||||
associated documentation files (the "Font Software"), to reproduce
|
||||
and distribute the modifications to the Bitstream Vera Font Software,
|
||||
including without limitation the rights to use, copy, merge, publish,
|
||||
distribute, and/or sell copies of the Font Software, and to permit
|
||||
persons to whom the Font Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright and trademark notices and this permission notice
|
||||
shall be included in all copies of one or more of the Font Software
|
||||
typefaces.
|
||||
|
||||
The Font Software may be modified, altered, or added to, and in
|
||||
particular the designs of glyphs or characters in the Fonts may be
|
||||
modified and additional glyphs or characters may be added to the
|
||||
Fonts, only if the fonts are renamed to names not containing either
|
||||
the words "Tavmjong Bah" or the word "Arev".
|
||||
|
||||
This License becomes null and void to the extent applicable to Fonts
|
||||
or Font Software that has been modified and is distributed under the
|
||||
"Tavmjong Bah Arev" names.
|
||||
|
||||
The Font Software may be sold as part of a larger software package but
|
||||
no copy of one or more of the Font Software typefaces may be sold by
|
||||
itself.
|
||||
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
|
||||
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Except as contained in this notice, the name of Tavmjong Bah shall not
|
||||
be used in advertising or otherwise to promote the sale, use or other
|
||||
dealings in this Font Software without prior written authorization
|
||||
from Tavmjong Bah. For further information, contact: tavmjong @ free
|
||||
. fr.
|
||||
|
||||
TeX Gyre DJV Math
|
||||
-----------------
|
||||
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
|
||||
|
||||
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
|
||||
(on behalf of TeX users groups) are in public domain.
|
||||
|
||||
Letters imported from Euler Fraktur from AMSfonts are (c) American
|
||||
Mathematical Society (see below).
|
||||
Bitstream Vera Fonts Copyright
|
||||
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
|
||||
is a trademark of Bitstream, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of the fonts accompanying this license (“Fonts”) and associated
|
||||
documentation
|
||||
files (the “Font Software”), to reproduce and distribute the Font Software,
|
||||
including without limitation the rights to use, copy, merge, publish,
|
||||
distribute,
|
||||
and/or sell copies of the Font Software, and to permit persons to whom
|
||||
the Font Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright and trademark notices and this permission notice
|
||||
shall be
|
||||
included in all copies of one or more of the Font Software typefaces.
|
||||
|
||||
The Font Software may be modified, altered, or added to, and in particular
|
||||
the designs of glyphs or characters in the Fonts may be modified and
|
||||
additional
|
||||
glyphs or characters may be added to the Fonts, only if the fonts are
|
||||
renamed
|
||||
to names not containing either the words “Bitstream” or the word “Vera”.
|
||||
|
||||
This License becomes null and void to the extent applicable to Fonts or
|
||||
Font Software
|
||||
that has been modified and is distributed under the “Bitstream Vera”
|
||||
names.
|
||||
|
||||
The Font Software may be sold as part of a larger software package but
|
||||
no copy
|
||||
of one or more of the Font Software typefaces may be sold by itself.
|
||||
|
||||
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
|
||||
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
|
||||
FOUNDATION
|
||||
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
|
||||
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
|
||||
ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
|
||||
INABILITY TO USE
|
||||
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Except as contained in this notice, the names of GNOME, the GNOME
|
||||
Foundation,
|
||||
and Bitstream Inc., shall not be used in advertising or otherwise to promote
|
||||
the sale, use or other dealings in this Font Software without prior written
|
||||
authorization from the GNOME Foundation or Bitstream Inc., respectively.
|
||||
For further information, contact: fonts at gnome dot org.
|
||||
|
||||
AMSFonts (v. 2.2) copyright
|
||||
|
||||
The PostScript Type 1 implementation of the AMSFonts produced by and
|
||||
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
|
||||
available for general use. This has been accomplished through the
|
||||
cooperation
|
||||
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
|
||||
Members of this consortium include:
|
||||
|
||||
Elsevier Science IBM Corporation Society for Industrial and Applied
|
||||
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
|
||||
|
||||
In order to assure the authenticity of these fonts, copyright will be
|
||||
held by
|
||||
the American Mathematical Society. This is not meant to restrict in any way
|
||||
the legitimate use of the fonts, such as (but not limited to) electronic
|
||||
distribution of documents containing these fonts, inclusion of these fonts
|
||||
into other public domain or commercial font collections or computer
|
||||
applications, use of the outline data to create derivative fonts and/or
|
||||
faces, etc. However, the AMS does require that the AMS copyright notice be
|
||||
removed from any derivative versions of the fonts which have been altered in
|
||||
any way. In addition, to ensure the fidelity of TeX documents using Computer
|
||||
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
|
||||
has requested that any alterations which yield different font metrics be
|
||||
given a different name.
|
||||
|
||||
$Id$
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2015 the Cormorant Project Authors (github.com/CatharsisFonts/Cormorant)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,8 @@
|
||||
Fonts of the gift card, compiled into the binary.
|
||||
|
||||
- Cormorant Garamond SemiBold, Inter Regular and SemiBold: static instances from
|
||||
Google Fonts (the same files as the share images), SIL Open Font License
|
||||
(LICENSE-OFL-*.txt).
|
||||
- Cormorant Garamond Medium Italic: a static instance of the Google Fonts
|
||||
variable font; its family name inside is "Cormorant Garamond Light".
|
||||
- DejaVu Sans 2.37: the zodiac and planet glyphs of the wheel (LICENSE-DejaVu.txt).
|
||||
@@ -0,0 +1,638 @@
|
||||
//! The printable gift card of a gifted package: one A4 page (PDF) with whom
|
||||
//! it is for, the package, the giver's message, the code to redeem (with a QR
|
||||
//! code), the example chart of the home page and the avatar of the questions.
|
||||
//!
|
||||
//! The page is drawn as an SVG and turned into a PDF with its text embedded
|
||||
//! (selectable and searchable). Fonts and pictures are compiled in: the
|
||||
//! services run in empty containers. Light and printer-friendly on purpose.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use base64::Engine as _;
|
||||
use krilla::action::{Action, LinkAction};
|
||||
use krilla::annotation::{Annotation, LinkAnnotation, Target};
|
||||
use krilla::geom::{Rect, Size};
|
||||
use krilla::metadata::Metadata;
|
||||
use krilla::page::PageSettings;
|
||||
use krilla_svg::{SurfaceExt as _, SvgSettings};
|
||||
use usvg::fontdb;
|
||||
|
||||
/// A4 in points.
|
||||
const W: f32 = 595.28;
|
||||
const H: f32 = 841.89;
|
||||
|
||||
const SERIF: &[u8] = include_bytes!("../fonts/CormorantGaramond-SemiBold.ttf");
|
||||
const SERIF_ITALIC: &[u8] = include_bytes!("../fonts/CormorantGaramond-MediumItalic.ttf");
|
||||
/// The family name inside that file (an instance cut from the variable font).
|
||||
const SERIF_ITALIC_FAMILY: &str = "Cormorant Garamond Light";
|
||||
const SANS: &[u8] = include_bytes!("../fonts/Inter-Regular.ttf");
|
||||
const SANS_BOLD: &[u8] = include_bytes!("../fonts/Inter-SemiBold.ttf");
|
||||
/// The zodiac and planet glyphs of the wheel.
|
||||
const SYMBOLS: &[u8] = include_bytes!("../fonts/DejaVuSans.ttf");
|
||||
const WHEEL: &str = include_str!("../assets/wheel.svg");
|
||||
const AVATAR: &[u8] = include_bytes!("../assets/avatar.webp");
|
||||
|
||||
const INK: &str = "#1b2238";
|
||||
const GOLD: &str = "#a07a2c";
|
||||
const MUTED: &str = "#5f6578";
|
||||
const LINE: &str = "#d9c9a3";
|
||||
const PAPER: &str = "#fdfaf3";
|
||||
|
||||
/// Where the code box starts; the message fills the space above it.
|
||||
const CODE_TOP: f32 = 636.0;
|
||||
const CODE_HEIGHT: f32 = 114.0;
|
||||
const CODE_LEFT: f32 = 56.0;
|
||||
const QR_SIZE: f32 = 86.0;
|
||||
const MESSAGE_LEFT: f32 = 164.0;
|
||||
const MESSAGE_RIGHT: f32 = W - 70.0;
|
||||
const AVATAR_SIZE: f32 = 70.0;
|
||||
|
||||
/// What goes on the card (the user's text is cleaned and escaped here).
|
||||
pub struct Card<'a> {
|
||||
/// The package's name ("Páros").
|
||||
pub package: &'a str,
|
||||
/// What the package gives, item by item ("2 részletes képletelemzés").
|
||||
pub contents: &'a [String],
|
||||
/// The code as shown (`ABCD-EFGH-JKLM`).
|
||||
pub code: &'a str,
|
||||
/// The link that opens the redeem page with the code filled in.
|
||||
pub redeem_url: &'a str,
|
||||
/// Whom it is for ("Bea részére").
|
||||
pub recipient_name: Option<&'a str>,
|
||||
/// Who gives it, as the buyer typed it.
|
||||
pub from_name: Option<&'a str>,
|
||||
/// The buyer's message (line breaks kept).
|
||||
pub message: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Error(String);
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "gift card: {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// The card as a PDF document.
|
||||
pub fn pdf(card: &Card) -> Result<Vec<u8>, Error> {
|
||||
let tree = tree(card)?;
|
||||
let size = Size::from_wh(W, H).expect("A4 is a size");
|
||||
let mut document = krilla::Document::new();
|
||||
document.set_metadata(
|
||||
Metadata::new()
|
||||
.title(format!("Sorsfonalak ajándékutalvány – {}", card.package))
|
||||
.language("hu".into())
|
||||
.creator("Sorsfonalak".into()),
|
||||
);
|
||||
let mut page = document.start_page_with(PageSettings::new(size));
|
||||
let mut surface = page.surface();
|
||||
surface.draw_svg(&tree, size, SvgSettings::default()).ok_or_else(|| Error("the page could not be drawn".into()))?;
|
||||
surface.finish();
|
||||
// The QR code and the address can be clicked in a PDF reader.
|
||||
let (qr, link) = link_areas(card);
|
||||
for rect in [qr, link] {
|
||||
let action = Action::Link(LinkAction::new(card.redeem_url.to_string()));
|
||||
page.add_annotation(Annotation::new_link(LinkAnnotation::new(rect, Target::Action(action)), None));
|
||||
}
|
||||
page.finish();
|
||||
document.finish().map_err(|e| Error(format!("{e:?}")))
|
||||
}
|
||||
|
||||
/// The page as an SVG tree (the PDF is made from it; tests render it to a picture).
|
||||
pub fn tree(card: &Card) -> Result<usvg::Tree, Error> {
|
||||
let options = usvg::Options { fontdb: fonts(), font_family: "Inter".into(), ..Default::default() };
|
||||
usvg::Tree::from_str(&svg(card), &options).map_err(|e| Error(e.to_string()))
|
||||
}
|
||||
|
||||
fn fonts() -> Arc<fontdb::Database> {
|
||||
static FONTS: OnceLock<Arc<fontdb::Database>> = OnceLock::new();
|
||||
FONTS
|
||||
.get_or_init(|| {
|
||||
let mut db = fontdb::Database::new();
|
||||
for data in [SERIF, SERIF_ITALIC, SANS, SANS_BOLD, SYMBOLS] {
|
||||
db.load_font_data(data.to_vec());
|
||||
}
|
||||
Arc::new(db)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
// --- measuring and wrapping text ---------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Face {
|
||||
Serif,
|
||||
SerifItalic,
|
||||
Sans,
|
||||
SansBold,
|
||||
}
|
||||
|
||||
impl Face {
|
||||
fn data(self) -> &'static [u8] {
|
||||
match self {
|
||||
Face::Serif => SERIF,
|
||||
Face::SerifItalic => SERIF_ITALIC,
|
||||
Face::Sans => SANS,
|
||||
Face::SansBold => SANS_BOLD,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The width of a line of text (without kerning: a little wider than drawn).
|
||||
fn width(face: Face, text: &str, size: f32, spacing: f32) -> f32 {
|
||||
let face = ttf_parser::Face::parse(face.data(), 0).expect("the fonts are compiled in");
|
||||
let em = f32::from(face.units_per_em());
|
||||
text.chars()
|
||||
.map(|c| {
|
||||
let advance =
|
||||
face.glyph_index(c).and_then(|g| face.glyph_hor_advance(g)).unwrap_or(face.units_per_em() / 2);
|
||||
f32::from(advance) * size / em + spacing
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Breaks text into lines of at most `max` points (a word longer than a line is cut).
|
||||
fn wrap(text: &str, max: f32, measure: &dyn Fn(&str) -> f32) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
for paragraph in text.split('\n') {
|
||||
let mut line = String::new();
|
||||
for word in paragraph.split_whitespace() {
|
||||
let joined = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
|
||||
if measure(&joined) <= max {
|
||||
line = joined;
|
||||
continue;
|
||||
}
|
||||
if !line.is_empty() {
|
||||
lines.push(std::mem::take(&mut line));
|
||||
}
|
||||
// The word alone, cut where it does not fit.
|
||||
for c in word.chars() {
|
||||
let longer = format!("{line}{c}");
|
||||
if !line.is_empty() && measure(&longer) > max {
|
||||
lines.push(std::mem::replace(&mut line, c.to_string()));
|
||||
} else {
|
||||
line = longer;
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Groups items into lines joined by `sep`, an item never split.
|
||||
fn wrap_items(items: &[String], sep: &str, max: f32, measure: &dyn Fn(&str) -> f32) -> Vec<String> {
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
for item in items {
|
||||
match lines.last_mut() {
|
||||
Some(line) if measure(&format!("{line}{sep}{item}")) <= max => {
|
||||
line.push_str(sep);
|
||||
line.push_str(item);
|
||||
}
|
||||
_ => lines.push(item.clone()),
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// User text made safe for the card: control characters out, at most one
|
||||
/// empty line in a row, spaces trimmed.
|
||||
fn clean(text: &str) -> String {
|
||||
let text: String = text.replace("\r\n", "\n").chars().filter(|&c| c == '\n' || !c.is_control()).collect();
|
||||
let mut out = String::new();
|
||||
let mut empty = 0;
|
||||
for line in text.trim().split('\n') {
|
||||
let line = line.trim();
|
||||
empty = if line.is_empty() { empty + 1 } else { 0 };
|
||||
if empty <= 1 {
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(line);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn escape(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// --- the page ----------------------------------------------------------------------------
|
||||
|
||||
/// The message part: lines of italic text, their size and line height, and the signature.
|
||||
struct Message {
|
||||
lines: Vec<String>,
|
||||
size: f32,
|
||||
leading: f32,
|
||||
signature: Option<String>,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
const SIGNATURE_GAP: f32 = 24.0;
|
||||
|
||||
fn of(card: &Card, room: f32) -> Message {
|
||||
let from = card.from_name.map(clean).map(|f| f.replace('\n', " ")).filter(|f| !f.is_empty());
|
||||
let message = card.message.map(clean).filter(|m| !m.is_empty());
|
||||
let (text, signature) = match (message, from) {
|
||||
(Some(m), from) => (format!("„{m}”"), from.map(|f| format!("– {f}"))),
|
||||
(None, Some(f)) => (format!("Szeretettel küldi: {f}"), None),
|
||||
(None, None) => (
|
||||
"Fedezd fel, mit mesélnek rólad a csillagok: a születési képleted, személyre szóló elemzések, \
|
||||
és válaszok a kérdéseidre."
|
||||
.to_string(),
|
||||
None,
|
||||
),
|
||||
};
|
||||
let room = room - if signature.is_some() { Self::SIGNATURE_GAP } else { 0.0 };
|
||||
let max = MESSAGE_RIGHT - MESSAGE_LEFT;
|
||||
let sizes = [(16.5, 22.0), (15.0, 20.0), (13.5, 18.0), (12.0, 16.0)];
|
||||
for (size, leading) in sizes {
|
||||
let lines = wrap(&text, max, &|s| width(Face::SerifItalic, s, size, 0.0));
|
||||
if lines.len() as f32 * leading <= room {
|
||||
return Message { lines, size, leading, signature };
|
||||
}
|
||||
}
|
||||
// Still too long (many line breaks): the lines that fit, the last one cut.
|
||||
let (size, leading) = sizes[sizes.len() - 1];
|
||||
let mut lines = wrap(&text, max, &|s| width(Face::SerifItalic, s, size, 0.0));
|
||||
let keep = ((room / leading).floor() as usize).max(1);
|
||||
if lines.len() > keep {
|
||||
lines.truncate(keep);
|
||||
if let Some(last) = lines.last_mut() {
|
||||
while !last.is_empty() && width(Face::SerifItalic, &format!("{last} …"), size, 0.0) > max {
|
||||
last.pop();
|
||||
}
|
||||
last.push_str(" …");
|
||||
}
|
||||
}
|
||||
Message { lines, size, leading, signature }
|
||||
}
|
||||
|
||||
fn height(&self) -> f32 {
|
||||
self.lines.len() as f32 * self.leading + if self.signature.is_some() { Self::SIGNATURE_GAP } else { 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// "sorsfonalak.hu/bevaltas" from the redeem link.
|
||||
fn short_address(url: &str) -> &str {
|
||||
let rest = url.split_once("://").map_or(url, |(_, r)| r);
|
||||
rest.split(['?', '#']).next().unwrap_or(rest)
|
||||
}
|
||||
|
||||
/// Where the QR code and the address are, for the link areas of the PDF.
|
||||
fn link_areas(card: &Card) -> (Rect, Rect) {
|
||||
let qr = Rect::from_xywh(qr_left(), CODE_TOP + (CODE_HEIGHT - QR_SIZE) / 2.0, QR_SIZE, QR_SIZE).expect("a rect");
|
||||
let text_width = width(Face::Sans, &format!("Beváltás: {}", short_address(card.redeem_url)), 10.0, 0.0);
|
||||
let link = Rect::from_xywh(CODE_LEFT + 26.0, CODE_TOP + 84.0, text_width, 15.0).expect("a rect");
|
||||
(qr, link)
|
||||
}
|
||||
|
||||
fn qr_left() -> f32 {
|
||||
W - CODE_LEFT - 22.0 - QR_SIZE
|
||||
}
|
||||
|
||||
/// A four-pointed star (the logo's), centred on (x, y).
|
||||
fn star(x: f32, y: f32, r: f32, fill: &str) -> String {
|
||||
let i = r * 0.28;
|
||||
format!(
|
||||
r#"<path fill="{fill}" d="M{x} {t}L{a} {b}L{rr} {y}L{a} {c}L{x} {bt}L{d} {c}L{l} {y}L{d} {b}Z"/>"#,
|
||||
t = y - r,
|
||||
a = x + i,
|
||||
b = y - i,
|
||||
rr = x + r,
|
||||
c = y + i,
|
||||
bt = y + r,
|
||||
d = x - i,
|
||||
l = x - r,
|
||||
)
|
||||
}
|
||||
|
||||
/// The QR code of the redeem link as a path of `size` points at (x, y).
|
||||
fn qr(url: &str, x: f32, y: f32, size: f32) -> String {
|
||||
let Ok(code) = qrcode::QrCode::with_error_correction_level(url, qrcode::EcLevel::M) else {
|
||||
return String::new();
|
||||
};
|
||||
let n = code.width();
|
||||
let colors = code.to_colors();
|
||||
let mut d = String::new();
|
||||
for row in 0..n {
|
||||
let mut col = 0;
|
||||
while col < n {
|
||||
if colors[row * n + col] == qrcode::Color::Dark {
|
||||
let start = col;
|
||||
while col < n && colors[row * n + col] == qrcode::Color::Dark {
|
||||
col += 1;
|
||||
}
|
||||
let _ = write!(d, "M{start} {row}h{}v1h-{}z", col - start, col - start);
|
||||
} else {
|
||||
col += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let scale = size / n as f32;
|
||||
format!(r#"<path fill="{INK}" transform="translate({x} {y}) scale({scale})" d="{d}"/>"#)
|
||||
}
|
||||
|
||||
/// The page as an SVG document (points as units).
|
||||
pub fn svg(card: &Card) -> String {
|
||||
let cx = W / 2.0;
|
||||
let mut s = String::new();
|
||||
let _ = write!(s, r#"<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">"#);
|
||||
|
||||
// Paper and a double frame with stars in the corners.
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<rect width="{W}" height="{H}" fill="white"/><rect x="18" y="18" width="{}" height="{}" fill="{PAPER}" stroke="{GOLD}" stroke-width="0.9"/><rect x="24" y="24" width="{}" height="{}" fill="none" stroke="{LINE}" stroke-width="0.5"/>"#,
|
||||
W - 36.0,
|
||||
H - 36.0,
|
||||
W - 48.0,
|
||||
H - 48.0
|
||||
);
|
||||
for (x, y) in [(24.0, 24.0), (W - 24.0, 24.0), (24.0, H - 24.0), (W - 24.0, H - 24.0)] {
|
||||
s.push_str(&star(x, y, 6.0, GOLD));
|
||||
}
|
||||
|
||||
// The logo: the mark and "sorsfonalak", centred.
|
||||
let word_size = 30.0;
|
||||
let mark = 34.0;
|
||||
let gap = 10.0;
|
||||
let total = mark + gap + width(Face::Serif, "sorsfonalak", word_size, 0.3);
|
||||
let x0 = cx - total / 2.0;
|
||||
let baseline = 80.0;
|
||||
let mark_top = baseline - 9.5 - mark / 2.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<g transform="translate({x0} {mark_top}) scale({k})"><g fill="none" stroke="{GOLD}" stroke-width="4.5" stroke-linecap="round"><circle cx="32" cy="32" r="23"/><path d="M10 46 C 24 45, 29 23, 44 18"/><path d="M18 33.5 L36 33.5" stroke-width="4.2"/></g><path d="M49 6 L51.8 13.2 L59 16 L51.8 18.8 L49 26 L46.2 18.8 L39 16 L46.2 13.2 Z" fill="{INK}"/></g>"#,
|
||||
k = mark / 64.0
|
||||
);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{}" y="{baseline}" font-family="Cormorant Garamond" font-weight="600" font-size="{word_size}" letter-spacing="0.3" fill="{INK}">sors<tspan fill="{GOLD}">fonalak</tspan></text>"#,
|
||||
x0 + mark + gap
|
||||
);
|
||||
|
||||
// "AJÁNDÉKUTALVÁNY" between two short lines.
|
||||
let eyebrow = "AJÁNDÉKUTALVÁNY";
|
||||
let spacing = 3.2;
|
||||
let ew = width(Face::SansBold, eyebrow, 9.0, spacing) - spacing;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{}" y="108" font-family="Inter" font-weight="600" font-size="9" letter-spacing="{spacing}" fill="{GOLD}">{eyebrow}</text>"#,
|
||||
cx - ew / 2.0
|
||||
);
|
||||
for (a, b) in [(cx - ew / 2.0 - 56.0, cx - ew / 2.0 - 14.0), (cx + ew / 2.0 + 14.0, cx + ew / 2.0 + 56.0)] {
|
||||
let _ = write!(s, r#"<line x1="{a}" y1="104.8" x2="{b}" y2="104.8" stroke="{LINE}" stroke-width="0.8"/>"#);
|
||||
}
|
||||
|
||||
// The example chart with an orbit around it and a few stars.
|
||||
let wheel = 216.0;
|
||||
let wheel_top = 124.0;
|
||||
let wy = wheel_top + wheel / 2.0;
|
||||
let orbit = wheel / 2.0 + 13.0;
|
||||
let _ = write!(s, r#"<circle cx="{cx}" cy="{wy}" r="{orbit}" fill="none" stroke="{LINE}" stroke-width="0.6"/>"#);
|
||||
for (deg, r) in [(90.0_f32, 2.4), (-8.0, 1.8), (218.0, 2.0)] {
|
||||
let (sin, cos) = deg.to_radians().sin_cos();
|
||||
let _ = write!(s, r#"<circle cx="{}" cy="{}" r="{r}" fill="{GOLD}"/>"#, cx + orbit * cos, wy - orbit * sin);
|
||||
}
|
||||
for (x, y, r) in
|
||||
[(124.0, 164.0, 5.0), (462.0, 148.0, 6.5), (470.0, 304.0, 4.0), (134.0, 322.0, 6.0), (420.0, 350.0, 3.0)]
|
||||
{
|
||||
s.push_str(&star(x, y, r, LINE));
|
||||
}
|
||||
let inner = WHEEL.split_once("viewBox=\"0 0 680 680\">").map_or("", |(_, rest)| rest);
|
||||
let inner = inner.trim_end().trim_end_matches("</svg>");
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<svg x="{}" y="{wheel_top}" width="{wheel}" height="{wheel}" viewBox="0 0 680 680">{inner}</svg>"#,
|
||||
cx - wheel / 2.0
|
||||
);
|
||||
|
||||
// Whom it is for, the package and what it gives.
|
||||
if let Some(name) = card.recipient_name.map(clean).map(|n| n.replace('\n', " ")).filter(|n| !n.is_empty()) {
|
||||
let line = format!("{name} részére");
|
||||
let size = (440.0 / width(Face::SerifItalic, &line, 1.0, 0.0)).min(21.0);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{cx}" y="{}" text-anchor="middle" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="{size}" fill="{GOLD}">{}</text>"#,
|
||||
wheel_top + wheel + 38.0,
|
||||
escape(&line)
|
||||
);
|
||||
}
|
||||
let title_y = wheel_top + wheel + 76.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{cx}" y="{title_y}" text-anchor="middle" font-family="Cormorant Garamond" font-weight="600" font-size="36" fill="{INK}">„{}” csomag</text>"#,
|
||||
escape(card.package)
|
||||
);
|
||||
let contents = wrap_items(card.contents, " · ", 440.0, &|t| width(Face::Sans, t, 10.0, 0.0));
|
||||
let mut y = title_y + 26.0;
|
||||
for line in &contents {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{cx}" y="{y}" text-anchor="middle" font-family="Inter" font-size="10" fill="{MUTED}" xml:space="preserve">{}</text>"#,
|
||||
escape(line)
|
||||
);
|
||||
y += 15.0;
|
||||
}
|
||||
|
||||
// A divider with a small diamond.
|
||||
let divider = y + 10.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><path d="M{cx} {} l3.5 3.5 l-3.5 3.5 l-3.5 -3.5 z" fill="{GOLD}"/>"#,
|
||||
cx - 150.0,
|
||||
cx - 10.0,
|
||||
cx + 10.0,
|
||||
cx + 150.0,
|
||||
divider - 3.5
|
||||
);
|
||||
|
||||
// The message next to the avatar, centred in the room above the code box.
|
||||
let room_top = divider + 22.0;
|
||||
let room_bottom = CODE_TOP - 22.0;
|
||||
let message = Message::of(card, room_bottom - room_top);
|
||||
let block = message.height().max(AVATAR_SIZE);
|
||||
let top = room_top + ((room_bottom - room_top - block) / 2.0).max(0.0);
|
||||
let avatar_y = top + (block - AVATAR_SIZE) / 2.0;
|
||||
let r = AVATAR_SIZE / 2.0;
|
||||
let (ax, ay) = (70.0 + r, avatar_y + r);
|
||||
let avatar = base64::engine::general_purpose::STANDARD.encode(AVATAR);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<clipPath id="avatar"><circle cx="{ax}" cy="{ay}" r="{r}"/></clipPath><image x="70" y="{avatar_y}" width="{AVATAR_SIZE}" height="{AVATAR_SIZE}" clip-path="url(#avatar)" href="data:image/webp;base64,{avatar}"/><circle cx="{ax}" cy="{ay}" r="{}" fill="none" stroke="{GOLD}" stroke-width="1.2"/><circle cx="{ax}" cy="{ay}" r="{}" fill="none" stroke="{LINE}" stroke-width="0.5"/>"#,
|
||||
r + 2.5,
|
||||
r + 6.0
|
||||
);
|
||||
let text_top = top + (block - message.height()) / 2.0;
|
||||
let mut y = text_top + message.size * 0.95;
|
||||
for line in &message.lines {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{MESSAGE_LEFT}" y="{y}" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="{}" fill="{INK}" xml:space="preserve">{}</text>"#,
|
||||
message.size,
|
||||
escape(line)
|
||||
);
|
||||
y += message.leading;
|
||||
}
|
||||
if let Some(signature) = &message.signature {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{MESSAGE_RIGHT}" y="{}" text-anchor="end" font-family="Cormorant Garamond" font-weight="600" font-size="15" fill="{GOLD}">{}</text>"#,
|
||||
y - message.leading + Message::SIGNATURE_GAP,
|
||||
escape(signature)
|
||||
);
|
||||
}
|
||||
|
||||
// The code, the address and the QR code in a box.
|
||||
let box_width = W - 2.0 * CODE_LEFT;
|
||||
let tx = CODE_LEFT + 26.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<rect x="{CODE_LEFT}" y="{CODE_TOP}" width="{box_width}" height="{CODE_HEIGHT}" rx="10" fill="white" stroke="{GOLD}" stroke-width="1"/>"#
|
||||
);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{tx}" y="{}" font-family="Inter" font-weight="600" font-size="8.5" letter-spacing="2.5" fill="{GOLD}">AJÁNDÉKKÓD</text>"#,
|
||||
CODE_TOP + 30.0
|
||||
);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{tx}" y="{}" font-family="Inter" font-weight="600" font-size="27" letter-spacing="1.5" fill="{INK}">{}</text>"#,
|
||||
CODE_TOP + 66.0,
|
||||
escape(card.code)
|
||||
);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{tx}" y="{}" font-family="Inter" font-size="10" fill="{MUTED}">Beváltás: <tspan fill="{INK}" font-weight="600">{}</tspan></text>"#,
|
||||
CODE_TOP + 95.0,
|
||||
escape(short_address(card.redeem_url))
|
||||
);
|
||||
s.push_str(&qr(card.redeem_url, qr_left(), CODE_TOP + (CODE_HEIGHT - QR_SIZE) / 2.0, QR_SIZE));
|
||||
|
||||
// How to redeem it.
|
||||
let how = "Lépj be vagy regisztrálj a sorsfonalak.hu oldalon, és írd be a kódot a „Kód beváltása” oldalon, \
|
||||
vagy olvasd be a QR-kódot a telefonoddal. A kód egyszer váltható be, és nem jár le.";
|
||||
let mut y = CODE_TOP + CODE_HEIGHT + 26.0;
|
||||
for line in wrap(how, 430.0, &|t| width(Face::Sans, t, 9.0, 0.0)) {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{cx}" y="{y}" text-anchor="middle" font-family="Inter" font-size="9" fill="{MUTED}">{}</text>"#,
|
||||
escape(&line)
|
||||
);
|
||||
y += 13.0;
|
||||
}
|
||||
|
||||
s.push_str("</svg>");
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn contents() -> Vec<String> {
|
||||
[
|
||||
"2 részletes képletelemzés",
|
||||
"1 kapcsolati elemzés",
|
||||
"2 éves előrejelzés",
|
||||
"1 személyhely",
|
||||
"3 kérdés",
|
||||
"5 kártyajóslás",
|
||||
]
|
||||
.map(String::from)
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
fn card<'a>(contents: &'a [String], message: Option<&'a str>, from: Option<&'a str>) -> Card<'a> {
|
||||
Card {
|
||||
package: "Páros",
|
||||
contents,
|
||||
code: "ABCD-EFGH-JKMN",
|
||||
redeem_url: "https://sorsfonalak.hu/bevaltas?kod=ABCD-EFGH-JKMN",
|
||||
recipient_name: Some("Bea"),
|
||||
from_name: from,
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fonts_are_found_by_their_names() {
|
||||
let db = fonts();
|
||||
let families: Vec<String> = db.faces().flat_map(|f| f.families.iter().map(|(n, _)| n.clone())).collect();
|
||||
for family in ["Cormorant Garamond", "Inter", "DejaVu Sans"] {
|
||||
assert!(families.iter().any(|f| f == family), "{family} not in {families:?}");
|
||||
}
|
||||
let italic = db.query(&fontdb::Query {
|
||||
families: &[fontdb::Family::Name(SERIF_ITALIC_FAMILY)],
|
||||
weight: fontdb::Weight(500),
|
||||
style: fontdb::Style::Italic,
|
||||
..Default::default()
|
||||
});
|
||||
assert!(italic.is_some_and(|id| db.face(id).is_some_and(|f| f.style == fontdb::Style::Italic)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_card_is_a_pdf_with_its_text() {
|
||||
let contents = contents();
|
||||
let pdf = pdf(&card(&contents, Some("Boldog születésnapot! Ölelés: Ági"), Some("Ági & <Péter>"))).unwrap();
|
||||
assert!(pdf.starts_with(b"%PDF-"));
|
||||
assert!(pdf.len() < 400_000, "{} bytes", pdf.len());
|
||||
// The redeem link is clickable.
|
||||
assert!(pdf.windows(26).any(|w| w == b"sorsfonalak.hu/bevaltas?ko"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_messages_get_smaller_and_still_fit() {
|
||||
let contents = contents();
|
||||
let short = Message::of(&card(&contents, Some("Boldog születésnapot!"), Some("Ági")), 150.0);
|
||||
assert_eq!((short.lines.len(), short.size), (1, 16.5));
|
||||
let long = "Nagyon sok boldog születésnapot kívánok! ".repeat(7);
|
||||
let m = Message::of(&card(&contents, Some(&long), Some("Ági")), 150.0);
|
||||
assert!(m.size < 16.5 && m.height() <= 150.0, "{} lines of {}", m.lines.len(), m.size);
|
||||
// Line after line: what does not fit is cut, with an ellipsis.
|
||||
let lines = "a\n".repeat(40);
|
||||
let m = Message::of(&card(&contents, Some(&lines), None), 150.0);
|
||||
assert!(m.height() <= 150.0 && m.lines.last().unwrap().ends_with('…'));
|
||||
// One endless word is broken.
|
||||
let word = "a".repeat(300);
|
||||
let m = Message::of(&card(&contents, Some(&word), None), 150.0);
|
||||
assert!(m.lines.iter().all(|l| width(Face::SerifItalic, l, m.size, 0.0) <= MESSAGE_RIGHT - MESSAGE_LEFT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_text_is_escaped_and_cleaned() {
|
||||
let contents = contents();
|
||||
let svg = svg(&card(&contents, Some("<b>szia</b>\u{7}\n\n\n\nvége"), Some("Ági & \"Péter\"")));
|
||||
assert!(svg.contains("<b>szia</b>") && !svg.contains('\u{7}'));
|
||||
assert!(svg.contains("– Ági & "Péter""));
|
||||
assert_eq!(clean(" a\n\n\n\nb "), "a\n\nb");
|
||||
usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_message_the_card_still_says_something() {
|
||||
let contents = contents();
|
||||
assert!(svg(&card(&contents, None, Some("Ági"))).contains("Szeretettel küldi: Ági"));
|
||||
assert!(svg(&card(&contents, None, None)).contains(">Bea részére</text>"));
|
||||
let nameless = Card { recipient_name: None, ..card(&contents, None, None) };
|
||||
assert!(!svg(&nameless).contains("részére"));
|
||||
assert!(svg(&card(&contents, None, None)).contains("Fedezd fel"));
|
||||
assert_eq!(short_address("https://sorsfonalak.hu/bevaltas?kod=X"), "sorsfonalak.hu/bevaltas");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user