Compare commits

...
Author SHA1 Message Date
fecoandClaude Opus 5.5 86f61c215a Merge main: Christmas gifts, timed gift e-mails, public gift pages
CI / test (push) Successful in 2m30s
CI / build (push) Successful in 7m52s
CI / deploy (push) Successful in 41s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 17:08:44 +00:00
fecoandClaude Opus 5.5 5feaa6836c Gift withdrawal in the confirmation e-mail through the feedback page
CI / test (push) Successful in 2m36s
CI / build (push) Skipped
CI / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 17:08:17 +00:00
fecoandClaude Opus 5.5 c367c218ac Gift withdrawal through the feedback form, not by e-mail
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 17:04:07 +00:00
fecoandClaude Opus 5.5 e0605a7653 Public gift pages for visitors and search engines
- /ajandek shows a page about giving to visitors (indexable, in the sitemap);
  the form still needs a login.
- A gift band on the home page and "Ajándékozás" in the footer (to
  /karacsony in the Christmas season).
- A link preview image for /karacsony.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 16:56:17 +00:00
fecoandClaude Opus 5.5 2d1373edd6 A Christmas tree in the packages page gift box
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 16:04:36 +00:00
fecoandClaude Opus 5.5 382bd31271 Christmas gifts and timed gift e-mails
- Gifts bought 15 Nov - 6 Jan get a Christmas card ("Boldog karácsonyt és
  csillagos 2027-et!", snowflakes) and a Christmas e-mail subject.
- The buyer can time the gift e-mail (e.g. Christmas morning); "Küldés most"
  replaces a waiting one, a refund takes it back.
- Admin: timed e-mails by hour (waiting / sent / failed), e-mail state per gift.
- /karacsony landing page; seasonal hints on /csomagok and /ajandek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 13:46:35 +00:00
fecoandClaude Opus 5.5 dff8f692b0 Merge main: new app header (marks, Felfedezés dropdown, the Moon today), package cards text
CI / test (push) Successful in 2m26s
CI / build (push) Successful in 8m39s
CI / deploy (push) Successful in 50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 09:21:17 +00:00
fecoandClaude Opus 5.5 227e8b5b80 App header: gold marks, a "Felfedezés" dropdown, the Moon today
CI / test (push) Successful in 2m28s
CI / build (push) Skipped
CI / deploy (push) Skipped
- Menu items with gold astrological marks (☉ ☽ ☌, card, box); the free
  pages (signs, famous people, moon calendar, retrogrades) in one
  "Felfedezés" dropdown with a line about each, opened by a click
- A starry header band with a gold edge; the current item has a glowing
  gold underline
- "Ma: Hold a ♉ Bikában" with the Moon's phase drawn as it is lit, to the
  moon calendar (narrower screens: the phase and the glyph)
- The ☰ menu grouped: the Moon today, Saját, Felfedezés · ingyenes as
  tiles, Csomagok with the package; it covers the page now
- Laptops (1440px) keep the row on one line

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 09:17:48 +00:00
fecoandClaude Opus 5.5 12d5d6a9d1 Package cards: no withdrawal sentence under the buttons (the ÁSZF and Stripe's page say it)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 08:04:50 +00:00
34 changed files with 1684 additions and 260 deletions
@@ -0,0 +1,6 @@
-- A gift e-mailed later (e.g. on Christmas morning): when (NULL: at once),
-- and the e-mail queued for it, to show whether it went out (the outbox row
-- itself is cleaned up a week after sending).
ALTER TABLE gifts
ADD COLUMN send_at timestamptz,
ADD COLUMN email_id uuid;
+39 -11
View File
@@ -320,6 +320,8 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
payload["paid_on"].as_str().and_then(|d| date(lang, d)).ok_or(TemplateError::MissingField("paid_on"))?;
let terms_url = field(payload, "terms_url")?;
let invoices_url = field(payload, "invoices_url")?;
// Gift withdrawals come through the feedback page (easier to handle there).
let feedback_url = format!("{}/visszajelzes", terms_url.trim_end_matches("/aszf"));
let greeting = |hu: bool| match (hu, name(payload, "display_name")) {
(true, Some(n)) => format!("Szia {n}!"),
(true, None) => "Szia!".to_owned(),
@@ -334,7 +336,13 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
.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)
// `2026-12-24 08:00`, Budapest clock: when it is e-mailed.
let when = payload["gift"]["send_at"].as_str().and_then(|t| {
let (day, clock) = t.split_once(' ')?;
let clock: String = clock.chars().filter(|c| c.is_ascii_digit() || *c == ':').take(5).collect();
Some((date(lang, day)?, clock))
});
(code, to, whom, when)
});
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();
@@ -359,9 +367,10 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
unsubscribe: None,
unsubscribe_post_url: None,
},
(Lang::Hu, Some((code, to, whom))) => Content {
(Lang::Hu, Some((code, to, whom, when))) => Content {
subject: format!("Köszönjük a vásárlást: {package} (ajándék)"),
preheader: Some(match &to {
Some(e) if when.is_some() => format!("Az ajándékot időzítve küldjük el ide: {e}."),
Some(e) => format!("Az ajándékot elküldtük ide: {e}."),
None => "Az ajándékutalványt csatoltuk ehhez a levélhez.".into(),
}),
@@ -370,13 +379,15 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
"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."),
Some(e) => match &when {
Some((day, clock)) => format!("Az ajándékkódot az utalvánnyal együtt {day}, {clock}-kor küldjük el ide: {e}. Addig az Ajándékaim oldalon letöltheted az utalványt PDF-ben, vagy elküldheted azonnal is."),
None => 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 vásárlástól számított 14 napon belül, amíg az ajándékkódot nem váltották be, elállhatsz a vásárlástól: írj az info@sorsfonalak.hu címre, és visszatérítjük az árát. A fizetés előtt kérted, hogy a kód beváltásakor a szolgáltatás azonnal megkezdődjön: a beváltással az elállási jog megszűnik."
.into(),
format!("A vásárlástól számított 14 napon belül, amíg az ajándékkódot nem váltották be, elállhatsz a vásárlástól: írd meg nekünk az oldalon, belépve ({feedback_url}), és visszatérítjük az árát. A fizetés előtt kérted, hogy a kód beváltásakor a szolgáltatás azonnal megkezdődjön: a beváltással az elállási jog megszűnik."),
),
points: None,
code: code.map(|c| ("AJÁNDÉKKÓD", c)),
@@ -409,7 +420,7 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
unsubscribe: None,
unsubscribe_post_url: None,
},
(Lang::En, Some((code, to, whom))) => Content {
(Lang::En, Some((code, to, whom, when))) => Content {
subject: format!("Thank you for your purchase: {package} (gift)"),
preheader: Some(match &to {
Some(e) => format!("We sent the gift to {e}."),
@@ -420,13 +431,15 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
"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."),
Some(e) => match &when {
Some((day, clock)) => format!("We send the gift code with the gift card to {e} on {day} at {clock}. Until then you can download the card on the My gifts page, or send it at once."),
None => 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(
"Within 14 days of the purchase, while the gift code is not redeemed, you may withdraw from the purchase: write to info@sorsfonalak.hu and we refund it. Before paying you asked for the service to start as soon as the code is redeemed: redeeming it ends the right of withdrawal."
.into(),
format!("Within 14 days of the purchase, while the gift code is not redeemed, you may withdraw from the purchase: tell us on the site, logged in ({feedback_url}), and we refund it. Before paying you asked for the service to start as soon as the code is redeemed: redeeming it ends the right of withdrawal."),
),
points: None,
code: code.map(|c| ("GIFT CODE", c)),
@@ -459,16 +472,21 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
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");
// Bought for Christmas: said so, with the wishes.
let christmas = payload["christmas_year"].as_i64().is_some();
let xmas = if christmas { "karácsonyi " } else { "" };
Ok(match lang {
Lang::Hu => Content {
subject: match &from {
Some(f) => format!("{f} ajándékot küldött neked: „{package}” csomag"),
Some(f) => format!("{f} {xmas}ajándékot küldött neked: „{package}” csomag"),
None if christmas => format!("Karácsonyi ajándékot kaptál: „{package}” csomag a Sorsfonalakon"),
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.{}",
"{}{} egy „{package}” csomagot a Sorsfonalakon.{}",
if christmas { "Boldog karácsonyt! " } else { "" },
match &from {
Some(f) => format!("{f} ajándékozott neked"),
None => "Ajándékba kaptál".into(),
@@ -497,6 +515,7 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
},
Lang::En => Content {
subject: match &from {
Some(f) if christmas => format!("{f} sent you a Christmas gift: the “{package}” package"),
Some(f) => format!("{f} sent you a gift: the “{package}” package"),
None => format!("A gift for you: the “{package}” package on Sorsfonalak"),
},
@@ -1021,6 +1040,11 @@ mod tests {
);
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 mut xmas = payload.clone();
xmas["christmas_year"] = 2027.into();
let hu = render("gift_package", "hu", &xmas).unwrap();
assert_eq!(hu.subject, "Ági karácsonyi ajándékot küldött neked: „Páros” csomag");
assert!(hu.text.contains("Boldog karácsonyt! Ági ajándékozott neked"));
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");
@@ -1046,6 +1070,10 @@ mod tests {
assert!(hu.text.contains("AJÁNDÉKKÓD: ABCD-EFGH-JKMN") && hu.text.contains("14 napon belül"));
assert!(hu.text.contains("a beváltással az elállási jog megszűnik"));
assert!(!hu.text.contains("jóváírtuk"));
payload["gift"]["send_at"] = Value::from("2026-12-24 08:00");
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
assert!(hu.text.contains("2026. december 24., 08:00-kor küldjük el ide: bea@example.com"), "{}", hu.text);
assert!(hu.text.contains("belépve (https://sorsfonalak.hu/visszajelzes)"), "{}", hu.text);
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"));
+1
View File
@@ -28,6 +28,7 @@ fn main() {
code: &code,
redeem_url: &url,
recipient_name: Some(to.as_str()),
christmas: std::env::var("CHRISTMAS").ok().and_then(|y| y.parse().ok()),
from_name: Some(from.as_str()),
message: (!message.is_empty()).then_some(message.as_str()),
};
+97 -12
View File
@@ -38,6 +38,8 @@ const GOLD: &str = "#a07a2c";
const MUTED: &str = "#5f6578";
const LINE: &str = "#d9c9a3";
const PAPER: &str = "#fdfaf3";
/// The Christmas snowflakes: gold, lighter than the text.
const GOLD_SOFT: &str = "#c9a862";
/// Where the code box starts; the message fills the space above it.
const CODE_TOP: f32 = 636.0;
@@ -64,6 +66,27 @@ pub struct Card<'a> {
pub from_name: Option<&'a str>,
/// The buyer's message (line breaks kept).
pub message: Option<&'a str>,
/// A Christmas gift: the card is festive and wishes a happy new year
/// (this one).
pub christmas: Option<i32>,
}
/// "2027-et", "2028-at": a year in the accusative, by how its last word sounds.
pub fn year_accusative(year: i32) -> String {
let ending = match year.rem_euclid(10) {
1 | 4 | 7 | 9 => "et",
2 => "t",
3 | 8 => "at",
5 => "öt",
6 => "ot",
// Tens: "…tízet", "…húszat", "…harmincat"…; hundreds and thousands: "…százat", "…ezret".
_ => match (year / 10).rem_euclid(10) {
1 | 4 | 7 | 9 => "et",
0 if (year / 100).rem_euclid(10) == 0 => "et",
_ => "at",
},
};
format!("{year}-{ending}")
}
#[derive(Debug)]
@@ -252,6 +275,11 @@ impl Message {
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) if card.christmas.is_some() => (
"Boldog karácsonyt! Fedezd fel, mit mesélnek rólad a csillagok, és mit hoz neked a következő év."
.to_string(),
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."
@@ -323,6 +351,26 @@ fn star(x: f32, y: f32, r: f32, fill: &str) -> String {
)
}
/// A six-armed snowflake of gold lines, centred on (x, y).
fn snowflake(x: f32, y: f32, r: f32, color: &str) -> String {
let mut d = String::new();
for k in 0..6 {
let a = (k as f32 * 60.0 - 90.0).to_radians();
let (sin, cos) = a.sin_cos();
let _ = write!(d, "M{x} {y}L{} {}", x + r * cos, y + r * sin);
// Two small branches on each arm.
let (bx, by) = (x + r * 0.6 * cos, y + r * 0.6 * sin);
for side in [-1.0_f32, 1.0] {
let b = a + side * 0.75;
let _ = write!(d, "M{bx} {by}L{} {}", bx + r * 0.32 * b.cos(), by + r * 0.32 * b.sin());
}
}
format!(
r#"<path d="{d}" fill="none" stroke="{color}" stroke-width="{}" stroke-linecap="round"/>"#,
(r / 9.0).max(0.6)
)
}
/// 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 {
@@ -388,7 +436,7 @@ pub fn svg(card: &Card) -> String {
);
// "AJÁNDÉKUTALVÁNY" between two short lines.
let eyebrow = "AJÁNDÉKUTALVÁNY";
let eyebrow = if card.christmas.is_some() { "KARÁCSONYI AJÁNDÉK" } else { "AJÁNDÉKUTALVÁNY" };
let spacing = 3.2;
let ew = width(Face::SansBold, eyebrow, 9.0, spacing) - spacing;
let _ = write!(
@@ -413,7 +461,12 @@ pub fn svg(card: &Card) -> String {
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));
// Christmas: snowflakes instead of stars, a little bigger.
if card.christmas.is_some() {
s.push_str(&snowflake(x, y, r * 1.9, GOLD_SOFT));
} else {
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>");
@@ -451,17 +504,32 @@ pub fn svg(card: &Card) -> String {
y += 15.0;
}
// A divider with a small diamond.
// A divider with a small diamond; at Christmas, the wishes on it.
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
);
if let Some(year) = card.christmas {
let wish = format!("Boldog karácsonyt és csillagos {}!", year_accusative(year));
let ww = width(Face::SerifItalic, &wish, 16.0, 0.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"/><text x="{cx}" y="{}" text-anchor="middle" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="16" fill="{GOLD}">{}</text>"#,
cx - ww / 2.0 - 70.0,
cx - ww / 2.0 - 12.0,
cx + ww / 2.0 + 12.0,
cx + ww / 2.0 + 70.0,
divider + 5.0,
escape(&wish)
);
} else {
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;
@@ -568,6 +636,7 @@ mod tests {
recipient_name: Some("Bea"),
from_name: from,
message,
christmas: None,
}
}
@@ -625,6 +694,22 @@ mod tests {
usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
}
#[test]
fn a_christmas_card_wishes_a_happy_new_year() {
let contents = contents();
let plain = svg(&card(&contents, None, None));
assert!(plain.contains("AJÁNDÉKUTALVÁNY") && !plain.contains("karácsony"));
let festive = Card { christmas: Some(2027), ..card(&contents, None, None) };
let svg = svg(&festive);
assert!(svg.contains("KARÁCSONYI AJÁNDÉK") && svg.contains("Boldog karácsonyt és csillagos 2027-et!"));
assert!(svg.contains("mit hoz neked a következő év"));
assert!(pdf(&festive).unwrap().starts_with(b"%PDF-"));
assert_eq!(
[2027, 2028, 2030, 2026, 2032, 2035, 2100, 2000].map(year_accusative),
["2027-et", "2028-at", "2030-at", "2026-ot", "2032-t", "2035-öt", "2100-at", "2000-et"]
);
}
#[test]
fn without_a_message_the_card_still_says_something() {
let contents = contents();
+22 -5
View File
@@ -7,6 +7,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
## A vásárló: `/ajandek`
- **Hol indul:**
- a főoldal ajándéksávja és a lábléc „Ajándékozás” pontja (nyilvános, lásd Karácsony);
- a Csomagok oldal fő csomagjai alatt az „Ajándékba adom →” link (`/ajandek?csomag=couple`);
- ugyanott az „Ajándékba is adhatod” doboz;
- a fiókmenü „Ajándékozás” pontja.
@@ -17,6 +18,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- **Hogyan kapja meg:**
- „E-mailben küldjük el neki”: a címzett e-mail-címe kétszer, a kettőnek egyeznie kell (a szerver is ellenőrzi);
- „Én adom át”: nincs címzett, a vásárló letölti az utalványt.
- **Mikor kapja meg?** (csak e-mailnél): „Fizetés után azonnal”, vagy „Időzítve” (nap és időpont, a vásárló saját órája szerint, alapból 8:00). Karácsony előtt egy gomb is van: „Karácsony reggel (dec. 24., 8:00)”. Legalább 5 perccel későbbre (a böngésző 10 percet kér), legfeljebb egy évre előre.
- **Személyes üzenet:** legfeljebb 300 karakter, link nélkül (mint a meghívóknál). Rajta van az utalványon és a levélben.
- **Fizetés:** a Stripe-on, mint bármelyik csomagnál; a termék neve „Sorsfonalak – Páros (ajándék)”.
- Az elfogadott szöveg itt más: „…kérem, hogy az ajándékkód beváltásakor a szolgáltatás azonnal megkezdődjön. Tudomásul veszem, hogy a beváltással a 14 napos elállási jog megszűnik.”
@@ -25,6 +27,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- **Fizetés után:** visszatér az **Ajándékaim** oldalra (`/ajandekaim`), ahol a visszaigazolás megmondja, hova ment az ajándék.
- **Visszaigazoló levél** (`purchase_confirmation`):
- azt írja, hogy ajándékba vette, és benne van a kód;
- időzítésnél: „…2026. december 24., 08:00-kor küldjük el ide: …” (magyar idő);
- ha ő adja át, az utalvány PDF-ben csatolva van.
## Ajándékaim: `/ajandekaim`
@@ -33,13 +36,14 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- a csomag, kinek szól, és a vásárlás napja;
- az állapot: „Még nincs beváltva” vagy „Beváltva: dátum”;
- a kód, másolás gombbal;
- kinek ment e-mailben (és hányszor), vagy hogy ő adja át;
- kinek ment e-mailben (és hányszor), vagy hogy ő adja át; időzítésnél „Időzítve: december 24. 8:00, ide: …”, sikertelen küldésnél hibaüzenet;
- a küldő neve és az üzenet.
- **Utalvány letöltése (PDF):** bármikor.
- **Küldés e-mailben:** amíg nincs beváltva.
- Újra ugyanoda, vagy másik címre (elírás); az „Én adom át” ajándékot is el lehet így küldeni.
- A cím itt is kétszer kell.
- Legfeljebb 3 levél ajándékonként, és kettő között legalább 10 perc.
- Időzített, még ki nem ment levélnél a gomb „Küldés most”: a várakozó levelet visszavonja, és azonnal küldi (ez nem számít külön levélnek, és nem kell 10 percet várni). Ugyanígy, ha az első levél még ki sem ment, a javított cím kiváltja.
## A címzett
@@ -53,6 +57,15 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- Könyvelés: egy `package_orders` sor `gift` forrással, 0 Ft-tal (az ár a vásárló fizetésénél van).
- Egy kód egyszer váltható be, és nem jár le.
## Karácsony
- **Az időszak:** november 15. és január 6. között (magyar idő) vett ajándék karácsonyi. A backend a fizetés idejéből számolja (`christmas_year`): novemberben és decemberben a következő év, januárban az aktuális.
- **Az utalványon:** „KARÁCSONYI AJÁNDÉK” felirat, hópelyhek a csillagok helyett, és „Boldog karácsonyt és csillagos 2027-et!” (a toldalékot a `year_accusative` adja). Üzenet nélkül egy karácsonyi szöveg áll rajta.
- **A levélben:** a tárgy „Anna karácsonyi ajándékot küldött neked: …”, a bevezető „Boldog karácsonyt! …”.
- **A `/karacsony` oldal:** a kampány nyitóoldala (a sitemapban is): mit kap (képlet, a következő éve, kapcsolati elemzés), karácsony reggelre időzítés, a három csomag „Ezt adom ajándékba” gombbal. Az éves előrejelzés a születésnaptól egy évre szól; ezt hívjuk itt „a következő évének”.
- **Nyilvános oldalak (a Google is látja):** a `/karacsony` és kijelentkezve az `/ajandek` egy bemutató oldal (`components/GiftLanding.tsx`, egész évben „Horoszkóp ajándékba”); a gombok a belépésen át (`/belepes?vissza=/ajandek?csomag=…`) az űrlapra visznek. Belépve az `/ajandek` az űrlap. Mindkettő a sitemapban van; rájuk linkel a főoldal ajándéksávja és a lábléc „Ajándékozás” pontja (karácsonykor a `/karacsony`-ra). A `/karacsony` Facebook-előnézete a `/kep/karacsony.png`.
- Az időszakban a Csomagok oldal ajándékdoboza a `/karacsony` oldalra visz, a `/ajandek` oldal a karácsonyi mintát mutatja (`public/img/ajandek-karacsony.webp`, `CHRISTMAS=2027`). A frontend ugyanazt az időszakot használja (`lib/season.ts`).
## Az utalvány (PDF)
- **Mi van rajta:** egy A4-es, világos, nyomtatóbarát oldal:
@@ -85,6 +98,9 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
## Admin
- **Időzített levelek** (Admin → Ajándékok, felül, ha van ilyen): óránként (magyar idő), hány levél vár, hány ment ki, hány hibás, az elmúlt 30 napra és előre. Az időpont után figyelni kell, hogy a „Kiment” megnőjön, és ne legyen hiba.
- Soronként is látszik a levél állapota: „levél időzítve · időpont”, „küldés alatt”, „kiment”, „hiba”.
- Visszatérítéskor a még ki nem ment időzített levél törlődik.
- Az ajándékkódok nem jelennek meg az Admin → Promókódok listában; az ajándékok az Admin → Ajándékok oldalon vannak.
## Adatok
@@ -93,6 +109,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- `gifts`: vásárló, csomag, a címzett neve és címe, a küldő neve, üzenet, fizetés ideje, a kód, a beváltás (ki, mikor, melyik rendelés), kiküldött levelek;
- `stripe_checkouts.gift_id`: a fizetés ajándéka;
- `gifts.refunded_at`, `refunded_by`, `refund_id`, `refund_error`: a visszatérítés;
- `gifts.send_at`: az időzítés; `gifts.email_id`: az utolsó sorba állított levél (`email_outbox`; a levél a `next_attempt_at` időpontig vár, a worker 30 másodpercenként néz rá);
- `invoice_cancellations`: a számla sztornója (állapot, próbálkozások, a Billingo sztornószámlája).
- **A kód:** ugyanolyan formájú, mint a promókód (`ABCD-EFGH-JKLM`), és sosem egyezik eggyel sem (mindkét oldal ellenőrzi a másik táblát).
- **Fiók törlése:** az ajándék beváltható marad, de a címzett neve és címe, a küldő neve és az üzenet törlődik.
@@ -102,11 +119,11 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
| Végpont | Ki | Mit csinál |
|---|---|---|
| `POST /v1/gifts/checkout` `{package, recipient_name, recipient_email?, recipient_email_confirm?, from_name?, message?}` | belépett felhasználó | ajándék indítása; a válaszban a Stripe-oldal címe (`url`; tesztüzemben `null`, és már ki is fizette) |
| `GET /v1/gifts` | belépett felhasználó | a kifizetett ajándékai |
| `POST /v1/gifts/checkout` `{package, recipient_name, recipient_email?, recipient_email_confirm?, from_name?, message?, send_at?}` (RFC 3339) | belépett felhasználó | ajándék indítása; a válaszban a Stripe-oldal címe (`url`; tesztüzemben `null`, és már ki is fizette) |
| `GET /v1/gifts` | belépett felhasználó | a kifizetett ajándékai (`send_at`, `email_state`, `christmas` is) |
| `GET /v1/gifts/{id}/card.pdf` | a vásárló | az utalvány |
| `POST /v1/gifts/{id}/send` `{recipient_email, recipient_email_confirm}` | a vásárló | küldés e-mailben (újra, vagy másik címre) |
| `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | promókód vagy ajándékkód beváltása; ajándéknál `gift: {from_name}` is |
| `GET /v1/payments/checkout/{id}` | a vásárló | a fizetés állapota; ajándéknál `gift: {id, recipient_name, recipient_email}` is |
| `GET /v1/admin/gifts?q=` | admin | az ajándékok, fizetéssel, számlával, sztornóval |
| `GET /v1/payments/checkout/{id}` | a vásárló | a fizetés állapota; ajándéknál `gift: {id, recipient_name, recipient_email, send_at}` is |
| `GET /v1/admin/gifts?q=` | admin | az ajándékok, fizetéssel, számlával, sztornóval, a levél állapotával; `schedule`: az időzített levelek óránként |
| `POST /v1/admin/gifts/{id}/refund` | admin | visszatérítés (csak beváltatlan ajándéknál; újrapróbálható, ha a Stripe visszautasította) |
+20 -3
View File
@@ -132,18 +132,35 @@ pub async fn queue_email_to(
locale: &str,
payload: Value,
) -> Result<(), ApiError> {
queue_email_at(conn, user_id, to, template, locale, payload, None).await.map(drop)
}
/// Queues an e-mail that the worker sends not before `at` (none: at once);
/// returns its id.
pub async fn queue_email_at(
conn: &mut PgConnection,
user_id: Option<Uuid>,
to: &str,
template: &str,
locale: &str,
payload: Value,
at: Option<time::OffsetDateTime>,
) -> Result<Uuid, ApiError> {
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload, next_attempt_at) \
VALUES ($1, $2, $3, $4, $5, $6, coalesce($7, now()))",
)
.bind(Uuid::now_v7())
.bind(id)
.bind(user_id)
.bind(to)
.bind(template)
.bind(locale)
.bind(payload)
.bind(at)
.execute(conn)
.await?;
Ok(())
Ok(id)
}
/// The e-mails that carry a password link.
+175 -17
View File
@@ -26,7 +26,7 @@ use sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
use super::auth::{normalize_email, queue_email_to};
use super::auth::{normalize_email, queue_email_at};
use super::promo::{CODE_LEN, display};
use super::{Body, IdPath, St, payments};
use crate::AppState;
@@ -92,10 +92,31 @@ struct Gift {
last_sent_at: Option<OffsetDateTime>,
refunded_at: Option<OffsetDateTime>,
refund_id: Option<String>,
/// E-mailed not before this (none: at once).
send_at: Option<OffsetDateTime>,
/// The last e-mail queued for it.
email_id: Option<Uuid>,
/// That e-mail: `scheduled`, `sending`, `sent` or `failed` (none: no
/// e-mail, or cleaned up a week after it went out).
email_state: Option<String>,
}
const COLUMNS: &str = "id, buyer_id, package, recipient_name, recipient_email, from_name, message, paid_at, code, \
redeemed_at, sendings, last_sent_at, refunded_at, refund_id";
redeemed_at, sendings, last_sent_at, refunded_at, refund_id, send_at, email_id, \
(SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \
WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \
FROM email_outbox o WHERE o.id = gifts.email_id) AS email_state";
/// The year a Christmas gift wishes for ("csillagos 2027-et"), if bought
/// between 15 November and 6 January (Budapest time; no summer time then).
fn christmas_year(paid: OffsetDateTime) -> Option<i32> {
let local = paid.to_offset(time::UtcOffset::from_hms(1, 0, 0).expect("an offset"));
match (local.month(), local.day()) {
(time::Month::November, 15..) | (time::Month::December, _) => Some(local.year() + 1),
(time::Month::January, ..=6) => Some(local.year()),
_ => None,
}
}
impl Gift {
fn package(&self) -> Result<&'static Package, ApiError> {
@@ -117,9 +138,15 @@ impl Gift {
"recipient_name": self.recipient_name,
"from_name": self.from_name,
"message": self.message,
"christmas_year": self.christmas(),
}))
}
/// The year a Christmas gift wishes for (see `christmas_year`).
fn christmas(&self) -> Option<i32> {
christmas_year(self.paid_at.unwrap_or_else(OffsetDateTime::now_utc))
}
fn status(&self) -> &'static str {
match (self.redeemed_at, self.refunded_at) {
(Some(_), _) => "redeemed",
@@ -141,6 +168,8 @@ impl Gift {
fn view(&self) -> Value {
let status = self.status();
let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc());
// A timed e-mail still waiting can be sent now instead.
let waiting = self.email_state.as_deref() == Some("scheduled");
json!({
"id": self.id,
"package": { "id": self.package, "name": packages::find(&self.package).map(|p| p.name) },
@@ -153,9 +182,12 @@ impl Gift {
"status": status,
"redeemed_at": rfc3339_opt(self.redeemed_at),
"refunded_at": rfc3339_opt(self.refunded_at),
"send_at": rfc3339_opt(self.send_at),
"email_state": self.email_state,
"christmas": self.christmas().is_some(),
"sendings": self.sendings,
"can_send": status == "open" && self.sendings < MAX_SENDINGS,
"send_again_at": rfc3339_opt(next_send),
"can_send": status == "open" && self.sendings - i32::from(waiting) < MAX_SENDINGS,
"send_again_at": rfc3339_opt(next_send.filter(|_| !waiting)),
})
}
}
@@ -185,6 +217,26 @@ pub struct GiftCheckout {
recipient_email_confirm: Option<String>,
from_name: Option<String>,
message: Option<String>,
/// E-mail it then (RFC 3339; none: right after paying), e.g. on Christmas morning.
send_at: Option<String>,
}
/// How far ahead a gift e-mail can be timed.
const MAX_SCHEDULE: time::Duration = time::Duration::days(366);
/// A time to e-mail a gift: in the future (a few minutes at least), within a year.
fn schedule(at: Option<&str>) -> Result<Option<OffsetDateTime>, ApiError> {
let Some(at) = at.map(str::trim).filter(|a| !a.is_empty()) else { return Ok(None) };
let at = OffsetDateTime::parse(at, &time::format_description::well_known::Rfc3339)
.map_err(|_| ApiError::BadRequest("send_at must be an RFC 3339 time".into()))?;
let now = OffsetDateTime::now_utc();
if at < now + time::Duration::minutes(5) {
return Err(ApiError::BadRequest("Az időzítés legyen a jövőben.".into()));
}
if at > now + MAX_SCHEDULE {
return Err(ApiError::BadRequest("Legfeljebb egy évre előre lehet időzíteni.".into()));
}
Ok(Some(at))
}
/// Starts paying for a gift: returns the address of Stripe's payment page.
@@ -200,6 +252,10 @@ pub async fn checkout(
let to = recipient(req.recipient_email.as_deref(), req.recipient_email_confirm.as_deref())?;
let from = clean_name(req.from_name)?;
let message = super::invitations::clean_message(req.message)?;
let send_at = schedule(req.send_at.as_deref())?;
if send_at.is_some() && to.is_none() {
return Err(ApiError::BadRequest("Időzíteni csak az e-mailben küldött ajándékot lehet.".into()));
}
// Whether this user may pay, before anything is written.
let stripe = match payments::method(&state.config) {
Some("stripe") => Some(payments::stripe_for(&state, &auth)?),
@@ -208,8 +264,8 @@ pub async fn checkout(
};
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message) \
VALUES ($1, $2, $3, $4, $5, $6, $7)",
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message, send_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
)
.bind(id)
.bind(auth.id())
@@ -218,6 +274,7 @@ pub async fn checkout(
.bind(&to)
.bind(&from)
.bind(&message)
.bind(send_at)
.execute(&state.db)
.await?;
let url = match stripe {
@@ -242,6 +299,8 @@ pub struct Paid {
pub recipient_name: Option<String>,
pub recipient_email: Option<String>,
pub card: Value,
/// When it is e-mailed, on the Budapest clock (`2026-12-24 08:00`); none: at once.
pub send_at_local: Option<String>,
}
/// A new gift code, never the same as a promo code or another gift's.
@@ -276,20 +335,38 @@ pub async fn fulfil(tx: &mut PgConnection, state: &AppState, id: Uuid) -> Result
.await?;
gift.code = Some(code);
if let Some(to) = gift.recipient_email.clone() {
send(tx, state, &gift, &to).await?;
// Timed for a moment already past (paid late): at once.
let at = gift.send_at.filter(|t| *t > OffsetDateTime::now_utc());
send(tx, state, &gift, &to, at).await?;
}
tracing::info!(gift = %id, package = %gift.package, by_email = gift.recipient_email.is_some(), "gift paid");
}
let send_at_local: Option<String> = sqlx::query_scalar(
"SELECT to_char(send_at AT TIME ZONE 'Europe/Budapest', 'YYYY-MM-DD HH24:MI') FROM gifts \
WHERE id = $1 AND send_at > now()",
)
.bind(id)
.fetch_optional(&mut *tx)
.await?
.flatten();
Ok(Paid {
code: display(gift.code()?),
card: gift.card_payload(state)?,
recipient_name: gift.recipient_name,
recipient_email: gift.recipient_email,
send_at_local,
})
}
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language.
async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) -> Result<(), ApiError> {
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language,
/// not before `at` (none: at once).
async fn send(
tx: &mut PgConnection,
state: &AppState,
gift: &Gift,
to: &str,
at: Option<OffsetDateTime>,
) -> Result<(), ApiError> {
let locale: Option<String> = sqlx::query_scalar("SELECT locale FROM users WHERE id = $1")
.bind(gift.buyer_id)
.fetch_optional(&mut *tx)
@@ -304,16 +381,38 @@ async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) ->
"from_name": gift.from_name,
"message": gift.message,
"gift_card": gift.card_payload(state)?,
"christmas_year": gift.christmas(),
});
// Not the recipient's account (if they have one): no user id.
queue_email_to(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload).await?;
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now() WHERE id = $1")
let email = queue_email_at(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload, at).await?;
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now(), email_id = $2 WHERE id = $1")
.bind(gift.id)
.bind(email)
.execute(&mut *tx)
.await?;
Ok(())
}
/// Takes back the gift's e-mail if it has not gone out yet (sent now
/// instead, or refunded): a timed one would come later otherwise. It does
/// not count as a sending then.
async fn cancel_pending_email(conn: &mut PgConnection, gift: &Gift) -> Result<bool, sqlx::Error> {
let Some(email) = gift.email_id else { return Ok(false) };
let taken = sqlx::query("DELETE FROM email_outbox WHERE id = $1 AND sent_at IS NULL AND failed_at IS NULL")
.bind(email)
.execute(&mut *conn)
.await?
.rows_affected()
== 1;
if taken {
sqlx::query("UPDATE gifts SET sendings = greatest(sendings - 1, 0) WHERE id = $1")
.bind(gift.id)
.execute(&mut *conn)
.await?;
}
Ok(taken)
}
/// The user's paid gifts, newest first.
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let gifts: Vec<Gift> = sqlx::query_as(&format!(
@@ -339,6 +438,7 @@ pub async fn card(
let code = display(gift.code()?);
let url = redeem_url(&state, gift.code()?);
let filename = format!("sorsfonalak-ajandek-{code}.pdf");
let christmas = gift.christmas();
let pdf = tokio::task::spawn_blocking(move || {
let contents = package.contents_items();
gift_card::pdf(&gift_card::Card {
@@ -349,6 +449,7 @@ pub async fn card(
recipient_name: gift.recipient_name.as_deref(),
from_name: gift.from_name.as_deref(),
message: gift.message.as_deref(),
christmas,
})
})
.await
@@ -387,18 +488,26 @@ pub async fn send_again(
return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották."));
}
gift.refused_if_refunded()?;
if gift.sendings >= MAX_SENDINGS {
// A timed e-mail still waiting is replaced by this one, not added to it.
let waiting = gift.email_state.as_deref() == Some("scheduled");
if gift.sendings - i32::from(waiting) >= MAX_SENDINGS {
return Err(ApiError::conflict(
"gift_send_limit",
"Ezt az ajándékot már háromszor elküldtük e-mailben. Töltsd le az utalványt, és küldd el te magad.",
));
}
if gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
if !waiting && gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
return Err(ApiError::conflict("gift_send_wait", "Pár perc múlva küldheted el újra."));
}
sqlx::query("UPDATE gifts SET recipient_email = $2 WHERE id = $1").bind(id).bind(&to).execute(&mut *tx).await?;
// Now, instead of a timed e-mail still waiting.
cancel_pending_email(&mut tx, &gift).await?;
sqlx::query("UPDATE gifts SET recipient_email = $2, send_at = NULL WHERE id = $1")
.bind(id)
.bind(&to)
.execute(&mut *tx)
.await?;
gift.recipient_email = Some(to.clone());
send(&mut tx, &state, &gift, &to).await?;
send(&mut tx, &state, &gift, &to, None).await?;
let gift = own_gift(&mut tx, id, auth.id(), false).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), gift = %id, "gift sent by e-mail");
@@ -469,6 +578,8 @@ struct AdminGift {
storno_status: Option<String>,
storno_number: Option<String>,
storno_error: Option<String>,
send_at: Option<OffsetDateTime>,
email_state: Option<String>,
}
#[derive(Deserialize)]
@@ -493,7 +604,11 @@ pub async fn admin_list(
g.redeemed_at, r.email AS redeemed_by, g.refunded_at, g.refund_id, g.refund_error, \
c.id AS checkout_id, c.live, coalesce(c.amount_huf, c.price_huf) AS amount_huf, \
i.invoice_number, i.status AS invoice_status, \
x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error \
x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error, \
g.send_at, \
(SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \
WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \
FROM email_outbox o WHERE o.id = g.email_id) AS email_state \
FROM gifts g LEFT JOIN users b ON b.id = g.buyer_id LEFT JOIN users r ON r.id = g.redeemed_by \
LEFT JOIN stripe_checkouts c ON c.gift_id = g.id LEFT JOIN invoices i ON i.checkout_id = c.id \
LEFT JOIN invoice_cancellations x ON x.invoice_id = i.id \
@@ -535,10 +650,29 @@ pub async fn admin_list(
"checkout": g.checkout_id.map(|id| json!({ "id": id, "live": g.live, "amount_huf": g.amount_huf })),
"invoice": g.invoice_status.map(|s| json!({ "number": g.invoice_number, "status": s })),
"storno": g.storno_status.map(|s| json!({ "status": s, "number": g.storno_number, "error": g.storno_error })),
"send_at": rfc3339_opt(g.send_at),
"email_state": g.email_state,
})
})
.collect();
Ok(Json(json!({ "gifts": gifts, "withdrawal_days": WITHDRAWAL_DAYS })))
// The timed e-mails by hour (Budapest clock): how many wait, went out or failed.
let schedule: Vec<(String, i64, i64, i64)> = sqlx::query_as(
"SELECT to_char(date_trunc('hour', g.send_at AT TIME ZONE 'Europe/Budapest'), 'YYYY-MM-DD HH24:MI'), \
count(*) FILTER (WHERE o.id IS NOT NULL AND o.sent_at IS NULL AND o.failed_at IS NULL), \
count(*) FILTER (WHERE o.sent_at IS NOT NULL OR (o.id IS NULL AND g.send_at <= now())), \
count(*) FILTER (WHERE o.failed_at IS NOT NULL) \
FROM gifts g LEFT JOIN email_outbox o ON o.id = g.email_id \
WHERE g.send_at IS NOT NULL AND g.paid_at IS NOT NULL AND g.refunded_at IS NULL \
AND g.send_at > now() - interval '30 days' \
GROUP BY 1 ORDER BY 1",
)
.fetch_all(&state.db)
.await?;
let schedule: Vec<Value> = schedule
.into_iter()
.map(|(at, waiting, sent, failed)| json!({ "at": at, "waiting": waiting, "sent": sent, "failed": failed }))
.collect();
Ok(Json(json!({ "gifts": gifts, "schedule": schedule, "withdrawal_days": WITHDRAWAL_DAYS })))
}
/// Admin: refunds a gift the buyer withdrew from. Refused once it is
@@ -577,6 +711,8 @@ pub async fn admin_refund(
.bind(admin.0.id())
.execute(&mut *tx)
.await?;
// A timed e-mail not gone out yet stays unsent.
cancel_pending_email(&mut tx, &gift).await?;
if let Some((checkout_id, _)) = &checkout {
let reason = format!("Elállás az ajándékcsomag vásárlásától (beváltás előtt), kód: {}", display(gift.code()?));
sqlx::query(
@@ -634,3 +770,25 @@ pub async fn admin_refund(
json!({ "status": gift.status(), "refund_id": gift.refund_id, "refunded_at": rfc3339_opt(gift.refunded_at) }),
))
}
#[cfg(test)]
mod tests {
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use super::christmas_year;
fn at(s: &str) -> OffsetDateTime {
OffsetDateTime::parse(s, &Rfc3339).unwrap()
}
#[test]
fn christmas_runs_from_mid_november_to_epiphany() {
assert_eq!(christmas_year(at("2026-11-14T22:59:00Z")), None);
assert_eq!(christmas_year(at("2026-11-14T23:00:00Z")), Some(2027));
assert_eq!(christmas_year(at("2026-12-31T23:30:00Z")), Some(2027));
assert_eq!(christmas_year(at("2027-01-06T22:59:00Z")), Some(2027));
assert_eq!(christmas_year(at("2027-01-06T23:00:00Z")), None);
assert_eq!(christmas_year(at("2027-07-01T12:00:00Z")), None);
}
}
+7 -3
View File
@@ -327,6 +327,7 @@ async fn confirm_by_email(
"promo_code": gift.code,
"recipient_name": gift.recipient_name,
"recipient_email": gift.recipient_email,
"send_at": gift.send_at_local,
});
// Handed over by the buyer: the card comes with the confirmation.
if gift.recipient_email.is_none() {
@@ -375,13 +376,16 @@ pub async fn checkout_status(
}
let gift = match gift_id {
Some(id) => {
let (name, to): (Option<String>, Option<String>) =
sqlx::query_as("SELECT recipient_name, recipient_email FROM gifts WHERE id = $1")
let (name, to, send_at): (Option<String>, Option<String>, Option<OffsetDateTime>) =
sqlx::query_as("SELECT recipient_name, recipient_email, send_at FROM gifts WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?
.unwrap_or_default();
Some(json!({ "id": id, "recipient_name": name, "recipient_email": to }))
Some(json!({
"id": id, "recipient_name": name, "recipient_email": to,
"send_at": crate::views::rfc3339_opt(send_at.filter(|t| *t > OffsetDateTime::now_utc())),
}))
}
None => None,
};
+75 -3
View File
@@ -3413,7 +3413,7 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
.unwrap();
assert_eq!(
confirmation["gift"],
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com"})
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com", "send_at": null})
);
assert!(confirmation["gift_card"].is_null(), "the recipient has the card");
assert_eq!(confirmation["url"], "https://sorsfonalak.test/ajandekaim");
@@ -3426,7 +3426,10 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
.unwrap();
assert_eq!(invoices, 1);
let r = app.get(&format!("/v1/payments/checkout/{session}"), Some(&anna)).await;
assert_eq!(r.body["gift"], json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com"}));
assert_eq!(
r.body["gift"],
json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com", "send_at": null})
);
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
@@ -3459,8 +3462,10 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
sqlx::query("UPDATE gifts SET last_sent_at = now() - interval '11 minutes'").execute(&app.pool).await.unwrap();
let r = send("cili@example.com").await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(2)));
// The first e-mail had not gone out yet (no worker here): the corrected address replaces it.
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(1)));
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 0);
let r = app
.post(
&format!("/v1/gifts/{gift_id}/send"),
@@ -3960,3 +3965,70 @@ async fn the_recommendation_question_comes_once_after_two_contents(pool: PgPool)
);
assert_eq!(nps["comments"][0]["comment"], "Nagyon tetszik.");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_gift_can_be_e_mailed_at_a_chosen_time(pool: PgPool) {
// The stand-in payment: paid at once.
let app = TestApp::new(pool).await;
let anna = app.register("anna@example.com", "Anna").await;
let admin = app.register("admin@example.com", "Admin").await;
let at = (time::OffsetDateTime::now_utc() + time::Duration::days(10))
.replace_nanosecond(0)
.unwrap()
.format(&time::format_description::well_known::Rfc3339)
.unwrap();
let body = |send_at: &str, email: Option<&str>| {
json!({"package": "couple", "recipient_name": "Bea", "recipient_email": email,
"recipient_email_confirm": email, "send_at": send_at})
};
// In the past, or with nobody to e-mail: refused.
let past = app.post("/v1/gifts/checkout", Some(&anna), body("2020-01-01T08:00:00Z", Some("bea@example.com"))).await;
assert_eq!(past.status, StatusCode::BAD_REQUEST);
let nobody = app.post("/v1/gifts/checkout", Some(&anna), body(&at, None)).await;
assert_eq!(nobody.status, StatusCode::BAD_REQUEST);
let r = app.post("/v1/gifts/checkout", Some(&anna), body(&at, Some("bea@example.com"))).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let id = r.body["id"].as_str().unwrap().to_string();
// Queued for that moment, not sent yet.
let (due, sent): (time::OffsetDateTime, Option<time::OffsetDateTime>) = sqlx::query_as(
"SELECT next_attempt_at, sent_at FROM email_outbox WHERE to_email = 'bea@example.com' AND template = 'gift_package'",
)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!((due.format(&time::format_description::well_known::Rfc3339).unwrap(), sent), (at.clone(), None));
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
assert_eq!(
(&gift["email_state"], &gift["send_at"], &gift["can_send"]),
(&json!("scheduled"), &json!(at), &json!(true))
);
let r = app.get("/v1/admin/gifts", Some(&admin)).await;
assert_eq!(r.body["gifts"][0]["email_state"], "scheduled");
let slot = &r.body["schedule"][0];
assert_eq!((&slot["waiting"], &slot["sent"]), (&json!(1), &json!(0)));
// Sent now after all: the timed one is taken back (one e-mail, not two), and it is no extra sending.
let r = app
.post(
&format!("/v1/gifts/{id}/send"),
Some(&anna),
json!({"recipient_email": "bea@example.com", "recipient_email_confirm": "bea@example.com"}),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(
(&r.body["send_at"], &r.body["sendings"], &r.body["email_state"]),
(&Value::Null, &json!(1), &json!("sending"))
);
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 1);
// A timed gift refunded before it goes out: the e-mail stays unsent.
let r = app.post("/v1/gifts/checkout", Some(&anna), body(&at, Some("cili@example.com"))).await;
let other = r.body["id"].as_str().unwrap().to_string();
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
let r = app.post(&format!("/v1/admin/gifts/{other}/refund"), Some(&admin), json!({})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 0);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+33
View File
@@ -4,6 +4,8 @@ import { ChartWheel } from "@/components/ChartWheel";
import { Rich } from "@/components/Rich";
import { TarotCard, TarotCardBack } from "@/components/tarot/TarotCard";
import { PublicHeader } from "@/components/SiteHeader";
import { ChristmasTree } from "@/components/ChristmasTree";
import { isChristmasTime } from "@/lib/season";
import example from "@/content/pelda.json";
import { tarotCard } from "@/lib/tarot";
import type { AnalysisContent, ChartResult } from "@/lib/types";
@@ -42,6 +44,8 @@ const SYNASTRY_TOPICS = ["Vonzás", "Kommunikáció", "Érzelmi kötődés", "S
/** The home page for visitors: what the site does, shown on the example chart. */
/** `loggedIn`: the layout shows the app's header, and the buttons lead to the user's chart instead of the login. */
export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean; loggedIn?: boolean }) {
// In the Christmas season the gift band leads to the Christmas page.
const xmas = isChristmasTime();
const chart = example.chart as unknown as ChartResult;
const analysis = example.analysis as AnalysisContent;
const sections = ["emotions", "love"].map((k) => analysis.sections?.[k]).filter((s) => s !== undefined);
@@ -442,6 +446,35 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
</div>
</section>
<section className="lp-band lp-alt lp-gift" aria-labelledby="gift-band-title">
<div className="lp-wrap lp-gift-inner">
{xmas && <ChristmasTree size={72} />}
<div className="lp-gift-text">
<span className="eyebrow">{xmas ? "Karácsonyi ajándék" : "Ajándék"}</span>
<h2 id="gift-band-title" className="lp-h2">
{xmas ? "Ajándékozz csillagokat karácsonyra" : "Horoszkópot ajándékba"}
</h2>
<p className="lp-text">
Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve, egy szép, nyomtatható
utalvánnyal.{" "}
{xmas ? "Az e-mailt karácsony reggelre is időzítheted." : "E-mailben küldjük el neki, vagy te adod át."}
</p>
<Link href={xmas ? "/karacsony" : "/ajandek"} className="btn lp-btn">
{xmas ? "Karácsonyi ajándék" : "Ajándékozás"}
</Link>
</div>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className="lp-gift-card"
src={xmas ? "/img/ajandek-karacsony.webp" : "/img/ajandek-utalvany.webp"}
width={200}
height={283}
alt=""
loading="lazy"
/>
</div>
</section>
<section className="lp-band">
<div className="lp-wrap lp-stack">
<h2 className="lp-h2 lp-center">Így működik</h2>
@@ -8,6 +8,16 @@ import type { AdminGift } from "@/lib/types";
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
/** The timed gift e-mails of one hour. */
type Slot = { at: string; waiting: number; sent: number; failed: number };
const EMAIL: Record<string, string> = {
scheduled: "levél időzítve",
sending: "levél küldés alatt",
sent: "levél kiment",
failed: "levél hiba",
};
const STORNO: Record<string, string> = {
pending: "sztornó folyamatban",
done: "sztornózva",
@@ -17,6 +27,7 @@ const STORNO: Record<string, string> = {
/** The gifts with their payment, invoice and storno, and the refund button. */
export function AdminGifts() {
const [gifts, setGifts] = useState<AdminGift[] | null>(null);
const [schedule, setSchedule] = useState<Slot[]>([]);
const [q, setQ] = useState("");
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -24,10 +35,11 @@ export function AdminGifts() {
const load = useCallback(async (search: string) => {
try {
const r = await api<{ gifts: AdminGift[] }>(
const r = await api<{ gifts: AdminGift[]; schedule: Slot[] }>(
`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`,
);
setGifts(r.gifts);
setSchedule(r.schedule ?? []);
} catch (e) {
setError(errorText(e));
}
@@ -66,153 +78,203 @@ export function AdminGifts() {
}
return (
<section className="card">
<div className="field">
<label htmlFor="gift-search">Keresés</label>
<input
id="gift-search"
className="inp"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{done && (
<p className="msg msg-ok" role="status">
{done}
</p>
)}
{gifts === null ? (
<p className="muted">Betöltés…</p>
) : gifts.length === 0 ? (
<p className="muted">Nincs ilyen ajándék.</p>
) : (
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Kód</th>
<th>Csomag</th>
<th>Vásárló → címzett</th>
<th>Fizetve</th>
<th>Állapot</th>
<th>Számla</th>
<th />
</tr>
</thead>
<tbody>
{gifts.map((g) => (
<tr key={g.id}>
<td>
<code className="promo-code">{g.code}</code>
</td>
<td>
{g.package.name ?? g.package.id}
{g.checkout?.amount_huf ? (
<span className="hint">{huf(g.checkout.amount_huf)}</span>
) : null}
{g.checkout && g.checkout.live === false && (
<span className="hint">teszt fizetés</span>
)}
</td>
<td>
{g.buyer_email ?? (
<span className="muted">törölt fiók</span>
)}
<span className="hint">
→ {g.recipient_name ?? "?"}
{g.recipient_email
? ` (${g.recipient_email})`
: " (maga adja át)"}
</span>
</td>
<td className="num">{formatDate(g.paid_at, true)}</td>
<td>
{g.status === "redeemed" ? (
<>
beváltva{" "}
{g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
{g.redeemed_by && (
<span className="hint">{g.redeemed_by}</span>
)}
</>
) : g.status === "refunded" ? (
<>
{g.refund_pending ? (
<span className="msg-error">
visszatérítés félbemaradt
</span>
) : (
"visszatérítve"
)}{" "}
{g.refunded_at ? formatDate(g.refunded_at, true) : ""}
{g.refund_pending && g.refund_error && (
<span className="hint">{g.refund_error}</span>
)}
</>
) : (
<>
<span className="promo-open">beváltatlan</span>
<span className="hint">
{g.within_withdrawal
? "14 napon belül"
: "14 nap letelt"}
</span>
</>
)}
</td>
<td>
{g.invoice ? (
<>
{g.invoice.number ??
(g.invoice.status === "pending"
? "kiállítás alatt"
: g.invoice.status)}
{g.storno && (
<span
className={
g.storno.status === "failed"
? "hint msg-error"
: "hint"
}
>
{STORNO[g.storno.status] ?? g.storno.status}
{g.storno.number ? `: ${g.storno.number}` : ""}
{g.storno.error ? ` – ${g.storno.error}` : ""}
</span>
)}
</>
) : (
<span className="muted">–</span>
)}
</td>
<td>
{(g.status === "open" || g.refund_pending) && (
<button
type="button"
className="btn btn-sm"
onClick={() => refund(g)}
disabled={busy !== null}
>
{busy === g.id
? "Folyamatban…"
: g.status === "refunded"
? "Újrapróbálás"
: "Visszatérítés"}
</button>
)}
</td>
<>
{schedule.length > 0 && (
<section className="card" aria-labelledby="schedule-title">
<h2 id="schedule-title">Időzített levelek</h2>
<p className="hint">
Az időzítve küldött ajándéklevelek óránként (magyar idő, az elmúlt
30 nap és ami még jön). Figyeld, hogy a kiment levelek száma az
időpont után megnőjön, és ne legyen hiba.
</p>
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Időpont</th>
<th>Vár</th>
<th>Kiment</th>
<th>Hiba</th>
</tr>
))}
</tbody>
</table>
</div>
</thead>
<tbody>
{schedule.map((s) => (
<tr key={s.at}>
<td className="num">{s.at}</td>
<td className="num">{s.waiting || "–"}</td>
<td className="num">{s.sent || "–"}</td>
<td className={s.failed ? "num msg-error" : "num"}>
{s.failed || "–"}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
)}
</section>
<section className="card">
<div className="field">
<label htmlFor="gift-search">Keresés</label>
<input
id="gift-search"
className="inp"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{done && (
<p className="msg msg-ok" role="status">
{done}
</p>
)}
{gifts === null ? (
<p className="muted">Betöltés…</p>
) : gifts.length === 0 ? (
<p className="muted">Nincs ilyen ajándék.</p>
) : (
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Kód</th>
<th>Csomag</th>
<th>Vásárló → címzett</th>
<th>Fizetve</th>
<th>Állapot</th>
<th>Számla</th>
<th />
</tr>
</thead>
<tbody>
{gifts.map((g) => (
<tr key={g.id}>
<td>
<code className="promo-code">{g.code}</code>
</td>
<td>
{g.package.name ?? g.package.id}
{g.checkout?.amount_huf ? (
<span className="hint">
{huf(g.checkout.amount_huf)}
</span>
) : null}
{g.checkout && g.checkout.live === false && (
<span className="hint">teszt fizetés</span>
)}
</td>
<td>
{g.buyer_email ?? (
<span className="muted">törölt fiók</span>
)}
<span className="hint">
→ {g.recipient_name ?? "?"}
{g.recipient_email
? ` (${g.recipient_email})`
: " (maga adja át)"}
</span>
{g.email_state && (
<span
className={
g.email_state === "failed"
? "hint msg-error"
: "hint"
}
>
{EMAIL[g.email_state]}
{g.send_at ? ` · ${formatDate(g.send_at, true)}` : ""}
</span>
)}
</td>
<td className="num">{formatDate(g.paid_at, true)}</td>
<td>
{g.status === "redeemed" ? (
<>
beváltva{" "}
{g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
{g.redeemed_by && (
<span className="hint">{g.redeemed_by}</span>
)}
</>
) : g.status === "refunded" ? (
<>
{g.refund_pending ? (
<span className="msg-error">
visszatérítés félbemaradt
</span>
) : (
"visszatérítve"
)}{" "}
{g.refunded_at ? formatDate(g.refunded_at, true) : ""}
{g.refund_pending && g.refund_error && (
<span className="hint">{g.refund_error}</span>
)}
</>
) : (
<>
<span className="promo-open">beváltatlan</span>
<span className="hint">
{g.within_withdrawal
? "14 napon belül"
: "14 nap letelt"}
</span>
</>
)}
</td>
<td>
{g.invoice ? (
<>
{g.invoice.number ??
(g.invoice.status === "pending"
? "kiállítás alatt"
: g.invoice.status)}
{g.storno && (
<span
className={
g.storno.status === "failed"
? "hint msg-error"
: "hint"
}
>
{STORNO[g.storno.status] ?? g.storno.status}
{g.storno.number ? `: ${g.storno.number}` : ""}
{g.storno.error ? ` – ${g.storno.error}` : ""}
</span>
)}
</>
) : (
<span className="muted">–</span>
)}
</td>
<td>
{(g.status === "open" || g.refund_pending) && (
<button
type="button"
className="btn btn-sm"
onClick={() => refund(g)}
disabled={busy !== null}
>
{busy === g.id
? "Folyamatban…"
: g.status === "refunded"
? "Újrapróbálás"
: "Visszatérítés"}
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</>
);
}
+112 -1
View File
@@ -7,6 +7,7 @@ import { useEffect, useId, useState } from "react";
import { huf } from "@/components/PackageCards";
import { api, errorText } from "@/lib/api";
import { contents } from "@/lib/packageContents";
import { christmasMorning } from "@/lib/season";
import type { Package, PayMethod } from "@/lib/types";
const MAX_MESSAGE = 300;
@@ -17,6 +18,19 @@ const looksLikeEmail = (s: string) =>
const same = (a: string, b: string) =>
a.trim().toLowerCase() === b.trim().toLowerCase();
/** `2026-12-24` on the browser's clock. */
const localDay = (d: Date) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
/** "dec. 24. 8:00" */
const whenText = (d: Date) =>
d.toLocaleString("hu-HU", {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
/**
* The gift order: which package, whom it is for and from whom, how it gets
* to the recipient (we e-mail it, the address typed twice; or the buyer
@@ -49,6 +63,10 @@ export function GiftForm({
const [confirm, setConfirm] = useState("");
const [from, setFrom] = useState(defaultFrom.slice(0, MAX_NAME));
const [message, setMessage] = useState("");
const [timed, setTimed] = useState(false);
const xmas = christmasMorning();
const [day, setDay] = useState(xmas ? localDay(xmas) : "");
const [clock, setClock] = useState("08:00");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Back from Stripe's page (the browser may restore this page as it was).
@@ -64,6 +82,14 @@ export function GiftForm({
const mismatch = byEmail && confirm.trim() !== "" && !same(email, confirm);
const emailOk = !byEmail || (looksLikeEmail(email) && same(email, confirm));
const stripe = canPay === "stripe" || canPay === "stripe_test";
// The chosen moment on the buyer's own clock.
const sendAt = day && clock ? new Date(`${day}T${clock}`) : null;
const ahead = sendAt ? sendAt.getTime() - Date.now() : 0;
const timeOk =
sendAt !== null &&
!Number.isNaN(ahead) &&
ahead > 10 * 60 * 1000 &&
ahead < 365 * 86400 * 1000;
async function submit(e: React.FormEvent) {
e.preventDefault();
@@ -81,6 +107,7 @@ export function GiftForm({
recipient_email_confirm: byEmail ? confirm.trim() : null,
from_name: from.trim() || null,
message: message.trim() || null,
send_at: byEmail && timed && sendAt ? sendAt.toISOString() : null,
},
},
);
@@ -223,6 +250,81 @@ export function GiftForm({
</div>
</div>
)}
{byEmail && (
<div className="gift-when">
<span className="label">Mikor kapja meg?</span>
<div className="gift-when-choices">
<label
className={!timed ? "feedback-kind is-on" : "feedback-kind"}
>
<input
type="radio"
name={`${id}-when`}
checked={!timed}
onChange={() => setTimed(false)}
/>
Fizetés után azonnal
</label>
<label
className={timed ? "feedback-kind is-on" : "feedback-kind"}
>
<input
type="radio"
name={`${id}-when`}
checked={timed}
onChange={() => setTimed(true)}
/>
Időzítve
</label>
{xmas && (
<button
type="button"
className="btn btn-sm"
onClick={() => {
setTimed(true);
setDay(localDay(xmas));
setClock("08:00");
}}
>
Karácsony reggel (dec. 24., 8:00)
</button>
)}
</div>
{timed && (
<div className="gift-when-fields">
<div className="field">
<label htmlFor={`${id}-day`}>Nap</label>
<input
id={`${id}-day`}
className="inp"
type="date"
value={day}
min={localDay(new Date())}
onChange={(e) => setDay(e.target.value)}
/>
</div>
<div className="field">
<label htmlFor={`${id}-clock`}>Időpont</label>
<input
id={`${id}-clock`}
className="inp"
type="time"
step={900}
value={clock}
onChange={(e) => setClock(e.target.value)}
/>
</div>
</div>
)}
<span className={timed && !timeOk ? "msg msg-error" : "hint"}>
{timed
? timeOk
? "A te időd szerint. Addig az Ajándékaim oldalon letöltheted az utalványt, vagy elküldheted azonnal is."
: "Válassz egy jövőbeli időpontot (legfeljebb egy évre előre)."
: "Ha későbbre szánod, időzítsd, vagy válaszd az „Én adom át” lehetőséget."}
</span>
</div>
)}
</fieldset>
<div className="field">
@@ -253,6 +355,9 @@ export function GiftForm({
<span className="muted">
„{chosen.name}” csomag ajándékba
{name.trim() ? `, ${name.trim()} részére` : ""}
{byEmail && timed && sendAt && timeOk
? ` · küldés: ${whenText(sendAt)}`
: ""}
</span>
<strong className="num">{huf(chosen.price_huf)}</strong>
</p>
@@ -261,7 +366,13 @@ export function GiftForm({
<button
type="submit"
className="btn btn-primary"
disabled={busy || !chosen || !emailOk || !name.trim()}
disabled={
busy ||
!chosen ||
!emailOk ||
!name.trim() ||
(byEmail && timed && !timeOk)
}
>
{busy
? stripe
+42 -11
View File
@@ -1,25 +1,50 @@
import type { Metadata } from "next";
import Link from "next/link";
import { GiftLanding } from "@/components/GiftLanding";
import { PublicHeader } from "@/components/SiteHeader";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import { isChristmasTime } from "@/lib/season";
import { backendGet, getMe } from "@/lib/server";
import { siteUrl } from "@/lib/share";
import type { Gift, Package, PublicConfig } from "@/lib/types";
import { GiftForm } from "./GiftForm";
export const metadata: Metadata = {
title: "Ajándék csomag",
robots: { index: false },
};
export async function generateMetadata(): Promise<Metadata> {
const base = await siteUrl();
const title = "Horoszkóp ajándékba";
const description =
"Ajándékozz születési képletet, személyre szóló elemzést és éves előrejelzést. Nyomtatható utalvány, e-mailben időzítve vagy személyesen átadva.";
return {
title,
description,
alternates: { canonical: `${base}/ajandek` },
openGraph: { type: "website", siteName: "Sorsfonalak", locale: "hu_HU", url: `${base}/ajandek`, title, description },
};
}
type Props = { searchParams: Promise<{ csomag?: string }> };
/** Buying a package as a gift; `?csomag=` picks the package (links on the package cards). */
export default async function GiftPage({ searchParams }: Props) {
const { csomag } = await searchParams;
const me = await requireMe(
csomag ? `/ajandek?csomag=${encodeURIComponent(csomag)}` : "/ajandek",
);
const me = await getMe();
if (!me) {
// Visitors (and search engines) get the page about giving; the form needs a login.
const catalog = await backendGet<{ packages: Package[] }>("/v1/packages");
return (
<>
<PublicHeader />
<GiftLanding
packages={(catalog?.packages ?? []).filter((p) => p.tier === "main")}
loggedIn={false}
christmas={false}
season={isChristmasTime()}
/>
</>
);
}
const [catalog, config, mine] = await Promise.all([
backendGet<{ packages: Package[] }>("/v1/packages"),
backendGet<PublicConfig>("/v1/config"),
@@ -27,11 +52,13 @@ export default async function GiftPage({ searchParams }: Props) {
]);
const packages = (catalog?.packages ?? []).filter((p) => p.tier === "main");
const given = mine?.gifts.length ?? 0;
// Gifts bought now get the Christmas card.
const xmas = isChristmasTime();
return (
<main className="page" style={{ maxWidth: 1080 }}>
<div className="page-head">
<span className="eyebrow">Ajándék</span>
<span className="eyebrow">{xmas ? "Karácsonyi ajándék" : "Ajándék"}</span>
<h1>Ajándékozz csomagot</h1>
<p className="muted">
Születési képlet, személyre szóló elemzések, kapcsolati összevetés:
@@ -57,7 +84,7 @@ export default async function GiftPage({ searchParams }: Props) {
<figure className="gift-sample">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/img/ajandek-utalvany.webp"
src={xmas ? "/img/ajandek-karacsony.webp" : "/img/ajandek-utalvany.webp"}
width={420}
height={594}
alt="Minta ajándékutalvány: a csomag neve, a személyes üzenet, az ajándékkód és a QR-kód"
@@ -81,7 +108,11 @@ export default async function GiftPage({ searchParams }: Props) {
<p className="hint">
A kód nem jár le, és egyszer váltható be. A számlát te kapod. Ha
meggondolod magad, 14 napon belül, beváltás előtt visszakérheted
az árát: írj az info@sorsfonalak.hu címre.
az árát:{" "}
<Link href="/visszajelzes?tipus=other&honnan=/ajandekaim">
írd meg nekünk itt
</Link>
.
</p>
</section>
</aside>
@@ -12,6 +12,15 @@ const day = (iso: string) =>
month: "long",
day: "numeric",
});
/** "december 24., 8:00" */
const when = (iso: string) =>
new Date(iso).toLocaleString("hu-HU", {
timeZone: "Europe/Budapest",
month: "long",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
const time = (iso: string) =>
new Date(iso).toLocaleTimeString("hu-HU", {
timeZone: "Europe/Budapest",
@@ -127,7 +136,19 @@ function GiftItem({
</div>
<p className="gift-to">
{gift.recipient_email ? (
{gift.recipient_email &&
gift.email_state === "scheduled" &&
gift.send_at ? (
<>
Időzítve: <strong>{when(gift.send_at)}</strong>, ide:{" "}
<strong>{gift.recipient_email}</strong>
</>
) : gift.recipient_email && gift.email_state === "failed" ? (
<>
Nem sikerült elküldeni ide: <strong>{gift.recipient_email}</strong>.
Ellenőrizd a címet, és küldd újra.
</>
) : gift.recipient_email ? (
<>
E-mailben elküldve ide: <strong>{gift.recipient_email}</strong>
{gift.sendings > 1 ? ` (${gift.sendings}×)` : ""}
@@ -165,9 +186,11 @@ function GiftItem({
className="btn btn-sm"
onClick={() => setSending(true)}
>
{gift.recipient_email
? "Újraküldés e-mailben"
: "Küldés e-mailben"}
{gift.email_state === "scheduled"
? "Küldés most"
: gift.recipient_email
? "Újraküldés e-mailben"
: "Küldés e-mailben"}
</button>
)}
</div>
+9 -4
View File
@@ -5,6 +5,8 @@ import { AiNote } from "@/components/AiNote";
import { PackageCards } from "@/components/PackageCards";
import { RedeemCode } from "@/components/RedeemCode";
import { payMethod } from "@/lib/payments";
import { isChristmasTime } from "@/lib/season";
import { ChristmasTree } from "@/components/ChristmasTree";
import { backendGet, requireMe } from "@/lib/server";
import type { Package, PublicConfig } from "@/lib/types";
@@ -50,6 +52,7 @@ export default async function PackagesPage() {
]);
const packages = catalog?.packages ?? [];
const canPay = payMethod(config, me);
const xmas = isChristmasTime();
const left = me.analyses_left;
const slots = me.persons;
@@ -99,15 +102,17 @@ export default async function PackagesPage() {
<PackageCards packages={packages} canPay={canPay} giftLinks />
<section className="card gift-banner" aria-labelledby="gift-title">
<div>
<h2 id="gift-title">Ajándékba is adhatod</h2>
{xmas && <ChristmasTree />}
<div className="gift-banner-text">
<h2 id="gift-title">{xmas ? "Karácsonyi ajándék a csillagokból" : "Ajándékba is adhatod"}</h2>
<p className="muted">
A három fő csomag bármelyikét megveheted másnak: e-mailben elküldjük neki egy nyomtatható utalvánnyal, vagy
letöltöd, és te adod át. A kódot ő váltja be a saját fiókjában, és nem jár le.
{xmas && " Karácsony reggelre is időzítheted."}
</p>
</div>
<Link className="btn" href="/ajandek">
Megajándékozok valakit
<Link className="btn" href={xmas ? "/karacsony" : "/ajandek"}>
{xmas ? "Karácsonyi ajándék" : "Megajándékozok valakit"}
</Link>
</section>
+109
View File
@@ -1534,6 +1534,8 @@ span.tarot-fan-card { cursor: default; }
.gift-banner h2 { font-size: 24px; }
.gift-banner p { margin: 6px 0 0; }
.gift-banner .btn { flex: none; }
.gift-banner-text { flex: 1; }
.gift-banner .xmas-tree { flex: none; filter: drop-shadow(0 0 10px rgba(217, 180, 106, 0.25)); }
.gift-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 24px; align-items: start; }
.gift-aside { display: flex; flex-direction: column; gap: 16px; }
.gift-sample { margin: 0; display: flex; flex-direction: column; gap: 8px; align-items: center; }
@@ -1586,6 +1588,7 @@ span.tarot-fan-card { cursor: default; }
}
@media (max-width: 640px) {
.gift-banner { flex-direction: column; align-items: stretch; }
.gift-banner .xmas-tree { align-self: center; }
.gift-packages, .gift-ways { grid-template-columns: 1fr; }
.gift-packages .gift-option-head { flex-direction: row; align-items: baseline; justify-content: space-between; }
.gift-aside { flex-direction: column; }
@@ -1675,3 +1678,109 @@ span.tarot-fan-card { cursor: default; }
.nps-score { min-width: 34px; }
}
.contact-card p { margin: 0; }
/* The app header (logged in): a starry band with a gold edge, menu items with
gold marks, the free pages in one dropdown, and the Moon today. */
.app-header {
background:
radial-gradient(1px 1px at 22% 28%, rgba(236, 230, 216, 0.6), transparent 60%),
radial-gradient(1px 1px at 47% 72%, rgba(236, 230, 216, 0.4), transparent 60%),
radial-gradient(1.5px 1.5px at 66% 20%, rgba(217, 180, 106, 0.7), transparent 60%),
radial-gradient(1px 1px at 83% 70%, rgba(236, 230, 216, 0.45), transparent 60%),
radial-gradient(1px 1px at 95% 30%, rgba(236, 230, 216, 0.5), transparent 60%),
rgba(15, 21, 40, 0.95);
border-bottom-color: transparent;
}
.app-header::after {
content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 1px; pointer-events: none;
background: linear-gradient(90deg, rgba(217, 180, 106, 0), rgba(217, 180, 106, 0.6) 30%, rgba(217, 180, 106, 0.6) 70%, rgba(217, 180, 106, 0));
}
.nav-icon { width: 17px; height: 17px; flex: none; color: rgba(217, 180, 106, 0.8); fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linejoin: round; stroke-linecap: round; }
.nav-icon.sym { width: auto; height: auto; font-size: 17px; line-height: 1; text-align: center; min-width: 17px; }
.nav-icon .nav-icon-fill { fill: currentColor; stroke: none; }
.app-nav { gap: 2px; align-items: center; }
.app-nav > a, .nav-group-button {
display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 10px 11px;
color: var(--ink-2); text-decoration: none; border-radius: 8px 8px 0 0; border-bottom: 2px solid transparent; font-size: 15px;
}
.app-nav > a:hover, .nav-group-button:hover { color: var(--ink); background: rgba(217, 180, 106, 0.06); }
.app-nav > a[aria-current="page"], .nav-group-button.is-active {
color: var(--ink); background: none; border-bottom-color: var(--gold); box-shadow: 0 7px 12px -9px rgba(217, 180, 106, 0.9);
}
.app-nav > a[aria-current="page"] .nav-icon, .nav-group-button.is-active .nav-icon { color: var(--gold); }
.nav-group { position: relative; }
.nav-group-button { background: none; border-top: 0; border-left: 0; border-right: 0; font-family: inherit; cursor: pointer; }
.nav-group-button[aria-expanded="true"] { color: var(--gold); background: rgba(217, 180, 106, 0.1); border-radius: 8px; }
.nav-group-chevron { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.nav-group-button[aria-expanded="true"] .nav-group-chevron { transform: rotate(180deg); }
.nav-dropdown {
position: absolute; left: 0; top: calc(100% + 8px); z-index: 30; width: 340px; padding: 8px;
display: flex; flex-direction: column; gap: 2px; background: var(--panel); border: 1px solid var(--line-2);
border-radius: 14px; box-shadow: 0 18px 44px rgba(0, 0, 0, 0.5);
}
.nav-dropdown-title { padding: 6px 10px 8px; font-size: 11px; font-weight: 600; letter-spacing: 1.2px; text-transform: uppercase; color: var(--gold); }
.nav-dropdown-item { display: flex; gap: 12px; align-items: flex-start; padding: 10px; border-radius: 10px; color: var(--ink); text-decoration: none; }
.nav-dropdown-item:hover, .nav-dropdown-item[aria-current="page"] { background: rgba(255, 255, 255, 0.04); color: var(--gold); }
.nav-dropdown-item .nav-icon { margin-top: 2px; width: 20px; height: 20px; font-size: 19px; color: var(--gold); }
.nav-dropdown-text { display: flex; flex-direction: column; gap: 2px; font-size: 15px; }
.nav-dropdown-text .hint { font-size: 13px; }
.moon-chip {
display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px 0 8px; border-radius: 999px;
background: rgba(217, 180, 106, 0.08); color: var(--ink); text-decoration: none; font-size: 13px; white-space: nowrap;
}
.moon-chip:hover { background: rgba(217, 180, 106, 0.14); color: var(--ink); }
.moon-chip-glyph { color: var(--gold); font-size: 15px; }
.moon-phase-icon { width: 20px; height: 20px; flex: none; }
.moon-phase-icon .moon-dark { fill: #1a2238; stroke: var(--gold); stroke-width: 1; }
.moon-phase-icon .moon-lit { fill: var(--gold); }
@media (max-width: 1760px) { .app-header .who .moon-chip-text { display: none; } .app-header .who .moon-chip { padding: 0 10px 0 8px; } }
/* The grouped ☰ menu of the app. */
.mobile-menu-panel > .moon-chip { align-self: stretch; min-height: 48px; padding: 0 14px; font-size: 14px; border-radius: 12px; }
.mobile-menu-list { display: flex; flex-direction: column; }
.mobile-menu-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
.mobile-menu-grid a { border: 1px solid var(--line); font-size: 15px; }
.mobile-menu-panel a { gap: 12px; }
.mobile-menu-panel a .nav-icon { color: var(--gold); }
.mobile-menu-label { flex: 1; min-width: 0; }
.mobile-menu-note { font-size: 13px; color: var(--gold); white-space: nowrap; }
/* Laptops (1440px): the items closer, so the row still fits next to the account. */
@media (max-width: 1520px) {
.app-nav > a, .nav-group-button { padding: 10px 7px; gap: 6px; font-size: 14.5px; }
.app-header { gap: 16px; }
.app-header .who { gap: 8px; }
}
/* The ☰ panel covers the page fully (the header's blur showed it through). */
.mobile-menu-panel { background: #0f1528; }
/* When the gift e-mail goes: at once, or timed (e.g. Christmas morning). */
.gift-when { display: flex; flex-direction: column; gap: 10px; padding-top: 6px; }
.gift-when-choices { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.gift-when-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 220px)); gap: 12px; }
@media (max-width: 640px) { .gift-when-fields { grid-template-columns: 1fr 1fr; } }
/* The Christmas campaign page */
.xmas-hero { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 32px; align-items: center; }
.xmas-hero-text { display: flex; flex-direction: column; gap: 14px; }
.xmas-hero h1 { font-size: clamp(40px, 5vw, 60px); }
.xmas-hero .lead { font-size: 18px; line-height: 1.6; color: var(--ink-2); margin: 0; }
.xmas-points { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
.xmas-points .card { gap: 8px; }
.xmas-points h2 { font-size: 24px; }
.xmas-points p { margin: 0; line-height: 1.6; }
.xmas-delivery ul { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 8px; color: var(--ink-2); }
.xmas-packages { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
@media (max-width: 900px) {
.xmas-hero { grid-template-columns: 1fr; }
.xmas-sample img { max-width: 260px; }
.xmas-points, .xmas-packages { grid-template-columns: 1fr; }
}
/* The home page gift band */
.lp-gift-inner { display: flex; align-items: center; gap: 32px; }
.lp-gift-text { flex: 1; display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
.lp-gift-text .lp-text { margin: 0; }
.lp-gift .xmas-tree { flex: none; filter: drop-shadow(0 0 14px rgba(217, 180, 106, 0.3)); }
.lp-gift-card { flex: none; width: 200px; height: auto; border-radius: 6px; transform: rotate(3deg); box-shadow: 0 18px 40px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(217, 180, 106, 0.25); }
.xmas-hero-text .xmas-tree { filter: drop-shadow(0 0 10px rgba(217, 180, 106, 0.3)); }
@media (max-width: 760px) {
.lp-gift-inner { flex-direction: column; text-align: center; }
.lp-gift-text { align-items: center; }
.lp-gift-card { width: 160px; }
}
@@ -0,0 +1,60 @@
import type { Metadata } from "next";
import { GiftLanding } from "@/components/GiftLanding";
import { PublicHeader } from "@/components/SiteHeader";
import { isChristmasTime } from "@/lib/season";
import { backendGet, getMe } from "@/lib/server";
import { siteUrl } from "@/lib/share";
import type { Package } from "@/lib/types";
export async function generateMetadata(): Promise<Metadata> {
const base = await siteUrl();
const title = "Karácsonyi ajándék a csillagokból";
const description =
"Ajándékozz születési képletet, személyre szóló elemzést, és azt, mit hoz neki a következő éve. Nyomtatható utalvány, karácsony reggelre időzíthető levél.";
const image = {
url: `${base}/kep/karacsony.png?v=1`,
width: 1200,
height: 630,
alt: title,
};
return {
title,
description,
alternates: { canonical: `${base}/karacsony` },
openGraph: {
type: "website",
siteName: "Sorsfonalak",
locale: "hu_HU",
url: `${base}/karacsony`,
title,
description,
images: [image],
},
twitter: {
card: "summary_large_image",
title,
description,
images: [image.url],
},
};
}
/** The Christmas campaign: the gift packages, with the year ahead as the hook. */
export default async function ChristmasPage() {
const [me, catalog] = await Promise.all([
getMe(),
backendGet<{ packages: Package[] }>("/v1/packages"),
]);
return (
<>
{!me && <PublicHeader />}
<GiftLanding
packages={(catalog?.packages ?? []).filter((p) => p.tier === "main")}
loggedIn={me !== null}
christmas
season={isChristmasTime()}
/>
</>
);
}
@@ -0,0 +1,21 @@
// The link preview image of the Christmas page (og:image), drawn from the
// example chart. The page links it with a version (?v=…).
import example from "@/content/pelda.json";
import { chartCard } from "@/lib/ogCard";
import type { ChartResult } from "@/lib/types";
export async function GET() {
return chartCard({
chart: example.chart as unknown as ChartResult,
timeKnown: true,
eyebrow: "KARÁCSONYI AJÁNDÉK",
title: "Ajándék a csillagokból.",
text: "Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve. Nyomtatható utalvánnyal, karácsony reggelre időzítve.",
lines: [
{ glyph: "☉", label: "Születési képlet" },
{ glyph: "♃", label: "A következő éve" },
{ glyph: "♀", label: "Kapcsolati elemzés" },
],
cacheControl: "public, max-age=86400, s-maxage=604800",
});
}
+4 -1
View File
@@ -9,6 +9,7 @@ import { SiteFooter } from "@/components/PublicFooter";
import { SiteHeader } from "@/components/SiteHeader";
import { ValidationMessages } from "@/components/ValidationMessages";
import { getMe } from "@/lib/server";
import { loadSky } from "@/lib/sky";
import { siteUrl } from "@/lib/share";
import "./globals.css";
@@ -31,12 +32,14 @@ export async function generateMetadata(): Promise<Metadata> {
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const me = await getMe();
// The Moon today in the header (cached for five minutes).
const sky = me ? await loadSky() : null;
return (
<html lang="hu" className={`${cormorant.variable} ${inter.variable}`}>
<body>
<NightSky />
<ValidationMessages />
{me && <SiteHeader me={me} />}
{me && <SiteHeader me={me} sky={sky} />}
{children}
{/* At the very bottom, apart from the page content: up top it drew the eye away. */}
{me?.nps_due && <NpsBanner />}
+2
View File
@@ -33,6 +33,8 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
{ url: `${base}/aszf`, changeFrequency: "yearly", priority: 0.2 },
{ url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 },
{ url: `${base}/karacsony`, changeFrequency: "monthly", priority: 0.7 },
{ url: `${base}/ajandek`, changeFrequency: "monthly", priority: 0.6 },
{ url: `${base}/adatvedelem`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
{ url: `${base}/privacy`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
];
@@ -0,0 +1,44 @@
/** A Christmas tree in the site's gold line style, with a star on top. */
export function ChristmasTree({ size = 64 }: { size?: number }) {
return (
<svg
className="xmas-tree"
width={size}
height={size * 1.25}
viewBox="0 0 64 80"
aria-hidden="true"
fill="none"
stroke="#d9b46a"
strokeWidth="2"
strokeLinejoin="round"
strokeLinecap="round"
>
{/* The star */}
<path
d="M32 2 L34.4 8 L40.6 8.6 L35.9 12.7 L37.3 18.8 L32 15.6 L26.7 18.8 L28.1 12.7 L23.4 8.6 L29.6 8 Z"
fill="#d9b46a"
/>
{/* Three tiers */}
<path
d="M32 20 L44 34 L38 34 L50 49 L42 49 L56 65 L8 65 L22 49 L14 49 L26 34 L20 34 Z"
fill="rgba(217,180,106,0.08)"
/>
{/* Garland */}
<path
d="M23 41 Q33 45 42 39 M17 56 Q31 61 47 54"
strokeWidth="1.2"
opacity="0.7"
/>
{/* Baubles */}
<g stroke="none">
<circle cx="29" cy="30" r="1.8" fill="#ece6d8" />
<circle cx="36" cy="44" r="2" fill="#d9b46a" />
<circle cx="25" cy="50" r="1.8" fill="#ece6d8" />
<circle cx="41" cy="59" r="2" fill="#ece6d8" />
<circle cx="20" cy="61" r="1.8" fill="#d9b46a" />
</g>
{/* Trunk */}
<path d="M28 65 L28 74 L36 74 L36 65" />
</svg>
);
}
@@ -0,0 +1,181 @@
import Link from "next/link";
import { ChristmasTree } from "@/components/ChristmasTree";
import { contents } from "@/lib/packageContents";
import type { Package } from "@/lib/types";
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
/** Where a "give this" button leads: the gift form, through the login when logged out. */
export function giftHref(loggedIn: boolean, packageId?: string): string {
const form = packageId
? `/ajandek?csomag=${encodeURIComponent(packageId)}`
: "/ajandek";
return loggedIn ? form : `/belepes?vissza=${encodeURIComponent(form)}`;
}
/**
* The public page about giving a package (crawlable, no login): `/karacsony`
* in the Christmas campaign, `/ajandek` for visitors all year.
*/
export function GiftLanding({
packages,
loggedIn,
christmas,
season,
}: {
packages: Package[];
loggedIn: boolean;
/** The Christmas page: wording, card and tree. */
christmas: boolean;
/** It is Christmas time (a timed Christmas e-mail can be mentioned). */
season: boolean;
}) {
return (
<main className="page xmas-page" style={{ maxWidth: 1080 }}>
<section className="xmas-hero">
<div className="xmas-hero-text">
{christmas && <ChristmasTree size={44} />}
<span className="eyebrow">
{christmas ? "Karácsonyi ajándék" : "Ajándék"}
</span>
<h1>
{christmas ? "Ajándék a csillagokból" : "Horoszkóp ajándékba"}
</h1>
<p className="lead">
{christmas
? "Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve. Annak, akit szeretsz, egy szép, nyomtatható utalvánnyal."
: "Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve. Születésnapra, évfordulóra vagy csak úgy, egy szép, nyomtatható utalvánnyal."}
</p>
<div className="form-actions">
<Link className="btn btn-primary" href={giftHref(loggedIn)}>
Megajándékozok valakit
</Link>
<a className="btn" href="#csomagok">
A csomagok
</a>
</div>
{!loggedIn && (
<p className="hint">
Az ajándékozáshoz be kell lépned, vagy regisztrálnod.
</p>
)}
</div>
<figure className="gift-sample xmas-sample">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={
christmas
? "/img/ajandek-karacsony.webp"
: "/img/ajandek-utalvany.webp"
}
width={420}
height={594}
alt={
christmas
? "Minta karácsonyi ajándékutalvány: Boldog karácsonyt és csillagos 2027-et, a csomag, az üzenet és az ajándékkód"
: "Minta ajándékutalvány: a képlet, a csomag, a személyes üzenet és az ajándékkód"
}
/>
<figcaption className="hint">
{christmas
? "A karácsonyi utalvány (A4-es PDF, nyomtatható)"
: "Az utalvány (A4-es PDF, nyomtatható)"}
</figcaption>
</figure>
</section>
<section className="xmas-points" aria-label="Mit kap?">
<div className="card">
<h2>A születési képlete</h2>
<p className="muted">
Percre pontosan kiszámolva és megrajzolva, mellé egy részletes
elemzés hat fejezetben: személyiség, érzelmek, gondolkodás,
szerelem, hivatás, fejlődés.
</p>
</div>
<div className="card">
<h2>A következő éve</h2>
<p className="muted">
Az éves előrejelzés a születésnapjától egy évre szól: mit hoznak a
bolygók, mire figyeljen, negyedévenként idővonallal. A Páros és a
Család csomagban benne van.
</p>
</div>
<div className="card">
<h2>Kettőtökről</h2>
<p className="muted">
A Páros csomagban kapcsolati elemzés is jár: mi vonz, hol súrlódtok,
és mit ad a kapcsolat. Szép ajándék párnak, testvérnek, barátnak.
</p>
</div>
</section>
<section
className="card xmas-delivery"
aria-labelledby="gift-delivery-title"
>
<h2 id="gift-delivery-title">
{christmas ? "Karácsony reggelre" : "Így kapja meg"}
</h2>
<ul>
<li>
<strong>Időzítve e-mailben:</strong>{" "}
{christmas
? "a levél az utalvánnyal december 24-én reggel érkezik meg hozzá (vagy amikor választod)."
: `a levél az utalvánnyal akkor érkezik meg hozzá, amikor választod, például a születésnapja reggelén${season ? " vagy karácsony reggel" : ""}. Vagy azonnal, fizetés után.`}
</li>
<li>
<strong>Te adod át:</strong>{" "}
{christmas
? "letöltöd az utalványt, kinyomtatod, és a fa alá teszed."
: "letöltöd az utalványt, kinyomtatod, és személyesen adod oda."}
</li>
<li>
<strong>Ő váltja be:</strong> belép vagy regisztrál, beírja a kódot,
és a csomag az övé. A kód nem jár le.
</li>
</ul>
</section>
<section
id="csomagok"
className="field"
aria-labelledby="gift-packages-title"
style={{ gap: 16 }}
>
<h2 id="gift-packages-title">Melyiket adnád?</h2>
<div className="xmas-packages">
{packages.map((p) => (
<article
key={p.id}
className={p.badge ? "pkg pkg-featured" : "pkg"}
>
<h3 className="pkg-name">{p.name}</h3>
<p className="muted pkg-tagline">{p.tagline}</p>
<div className="pkg-price">
<strong>{huf(p.price_huf)}</strong>
</div>
<ul className="pkg-list">
{contents(p).map((line) => (
<li key={line}>{line}</li>
))}
</ul>
<Link
className={p.badge ? "btn btn-primary" : "btn"}
href={giftHref(loggedIn, p.id)}
>
Ezt adom ajándékba
</Link>
</article>
))}
</div>
<p className="hint">
A számlát te kapod. Ha meggondolod magad, a vásárlástól számított 14
napon belül, beváltás előtt visszakérheted az árát.{" "}
<Link href="/aszf">ÁSZF</Link>
</p>
</section>
</main>
);
}
+30 -12
View File
@@ -4,10 +4,14 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useId, useRef, useState } from "react";
import { NavIcon, type NavIconName } from "./NavIcon";
export interface MenuSection {
/** A small heading above the group (e.g. "Ingyenes"). */
title?: string;
links: { href: string; label: string }[];
/** Two columns of tiles instead of a list. */
grid?: boolean;
links: { href: string; label: string; icon?: NavIconName; note?: string }[];
}
/**
@@ -15,7 +19,16 @@ export interface MenuSection {
* hidden there, see globals.css). Closes on a click outside, Escape, or
* moving to another page. `className` sets the width from which it shows.
*/
export function MobileMenu({ sections, className }: { sections: MenuSection[]; className: string }) {
export function MobileMenu({
sections,
className,
lead,
}: {
sections: MenuSection[];
className: string;
/** Shown first in the panel (the Moon today). */
lead?: React.ReactNode;
}) {
const [open, setOpen] = useState(false);
const box = useRef<HTMLDivElement>(null);
const button = useRef<HTMLButtonElement>(null);
@@ -61,19 +74,24 @@ export function MobileMenu({ sections, className }: { sections: MenuSection[]; c
</button>
{open && (
<nav id={panelId} className="mobile-menu-panel" aria-label="Menü">
{lead}
{sections.map((s, i) => (
<div key={i} className="mobile-menu-group">
{s.title && <span className="lp-free-label">{s.title}</span>}
{s.links.map((l) => (
<Link
key={l.href}
href={l.href}
aria-current={current(l.href) ? "page" : undefined}
onClick={() => setOpen(false)}
>
{l.label}
</Link>
))}
<div className={s.grid ? "mobile-menu-grid" : "mobile-menu-list"}>
{s.links.map((l) => (
<Link
key={l.href}
href={l.href}
aria-current={current(l.href) ? "page" : undefined}
onClick={() => setOpen(false)}
>
{l.icon && <NavIcon name={l.icon} />}
<span className="mobile-menu-label">{l.label}</span>
{l.note && <span className="mobile-menu-note">{l.note}</span>}
</Link>
))}
</div>
</div>
))}
</nav>
@@ -0,0 +1,58 @@
import Link from "next/link";
import { SIGNS } from "@/lib/astro";
import { SIGN_IN, withArticle } from "@/lib/skyText";
import type { SkyNow } from "@/lib/types";
/** The Moon as it is lit now: the lit part on the right while waxing, on the left while waning. */
export function MoonPhaseIcon({
illumination,
waxing,
}: {
illumination: number;
waxing: boolean;
}) {
const r = 8.5;
const k = Math.min(1, Math.max(0, illumination));
const rx = Math.abs(1 - 2 * k) * r;
// The outer edge on the lit side, then the terminator back.
const outer = waxing ? 1 : 0;
const terminator = waxing ? (k > 0.5 ? 1 : 0) : k > 0.5 ? 0 : 1;
const d = `M12 ${12 - r}A${r} ${r} 0 0 ${outer} 12 ${12 + r}A${rx} ${r} 0 0 ${terminator} 12 ${12 - r}Z`;
return (
<svg className="moon-phase-icon" viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r={r} className="moon-dark" />
<path d={d} className="moon-lit" />
</svg>
);
}
/**
* "Ma: Hold a ♉ Bikában" in the header (the moon calendar behind it). Narrow
* screens show the phase and the sign's glyph only.
*/
export function MoonChip({ sky }: { sky: SkyNow }) {
const moon = sky.moon;
const sign = moon.position.sign;
const where = withArticle(SIGN_IN[sign] ?? sign);
return (
<Link
href="/holdnaptar"
className="moon-chip"
aria-label={`Ma a Hold ${where} jár: holdnaptár`}
>
<MoonPhaseIcon illumination={moon.illumination} waxing={moon.waxing} />
<span className="moon-chip-text" aria-hidden="true">
Ma: Hold {where.split(" ")[0]}{" "}
</span>
<span className="moon-chip-glyph sym" aria-hidden="true">
{SIGNS[sign]?.glyph}
{"︎"}
</span>
<span className="moon-chip-text" aria-hidden="true">
{" "}
{SIGN_IN[sign]}
</span>
</Link>
);
}
@@ -0,0 +1,73 @@
// Small gold marks before the menu items: astrological glyphs where one fits,
// otherwise a line drawing.
export type NavIconName =
| "chart"
| "persons"
| "compare"
| "tarot"
| "explore"
| "signs"
| "famous"
| "moon"
| "retro"
| "packages"
| "admin";
const GLYPHS: Partial<Record<NavIconName, string>> = {
chart: "☉",
persons: "☽",
compare: "☌",
explore: "✧",
signs: "♈",
retro: "☿",
};
export function NavIcon({ name }: { name: NavIconName }) {
const glyph = GLYPHS[name];
if (glyph) {
return (
<span className="nav-icon sym" aria-hidden="true">
{glyph}
{"︎"}
</span>
);
}
return (
<svg className="nav-icon" viewBox="0 0 24 24" aria-hidden="true">
{name === "tarot" && (
<>
<rect x="5" y="3" width="14" height="18" rx="2.2" />
<path
d="M12 8l1.2 2.8 2.8 1.2-2.8 1.2L12 16l-1.2-2.8L8 12l2.8-1.2z"
className="nav-icon-fill"
/>
</>
)}
{name === "famous" && (
<path d="M12 3l2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6 6.6 19.5l1.2-6L3.3 9.3l6.1-.7z" />
)}
{name === "moon" && (
<>
<circle cx="12" cy="12" r="8.5" />
<path
d="M12 3.5a8.5 8.5 0 0 1 0 17a5 8.5 0 0 0 0-17z"
className="nav-icon-fill"
/>
</>
)}
{name === "packages" && (
<>
<path d="M12 2.5l8.5 4.7v9.6L12 21.5l-8.5-4.7V7.2z" />
<path d="M3.5 7.2L12 12l8.5-4.8M12 12v9.5" />
</>
)}
{name === "admin" && (
<>
<circle cx="12" cy="12" r="3" />
<path d="M12 2.5v3M12 18.5v3M2.5 12h3M18.5 12h3M5.3 5.3l2.1 2.1M16.6 16.6l2.1 2.1M5.3 18.7l2.1-2.1M16.6 7.4l2.1-2.1" />
</>
)}
</svg>
);
}
+126 -6
View File
@@ -2,16 +2,136 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useId, useRef, useState } from "react";
export function NavLinks({ links }: { links: { href: string; label: string }[] }) {
import { NavIcon, type NavIconName } from "./NavIcon";
export interface NavItem {
href: string;
label: string;
icon: NavIconName;
/** One line under the label in a dropdown. */
note?: string;
}
export interface NavGroup {
label: string;
icon: NavIconName;
/** The dropdown's small heading. */
title: string;
items: NavItem[];
}
const isGroup = (e: NavItem | NavGroup): e is NavGroup => "items" in e;
/**
* The app's menu row: items with a gold mark, and a group (the free pages)
* that opens on a click as a dropdown. Closes on a click outside, Escape or
* moving to another page.
*/
export function NavLinks({ entries }: { entries: (NavItem | NavGroup)[] }) {
const pathname = usePathname();
const here = (href: string) => pathname.startsWith(href);
return (
<nav className="nav app-nav" aria-label="Fő navigáció">
{links.map((l) => (
<Link key={l.href} href={l.href} aria-current={pathname.startsWith(l.href) ? "page" : undefined}>
{l.label}
</Link>
))}
{entries.map((e) =>
isGroup(e) ? (
<Dropdown
key={e.label}
group={e}
active={e.items.some((i) => here(i.href))}
here={here}
/>
) : (
<Link
key={e.href}
href={e.href}
aria-current={here(e.href) ? "page" : undefined}
>
<NavIcon name={e.icon} />
{e.label}
</Link>
),
)}
</nav>
);
}
function Dropdown({
group,
active,
here,
}: {
group: NavGroup;
active: boolean;
here: (href: string) => boolean;
}) {
const [open, setOpen] = useState(false);
const box = useRef<HTMLDivElement>(null);
const button = useRef<HTMLButtonElement>(null);
const id = useId();
const pathname = usePathname();
useEffect(() => setOpen(false), [pathname]);
useEffect(() => {
if (!open) return;
const outside = (e: PointerEvent) => {
if (box.current && !box.current.contains(e.target as Node))
setOpen(false);
};
const escape = (e: KeyboardEvent) => {
if (e.key === "Escape") {
setOpen(false);
button.current?.focus();
}
};
document.addEventListener("pointerdown", outside);
document.addEventListener("keydown", escape);
return () => {
document.removeEventListener("pointerdown", outside);
document.removeEventListener("keydown", escape);
};
}, [open]);
return (
<div className="nav-group" ref={box}>
<button
ref={button}
type="button"
className={active ? "nav-group-button is-active" : "nav-group-button"}
aria-expanded={open}
aria-controls={id}
onClick={() => setOpen((o) => !o)}
>
<NavIcon name={group.icon} />
{group.label}
<svg
viewBox="0 0 24 24"
aria-hidden="true"
className="nav-group-chevron"
>
<path d="M6 9l6 6 6-6" />
</svg>
</button>
{open && (
<div id={id} className="nav-dropdown">
<span className="nav-dropdown-title">{group.title}</span>
{group.items.map((i) => (
<Link
key={i.href}
href={i.href}
className="nav-dropdown-item"
aria-current={here(i.href) ? "page" : undefined}
>
<NavIcon name={i.icon} />
<span className="nav-dropdown-text">
<span>{i.label}</span>
{i.note && <span className="hint">{i.note}</span>}
</span>
</Link>
))}
</div>
)}
</div>
);
}
@@ -184,8 +184,7 @@ export function PackageCards({
{termsConsent && (
<>
{" "}
A csomagot azonnal megkapod, ezért a fizetésnél kéred a teljesítés megkezdését, és ezzel lemondasz a 14
napos elállási jogról. <Link href="/aszf">ÁSZF</Link>
<Link href="/aszf">ÁSZF</Link>
</>
)}
</p>
@@ -44,13 +44,20 @@ export function PaymentReturn() {
const r = await api<{
status: string;
name: string | null;
gift: { id: string; recipient_name: string | null; recipient_email: string | null } | null;
gift: {
id: string;
recipient_name: string | null;
recipient_email: string | null;
send_at: string | null;
} | null;
}>(`/payments/checkout/${encodeURIComponent(value)}`);
if (stopped) return;
if (r.status === "paid") {
const text = !r.gift
? `Köszönjük! Jóváírtuk: ${r.name ?? "a csomagod"}.`
: r.gift.recipient_email
: r.gift.recipient_email && r.gift.send_at
? `Köszönjük! Az ajándékot ${new Date(r.gift.send_at).toLocaleString("hu-HU", { month: "long", day: "numeric", hour: "numeric", minute: "2-digit" })}-kor küldjük el ide: ${r.gift.recipient_email}.`
: r.gift.recipient_email
? `Köszönjük! Az ajándékot elküldtük ide: ${r.gift.recipient_email}. Az utalványt lent le is töltheted.`
: "Köszönjük! Az ajándékutalvány elkészült: lent letöltheted, és átadhatod.";
setNotice({ kind: "ok", text });
@@ -1,6 +1,7 @@
import Link from "next/link";
import { Logo } from "@/components/SiteHeader";
import { isChristmasTime } from "@/lib/season";
/**
* The footer of every page (the root layout draws it): the free content
@@ -26,6 +27,7 @@ export function SiteFooter({ loggedIn }: { loggedIn: boolean }) {
<Link href="/retrograd">Retrográd bolygók</Link>
<Link href="/pelda">Példaelemzés</Link>
<Link href="/kartyajoslas/pelda">Példajóslás</Link>
<Link href={isChristmasTime() ? "/karacsony" : "/ajandek"}>Ajándékozás</Link>
<Link href={loggedIn ? "/visszajelzes" : "/kapcsolat"}>Kapcsolat</Link>
<Link href="/aszf">ÁSZF</Link>
<Link href="/adatvedelem">Adatvédelem</Link>
+49 -16
View File
@@ -1,9 +1,10 @@
import Link from "next/link";
import type { Me } from "@/lib/types";
import type { Me, SkyNow } from "@/lib/types";
import { MobileMenu } from "./MobileMenu";
import { NavLinks } from "./NavLinks";
import { MoonChip } from "./MoonChip";
import { type NavGroup, type NavItem, NavLinks } from "./NavLinks";
import { UserMenu } from "./UserMenu";
/** The mark: the orbit, the thread (an S, with the crossbar an f) and a star on the rim. */
@@ -128,23 +129,47 @@ function PackageBadge({ me }: { me: Me }) {
);
}
export function SiteHeader({ me }: { me: Me }) {
const links = [
{ href: "/keplet", label: "Képletem" },
{ href: "/szemelyek", label: "Személyek" },
{ href: "/osszevetesek", label: "Összevetések" },
{ href: "/kartyajoslas", label: "Kártyajóslás" },
{ href: "/csillagjegyek", label: "Csillagjegyek" },
{ href: "/hires-emberek", label: "Híres emberek" },
{ href: "/csomagok", label: "Csomagok" },
/** The free pages: in the menu row one dropdown, in the ☰ menu a group of tiles. */
const EXPLORE: NavItem[] = [
{ href: "/csillagjegyek", label: "Csillagjegyek", icon: "signs", note: "A tizenkét jegy jellemzése" },
{ href: "/hires-emberek", label: "Híres emberek", icon: "famous", note: "Ismert emberek képlete és elemzése" },
{ href: "/holdnaptar", label: "Holdnaptár", icon: "moon", note: "Holdfázisok, fogyatkozások, holdjegyek" },
{ href: "/retrograd", label: "Retrográd bolygók", icon: "retro", note: "Mikor retrográd a Merkúr és a többi" },
];
/**
* The header of the logged-in app: the menu with gold marks (the free pages
* in one "Felfedezés" dropdown), the Moon today, the package and the account.
* Below 1380px the menu moves behind ☰, grouped.
*/
export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
const own: NavItem[] = [
{ href: "/keplet", label: "Képletem", icon: "chart" },
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
];
if (me.user.roles.includes("admin")) links.push({ href: "/admin", label: "Admin" });
else if (me.user.roles.includes("creator")) links.push({ href: "/admin/hires-emberek", label: "Szerző" });
const packages: NavItem = { href: "/csomagok", label: "Csomagok", icon: "packages" };
const team: NavItem[] = me.user.roles.includes("admin")
? [{ href: "/admin", label: "Admin", icon: "admin" }]
: me.user.roles.includes("creator")
? [{ href: "/admin/hires-emberek", label: "Szerző", icon: "admin" }]
: [];
const entries: (NavItem | NavGroup)[] = [
...own,
{ label: "Felfedezés", icon: "explore", title: "Ingyenes, mindenkinek", items: EXPLORE },
packages,
...team,
];
const { natal, synastry } = me.analyses_left;
const left = natal + synastry;
const packageNote = me.package ? `${me.package.name} · ${left} elemzés` : left > 0 ? `${left} elemzés` : undefined;
return (
<header className="site-header">
<header className="site-header app-header">
<Logo />
<NavLinks links={links} />
<NavLinks entries={entries} />
<div className="who">
{sky && <MoonChip sky={sky} />}
<PackageBadge me={me} />
<UserMenu
name={me.user.display_name || me.user.email}
@@ -152,7 +177,15 @@ export function SiteHeader({ me }: { me: Me }) {
replies={me.feedback_replies_unseen ?? 0}
/>
</div>
<MobileMenu className="mobile-menu-app" sections={[{ links }]} />
<MobileMenu
className="mobile-menu-app"
lead={sky ? <MoonChip sky={sky} /> : undefined}
sections={[
{ title: "Saját", links: own },
{ title: "Felfedezés · ingyenes", grid: true, links: EXPLORE.map(({ note: _note, ...l }) => l) },
{ links: [{ ...packages, note: packageNote }, ...team] },
]}
/>
</header>
);
}
+30
View File
@@ -0,0 +1,30 @@
// The Christmas season of the gift campaign (Budapest dates; the backend
// marks the gifts by the same window).
const parts = (now: Date) => {
const [y, m, d] = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Budapest",
year: "numeric",
month: "2-digit",
day: "2-digit",
})
.format(now)
.split("-")
.map(Number);
return { y, m, d };
};
/** 15 November to 6 January: gifts are Christmas gifts (festive card, e-mail). */
export function isChristmasTime(now = new Date()): boolean {
const { m, d } = parts(now);
return (m === 11 && d >= 15) || m === 12 || (m === 1 && d <= 6);
}
/** Christmas morning (24 December, 8:00 Budapest) of this season, if still ahead. */
export function christmasMorning(now = new Date()): Date | null {
const { y, m } = parts(now);
if (m !== 11 && m !== 12) return null;
// 8:00 in Budapest is 7:00 UTC in December (winter time).
const at = new Date(Date.UTC(y, 11, 24, 7, 0));
return at.getTime() > now.getTime() + 10 * 60 * 1000 ? at : null;
}
+10
View File
@@ -660,8 +660,12 @@ export interface AdminGift {
checkout: { id: string; live: boolean | null; amount_huf: number | null } | null;
invoice: { number: string | null; status: string } | null;
storno: { status: string; number: string | null; error: string | null } | null;
send_at: string | null;
email_state: EmailState | null;
}
export type EmailState = "scheduled" | "sending" | "sent" | "failed";
/** A package the user bought as a gift (`GET /v1/gifts`). */
export interface Gift {
id: string;
@@ -678,6 +682,12 @@ export interface Gift {
status: "open" | "redeemed" | "refunded";
redeemed_at: string | null;
refunded_at: string | null;
/** E-mailed at this time (null: at once). */
send_at: string | null;
/** The e-mail: waiting for its time, going out, gone out or failed (null: none, or long gone out). */
email_state: EmailState | null;
/** Bought for Christmas (the card is festive). */
christmas: boolean;
/** E-mails sent so far. */
sendings: number;
/** Whether it can be sent by e-mail (again). */
+1
View File
@@ -137,6 +137,7 @@ async fn gift_card(id: Uuid, payload: &Value) -> Option<Pdf> {
recipient_name: to.as_deref(),
from_name: from.as_deref(),
message: message.as_deref(),
christmas: card["christmas_year"].as_i64().and_then(|y| i32::try_from(y).ok()),
})
.map_err(|e| e.to_string())?;
let code: String = code.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();