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:
+14
-24
@@ -1,6 +1,6 @@
|
||||
# backend
|
||||
|
||||
Felhasználók, belépés, mentett születési képletek, szinasztriák és meghívók, szöveges elemzések, kreditek és nyilvános megosztás. A képleteket a `horoscope-api` számolja, az adatok PostgreSQL-ben vannak. A migrációk a `crates/db/migrations` mappában vannak, és induláskor lefutnak.
|
||||
Felhasználók, belépés, mentett születési képletek, szinasztriák és meghívók, szöveges elemzések, elemzési egységek és nyilvános megosztás. A képleteket a `horoscope-api` számolja, az adatok PostgreSQL-ben vannak. A migrációk a `crates/db/migrations` mappában vannak, és induláskor lefutnak.
|
||||
|
||||
## Konfiguráció (környezeti változók)
|
||||
|
||||
@@ -17,9 +17,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
|
||||
| `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) |
|
||||
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
|
||||
| `MONTHLY_FREE_CREDITS` | `10` | havi ingyenes kreditkeret |
|
||||
| `ANALYSIS_COST` | `1` | egy új elemzés ára kreditben azoknál a modelleknél, amelyeknél az `LLM_MODELS` nem ad meg árat |
|
||||
| `LLM_MODELS` | lásd lent | választható modellek `modell[=kredit][@szerep]` alakban, vesszővel elválasztva; az első az alapértelmezett, és ahhoz nem kellhet szerep |
|
||||
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | ez írja a fizetős részletes elemzéseket |
|
||||
| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
|
||||
| `ANALYSIS_PROMPT_VERSION` | `v2` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
|
||||
| `MAX_CHARTS_PER_USER` | `50` | ennyi képletet menthet egy felhasználó |
|
||||
@@ -35,7 +33,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
- **Google:** a frontend a Google Identity Services gombbal vagy a One Tap felülettel szerez ID tokent, és elküldi a `POST /v1/auth/google` végpontra. A backend Google kulcsaival ellenőrzi az aláírást, a kiállítót és a kliens-azonosítót.
|
||||
- Ismeretlen Google-fióknál, ha a Google által igazolt e-mail-címmel már van felhasználó, ahhoz kapcsolja; ha nincs, újat hoz létre.
|
||||
- Ugyanaz a felhasználó több belépési móddal is rendelkezhet (`auth_identities`). A Facebook, az Apple és a passkey ugyanígy adható hozzá.
|
||||
- **Szerepek** (`users.roles`, tömb): `user` (alap), `creator` (cikkírás, 2. fázis), `premium` és `vip` (előfizetési szintek, amíg nincs fizetés, az admin osztja ki), `admin`.
|
||||
- **Szerepek** (`users.roles`, tömb): `user` (alap), `creator` (cikkírás, 2. fázis), `premium` és `vip` (jelenleg nincs hozzájuk funkció; a fizetős elemzés egységekkel megy), `admin`.
|
||||
- **Guardok:**
|
||||
- `AuthUser`: belépés kell (401);
|
||||
- `AdminUser`: admin szerep is kell (403).
|
||||
@@ -46,7 +44,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
|
||||
| Végpont | Guard | Leírás |
|
||||
|---|---|---|
|
||||
| `GET /v1/config` | – | Google kliens-azonosító, `password_login`, nyelvek, modellek, kreditárak |
|
||||
| `GET /v1/config` | – | Google kliens-azonosító, `password_login`, nyelvek, elemző és összefoglaló modell |
|
||||
| `POST /v1/auth/register` | – | `{email, password, display_name?, locale?}` → munkamenet; megerősítő e-mailt küld |
|
||||
| `POST /v1/auth/login` | – | `{email, password}` |
|
||||
| `POST /v1/auth/google` | – | `{id_token}`; `created: true`, ha most jött létre a fiók |
|
||||
@@ -58,7 +56,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
| `GET`/`PATCH`/`DELETE /v1/me` | user | profil (`display_name`, `locale`); törlés: `{confirm: "DELETE"}` |
|
||||
| `POST /v1/me/password` | user | `{current_password?, new_password}`; Google-fiókhoz jelszót is ad |
|
||||
| `GET /v1/me/export` | user | GDPR: minden adat egy JSON-ban |
|
||||
| `GET /v1/credits` | user | egyenleg és kreditmozgások |
|
||||
| `GET /v1/credits` | user | megmaradt elemzések típusonként (`balance: {natal, synastry}`) és a mozgások |
|
||||
| `GET`/`POST /v1/charts` | user | képletek listája; új képlet: `{label, is_primary, birth}`, ahol a `birth` a horoscope-api `/v1/natal` kérésformátuma |
|
||||
| `GET`/`PATCH`/`DELETE /v1/charts/{id}` | tulajdonos | a születési adat nem módosítható: a javított képlet új képlet. Ugyanarra a születési adatra a `POST /v1/charts` a meglévő képletet adja vissza (200), nem számol újat |
|
||||
| `POST /v1/charts/{id}/summary` | tulajdonos | az ingyenes rövid összefoglaló (`kind: summary`, `{title, summary}`); mentéskor magától sorba áll, ez visszaadja, és ha elbukott, újra sorba állítja |
|
||||
@@ -73,9 +71,9 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
| `GET /v1/analyses/{id}` | jogosult | |
|
||||
| `GET`/`POST /v1/shares`, `DELETE /v1/shares/{id}` | user | `{kind: chart\|synastry\|analysis, target_id, title?, show_birth_data?}` |
|
||||
| `GET /v1/public/shares/{slug}` | – | a megosztott tartalom (oldal + OG-kép adatai) |
|
||||
| `GET /v1/admin/users?q=` | admin | felhasználók kereséssel, szerepekkel, kreditekkel |
|
||||
| `GET /v1/admin/users?q=` | admin | felhasználók kereséssel, szerepekkel, megmaradt elemzésekkel |
|
||||
| `PATCH /v1/admin/users/{id}` | admin | `{roles: [...]}`; a saját admin szerep nem vehető el |
|
||||
| `POST /v1/admin/users/{id}/credits` | admin | `{delta, note?}` |
|
||||
| `POST /v1/admin/users/{id}/credits` | admin | `{unit: natal\|synastry, delta, note?}`: elemzések jóváírása vagy levonása |
|
||||
|
||||
Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái (például ismeretlen hely, javaslatokkal együtt) változatlanul jönnek tovább a horoscope-api-ból.
|
||||
|
||||
@@ -90,7 +88,7 @@ Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái
|
||||
| `synastries` | két képlet összevetése (`result`: fényszögek, házak, kompozit), `synastry_hash` |
|
||||
| `synastry_invites` | meghívó linkek: token hash, lejárat, ki fogadta el, melyik szinasztria lett belőle |
|
||||
| `analyses` | szöveges elemzések: típus, nyelv, modell, promptverzió, `cache_key`, állapot (`pending` → `running` → `done`/`failed`), strukturált `content` |
|
||||
| `credit_ledger` | csak hozzáírható kreditnapló; az egyenleg `SUM(delta)`; havi keret lustán, egyszer havonta |
|
||||
| `credit_ledger` | csak hozzáírható egységnapló (`unit`: `natal` vagy `synastry`); az egyenleg típusonként `SUM(delta)` |
|
||||
| `shares` | nyilvános linkek: véletlen `slug`, mit mutat, `show_birth_data`, nézettség, visszavonás |
|
||||
| `email_outbox` | kimenő e-mailek; a worker küldi ki (újrapróbálással) |
|
||||
|
||||
@@ -100,24 +98,16 @@ Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái
|
||||
- A szinasztria másik fele csak a pozíciókat látja, a születési adatokat nem.
|
||||
- A fiók törlése mindent töröl, ami a felhasználóhoz tartozik, beleértve a más által létrehozott, de az ő képletét használó szinasztriákat is.
|
||||
|
||||
## Elemzések és kreditek
|
||||
## Elemzések és egységek
|
||||
|
||||
- **Modellek és szintek:** az alapértelmezett beállítás
|
||||
|
||||
```
|
||||
LLM_MODELS=anthropic/claude-haiku-5.5=1,openai/gpt-5.6-terra=3@premium,anthropic/claude-opus-5.5=10@vip
|
||||
```
|
||||
|
||||
- **Haiku 5.5:** az ingyenes szint, 1 kredit.
|
||||
- **GPT-5.6 Terra:** `premium` szerep kell hozzá, 3 kredit.
|
||||
- **Opus 5.5:** privát/VIP célra, `vip` szerep kell hozzá, 10 kredit.
|
||||
|
||||
A `vip` szerep a premium modelleket is megnyitja, az `admin` mindent. Szerep nélkül 403 `forbidden` a válasz. A `GET /v1/config` és a `GET /v1/credits` visszaadja a listát (`llm_models: [{id, credits, role}]`, illetve `default_model`). A választás egy 2026-11-ben, egy asztrológus értékelésével lefutott összevetésen alapul (lásd `services/worker/README.md`).
|
||||
- **Kérés:** a `POST .../analyses` (`{language?, model?}`) létrehoz egy `pending` elemzést, és levonja a választott modell kreditárát; a szöveget a worker írja meg, általában 1–2 perc alatt. A kliens a `GET /v1/analyses/{id}` végponton kérdezi le az állapotát. Ha nincs elég kredit, 402 `insufficient_credits` a válasz.
|
||||
- **Ingyenes rész:** minden mentett képlethez elkészül egy rövid összefoglaló (`summary`, `SUMMARY_MODEL`), ezért nem kell fizetni.
|
||||
- **Fizetős rész:** a részletes elemzés darabra megy. A képletelemzés egy `natal`, a szinasztria-elemzés egy `synastry` egységet von le (`credit_ledger.unit`). Az egységek csomagvásárlásból (Stripe, később) vagy admin jóváírásból jönnek. Havi ingyenes keret nincs.
|
||||
- **Modell:** egyetlen, az `ANALYSIS_MODEL` (alapból Opus 5.5, a 2026-11-es összevetés legjobbja, lásd `services/worker/README.md`). A kliens nem választ modellt.
|
||||
- **Kérés:** a `POST .../analyses` (`{language?}`) létrehoz egy `pending` elemzést, és levon egy egységet; a szöveget a worker írja meg, általában 1–2 perc alatt. A kliens a `GET /v1/analyses/{id}` végponton kérdezi le az állapotát. Ha nincs egység, 402 `insufficient_credits` a válasz (`unit`, `balance` részletekkel). Hiba esetén a worker visszaadja az egységet.
|
||||
- **Gyorsítótár:** a kulcs `sha256(típus | képlet- vagy szinasztria-hash | promptverzió | modell | nyelv)`.
|
||||
- Ha ugyanarra a képletre már kértek ilyet, ugyanazt adja vissza (200).
|
||||
- Ha bárhol van kész elemzés ugyanezzel a kulccsal (például ugyanaz a születési adat egy másik felhasználónál), ingyen átmásolja (201, `done`).
|
||||
|
||||
## Háttérmunkák
|
||||
|
||||
A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket (OpenRouter, strukturált JSON; hibánál visszaadja a kreditet), és óránként takarít. Még hátravan az elemzés streamelése a frontend felé.
|
||||
A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket (OpenRouter, strukturált JSON; hibánál visszaadja az egységet), és óránként takarít. Még hátravan az elemzés streamelése a frontend felé.
|
||||
|
||||
@@ -1,57 +1,6 @@
|
||||
//! Configuration from the environment.
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use db::Role;
|
||||
use serde::Serialize;
|
||||
|
||||
/// A model users may choose for analyses.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct LlmModel {
|
||||
/// OpenRouter model id.
|
||||
pub id: String,
|
||||
/// Credits charged per new analysis.
|
||||
pub credits: i32,
|
||||
/// Role needed to use it (`None`: everyone).
|
||||
pub role: Option<Role>,
|
||||
}
|
||||
|
||||
/// Parses `id[=credits][@role]` entries; `credits` defaults to `default_credits`.
|
||||
fn parse_models(entries: &[String], default_credits: i32) -> anyhow::Result<Vec<LlmModel>> {
|
||||
entries
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let (rest, role) = match entry.split_once('@') {
|
||||
Some((rest, role)) => {
|
||||
let role = Role::parse(role.trim())
|
||||
.with_context(|| format!("unknown role '{role}' in LLM_MODELS entry '{entry}'"))?;
|
||||
(rest, Some(role))
|
||||
}
|
||||
None => (entry.as_str(), None),
|
||||
};
|
||||
let (id, credits) = match rest.split_once('=') {
|
||||
Some((id, credits)) => (
|
||||
id,
|
||||
credits
|
||||
.trim()
|
||||
.parse::<i32>()
|
||||
.ok()
|
||||
.filter(|c| *c >= 0)
|
||||
.with_context(|| format!("invalid credits in LLM_MODELS entry '{entry}'"))?,
|
||||
),
|
||||
None => (rest, default_credits),
|
||||
};
|
||||
let id = id.trim();
|
||||
if id.is_empty() {
|
||||
bail!("empty model id in LLM_MODELS entry '{entry}'");
|
||||
}
|
||||
Ok(LlmModel { id: id.to_owned(), credits, role })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Free tier, paid tier, VIP tier (model choice of 2026-11).
|
||||
const DEFAULT_LLM_MODELS: &str =
|
||||
"anthropic/claude-haiku-5.5=1,openai/gpt-5.6-terra=3@premium,anthropic/claude-opus-5.5=10@vip";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
@@ -85,13 +34,9 @@ pub struct Config {
|
||||
pub bootstrap_admin_emails: Vec<String>,
|
||||
/// `SUPPORTED_LOCALES` (default `hu,en`); the first is the default.
|
||||
pub supported_locales: Vec<String>,
|
||||
/// `MONTHLY_FREE_CREDITS` (default 10).
|
||||
pub monthly_free_credits: i32,
|
||||
/// `LLM_MODELS`: comma-separated `model[=credits][@role]` entries users
|
||||
/// may choose from; the first is the default and should need no role.
|
||||
/// Credits default to `ANALYSIS_COST` (default 1). Default:
|
||||
/// [`DEFAULT_LLM_MODELS`].
|
||||
pub llm_models: Vec<LlmModel>,
|
||||
/// `ANALYSIS_MODEL`: writes the paid detailed analyses (default
|
||||
/// `anthropic/claude-opus-5.5`, the best of the 2026-11 comparison).
|
||||
pub analysis_model: String,
|
||||
/// `SUMMARY_MODEL`: writes the free short summary of every saved chart
|
||||
/// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each).
|
||||
pub summary_model: String,
|
||||
@@ -133,18 +78,6 @@ impl Config {
|
||||
if supported_locales.is_empty() {
|
||||
supported_locales = vec!["hu".into(), "en".into()];
|
||||
}
|
||||
let analysis_cost: i32 = parsed("ANALYSIS_COST", 1)?;
|
||||
if analysis_cost < 0 {
|
||||
bail!("ANALYSIS_COST must not be negative");
|
||||
}
|
||||
let mut model_entries = list("LLM_MODELS");
|
||||
if model_entries.is_empty() {
|
||||
model_entries = DEFAULT_LLM_MODELS.split(',').map(str::to_owned).collect();
|
||||
}
|
||||
let llm_models = parse_models(&model_entries, analysis_cost)?;
|
||||
if llm_models[0].role.is_some() {
|
||||
bail!("the first LLM_MODELS entry is the default and must not need a role");
|
||||
}
|
||||
let config = Self {
|
||||
database_url: var("DATABASE_URL").context("DATABASE_URL is required")?,
|
||||
horoscope_api_url: var("HOROSCOPE_API_URL").unwrap_or_else(|| "http://localhost:8080".into()),
|
||||
@@ -159,8 +92,7 @@ impl Config {
|
||||
.unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()),
|
||||
bootstrap_admin_emails: list("BOOTSTRAP_ADMIN_EMAILS").into_iter().map(|e| e.to_lowercase()).collect(),
|
||||
supported_locales,
|
||||
monthly_free_credits: parsed("MONTHLY_FREE_CREDITS", 10)?,
|
||||
llm_models,
|
||||
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
|
||||
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()),
|
||||
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()),
|
||||
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 50)?,
|
||||
@@ -168,9 +100,6 @@ impl Config {
|
||||
if config.session_ttl_days < 1 {
|
||||
bail!("SESSION_TTL_DAYS must be at least 1");
|
||||
}
|
||||
if config.monthly_free_credits < 0 {
|
||||
bail!("MONTHLY_FREE_CREDITS must not be negative");
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
@@ -190,39 +119,10 @@ impl Config {
|
||||
google_jwks_url,
|
||||
bootstrap_admin_emails: vec!["admin@example.com".into()],
|
||||
supported_locales: vec!["hu".into(), "en".into()],
|
||||
monthly_free_credits: 2,
|
||||
llm_models: parse_models(
|
||||
&["openrouter/auto".into(), "anthropic/claude-test=1".into(), "anthropic/claude-vip=2@vip".into()],
|
||||
1,
|
||||
)
|
||||
.unwrap(),
|
||||
analysis_model: "anthropic/claude-test".into(),
|
||||
summary_model: "anthropic/claude-summary".into(),
|
||||
prompt_version: "v1".into(),
|
||||
max_charts_per_user: 50,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_model_entries() {
|
||||
let models = parse_models(&DEFAULT_LLM_MODELS.split(',').map(str::to_owned).collect::<Vec<_>>(), 1).unwrap();
|
||||
assert_eq!(
|
||||
models,
|
||||
vec![
|
||||
LlmModel { id: "anthropic/claude-haiku-5.5".into(), credits: 1, role: None },
|
||||
LlmModel { id: "openai/gpt-5.6-terra".into(), credits: 3, role: Some(Role::Premium) },
|
||||
LlmModel { id: "anthropic/claude-opus-5.5".into(), credits: 10, role: Some(Role::Vip) },
|
||||
]
|
||||
);
|
||||
let models = parse_models(&["a/b:free".into(), "c/d@vip".into()], 2).unwrap();
|
||||
assert_eq!((models[0].id.as_str(), models[0].credits), ("a/b:free", 2));
|
||||
assert_eq!((models[1].credits, models[1].role), (2, Some(Role::Vip)));
|
||||
assert!(parse_models(&["a/b@boss".into()], 1).is_err());
|
||||
assert!(parse_models(&["a/b=-1".into()], 1).is_err());
|
||||
assert!(parse_models(&["=3".into()], 1).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -24,8 +24,8 @@ pub enum ApiError {
|
||||
Gone(String),
|
||||
#[error("the link is invalid or has expired")]
|
||||
InvalidToken,
|
||||
#[error("not enough credits: {needed} needed, {balance} available")]
|
||||
InsufficientCredits { needed: i32, balance: i64 },
|
||||
#[error("no {unit} analysis left (balance {balance})")]
|
||||
InsufficientCredits { unit: &'static str, balance: i64 },
|
||||
#[error("too many attempts; try again later")]
|
||||
TooManyRequests,
|
||||
/// Birth data rejected by the horoscope service; its error object is passed through.
|
||||
|
||||
@@ -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,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() }))))
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
}))
|
||||
|
||||
@@ -222,7 +222,7 @@ async fn register_login_verify_logout(pool: PgPool) {
|
||||
let r = app.get("/v1/me", Some(&token)).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.body["providers"], json!(["password"]));
|
||||
assert_eq!(r.body["credits"], 2);
|
||||
assert_eq!(r.body["analyses_left"], json!({"natal": 0, "synastry": 0}));
|
||||
|
||||
// e-mail verification through the queued e-mail's link
|
||||
let url = app.outbox_url("anna@example.com", "verify_email").await;
|
||||
@@ -341,10 +341,14 @@ async fn roles_and_admin_guard(pool: PgPool) {
|
||||
app.call("PATCH", &format!("/v1/admin/users/{admin_id}"), Some(&admin), Some(json!({"roles": ["user"]}))).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT);
|
||||
|
||||
let r =
|
||||
app.post(&format!("/v1/admin/users/{anna}/credits"), Some(&admin), json!({"delta": 5, "note": "bonus"})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED);
|
||||
assert_eq!(app.get("/v1/credits", Some(&user)).await.body["balance"], 7); // 2 monthly + 5
|
||||
let grant = |unit: &str, delta: i32| json!({"unit": unit, "delta": delta, "note": "bonus"});
|
||||
let r = app.post(&format!("/v1/admin/users/{anna}/credits"), Some(&admin), grant("natal", 5)).await;
|
||||
assert_eq!((r.status, &r.body["analyses_left"]), (StatusCode::CREATED, &json!({"natal": 5, "synastry": 0})));
|
||||
let r = app.post(&format!("/v1/admin/users/{anna}/credits"), Some(&admin), grant("chat", 5)).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
let credits = app.get("/v1/credits", Some(&user)).await.body;
|
||||
assert_eq!(credits["balance"], json!({"natal": 5, "synastry": 0}));
|
||||
assert_eq!((credits["ledger"][0]["unit"].as_str(), &credits["ledger"][0]["delta"]), (Some("natal"), &json!(5)));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -456,8 +460,22 @@ async fn invitation_links_two_users(pool: PgPool) {
|
||||
assert!(app.outbox_url("anna@example.com", "invite_accepted").await.ends_with(&synastry_id));
|
||||
}
|
||||
|
||||
/// Gives `token`'s user analysis units (the admin endpoint is tested in `roles_and_admin_guard`).
|
||||
async fn grant_units(app: &TestApp, token: &str, unit: &str, delta: i32) {
|
||||
let id = app.get("/v1/me", Some(token)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason) VALUES (gen_random_uuid(), $1::uuid, $2, $3, 'purchase')",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(unit)
|
||||
.bind(delta)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn analyses_spend_credits_and_reuse_results(pool: PgPool) {
|
||||
async fn analyses_spend_units_and_reuse_results(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
@@ -472,26 +490,32 @@ async fn analyses_spend_credits_and_reuse_results(pool: PgPool) {
|
||||
);
|
||||
let r = app.call("POST", &format!("/v1/charts/{}/summary", chart["id"].as_str().unwrap()), Some(&anna), None).await;
|
||||
assert_eq!((r.status, &r.body["id"]), (StatusCode::OK, &summary["id"]));
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], 2);
|
||||
|
||||
// the detailed analysis is paid: no unit, no analysis
|
||||
let r = app.call("POST", &uri, Some(&anna), None).await;
|
||||
assert_eq!(
|
||||
(r.status, r.body["error"]["code"].as_str()),
|
||||
(StatusCode::PAYMENT_REQUIRED, Some("insufficient_credits"))
|
||||
);
|
||||
grant_units(&app, &anna, "natal", 2).await;
|
||||
|
||||
let r = app.call("POST", &uri, Some(&anna), None).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
assert_eq!((r.body["status"].as_str(), r.body["language"].as_str()), (Some("pending"), Some("hu")));
|
||||
assert_eq!(
|
||||
(r.body["status"].as_str(), r.body["language"].as_str(), r.body["model"].as_str(), &r.body["credits_charged"]),
|
||||
(Some("pending"), Some("hu"), Some("anthropic/claude-test"), &json!(1))
|
||||
);
|
||||
let first = r.body["id"].as_str().unwrap().to_string();
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], 1);
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], json!({"natal": 1, "synastry": 0}));
|
||||
|
||||
// same request again: the same analysis, no charge
|
||||
let r = app.call("POST", &uri, Some(&anna), None).await;
|
||||
assert_eq!((r.status, r.body["id"].as_str()), (StatusCode::OK, Some(first.as_str())));
|
||||
let r = app.post(&uri, Some(&anna), json!({"language": "en"})).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
let r = app.post(&uri, Some(&anna), json!({"model": "anthropic/claude-test"})).await;
|
||||
assert_eq!(
|
||||
(r.status, r.body["error"]["code"].as_str()),
|
||||
(StatusCode::PAYMENT_REQUIRED, Some("insufficient_credits"))
|
||||
);
|
||||
let r = app.post(&uri, Some(&anna), json!({"model": "unknown/model"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], json!({"natal": 0, "synastry": 0}));
|
||||
let r = app.post(&uri, Some(&anna), json!({"model": "anthropic/claude-other"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST); // no model choice
|
||||
|
||||
// the worker finishes the first one; another user with the same birth data gets it for free
|
||||
sqlx::query("UPDATE analyses SET status = 'done', content = $1, completed_at = now() WHERE id = $2::uuid")
|
||||
@@ -506,7 +530,6 @@ async fn analyses_spend_credits_and_reuse_results(pool: PgPool) {
|
||||
let r = app.call("POST", &format!("/v1/charts/{}/analyses", same["id"].as_str().unwrap()), Some(&bela), None).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!((r.body["status"].as_str(), &r.body["credits_charged"]), (Some("done"), &json!(0)));
|
||||
assert_eq!(app.get("/v1/credits", Some(&bela)).await.body["balance"], 2);
|
||||
|
||||
assert_eq!(app.get(&format!("/v1/analyses/{first}"), Some(&bela)).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get(&uri, Some(&anna)).await.body["analyses"].as_array().unwrap().len(), 3); // 2 + summary
|
||||
@@ -606,30 +629,26 @@ async fn public_config_and_health(pool: PgPool) {
|
||||
assert_eq!(r.body["google_login"]["enabled"], true);
|
||||
assert_eq!(r.body["google_login"]["client_id"], GOOGLE_CLIENT);
|
||||
assert_eq!(r.body["locales"], json!(["hu", "en"]));
|
||||
assert_eq!(r.body["default_model"], "openrouter/auto");
|
||||
assert_eq!(r.body["llm_models"][2], json!({"id": "anthropic/claude-vip", "credits": 2, "role": "vip"}));
|
||||
assert_eq!(r.body["analysis_model"], "anthropic/claude-test");
|
||||
assert_eq!(r.body["summary_model"], "anthropic/claude-summary");
|
||||
assert_eq!(app.get("/healthz", None).await.status, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn tier_models_need_their_role(pool: PgPool) {
|
||||
async fn synastry_analyses_use_synastry_units(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
let uri = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap());
|
||||
let vip = json!({"model": "anthropic/claude-vip"});
|
||||
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
let other = app.chart(&anna, "Anya", false, "1950-03-01").await;
|
||||
let r = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": other["id"]})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let uri = format!("/v1/synastries/{}/analyses", r.body["id"].as_str().unwrap());
|
||||
|
||||
let r = app.post(&uri, Some(&anna), vip.clone()).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("forbidden")));
|
||||
|
||||
let anna_id = app.get("/v1/me", Some(&anna)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
let r = app
|
||||
.call("PATCH", &format!("/v1/admin/users/{anna_id}"), Some(&admin), Some(json!({"roles": ["user", "vip"]})))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let r = app.post(&uri, Some(&anna), vip).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
assert_eq!((r.body["model"].as_str(), &r.body["credits_charged"]), (Some("anthropic/claude-vip"), &json!(2)));
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], 0);
|
||||
grant_units(&app, &anna, "natal", 1).await;
|
||||
let r = app.call("POST", &uri, Some(&anna), None).await;
|
||||
assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED); // a natal unit does not pay for a synastry
|
||||
grant_units(&app, &anna, "synastry", 1).await;
|
||||
let r = app.call("POST", &uri, Some(&anna), None).await;
|
||||
assert_eq!((r.status, r.body["kind"].as_str()), (StatusCode::ACCEPTED, Some("synastry")));
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], json!({"natal": 1, "synastry": 0}));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user