Admin gifts: an e-mail to the user; the user dialog no longer loses a pick
- 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:
@@ -177,6 +177,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
|
|||||||
("synastry_invite", _) => synastry_invite(lang, payload, url)?,
|
("synastry_invite", _) => synastry_invite(lang, payload, url)?,
|
||||||
("waitlist_joined", _) => waitlist_joined(lang, payload, url)?,
|
("waitlist_joined", _) => waitlist_joined(lang, payload, url)?,
|
||||||
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
||||||
|
("gift", _) => gift(lang, payload, url)?,
|
||||||
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
|
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
|
||||||
};
|
};
|
||||||
Ok(content.render(lang))
|
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.
|
/// 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> {
|
fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||||
let unsubscribe_url = field(payload, "unsubscribe_url")?;
|
let unsubscribe_url = field(payload, "unsubscribe_url")?;
|
||||||
let unsubscribe_post_url = field(payload, "unsubscribe_post_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")));
|
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]
|
#[test]
|
||||||
fn purchase_confirmations_confirm_the_waiver() {
|
fn purchase_confirmations_confirm_the_waiver() {
|
||||||
let payload = serde_json::json!({
|
let payload = serde_json::json!({
|
||||||
|
|||||||
@@ -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::Json;
|
||||||
use axum::extract::{Path, Query, State};
|
use axum::extract::{Path, Query, State};
|
||||||
@@ -7,6 +8,7 @@ use axum_extra::extract::WithRejection;
|
|||||||
use db::Role;
|
use db::Role;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
use sqlx::PgConnection;
|
||||||
use time::OffsetDateTime;
|
use time::OffsetDateTime;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
@@ -140,6 +142,7 @@ pub async fn adjust_credits(
|
|||||||
let exists: Option<(Uuid,)> =
|
let exists: Option<(Uuid,)> =
|
||||||
sqlx::query_as("SELECT id FROM users WHERE id = $1").bind(id).fetch_optional(&state.db).await?;
|
sqlx::query_as("SELECT id FROM users WHERE id = $1").bind(id).fetch_optional(&state.db).await?;
|
||||||
exists.ok_or(ApiError::NotFound("user"))?;
|
exists.ok_or(ApiError::NotFound("user"))?;
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note, created_by) \
|
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note, created_by) \
|
||||||
VALUES ($1, $2, $3, $4, 'admin_adjust', $5, $6)",
|
VALUES ($1, $2, $3, $4, 'admin_adjust', $5, $6)",
|
||||||
@@ -150,9 +153,14 @@ pub async fn adjust_credits(
|
|||||||
.bind(req.delta)
|
.bind(req.delta)
|
||||||
.bind(req.note.map(|n| n.chars().take(500).collect::<String>()))
|
.bind(req.note.map(|n| n.chars().take(500).collect::<String>()))
|
||||||
.bind(admin.id())
|
.bind(admin.id())
|
||||||
.execute(&state.db)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.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() }))))
|
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 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 mut tx = state.db.begin().await?;
|
||||||
let order = packages::grant(&mut tx, id, package, Source::Admin, Some(admin.id()), note.as_deref()).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?;
|
let balance = credits::balance(&mut tx, id).await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
tracing::info!(admin = %admin.id(), user = %id, package = package.id, "package granted");
|
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)",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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;
|
let r = app.post(&format!("/v1/admin/users/{anna}/credits"), Some(&admin), grant("chat", 5)).await;
|
||||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
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;
|
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["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")]
|
#[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, &anna, &anna_id, "family").await.status, StatusCode::FORBIDDEN);
|
||||||
assert_eq!(grant_package(&app, &admin, &anna_id, "gold").await.status, StatusCode::NOT_FOUND);
|
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 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!(
|
assert_eq!(
|
||||||
(r.status, &r.body["analyses_left"]),
|
(r.status, &r.body["analyses_left"]),
|
||||||
(StatusCode::CREATED, &json!({"natal": 6, "synastry": 5, "forecast": 6, "question": 3, "tarot": 10})),
|
(StatusCode::CREATED, &json!({"natal": 6, "synastry": 5, "forecast": 6, "question": 3, "tarot": 10})),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import { Modal } from "@/components/Modal";
|
import { Modal } from "@/components/Modal";
|
||||||
import { huf, usePackages } from "@/components/PackageCards";
|
import { huf, usePackages } from "@/components/PackageCards";
|
||||||
@@ -207,6 +207,13 @@ function UserDialog({
|
|||||||
onChange: (u: AdminUser) => void;
|
onChange: (u: AdminUser) => void;
|
||||||
onClose: () => 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 (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={user.display_name || "(nincs név)"}
|
title={user.display_name || "(nincs név)"}
|
||||||
@@ -217,13 +224,33 @@ function UserDialog({
|
|||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
|
canClose={canClose}
|
||||||
>
|
>
|
||||||
<RolesEditor user={user} isSelf={isSelf} onChange={onChange} />
|
<RolesEditor user={user} isSelf={isSelf} onChange={onChange} />
|
||||||
<PackageGrant user={user} packages={packages} onChange={onChange} />
|
<PackageGrant
|
||||||
<CreditGrant user={user} onChange={onChange} />
|
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" }}>
|
<div className="row" style={{ justifyContent: "flex-end" }}>
|
||||||
<button type="button" className="btn btn-primary" onClick={onClose}>
|
<button
|
||||||
Kész
|
type="button"
|
||||||
|
className="btn"
|
||||||
|
onClick={() => {
|
||||||
|
if (canClose()) onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Bezárás
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
@@ -287,12 +314,18 @@ function PackageGrant({
|
|||||||
user,
|
user,
|
||||||
packages,
|
packages,
|
||||||
onChange,
|
onChange,
|
||||||
|
onUnsent,
|
||||||
}: {
|
}: {
|
||||||
user: AdminUser;
|
user: AdminUser;
|
||||||
packages: Package[];
|
packages: Package[];
|
||||||
onChange: (u: AdminUser) => void;
|
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("");
|
const [id, setId] = useState("");
|
||||||
|
useEffect(() => {
|
||||||
|
onUnsent(packages.find((p) => p.id === id)?.name ?? null);
|
||||||
|
}, [id, packages, onUnsent]);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [status, setStatus] = useState<Status>(null);
|
const [status, setStatus] = useState<Status>(null);
|
||||||
|
|
||||||
@@ -339,7 +372,7 @@ function PackageGrant({
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</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"}
|
{busy ? "…" : "Kiosztás"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -354,9 +387,22 @@ function PackageGrant({
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Adds (or takes away) single analyses of one kind. */
|
/** 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 [delta, setDelta] = useState("");
|
||||||
const [unit, setUnit] = useState<UnitKind>("natal");
|
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 [busy, setBusy] = useState(false);
|
||||||
const [status, setStatus] = useState<Status>(null);
|
const [status, setStatus] = useState<Status>(null);
|
||||||
|
|
||||||
@@ -422,7 +468,7 @@ function CreditGrant({ user, onChange }: { user: AdminUser; onChange: (u: AdminU
|
|||||||
value={delta}
|
value={delta}
|
||||||
onChange={(e) => setDelta(e.target.value)}
|
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
|
Jóváír
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,20 +5,30 @@ import { useEffect, useId, useRef } from "react";
|
|||||||
/**
|
/**
|
||||||
* A modal window (the browser's own <dialog>: focus stays inside, Escape
|
* 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.
|
* 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({
|
export function Modal({
|
||||||
title,
|
title,
|
||||||
subtitle,
|
subtitle,
|
||||||
onClose,
|
onClose,
|
||||||
|
canClose,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
title: string;
|
title: string;
|
||||||
subtitle?: React.ReactNode;
|
subtitle?: React.ReactNode;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
canClose?: () => boolean;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const ref = useRef<HTMLDialogElement>(null);
|
const ref = useRef<HTMLDialogElement>(null);
|
||||||
const titleId = useId();
|
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.
|
// No close() on unmount: that would fire onClose; a removed dialog is gone anyway.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -32,8 +42,17 @@ export function Modal({
|
|||||||
className="modal"
|
className="modal"
|
||||||
aria-labelledby={titleId}
|
aria-labelledby={titleId}
|
||||||
onClose={onClose}
|
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) => {
|
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">
|
<div className="modal-inner">
|
||||||
@@ -42,7 +61,7 @@ export function Modal({
|
|||||||
<h2 id={titleId}>{title}</h2>
|
<h2 id={titleId}>{title}</h2>
|
||||||
{subtitle && <div className="muted modal-sub">{subtitle}</div>}
|
{subtitle && <div className="muted modal-sub">{subtitle}</div>}
|
||||||
</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">
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
<path d="M6 6l12 12M18 6L6 18" />
|
<path d="M6 6l12 12M18 6L6 18" />
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
Reference in New Issue
Block a user