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
This commit is contained in:
@@ -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;
|
||||||
@@ -334,7 +334,13 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
|||||||
.as_str()
|
.as_str()
|
||||||
.map(|e| e.chars().filter(|c| !c.is_control()).take(254).collect::<String>());
|
.map(|e| e.chars().filter(|c| !c.is_control()).take(254).collect::<String>());
|
||||||
let whom = name(&payload["gift"], "recipient_name");
|
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_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();
|
let contents_en = contents.as_ref().map(|c| format!(" It contains: {c}.")).unwrap_or_default();
|
||||||
@@ -359,9 +365,10 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
|||||||
unsubscribe: None,
|
unsubscribe: None,
|
||||||
unsubscribe_post_url: 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)"),
|
subject: format!("Köszönjük a vásárlást: {package} (ajándék)"),
|
||||||
preheader: Some(match &to {
|
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}."),
|
Some(e) => format!("Az ajándékot elküldtük ide: {e}."),
|
||||||
None => "Az ajándékutalványt csatoltuk ehhez a levélhez.".into(),
|
None => "Az ajándékutalványt csatoltuk ehhez a levélhez.".into(),
|
||||||
}),
|
}),
|
||||||
@@ -370,7 +377,10 @@ 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} {}",
|
"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(),
|
whom.as_ref().map(|w| format!(" {w} részére")).unwrap_or_default(),
|
||||||
match &to {
|
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(),
|
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(),
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
@@ -409,7 +419,7 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
|||||||
unsubscribe: None,
|
unsubscribe: None,
|
||||||
unsubscribe_post_url: 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)"),
|
subject: format!("Thank you for your purchase: {package} (gift)"),
|
||||||
preheader: Some(match &to {
|
preheader: Some(match &to {
|
||||||
Some(e) => format!("We sent the gift to {e}."),
|
Some(e) => format!("We sent the gift to {e}."),
|
||||||
@@ -420,7 +430,10 @@ 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} {}",
|
"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(),
|
whom.as_ref().map(|w| format!(" for {w}")).unwrap_or_default(),
|
||||||
match &to {
|
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(),
|
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(),
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
@@ -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>());
|
payload["contents"].as_str().map(|c| c.chars().filter(|c| !c.is_control()).take(300).collect::<String>());
|
||||||
let from = name(payload, "from_name");
|
let from = name(payload, "from_name");
|
||||||
let to = name(payload, "recipient_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 {
|
Ok(match lang {
|
||||||
Lang::Hu => Content {
|
Lang::Hu => Content {
|
||||||
subject: match &from {
|
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"),
|
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()),
|
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}!")),
|
greeting: to.as_ref().map_or_else(|| "Szia!".into(), |t| format!("Szia {t}!")),
|
||||||
intro: format!(
|
intro: format!(
|
||||||
"{} egy „{package}” csomagot a Sorsfonalakon.{}",
|
"{}{} egy „{package}” csomagot a Sorsfonalakon.{}",
|
||||||
|
if christmas { "Boldog karácsonyt! " } else { "" },
|
||||||
match &from {
|
match &from {
|
||||||
Some(f) => format!("{f} ajándékozott neked"),
|
Some(f) => format!("{f} ajándékozott neked"),
|
||||||
None => "Ajándékba kaptál".into(),
|
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 {
|
Lang::En => Content {
|
||||||
subject: match &from {
|
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"),
|
Some(f) => format!("{f} sent you a gift: the “{package}” package"),
|
||||||
None => format!("A gift for you: the “{package}” package on Sorsfonalak"),
|
None => format!("A gift for you: the “{package}” package on Sorsfonalak"),
|
||||||
},
|
},
|
||||||
@@ -1021,6 +1040,11 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert!(hu.html.contains("<b>Ölel</b>") && hu.html.contains(">ABCD-EFGH-JKMN</div>"));
|
assert!(hu.html.contains("<b>Ölel</b>") && hu.html.contains(">ABCD-EFGH-JKMN</div>"));
|
||||||
assert!(hu.text.contains("PDF-ben is csatoltuk") && hu.text.contains("mert Ági a Sorsfonalakon"));
|
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 anonymous = serde_json::json!({"url": "u", "package_name": "Család", "promo_code": "X1-<script>"});
|
||||||
let hu = render("gift_package", "hu", &anonymous).unwrap();
|
let hu = render("gift_package", "hu", &anonymous).unwrap();
|
||||||
assert_eq!(hu.subject, "Ajándékot kaptál: „Család” csomag a Sorsfonalakon");
|
assert_eq!(hu.subject, "Ajándékot kaptál: „Család” csomag a Sorsfonalakon");
|
||||||
@@ -1046,6 +1070,9 @@ mod tests {
|
|||||||
assert!(hu.text.contains("AJÁNDÉKKÓD: ABCD-EFGH-JKMN") && hu.text.contains("14 napon belül"));
|
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("a beváltással az elállási jog megszűnik"));
|
||||||
assert!(!hu.text.contains("jóváírtuk"));
|
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);
|
||||||
payload["gift"]["recipient_email"] = Value::Null;
|
payload["gift"]["recipient_email"] = Value::Null;
|
||||||
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
|
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
|
||||||
assert!(hu.text.contains("PDF-ben csatoltuk ehhez a levélhez"));
|
assert!(hu.text.contains("PDF-ben csatoltuk ehhez a levélhez"));
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ fn main() {
|
|||||||
code: &code,
|
code: &code,
|
||||||
redeem_url: &url,
|
redeem_url: &url,
|
||||||
recipient_name: Some(to.as_str()),
|
recipient_name: Some(to.as_str()),
|
||||||
|
christmas: std::env::var("CHRISTMAS").ok().and_then(|y| y.parse().ok()),
|
||||||
from_name: Some(from.as_str()),
|
from_name: Some(from.as_str()),
|
||||||
message: (!message.is_empty()).then_some(message.as_str()),
|
message: (!message.is_empty()).then_some(message.as_str()),
|
||||||
};
|
};
|
||||||
|
|||||||
+97
-12
@@ -38,6 +38,8 @@ const GOLD: &str = "#a07a2c";
|
|||||||
const MUTED: &str = "#5f6578";
|
const MUTED: &str = "#5f6578";
|
||||||
const LINE: &str = "#d9c9a3";
|
const LINE: &str = "#d9c9a3";
|
||||||
const PAPER: &str = "#fdfaf3";
|
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.
|
/// Where the code box starts; the message fills the space above it.
|
||||||
const CODE_TOP: f32 = 636.0;
|
const CODE_TOP: f32 = 636.0;
|
||||||
@@ -64,6 +66,27 @@ pub struct Card<'a> {
|
|||||||
pub from_name: Option<&'a str>,
|
pub from_name: Option<&'a str>,
|
||||||
/// The buyer's message (line breaks kept).
|
/// The buyer's message (line breaks kept).
|
||||||
pub message: Option<&'a str>,
|
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)]
|
#[derive(Debug)]
|
||||||
@@ -252,6 +275,11 @@ impl Message {
|
|||||||
let (text, signature) = match (message, from) {
|
let (text, signature) = match (message, from) {
|
||||||
(Some(m), from) => (format!("„{m}”"), from.map(|f| format!("– {f}"))),
|
(Some(m), from) => (format!("„{m}”"), from.map(|f| format!("– {f}"))),
|
||||||
(None, Some(f)) => (format!("Szeretettel küldi: {f}"), None),
|
(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) => (
|
(None, None) => (
|
||||||
"Fedezd fel, mit mesélnek rólad a csillagok: a születési képleted, személyre szóló elemzések, \
|
"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."
|
é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).
|
/// 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 {
|
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 {
|
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.
|
// "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 spacing = 3.2;
|
||||||
let ew = width(Face::SansBold, eyebrow, 9.0, spacing) - spacing;
|
let ew = width(Face::SansBold, eyebrow, 9.0, spacing) - spacing;
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
@@ -413,7 +461,12 @@ pub fn svg(card: &Card) -> String {
|
|||||||
for (x, y, r) in
|
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)]
|
[(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 = WHEEL.split_once("viewBox=\"0 0 680 680\">").map_or("", |(_, rest)| rest);
|
||||||
let inner = inner.trim_end().trim_end_matches("</svg>");
|
let inner = inner.trim_end().trim_end_matches("</svg>");
|
||||||
@@ -451,17 +504,32 @@ pub fn svg(card: &Card) -> String {
|
|||||||
y += 15.0;
|
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 divider = y + 10.0;
|
||||||
let _ = write!(
|
if let Some(year) = card.christmas {
|
||||||
s,
|
let wish = format!("Boldog karácsonyt és csillagos {}!", year_accusative(year));
|
||||||
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}"/>"#,
|
let ww = width(Face::SerifItalic, &wish, 16.0, 0.0);
|
||||||
cx - 150.0,
|
let _ = write!(
|
||||||
cx - 10.0,
|
s,
|
||||||
cx + 10.0,
|
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 + 150.0,
|
cx - ww / 2.0 - 70.0,
|
||||||
divider - 3.5
|
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.
|
// The message next to the avatar, centred in the room above the code box.
|
||||||
let room_top = divider + 22.0;
|
let room_top = divider + 22.0;
|
||||||
@@ -568,6 +636,7 @@ mod tests {
|
|||||||
recipient_name: Some("Bea"),
|
recipient_name: Some("Bea"),
|
||||||
from_name: from,
|
from_name: from,
|
||||||
message,
|
message,
|
||||||
|
christmas: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -625,6 +694,22 @@ mod tests {
|
|||||||
usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
|
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]
|
#[test]
|
||||||
fn without_a_message_the_card_still_says_something() {
|
fn without_a_message_the_card_still_says_something() {
|
||||||
let contents = contents();
|
let contents = contents();
|
||||||
|
|||||||
+20
-5
@@ -17,6 +17,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
|||||||
- **Hogyan kapja meg:**
|
- **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);
|
- „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.
|
- „É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.
|
- **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)”.
|
- **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.”
|
- 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 +26,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.
|
- **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`):
|
- **Visszaigazoló levél** (`purchase_confirmation`):
|
||||||
- azt írja, hogy ajándékba vette, és benne van a kód;
|
- 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.
|
- ha ő adja át, az utalvány PDF-ben csatolva van.
|
||||||
|
|
||||||
## Ajándékaim: `/ajandekaim`
|
## Ajándékaim: `/ajandekaim`
|
||||||
@@ -33,13 +35,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;
|
- a csomag, kinek szól, és a vásárlás napja;
|
||||||
- az állapot: „Még nincs beváltva” vagy „Beváltva: dátum”;
|
- az állapot: „Még nincs beváltva” vagy „Beváltva: dátum”;
|
||||||
- a kód, másolás gombbal;
|
- 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.
|
- a küldő neve és az üzenet.
|
||||||
- **Utalvány letöltése (PDF):** bármikor.
|
- **Utalvány letöltése (PDF):** bármikor.
|
||||||
- **Küldés e-mailben:** amíg nincs beváltva.
|
- **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.
|
- Ú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.
|
- 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.
|
- 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
|
## A címzett
|
||||||
|
|
||||||
@@ -53,6 +56,14 @@ 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).
|
- 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.
|
- 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”.
|
||||||
|
- 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)
|
## Az utalvány (PDF)
|
||||||
|
|
||||||
- **Mi van rajta:** egy A4-es, világos, nyomtatóbarát oldal:
|
- **Mi van rajta:** egy A4-es, világos, nyomtatóbarát oldal:
|
||||||
@@ -85,6 +96,9 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
|||||||
|
|
||||||
## Admin
|
## 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.
|
- 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
|
## Adatok
|
||||||
@@ -93,6 +107,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;
|
- `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;
|
- `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.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).
|
- `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).
|
- **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.
|
- **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 +117,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 |
|
| 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) |
|
| `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 |
|
| `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 |
|
| `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/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 |
|
| `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/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 |
|
| `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) |
|
| `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) |
|
||||||
|
|||||||
@@ -132,18 +132,35 @@ pub async fn queue_email_to(
|
|||||||
locale: &str,
|
locale: &str,
|
||||||
payload: Value,
|
payload: Value,
|
||||||
) -> Result<(), ApiError> {
|
) -> 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(
|
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(user_id)
|
||||||
.bind(to)
|
.bind(to)
|
||||||
.bind(template)
|
.bind(template)
|
||||||
.bind(locale)
|
.bind(locale)
|
||||||
.bind(payload)
|
.bind(payload)
|
||||||
|
.bind(at)
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The e-mails that carry a password link.
|
/// The e-mails that carry a password link.
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ use sqlx::PgConnection;
|
|||||||
use time::OffsetDateTime;
|
use time::OffsetDateTime;
|
||||||
use uuid::Uuid;
|
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::promo::{CODE_LEN, display};
|
||||||
use super::{Body, IdPath, St, payments};
|
use super::{Body, IdPath, St, payments};
|
||||||
use crate::AppState;
|
use crate::AppState;
|
||||||
@@ -92,10 +92,31 @@ struct Gift {
|
|||||||
last_sent_at: Option<OffsetDateTime>,
|
last_sent_at: Option<OffsetDateTime>,
|
||||||
refunded_at: Option<OffsetDateTime>,
|
refunded_at: Option<OffsetDateTime>,
|
||||||
refund_id: Option<String>,
|
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, \
|
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 {
|
impl Gift {
|
||||||
fn package(&self) -> Result<&'static Package, ApiError> {
|
fn package(&self) -> Result<&'static Package, ApiError> {
|
||||||
@@ -117,9 +138,15 @@ impl Gift {
|
|||||||
"recipient_name": self.recipient_name,
|
"recipient_name": self.recipient_name,
|
||||||
"from_name": self.from_name,
|
"from_name": self.from_name,
|
||||||
"message": self.message,
|
"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 {
|
fn status(&self) -> &'static str {
|
||||||
match (self.redeemed_at, self.refunded_at) {
|
match (self.redeemed_at, self.refunded_at) {
|
||||||
(Some(_), _) => "redeemed",
|
(Some(_), _) => "redeemed",
|
||||||
@@ -141,6 +168,8 @@ impl Gift {
|
|||||||
fn view(&self) -> Value {
|
fn view(&self) -> Value {
|
||||||
let status = self.status();
|
let status = self.status();
|
||||||
let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc());
|
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!({
|
json!({
|
||||||
"id": self.id,
|
"id": self.id,
|
||||||
"package": { "id": self.package, "name": packages::find(&self.package).map(|p| p.name) },
|
"package": { "id": self.package, "name": packages::find(&self.package).map(|p| p.name) },
|
||||||
@@ -153,9 +182,12 @@ impl Gift {
|
|||||||
"status": status,
|
"status": status,
|
||||||
"redeemed_at": rfc3339_opt(self.redeemed_at),
|
"redeemed_at": rfc3339_opt(self.redeemed_at),
|
||||||
"refunded_at": rfc3339_opt(self.refunded_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,
|
"sendings": self.sendings,
|
||||||
"can_send": status == "open" && self.sendings < MAX_SENDINGS,
|
"can_send": status == "open" && self.sendings - i32::from(waiting) < MAX_SENDINGS,
|
||||||
"send_again_at": rfc3339_opt(next_send),
|
"send_again_at": rfc3339_opt(next_send.filter(|_| !waiting)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -185,6 +217,26 @@ pub struct GiftCheckout {
|
|||||||
recipient_email_confirm: Option<String>,
|
recipient_email_confirm: Option<String>,
|
||||||
from_name: Option<String>,
|
from_name: Option<String>,
|
||||||
message: 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.
|
/// 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 to = recipient(req.recipient_email.as_deref(), req.recipient_email_confirm.as_deref())?;
|
||||||
let from = clean_name(req.from_name)?;
|
let from = clean_name(req.from_name)?;
|
||||||
let message = super::invitations::clean_message(req.message)?;
|
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.
|
// Whether this user may pay, before anything is written.
|
||||||
let stripe = match payments::method(&state.config) {
|
let stripe = match payments::method(&state.config) {
|
||||||
Some("stripe") => Some(payments::stripe_for(&state, &auth)?),
|
Some("stripe") => Some(payments::stripe_for(&state, &auth)?),
|
||||||
@@ -208,8 +264,8 @@ pub async fn checkout(
|
|||||||
};
|
};
|
||||||
let id = Uuid::now_v7();
|
let id = Uuid::now_v7();
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message) \
|
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message, send_at) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||||||
)
|
)
|
||||||
.bind(id)
|
.bind(id)
|
||||||
.bind(auth.id())
|
.bind(auth.id())
|
||||||
@@ -218,6 +274,7 @@ pub async fn checkout(
|
|||||||
.bind(&to)
|
.bind(&to)
|
||||||
.bind(&from)
|
.bind(&from)
|
||||||
.bind(&message)
|
.bind(&message)
|
||||||
|
.bind(send_at)
|
||||||
.execute(&state.db)
|
.execute(&state.db)
|
||||||
.await?;
|
.await?;
|
||||||
let url = match stripe {
|
let url = match stripe {
|
||||||
@@ -242,6 +299,8 @@ pub struct Paid {
|
|||||||
pub recipient_name: Option<String>,
|
pub recipient_name: Option<String>,
|
||||||
pub recipient_email: Option<String>,
|
pub recipient_email: Option<String>,
|
||||||
pub card: Value,
|
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.
|
/// 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?;
|
.await?;
|
||||||
gift.code = Some(code);
|
gift.code = Some(code);
|
||||||
if let Some(to) = gift.recipient_email.clone() {
|
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");
|
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 {
|
Ok(Paid {
|
||||||
code: display(gift.code()?),
|
code: display(gift.code()?),
|
||||||
card: gift.card_payload(state)?,
|
card: gift.card_payload(state)?,
|
||||||
recipient_name: gift.recipient_name,
|
recipient_name: gift.recipient_name,
|
||||||
recipient_email: gift.recipient_email,
|
recipient_email: gift.recipient_email,
|
||||||
|
send_at_local,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language.
|
/// 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> {
|
/// 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")
|
let locale: Option<String> = sqlx::query_scalar("SELECT locale FROM users WHERE id = $1")
|
||||||
.bind(gift.buyer_id)
|
.bind(gift.buyer_id)
|
||||||
.fetch_optional(&mut *tx)
|
.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,
|
"from_name": gift.from_name,
|
||||||
"message": gift.message,
|
"message": gift.message,
|
||||||
"gift_card": gift.card_payload(state)?,
|
"gift_card": gift.card_payload(state)?,
|
||||||
|
"christmas_year": gift.christmas(),
|
||||||
});
|
});
|
||||||
// Not the recipient's account (if they have one): no user id.
|
// 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?;
|
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() WHERE id = $1")
|
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now(), email_id = $2 WHERE id = $1")
|
||||||
.bind(gift.id)
|
.bind(gift.id)
|
||||||
|
.bind(email)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
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.
|
/// The user's paid gifts, newest first.
|
||||||
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||||
let gifts: Vec<Gift> = sqlx::query_as(&format!(
|
let gifts: Vec<Gift> = sqlx::query_as(&format!(
|
||||||
@@ -339,6 +438,7 @@ pub async fn card(
|
|||||||
let code = display(gift.code()?);
|
let code = display(gift.code()?);
|
||||||
let url = redeem_url(&state, gift.code()?);
|
let url = redeem_url(&state, gift.code()?);
|
||||||
let filename = format!("sorsfonalak-ajandek-{code}.pdf");
|
let filename = format!("sorsfonalak-ajandek-{code}.pdf");
|
||||||
|
let christmas = gift.christmas();
|
||||||
let pdf = tokio::task::spawn_blocking(move || {
|
let pdf = tokio::task::spawn_blocking(move || {
|
||||||
let contents = package.contents_items();
|
let contents = package.contents_items();
|
||||||
gift_card::pdf(&gift_card::Card {
|
gift_card::pdf(&gift_card::Card {
|
||||||
@@ -349,6 +449,7 @@ pub async fn card(
|
|||||||
recipient_name: gift.recipient_name.as_deref(),
|
recipient_name: gift.recipient_name.as_deref(),
|
||||||
from_name: gift.from_name.as_deref(),
|
from_name: gift.from_name.as_deref(),
|
||||||
message: gift.message.as_deref(),
|
message: gift.message.as_deref(),
|
||||||
|
christmas,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await
|
.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."));
|
return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották."));
|
||||||
}
|
}
|
||||||
gift.refused_if_refunded()?;
|
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(
|
return Err(ApiError::conflict(
|
||||||
"gift_send_limit",
|
"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.",
|
"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."));
|
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());
|
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?;
|
let gift = own_gift(&mut tx, id, auth.id(), false).await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
tracing::info!(user = %auth.id(), gift = %id, "gift sent by e-mail");
|
tracing::info!(user = %auth.id(), gift = %id, "gift sent by e-mail");
|
||||||
@@ -469,6 +578,8 @@ struct AdminGift {
|
|||||||
storno_status: Option<String>,
|
storno_status: Option<String>,
|
||||||
storno_number: Option<String>,
|
storno_number: Option<String>,
|
||||||
storno_error: Option<String>,
|
storno_error: Option<String>,
|
||||||
|
send_at: Option<OffsetDateTime>,
|
||||||
|
email_state: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[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, \
|
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, \
|
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, \
|
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 \
|
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 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 \
|
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 })),
|
"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 })),
|
"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 })),
|
"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();
|
.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
|
/// 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())
|
.bind(admin.0.id())
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
|
// A timed e-mail not gone out yet stays unsent.
|
||||||
|
cancel_pending_email(&mut tx, &gift).await?;
|
||||||
if let Some((checkout_id, _)) = &checkout {
|
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()?));
|
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(
|
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) }),
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -327,6 +327,7 @@ async fn confirm_by_email(
|
|||||||
"promo_code": gift.code,
|
"promo_code": gift.code,
|
||||||
"recipient_name": gift.recipient_name,
|
"recipient_name": gift.recipient_name,
|
||||||
"recipient_email": gift.recipient_email,
|
"recipient_email": gift.recipient_email,
|
||||||
|
"send_at": gift.send_at_local,
|
||||||
});
|
});
|
||||||
// Handed over by the buyer: the card comes with the confirmation.
|
// Handed over by the buyer: the card comes with the confirmation.
|
||||||
if gift.recipient_email.is_none() {
|
if gift.recipient_email.is_none() {
|
||||||
@@ -375,13 +376,16 @@ pub async fn checkout_status(
|
|||||||
}
|
}
|
||||||
let gift = match gift_id {
|
let gift = match gift_id {
|
||||||
Some(id) => {
|
Some(id) => {
|
||||||
let (name, to): (Option<String>, Option<String>) =
|
let (name, to, send_at): (Option<String>, Option<String>, Option<OffsetDateTime>) =
|
||||||
sqlx::query_as("SELECT recipient_name, recipient_email FROM gifts WHERE id = $1")
|
sqlx::query_as("SELECT recipient_name, recipient_email, send_at FROM gifts WHERE id = $1")
|
||||||
.bind(id)
|
.bind(id)
|
||||||
.fetch_optional(&state.db)
|
.fetch_optional(&state.db)
|
||||||
.await?
|
.await?
|
||||||
.unwrap_or_default();
|
.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,
|
None => None,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3413,7 +3413,7 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
confirmation["gift"],
|
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!(confirmation["gift_card"].is_null(), "the recipient has the card");
|
||||||
assert_eq!(confirmation["url"], "https://sorsfonalak.test/ajandekaim");
|
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();
|
.unwrap();
|
||||||
assert_eq!(invoices, 1);
|
assert_eq!(invoices, 1);
|
||||||
let r = app.get(&format!("/v1/payments/checkout/{session}"), Some(&anna)).await;
|
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 r = app.get("/v1/gifts", Some(&anna)).await;
|
||||||
let gift = &r.body["gifts"][0];
|
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();
|
sqlx::query("UPDATE gifts SET last_sent_at = now() - interval '11 minutes'").execute(&app.pool).await.unwrap();
|
||||||
let r = send("cili@example.com").await;
|
let r = send("cili@example.com").await;
|
||||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
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("cili@example.com", "gift_package").await, 1);
|
||||||
|
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 0);
|
||||||
let r = app
|
let r = app
|
||||||
.post(
|
.post(
|
||||||
&format!("/v1/gifts/{gift_id}/send"),
|
&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.");
|
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 |
@@ -8,6 +8,16 @@ import type { AdminGift } from "@/lib/types";
|
|||||||
|
|
||||||
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
|
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> = {
|
const STORNO: Record<string, string> = {
|
||||||
pending: "sztornó folyamatban",
|
pending: "sztornó folyamatban",
|
||||||
done: "sztornózva",
|
done: "sztornózva",
|
||||||
@@ -17,6 +27,7 @@ const STORNO: Record<string, string> = {
|
|||||||
/** The gifts with their payment, invoice and storno, and the refund button. */
|
/** The gifts with their payment, invoice and storno, and the refund button. */
|
||||||
export function AdminGifts() {
|
export function AdminGifts() {
|
||||||
const [gifts, setGifts] = useState<AdminGift[] | null>(null);
|
const [gifts, setGifts] = useState<AdminGift[] | null>(null);
|
||||||
|
const [schedule, setSchedule] = useState<Slot[]>([]);
|
||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
const [busy, setBusy] = useState<string | null>(null);
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -24,10 +35,11 @@ export function AdminGifts() {
|
|||||||
|
|
||||||
const load = useCallback(async (search: string) => {
|
const load = useCallback(async (search: string) => {
|
||||||
try {
|
try {
|
||||||
const r = await api<{ gifts: AdminGift[] }>(
|
const r = await api<{ gifts: AdminGift[]; schedule: Slot[] }>(
|
||||||
`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`,
|
`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`,
|
||||||
);
|
);
|
||||||
setGifts(r.gifts);
|
setGifts(r.gifts);
|
||||||
|
setSchedule(r.schedule ?? []);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(errorText(e));
|
setError(errorText(e));
|
||||||
}
|
}
|
||||||
@@ -66,153 +78,203 @@ export function AdminGifts() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="card">
|
<>
|
||||||
<div className="field">
|
{schedule.length > 0 && (
|
||||||
<label htmlFor="gift-search">Keresés</label>
|
<section className="card" aria-labelledby="schedule-title">
|
||||||
<input
|
<h2 id="schedule-title">Időzített levelek</h2>
|
||||||
id="gift-search"
|
<p className="hint">
|
||||||
className="inp"
|
Az időzítve küldött ajándéklevelek óránként (magyar idő, az elmúlt
|
||||||
value={q}
|
30 nap és ami még jön). Figyeld, hogy a kiment levelek száma az
|
||||||
onChange={(e) => setQ(e.target.value)}
|
időpont után megnőjön, és ne legyen hiba.
|
||||||
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
|
</p>
|
||||||
/>
|
<div className="table-wrap">
|
||||||
</div>
|
<table className="promo-table">
|
||||||
{error && (
|
<thead>
|
||||||
<p className="msg msg-error" role="alert">
|
<tr>
|
||||||
{error}
|
<th>Időpont</th>
|
||||||
</p>
|
<th>Vár</th>
|
||||||
)}
|
<th>Kiment</th>
|
||||||
{done && (
|
<th>Hiba</th>
|
||||||
<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>
|
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
</thead>
|
||||||
</tbody>
|
<tbody>
|
||||||
</table>
|
{schedule.map((s) => (
|
||||||
</div>
|
<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>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { useEffect, useId, useState } from "react";
|
|||||||
import { huf } from "@/components/PackageCards";
|
import { huf } from "@/components/PackageCards";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { contents } from "@/lib/packageContents";
|
import { contents } from "@/lib/packageContents";
|
||||||
|
import { christmasMorning } from "@/lib/season";
|
||||||
import type { Package, PayMethod } from "@/lib/types";
|
import type { Package, PayMethod } from "@/lib/types";
|
||||||
|
|
||||||
const MAX_MESSAGE = 300;
|
const MAX_MESSAGE = 300;
|
||||||
@@ -17,6 +18,19 @@ const looksLikeEmail = (s: string) =>
|
|||||||
const same = (a: string, b: string) =>
|
const same = (a: string, b: string) =>
|
||||||
a.trim().toLowerCase() === b.trim().toLowerCase();
|
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
|
* 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
|
* 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 [confirm, setConfirm] = useState("");
|
||||||
const [from, setFrom] = useState(defaultFrom.slice(0, MAX_NAME));
|
const [from, setFrom] = useState(defaultFrom.slice(0, MAX_NAME));
|
||||||
const [message, setMessage] = useState("");
|
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 [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
// Back from Stripe's page (the browser may restore this page as it was).
|
// 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 mismatch = byEmail && confirm.trim() !== "" && !same(email, confirm);
|
||||||
const emailOk = !byEmail || (looksLikeEmail(email) && same(email, confirm));
|
const emailOk = !byEmail || (looksLikeEmail(email) && same(email, confirm));
|
||||||
const stripe = canPay === "stripe" || canPay === "stripe_test";
|
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) {
|
async function submit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -81,6 +107,7 @@ export function GiftForm({
|
|||||||
recipient_email_confirm: byEmail ? confirm.trim() : null,
|
recipient_email_confirm: byEmail ? confirm.trim() : null,
|
||||||
from_name: from.trim() || null,
|
from_name: from.trim() || null,
|
||||||
message: message.trim() || null,
|
message: message.trim() || null,
|
||||||
|
send_at: byEmail && timed && sendAt ? sendAt.toISOString() : null,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -223,6 +250,81 @@ export function GiftForm({
|
|||||||
</div>
|
</div>
|
||||||
</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>
|
</fieldset>
|
||||||
|
|
||||||
<div className="field">
|
<div className="field">
|
||||||
@@ -253,6 +355,9 @@ export function GiftForm({
|
|||||||
<span className="muted">
|
<span className="muted">
|
||||||
„{chosen.name}” csomag ajándékba
|
„{chosen.name}” csomag ajándékba
|
||||||
{name.trim() ? `, ${name.trim()} részére` : ""}
|
{name.trim() ? `, ${name.trim()} részére` : ""}
|
||||||
|
{byEmail && timed && sendAt && timeOk
|
||||||
|
? ` · küldés: ${whenText(sendAt)}`
|
||||||
|
: ""}
|
||||||
</span>
|
</span>
|
||||||
<strong className="num">{huf(chosen.price_huf)}</strong>
|
<strong className="num">{huf(chosen.price_huf)}</strong>
|
||||||
</p>
|
</p>
|
||||||
@@ -261,7 +366,13 @@ export function GiftForm({
|
|||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="btn btn-primary"
|
className="btn btn-primary"
|
||||||
disabled={busy || !chosen || !emailOk || !name.trim()}
|
disabled={
|
||||||
|
busy ||
|
||||||
|
!chosen ||
|
||||||
|
!emailOk ||
|
||||||
|
!name.trim() ||
|
||||||
|
(byEmail && timed && !timeOk)
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{busy
|
{busy
|
||||||
? stripe
|
? stripe
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
|
||||||
import { payMethod } from "@/lib/payments";
|
import { payMethod } from "@/lib/payments";
|
||||||
|
import { isChristmasTime } from "@/lib/season";
|
||||||
import { backendGet, requireMe } from "@/lib/server";
|
import { backendGet, requireMe } from "@/lib/server";
|
||||||
import type { Gift, Package, PublicConfig } from "@/lib/types";
|
import type { Gift, Package, PublicConfig } from "@/lib/types";
|
||||||
|
|
||||||
@@ -27,11 +28,13 @@ export default async function GiftPage({ searchParams }: Props) {
|
|||||||
]);
|
]);
|
||||||
const packages = (catalog?.packages ?? []).filter((p) => p.tier === "main");
|
const packages = (catalog?.packages ?? []).filter((p) => p.tier === "main");
|
||||||
const given = mine?.gifts.length ?? 0;
|
const given = mine?.gifts.length ?? 0;
|
||||||
|
// Gifts bought now get the Christmas card.
|
||||||
|
const xmas = isChristmasTime();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page" style={{ maxWidth: 1080 }}>
|
<main className="page" style={{ maxWidth: 1080 }}>
|
||||||
<div className="page-head">
|
<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>
|
<h1>Ajándékozz csomagot</h1>
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
Születési képlet, személyre szóló elemzések, kapcsolati összevetés:
|
Születési képlet, személyre szóló elemzések, kapcsolati összevetés:
|
||||||
@@ -57,7 +60,7 @@ export default async function GiftPage({ searchParams }: Props) {
|
|||||||
<figure className="gift-sample">
|
<figure className="gift-sample">
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img
|
<img
|
||||||
src="/img/ajandek-utalvany.webp"
|
src={xmas ? "/img/ajandek-karacsony.webp" : "/img/ajandek-utalvany.webp"}
|
||||||
width={420}
|
width={420}
|
||||||
height={594}
|
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"
|
alt="Minta ajándékutalvány: a csomag neve, a személyes üzenet, az ajándékkód és a QR-kód"
|
||||||
|
|||||||
@@ -12,6 +12,15 @@ const day = (iso: string) =>
|
|||||||
month: "long",
|
month: "long",
|
||||||
day: "numeric",
|
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) =>
|
const time = (iso: string) =>
|
||||||
new Date(iso).toLocaleTimeString("hu-HU", {
|
new Date(iso).toLocaleTimeString("hu-HU", {
|
||||||
timeZone: "Europe/Budapest",
|
timeZone: "Europe/Budapest",
|
||||||
@@ -127,7 +136,19 @@ function GiftItem({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="gift-to">
|
<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>
|
E-mailben elküldve ide: <strong>{gift.recipient_email}</strong>
|
||||||
{gift.sendings > 1 ? ` (${gift.sendings}×)` : ""}
|
{gift.sendings > 1 ? ` (${gift.sendings}×)` : ""}
|
||||||
@@ -165,9 +186,11 @@ function GiftItem({
|
|||||||
className="btn btn-sm"
|
className="btn btn-sm"
|
||||||
onClick={() => setSending(true)}
|
onClick={() => setSending(true)}
|
||||||
>
|
>
|
||||||
{gift.recipient_email
|
{gift.email_state === "scheduled"
|
||||||
? "Újraküldés e-mailben"
|
? "Küldés most"
|
||||||
: "Küldés e-mailben"}
|
: gift.recipient_email
|
||||||
|
? "Újraküldés e-mailben"
|
||||||
|
: "Küldés e-mailben"}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { AiNote } from "@/components/AiNote";
|
|||||||
import { PackageCards } from "@/components/PackageCards";
|
import { PackageCards } from "@/components/PackageCards";
|
||||||
import { RedeemCode } from "@/components/RedeemCode";
|
import { RedeemCode } from "@/components/RedeemCode";
|
||||||
import { payMethod } from "@/lib/payments";
|
import { payMethod } from "@/lib/payments";
|
||||||
|
import { isChristmasTime } from "@/lib/season";
|
||||||
import { backendGet, requireMe } from "@/lib/server";
|
import { backendGet, requireMe } from "@/lib/server";
|
||||||
import type { Package, PublicConfig } from "@/lib/types";
|
import type { Package, PublicConfig } from "@/lib/types";
|
||||||
|
|
||||||
@@ -50,6 +51,7 @@ export default async function PackagesPage() {
|
|||||||
]);
|
]);
|
||||||
const packages = catalog?.packages ?? [];
|
const packages = catalog?.packages ?? [];
|
||||||
const canPay = payMethod(config, me);
|
const canPay = payMethod(config, me);
|
||||||
|
const xmas = isChristmasTime();
|
||||||
const left = me.analyses_left;
|
const left = me.analyses_left;
|
||||||
const slots = me.persons;
|
const slots = me.persons;
|
||||||
|
|
||||||
@@ -100,14 +102,15 @@ export default async function PackagesPage() {
|
|||||||
|
|
||||||
<section className="card gift-banner" aria-labelledby="gift-title">
|
<section className="card gift-banner" aria-labelledby="gift-title">
|
||||||
<div>
|
<div>
|
||||||
<h2 id="gift-title">Ajándékba is adhatod</h2>
|
<h2 id="gift-title">{xmas ? "Karácsonyi ajándék a csillagokból" : "Ajándékba is adhatod"}</h2>
|
||||||
<p className="muted">
|
<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
|
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.
|
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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Link className="btn" href="/ajandek">
|
<Link className="btn" href={xmas ? "/karacsony" : "/ajandek"}>
|
||||||
Megajándékozok valakit
|
{xmas ? "Karácsonyi ajándék" : "Megajándékozok valakit"}
|
||||||
</Link>
|
</Link>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|||||||
@@ -1748,3 +1748,24 @@ span.tarot-fan-card { cursor: default; }
|
|||||||
}
|
}
|
||||||
/* The ☰ panel covers the page fully (the header's blur showed it through). */
|
/* The ☰ panel covers the page fully (the header's blur showed it through). */
|
||||||
.mobile-menu-panel { background: #0f1528; }
|
.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; }
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { PublicHeader } from "@/components/SiteHeader";
|
||||||
|
import { contents } from "@/lib/packageContents";
|
||||||
|
import { backendGet, getMe } from "@/lib/server";
|
||||||
|
import type { Package } from "@/lib/types";
|
||||||
|
|
||||||
|
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "Karácsonyi ajándék a csillagokból",
|
||||||
|
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.",
|
||||||
|
alternates: { canonical: "/karacsony" },
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 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"),
|
||||||
|
]);
|
||||||
|
const packages = (catalog?.packages ?? []).filter((p) => p.tier === "main");
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{!me && <PublicHeader />}
|
||||||
|
<main className="page xmas-page" style={{ maxWidth: 1080 }}>
|
||||||
|
<section className="xmas-hero">
|
||||||
|
<div className="xmas-hero-text">
|
||||||
|
<span className="eyebrow">Karácsonyi ajándék</span>
|
||||||
|
<h1>Ajándék a csillagokból</h1>
|
||||||
|
<p className="lead">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
<div className="form-actions">
|
||||||
|
<Link className="btn btn-primary" href="/ajandek">
|
||||||
|
Megajándékozok valakit
|
||||||
|
</Link>
|
||||||
|
<a className="btn" href="#csomagok">
|
||||||
|
A csomagok
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<figure className="gift-sample xmas-sample">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src="/img/ajandek-karacsony.webp"
|
||||||
|
width={420}
|
||||||
|
height={594}
|
||||||
|
alt="Minta karácsonyi ajándékutalvány: Boldog karácsonyt és csillagos 2027-et, a csomag, az üzenet és az ajándékkód"
|
||||||
|
/>
|
||||||
|
<figcaption className="hint">
|
||||||
|
A karácsonyi 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="xmas-delivery-title"
|
||||||
|
>
|
||||||
|
<h2 id="xmas-delivery-title">Karácsony reggelre</h2>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<strong>Időzítve e-mailben:</strong> a levél az utalvánnyal
|
||||||
|
december 24-én reggel érkezik meg hozzá (vagy amikor választod).
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>Te adod át:</strong> letöltöd az utalványt, kinyomtatod,
|
||||||
|
és a fa alá teszed.
|
||||||
|
</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="xmas-packages-title"
|
||||||
|
style={{ gap: 16 }}
|
||||||
|
>
|
||||||
|
<h2 id="xmas-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={`/ajandek?csomag=${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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -33,6 +33,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
|||||||
{ url: `${base}/aszf`, changeFrequency: "yearly", priority: 0.2 },
|
{ url: `${base}/aszf`, changeFrequency: "yearly", priority: 0.2 },
|
||||||
|
|
||||||
{ url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 },
|
{ url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 },
|
||||||
|
{ url: `${base}/karacsony`, changeFrequency: "monthly", priority: 0.7 },
|
||||||
{ url: `${base}/adatvedelem`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
|
{ url: `${base}/adatvedelem`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
|
||||||
{ url: `${base}/privacy`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
|
{ url: `${base}/privacy`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -44,13 +44,20 @@ export function PaymentReturn() {
|
|||||||
const r = await api<{
|
const r = await api<{
|
||||||
status: string;
|
status: string;
|
||||||
name: string | null;
|
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)}`);
|
}>(`/payments/checkout/${encodeURIComponent(value)}`);
|
||||||
if (stopped) return;
|
if (stopped) return;
|
||||||
if (r.status === "paid") {
|
if (r.status === "paid") {
|
||||||
const text = !r.gift
|
const text = !r.gift
|
||||||
? `Köszönjük! Jóváírtuk: ${r.name ?? "a csomagod"}.`
|
? `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é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.";
|
: "Köszönjük! Az ajándékutalvány elkészült: lent letöltheted, és átadhatod.";
|
||||||
setNotice({ kind: "ok", text });
|
setNotice({ kind: "ok", text });
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -660,8 +660,12 @@ export interface AdminGift {
|
|||||||
checkout: { id: string; live: boolean | null; amount_huf: number | null } | null;
|
checkout: { id: string; live: boolean | null; amount_huf: number | null } | null;
|
||||||
invoice: { number: string | null; status: string } | null;
|
invoice: { number: string | null; status: string } | null;
|
||||||
storno: { status: string; number: string | null; error: string | null } | 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`). */
|
/** A package the user bought as a gift (`GET /v1/gifts`). */
|
||||||
export interface Gift {
|
export interface Gift {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -678,6 +682,12 @@ export interface Gift {
|
|||||||
status: "open" | "redeemed" | "refunded";
|
status: "open" | "redeemed" | "refunded";
|
||||||
redeemed_at: string | null;
|
redeemed_at: string | null;
|
||||||
refunded_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. */
|
/** E-mails sent so far. */
|
||||||
sendings: number;
|
sendings: number;
|
||||||
/** Whether it can be sent by e-mail (again). */
|
/** Whether it can be sent by e-mail (again). */
|
||||||
|
|||||||
@@ -137,6 +137,7 @@ async fn gift_card(id: Uuid, payload: &Value) -> Option<Pdf> {
|
|||||||
recipient_name: to.as_deref(),
|
recipient_name: to.as_deref(),
|
||||||
from_name: from.as_deref(),
|
from_name: from.as_deref(),
|
||||||
message: message.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())?;
|
.map_err(|e| e.to_string())?;
|
||||||
let code: String = code.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
|
let code: String = code.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
|
||||||
|
|||||||
Reference in New Issue
Block a user