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:
@@ -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)));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user