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:
feco
2026-11-24 13:46:35 +00:00
co-authored by Claude Opus 5.5
parent 227e8b5b80
commit 382bd31271
22 changed files with 1016 additions and 209 deletions
+20 -3
View File
@@ -132,18 +132,35 @@ pub async fn queue_email_to(
locale: &str,
payload: Value,
) -> Result<(), ApiError> {
queue_email_at(conn, user_id, to, template, locale, payload, None).await.map(drop)
}
/// Queues an e-mail that the worker sends not before `at` (none: at once);
/// returns its id.
pub async fn queue_email_at(
conn: &mut PgConnection,
user_id: Option<Uuid>,
to: &str,
template: &str,
locale: &str,
payload: Value,
at: Option<time::OffsetDateTime>,
) -> Result<Uuid, ApiError> {
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload, next_attempt_at) \
VALUES ($1, $2, $3, $4, $5, $6, coalesce($7, now()))",
)
.bind(Uuid::now_v7())
.bind(id)
.bind(user_id)
.bind(to)
.bind(template)
.bind(locale)
.bind(payload)
.bind(at)
.execute(conn)
.await?;
Ok(())
Ok(id)
}
/// The e-mails that carry a password link.
+175 -17
View File
@@ -26,7 +26,7 @@ use sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
use super::auth::{normalize_email, queue_email_to};
use super::auth::{normalize_email, queue_email_at};
use super::promo::{CODE_LEN, display};
use super::{Body, IdPath, St, payments};
use crate::AppState;
@@ -92,10 +92,31 @@ struct Gift {
last_sent_at: Option<OffsetDateTime>,
refunded_at: Option<OffsetDateTime>,
refund_id: Option<String>,
/// E-mailed not before this (none: at once).
send_at: Option<OffsetDateTime>,
/// The last e-mail queued for it.
email_id: Option<Uuid>,
/// That e-mail: `scheduled`, `sending`, `sent` or `failed` (none: no
/// e-mail, or cleaned up a week after it went out).
email_state: Option<String>,
}
const COLUMNS: &str = "id, buyer_id, package, recipient_name, recipient_email, from_name, message, paid_at, code, \
redeemed_at, sendings, last_sent_at, refunded_at, refund_id";
redeemed_at, sendings, last_sent_at, refunded_at, refund_id, send_at, email_id, \
(SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \
WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \
FROM email_outbox o WHERE o.id = gifts.email_id) AS email_state";
/// The year a Christmas gift wishes for ("csillagos 2027-et"), if bought
/// between 15 November and 6 January (Budapest time; no summer time then).
fn christmas_year(paid: OffsetDateTime) -> Option<i32> {
let local = paid.to_offset(time::UtcOffset::from_hms(1, 0, 0).expect("an offset"));
match (local.month(), local.day()) {
(time::Month::November, 15..) | (time::Month::December, _) => Some(local.year() + 1),
(time::Month::January, ..=6) => Some(local.year()),
_ => None,
}
}
impl Gift {
fn package(&self) -> Result<&'static Package, ApiError> {
@@ -117,9 +138,15 @@ impl Gift {
"recipient_name": self.recipient_name,
"from_name": self.from_name,
"message": self.message,
"christmas_year": self.christmas(),
}))
}
/// The year a Christmas gift wishes for (see `christmas_year`).
fn christmas(&self) -> Option<i32> {
christmas_year(self.paid_at.unwrap_or_else(OffsetDateTime::now_utc))
}
fn status(&self) -> &'static str {
match (self.redeemed_at, self.refunded_at) {
(Some(_), _) => "redeemed",
@@ -141,6 +168,8 @@ impl Gift {
fn view(&self) -> Value {
let status = self.status();
let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc());
// A timed e-mail still waiting can be sent now instead.
let waiting = self.email_state.as_deref() == Some("scheduled");
json!({
"id": self.id,
"package": { "id": self.package, "name": packages::find(&self.package).map(|p| p.name) },
@@ -153,9 +182,12 @@ impl Gift {
"status": status,
"redeemed_at": rfc3339_opt(self.redeemed_at),
"refunded_at": rfc3339_opt(self.refunded_at),
"send_at": rfc3339_opt(self.send_at),
"email_state": self.email_state,
"christmas": self.christmas().is_some(),
"sendings": self.sendings,
"can_send": status == "open" && self.sendings < MAX_SENDINGS,
"send_again_at": rfc3339_opt(next_send),
"can_send": status == "open" && self.sendings - i32::from(waiting) < MAX_SENDINGS,
"send_again_at": rfc3339_opt(next_send.filter(|_| !waiting)),
})
}
}
@@ -185,6 +217,26 @@ pub struct GiftCheckout {
recipient_email_confirm: Option<String>,
from_name: Option<String>,
message: Option<String>,
/// E-mail it then (RFC 3339; none: right after paying), e.g. on Christmas morning.
send_at: Option<String>,
}
/// How far ahead a gift e-mail can be timed.
const MAX_SCHEDULE: time::Duration = time::Duration::days(366);
/// A time to e-mail a gift: in the future (a few minutes at least), within a year.
fn schedule(at: Option<&str>) -> Result<Option<OffsetDateTime>, ApiError> {
let Some(at) = at.map(str::trim).filter(|a| !a.is_empty()) else { return Ok(None) };
let at = OffsetDateTime::parse(at, &time::format_description::well_known::Rfc3339)
.map_err(|_| ApiError::BadRequest("send_at must be an RFC 3339 time".into()))?;
let now = OffsetDateTime::now_utc();
if at < now + time::Duration::minutes(5) {
return Err(ApiError::BadRequest("Az időzítés legyen a jövőben.".into()));
}
if at > now + MAX_SCHEDULE {
return Err(ApiError::BadRequest("Legfeljebb egy évre előre lehet időzíteni.".into()));
}
Ok(Some(at))
}
/// Starts paying for a gift: returns the address of Stripe's payment page.
@@ -200,6 +252,10 @@ pub async fn checkout(
let to = recipient(req.recipient_email.as_deref(), req.recipient_email_confirm.as_deref())?;
let from = clean_name(req.from_name)?;
let message = super::invitations::clean_message(req.message)?;
let send_at = schedule(req.send_at.as_deref())?;
if send_at.is_some() && to.is_none() {
return Err(ApiError::BadRequest("Időzíteni csak az e-mailben küldött ajándékot lehet.".into()));
}
// Whether this user may pay, before anything is written.
let stripe = match payments::method(&state.config) {
Some("stripe") => Some(payments::stripe_for(&state, &auth)?),
@@ -208,8 +264,8 @@ pub async fn checkout(
};
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message) \
VALUES ($1, $2, $3, $4, $5, $6, $7)",
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message, send_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
)
.bind(id)
.bind(auth.id())
@@ -218,6 +274,7 @@ pub async fn checkout(
.bind(&to)
.bind(&from)
.bind(&message)
.bind(send_at)
.execute(&state.db)
.await?;
let url = match stripe {
@@ -242,6 +299,8 @@ pub struct Paid {
pub recipient_name: Option<String>,
pub recipient_email: Option<String>,
pub card: Value,
/// When it is e-mailed, on the Budapest clock (`2026-12-24 08:00`); none: at once.
pub send_at_local: Option<String>,
}
/// A new gift code, never the same as a promo code or another gift's.
@@ -276,20 +335,38 @@ pub async fn fulfil(tx: &mut PgConnection, state: &AppState, id: Uuid) -> Result
.await?;
gift.code = Some(code);
if let Some(to) = gift.recipient_email.clone() {
send(tx, state, &gift, &to).await?;
// Timed for a moment already past (paid late): at once.
let at = gift.send_at.filter(|t| *t > OffsetDateTime::now_utc());
send(tx, state, &gift, &to, at).await?;
}
tracing::info!(gift = %id, package = %gift.package, by_email = gift.recipient_email.is_some(), "gift paid");
}
let send_at_local: Option<String> = sqlx::query_scalar(
"SELECT to_char(send_at AT TIME ZONE 'Europe/Budapest', 'YYYY-MM-DD HH24:MI') FROM gifts \
WHERE id = $1 AND send_at > now()",
)
.bind(id)
.fetch_optional(&mut *tx)
.await?
.flatten();
Ok(Paid {
code: display(gift.code()?),
card: gift.card_payload(state)?,
recipient_name: gift.recipient_name,
recipient_email: gift.recipient_email,
send_at_local,
})
}
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language.
async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) -> Result<(), ApiError> {
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language,
/// not before `at` (none: at once).
async fn send(
tx: &mut PgConnection,
state: &AppState,
gift: &Gift,
to: &str,
at: Option<OffsetDateTime>,
) -> Result<(), ApiError> {
let locale: Option<String> = sqlx::query_scalar("SELECT locale FROM users WHERE id = $1")
.bind(gift.buyer_id)
.fetch_optional(&mut *tx)
@@ -304,16 +381,38 @@ async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) ->
"from_name": gift.from_name,
"message": gift.message,
"gift_card": gift.card_payload(state)?,
"christmas_year": gift.christmas(),
});
// Not the recipient's account (if they have one): no user id.
queue_email_to(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload).await?;
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now() WHERE id = $1")
let email = queue_email_at(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload, at).await?;
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now(), email_id = $2 WHERE id = $1")
.bind(gift.id)
.bind(email)
.execute(&mut *tx)
.await?;
Ok(())
}
/// Takes back the gift's e-mail if it has not gone out yet (sent now
/// instead, or refunded): a timed one would come later otherwise. It does
/// not count as a sending then.
async fn cancel_pending_email(conn: &mut PgConnection, gift: &Gift) -> Result<bool, sqlx::Error> {
let Some(email) = gift.email_id else { return Ok(false) };
let taken = sqlx::query("DELETE FROM email_outbox WHERE id = $1 AND sent_at IS NULL AND failed_at IS NULL")
.bind(email)
.execute(&mut *conn)
.await?
.rows_affected()
== 1;
if taken {
sqlx::query("UPDATE gifts SET sendings = greatest(sendings - 1, 0) WHERE id = $1")
.bind(gift.id)
.execute(&mut *conn)
.await?;
}
Ok(taken)
}
/// The user's paid gifts, newest first.
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let gifts: Vec<Gift> = sqlx::query_as(&format!(
@@ -339,6 +438,7 @@ pub async fn card(
let code = display(gift.code()?);
let url = redeem_url(&state, gift.code()?);
let filename = format!("sorsfonalak-ajandek-{code}.pdf");
let christmas = gift.christmas();
let pdf = tokio::task::spawn_blocking(move || {
let contents = package.contents_items();
gift_card::pdf(&gift_card::Card {
@@ -349,6 +449,7 @@ pub async fn card(
recipient_name: gift.recipient_name.as_deref(),
from_name: gift.from_name.as_deref(),
message: gift.message.as_deref(),
christmas,
})
})
.await
@@ -387,18 +488,26 @@ pub async fn send_again(
return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották."));
}
gift.refused_if_refunded()?;
if gift.sendings >= MAX_SENDINGS {
// A timed e-mail still waiting is replaced by this one, not added to it.
let waiting = gift.email_state.as_deref() == Some("scheduled");
if gift.sendings - i32::from(waiting) >= MAX_SENDINGS {
return Err(ApiError::conflict(
"gift_send_limit",
"Ezt az ajándékot már háromszor elküldtük e-mailben. Töltsd le az utalványt, és küldd el te magad.",
));
}
if gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
if !waiting && gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
return Err(ApiError::conflict("gift_send_wait", "Pár perc múlva küldheted el újra."));
}
sqlx::query("UPDATE gifts SET recipient_email = $2 WHERE id = $1").bind(id).bind(&to).execute(&mut *tx).await?;
// Now, instead of a timed e-mail still waiting.
cancel_pending_email(&mut tx, &gift).await?;
sqlx::query("UPDATE gifts SET recipient_email = $2, send_at = NULL WHERE id = $1")
.bind(id)
.bind(&to)
.execute(&mut *tx)
.await?;
gift.recipient_email = Some(to.clone());
send(&mut tx, &state, &gift, &to).await?;
send(&mut tx, &state, &gift, &to, None).await?;
let gift = own_gift(&mut tx, id, auth.id(), false).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), gift = %id, "gift sent by e-mail");
@@ -469,6 +578,8 @@ struct AdminGift {
storno_status: Option<String>,
storno_number: Option<String>,
storno_error: Option<String>,
send_at: Option<OffsetDateTime>,
email_state: Option<String>,
}
#[derive(Deserialize)]
@@ -493,7 +604,11 @@ pub async fn admin_list(
g.redeemed_at, r.email AS redeemed_by, g.refunded_at, g.refund_id, g.refund_error, \
c.id AS checkout_id, c.live, coalesce(c.amount_huf, c.price_huf) AS amount_huf, \
i.invoice_number, i.status AS invoice_status, \
x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error \
x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error, \
g.send_at, \
(SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \
WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \
FROM email_outbox o WHERE o.id = g.email_id) AS email_state \
FROM gifts g LEFT JOIN users b ON b.id = g.buyer_id LEFT JOIN users r ON r.id = g.redeemed_by \
LEFT JOIN stripe_checkouts c ON c.gift_id = g.id LEFT JOIN invoices i ON i.checkout_id = c.id \
LEFT JOIN invoice_cancellations x ON x.invoice_id = i.id \
@@ -535,10 +650,29 @@ pub async fn admin_list(
"checkout": g.checkout_id.map(|id| json!({ "id": id, "live": g.live, "amount_huf": g.amount_huf })),
"invoice": g.invoice_status.map(|s| json!({ "number": g.invoice_number, "status": s })),
"storno": g.storno_status.map(|s| json!({ "status": s, "number": g.storno_number, "error": g.storno_error })),
"send_at": rfc3339_opt(g.send_at),
"email_state": g.email_state,
})
})
.collect();
Ok(Json(json!({ "gifts": gifts, "withdrawal_days": WITHDRAWAL_DAYS })))
// The timed e-mails by hour (Budapest clock): how many wait, went out or failed.
let schedule: Vec<(String, i64, i64, i64)> = sqlx::query_as(
"SELECT to_char(date_trunc('hour', g.send_at AT TIME ZONE 'Europe/Budapest'), 'YYYY-MM-DD HH24:MI'), \
count(*) FILTER (WHERE o.id IS NOT NULL AND o.sent_at IS NULL AND o.failed_at IS NULL), \
count(*) FILTER (WHERE o.sent_at IS NOT NULL OR (o.id IS NULL AND g.send_at <= now())), \
count(*) FILTER (WHERE o.failed_at IS NOT NULL) \
FROM gifts g LEFT JOIN email_outbox o ON o.id = g.email_id \
WHERE g.send_at IS NOT NULL AND g.paid_at IS NOT NULL AND g.refunded_at IS NULL \
AND g.send_at > now() - interval '30 days' \
GROUP BY 1 ORDER BY 1",
)
.fetch_all(&state.db)
.await?;
let schedule: Vec<Value> = schedule
.into_iter()
.map(|(at, waiting, sent, failed)| json!({ "at": at, "waiting": waiting, "sent": sent, "failed": failed }))
.collect();
Ok(Json(json!({ "gifts": gifts, "schedule": schedule, "withdrawal_days": WITHDRAWAL_DAYS })))
}
/// Admin: refunds a gift the buyer withdrew from. Refused once it is
@@ -577,6 +711,8 @@ pub async fn admin_refund(
.bind(admin.0.id())
.execute(&mut *tx)
.await?;
// A timed e-mail not gone out yet stays unsent.
cancel_pending_email(&mut tx, &gift).await?;
if let Some((checkout_id, _)) = &checkout {
let reason = format!("Elállás az ajándékcsomag vásárlásától (beváltás előtt), kód: {}", display(gift.code()?));
sqlx::query(
@@ -634,3 +770,25 @@ pub async fn admin_refund(
json!({ "status": gift.status(), "refund_id": gift.refund_id, "refunded_at": rfc3339_opt(gift.refunded_at) }),
))
}
#[cfg(test)]
mod tests {
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use super::christmas_year;
fn at(s: &str) -> OffsetDateTime {
OffsetDateTime::parse(s, &Rfc3339).unwrap()
}
#[test]
fn christmas_runs_from_mid_november_to_epiphany() {
assert_eq!(christmas_year(at("2026-11-14T22:59:00Z")), None);
assert_eq!(christmas_year(at("2026-11-14T23:00:00Z")), Some(2027));
assert_eq!(christmas_year(at("2026-12-31T23:30:00Z")), Some(2027));
assert_eq!(christmas_year(at("2027-01-06T22:59:00Z")), Some(2027));
assert_eq!(christmas_year(at("2027-01-06T23:00:00Z")), None);
assert_eq!(christmas_year(at("2027-07-01T12:00:00Z")), None);
}
}
+7 -3
View File
@@ -327,6 +327,7 @@ async fn confirm_by_email(
"promo_code": gift.code,
"recipient_name": gift.recipient_name,
"recipient_email": gift.recipient_email,
"send_at": gift.send_at_local,
});
// Handed over by the buyer: the card comes with the confirmation.
if gift.recipient_email.is_none() {
@@ -375,13 +376,16 @@ pub async fn checkout_status(
}
let gift = match gift_id {
Some(id) => {
let (name, to): (Option<String>, Option<String>) =
sqlx::query_as("SELECT recipient_name, recipient_email FROM gifts WHERE id = $1")
let (name, to, send_at): (Option<String>, Option<String>, Option<OffsetDateTime>) =
sqlx::query_as("SELECT recipient_name, recipient_email, send_at FROM gifts WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?
.unwrap_or_default();
Some(json!({ "id": id, "recipient_name": name, "recipient_email": to }))
Some(json!({
"id": id, "recipient_name": name, "recipient_email": to,
"send_at": crate::views::rfc3339_opt(send_at.filter(|t| *t > OffsetDateTime::now_utc())),
}))
}
None => None,
};
+75 -3
View File
@@ -3413,7 +3413,7 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
.unwrap();
assert_eq!(
confirmation["gift"],
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com"})
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com", "send_at": null})
);
assert!(confirmation["gift_card"].is_null(), "the recipient has the card");
assert_eq!(confirmation["url"], "https://sorsfonalak.test/ajandekaim");
@@ -3426,7 +3426,10 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
.unwrap();
assert_eq!(invoices, 1);
let r = app.get(&format!("/v1/payments/checkout/{session}"), Some(&anna)).await;
assert_eq!(r.body["gift"], json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com"}));
assert_eq!(
r.body["gift"],
json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com", "send_at": null})
);
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
@@ -3459,8 +3462,10 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
sqlx::query("UPDATE gifts SET last_sent_at = now() - interval '11 minutes'").execute(&app.pool).await.unwrap();
let r = send("cili@example.com").await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(2)));
// The first e-mail had not gone out yet (no worker here): the corrected address replaces it.
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(1)));
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 0);
let r = app
.post(
&format!("/v1/gifts/{gift_id}/send"),
@@ -3960,3 +3965,70 @@ async fn the_recommendation_question_comes_once_after_two_contents(pool: PgPool)
);
assert_eq!(nps["comments"][0]["comment"], "Nagyon tetszik.");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_gift_can_be_e_mailed_at_a_chosen_time(pool: PgPool) {
// The stand-in payment: paid at once.
let app = TestApp::new(pool).await;
let anna = app.register("anna@example.com", "Anna").await;
let admin = app.register("admin@example.com", "Admin").await;
let at = (time::OffsetDateTime::now_utc() + time::Duration::days(10))
.replace_nanosecond(0)
.unwrap()
.format(&time::format_description::well_known::Rfc3339)
.unwrap();
let body = |send_at: &str, email: Option<&str>| {
json!({"package": "couple", "recipient_name": "Bea", "recipient_email": email,
"recipient_email_confirm": email, "send_at": send_at})
};
// In the past, or with nobody to e-mail: refused.
let past = app.post("/v1/gifts/checkout", Some(&anna), body("2020-01-01T08:00:00Z", Some("bea@example.com"))).await;
assert_eq!(past.status, StatusCode::BAD_REQUEST);
let nobody = app.post("/v1/gifts/checkout", Some(&anna), body(&at, None)).await;
assert_eq!(nobody.status, StatusCode::BAD_REQUEST);
let r = app.post("/v1/gifts/checkout", Some(&anna), body(&at, Some("bea@example.com"))).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let id = r.body["id"].as_str().unwrap().to_string();
// Queued for that moment, not sent yet.
let (due, sent): (time::OffsetDateTime, Option<time::OffsetDateTime>) = sqlx::query_as(
"SELECT next_attempt_at, sent_at FROM email_outbox WHERE to_email = 'bea@example.com' AND template = 'gift_package'",
)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!((due.format(&time::format_description::well_known::Rfc3339).unwrap(), sent), (at.clone(), None));
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
assert_eq!(
(&gift["email_state"], &gift["send_at"], &gift["can_send"]),
(&json!("scheduled"), &json!(at), &json!(true))
);
let r = app.get("/v1/admin/gifts", Some(&admin)).await;
assert_eq!(r.body["gifts"][0]["email_state"], "scheduled");
let slot = &r.body["schedule"][0];
assert_eq!((&slot["waiting"], &slot["sent"]), (&json!(1), &json!(0)));
// Sent now after all: the timed one is taken back (one e-mail, not two), and it is no extra sending.
let r = app
.post(
&format!("/v1/gifts/{id}/send"),
Some(&anna),
json!({"recipient_email": "bea@example.com", "recipient_email_confirm": "bea@example.com"}),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(
(&r.body["send_at"], &r.body["sendings"], &r.body["email_state"]),
(&Value::Null, &json!(1), &json!("sending"))
);
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 1);
// A timed gift refunded before it goes out: the e-mail stays unsent.
let r = app.post("/v1/gifts/checkout", Some(&anna), body(&at, Some("cili@example.com"))).await;
let other = r.body["id"].as_str().unwrap().to_string();
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
let r = app.post(&format!("/v1/admin/gifts/{other}/refund"), Some(&admin), json!({})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 0);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

@@ -8,6 +8,16 @@ import type { AdminGift } from "@/lib/types";
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
/** The timed gift e-mails of one hour. */
type Slot = { at: string; waiting: number; sent: number; failed: number };
const EMAIL: Record<string, string> = {
scheduled: "levél időzítve",
sending: "levél küldés alatt",
sent: "levél kiment",
failed: "levél hiba",
};
const STORNO: Record<string, string> = {
pending: "sztornó folyamatban",
done: "sztornózva",
@@ -17,6 +27,7 @@ const STORNO: Record<string, string> = {
/** The gifts with their payment, invoice and storno, and the refund button. */
export function AdminGifts() {
const [gifts, setGifts] = useState<AdminGift[] | null>(null);
const [schedule, setSchedule] = useState<Slot[]>([]);
const [q, setQ] = useState("");
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -24,10 +35,11 @@ export function AdminGifts() {
const load = useCallback(async (search: string) => {
try {
const r = await api<{ gifts: AdminGift[] }>(
const r = await api<{ gifts: AdminGift[]; schedule: Slot[] }>(
`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`,
);
setGifts(r.gifts);
setSchedule(r.schedule ?? []);
} catch (e) {
setError(errorText(e));
}
@@ -66,153 +78,203 @@ export function AdminGifts() {
}
return (
<section className="card">
<div className="field">
<label htmlFor="gift-search">Keresés</label>
<input
id="gift-search"
className="inp"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{done && (
<p className="msg msg-ok" role="status">
{done}
</p>
)}
{gifts === null ? (
<p className="muted">Betöltés…</p>
) : gifts.length === 0 ? (
<p className="muted">Nincs ilyen ajándék.</p>
) : (
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Kód</th>
<th>Csomag</th>
<th>Vásárló → címzett</th>
<th>Fizetve</th>
<th>Állapot</th>
<th>Számla</th>
<th />
</tr>
</thead>
<tbody>
{gifts.map((g) => (
<tr key={g.id}>
<td>
<code className="promo-code">{g.code}</code>
</td>
<td>
{g.package.name ?? g.package.id}
{g.checkout?.amount_huf ? (
<span className="hint">{huf(g.checkout.amount_huf)}</span>
) : null}
{g.checkout && g.checkout.live === false && (
<span className="hint">teszt fizetés</span>
)}
</td>
<td>
{g.buyer_email ?? (
<span className="muted">törölt fiók</span>
)}
<span className="hint">
→ {g.recipient_name ?? "?"}
{g.recipient_email
? ` (${g.recipient_email})`
: " (maga adja át)"}
</span>
</td>
<td className="num">{formatDate(g.paid_at, true)}</td>
<td>
{g.status === "redeemed" ? (
<>
beváltva{" "}
{g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
{g.redeemed_by && (
<span className="hint">{g.redeemed_by}</span>
)}
</>
) : g.status === "refunded" ? (
<>
{g.refund_pending ? (
<span className="msg-error">
visszatérítés félbemaradt
</span>
) : (
"visszatérítve"
)}{" "}
{g.refunded_at ? formatDate(g.refunded_at, true) : ""}
{g.refund_pending && g.refund_error && (
<span className="hint">{g.refund_error}</span>
)}
</>
) : (
<>
<span className="promo-open">beváltatlan</span>
<span className="hint">
{g.within_withdrawal
? "14 napon belül"
: "14 nap letelt"}
</span>
</>
)}
</td>
<td>
{g.invoice ? (
<>
{g.invoice.number ??
(g.invoice.status === "pending"
? "kiállítás alatt"
: g.invoice.status)}
{g.storno && (
<span
className={
g.storno.status === "failed"
? "hint msg-error"
: "hint"
}
>
{STORNO[g.storno.status] ?? g.storno.status}
{g.storno.number ? `: ${g.storno.number}` : ""}
{g.storno.error ? ` – ${g.storno.error}` : ""}
</span>
)}
</>
) : (
<span className="muted">–</span>
)}
</td>
<td>
{(g.status === "open" || g.refund_pending) && (
<button
type="button"
className="btn btn-sm"
onClick={() => refund(g)}
disabled={busy !== null}
>
{busy === g.id
? "Folyamatban…"
: g.status === "refunded"
? "Újrapróbálás"
: "Visszatérítés"}
</button>
)}
</td>
<>
{schedule.length > 0 && (
<section className="card" aria-labelledby="schedule-title">
<h2 id="schedule-title">Időzített levelek</h2>
<p className="hint">
Az időzítve küldött ajándéklevelek óránként (magyar idő, az elmúlt
30 nap és ami még jön). Figyeld, hogy a kiment levelek száma az
időpont után megnőjön, és ne legyen hiba.
</p>
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Időpont</th>
<th>Vár</th>
<th>Kiment</th>
<th>Hiba</th>
</tr>
))}
</tbody>
</table>
</div>
</thead>
<tbody>
{schedule.map((s) => (
<tr key={s.at}>
<td className="num">{s.at}</td>
<td className="num">{s.waiting || "–"}</td>
<td className="num">{s.sent || "–"}</td>
<td className={s.failed ? "num msg-error" : "num"}>
{s.failed || "–"}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
)}
</section>
<section className="card">
<div className="field">
<label htmlFor="gift-search">Keresés</label>
<input
id="gift-search"
className="inp"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{done && (
<p className="msg msg-ok" role="status">
{done}
</p>
)}
{gifts === null ? (
<p className="muted">Betöltés…</p>
) : gifts.length === 0 ? (
<p className="muted">Nincs ilyen ajándék.</p>
) : (
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Kód</th>
<th>Csomag</th>
<th>Vásárló → címzett</th>
<th>Fizetve</th>
<th>Állapot</th>
<th>Számla</th>
<th />
</tr>
</thead>
<tbody>
{gifts.map((g) => (
<tr key={g.id}>
<td>
<code className="promo-code">{g.code}</code>
</td>
<td>
{g.package.name ?? g.package.id}
{g.checkout?.amount_huf ? (
<span className="hint">
{huf(g.checkout.amount_huf)}
</span>
) : null}
{g.checkout && g.checkout.live === false && (
<span className="hint">teszt fizetés</span>
)}
</td>
<td>
{g.buyer_email ?? (
<span className="muted">törölt fiók</span>
)}
<span className="hint">
→ {g.recipient_name ?? "?"}
{g.recipient_email
? ` (${g.recipient_email})`
: " (maga adja át)"}
</span>
{g.email_state && (
<span
className={
g.email_state === "failed"
? "hint msg-error"
: "hint"
}
>
{EMAIL[g.email_state]}
{g.send_at ? ` · ${formatDate(g.send_at, true)}` : ""}
</span>
)}
</td>
<td className="num">{formatDate(g.paid_at, true)}</td>
<td>
{g.status === "redeemed" ? (
<>
beváltva{" "}
{g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
{g.redeemed_by && (
<span className="hint">{g.redeemed_by}</span>
)}
</>
) : g.status === "refunded" ? (
<>
{g.refund_pending ? (
<span className="msg-error">
visszatérítés félbemaradt
</span>
) : (
"visszatérítve"
)}{" "}
{g.refunded_at ? formatDate(g.refunded_at, true) : ""}
{g.refund_pending && g.refund_error && (
<span className="hint">{g.refund_error}</span>
)}
</>
) : (
<>
<span className="promo-open">beváltatlan</span>
<span className="hint">
{g.within_withdrawal
? "14 napon belül"
: "14 nap letelt"}
</span>
</>
)}
</td>
<td>
{g.invoice ? (
<>
{g.invoice.number ??
(g.invoice.status === "pending"
? "kiállítás alatt"
: g.invoice.status)}
{g.storno && (
<span
className={
g.storno.status === "failed"
? "hint msg-error"
: "hint"
}
>
{STORNO[g.storno.status] ?? g.storno.status}
{g.storno.number ? `: ${g.storno.number}` : ""}
{g.storno.error ? ` – ${g.storno.error}` : ""}
</span>
)}
</>
) : (
<span className="muted">–</span>
)}
</td>
<td>
{(g.status === "open" || g.refund_pending) && (
<button
type="button"
className="btn btn-sm"
onClick={() => refund(g)}
disabled={busy !== null}
>
{busy === g.id
? "Folyamatban…"
: g.status === "refunded"
? "Újrapróbálás"
: "Visszatérítés"}
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</>
);
}
+112 -1
View File
@@ -7,6 +7,7 @@ import { useEffect, useId, useState } from "react";
import { huf } from "@/components/PackageCards";
import { api, errorText } from "@/lib/api";
import { contents } from "@/lib/packageContents";
import { christmasMorning } from "@/lib/season";
import type { Package, PayMethod } from "@/lib/types";
const MAX_MESSAGE = 300;
@@ -17,6 +18,19 @@ const looksLikeEmail = (s: string) =>
const same = (a: string, b: string) =>
a.trim().toLowerCase() === b.trim().toLowerCase();
/** `2026-12-24` on the browser's clock. */
const localDay = (d: Date) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
/** "dec. 24. 8:00" */
const whenText = (d: Date) =>
d.toLocaleString("hu-HU", {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
/**
* The gift order: which package, whom it is for and from whom, how it gets
* to the recipient (we e-mail it, the address typed twice; or the buyer
@@ -49,6 +63,10 @@ export function GiftForm({
const [confirm, setConfirm] = useState("");
const [from, setFrom] = useState(defaultFrom.slice(0, MAX_NAME));
const [message, setMessage] = useState("");
const [timed, setTimed] = useState(false);
const xmas = christmasMorning();
const [day, setDay] = useState(xmas ? localDay(xmas) : "");
const [clock, setClock] = useState("08:00");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Back from Stripe's page (the browser may restore this page as it was).
@@ -64,6 +82,14 @@ export function GiftForm({
const mismatch = byEmail && confirm.trim() !== "" && !same(email, confirm);
const emailOk = !byEmail || (looksLikeEmail(email) && same(email, confirm));
const stripe = canPay === "stripe" || canPay === "stripe_test";
// The chosen moment on the buyer's own clock.
const sendAt = day && clock ? new Date(`${day}T${clock}`) : null;
const ahead = sendAt ? sendAt.getTime() - Date.now() : 0;
const timeOk =
sendAt !== null &&
!Number.isNaN(ahead) &&
ahead > 10 * 60 * 1000 &&
ahead < 365 * 86400 * 1000;
async function submit(e: React.FormEvent) {
e.preventDefault();
@@ -81,6 +107,7 @@ export function GiftForm({
recipient_email_confirm: byEmail ? confirm.trim() : null,
from_name: from.trim() || null,
message: message.trim() || null,
send_at: byEmail && timed && sendAt ? sendAt.toISOString() : null,
},
},
);
@@ -223,6 +250,81 @@ export function GiftForm({
</div>
</div>
)}
{byEmail && (
<div className="gift-when">
<span className="label">Mikor kapja meg?</span>
<div className="gift-when-choices">
<label
className={!timed ? "feedback-kind is-on" : "feedback-kind"}
>
<input
type="radio"
name={`${id}-when`}
checked={!timed}
onChange={() => setTimed(false)}
/>
Fizetés után azonnal
</label>
<label
className={timed ? "feedback-kind is-on" : "feedback-kind"}
>
<input
type="radio"
name={`${id}-when`}
checked={timed}
onChange={() => setTimed(true)}
/>
Időzítve
</label>
{xmas && (
<button
type="button"
className="btn btn-sm"
onClick={() => {
setTimed(true);
setDay(localDay(xmas));
setClock("08:00");
}}
>
Karácsony reggel (dec. 24., 8:00)
</button>
)}
</div>
{timed && (
<div className="gift-when-fields">
<div className="field">
<label htmlFor={`${id}-day`}>Nap</label>
<input
id={`${id}-day`}
className="inp"
type="date"
value={day}
min={localDay(new Date())}
onChange={(e) => setDay(e.target.value)}
/>
</div>
<div className="field">
<label htmlFor={`${id}-clock`}>Időpont</label>
<input
id={`${id}-clock`}
className="inp"
type="time"
step={900}
value={clock}
onChange={(e) => setClock(e.target.value)}
/>
</div>
</div>
)}
<span className={timed && !timeOk ? "msg msg-error" : "hint"}>
{timed
? timeOk
? "A te időd szerint. Addig az Ajándékaim oldalon letöltheted az utalványt, vagy elküldheted azonnal is."
: "Válassz egy jövőbeli időpontot (legfeljebb egy évre előre)."
: "Ha későbbre szánod, időzítsd, vagy válaszd az „Én adom át” lehetőséget."}
</span>
</div>
)}
</fieldset>
<div className="field">
@@ -253,6 +355,9 @@ export function GiftForm({
<span className="muted">
„{chosen.name}” csomag ajándékba
{name.trim() ? `, ${name.trim()} részére` : ""}
{byEmail && timed && sendAt && timeOk
? ` · küldés: ${whenText(sendAt)}`
: ""}
</span>
<strong className="num">{huf(chosen.price_huf)}</strong>
</p>
@@ -261,7 +366,13 @@ export function GiftForm({
<button
type="submit"
className="btn btn-primary"
disabled={busy || !chosen || !emailOk || !name.trim()}
disabled={
busy ||
!chosen ||
!emailOk ||
!name.trim() ||
(byEmail && timed && !timeOk)
}
>
{busy
? stripe
+5 -2
View File
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import Link from "next/link";
import { payMethod } from "@/lib/payments";
import { isChristmasTime } from "@/lib/season";
import { backendGet, requireMe } from "@/lib/server";
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 given = mine?.gifts.length ?? 0;
// Gifts bought now get the Christmas card.
const xmas = isChristmasTime();
return (
<main className="page" style={{ maxWidth: 1080 }}>
<div className="page-head">
<span className="eyebrow">Ajándék</span>
<span className="eyebrow">{xmas ? "Karácsonyi ajándék" : "Ajándék"}</span>
<h1>Ajándékozz csomagot</h1>
<p className="muted">
Születési képlet, személyre szóló elemzések, kapcsolati összevetés:
@@ -57,7 +60,7 @@ export default async function GiftPage({ searchParams }: Props) {
<figure className="gift-sample">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/img/ajandek-utalvany.webp"
src={xmas ? "/img/ajandek-karacsony.webp" : "/img/ajandek-utalvany.webp"}
width={420}
height={594}
alt="Minta ajándékutalvány: a csomag neve, a személyes üzenet, az ajándékkód és a QR-kód"
@@ -12,6 +12,15 @@ const day = (iso: string) =>
month: "long",
day: "numeric",
});
/** "december 24., 8:00" */
const when = (iso: string) =>
new Date(iso).toLocaleString("hu-HU", {
timeZone: "Europe/Budapest",
month: "long",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
const time = (iso: string) =>
new Date(iso).toLocaleTimeString("hu-HU", {
timeZone: "Europe/Budapest",
@@ -127,7 +136,19 @@ function GiftItem({
</div>
<p className="gift-to">
{gift.recipient_email ? (
{gift.recipient_email &&
gift.email_state === "scheduled" &&
gift.send_at ? (
<>
Időzítve: <strong>{when(gift.send_at)}</strong>, ide:{" "}
<strong>{gift.recipient_email}</strong>
</>
) : gift.recipient_email && gift.email_state === "failed" ? (
<>
Nem sikerült elküldeni ide: <strong>{gift.recipient_email}</strong>.
Ellenőrizd a címet, és küldd újra.
</>
) : gift.recipient_email ? (
<>
E-mailben elküldve ide: <strong>{gift.recipient_email}</strong>
{gift.sendings > 1 ? ` (${gift.sendings}×)` : ""}
@@ -165,9 +186,11 @@ function GiftItem({
className="btn btn-sm"
onClick={() => setSending(true)}
>
{gift.recipient_email
? "Újraküldés e-mailben"
: "Küldés e-mailben"}
{gift.email_state === "scheduled"
? "Küldés most"
: gift.recipient_email
? "Újraküldés e-mailben"
: "Küldés e-mailben"}
</button>
)}
</div>
+6 -3
View File
@@ -5,6 +5,7 @@ import { AiNote } from "@/components/AiNote";
import { PackageCards } from "@/components/PackageCards";
import { RedeemCode } from "@/components/RedeemCode";
import { payMethod } from "@/lib/payments";
import { isChristmasTime } from "@/lib/season";
import { backendGet, requireMe } from "@/lib/server";
import type { Package, PublicConfig } from "@/lib/types";
@@ -50,6 +51,7 @@ export default async function PackagesPage() {
]);
const packages = catalog?.packages ?? [];
const canPay = payMethod(config, me);
const xmas = isChristmasTime();
const left = me.analyses_left;
const slots = me.persons;
@@ -100,14 +102,15 @@ export default async function PackagesPage() {
<section className="card gift-banner" aria-labelledby="gift-title">
<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">
A három fő csomag bármelyikét megveheted másnak: e-mailben elküldjük neki egy nyomtatható utalvánnyal, vagy
letöltöd, és te adod át. A kódot ő váltja be a saját fiókjában, és nem jár le.
{xmas && " Karácsony reggelre is időzítheted."}
</p>
</div>
<Link className="btn" href="/ajandek">
Megajándékozok valakit
<Link className="btn" href={xmas ? "/karacsony" : "/ajandek"}>
{xmas ? "Karácsonyi ajándék" : "Megajándékozok valakit"}
</Link>
</section>
+21
View File
@@ -1748,3 +1748,24 @@ span.tarot-fan-card { cursor: default; }
}
/* The ☰ panel covers the page fully (the header's blur showed it through). */
.mobile-menu-panel { background: #0f1528; }
/* When the gift e-mail goes: at once, or timed (e.g. Christmas morning). */
.gift-when { display: flex; flex-direction: column; gap: 10px; padding-top: 6px; }
.gift-when-choices { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.gift-when-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 220px)); gap: 12px; }
@media (max-width: 640px) { .gift-when-fields { grid-template-columns: 1fr 1fr; } }
/* The Christmas campaign page */
.xmas-hero { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 32px; align-items: center; }
.xmas-hero-text { display: flex; flex-direction: column; gap: 14px; }
.xmas-hero h1 { font-size: clamp(40px, 5vw, 60px); }
.xmas-hero .lead { font-size: 18px; line-height: 1.6; color: var(--ink-2); margin: 0; }
.xmas-points { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
.xmas-points .card { gap: 8px; }
.xmas-points h2 { font-size: 24px; }
.xmas-points p { margin: 0; line-height: 1.6; }
.xmas-delivery ul { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 8px; color: var(--ink-2); }
.xmas-packages { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
@media (max-width: 900px) {
.xmas-hero { grid-template-columns: 1fr; }
.xmas-sample img { max-width: 260px; }
.xmas-points, .xmas-packages { grid-template-columns: 1fr; }
}
@@ -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>
</>
);
}
+1
View File
@@ -33,6 +33,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
{ url: `${base}/aszf`, changeFrequency: "yearly", priority: 0.2 },
{ url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 },
{ url: `${base}/karacsony`, changeFrequency: "monthly", priority: 0.7 },
{ url: `${base}/adatvedelem`, 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<{
status: string;
name: string | null;
gift: { id: string; recipient_name: string | null; recipient_email: string | null } | null;
gift: {
id: string;
recipient_name: string | null;
recipient_email: string | null;
send_at: string | null;
} | null;
}>(`/payments/checkout/${encodeURIComponent(value)}`);
if (stopped) return;
if (r.status === "paid") {
const text = !r.gift
? `Köszönjük! Jóváírtuk: ${r.name ?? "a csomagod"}.`
: r.gift.recipient_email
: r.gift.recipient_email && r.gift.send_at
? `Köszönjük! Az ajándékot ${new Date(r.gift.send_at).toLocaleString("hu-HU", { month: "long", day: "numeric", hour: "numeric", minute: "2-digit" })}-kor küldjük el ide: ${r.gift.recipient_email}.`
: r.gift.recipient_email
? `Köszönjük! Az ajándékot elküldtük ide: ${r.gift.recipient_email}. Az utalványt lent le is töltheted.`
: "Köszönjük! Az ajándékutalvány elkészült: lent letöltheted, és átadhatod.";
setNotice({ kind: "ok", text });
+30
View File
@@ -0,0 +1,30 @@
// The Christmas season of the gift campaign (Budapest dates; the backend
// marks the gifts by the same window).
const parts = (now: Date) => {
const [y, m, d] = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Budapest",
year: "numeric",
month: "2-digit",
day: "2-digit",
})
.format(now)
.split("-")
.map(Number);
return { y, m, d };
};
/** 15 November to 6 January: gifts are Christmas gifts (festive card, e-mail). */
export function isChristmasTime(now = new Date()): boolean {
const { m, d } = parts(now);
return (m === 11 && d >= 15) || m === 12 || (m === 1 && d <= 6);
}
/** Christmas morning (24 December, 8:00 Budapest) of this season, if still ahead. */
export function christmasMorning(now = new Date()): Date | null {
const { y, m } = parts(now);
if (m !== 11 && m !== 12) return null;
// 8:00 in Budapest is 7:00 UTC in December (winter time).
const at = new Date(Date.UTC(y, 11, 24, 7, 0));
return at.getTime() > now.getTime() + 10 * 60 * 1000 ? at : null;
}
+10
View File
@@ -660,8 +660,12 @@ export interface AdminGift {
checkout: { id: string; live: boolean | null; amount_huf: number | null } | null;
invoice: { number: string | null; status: string } | null;
storno: { status: string; number: string | null; error: string | null } | null;
send_at: string | null;
email_state: EmailState | null;
}
export type EmailState = "scheduled" | "sending" | "sent" | "failed";
/** A package the user bought as a gift (`GET /v1/gifts`). */
export interface Gift {
id: string;
@@ -678,6 +682,12 @@ export interface Gift {
status: "open" | "redeemed" | "refunded";
redeemed_at: string | null;
refunded_at: string | null;
/** E-mailed at this time (null: at once). */
send_at: string | null;
/** The e-mail: waiting for its time, going out, gone out or failed (null: none, or long gone out). */
email_state: EmailState | null;
/** Bought for Christmas (the card is festive). */
christmas: boolean;
/** E-mails sent so far. */
sendings: number;
/** Whether it can be sent by e-mail (again). */
+1
View File
@@ -137,6 +137,7 @@ async fn gift_card(id: Uuid, payload: &Value) -> Option<Pdf> {
recipient_name: to.as_deref(),
from_name: from.as_deref(),
message: message.as_deref(),
christmas: card["christmas_year"].as_i64().and_then(|y| i32::try_from(y).ok()),
})
.map_err(|e| e.to_string())?;
let code: String = code.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();