Gift packages: buy a main package for someone, with a printable gift card

- /ajandek: the package, whom it is for and from whom, the recipient's
  address typed twice (or "I hand it over"), a message; paid on Stripe
  like any package, the invoice is the buyer's
- On payment the gift gets its own code (not a promo code: it cannot be
  withdrawn, and it adds the whole package); redeemed on /bevaltas
- The recipient's e-mail carries the message and the code, with the gift
  card attached as a PDF; the buyer's confirmation says it was a gift
- /ajandekaim: codes, state, the card to download, sending it by e-mail
  (again, or to another address) up to three times
- crates/gift-card draws the A4 card (example chart, questions avatar,
  QR code) as SVG and makes a PDF with krilla, fonts compiled in; the
  backend draws downloads on a blocking thread, the worker the e-mails
- Telegram notices say "(ajándék)"; unpaid gifts go after a week

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-23 20:28:11 +00:00
co-authored by Claude Opus 5.5
parent 699ce2abbd
commit c90232f40c
46 changed files with 3647 additions and 88 deletions
+1
View File
@@ -10,6 +10,7 @@ publish.workspace = true
db.workspace = true
analysis-prompt.workspace = true
email-templates.workspace = true
gift-card.workspace = true
hmac.workspace = true
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
rand.workspace = true
+11 -3
View File
@@ -210,6 +210,8 @@ pub enum Source {
Mock,
/// A redeemed promo code.
Promo,
/// A redeemed gift code (someone else paid for it).
Gift,
/// Paid through Stripe Checkout.
Stripe,
}
@@ -220,6 +222,7 @@ impl Source {
Source::Admin => "admin",
Source::Mock => "mock",
Source::Promo => "promo",
Source::Gift => "gift",
Source::Stripe => "stripe",
}
}
@@ -228,6 +231,11 @@ impl Source {
impl Package {
/// What the package gives, as a phrase: "2 részletes képletelemzés, 1 kapcsolati elemzés, …".
pub fn contents_text(&self) -> String {
self.contents_items().join(", ")
}
/// What the package gives, item by item ("2 részletes képletelemzés").
pub fn contents_items(&self) -> Vec<String> {
[
(self.natal, "részletes képletelemzés"),
(self.synastry, "kapcsolati elemzés"),
@@ -239,8 +247,7 @@ impl Package {
.into_iter()
.filter(|&(n, _)| n > 0)
.map(|(n, what)| format!("{n} {what}"))
.collect::<Vec<_>>()
.join(", ")
.collect()
}
/// The invoice item: a name that says what the service is (online,
@@ -349,7 +356,8 @@ async fn record(
) -> Result<Uuid, ApiError> {
let order = Uuid::now_v7();
let price = match source {
Source::Admin | Source::Promo => 0,
// A gift's price is on the buyer's checkout.
Source::Admin | Source::Promo | Source::Gift => 0,
Source::Mock | Source::Stripe => package.price_huf,
};
sqlx::query(
+8
View File
@@ -226,6 +226,14 @@ pub async fn delete_me(
.bind(auth.id())
.execute(&mut *tx)
.await?;
// Gifts stay redeemable, but whom they were for and the message go.
sqlx::query(
"UPDATE gifts SET recipient_name = NULL, recipient_email = NULL, from_name = NULL, message = NULL \
WHERE buyer_id = $1",
)
.bind(auth.id())
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), "account deleted");
+413
View File
@@ -0,0 +1,413 @@
//! Gifts: a package of the main ladder bought for someone else.
//!
//! The buyer says whom it is for (a name, and an e-mail address typed twice,
//! or no address: they hand it over themselves), their own name and a
//! message, and pays on Stripe as for any package. When the payment is
//! confirmed the gift gets its code and, with an address, it is e-mailed to
//! the recipient; the worker attaches the gift card (PDF). The buyer can
//! download the card, and send it by e-mail (again, or to another address)
//! while it is not redeemed.
//!
//! A gift code is not a promo code: it cannot be withdrawn (it was paid
//! for), and it adds the whole package, while a promo code only fills the
//! units up to the package's. Both are redeemed in the same place.
use axum::Json;
use axum::extract::{Path, State};
use axum::http::header;
use axum::response::IntoResponse;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
use super::auth::{normalize_email, queue_email_to};
use super::promo::{CODE_LEN, display};
use super::{Body, IdPath, St, payments};
use crate::AppState;
use crate::auth::AuthUser;
use crate::credits::Unit;
use crate::error::{ApiError, ApiResult};
use crate::packages::{self, Package, Source, Tier};
use crate::views::rfc3339_opt;
const MAX_NAME_CHARS: usize = 60;
/// E-mails of one gift: at most this many in all, at least this far apart.
const MAX_SENDINGS: i32 = 3;
const SEND_GAP: time::Duration = time::Duration::minutes(10);
/// The packages that can be given (the main ladder: a good first package).
fn giftable(id: &str) -> Option<&'static Package> {
packages::find(id).filter(|p| p.tier == Tier::Main)
}
/// The recipient's address, typed twice (both the same); `None`: no address.
fn recipient(email: Option<&str>, confirm: Option<&str>) -> Result<Option<String>, ApiError> {
let Some(email) = email.map(str::trim).filter(|e| !e.is_empty()) else { return Ok(None) };
let email = normalize_email(email)?;
if confirm.map(|c| c.trim().to_lowercase()).as_deref() != Some(email.as_str()) {
return Err(ApiError::BadRequest("A két e-mail-cím nem egyezik.".into()));
}
Ok(Some(email))
}
/// A name as shown on the card and in the e-mail (the recipient's or the giver's).
fn clean_name(name: Option<String>) -> Result<Option<String>, ApiError> {
let name: Option<String> = name
.map(|n| n.chars().filter(|c| !c.is_control()).collect::<String>().trim().to_string())
.filter(|n| !n.is_empty());
let Some(name) = name else { return Ok(None) };
if name.chars().count() > MAX_NAME_CHARS {
return Err(ApiError::BadRequest(format!("A név legfeljebb {MAX_NAME_CHARS} karakter lehet.")));
}
let lower = name.to_lowercase();
if lower.contains("://") || lower.contains("www.") {
return Err(ApiError::BadRequest("A névben nem lehet link.".into()));
}
Ok(Some(name))
}
fn redeem_url(state: &AppState, code: &str) -> String {
format!("{}/bevaltas?kod={}", state.config.public_base_url, display(code))
}
#[derive(sqlx::FromRow)]
struct Gift {
id: Uuid,
buyer_id: Option<Uuid>,
package: String,
recipient_name: Option<String>,
recipient_email: Option<String>,
from_name: Option<String>,
message: Option<String>,
paid_at: Option<OffsetDateTime>,
code: Option<String>,
redeemed_at: Option<OffsetDateTime>,
sendings: i32,
last_sent_at: Option<OffsetDateTime>,
}
const COLUMNS: &str = "id, buyer_id, package, recipient_name, recipient_email, from_name, message, paid_at, code, \
redeemed_at, sendings, last_sent_at";
impl Gift {
fn package(&self) -> Result<&'static Package, ApiError> {
packages::find(&self.package).ok_or_else(|| ApiError::Internal(format!("unknown package {}", self.package)))
}
fn code(&self) -> Result<&str, ApiError> {
self.code.as_deref().ok_or_else(|| ApiError::Internal(format!("gift {} has no code", self.id)))
}
/// What the worker needs to draw the gift card for an e-mail.
fn card_payload(&self, state: &AppState) -> Result<Value, ApiError> {
let (package, code) = (self.package()?, self.code()?);
Ok(json!({
"package": package.name,
"contents": package.contents_items(),
"code": display(code),
"redeem_url": redeem_url(state, code),
"recipient_name": self.recipient_name,
"from_name": self.from_name,
"message": self.message,
}))
}
fn view(&self) -> Value {
let status = if self.redeemed_at.is_some() { "redeemed" } else { "open" };
let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc());
json!({
"id": self.id,
"package": { "id": self.package, "name": packages::find(&self.package).map(|p| p.name) },
"recipient_name": self.recipient_name,
"recipient_email": self.recipient_email,
"from_name": self.from_name,
"message": self.message,
"paid_at": rfc3339_opt(self.paid_at),
"code": self.code.as_deref().map(display),
"status": status,
"redeemed_at": rfc3339_opt(self.redeemed_at),
"sendings": self.sendings,
"can_send": status == "open" && self.sendings < MAX_SENDINGS,
"send_again_at": rfc3339_opt(next_send),
})
}
}
/// The buyer's paid gift, locked for an update if `lock`.
async fn own_gift(conn: &mut PgConnection, id: Uuid, buyer: Uuid, lock: bool) -> Result<Gift, ApiError> {
let lock = if lock { " FOR UPDATE" } else { "" };
sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM gifts WHERE id = $1 AND buyer_id = $2 AND paid_at IS NOT NULL{lock}"
))
.bind(id)
.bind(buyer)
.fetch_optional(conn)
.await?
.ok_or(ApiError::NotFound("gift"))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GiftCheckout {
package: String,
/// Whom it is for.
recipient_name: Option<String>,
/// Who gets the gift by e-mail; none: the buyer hands it over.
recipient_email: Option<String>,
/// The address typed again.
recipient_email_confirm: Option<String>,
from_name: Option<String>,
message: Option<String>,
}
/// Starts paying for a gift: returns the address of Stripe's payment page.
/// With the stand-in payment the gift is paid at once (`url` is null).
pub async fn checkout(
State(state): St,
auth: AuthUser,
WithRejection(Json(req), _): Body<GiftCheckout>,
) -> ApiResult<Json<Value>> {
let package = giftable(&req.package).ok_or(ApiError::NotFound("package"))?;
let name = clean_name(req.recipient_name)?
.ok_or_else(|| ApiError::BadRequest("Add meg, kinek szól az ajándék.".into()))?;
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)?;
// Whether this user may pay, before anything is written.
let stripe = match payments::method(&state.config) {
Some("stripe") => Some(payments::stripe_for(&state, &auth)?),
Some(_) => None,
None => return Err(ApiError::NotFound("payment method")),
};
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)",
)
.bind(id)
.bind(auth.id())
.bind(package.id)
.bind(&name)
.bind(&to)
.bind(&from)
.bind(&message)
.execute(&state.db)
.await?;
let url = match stripe {
Some(config) => {
Some(payments::start_checkout(&state, config, &auth, package, Some("/ajandekaim"), Some(id)).await?)
}
None => {
let mut tx = state.db.begin().await?;
fulfil(&mut tx, &state, id).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), package = package.id, "mock gift payment");
None
}
};
Ok(Json(json!({ "id": id, "url": url })))
}
/// A paid gift: its code as shown, whom it is for, where it went, and its
/// card for an e-mail.
pub struct Paid {
pub code: String,
pub recipient_name: Option<String>,
pub recipient_email: Option<String>,
pub card: Value,
}
/// A new gift code, never the same as a promo code or another gift's.
async fn new_code(tx: &mut PgConnection) -> Result<String, sqlx::Error> {
loop {
let code = db::random_code(CODE_LEN);
let taken: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM promo_codes WHERE code = $1) OR EXISTS (SELECT 1 FROM gifts WHERE code = $1)",
)
.bind(&code)
.fetch_one(&mut *tx)
.await?;
if !taken {
return Ok(code);
}
}
}
/// Makes the code of a paid gift and e-mails it to the recipient, inside the
/// caller's transaction. Once: a gift paid already returns what it has.
pub async fn fulfil(tx: &mut PgConnection, state: &AppState, id: Uuid) -> Result<Paid, ApiError> {
let mut gift: Gift = sqlx::query_as(&format!("SELECT {COLUMNS} FROM gifts WHERE id = $1 FOR UPDATE"))
.bind(id)
.fetch_one(&mut *tx)
.await?;
if gift.paid_at.is_none() {
let code = new_code(tx).await?;
sqlx::query("UPDATE gifts SET code = $2, paid_at = now() WHERE id = $1")
.bind(id)
.bind(&code)
.execute(&mut *tx)
.await?;
gift.code = Some(code);
if let Some(to) = gift.recipient_email.clone() {
send(tx, state, &gift, &to).await?;
}
tracing::info!(gift = %id, package = %gift.package, by_email = gift.recipient_email.is_some(), "gift paid");
}
Ok(Paid {
code: display(gift.code()?),
card: gift.card_payload(state)?,
recipient_name: gift.recipient_name,
recipient_email: gift.recipient_email,
})
}
/// 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> {
let locale: Option<String> = sqlx::query_scalar("SELECT locale FROM users WHERE id = $1")
.bind(gift.buyer_id)
.fetch_optional(&mut *tx)
.await?;
let (package, code) = (gift.package()?, gift.code()?);
let payload = json!({
"url": redeem_url(state, code),
"package_name": package.name,
"contents": package.contents_text(),
"promo_code": display(code),
"recipient_name": gift.recipient_name,
"from_name": gift.from_name,
"message": gift.message,
"gift_card": gift.card_payload(state)?,
});
// 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")
.bind(gift.id)
.execute(&mut *tx)
.await?;
Ok(())
}
/// 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!(
"SELECT {COLUMNS} FROM gifts WHERE buyer_id = $1 AND paid_at IS NOT NULL ORDER BY paid_at DESC, id DESC"
))
.bind(auth.id())
.fetch_all(&state.db)
.await?;
Ok(Json(json!({ "gifts": gifts.iter().map(Gift::view).collect::<Vec<_>>(), "max_sendings": MAX_SENDINGS })))
}
/// The gift card as a PDF, for the buyer (drawn on a blocking thread).
pub async fn card(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<impl IntoResponse> {
let mut conn = state.db.acquire().await?;
let gift = own_gift(&mut conn, id, auth.id(), false).await?;
drop(conn);
let package = gift.package()?;
let code = display(gift.code()?);
let url = redeem_url(&state, gift.code()?);
let filename = format!("sorsfonalak-ajandek-{code}.pdf");
let pdf = tokio::task::spawn_blocking(move || {
let contents = package.contents_items();
gift_card::pdf(&gift_card::Card {
package: package.name,
contents: &contents,
code: &code,
redeem_url: &url,
recipient_name: gift.recipient_name.as_deref(),
from_name: gift.from_name.as_deref(),
message: gift.message.as_deref(),
})
})
.await
.map_err(|e| ApiError::Internal(e.to_string()))?
.map_err(|e| ApiError::Internal(e.to_string()))?;
Ok((
[
(header::CONTENT_TYPE, "application/pdf".to_string()),
(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{filename}\"")),
(header::CACHE_CONTROL, "private, no-store".to_string()),
],
pdf,
))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SendGift {
recipient_email: String,
recipient_email_confirm: String,
}
/// Sends the gift by e-mail: again, or to another address, or for the first
/// time when the buyer meant to hand it over. Only while it is not redeemed.
pub async fn send_again(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<SendGift>,
) -> ApiResult<Json<Value>> {
let to = recipient(Some(&req.recipient_email), Some(&req.recipient_email_confirm))?
.ok_or_else(|| ApiError::BadRequest("Add meg, kinek küldjük az ajándékot.".into()))?;
let mut tx = state.db.begin().await?;
let mut gift = own_gift(&mut tx, id, auth.id(), true).await?;
if gift.redeemed_at.is_some() {
return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották."));
}
if gift.sendings >= 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()) {
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?;
gift.recipient_email = Some(to.clone());
send(&mut tx, &state, &gift, &to).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");
Ok(Json(gift.view()))
}
/// A redeemed gift code: the package, what was added and who gave it.
pub(super) struct Redeemed {
pub package: &'static Package,
pub added: Vec<(Unit, i64)>,
pub from_name: Option<String>,
}
/// Redeems a gift code (stored form) for the user, inside the caller's
/// transaction: the whole package, recorded as an order with source `gift`.
/// `None`: not a gift code.
pub(super) async fn redeem(tx: &mut PgConnection, code: &str, user_id: Uuid) -> Result<Option<Redeemed>, ApiError> {
let gift: Option<Gift> =
sqlx::query_as(&format!("SELECT {COLUMNS} FROM gifts WHERE code = $1 AND paid_at IS NOT NULL FOR UPDATE"))
.bind(code)
.fetch_optional(&mut *tx)
.await?;
let Some(gift) = gift else { return Ok(None) };
if gift.redeemed_at.is_some() {
return Err(ApiError::conflict("promo_used", "Ezt a kódot már felhasználták."));
}
let package = gift.package()?;
let note = format!("ajándékkód {}", display(code));
let order = packages::grant(tx, user_id, package, Source::Gift, None, Some(&note)).await?;
sqlx::query("UPDATE gifts SET redeemed_by = $2, redeemed_at = now(), order_id = $3 WHERE id = $1")
.bind(gift.id)
.bind(user_id)
.bind(order)
.execute(&mut *tx)
.await?;
let added = package.contents().into_iter().filter(|&(_, n)| n > 0).collect();
Ok(Some(Redeemed { package, added, from_name: gift.from_name }))
}
+5
View File
@@ -14,6 +14,7 @@ mod celebrities;
mod charts;
mod errors;
mod forecasts;
mod gifts;
mod invitations;
mod invoices_user;
mod jobs;
@@ -117,6 +118,10 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/tarot/readings/{id}", get(tarot::get_one))
// sharing
.route("/v1/promo-codes/redeem", post(promo::redeem))
.route("/v1/gifts", get(gifts::list))
.route("/v1/gifts/checkout", post(gifts::checkout))
.route("/v1/gifts/{id}/card.pdf", get(gifts::card))
.route("/v1/gifts/{id}/send", post(gifts::send_again))
.route("/v1/admin/promo-codes", get(promo::list).post(promo::create))
.route("/v1/admin/promo-codes/{id}/revoke", post(promo::revoke))
.route("/v1/shares", get(shares::list).post(shares::create))
+82 -25
View File
@@ -96,7 +96,7 @@ pub fn admins_only(config: &crate::config::Config) -> bool {
}
/// Stripe, if this user may pay through it.
fn stripe_for<'a>(state: &'a AppState, auth: &AuthUser) -> Result<&'a StripeConfig, ApiError> {
pub(super) fn stripe_for<'a>(state: &'a AppState, auth: &AuthUser) -> Result<&'a StripeConfig, ApiError> {
let config = state.config.stripe.as_ref().ok_or(ApiError::NotFound("payment method"))?;
if admins_only(&state.config) && !auth.user.has_role(Role::Admin) {
return Err(ApiError::Forbidden("purchases are being tested; they open soon".into()));
@@ -131,8 +131,25 @@ pub async fn checkout(
) -> ApiResult<Json<Value>> {
let config = stripe_for(&state, &auth)?;
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
let back = format!("{}{}", state.config.public_base_url, return_path(req.return_path.as_deref()));
let (checkout_name, checkout_description) = package.checkout_text();
let url = start_checkout(&state, config, &auth, package, req.return_path.as_deref(), None).await?;
Ok(Json(json!({ "url": url })))
}
/// Creates the Stripe Checkout session of a package (for the buyer, or a
/// `gift` for someone else) and records it; returns the payment page.
pub(super) async fn start_checkout(
state: &AppState,
config: &StripeConfig,
auth: &AuthUser,
package: &packages::Package,
return_path: Option<&str>,
gift: Option<Uuid>,
) -> Result<String, ApiError> {
let back = format!("{}{}", state.config.public_base_url, self::return_path(return_path));
let (mut checkout_name, checkout_description) = package.checkout_text();
if gift.is_some() {
checkout_name.push_str(" (ajándék)");
}
let field = |k: &str, v: &str| (k.to_string(), v.to_string());
let mut form = vec![
field("mode", "payment"),
@@ -157,6 +174,9 @@ pub async fn checkout(
field("success_url", &format!("{back}?fizetes={{CHECKOUT_SESSION_ID}}")),
field("cancel_url", &format!("{back}?fizetes=megszakitva")),
];
if let Some(gift) = gift {
form.push(field("metadata[gift_id]", &gift.to_string()));
}
if state.config.terms_consent {
// Every purchase accepts the terms and asks for immediate delivery,
// giving up the 14-day withdrawal right (45/2014. Korm. rendelet 29. §).
@@ -173,30 +193,33 @@ pub async fn checkout(
}
let session = state.stripe.create_session(config, &form).await?;
let url = session.url.ok_or_else(|| ApiError::Internal(format!("checkout session {} has no url", session.id)))?;
sqlx::query("INSERT INTO stripe_checkouts (id, user_id, package, price_huf, live) VALUES ($1, $2, $3, $4, $5)")
.bind(&session.id)
.bind(auth.id())
.bind(package.id)
.bind(package.price_huf as i32)
.bind(!config.test_mode())
.execute(&state.db)
.await?;
tracing::info!(user = %auth.id(), package = package.id, session = %session.id, "checkout started");
Ok(Json(json!({ "url": url })))
sqlx::query(
"INSERT INTO stripe_checkouts (id, user_id, package, price_huf, live, gift_id) VALUES ($1, $2, $3, $4, $5, $6)",
)
.bind(&session.id)
.bind(auth.id())
.bind(package.id)
.bind(package.price_huf as i32)
.bind(!config.test_mode())
.bind(gift)
.execute(&state.db)
.await?;
tracing::info!(user = %auth.id(), package = package.id, session = %session.id, gift = gift.is_some(), "checkout started");
Ok(url)
}
/// Records a paid session (what was charged, the buyer's billing details),
/// grants its package and queues the invoice, once. `false`: not our session.
async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, ApiError> {
let mut tx = state.db.begin().await?;
type Checkout = (Option<Uuid>, String, i32, Option<OffsetDateTime>);
type Checkout = (Option<Uuid>, String, i32, Option<OffsetDateTime>, Option<Uuid>);
let row: Option<Checkout> = sqlx::query_as(
"SELECT user_id, package, price_huf, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE",
"SELECT user_id, package, price_huf, completed_at, gift_id FROM stripe_checkouts WHERE id = $1 FOR UPDATE",
)
.bind(&session.id)
.fetch_optional(&mut *tx)
.await?;
let Some((user_id, package_id, price_huf, completed_at)) = row else { return Ok(false) };
let Some((user_id, package_id, price_huf, completed_at, gift_id)) = row else { return Ok(false) };
if completed_at.is_some() {
return Ok(true);
}
@@ -206,13 +229,20 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, A
}
let package =
packages::find(&package_id).ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?;
// A deleted account still gets its invoice, but no package.
let order = match user_id {
Some(user_id) => {
// A gift gets its code (and goes to its recipient); the package is
// granted when the code is redeemed. A deleted account still gets its
// invoice, but no package.
let mut gift = None;
let order = match (gift_id, user_id) {
(Some(gift_id), _) => {
gift = Some(super::gifts::fulfil(&mut tx, state, gift_id).await?);
None
}
(None, Some(user_id)) => {
let note = format!("Stripe {}", session.id);
Some(packages::grant(&mut tx, user_id, package, Source::Stripe, Some(user_id), Some(&note)).await?)
}
None => None,
(None, None) => None,
};
if state.config.terms_consent && !session.terms_accepted() {
tracing::warn!(session = %session.id, "paid without the terms consent");
@@ -233,7 +263,8 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result<bool, A
.await?;
// The confirmation confirms the withdrawal waiver: only when it was given.
if session.terms_accepted() {
confirm_by_email(&mut tx, state, session, user_id, package, amount_huf.unwrap_or(i64::from(price_huf))).await?;
let amount = amount_huf.unwrap_or(i64::from(price_huf));
confirm_by_email(&mut tx, state, session, user_id, package, amount, gift.as_ref()).await?;
}
let buyer = invoices::Buyer::from_stripe(session.customer_details.as_ref().unwrap_or(&Value::Null), None);
let (item, comment) = package.invoice_item();
@@ -253,6 +284,7 @@ async fn confirm_by_email(
user_id: Option<Uuid>,
package: &packages::Package,
amount_huf: i64,
gift: Option<&super::gifts::Paid>,
) -> Result<(), ApiError> {
let account: Option<(String, String, Option<String>)> = match user_id {
Some(id) => {
@@ -272,7 +304,7 @@ async fn confirm_by_email(
},
};
let base = &state.config.public_base_url;
let payload = json!({
let mut payload = json!({
"url": format!("{base}/csomagok"),
"display_name": name,
"package_name": package.name,
@@ -282,6 +314,18 @@ async fn confirm_by_email(
"terms_url": format!("{base}/aszf"),
"invoices_url": format!("{base}/szamlak"),
});
if let Some(gift) = gift {
payload["url"] = json!(format!("{base}/ajandekaim"));
payload["gift"] = json!({
"promo_code": gift.code,
"recipient_name": gift.recipient_name,
"recipient_email": gift.recipient_email,
});
// Handed over by the buyer: the card comes with the confirmation.
if gift.recipient_email.is_none() {
payload["gift_card"] = gift.card.clone();
}
}
super::auth::queue_email_to(tx, user_id, &to, "purchase_confirmation", &locale, payload).await
}
@@ -305,13 +349,13 @@ pub async fn checkout_status(
auth: AuthUser,
WithRejection(Path(id), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<Json<Value>> {
let row: Option<(String, Option<OffsetDateTime>)> =
sqlx::query_as("SELECT package, completed_at FROM stripe_checkouts WHERE id = $1 AND user_id = $2")
let row: Option<(String, Option<OffsetDateTime>, Option<Uuid>)> =
sqlx::query_as("SELECT package, completed_at, gift_id FROM stripe_checkouts WHERE id = $1 AND user_id = $2")
.bind(&id)
.bind(auth.id())
.fetch_optional(&state.db)
.await?;
let (package_id, completed_at) = row.ok_or(ApiError::NotFound("payment"))?;
let (package_id, completed_at, gift_id) = row.ok_or(ApiError::NotFound("payment"))?;
let mut status = if completed_at.is_some() { "paid" } else { "pending" };
if let (None, Some(config)) = (completed_at, &state.config.stripe) {
let session = state.stripe.get_session(config, &id).await?;
@@ -322,10 +366,23 @@ pub async fn checkout_status(
status = "expired";
}
}
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")
.bind(id)
.fetch_optional(&state.db)
.await?
.unwrap_or_default();
Some(json!({ "id": id, "recipient_name": name, "recipient_email": to }))
}
None => None,
};
Ok(Json(json!({
"status": status,
"package": package_id,
"name": packages::find(&package_id).map(|p| p.name),
"gift": gift,
})))
}
+40 -9
View File
@@ -3,7 +3,8 @@
//! user's units up to the package's amounts (used ones come back, more than
//! that stays), recorded as an order with source `promo`. Unused codes can be
//! withdrawn. Failed redemptions are rate limited per user, so codes cannot
//! be guessed.
//! be guessed. Gift codes (packages someone paid for, see `gifts`) are
//! redeemed here too, but they are not promo codes.
use axum::Json;
use axum::extract::{Path, Query, State};
@@ -23,7 +24,7 @@ use crate::packages;
use crate::views::{rfc3339, rfc3339_opt};
/// Characters of a code (12 × ~5 bits: not guessable within the rate limit).
const CODE_LEN: usize = 12;
pub(super) const CODE_LEN: usize = 12;
const MAX_BATCH: i64 = 500;
/// `ABCD-EFGH-JKLM`: the stored code in groups of four.
@@ -46,10 +47,12 @@ pub(super) async fn new_code(
) -> Result<String, sqlx::Error> {
loop {
let code = db::random_code(CODE_LEN);
// A clash is practically impossible; another code is drawn if it happens.
// A clash (with another code or a gift's) is practically impossible;
// another code is drawn if it happens.
let inserted = sqlx::query(
"INSERT INTO promo_codes (id, code, package, note, created_by, invitation_id) \
VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (code) DO NOTHING",
SELECT $1, $2, $3, $4, $5, $6 WHERE NOT EXISTS (SELECT 1 FROM gifts WHERE code = $2) \
ON CONFLICT (code) DO NOTHING",
)
.bind(Uuid::now_v7())
.bind(&code)
@@ -225,7 +228,8 @@ pub struct Redeem {
code: String,
}
/// Redeems a code: the user gets its package. One use per code.
/// Redeems a code: the user gets its package. One use per code. A gift code
/// adds the whole package.
pub async fn redeem(
State(state): St,
auth: AuthUser,
@@ -242,6 +246,7 @@ pub async fn redeem(
.await?;
let (id, package_id) = match found {
Some((id, package, None, None)) => (id, package),
None => return redeem_gift(&state, &auth, &key, tx, &code).await,
Some((_, _, Some(_), _)) => {
state.login_limiter.failed(&key);
return Err(ApiError::conflict("promo_used", "Ezt a kódot már felhasználták."));
@@ -250,10 +255,6 @@ pub async fn redeem(
state.login_limiter.failed(&key);
return Err(ApiError::conflict("promo_revoked", "Ez a kód már nem érvényes."));
}
None => {
state.login_limiter.failed(&key);
return Err(ApiError::conflict("promo_unknown", "Nincs ilyen kód. Ellenőrizd, hogy pontosan írtad-e be."));
}
};
let package = packages::find(&package_id).ok_or(ApiError::NotFound("package"))?;
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?;
@@ -275,3 +276,33 @@ pub async fn redeem(
body["added"] = added.iter().map(|(unit, n)| (unit.as_str().to_string(), json!(n))).collect();
Ok(Json(body))
}
/// Redeems a gift code, if `code` is one (see `redeem`).
async fn redeem_gift(
state: &crate::AppState,
auth: &AuthUser,
key: &str,
mut tx: sqlx::Transaction<'_, sqlx::Postgres>,
code: &str,
) -> ApiResult<Json<Value>> {
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?;
let redeemed = match super::gifts::redeem(&mut tx, code, auth.id()).await {
Ok(Some(redeemed)) => redeemed,
Ok(None) => {
state.login_limiter.failed(key);
return Err(ApiError::conflict("promo_unknown", "Nincs ilyen kód. Ellenőrizd, hogy pontosan írtad-e be."));
}
Err(e) => {
state.login_limiter.failed(key);
return Err(e);
}
};
tx.commit().await?;
state.login_limiter.succeeded(key);
tracing::info!(user = %auth.id(), package = redeemed.package.id, "gift code redeemed");
let mut body = holdings(state, auth).await?;
body["package"] = json!({ "id": redeemed.package.id, "name": redeemed.package.name });
body["added"] = redeemed.added.iter().map(|(unit, n)| (unit.as_str().to_string(), json!(n))).collect();
body["gift"] = json!({ "from_name": redeemed.from_name });
Ok(Json(body))
}
+254
View File
@@ -3283,3 +3283,257 @@ async fn the_sky_is_shared_and_kept(pool: PgPool) {
}
assert_eq!(calls() - before, 2);
}
// --- gifts -----------------------------------------------------------------------------------
async fn natal_left(app: &TestApp, token: &str) -> i64 {
app.get("/v1/me", Some(token)).await.body["analyses_left"]["natal"].as_i64().unwrap()
}
async fn gift_card_pdf(app: &TestApp, token: &str, id: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
let req = Request::builder()
.uri(format!("/v1/gifts/{id}/card.pdf"))
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())
.unwrap();
let resp = app.router.clone().oneshot(req).await.unwrap();
let (status, headers) = (resp.status(), resp.headers().clone());
(status, headers, resp.into_body().collect().await.unwrap().to_bytes().to_vec())
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPool) {
let app = TestApp::with_config(pool, |c| with_stripe(c, "sk_live_fake")).await;
let anna = app.register("anna@example.com", "Anna").await;
let checkout = |body: Value| app.post("/v1/gifts/checkout", Some(&anna), body);
// Only the main packages, for someone with a name, the address typed twice, no links.
let r = checkout(json!({"package": "addon_tarot", "recipient_name": "Bea"})).await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
let r = checkout(json!({"package": "couple", "recipient_name": " "})).await;
assert_eq!(
(r.status, r.body["error"]["message"].as_str()),
(StatusCode::BAD_REQUEST, Some("Add meg, kinek szól az ajándék."))
);
let r = checkout(json!({"package": "couple", "recipient_name": "Bea", "recipient_email": "bea@example.com", "recipient_email_confirm": "bia@example.com"})).await;
assert_eq!(
(r.status, r.body["error"]["message"].as_str()),
(StatusCode::BAD_REQUEST, Some("A két e-mail-cím nem egyezik."))
);
let r =
checkout(json!({"package": "couple", "recipient_name": "Bea", "message": "Nézd: https://evil.example"})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
let r = checkout(json!({"package": "couple", "recipient_name": "Bea", "from_name": "x".repeat(61)})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
assert_eq!(sqlx::query_scalar::<_, i64>("SELECT count(*) FROM gifts").fetch_one(&app.pool).await.unwrap(), 0);
let r = checkout(json!({"package": "couple", "recipient_name": " Bea ", "recipient_email": " Bea@Example.com", "recipient_email_confirm": "bea@example.com ",
"from_name": "Anna", "message": "Boldog születésnapot!\nÖlel: Anna"}))
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let gift_id = r.body["id"].as_str().unwrap().to_string();
let session = r.body["url"].as_str().unwrap().rsplit('/').next().unwrap().to_string();
assert_eq!(
stripe_form(&session, "line_items[0][price_data][product_data][name]").as_deref(),
Some("Sorsfonalak – Páros (ajándék)")
);
assert_eq!(stripe_form(&session, "metadata[gift_id]").as_deref(), Some(gift_id.as_str()));
assert_eq!(
stripe_form(&session, "success_url").as_deref(),
Some("https://sorsfonalak.test/ajandekaim?fizetes={CHECKOUT_SESSION_ID}")
);
// Not paid: not listed, nothing sent.
assert_eq!(app.get("/v1/gifts", Some(&anna)).await.body["gifts"], json!([]));
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 0);
let event = json!({"id": "evt_g", "type": "checkout.session.completed",
"data": {"object": {"id": session, "payment_status": "paid", "status": "complete",
"consent": {"terms_of_service": "accepted"},
"amount_total": 600000, "currency": "huf", "payment_intent": "pi_g",
"customer_details": {"name": "Kovács Anna", "email": "anna@example.com",
"address": {"line1": "Fő utca 1.", "city": "Szeged", "postal_code": "6720", "country": "HU"},
"tax_ids": []}}}});
let body = event.to_string();
let signature =
crate::stripe::sign("whsec_fake", body.as_bytes(), time::OffsetDateTime::now_utc().unix_timestamp());
for _ in 0..2 {
let r = app
.call_with(
"POST",
"/v1/payments/stripe/webhook",
None,
Some(event.clone()),
&[("stripe-signature", &signature)],
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
// The buyer gets no package, the recipient one e-mail with the card, the
// buyer a confirmation that says it was a gift.
assert!(stripe_orders(&app.pool, "anna@example.com").await.is_empty());
assert_eq!(natal_left(&app, &anna).await, 0);
let (mail,): (Value,) = sqlx::query_as(
"SELECT payload FROM email_outbox WHERE to_email = 'bea@example.com' AND template = 'gift_package'",
)
.fetch_one(&app.pool)
.await
.unwrap();
let code = mail["promo_code"].as_str().unwrap().to_string();
assert_eq!(mail["url"], format!("https://sorsfonalak.test/bevaltas?kod={code}"));
assert_eq!((&mail["from_name"], &mail["message"]), (&json!("Anna"), &json!("Boldog születésnapot!\nÖlel: Anna")));
assert_eq!(mail["gift_card"]["contents"][0], "2 részletes képletelemzés");
assert!(email_templates::render("gift_package", "hu", &mail).unwrap().text.contains(&code));
let (confirmation,): (Value,) = sqlx::query_as(
"SELECT payload FROM email_outbox WHERE to_email = 'anna@example.com' AND template = 'purchase_confirmation'",
)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(
confirmation["gift"],
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com"})
);
assert!(confirmation["gift_card"].is_null(), "the recipient has the card");
assert_eq!(confirmation["url"], "https://sorsfonalak.test/ajandekaim");
email_templates::render("purchase_confirmation", "hu", &confirmation).unwrap();
// The invoice is the buyer's, as for any purchase.
let invoices: i64 = sqlx::query_scalar("SELECT count(*) FROM invoices WHERE checkout_id = $1")
.bind(&session)
.fetch_one(&app.pool)
.await
.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"}));
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
assert_eq!((&gift["code"], &gift["status"], &gift["sendings"]), (&json!(code), &json!("open"), &json!(1)));
assert_eq!((&gift["package"]["name"], &gift["can_send"]), (&json!("Páros"), &json!(true)));
assert_eq!(
(&gift["recipient_name"], &mail["recipient_name"], &mail["gift_card"]["recipient_name"]),
(&json!("Bea"), &json!("Bea"), &json!("Bea"))
);
// A gift code is not a promo code: admins cannot withdraw it.
let promo: i64 = sqlx::query_scalar("SELECT count(*) FROM promo_codes").fetch_one(&app.pool).await.unwrap();
assert_eq!(promo, 0);
// The card, for the buyer only.
let (status, headers, pdf) = gift_card_pdf(&app, &anna, &gift_id).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(headers["content-type"], "application/pdf");
assert_eq!(headers["content-disposition"], format!("attachment; filename=\"sorsfonalak-ajandek-{code}.pdf\""));
assert!(pdf.starts_with(b"%PDF-"));
let bela = app.register("bela@example.com", "Béla").await;
assert_eq!(gift_card_pdf(&app, &bela, &gift_id).await.0, StatusCode::NOT_FOUND);
assert_eq!(app.get("/v1/gifts", Some(&bela)).await.body["gifts"], json!([]));
// Sending again: not at once, then to a corrected address.
let send_url = format!("/v1/gifts/{gift_id}/send");
let send =
|to: &str| app.post(&send_url, Some(&anna), json!({"recipient_email": to, "recipient_email_confirm": to}));
let r = send("cili@example.com").await;
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("gift_send_wait")));
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)));
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
let r = app
.post(
&format!("/v1/gifts/{gift_id}/send"),
Some(&bela),
json!({"recipient_email": "x@example.com", "recipient_email_confirm": "x@example.com"}),
)
.await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
// Redeemed by someone who has the package's units already: the whole
// package is added (a promo code would only fill up to it).
let admin = app.register("admin@example.com", "Admin").await;
let r = app.post("/v1/admin/promo-codes", Some(&admin), json!({"package": "couple", "count": 1})).await;
let promo = r.body["codes"][0].as_str().unwrap().to_string();
assert_eq!(app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": promo})).await.status, StatusCode::OK);
assert_eq!(natal_left(&app, &bela).await, 2);
let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": code.to_lowercase()})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!((&r.body["gift"]["from_name"], &r.body["added"]["natal"]), (&json!("Anna"), &json!(2)));
assert_eq!(natal_left(&app, &bela).await, 4);
let source: (String, i32) = sqlx::query_as(
"SELECT o.source, o.price_huf FROM package_orders o JOIN users u ON u.id = o.user_id \
WHERE u.email = 'bela@example.com' AND o.source = 'gift'",
)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(source, ("gift".to_string(), 0));
let r = app.get("/v1/gifts", Some(&anna)).await;
assert_eq!((&r.body["gifts"][0]["status"], &r.body["gifts"][0]["can_send"]), (&json!("redeemed"), &json!(false)));
sqlx::query("UPDATE gifts SET last_sent_at = now() - interval '11 minutes'").execute(&app.pool).await.unwrap();
assert_eq!(send("dora@example.com").await.body["error"]["code"], "gift_redeemed");
// Used once, like any code.
let r = app.post("/v1/promo-codes/redeem", Some(&admin), json!({"code": code})).await;
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("promo_used")));
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_gift_handed_over_by_the_buyer(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 r = app
.post(
"/v1/gifts/checkout",
Some(&anna),
json!({"package": "family", "recipient_name": "Bea", "from_name": "Anna"}),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert!(r.body["url"].is_null());
let id = r.body["id"].as_str().unwrap().to_string();
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
assert_eq!(
(&gift["recipient_email"], &gift["sendings"], &gift["can_send"]),
(&Value::Null, &json!(0), &json!(true))
);
let sent: i64 = sqlx::query_scalar("SELECT count(*) FROM email_outbox WHERE template = 'gift_package'")
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(sent, 0);
assert!(gift_card_pdf(&app, &anna, &id).await.2.starts_with(b"%PDF-"));
// Sent by e-mail later after all.
let r = app
.post(
&format!("/v1/gifts/{id}/send"),
Some(&anna),
json!({"recipient_email": "bea@example.com", "recipient_email_confirm": "bea@example.hu"}),
)
.await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
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, &r.body["sendings"]), (StatusCode::OK, &json!(1)));
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 1);
// The buyer's account goes: the gift stays redeemable, without its personal parts.
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "DELETE"}))).await;
assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body);
let left: (Option<uuid::Uuid>, Option<String>, Option<String>, Option<String>) =
sqlx::query_as("SELECT buyer_id, recipient_name, recipient_email, from_name FROM gifts")
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!(left, (None, None, None, None));
let code: String = sqlx::query_scalar("SELECT code FROM gifts").fetch_one(&app.pool).await.unwrap();
let bea = app.register("bea@example.com", "Bea").await;
let r = app.post("/v1/promo-codes/redeem", Some(&bea), json!({"code": code})).await;
assert_eq!((r.status, &r.body["added"]["natal"]), (StatusCode::OK, &json!(6)));
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

@@ -0,0 +1,251 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useId, useState } from "react";
import { huf } from "@/components/PackageCards";
import { api, errorText } from "@/lib/api";
import { contents } from "@/lib/packageContents";
import type { Package, PayMethod } from "@/lib/types";
const MAX_MESSAGE = 300;
const MAX_NAME = 60;
const looksLikeEmail = (s: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim());
const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();
/**
* 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
* hands it over), and a message. Then Stripe's payment page, back to "My
* gifts".
*/
export function GiftForm({
packages,
initial,
defaultFrom,
canPay,
termsConsent,
}: {
packages: Package[];
initial?: string;
defaultFrom: string;
canPay: PayMethod | null;
termsConsent: boolean;
}) {
const router = useRouter();
const id = useId();
const start = packages.find((p) => p.id === initial) ?? packages.find((p) => p.id === "couple") ?? packages[0];
const [pkg, setPkg] = useState(start?.id ?? "");
const [name, setName] = useState("");
const [byEmail, setByEmail] = useState(true);
const [email, setEmail] = useState("");
const [confirm, setConfirm] = useState("");
const [from, setFrom] = useState(defaultFrom.slice(0, MAX_NAME));
const [message, setMessage] = useState("");
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).
useEffect(() => {
const reset = (e: PageTransitionEvent) => {
if (e.persisted) setBusy(false);
};
window.addEventListener("pageshow", reset);
return () => window.removeEventListener("pageshow", reset);
}, []);
const chosen = packages.find((p) => p.id === pkg);
const mismatch = byEmail && confirm.trim() !== "" && !same(email, confirm);
const emailOk = !byEmail || (looksLikeEmail(email) && same(email, confirm));
const stripe = canPay === "stripe" || canPay === "stripe_test";
async function submit(e: React.FormEvent) {
e.preventDefault();
if (!chosen || !emailOk || !name.trim()) return;
setBusy(true);
setError(null);
try {
const r = await api<{ id: string; url: string | null }>("/gifts/checkout", {
body: {
package: chosen.id,
recipient_name: name.trim(),
recipient_email: byEmail ? email.trim() : null,
recipient_email_confirm: byEmail ? confirm.trim() : null,
from_name: from.trim() || null,
message: message.trim() || null,
},
});
if (r.url) {
window.location.assign(r.url);
return;
}
router.push("/ajandekaim");
} catch (err) {
setError(errorText(err));
setBusy(false);
}
}
return (
<form className="card gift-form" onSubmit={submit}>
<fieldset className="gift-set">
<legend className="label">Melyik csomagot adod?</legend>
<div className="gift-packages">
{packages.map((p) => (
<label key={p.id} className={p.id === pkg ? "gift-option is-chosen" : "gift-option"}>
<input type="radio" name={`${id}-pkg`} value={p.id} checked={p.id === pkg} onChange={() => setPkg(p.id)} />
<span className="gift-option-head">
<strong>{p.name}</strong>
<span className="num">{huf(p.price_huf)}</span>
</span>
<span className="hint">{contents(p).join(" · ")}</span>
</label>
))}
</div>
</fieldset>
<div className="grid-2">
<div className="field">
<label htmlFor={`${id}-name`}>Kinek szól?</label>
<input
id={`${id}-name`}
className="inp"
value={name}
maxLength={MAX_NAME}
onChange={(e) => setName(e.target.value)}
placeholder="Például: Bea"
aria-describedby={`${id}-name-hint`}
required
/>
<span id={`${id}-name-hint`} className="hint">
Az utalványon: „{name.trim() || "Bea"} részére”
{byEmail ? `, a levélben: „Szia ${name.trim() || "Bea"}!”` : ""}.
</span>
</div>
<div className="field">
<label htmlFor={`${id}-from`}>Kitől? (a te neved)</label>
<input
id={`${id}-from`}
className="inp"
value={from}
maxLength={MAX_NAME}
onChange={(e) => setFrom(e.target.value)}
placeholder="Például: Anna"
/>
</div>
</div>
<fieldset className="gift-set">
<legend className="label">Hogyan kapja meg?</legend>
<div className="gift-ways">
<label className={byEmail ? "gift-option is-chosen" : "gift-option"}>
<input type="radio" name={`${id}-way`} checked={byEmail} onChange={() => setByEmail(true)} />
<strong>E-mailben küldjük el neki</strong>
<span className="hint">Fizetés után azonnal megkapja a kódot, mellé az utalványt PDF-ben.</span>
</label>
<label className={!byEmail ? "gift-option is-chosen" : "gift-option"}>
<input type="radio" name={`${id}-way`} checked={!byEmail} onChange={() => setByEmail(false)} />
<strong>Én adom át</strong>
<span className="hint">
Letöltöd az utalványt PDF-ben: kinyomtathatod, vagy elküldheted te magad. Később innen is kérheted, hogy
e-mailben küldjük el.
</span>
</label>
</div>
{byEmail && (
<div className="grid-2">
<div className="field">
<label htmlFor={`${id}-email`}>A címzett e-mail-címe</label>
<input
id={`${id}-email`}
className="inp"
type="email"
autoComplete="off"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="field">
<label htmlFor={`${id}-confirm`}>Még egyszer, ellenőrzésképp</label>
<input
id={`${id}-confirm`}
className="inp"
type="email"
autoComplete="off"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
aria-invalid={mismatch || undefined}
aria-describedby={`${id}-confirm-msg`}
required
/>
<span id={`${id}-confirm-msg`} className={mismatch ? "msg msg-error" : "hint"} aria-live="polite">
{mismatch ? "A két cím nem egyezik." : "Hogy biztosan jó címre menjen."}
</span>
</div>
</div>
)}
</fieldset>
<div className="field">
<label htmlFor={`${id}-message`}>Személyes üzenet (nem kötelező)</label>
<textarea
id={`${id}-message`}
className="inp"
value={message}
maxLength={MAX_MESSAGE}
onChange={(e) => setMessage(e.target.value)}
placeholder="Boldog születésnapot! Nézd meg, mit mesélnek rólad a csillagok."
aria-describedby={`${id}-message-hint`}
/>
<span id={`${id}-message-hint`} className="hint">
Rajta lesz az utalványon és a levélben. Link nem lehet benne. {message.length}/{MAX_MESSAGE}
</span>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="gift-submit">
{chosen && (
<p className="gift-total">
<span className="muted">
„{chosen.name}” csomag ajándékba{name.trim() ? `, ${name.trim()} részére` : ""}
</span>
<strong className="num">{huf(chosen.price_huf)}</strong>
</p>
)}
{canPay ? (
<button type="submit" className="btn btn-primary" disabled={busy || !chosen || !emailOk || !name.trim()}>
{busy ? (stripe ? "Átirányítás…" : "Fizetés…") : stripe ? "Tovább a fizetéshez" : "Megveszem ajándékba"}
</button>
) : (
<button type="button" className="btn" disabled>
Hamarosan
</button>
)}
</div>
{canPay === "mock" && <p className="hint">Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.</p>}
{stripe && (
<p className="hint">
<span aria-hidden="true">🔒</span> A fizetés a Stripe biztonságos oldalán történik. A számlát te kapod.
{termsConsent && (
<>
{" "}
Az ajándékkód a fizetés után azonnal elkészül, ezért a fizetésnél kéred a teljesítés megkezdését, és ezzel
lemondasz a 14 napos elállási jogról. <Link href="/aszf">ÁSZF</Link>
</>
)}
</p>
)}
{canPay === "stripe_test" && (
<p className="hint">
Stripe tesztmód (csak adminoknak látszik): kártyaszám 4242 4242 4242 4242, bármilyen jövőbeli lejárat és CVC.
</p>
)}
</form>
);
}
@@ -0,0 +1,75 @@
import type { Metadata } from "next";
import Link from "next/link";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import type { Gift, Package, PublicConfig } from "@/lib/types";
import { GiftForm } from "./GiftForm";
export const metadata: Metadata = { title: "Ajándék csomag", robots: { index: false } };
type Props = { searchParams: Promise<{ csomag?: string }> };
/** Buying a package as a gift; `?csomag=` picks the package (links on the package cards). */
export default async function GiftPage({ searchParams }: Props) {
const { csomag } = await searchParams;
const me = await requireMe(csomag ? `/ajandek?csomag=${encodeURIComponent(csomag)}` : "/ajandek");
const [catalog, config, mine] = await Promise.all([
backendGet<{ packages: Package[] }>("/v1/packages"),
backendGet<PublicConfig>("/v1/config"),
backendGet<{ gifts: Gift[] }>("/v1/gifts"),
]);
const packages = (catalog?.packages ?? []).filter((p) => p.tier === "main");
const given = mine?.gifts.length ?? 0;
return (
<main className="page" style={{ maxWidth: 1080 }}>
<div className="page-head">
<span className="eyebrow">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: ajándékba annak, akit szeretsz. Ő egy
ajándékkódot kap egy nyomtatható utalvánnyal, és a saját fiókjában váltja be.
</p>
{given > 0 && (
<p className="hint">
<Link href="/ajandekaim">Korábbi ajándékaim ({given}) →</Link>
</p>
)}
</div>
<div className="gift-layout">
<GiftForm
packages={packages}
initial={csomag}
defaultFrom={me.user.display_name ?? ""}
canPay={payMethod(config, me)}
termsConsent={config?.terms_consent === true}
/>
<aside className="gift-aside">
<figure className="gift-sample">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/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"
/>
<figcaption className="hint">Így néz ki az utalvány (A4-es PDF, nyomtatható)</figcaption>
</figure>
<section className="card gift-how" aria-labelledby="gift-how-title">
<h2 id="gift-how-title">Hogyan működik?</h2>
<ol>
<li>Kiválasztod a csomagot, és megírod, kinek szól.</li>
<li>Fizetés után elkészül az ajándékkód és az utalvány.</li>
<li>E-mailben elküldjük neki, vagy letöltöd a PDF-et, és te adod át.</li>
<li>Belép vagy regisztrál, beváltja a kódot, és a csomag az övé.</li>
</ol>
<p className="hint">A kód nem jár le, és egyszer váltható be. A számlát te kapod.</p>
</section>
</aside>
</div>
</main>
);
}
@@ -0,0 +1,174 @@
"use client";
import { useId, useState } from "react";
import { api, errorText } from "@/lib/api";
import type { Gift } from "@/lib/types";
const day = (iso: string) =>
new Date(iso).toLocaleDateString("hu-HU", { timeZone: "Europe/Budapest", year: "numeric", month: "long", day: "numeric" });
const time = (iso: string) => new Date(iso).toLocaleTimeString("hu-HU", { timeZone: "Europe/Budapest", hour: "2-digit", minute: "2-digit" });
/** The user's gifts: code, state, the card to download, and sending it by e-mail. */
export function GiftList({ gifts: initial }: { gifts: Gift[] }) {
const [gifts, setGifts] = useState(initial);
return (
<ul className="gift-list">
{gifts.map((g) => (
<GiftItem key={g.id} gift={g} onChange={(next) => setGifts((all) => all.map((x) => (x.id === next.id ? next : x)))} />
))}
</ul>
);
}
function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void }) {
const id = useId();
const [sending, setSending] = useState(false);
const [email, setEmail] = useState("");
const [confirm, setConfirm] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [sent, setSent] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const open = gift.status === "open";
const mismatch = confirm.trim() !== "" && email.trim().toLowerCase() !== confirm.trim().toLowerCase();
async function send(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const next = await api<Gift>(`/gifts/${gift.id}/send`, {
body: { recipient_email: email.trim(), recipient_email_confirm: confirm.trim() },
});
onChange(next);
setSent(next.recipient_email);
setSending(false);
setEmail("");
setConfirm("");
} catch (err) {
setError(errorText(err));
} finally {
setBusy(false);
}
}
async function copy() {
try {
await navigator.clipboard.writeText(gift.code);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
// The code stays visible and selectable.
}
}
return (
<li className="card gift-item">
<div className="gift-item-head">
<div>
<h2 className="gift-item-title">
„{gift.package.name ?? gift.package.id}” csomag
{gift.recipient_name && <span className="gift-item-for"> {gift.recipient_name} részére</span>}
</h2>
<span className="hint">Vásárolva: {day(gift.paid_at)}</span>
</div>
{gift.status === "redeemed" ? (
<span className="badge">Beváltva{gift.redeemed_at ? `: ${day(gift.redeemed_at)}` : ""}</span>
) : (
<span className="badge badge-gold">Még nincs beváltva</span>
)}
</div>
<div className="gift-code-row">
<span className="eyebrow">Ajándékkód</span>
<code className="gift-code">{gift.code}</code>
<button type="button" className="btn btn-sm btn-ghost" onClick={copy}>
{copied ? "Másolva" : "Másolás"}
</button>
</div>
<p className="gift-to">
{gift.recipient_email ? (
<>
E-mailben elküldve ide: <strong>{gift.recipient_email}</strong>
{gift.sendings > 1 ? ` (${gift.sendings}×)` : ""}
</>
) : (
"Te adod át: töltsd le az utalványt."
)}
{gift.from_name && <span className="hint"> · Kitől: {gift.from_name}</span>}
</p>
{gift.message && <blockquote className="gift-message">{gift.message}</blockquote>}
<div className="form-actions">
<a className="btn btn-primary btn-sm" href={`/api/v1/gifts/${gift.id}/card.pdf`} download>
Utalvány letöltése (PDF)
</a>
{open && gift.can_send && !sending && (
<button type="button" className="btn btn-sm" onClick={() => setSending(true)}>
{gift.recipient_email ? "Újraküldés e-mailben" : "Küldés e-mailben"}
</button>
)}
</div>
{open && !gift.can_send && gift.sendings > 0 && (
<p className="hint">E-mailben már többször elküldtük. Ha nem érkezett meg, töltsd le az utalványt, és küldd el te.</p>
)}
{sent && (
<p className="msg msg-ok" role="status">
Elküldtük ide: {sent}.
</p>
)}
{sending && (
<form className="gift-send" onSubmit={send}>
<div className="grid-2">
<div className="field">
<label htmlFor={`${id}-email`}>Kinek küldjük?</label>
<input
id={`${id}-email`}
className="inp"
type="email"
autoComplete="off"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={gift.recipient_email ?? ""}
required
/>
</div>
<div className="field">
<label htmlFor={`${id}-confirm`}>Még egyszer, ellenőrzésképp</label>
<input
id={`${id}-confirm`}
className="inp"
type="email"
autoComplete="off"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
aria-invalid={mismatch || undefined}
required
/>
{mismatch && <span className="msg msg-error">A két cím nem egyezik.</span>}
</div>
</div>
{gift.send_again_at && (
<p className="hint">Most küldtük el: {time(gift.send_again_at)} után küldheted újra.</p>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="form-actions">
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || mismatch || !email.trim()}>
{busy ? "Küldés…" : "Elküldöm"}
</button>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setSending(false)}>
Mégse
</button>
</div>
</form>
)}
</li>
);
}
@@ -0,0 +1,45 @@
import type { Metadata } from "next";
import Link from "next/link";
import { backendGet, requireMe } from "@/lib/server";
import type { Gift } from "@/lib/types";
import { GiftList } from "./GiftList";
export const metadata: Metadata = { title: "Ajándékaim", robots: { index: false } };
/** The packages the user bought as gifts: codes, cards to download, sending them by e-mail. */
export default async function MyGiftsPage() {
await requireMe("/ajandekaim");
const gifts = (await backendGet<{ gifts: Gift[] }>("/v1/gifts"))?.gifts ?? [];
return (
<main className="page" style={{ maxWidth: 900 }}>
<div className="page-head">
<span className="eyebrow">Ajándék</span>
<h1>Ajándékaim</h1>
<p className="muted">
Az ajándékba vett csomagjaid. Ha nem e-mailben adnád át, töltsd le az utalványt PDF-ben: kinyomtathatod, vagy
elküldheted te magad. Amíg nem váltották be, e-mailben is elküldhetjük, akár másik címre.
</p>
<div className="form-actions">
<Link className="btn btn-primary" href="/ajandek">
Új ajándék
</Link>
</div>
</div>
{gifts.length === 0 ? (
<section className="card">
<p className="muted">
Még nem vettél ajándékot. Egy csomagot bárkinek megvehetsz: e-mailben kapja meg, vagy te adod át egy
nyomtatható utalvánnyal. <Link href="/ajandek">Ajándékozás →</Link>
</p>
</section>
) : (
// A new gift (back from paying) or a change starts the list afresh.
<GiftList key={gifts.map((g) => `${g.id}:${g.status}:${g.sendings}`).join()} gifts={gifts} />
)}
</main>
);
}
+10 -6
View File
@@ -3,22 +3,26 @@ import type { Metadata } from "next";
import { RedeemCode } from "@/components/RedeemCode";
import { requireMe } from "@/lib/server";
export const metadata: Metadata = { title: "Promókód beváltása", robots: { index: false } };
export const metadata: Metadata = { title: "Kód beváltása", robots: { index: false } };
type Props = { searchParams: Promise<{ kod?: string }> };
/** Redeeming a promo code; `?kod=` fills it in (links in invitations). */
/** Redeeming a promo or gift code; `?kod=` fills it in (links in invitations and gift e-mails). */
export default async function RedeemPage({ searchParams }: Props) {
const { kod } = await searchParams;
await requireMe(kod ? `/bevaltas?kod=${encodeURIComponent(kod)}` : "/bevaltas");
return (
<main className="page" style={{ maxWidth: 640 }}>
<div className="page-head">
<span className="eyebrow">Promókód</span>
<h1>Promókód beváltása</h1>
<span className="eyebrow">Promókód, ajándékkód</span>
<h1>Kód beváltása</h1>
<p className="muted">
Írd be a kapott kódot. Az egyenlegedet azonnal feltöltjük a csomag szintjéig: amit már elhasználtál belőle,
visszakapod, ami ennél több van, megmarad. Egy kód egyszer váltható be.
Írd be a kapott kódot. Egy kód egyszer váltható be. Az ajándékba kapott csomag teljes egészében hozzáadódik
az egyenlegedhez.
</p>
<p className="hint">
Promókódnál az egyenlegedet a csomag szintjéig töltjük fel: amit már elhasználtál belőle, visszakapod, ami
ennél több van, megmarad.
</p>
</div>
<section className="card">
+14 -1
View File
@@ -96,7 +96,20 @@ export default async function PackagesPage() {
</p>
)}
<PackageCards packages={packages} canPay={canPay} />
<PackageCards packages={packages} canPay={canPay} giftLinks />
<section className="card gift-banner" aria-labelledby="gift-title">
<div>
<h2 id="gift-title">Ajándékba is adhatod</h2>
<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.
</p>
</div>
<Link className="btn" href="/ajandek">
Megajándékozok valakit
</Link>
</section>
<section className="field" aria-labelledby="addon-title" style={{ gap: 12 }}>
<h2 id="addon-title">Kiegészítők</h2>
+70
View File
@@ -1511,3 +1511,73 @@ span.tarot-fan-card { cursor: default; }
.sky-events li { grid-template-columns: 24px minmax(0, 1fr); }
.sky-events li .num { grid-column: 2; }
}
/* Gifts: the order form, "My gifts", the link on the package cards */
.pkg-gift {
align-self: center; display: inline-flex; align-items: center; min-height: 36px;
font-size: 14px; color: var(--gold); text-decoration: none;
}
.pkg-gift:hover { color: var(--gold-hover); text-decoration: underline; }
.gift-banner { flex-direction: row; align-items: center; justify-content: space-between; gap: 20px; border-color: rgba(217, 180, 106, 0.35); }
.gift-banner h2 { font-size: 24px; }
.gift-banner p { margin: 6px 0 0; }
.gift-banner .btn { flex: none; }
.gift-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 24px; align-items: start; }
.gift-aside { display: flex; flex-direction: column; gap: 16px; }
.gift-sample { margin: 0; display: flex; flex-direction: column; gap: 8px; align-items: center; }
.gift-sample img {
width: 100%; max-width: 320px; height: auto; border-radius: 6px;
box-shadow: 0 18px 40px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(217, 180, 106, 0.25);
}
.gift-how { gap: 10px; }
.gift-how h2 { font-size: 22px; }
.gift-how ol { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 6px; color: var(--ink-2); font-size: 14px; }
.gift-how p { margin: 0; }
.gift-form { gap: 22px; }
.gift-set { border: 0; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
.gift-set legend { padding: 0; margin-bottom: 10px; }
.gift-packages { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
.gift-ways { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.gift-option {
position: relative; display: flex; flex-direction: column; gap: 6px; padding: 14px 14px 14px 44px; cursor: pointer;
border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2);
}
.gift-option:hover { border-color: #5a6790; }
.gift-option.is-chosen { border-color: var(--gold); box-shadow: 0 0 0 1px var(--gold); }
.gift-option input { position: absolute; left: 14px; top: 16px; width: 18px; height: 18px; margin: 0; accent-color: var(--gold); }
.gift-option:has(input:focus-visible) { outline: 2px solid var(--gold); outline-offset: 2px; }
.gift-option-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; flex-wrap: wrap; }
.gift-option-head strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
.gift-packages .gift-option-head { flex-direction: column; align-items: flex-start; gap: 2px; }
.gift-packages .gift-option-head .num { color: var(--gold); }
.gift-submit { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; padding-top: 16px; border-top: 1px solid var(--line); }
.gift-total { margin: 0; display: flex; flex-direction: column; gap: 2px; }
.gift-total strong { font-family: var(--font-display); font-size: 28px; font-weight: 600; }
.gift-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 16px; }
.gift-item { gap: 14px; }
.gift-item-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; flex-wrap: wrap; }
.gift-item-title { font-size: 24px; }
.gift-item-for { font-style: italic; font-weight: 500; color: var(--gold); }
.gift-code-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.gift-code { font: 600 20px var(--font-body); letter-spacing: 1.5px; color: var(--ink); user-select: all; }
.gift-to { margin: 0; color: var(--ink-2); }
.gift-message {
margin: 0; padding: 4px 0 4px 14px; border-left: 2px solid rgba(217, 180, 106, 0.5);
font-family: var(--font-display); font-style: italic; font-size: 18px; color: var(--ink-2); white-space: pre-line;
}
.gift-send { display: flex; flex-direction: column; gap: 12px; padding-top: 14px; border-top: 1px solid var(--line); }
@media (max-width: 900px) {
.gift-layout { grid-template-columns: 1fr; }
.gift-aside { flex-direction: row; align-items: flex-start; }
.gift-sample { flex: 0 0 180px; }
.gift-how { flex: 1; }
}
@media (max-width: 640px) {
.gift-banner { flex-direction: column; align-items: stretch; }
.gift-packages, .gift-ways { grid-template-columns: 1fr; }
.gift-packages .gift-option-head { flex-direction: row; align-items: baseline; justify-content: space-between; }
.gift-aside { flex-direction: column; }
.gift-sample { flex: none; }
.gift-sample img { max-width: 240px; }
.gift-submit .btn { width: 100%; }
}
@@ -22,6 +22,7 @@ export function PackageCards({
canPay,
compact = false,
row = false,
giftLinks = false,
onBought,
}: {
packages: Package[];
@@ -32,6 +33,8 @@ export function PackageCards({
compact?: boolean;
/** One line per package (name, price, button), for tight places like the question panel. */
row?: boolean;
/** A "give it as a gift" link under the buy button of the main packages. */
giftLinks?: boolean;
/** After a stand-in purchase (default: reload the page data). */
onBought?: (p: Package) => Promise<void> | void;
}) {
@@ -153,6 +156,11 @@ export function PackageCards({
</p>
)}
{buyButton(p)}
{giftLinks && canPay && p.tier === "main" && (
<Link href={`/ajandek?csomag=${p.id}`} className="pkg-gift">
Ajándékba adom →
</Link>
)}
</article>
);
})}
@@ -41,12 +41,19 @@ export function PaymentReturn() {
(async () => {
for (let i = 0; i < POLLS && !stopped; i++) {
try {
const r = await api<{ status: string; name: string | null }>(
`/payments/checkout/${encodeURIComponent(value)}`,
);
const r = await api<{
status: string;
name: string | null;
gift: { id: string; recipient_name: string | null; recipient_email: string | null } | null;
}>(`/payments/checkout/${encodeURIComponent(value)}`);
if (stopped) return;
if (r.status === "paid") {
setNotice({ kind: "ok", text: `Köszönjük! Jóváírtuk: ${r.name ?? "a csomagod"}.` });
const text = !r.gift
? `Köszönjük! Jóváírtuk: ${r.name ?? "a csomagod"}.`
: 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 });
clean();
router.refresh();
return;
+29 -13
View File
@@ -18,18 +18,23 @@ const UNITS: Record<string, string> = {
forecast: "éves előrejelzés",
person: "személyhely",
question: "kérdés",
tarot: "kártyajóslás",
};
/** "+2 képletelemzés, +3 kérdés" */
/** "+2 képletelemzés, +3 kérdés", in the order of UNITS. */
function addedText(added: Record<string, number>): string {
const order = Object.keys(UNITS);
const rank = (unit: string) => (order.includes(unit) ? order.indexOf(unit) : order.length);
return Object.entries(added)
.sort(([a], [b]) => rank(a) - rank(b))
.map(([unit, n]) => `+${n} ${UNITS[unit] ?? unit}`)
.join(", ");
}
/**
* Redeeming a promo code. It fills the units up to the package's amounts
* (used ones come back, more than that stays).
* (used ones come back, more than that stays); a gift code adds the whole
* package.
*/
export function RedeemCode({ initial = "", compact = false }: { initial?: string; compact?: boolean }) {
const router = useRouter();
@@ -37,17 +42,21 @@ export function RedeemCode({ initial = "", compact = false }: { initial?: string
const [code, setCode] = useState(format(initial));
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [got, setGot] = useState<{ name: string; added: string } | null>(null);
const [got, setGot] = useState<{ name: string; added: string; gift: { from_name: string | null } | null } | null>(
null,
);
async function redeem(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const r = await api<{ package: { name: string }; added: Record<string, number> }>("/promo-codes/redeem", {
body: { code },
});
setGot({ name: r.package.name, added: addedText(r.added ?? {}) });
const r = await api<{
package: { name: string };
added: Record<string, number>;
gift?: { from_name: string | null };
}>("/promo-codes/redeem", { body: { code } });
setGot({ name: r.package.name, added: addedText(r.added ?? {}), gift: r.gift ?? null });
setCode("");
router.refresh();
} catch (err) {
@@ -85,12 +94,19 @@ export function RedeemCode({ initial = "", compact = false }: { initial?: string
</div>
<div id={`${id}-msg`} aria-live="polite">
{error && <p className="msg msg-error">{error}</p>}
{got && (
<p className="msg msg-ok">
Beváltva: <strong>{got.name}</strong>. Feltöltöttük az egyenlegedet: {got.added}.{" "}
<Link href="/keplet">Tovább a képletedhez</Link>
</p>
)}
{got &&
(got.gift ? (
<p className="msg msg-ok">
Beváltva: <strong>{got.name}</strong>
{got.gift.from_name ? `, ${got.gift.from_name} ajándéka` : " ajándék"}. Hozzáadtuk az egyenlegedhez:{" "}
{got.added}. <Link href="/keplet">Tovább a képletedhez</Link>
</p>
) : (
<p className="msg msg-ok">
Beváltva: <strong>{got.name}</strong>. Feltöltöttük az egyenlegedet: {got.added}.{" "}
<Link href="/keplet">Tovább a képletedhez</Link>
</p>
))}
</div>
</form>
);
@@ -8,7 +8,7 @@ import { LogoutButton } from "./LogoutButton";
/**
* The account menu under the user's name (top right): profile, invoices,
* redeeming a code, logging out. Closes on a click outside, Escape, or
* redeeming a code, giving a gift, logging out. Closes on a click outside, Escape, or
* moving to another page.
*/
export function UserMenu({ name, invoices }: { name: string; invoices: boolean }) {
@@ -39,6 +39,7 @@ export function UserMenu({ name, invoices }: { name: string; invoices: boolean }
{ href: "/profil", label: "Profil" },
...(invoices ? [{ href: "/szamlak", label: "Számláim" }] : []),
{ href: "/bevaltas", label: "Kód beváltása" },
{ href: "/ajandek", label: "Ajándékozás" },
];
return (
+23
View File
@@ -633,6 +633,29 @@ export interface PromoCode {
redeemed_by: { email: string; name: string | null } | null;
}
/** A package the user bought as a gift (`GET /v1/gifts`). */
export interface Gift {
id: string;
package: { id: string; name: string | null };
/** Whom it is for (on the card: "Bea részére"). */
recipient_name: string | null;
/** Where it was e-mailed (null: the buyer hands it over). */
recipient_email: string | null;
from_name: string | null;
message: string | null;
paid_at: string;
/** ABCD-EFGH-JKLM */
code: string;
status: "open" | "redeemed";
redeemed_at: string | null;
/** E-mails sent so far. */
sendings: number;
/** Whether it can be sent by e-mail (again). */
can_send: boolean;
/** Not before this (just sent). */
send_again_at: string | null;
}
/** A "how compatible are we?" invitation of the user (`GET /v1/invites`). */
export interface PersonInvite {
id: string;
+1
View File
@@ -10,6 +10,7 @@ publish.workspace = true
db.workspace = true
analysis-prompt.workspace = true
email-templates.workspace = true
gift-card.workspace = true
service-kit.workspace = true
anyhow.workspace = true
axum.workspace = true
+4 -1
View File
@@ -8,7 +8,7 @@ use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows.
const STATEMENTS: [(&str, &str); 7] = [
const STATEMENTS: [(&str, &str); 8] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support.
@@ -27,6 +27,9 @@ const STATEMENTS: [(&str, &str); 7] = [
),
("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
("generation_errors", "DELETE FROM generation_errors WHERE created_at < now() - interval '90 days'"),
// Gifts never paid (Stripe's payment page is long closed by then), with
// the recipient's address in them.
("gifts", "DELETE FROM gifts WHERE paid_at IS NULL AND created_at < now() - interval '7 days'"),
];
pub async fn run_once(db: &PgPool) -> Result<Vec<(&'static str, u64)>, sqlx::Error> {
+72 -7
View File
@@ -3,11 +3,14 @@
//! New rows wake the job at once (`NOTIFY email_outbox`, see migration 0002);
//! a slow poll picks up retries. Rows are claimed with `FOR UPDATE SKIP LOCKED`,
//! so several workers can run side by side. Delivery is at-least-once.
//!
//! An e-mail whose payload has a `gift_card` gets the gift card as a PDF
//! attachment, drawn here (it is not stored anywhere).
use std::time::Duration;
use lettre::message::header::{Header, HeaderName, HeaderValue};
use lettre::message::{Mailbox, MultiPart};
use lettre::message::header::{ContentType, Header, HeaderName, HeaderValue};
use lettre::message::{Attachment, Mailbox, MultiPart};
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use serde_json::Value;
use sqlx::PgPool;
@@ -60,7 +63,14 @@ impl Mailer {
Ok(Mailer::Smtp(transport))
}
async fn send(&self, id: Uuid, from: &Mailbox, to: &str, mail: &Rendered) -> Result<(), SendError> {
async fn send(
&self,
id: Uuid,
from: &Mailbox,
to: &str,
mail: &Rendered,
attachment: Option<&Pdf>,
) -> Result<(), SendError> {
let to_mailbox: Mailbox = to.parse().map_err(SendError::permanent)?;
// A Message-ID on our own domain (lettre would use the container's
// host name, which spam filters dislike); the same on every retry.
@@ -72,9 +82,15 @@ impl Mailer {
if let Some(url) = &mail.unsubscribe_post_url {
builder = builder.header(ListUnsubscribe(url.clone())).header(ListUnsubscribePost);
}
let message = builder
.multipart(MultiPart::alternative_plain_html(mail.text.clone(), mail.html.clone()))
.map_err(SendError::permanent)?;
let body = MultiPart::alternative_plain_html(mail.text.clone(), mail.html.clone());
let body = match attachment {
Some(pdf) => MultiPart::mixed().multipart(body).singlepart(
Attachment::new(pdf.filename.clone())
.body(pdf.bytes.clone(), ContentType::parse("application/pdf").expect("a content type")),
),
None => body,
};
let message = builder.multipart(body).map_err(SendError::permanent)?;
match self {
Mailer::Smtp(transport) => transport
.send(message)
@@ -94,6 +110,52 @@ impl Mailer {
}
}
/// A PDF to attach.
pub struct Pdf {
pub filename: String,
pub bytes: Vec<u8>,
}
/// The gift card of a payload's `gift_card`, if it has one. A card that
/// cannot be drawn is logged, and the e-mail goes without it (the code is in
/// the text too).
async fn gift_card(id: Uuid, payload: &Value) -> Option<Pdf> {
let card = payload.get("gift_card").filter(|c| c.is_object())?.clone();
let drawn = tokio::task::spawn_blocking(move || {
let text = |k: &str| card[k].as_str().map(str::to_owned);
let contents: Vec<String> =
card["contents"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_owned)).collect();
let (Some(package), Some(code), Some(url)) = (text("package"), text("code"), text("redeem_url")) else {
return Err("the gift card has no package, code or link".to_string());
};
let (to, from, message) = (text("recipient_name"), text("from_name"), text("message"));
let bytes = gift_card::pdf(&gift_card::Card {
package: &package,
contents: &contents,
code: &code,
redeem_url: &url,
recipient_name: to.as_deref(),
from_name: from.as_deref(),
message: message.as_deref(),
})
.map_err(|e| e.to_string())?;
let code: String = code.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
Ok(Pdf { filename: format!("sorsfonalak-ajandek-{code}.pdf"), bytes })
})
.await;
match drawn {
Ok(Ok(pdf)) => Some(pdf),
Ok(Err(e)) => {
tracing::error!(%id, error = %e, "gift card not drawn; the e-mail goes without it");
None
}
Err(e) => {
tracing::error!(%id, error = %e, "gift card not drawn; the e-mail goes without it");
None
}
}
}
/// `List-Unsubscribe: <url>`: mail clients show an unsubscribe button.
#[derive(Clone)]
struct ListUnsubscribe(String);
@@ -169,7 +231,10 @@ impl Delivery {
for row in &rows {
let attempts = row.attempts + 1;
let result = match templates::render(&row.template, &row.locale, &row.payload) {
Ok(mail) => self.mailer.send(row.id, &self.from, &row.to_email, &mail).await,
Ok(mail) => {
let pdf = gift_card(row.id, &row.payload).await;
self.mailer.send(row.id, &self.from, &row.to_email, &mail, pdf.as_ref()).await
}
Err(e) => Err(SendError::permanent(e)),
};
match result {
+20 -9
View File
@@ -17,20 +17,26 @@ use crate::telegram::{Telegram, huf};
const BATCH: i64 = 20;
/// The notice of one purchase.
fn text(item: &str, package: &str, price_huf: i32, live: bool) -> String {
fn text(item: &str, package: &str, price_huf: i32, live: bool, gift: bool) -> String {
// The invoice item without its service prefix ("Online tartalomszolgáltatás – ").
let item = item.rsplit(" – ").next().unwrap_or(item);
// The add-ons share one neutral invoice name; their id tells them apart.
let what =
if package.starts_with("addon_") && item != package { format!("{item} ({package})") } else { item.into() };
format!("🛒 Vásárlás: {what}, {}{}", huf(price_huf), if live { "" } else { " (teszt fizetés)" })
format!(
"🛒 Vásárlás: {what}{}, {}{}",
if gift { " (ajándék)" } else { "" },
huf(price_huf),
if live { "" } else { " (teszt fizetés)" }
)
}
/// Sends the notices of the purchases not notified yet; returns how many went out.
pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result<usize, sqlx::Error> {
let mut tx = db.begin().await?;
let due: Vec<(String, String, String, i32, bool)> = sqlx::query_as(
"SELECT c.id, coalesce(i.item_name, c.package), c.package, coalesce(c.amount_huf, c.price_huf), c.live \
let due: Vec<(String, String, String, i32, bool, bool)> = sqlx::query_as(
"SELECT c.id, coalesce(i.item_name, c.package), c.package, coalesce(c.amount_huf, c.price_huf), c.live, \
c.gift_id IS NOT NULL \
FROM stripe_checkouts c LEFT JOIN invoices i ON i.checkout_id = c.id \
WHERE c.completed_at IS NOT NULL AND c.notified_at IS NULL \
ORDER BY c.completed_at LIMIT $1 FOR UPDATE OF c SKIP LOCKED",
@@ -39,8 +45,8 @@ pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result<usize, sqlx::E
.fetch_all(&mut *tx)
.await?;
let mut sent = 0;
for (id, item, package, price, live) in due {
match telegram.send(&text(&item, &package, price, live)).await {
for (id, item, package, price, live, gift) in due {
match telegram.send(&text(&item, &package, price, live, gift)).await {
Ok(()) => sent += 1,
Err(e) if e.permanent => {
tracing::error!(checkout = %id, error = %e.message, "telegram refused the purchase notice; check TELEGRAM_*");
@@ -125,17 +131,22 @@ mod tests {
#[test]
fn notice_texts() {
assert_eq!(
text("Online tartalomszolgáltatás – Páros csomag", "couple", 6000, true),
text("Online tartalomszolgáltatás – Páros csomag", "couple", 6000, true, false),
"🛒 Vásárlás: Páros csomag, 6\u{a0}000\u{a0}Ft"
);
// Bought for someone else.
assert_eq!(
text("Online tartalomszolgáltatás – Család csomag", "family", 11000, true, true),
"🛒 Vásárlás: Család csomag (ajándék), 11\u{a0}000\u{a0}Ft"
);
// The add-ons share one invoice name: the id says which one it was.
assert_eq!(
text("Online tartalomszolgáltatás – kiegészítő csomag", "addon_tarot", 1000, true),
text("Online tartalomszolgáltatás – kiegészítő csomag", "addon_tarot", 1000, true, false),
"🛒 Vásárlás: kiegészítő csomag (addon_tarot), 1\u{a0}000\u{a0}Ft"
);
// No invoice yet: the id alone.
assert_eq!(
text("addon_questions", "addon_questions", 1000, false),
text("addon_questions", "addon_questions", 1000, false, false),
"🛒 Vásárlás: addon_questions, 1\u{a0}000\u{a0}Ft (teszt fizetés)"
);
}
+61 -1
View File
@@ -153,6 +153,48 @@ async fn invitation_headers_for_spam_filters(db: PgPool) {
assert!(raw.contains("multipart/alternative") && raw.contains("text/plain") && raw.contains("text/html"));
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn gift_e_mails_carry_the_gift_card(db: PgPool) {
let card = json!({
"package": "Páros", "contents": ["2 részletes képletelemzés", "3 kérdés"], "code": "ABCD-EFGH-JKMN",
"redeem_url": "https://example.com/bevaltas?kod=ABCD-EFGH-JKMN", "recipient_name": "Bea", "from_name": "Ági",
"message": "Boldog szülinapot!",
});
for (to, template, card) in [
("bea@example.com", "gift_package", card.clone()),
// A broken card: the e-mail still goes, without it.
("cili@example.com", "gift_package", json!({"package": "Páros"})),
] {
sqlx::query("INSERT INTO email_outbox (id, to_email, template, locale, payload) VALUES ($1, $2, $3, 'hu', $4)")
.bind(Uuid::now_v7())
.bind(to)
.bind(template)
.bind(json!({
"url": "https://example.com/bevaltas?kod=ABCD-EFGH-JKMN", "package_name": "Páros",
"contents": "2 részletes képletelemzés, 3 kérdés", "promo_code": "ABCD-EFGH-JKMN",
"from_name": "Ági", "message": "Boldog szülinapot!", "gift_card": card,
}))
.execute(&db)
.await
.unwrap();
}
queue(&db, "anna@example.com", "verify_email").await;
let d = delivery(db.clone(), vec![]);
assert_eq!(d.deliver_due().await.unwrap(), 3);
let Mailer::Memory { sent, .. } = &d.mailer else { unreachable!() };
let sent = sent.lock().unwrap();
let raw = |to: &str| sent.iter().find(|(t, _, _)| t == to).unwrap().2.clone();
let bea = raw("bea@example.com");
assert!(bea.contains("multipart/mixed") && bea.contains("multipart/alternative"), "{bea}");
assert!(bea.contains("Content-Type: application/pdf"));
assert!(bea.contains("sorsfonalak-ajandek-ABCD-EFGH-JKMN.pdf"), "{}", &bea[..bea.find("JVBERi0").unwrap_or(0)]);
// The PDF itself, base64 ("%PDF-" is "JVBERi0").
assert!(bea.contains("JVBERi0"));
for plain in [raw("cili@example.com"), raw("anna@example.com")] {
assert!(!plain.contains("application/pdf") && !plain.contains("multipart/mixed"));
}
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn concurrent_workers_do_not_send_twice(db: PgPool) {
for i in 0..15 {
@@ -203,6 +245,21 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
.await
.unwrap();
sqlx::query("UPDATE email_outbox SET sent_at = now() WHERE id = $1").bind(recent).execute(&db).await.unwrap();
// Gifts: one never paid (gone after a week), one just started, one paid long ago.
let gifts = [("8 days", false), ("1 hour", false), ("30 days", true)].map(|g| (Uuid::now_v7(), g));
for (id, (age, paid)) in &gifts {
sqlx::query(
"INSERT INTO gifts (id, package, recipient_email, created_at, paid_at, code) \
VALUES ($1, 'couple', 'bea@example.com', now() - $2::interval, CASE WHEN $3 THEN now() END, \
CASE WHEN $3 THEN 'ABCDEFGHJKMN' END)",
)
.bind(id)
.bind(age)
.bind(paid)
.execute(&db)
.await
.unwrap();
}
let deleted = crate::cleanup::run_once(&db).await.unwrap();
assert_eq!(
@@ -214,9 +271,12 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
("invites", 0),
("invitations", 0),
("prompt_previews", 0),
("generation_errors", 0)
("generation_errors", 0),
("gifts", 1),
]
);
let kept: Vec<Uuid> = sqlx::query_scalar("SELECT id FROM gifts ORDER BY id").fetch_all(&db).await.unwrap();
assert_eq!(kept, vec![gifts[1].0, gifts[2].0]);
let (left,): (Vec<Uuid>,) =
sqlx::query_as("SELECT array_agg(id ORDER BY id) FROM email_outbox").fetch_one(&db).await.unwrap();
assert_eq!(left, vec![recent, unsent]);