Files
sorsfonalak/services/backend/src/routes/admin.rs
T
fecoandClaude Opus 5.5 b0fc547b73
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 5m52s
CI / deploy (push) Skipped
Tarot readings: AI-written, drawn on the server, sold as units
A new Kártyajóslás page: choose a spread (1, 3 or 5 cards), ask a
question, pick the cards from the fanned deck and watch them turn over;
the reading is written by the detailed-analysis model from the cards,
their positions and base meanings, the question and the reader's Sun,
Moon and Ascendant. The server shuffles and draws, so nobody can draw
again for free. A reading is a 'tarot' analysis (worker, retries,
fallback, refunds and admin regeneration as for analyses), uses one
'tarot' unit, and survives recalculations; deleting the account
deletes it.

Packages carry 2/5/10 readings, the new +5 kártyajóslás addon costs
1 000 Ft. The card artwork comes from the tarot design studio
(celestial astrolabe style); the deck JSON is shared by the frontend
and the prompt. A public example is at /kartyajoslas/pelda.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 14:35:50 +00:00

185 lines
6.8 KiB
Rust

//! Administration (admin role only): users, roles, credits.
use axum::Json;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use db::Role;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::{Body, IdPath, St};
use crate::auth::AdminUser;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::packages::{self, Source};
use crate::views::{rfc3339, rfc3339_opt};
#[derive(Deserialize)]
pub struct UserQuery {
/// Part of the e-mail address or display name.
q: Option<String>,
limit: Option<i64>,
offset: Option<i64>,
}
pub async fn list_users(
State(state): St,
_admin: AdminUser,
WithRejection(Query(query), _): WithRejection<Query<UserQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let limit = query.limit.unwrap_or(50).clamp(1, 200);
let offset = query.offset.unwrap_or(0).max(0);
let pattern = query.q.as_deref().map(|q| format!("%{}%", q.trim().replace(['%', '_'], "")));
type Row = (
Uuid,
String,
Option<String>,
Vec<String>,
bool,
OffsetDateTime,
Option<OffsetDateTime>,
i64,
i64,
i64,
i64,
i64,
i64,
);
let rows: Vec<Row> = sqlx::query_as(
"SELECT u.id, u.email, u.display_name, u.roles, u.email_verified_at IS NOT NULL, u.created_at, u.last_login_at, \
(SELECT count(*) FROM charts c WHERE c.owner_id = u.id), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'natal'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'synastry'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'forecast'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'question'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'tarot') \
FROM users u \
WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1 \
ORDER BY u.created_at DESC LIMIT $2 OFFSET $3",
)
.bind(pattern)
.bind(limit)
.bind(offset)
.fetch_all(&state.db)
.await?;
let users: Vec<Value> = rows
.into_iter()
.map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, forecast, question, tarot)| {
json!({
"id": id, "email": email, "display_name": name, "roles": roles, "email_verified": verified,
"created_at": rfc3339(created), "last_login_at": rfc3339_opt(last_login),
"charts": charts,
"analyses_left": {
"natal": natal, "synastry": synastry, "forecast": forecast, "question": question, "tarot": tarot,
},
})
})
.collect();
Ok(Json(json!({ "users": users, "limit": limit, "offset": offset })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateUser {
roles: Vec<Role>,
}
pub async fn update_user(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<UpdateUser>,
) -> ApiResult<Json<Value>> {
let mut roles: Vec<&str> = req.roles.iter().map(|r| r.as_str()).collect();
roles.sort_unstable();
roles.dedup();
if roles.is_empty() {
return Err(ApiError::BadRequest("at least one role is required".into()));
}
if id == admin.id() && !roles.contains(&Role::Admin.as_str()) {
return Err(ApiError::conflict("own_admin_role", "you cannot remove your own admin role"));
}
let row: Option<(Uuid, Vec<String>)> =
sqlx::query_as("UPDATE users SET roles = $1, updated_at = now() WHERE id = $2 RETURNING id, roles")
.bind(&roles)
.bind(id)
.fetch_optional(&state.db)
.await?;
let (id, roles) = row.ok_or(ApiError::NotFound("user"))?;
tracing::info!(admin = %admin.id(), user = %id, ?roles, "roles changed");
Ok(Json(json!({ "id": id, "roles": roles })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AdjustCredits {
unit: Unit,
/// Positive to add, negative to take away.
delta: i32,
note: Option<String>,
}
pub async fn adjust_credits(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<AdjustCredits>,
) -> ApiResult<(StatusCode, Json<Value>)> {
if req.delta == 0 {
return Err(ApiError::BadRequest("delta must not be 0".into()));
}
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"))?;
sqlx::query(
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note, created_by) \
VALUES ($1, $2, $3, $4, 'admin_adjust', $5, $6)",
)
.bind(Uuid::now_v7())
.bind(id)
.bind(req.unit.as_str())
.bind(req.delta)
.bind(req.note.map(|n| n.chars().take(500).collect::<String>()))
.bind(admin.id())
.execute(&state.db)
.await?;
let balance = credits::balance(&mut *state.db.acquire().await?, id).await?;
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "analyses_left": balance.view() }))))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GrantPackage {
package: String,
note: Option<String>,
}
/// Gives a user a package from the catalog (a gift: no payment, price 0).
pub async fn grant_package(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<GrantPackage>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
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 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?;
let balance = credits::balance(&mut tx, id).await?;
tx.commit().await?;
tracing::info!(admin = %admin.id(), user = %id, package = package.id, "package granted");
Ok((
StatusCode::CREATED,
Json(json!({
"order_id": order, "user_id": id, "package": package.id,
"analyses_left": balance.view(),
})),
))
}