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
This commit is contained in:
feco
2026-11-16 17:39:15 +00:00
co-authored by Claude Opus 5.5
parent 450174c273
commit ce3d3804a7
29 changed files with 1309 additions and 349 deletions
+10 -12
View File
@@ -28,12 +28,12 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
.bind(auth.id())
.fetch_optional(&state.db)
.await?;
let balance = credits::balance(&state.db, auth.id(), state.config.monthly_free_credits).await?;
let balance = credits::balance(&mut *state.db.acquire().await?, auth.id()).await?;
Ok(Json(json!({
"user": UserView::from(&auth.user),
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
"primary_chart_id": primary.map(|(id,)| id),
"credits": balance,
"analyses_left": balance.view(),
})))
}
@@ -112,22 +112,20 @@ pub async fn change_password(
}
pub async fn credits(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let balance = credits::balance(&state.db, auth.id(), state.config.monthly_free_credits).await?;
type Row = (Uuid, i32, String, Option<String>, Option<Uuid>, Option<String>, OffsetDateTime);
let balance = credits::balance(&mut *state.db.acquire().await?, auth.id()).await?;
type Row = (Uuid, String, i32, String, Option<Uuid>, Option<String>, OffsetDateTime);
let ledger: Vec<Row> = sqlx::query_as(
"SELECT id, delta, reason, period, analysis_id, note, created_at FROM credit_ledger \
"SELECT id, unit, delta, reason, analysis_id, note, created_at FROM credit_ledger \
WHERE user_id = $1 ORDER BY created_at DESC LIMIT 100",
)
.bind(auth.id())
.fetch_all(&state.db)
.await?;
Ok(Json(json!({
"balance": balance,
"monthly_free_credits": state.config.monthly_free_credits,
"llm_models": state.config.llm_models,
"period": credits::current_period(),
"ledger": ledger.into_iter().map(|(id, delta, reason, period, analysis_id, note, at)| json!({
"id": id, "delta": delta, "reason": reason, "period": period,
"balance": balance.view(),
"analysis_model": state.config.analysis_model,
"ledger": ledger.into_iter().map(|(id, unit, delta, reason, analysis_id, note, at)| json!({
"id": id, "unit": unit, "delta": delta, "reason": reason,
"analysis_id": analysis_id, "note": note, "created_at": rfc3339(at),
})).collect::<Vec<_>>(),
})))
@@ -153,7 +151,7 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
"synastries": rows("SELECT json_build_object('id', s.id, 'owner_id', s.owner_id, 'chart1_id', s.chart1_id, 'chart2_id', s.chart2_id, 'result', s.result, 'created_at', s.created_at) FROM synastries s JOIN charts c1 ON c1.id = s.chart1_id JOIN charts c2 ON c2.id = s.chart2_id WHERE s.owner_id = $1 OR c1.owner_id = $1 OR c2.owner_id = $1").await?,
"invites": rows("SELECT json_build_object('id', id, 'chart_id', inviter_chart_id, 'message', message, 'created_at', created_at, 'expires_at', expires_at, 'accepted_at', accepted_at) FROM synastry_invites WHERE inviter_id = $1").await?,
"analyses": rows("SELECT json_build_object('id', a.id, 'kind', a.kind, 'chart_id', a.chart_id, 'synastry_id', a.synastry_id, 'language', a.language, 'model', a.model, 'status', a.status, 'content', a.content, 'created_at', a.created_at) FROM analyses a WHERE a.requested_by = $1 OR a.chart_id IN (SELECT id FROM charts WHERE owner_id = $1)").await?,
"credit_ledger": rows("SELECT json_build_object('delta', delta, 'reason', reason, 'period', period, 'note', note, 'created_at', created_at) FROM credit_ledger WHERE user_id = $1 ORDER BY created_at").await?,
"credit_ledger": rows("SELECT json_build_object('unit', unit, 'delta', delta, 'reason', reason, 'note', note, 'created_at', created_at) FROM credit_ledger WHERE user_id = $1 ORDER BY created_at").await?,
"shares": rows("SELECT json_build_object('slug', slug, 'kind', kind, 'title', title, 'show_birth_data', show_birth_data, 'view_count', view_count, 'created_at', created_at, 'revoked_at', revoked_at) FROM shares WHERE owner_id = $1").await?,
});
Ok(([("content-disposition", "attachment; filename=\"sorsfonalak-export.json\"")], Json(document)))
+12 -11
View File
@@ -12,6 +12,7 @@ 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};
@@ -31,11 +32,12 @@ pub async fn list_users(
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);
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) \
(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",
@@ -47,11 +49,11 @@ pub async fn list_users(
.await?;
let users: Vec<Value> = rows
.into_iter()
.map(|(id, email, name, roles, verified, created, last_login, charts, credits)| {
.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, "credits": credits,
"charts": charts, "analyses_left": {"natal": natal, "synastry": synastry},
})
})
.collect();
@@ -93,6 +95,7 @@ pub async fn update_user(
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AdjustCredits {
unit: Unit,
/// Positive to add, negative to take away.
delta: i32,
note: Option<String>,
@@ -111,19 +114,17 @@ pub async fn adjust_credits(
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, delta, reason, note, created_by) VALUES ($1, $2, $3, 'admin_adjust', $4, $5)",
"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,): (i64,) =
sqlx::query_as("SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger WHERE user_id = $1")
.bind(id)
.fetch_one(&state.db)
.await?;
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "balance": balance }))))
let balance = credits::balance(&mut *state.db.acquire().await?, id).await?;
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "analyses_left": balance.view() }))))
}
+15 -25
View File
@@ -1,6 +1,7 @@
//! Text analyses (LLM) of charts and synastries.
//!
//! A request creates a `pending` analysis and spends credits; the worker
//! A request creates a `pending` analysis and spends one unit of its kind
//! (`natal` or `synastry`, see [`credits`]); the worker
//! writes the text later. A finished analysis with the same cache key (same
//! chart or synastry hash, prompt version, model and language) is copied
//! instead, free of charge, so the same chart is never paid for twice.
@@ -25,7 +26,7 @@ use super::synastries::{load_synastry, visible_synastry};
use super::{IdPath, St};
use crate::AppState;
use crate::auth::AuthUser;
use crate::credits;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
@@ -93,8 +94,6 @@ pub async fn can_see(db: &PgPool, analysis: &AnalysisRow, user: Uuid) -> Result<
pub struct AnalysisRequest {
/// Defaults to the user's locale.
language: Option<String>,
/// One of the configured models; defaults to the first.
model: Option<String>,
}
/// The request body is optional: empty means all defaults.
@@ -118,34 +117,25 @@ async fn request(
req: AnalysisRequest,
) -> ApiResult<(StatusCode, Json<Value>)> {
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
let models = &state.config.llm_models;
let chosen = match &req.model {
None => &models[0],
Some(id) => models.iter().find(|m| &m.id == id).ok_or_else(|| {
let available: Vec<&str> = models.iter().map(|m| m.id.as_str()).collect();
ApiError::BadRequest(format!("unknown model '{id}'; available: {}", available.join(", ")))
})?,
let unit = match target {
Target::Synastry { .. } => Unit::Synastry,
_ => Unit::Natal,
};
if let Some(role) = chosen.role
&& !auth.user.has_access(role)
{
return Err(ApiError::Forbidden(format!("the model '{}' needs the '{}' role", chosen.id, role.as_str())));
}
let cost = chosen.credits;
let (status, row) = queue(state, auth.id(), &target, &language, &chosen.id, cost).await?;
let model = state.config.analysis_model.clone();
let (status, row) = queue(state, auth.id(), &target, &language, &model, Some(unit)).await?;
Ok((status, Json(row.view())))
}
/// Returns the existing analysis with the same cache key for this target,
/// copies a finished one from another chart with the same data, or queues a
/// new one (spending `cost` credits). 200, 201 and 202 respectively.
/// new one (spending one `unit`, if given). 200, 201 and 202 respectively.
async fn queue(
state: &AppState,
user: Uuid,
target: &Target,
language: &str,
model: &str,
cost: i32,
unit: Option<Unit>,
) -> Result<(StatusCode, AnalysisRow), ApiError> {
let (kind, hash, chart_id, synastry_id) = match target {
Target::Natal { chart_id, hash } => ("natal", hash, Some(*chart_id), None),
@@ -206,7 +196,7 @@ async fn queue(
return Ok((StatusCode::CREATED, row));
}
// New analysis: spend credits and queue it for the worker.
// New analysis: spend a unit and queue it for the worker.
let mut tx = state.db.begin().await?;
let row: AnalysisRow = sqlx::query_as(&insert)
.bind(id)
@@ -222,12 +212,12 @@ async fn queue(
.bind(None::<Value>)
.bind(None::<i32>)
.bind(None::<i32>)
.bind(cost)
.bind(i32::from(unit.is_some()))
.bind(None::<OffsetDateTime>)
.fetch_one(&mut *tx)
.await?;
if cost > 0 {
credits::spend(&mut tx, user, cost, state.config.monthly_free_credits, "analysis", Some(id)).await?;
if let Some(unit) = unit {
credits::spend(&mut tx, user, unit, id).await?;
}
tx.commit().await?;
Ok((StatusCode::ACCEPTED, row))
@@ -238,7 +228,7 @@ async fn queue(
pub async fn ensure_summary(state: &AppState, owner: &AuthUser, chart: &ChartRow) -> Result<AnalysisRow, ApiError> {
let target = Target::Summary { chart_id: chart.id, hash: chart.chart_hash.clone() };
let model = state.config.summary_model.clone();
Ok(queue(state, owner.id(), &target, &owner.user.locale, &model, 0).await?.1)
Ok(queue(state, owner.id(), &target, &owner.user.locale, &model, None).await?.1)
}
pub async fn summary_for_chart(
+2 -3
View File
@@ -116,9 +116,8 @@ async fn public_config(State(state): St) -> Json<Value> {
Json(json!({
"google_login": { "enabled": state.google.enabled(), "client_id": c.google_client_ids.first() },
"locales": c.supported_locales,
"llm_models": c.llm_models,
"default_model": c.llm_models[0].id,
"monthly_free_credits": c.monthly_free_credits,
"analysis_model": c.analysis_model,
"summary_model": c.summary_model,
"password_login": c.password_login,
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
}))