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
+63 -63
View File
@@ -1,78 +1,78 @@
//! Credit ledger: every LLM call costs credits; users get a free monthly
//! allowance, granted lazily on the first balance query or spend of a month.
//! Analysis units: a detailed natal analysis uses one `natal` unit, a
//! synastry analysis one `synastry` unit. Units come from purchases or an
//! admin; a failed analysis gives its unit back (the worker does that).
use sqlx::{PgConnection, PgPool};
use time::OffsetDateTime;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sqlx::PgConnection;
use uuid::Uuid;
use crate::error::ApiError;
pub fn current_period() -> String {
let now = OffsetDateTime::now_utc();
format!("{:04}-{:02}", now.year(), u8::from(now.month()))
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Unit {
Natal,
Synastry,
}
/// Grants this month's free credits if not granted yet.
pub async fn ensure_monthly_grant(conn: &mut PgConnection, user_id: Uuid, amount: i32) -> Result<(), ApiError> {
if amount <= 0 {
return Ok(());
impl Unit {
pub fn as_str(self) -> &'static str {
match self {
Unit::Natal => "natal",
Unit::Synastry => "synastry",
}
}
}
/// Units left per kind.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Balance {
pub natal: i64,
pub synastry: i64,
}
impl Balance {
pub fn of(self, unit: Unit) -> i64 {
match unit {
Unit::Natal => self.natal,
Unit::Synastry => self.synastry,
}
}
pub fn view(self) -> Value {
json!({ "natal": self.natal, "synastry": self.synastry })
}
}
pub async fn balance(conn: &mut PgConnection, user_id: Uuid) -> Result<Balance, ApiError> {
let (natal, synastry): (i64, i64) = sqlx::query_as(
"SELECT COALESCE(SUM(delta) FILTER (WHERE unit = 'natal'), 0)::bigint, \
COALESCE(SUM(delta) FILTER (WHERE unit = 'synastry'), 0)::bigint \
FROM credit_ledger WHERE user_id = $1",
)
.bind(user_id)
.fetch_one(conn)
.await?;
Ok(Balance { natal, synastry })
}
/// Spends one unit inside the caller's transaction. The user row is locked
/// so concurrent requests cannot overspend.
pub async fn spend(tx: &mut PgConnection, user_id: Uuid, unit: Unit, analysis_id: Uuid) -> Result<(), ApiError> {
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user_id).execute(&mut *tx).await?;
let left = balance(tx, user_id).await?.of(unit);
if left < 1 {
return Err(ApiError::InsufficientCredits { unit: unit.as_str(), balance: left });
}
sqlx::query(
"INSERT INTO credit_ledger (id, user_id, delta, reason, period, note) \
VALUES ($1, $2, $3, 'monthly_grant', $4, 'monthly free credits') \
ON CONFLICT (user_id, period) WHERE reason = 'monthly_grant' DO NOTHING",
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, analysis_id) VALUES ($1, $2, $3, -1, 'analysis', $4)",
)
.bind(Uuid::now_v7())
.bind(user_id)
.bind(amount)
.bind(current_period())
.execute(conn)
.bind(unit.as_str())
.bind(analysis_id)
.execute(tx)
.await?;
Ok(())
}
pub async fn balance_of(conn: &mut PgConnection, user_id: Uuid) -> Result<i64, ApiError> {
let (balance,): (i64,) =
sqlx::query_as("SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger WHERE user_id = $1")
.bind(user_id)
.fetch_one(conn)
.await?;
Ok(balance)
}
/// Current balance including this month's allowance.
pub async fn balance(pool: &PgPool, user_id: Uuid, monthly: i32) -> Result<i64, ApiError> {
let mut conn = pool.acquire().await?;
ensure_monthly_grant(&mut conn, user_id, monthly).await?;
balance_of(&mut conn, user_id).await
}
/// Spends `cost` credits inside the caller's transaction. The user row is
/// locked so concurrent requests cannot overspend.
pub async fn spend(
tx: &mut PgConnection,
user_id: Uuid,
cost: i32,
monthly: i32,
reason: &str,
analysis_id: Option<Uuid>,
) -> Result<(), ApiError> {
if cost <= 0 {
return Ok(());
}
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user_id).execute(&mut *tx).await?;
ensure_monthly_grant(tx, user_id, monthly).await?;
let balance = balance_of(tx, user_id).await?;
if balance < i64::from(cost) {
return Err(ApiError::InsufficientCredits { needed: cost, balance });
}
sqlx::query("INSERT INTO credit_ledger (id, user_id, delta, reason, analysis_id) VALUES ($1, $2, $3, $4, $5)")
.bind(Uuid::now_v7())
.bind(user_id)
.bind(-cost)
.bind(reason)
.bind(analysis_id)
.execute(tx)
.await?;
Ok(())
}