Admin gifts: an e-mail to the user; the user dialog no longer loses a pick
CI / test (push) Successful in 2m3s
CI / build (push) Skipped
CI / deploy (push) Skipped

- A package or units an admin gives a user are announced in a "gift"
  e-mail (taking units away is not). Queued in the same transaction.
- The user dialog asks before closing with a chosen package or a typed
  amount not sent yet; the send buttons turn gold when ready, "Kész" is now
  a plain "Bezárás".
- The modal closes on the backdrop only when the press started there too,
  so picking from a select whose list hangs over the backdrop, or dragging
  a selection out, no longer closes it.

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 11:20:14 +00:00
co-authored by Claude Opus 5.5
parent e5c90b260d
commit f8abdac790
5 changed files with 221 additions and 14 deletions
+70
View File
@@ -177,6 +177,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
("synastry_invite", _) => synastry_invite(lang, payload, url)?,
("waitlist_joined", _) => waitlist_joined(lang, payload, url)?,
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
("gift", _) => gift(lang, payload, url)?,
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
};
Ok(content.render(lang))
@@ -365,6 +366,58 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
}
/// The confirmation of a waitlist sign-up, with the link that takes the address off the list.
/// Something an administrator gave the user: a package or single units.
/// `gift` says what (e.g. "a(z) „Páros” csomagot", "2 kérdést"), `contents`
/// what a package holds.
fn gift(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
let clean = |s: &str| s.chars().filter(|c| !c.is_control()).take(300).collect::<String>();
let what = payload["gift"].as_str().map(clean).filter(|s| !s.trim().is_empty());
let what = what.ok_or(TemplateError::MissingField("gift"))?;
let contents = payload["contents"].as_str().map(clean).filter(|s| !s.trim().is_empty());
let greeting = match (lang, name(payload, "display_name")) {
(Lang::Hu, Some(n)) => format!("Szia {n}!"),
(Lang::Hu, None) => "Szia!".to_owned(),
(Lang::En, Some(n)) => format!("Hi {n},"),
(Lang::En, None) => "Hi,".to_owned(),
};
Ok(match lang {
Lang::Hu => Content {
subject: "Ajándékot kaptál a Sorsfonalaktól".into(),
preheader: Some(format!("Jóváírtuk {what}.")),
greeting,
intro: format!(
"Ajándékba kaptad {what}, és már jóvá is írtuk a fiókodban.{} Rögtön felhasználhatod, nem jár le.",
contents.map(|c| format!(" Tartalma: {c}.")).unwrap_or_default()
),
quote: None,
points: None,
button: "Megnézem",
url,
note: "Ha kérdésed van, írj nekünk az info@sorsfonalak.hu címre.".into(),
reason: Some("Ezt a levelet azért kaptad, mert ajándékot írtunk jóvá a Sorsfonalak-fiókodban.".into()),
unsubscribe: None,
unsubscribe_post_url: None,
},
Lang::En => Content {
subject: "A gift from Sorsfonalak".into(),
preheader: Some(format!("Added to your account: {what}.")),
greeting,
intro: format!(
"You got {what} as a gift, already added to your account.{} You can use it right away; it does not expire.",
contents.map(|c| format!(" It contains: {c}.")).unwrap_or_default()
),
quote: None,
points: None,
button: "Take a look",
url,
note: "If you have a question, write to info@sorsfonalak.hu.".into(),
reason: Some("You got this e-mail because a gift was added to your Sorsfonalak account.".into()),
unsubscribe: None,
unsubscribe_post_url: None,
},
})
}
fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
let unsubscribe_url = field(payload, "unsubscribe_url")?;
let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
@@ -731,6 +784,23 @@ mod tests {
assert_eq!(render("invitation", "hu", &broken), Err(TemplateError::MissingField("unsubscribe_url")));
}
#[test]
fn gifts_say_what_was_given() {
let payload = json!({
"url": "https://sorsfonalak.hu/csomagok", "display_name": "Anna",
"gift": "a(z) „Páros” csomagot", "contents": "2 részletes képletelemzés, 3 kérdés",
});
let hu = render("gift", "hu", &payload).unwrap();
assert_eq!(hu.subject, "Ajándékot kaptál a Sorsfonalaktól");
assert!(hu.text.contains("Ajándékba kaptad a(z) „Páros” csomagot"), "{}", hu.text);
assert!(hu.text.contains("Tartalma: 2 részletes képletelemzés, 3 kérdés."), "{}", hu.text);
let units = json!({"url": "https://sorsfonalak.hu/csomagok", "gift": "2 kérdést"});
let hu = render("gift", "hu", &units).unwrap();
assert!(hu.text.contains("Szia!") && hu.text.contains("Ajándékba kaptad 2 kérdést,") && !hu.text.contains("Tartalma"));
assert!(render("gift", "en", &payload).unwrap().subject.starts_with("A gift"));
assert_eq!(render("gift", "hu", &json!({"url": "x"})), Err(TemplateError::MissingField("gift")));
}
#[test]
fn purchase_confirmations_confirm_the_waiver() {
let payload = serde_json::json!({
+55 -3
View File
@@ -1,4 +1,5 @@
//! Administration (admin role only): users, roles, credits.
//! Administration (admin role only): users, roles, credits. A package or
//! units given to a user are announced to them in an e-mail (`gift`).
use axum::Json;
use axum::extract::{Path, Query, State};
@@ -7,6 +8,7 @@ use axum_extra::extract::WithRejection;
use db::Role;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
@@ -140,6 +142,7 @@ pub async fn adjust_credits(
let exists: Option<(Uuid,)> =
sqlx::query_as("SELECT id FROM users WHERE id = $1").bind(id).fetch_optional(&state.db).await?;
exists.ok_or(ApiError::NotFound("user"))?;
let mut tx = state.db.begin().await?;
sqlx::query(
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note, created_by) \
VALUES ($1, $2, $3, $4, 'admin_adjust', $5, $6)",
@@ -150,9 +153,14 @@ pub async fn adjust_credits(
.bind(req.delta)
.bind(req.note.map(|n| n.chars().take(500).collect::<String>()))
.bind(admin.id())
.execute(&state.db)
.execute(&mut *tx)
.await?;
let balance = credits::balance(&mut *state.db.acquire().await?, id).await?;
// Only a gift is announced, not taking units away.
if req.delta > 0 {
queue_gift(&mut tx, &state.config.public_base_url, id, Gift::Units(req.unit, req.delta)).await?;
}
let balance = credits::balance(&mut tx, id).await?;
tx.commit().await?;
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "analyses_left": balance.view() }))))
}
@@ -177,6 +185,7 @@ pub async fn grant_package(
let note = req.note.map(|n| n.trim().chars().take(500).collect::<String>()).filter(|n| !n.is_empty());
let mut tx = state.db.begin().await?;
let order = packages::grant(&mut tx, id, package, Source::Admin, Some(admin.id()), note.as_deref()).await?;
queue_gift(&mut tx, &state.config.public_base_url, id, Gift::Package(package)).await?;
let balance = credits::balance(&mut tx, id).await?;
tx.commit().await?;
tracing::info!(admin = %admin.id(), user = %id, package = package.id, "package granted");
@@ -188,3 +197,46 @@ pub async fn grant_package(
})),
))
}
/// What an administrator gave a user.
enum Gift {
Package(&'static packages::Package),
Units(Unit, i32),
}
/// Queues the "you got a gift" e-mail for the user.
async fn queue_gift(conn: &mut PgConnection, base: &str, user_id: Uuid, gift: Gift) -> Result<(), ApiError> {
let (email, locale, name): (String, String, Option<String>) =
sqlx::query_as("SELECT email, locale, display_name FROM users WHERE id = $1")
.bind(user_id)
.fetch_one(&mut *conn)
.await?;
let hu = locale.eq_ignore_ascii_case("hu");
let (what, contents) = match gift {
Gift::Package(p) if hu => (format!("a(z) „{}” csomagot", p.name), Some(p.contents_text())),
Gift::Package(p) => (format!("the “{}” package", p.name), Some(p.contents_text())),
Gift::Units(unit, n) => (format!("{n} {}", unit_name(unit, hu)), None),
};
let payload = json!({
"url": format!("{base}/csomagok"), "display_name": name, "gift": what, "contents": contents,
});
super::auth::queue_email_to(conn, Some(user_id), &email, "gift", &locale, payload).await
}
/// A unit's name after a number, as the object of the sentence ("2 kérdést").
fn unit_name(unit: Unit, hu: bool) -> &'static str {
match (unit, hu) {
(Unit::Natal, true) => "részletes képletelemzést",
(Unit::Synastry, true) => "kapcsolati elemzést",
(Unit::Forecast, true) => "éves előrejelzést",
(Unit::Person, true) => "személyhelyet",
(Unit::Question, true) => "kérdést",
(Unit::Tarot, true) => "kártyajóslást",
(Unit::Natal, false) => "detailed chart analysis(es)",
(Unit::Synastry, false) => "relationship analysis(es)",
(Unit::Forecast, false) => "yearly forecast(s)",
(Unit::Person, false) => "person slot(s)",
(Unit::Question, false) => "question(s)",
(Unit::Tarot, false) => "tarot reading(s)",
}
}
+21 -1
View File
@@ -616,9 +616,21 @@ async fn roles_and_admin_guard(pool: PgPool) {
);
let r = app.post(&format!("/v1/admin/users/{anna}/credits"), Some(&admin), grant("chat", 5)).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
// the gift is announced in an e-mail; taking units away is not
app.post(&format!("/v1/admin/users/{anna}/credits"), Some(&admin), grant("natal", -1)).await;
let gifts: Vec<(Value,)> =
sqlx::query_as("SELECT payload FROM email_outbox WHERE to_email = 'anna@example.com' AND template = 'gift'")
.fetch_all(&app.pool)
.await
.unwrap();
assert_eq!(gifts.len(), 1);
assert_eq!((&gifts[0].0["gift"], &gifts[0].0["display_name"]), (&json!("5 részletes képletelemzést"), &json!("Anna")));
app.post(&format!("/v1/admin/users/{anna}/credits"), Some(&admin), grant("natal", 1)).await;
let credits = app.get("/v1/credits", Some(&user)).await.body;
assert_eq!(credits["balance"], json!({"natal": 5, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0}));
assert_eq!((credits["ledger"][0]["unit"].as_str(), &credits["ledger"][0]["delta"]), (Some("natal"), &json!(5)));
// newest first: +1 after −1 after +5
let deltas: Vec<&Value> = credits["ledger"].as_array().unwrap().iter().map(|l| &l["delta"]).collect();
assert_eq!(deltas, [&json!(1), &json!(-1), &json!(5)]);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -1616,6 +1628,14 @@ async fn packages_grant_units(pool: PgPool) {
assert_eq!(grant_package(&app, &anna, &anna_id, "family").await.status, StatusCode::FORBIDDEN);
assert_eq!(grant_package(&app, &admin, &anna_id, "gold").await.status, StatusCode::NOT_FOUND);
let r = grant_package(&app, &admin, &anna_id, "family").await;
let (gift,): (Value,) =
sqlx::query_as("SELECT payload FROM email_outbox WHERE to_email = 'anna@example.com' AND template = 'gift'")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(gift["gift"], "a(z) „Család” csomagot");
assert!(gift["contents"].as_str().unwrap().contains("részletes képletelemzés"), "{gift}");
assert!(gift["url"].as_str().unwrap().ends_with("/csomagok"));
assert_eq!(
(r.status, &r.body["analyses_left"]),
(StatusCode::CREATED, &json!({"natal": 6, "synastry": 5, "forecast": 6, "question": 3, "tarot": 10})),
+54 -8
View File
@@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Modal } from "@/components/Modal";
import { huf, usePackages } from "@/components/PackageCards";
@@ -207,6 +207,13 @@ function UserDialog({
onChange: (u: AdminUser) => void;
onClose: () => void;
}) {
// What was chosen or typed but not sent yet (a package, a number of units).
const unsent = useRef<{ pkg: string | null; credit: string | null }>({ pkg: null, credit: null });
const canClose = () => {
const { pkg, credit } = unsent.current;
const what = [pkg && `a(z) ${pkg} csomag`, credit && `${credit} jóváírás`].filter(Boolean).join(" és ");
return !what || window.confirm(`Még nem küldted el: ${what}. Bezárod nélküle?`);
};
return (
<Modal
title={user.display_name || "(nincs név)"}
@@ -217,13 +224,33 @@ function UserDialog({
</>
}
onClose={onClose}
canClose={canClose}
>
<RolesEditor user={user} isSelf={isSelf} onChange={onChange} />
<PackageGrant user={user} packages={packages} onChange={onChange} />
<CreditGrant user={user} onChange={onChange} />
<PackageGrant
user={user}
packages={packages}
onChange={onChange}
onUnsent={(name) => {
unsent.current.pkg = name;
}}
/>
<CreditGrant
user={user}
onChange={onChange}
onUnsent={(text) => {
unsent.current.credit = text;
}}
/>
<div className="row" style={{ justifyContent: "flex-end" }}>
<button type="button" className="btn btn-primary" onClick={onClose}>
Kész
<button
type="button"
className="btn"
onClick={() => {
if (canClose()) onClose();
}}
>
Bezárás
</button>
</div>
</Modal>
@@ -287,12 +314,18 @@ function PackageGrant({
user,
packages,
onChange,
onUnsent,
}: {
user: AdminUser;
packages: Package[];
onChange: (u: AdminUser) => void;
/** The chosen package's name while it is not given yet (null: nothing pending). */
onUnsent: (name: string | null) => void;
}) {
const [id, setId] = useState("");
useEffect(() => {
onUnsent(packages.find((p) => p.id === id)?.name ?? null);
}, [id, packages, onUnsent]);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<Status>(null);
@@ -339,7 +372,7 @@ function PackageGrant({
</option>
))}
</select>
<button type="submit" className="btn btn-sm" disabled={busy || !id}>
<button type="submit" className={id ? "btn btn-sm btn-primary" : "btn btn-sm"} disabled={busy || !id}>
{busy ? "…" : "Kiosztás"}
</button>
</div>
@@ -354,9 +387,22 @@ function PackageGrant({
}
/** Adds (or takes away) single analyses of one kind. */
function CreditGrant({ user, onChange }: { user: AdminUser; onChange: (u: AdminUser) => void }) {
function CreditGrant({
user,
onChange,
onUnsent,
}: {
user: AdminUser;
onChange: (u: AdminUser) => void;
/** The typed amount while it is not sent yet (null: nothing pending). */
onUnsent: (text: string | null) => void;
}) {
const [delta, setDelta] = useState("");
const [unit, setUnit] = useState<UnitKind>("natal");
useEffect(() => {
const label = UNITS.find((u) => u.value === unit)?.label;
onUnsent(delta.trim() ? `${delta.trim()} ${label}` : null);
}, [delta, unit, onUnsent]);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<Status>(null);
@@ -422,7 +468,7 @@ function CreditGrant({ user, onChange }: { user: AdminUser; onChange: (u: AdminU
value={delta}
onChange={(e) => setDelta(e.target.value)}
/>
<button type="submit" className="btn btn-sm" disabled={busy || !delta}>
<button type="submit" className={delta ? "btn btn-sm btn-primary" : "btn btn-sm"} disabled={busy || !delta}>
Jóváír
</button>
</div>
+21 -2
View File
@@ -5,20 +5,30 @@ import { useEffect, useId, useRef } from "react";
/**
* A modal window (the browser's own <dialog>: focus stays inside, Escape
* closes it). Shown while mounted; a click on the dimmed backdrop closes it.
* `canClose`: asked first (e.g. about unsaved input); false keeps it open.
*/
export function Modal({
title,
subtitle,
onClose,
canClose,
children,
}: {
title: string;
subtitle?: React.ReactNode;
onClose: () => void;
canClose?: () => boolean;
children: React.ReactNode;
}) {
const ref = useRef<HTMLDialogElement>(null);
const titleId = useId();
// Where the press started: only a press and release both on the backdrop close
// it (not a text selection dragged out, nor a pick from a select's list that
// hangs over the backdrop).
const pressedBackdrop = useRef(false);
const close = () => {
if (!canClose || canClose()) onClose();
};
// No close() on unmount: that would fire onClose; a removed dialog is gone anyway.
useEffect(() => {
@@ -32,8 +42,17 @@ export function Modal({
className="modal"
aria-labelledby={titleId}
onClose={onClose}
onCancel={(e) => {
// Escape: the dialog would close by itself.
if (canClose && !canClose()) e.preventDefault();
}}
onPointerDown={(e) => {
pressedBackdrop.current = e.target === ref.current;
}}
onClick={(e) => {
if (e.target === ref.current) onClose();
const onBackdrop = pressedBackdrop.current && e.target === ref.current;
pressedBackdrop.current = false;
if (onBackdrop) close();
}}
>
<div className="modal-inner">
@@ -42,7 +61,7 @@ export function Modal({
<h2 id={titleId}>{title}</h2>
{subtitle && <div className="muted modal-sub">{subtitle}</div>}
</div>
<button type="button" className="modal-close" onClick={onClose} aria-label="Bezárás">
<button type="button" className="modal-close" onClick={close} aria-label="Bezárás">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M6 6l12 12M18 6L6 18" />
</svg>