Christmas gifts and timed gift e-mails

- Gifts bought 15 Nov - 6 Jan get a Christmas card ("Boldog karácsonyt és
  csillagos 2027-et!", snowflakes) and a Christmas e-mail subject.
- The buyer can time the gift e-mail (e.g. Christmas morning); "Küldés most"
  replaces a waiting one, a refund takes it back.
- Admin: timed e-mails by hour (waiting / sent / failed), e-mail state per gift.
- /karacsony landing page; seasonal hints on /csomagok and /ajandek.

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