Files
sorsfonalak/services/backend/src/routes/admin.rs
T
fecoandClaude Opus 5.5 ce3d3804a7 Paid detailed analyses with per-kind units; example analysis page
- Credits become analysis units (migration 0006): a natal analysis uses
  one 'natal' unit, a synastry analysis one 'synastry' unit. No monthly
  free credits, no model tiers: ANALYSIS_MODEL (default Opus 5.5) writes
  every paid analysis. Admins grant units per kind; the worker refunds
  the right unit on failure.
- Chart page: the detailed analysis card (offer with units left and a
  confirmation, progress while writing, the finished six sections).
- Public /pelda page: a full Opus analysis of a made-up chart, with the
  free summary and a login call to action.
- The worker sends the JSON schema with properties in 'required' order.
  serde_json sorted them, so the title came after ~9000 tokens of text
  and Opus sometimes left it empty (3 failed attempts in a live test);
  with the order fixed the same analysis succeeded at the first try.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-16 17:39:15 +00:00

131 lines
4.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::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);
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') \
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)| {
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},
})
})
.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() }))))
}