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:
@@ -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(¬e)).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,
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user