Tarot readings: AI-written, drawn on the server, sold as units
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 5m52s
CI / deploy (push) Skipped

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
This commit is contained in:
feco
2026-11-20 14:35:50 +00:00
co-authored by Claude Opus 5.5
parent 54af54cd39
commit b0fc547b73
36 changed files with 2957 additions and 46 deletions
+16 -7
View File
@@ -1,8 +1,8 @@
//! Analysis units: a detailed natal analysis uses one `natal` unit, a
//! synastry analysis one `synastry` unit, a yearly forecast one `forecast`
//! unit, a question about an analysis one `question` unit. Units come from
//! purchases or an admin; a failed analysis or answer gives its unit back
//! (the worker does that).
//! unit, a question about an analysis one `question` unit, a tarot reading one
//! `tarot` unit. Units come from purchases or an admin; a failed analysis or
//! answer gives its unit back (the worker does that).
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -22,6 +22,8 @@ pub enum Unit {
Person,
/// A question about a finished analysis (see `routes::questions`).
Question,
/// A tarot reading (see `routes::tarot`).
Tarot,
}
impl Unit {
@@ -32,6 +34,7 @@ impl Unit {
Unit::Forecast => "forecast",
Unit::Person => "person",
Unit::Question => "question",
Unit::Tarot => "tarot",
}
}
}
@@ -45,6 +48,7 @@ pub struct Balance {
/// Bought person slots (not the slots left; see [`crate::persons::slots`]).
pub person: i64,
pub question: i64,
pub tarot: i64,
}
impl Balance {
@@ -55,27 +59,32 @@ impl Balance {
Unit::Forecast => self.forecast,
Unit::Person => self.person,
Unit::Question => self.question,
Unit::Tarot => self.tarot,
}
}
pub fn view(self) -> Value {
json!({ "natal": self.natal, "synastry": self.synastry, "forecast": self.forecast, "question": self.question })
json!({
"natal": self.natal, "synastry": self.synastry, "forecast": self.forecast, "question": self.question,
"tarot": self.tarot,
})
}
}
pub async fn balance(conn: &mut PgConnection, user_id: Uuid) -> Result<Balance, ApiError> {
let (natal, synastry, forecast, person, question): (i64, i64, i64, i64, i64) = sqlx::query_as(
let (natal, synastry, forecast, person, question, tarot): (i64, i64, i64, i64, i64, i64) = sqlx::query_as(
"SELECT COALESCE(SUM(delta) FILTER (WHERE unit = 'natal'), 0)::bigint, \
COALESCE(SUM(delta) FILTER (WHERE unit = 'synastry'), 0)::bigint, \
COALESCE(SUM(delta) FILTER (WHERE unit = 'forecast'), 0)::bigint, \
COALESCE(SUM(delta) FILTER (WHERE unit = 'person' AND reason <> 'person'), 0)::bigint, \
COALESCE(SUM(delta) FILTER (WHERE unit = 'question'), 0)::bigint \
COALESCE(SUM(delta) FILTER (WHERE unit = 'question'), 0)::bigint, \
COALESCE(SUM(delta) FILTER (WHERE unit = 'tarot'), 0)::bigint \
FROM credit_ledger WHERE user_id = $1",
)
.bind(user_id)
.fetch_one(conn)
.await?;
Ok(Balance { natal, synastry, forecast, person, question })
Ok(Balance { natal, synastry, forecast, person, question, tarot })
}
/// Spends one unit inside the caller's transaction. The user row is locked
+31 -4
View File
@@ -45,11 +45,13 @@ pub struct Package {
pub persons: i64,
/// Questions about the user's analyses and forecasts.
pub questions: i64,
/// Tarot readings.
pub tarot: i64,
/// Badge on the card ("Legnépszerűbb").
pub badge: Option<&'static str>,
}
pub const CATALOG: [Package; 7] = [
pub const CATALOG: [Package; 8] = [
Package {
id: "single",
name: "Egy elemzés",
@@ -61,6 +63,7 @@ pub const CATALOG: [Package; 7] = [
forecast: 0,
persons: 0,
questions: QUESTIONS_INCLUDED,
tarot: 2,
badge: None,
},
Package {
@@ -74,6 +77,7 @@ pub const CATALOG: [Package; 7] = [
forecast: 2,
persons: 1,
questions: QUESTIONS_INCLUDED,
tarot: 5,
badge: None,
},
Package {
@@ -87,6 +91,7 @@ pub const CATALOG: [Package; 7] = [
forecast: 6,
persons: 5,
questions: QUESTIONS_INCLUDED,
tarot: 10,
badge: Some("Legnépszerűbb"),
},
Package {
@@ -100,6 +105,7 @@ pub const CATALOG: [Package; 7] = [
forecast: 0,
persons: 0,
questions: 0,
tarot: 0,
badge: None,
},
Package {
@@ -113,6 +119,7 @@ pub const CATALOG: [Package; 7] = [
forecast: 1,
persons: 0,
questions: 0,
tarot: 0,
badge: None,
},
Package {
@@ -126,6 +133,7 @@ pub const CATALOG: [Package; 7] = [
forecast: 0,
persons: 5,
questions: 0,
tarot: 0,
badge: None,
},
Package {
@@ -139,6 +147,21 @@ pub const CATALOG: [Package; 7] = [
forecast: 0,
persons: 0,
questions: 5,
tarot: 0,
badge: None,
},
Package {
id: "addon_tarot",
name: "+5 kártyajóslás",
tagline: "Öt újabb kártyajóslás a saját kérdéseidre.",
tier: Tier::Addon,
price_huf: 1_000,
natal: 0,
synastry: 0,
forecast: 0,
persons: 0,
questions: 0,
tarot: 5,
badge: None,
},
];
@@ -171,6 +194,7 @@ impl Package {
"forecast": self.forecast,
"persons": self.persons,
"questions": self.questions,
"tarot": self.tarot,
"badge": self.badge,
"list_price_huf": list,
"savings_percent": savings,
@@ -210,6 +234,7 @@ impl Package {
(self.forecast, "éves előrejelzés"),
(self.persons, "személyhely"),
(self.questions, "kérdés"),
(self.tarot, "kártyajóslás"),
]
.into_iter()
.filter(|&(n, _)| n > 0)
@@ -232,6 +257,7 @@ impl Package {
(self.forecast, "éves előrejelzés"),
(self.persons, "további személy felvétele"),
(self.questions, "kérdés"),
(self.tarot, "kártyaértelmezés"),
]
.into_iter()
.filter(|&(n, _)| n > 0)
@@ -246,13 +272,14 @@ impl Package {
}
/// What the package gives, unit by unit.
pub fn contents(&self) -> [(Unit, i64); 5] {
pub fn contents(&self) -> [(Unit, i64); 6] {
[
(Unit::Natal, self.natal),
(Unit::Synastry, self.synastry),
(Unit::Forecast, self.forecast),
(Unit::Person, self.persons),
(Unit::Question, self.questions),
(Unit::Tarot, self.tarot),
]
}
}
@@ -392,8 +419,8 @@ mod tests {
assert_eq!(
comment,
"Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: \
2 képletelemzés, 1 kapcsolati elemzés, 2 éves előrejelzés, 1 további személy felvétele, 3 kérdés. \
Digitális tartalom."
2 képletelemzés, 1 kapcsolati elemzés, 2 éves előrejelzés, 1 további személy felvétele, 3 kérdés, \
5 kártyaértelmezés. Digitális tartalom."
);
let (name, comment) = find("addon_persons").unwrap().invoice_item();
assert_eq!(name, "Online tartalomszolgáltatás – +5 személy kiegészítő");
+9 -2
View File
@@ -185,7 +185,7 @@ pub struct DeleteMe {
}
/// GDPR: deletes the account and everything that belongs to it (charts,
/// synastries using them, analyses, shares, sessions, credits).
/// synastries using them, analyses, tarot readings, shares, sessions, credits).
pub async fn delete_me(
State(state): St,
auth: AuthUser,
@@ -195,7 +195,14 @@ pub async fn delete_me(
if req.confirm != "DELETE" {
return Err(ApiError::BadRequest("set confirm to \"DELETE\" to delete the account".into()));
}
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&state.db).await?;
let mut tx = state.db.begin().await?;
// Tarot readings belong to no chart: they go with the account.
sqlx::query("DELETE FROM analyses WHERE kind = 'tarot' AND requested_by = $1")
.bind(auth.id())
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), "account deleted");
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
}
+7 -3
View File
@@ -46,6 +46,7 @@ pub async fn list_users(
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, \
@@ -53,7 +54,8 @@ pub async fn list_users(
(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 = '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",
@@ -65,12 +67,14 @@ pub async fn list_users(
.await?;
let users: Vec<Value> = rows
.into_iter()
.map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, forecast, question)| {
.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},
"analyses_left": {
"natal": natal, "synastry": synastry, "forecast": forecast, "question": question, "tarot": tarot,
},
})
})
.collect();
+13 -6
View File
@@ -386,11 +386,18 @@ pub async fn regenerate(
if row.status == "pending" || row.status == "running" {
return Err(ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül."));
}
let kind = Kind::parse(&row.kind).ok_or_else(|| ApiError::Internal(format!("unknown kind {}", row.kind)))?;
let hash = target_hash(&state.db, &row).await?;
let hash = hash.ok_or(ApiError::NotFound("analysis"))?;
let (model, fallback) = crate::models::models_for(&state, kind).await?;
let (cache_key, prompt_version) = versions(&state, kind.as_str(), &hash, &model, &row.language).await?;
let (kind, model, fallback, cache_key, prompt_version) = if row.kind == "tarot" {
// A tarot reading: the analysis model, the same cards, never cached.
let (model, fallback) = crate::models::models_for(&state, Kind::Natal).await?;
("tarot", model, fallback, format!("tarot|{id}"), state.config.prompt_version.clone())
} else {
let kind = Kind::parse(&row.kind).ok_or_else(|| ApiError::Internal(format!("unknown kind {}", row.kind)))?;
let hash = target_hash(&state.db, &row).await?;
let hash = hash.ok_or(ApiError::NotFound("analysis"))?;
let (model, fallback) = crate::models::models_for(&state, kind).await?;
let (cache_key, prompt_version) = versions(&state, kind.as_str(), &hash, &model, &row.language).await?;
(kind.as_str(), model, fallback, cache_key, prompt_version)
};
let mut tx = state.db.begin().await?;
let row: AnalysisRow = sqlx::query_as(&format!(
"UPDATE analyses SET status = 'pending', content = NULL, error = NULL, model_used = NULL, \
@@ -410,6 +417,6 @@ pub async fn regenerate(
// Wakes the worker, as a new analysis does.
sqlx::query("SELECT pg_notify('analyses', '')").execute(&mut *tx).await?;
tx.commit().await?;
tracing::info!(%id, kind = kind.as_str(), "analysis regenerated");
tracing::info!(%id, kind, "analysis regenerated");
Ok(Json(row.view()))
}
+3
View File
@@ -23,6 +23,7 @@ mod questions;
mod recalculate;
mod shares;
mod synastries;
mod tarot;
pub use recalculate::run as recalculate;
@@ -102,6 +103,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/analyses/{id}", get(analyses::get_one))
.route("/v1/analyses/{id}/questions", get(questions::list).post(questions::ask))
.route("/v1/questions/{id}", get(questions::get_one))
.route("/v1/tarot/readings", get(tarot::list).post(tarot::create))
.route("/v1/tarot/readings/{id}", get(tarot::get_one))
// sharing
.route("/v1/promo-codes/redeem", post(promo::redeem))
.route("/v1/admin/promo-codes", get(promo::list).post(promo::create))
+1
View File
@@ -64,6 +64,7 @@ pub async fn mock(
(None, Some(Unit::Forecast)) => "addon_forecast",
(None, Some(Unit::Person)) => "addon_persons",
(None, Some(Unit::Question)) => "addon_questions",
(None, Some(Unit::Tarot)) => "addon_tarot",
_ => return Err(ApiError::BadRequest("give either package or unit".into())),
};
let package = packages::find(id).ok_or(ApiError::NotFound("package"))?;
+3 -2
View File
@@ -1,6 +1,6 @@
//! `backend recalculate`: after a change in the calculation, recalculates
//! every stored chart, comparison and forecast with the horoscope service,
//! then deletes all analyses and queues them again: a short summary and a
//! then deletes all analyses (but the tarot readings) and queues them again: a short summary and a
//! detailed analysis for every chart, one analysis for every comparison and
//! every forecast. Nobody is charged; each analysis is requested in the name
//! of the owner, in the owner's language.
@@ -90,7 +90,8 @@ pub async fn run(state: &AppState) -> anyhow::Result<()> {
}
tracing::info!(count = forecast_hashes.len(), "forecasts recalculated");
let deleted = sqlx::query("DELETE FROM analyses").execute(db).await?.rows_affected();
// Tarot readings depend on no calculation: they stay.
let deleted = sqlx::query("DELETE FROM analyses WHERE kind <> 'tarot'").execute(db).await?.rows_affected();
let mut queued = 0;
for c in &charts {
let language = locale(db, c.owner_id).await?;
+212
View File
@@ -0,0 +1,212 @@
//! Tarot readings. The server shuffles and draws the cards (so nobody can
//! draw again for free until a card they like comes), stores them with the
//! question as a `tarot` analysis and spends one `tarot` unit; the worker
//! writes the reading with the model of the detailed analyses. A failed
//! reading gives its unit back.
use analysis_prompt::tarot::{self, Spread};
use analysis_prompt::{Kind, TAROT_QUESTION_MAX_CHARS};
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use rand::seq::SliceRandom;
use rand::{Rng, rng};
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::{Body, IdPath, St};
use crate::auth::AuthUser;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, rfc3339_opt};
/// How often a card comes up reversed.
const REVERSED_SHARE: f64 = 0.28;
/// The readings listed on the page, newest first.
const LIST_LIMIT: i64 = 100;
#[derive(Debug, sqlx::FromRow)]
pub struct ReadingRow {
pub id: Uuid,
pub status: String,
pub tarot: Value,
pub content: Option<Value>,
pub error: Option<String>,
pub credits_charged: i32,
pub attempts: i32,
pub created_at: OffsetDateTime,
pub completed_at: Option<OffsetDateTime>,
}
const COLUMNS: &str = "id, status, tarot, content, error, credits_charged, attempts, created_at, completed_at";
impl ReadingRow {
/// The reading as users see it: the cards with their positions (the model
/// and the reader's signs are left out).
pub fn view(&self) -> Value {
let spread = tarot::spread(self.tarot["spread"].as_str().unwrap_or_default());
let positions = spread.map(|s| s.positions).unwrap_or_default();
let cards: Vec<Value> = self.tarot["cards"]
.as_array()
.into_iter()
.flatten()
.enumerate()
.map(|(i, c)| {
let position = positions.get(i);
json!({
"card": c["card"],
"reversed": c["reversed"],
"position": position.map(|p| p.title),
"about": position.map(|p| p.about),
})
})
.collect();
json!({
"id": self.id,
"status": self.status,
"spread": self.tarot["spread"],
"spread_name": spread.map(|s| s.name),
"question": self.tarot["question"],
"cards": cards,
"content": self.content,
"error": self.error,
"credits_charged": self.credits_charged,
"attempts": self.attempts,
"created_at": rfc3339(self.created_at),
"completed_at": rfc3339_opt(self.completed_at),
})
}
}
/// Shuffles the deck and draws one card per position.
fn draw(spread: &Spread) -> Vec<Value> {
let mut rng = rng();
let mut ids: Vec<&str> = tarot::deck().iter().map(|c| c.id.as_str()).collect();
ids.shuffle(&mut rng);
ids.into_iter()
.take(spread.positions.len())
.map(|id| json!({ "card": id, "reversed": rng.random_bool(REVERSED_SHARE) }))
.collect()
}
/// The Sun, Moon and Ascendant signs of the user's own chart (the Ascendant
/// only with a known birth time).
async fn big_three(
state: &crate::AppState,
user: Uuid,
) -> Result<(Option<String>, Option<String>, Option<String>), ApiError> {
let chart: Option<Value> = sqlx::query_scalar(
"SELECT result FROM charts WHERE owner_id = $1 AND kind = 'own' ORDER BY is_primary DESC, created_at LIMIT 1",
)
.bind(user)
.fetch_optional(&state.db)
.await?;
let Some(chart) = chart else { return Ok((None, None, None)) };
let sign_of = |id: &str| {
chart["points"]
.as_array()
.into_iter()
.flatten()
.find(|p| p["id"] == id)
.and_then(|p| p["sign"].as_str())
.map(str::to_string)
};
let time_known = chart["time"]["time_known"].as_bool().unwrap_or(false);
let ascendant = chart["angles"]["ascendant"]["sign"].as_str().filter(|_| time_known).map(str::to_string);
Ok((sign_of("sun"), sign_of("moon"), ascendant))
}
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let rows: Vec<ReadingRow> = sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM analyses WHERE kind = 'tarot' AND requested_by = $1 ORDER BY created_at DESC LIMIT $2"
))
.bind(auth.id())
.bind(LIST_LIMIT)
.fetch_all(&state.db)
.await?;
let left = credits::balance(&mut *state.db.acquire().await?, auth.id()).await?.tarot;
Ok(Json(json!({ "readings": rows.iter().map(ReadingRow::view).collect::<Vec<_>>(), "left": left })))
}
pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
let row: ReadingRow = sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM analyses WHERE id = $1 AND kind = 'tarot' AND requested_by = $2"
))
.bind(id)
.bind(auth.id())
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("reading"))?;
Ok(Json(row.view()))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NewReading {
spread: String,
question: Option<String>,
}
/// Draws the cards and queues the reading (one `tarot` unit).
pub async fn create(
State(state): St,
auth: AuthUser,
WithRejection(Json(req), _): Body<NewReading>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let spread = tarot::spread(&req.spread).ok_or_else(|| ApiError::BadRequest("unknown spread".into()))?;
let question = req.question.map(|q| q.trim().replace("\r\n", "\n")).filter(|q| !q.is_empty());
if question.as_ref().is_some_and(|q| q.chars().count() > TAROT_QUESTION_MAX_CHARS) {
return Err(ApiError::BadRequest(format!(
"the question is at most {TAROT_QUESTION_MAX_CHARS} characters long"
)));
}
let open: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM analyses WHERE kind = 'tarot' AND requested_by = $1 \
AND status IN ('pending', 'running'))",
)
.bind(auth.id())
.fetch_one(&state.db)
.await?;
if open {
return Err(ApiError::conflict(
"tarot_in_progress",
"Az előző jóslásod még készül. Várd meg, és utána húzz újra.",
));
}
let (sun, moon, ascendant) = big_three(&state, auth.id()).await?;
let reading = json!({
"spread": spread.id,
"question": question,
"cards": draw(spread),
"sun": sun,
"moon": moon,
"ascendant": ascendant,
});
// The model of the detailed analyses writes the readings too.
let (model, fallback) = crate::models::models_for(&state, Kind::Natal).await?;
let language = super::auth::validate_locale(&state, Some(&auth.user.locale))?;
let id = Uuid::now_v7();
let mut tx = state.db.begin().await?;
let row: ReadingRow = sqlx::query_as(&format!(
"INSERT INTO analyses (id, kind, requested_by, language, model, prompt_version, cache_key, status, \
credits_charged, fallback_model, tarot) \
VALUES ($1, 'tarot', $2, $3, $4, $5, $6, 'pending', 1, $7, $8) RETURNING {COLUMNS}"
))
.bind(id)
.bind(auth.id())
.bind(&language)
.bind(&model)
.bind(&state.config.prompt_version)
.bind(format!("tarot|{id}"))
.bind(&fallback)
.bind(&reading)
.fetch_one(&mut *tx)
.await?;
credits::spend(&mut tx, auth.id(), Unit::Tarot, id).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), %id, spread = spread.id, "tarot reading queued");
Ok((StatusCode::ACCEPTED, Json(row.view())))
}
+115 -13
View File
@@ -343,7 +343,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["analyses_left"], json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 0}));
assert_eq!(r.body["analyses_left"], json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0}));
// e-mail verification through the queued e-mail's link
let url = app.outbox_url("anna@example.com", "verify_email").await;
@@ -466,12 +466,12 @@ async fn roles_and_admin_guard(pool: PgPool) {
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, "forecast": 0, "question": 0}))
(StatusCode::CREATED, &json!({"natal": 5, "synastry": 0, "forecast": 0, "question": 0, "tarot": 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, "forecast": 0, "question": 0}));
assert_eq!(credits["balance"], json!({"natal": 5, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0}));
assert_eq!((credits["ledger"][0]["unit"].as_str(), &credits["ledger"][0]["delta"]), (Some("natal"), &json!(5)));
}
@@ -703,7 +703,7 @@ async fn analyses_spend_units_and_reuse_results(pool: PgPool) {
assert_eq!(model, "anthropic/claude-test");
assert_eq!(
app.get("/v1/credits", Some(&anna)).await.body["balance"],
json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 0})
json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0})
);
// same request again: the same analysis, no charge
@@ -713,7 +713,7 @@ async fn analyses_spend_units_and_reuse_results(pool: PgPool) {
assert_eq!(r.status, StatusCode::ACCEPTED);
assert_eq!(
app.get("/v1/credits", Some(&anna)).await.body["balance"],
json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 0})
json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0})
);
let r = app.post(&uri, Some(&anna), json!({"model": "anthropic/claude-other"})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST); // no model choice
@@ -985,7 +985,7 @@ async fn synastry_analyses_use_synastry_units(pool: PgPool) {
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, "forecast": 0, "question": 0})
json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0})
);
// questions can be asked about the relationship analysis too
@@ -1089,7 +1089,7 @@ async fn admins_use_units_too_and_mock_payments_add_units(pool: PgPool) {
let r = app.post("/v1/payments/mock", Some(&anna), json!({"unit": "natal"})).await;
assert_eq!(
(r.status, &r.body["analyses_left"]),
(StatusCode::OK, &json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 3})),
(StatusCode::OK, &json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 3, "tarot": 2})),
"{}",
r.body
);
@@ -1098,7 +1098,7 @@ async fn admins_use_units_too_and_mock_payments_add_units(pool: PgPool) {
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(1)), "{}", r.body);
assert_eq!(
app.get("/v1/credits", Some(&anna)).await.body["balance"],
json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 3})
json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 3, "tarot": 2})
);
// without MOCK_PAYMENTS there is no such payment
@@ -1389,7 +1389,16 @@ async fn packages_grant_units(pool: PgPool) {
let ids: Vec<&str> = r.body["packages"].as_array().unwrap().iter().map(|p| p["id"].as_str().unwrap()).collect();
assert_eq!(
ids,
["single", "couple", "family", "addon_synastry", "addon_forecast", "addon_persons", "addon_questions"]
[
"single",
"couple",
"family",
"addon_synastry",
"addon_forecast",
"addon_persons",
"addon_questions",
"addon_tarot"
]
);
assert_eq!(
(&r.body["packages"][2]["badge"], &r.body["packages"][2]["per_analysis_huf"]),
@@ -1402,7 +1411,7 @@ async fn packages_grant_units(pool: PgPool) {
let r = grant_package(&app, &admin, &anna_id, "family").await;
assert_eq!(
(r.status, &r.body["analyses_left"]),
(StatusCode::CREATED, &json!({"natal": 6, "synastry": 5, "forecast": 6, "question": 3})),
(StatusCode::CREATED, &json!({"natal": 6, "synastry": 5, "forecast": 6, "question": 3, "tarot": 10})),
"{}",
r.body
);
@@ -1417,7 +1426,12 @@ async fn packages_grant_units(pool: PgPool) {
// a (mock) purchase adds to it and records the price
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "couple"})).await;
assert_eq!(r.body["analyses_left"], json!({"natal": 8, "synastry": 6, "forecast": 8, "question": 6}), "{}", r.body);
assert_eq!(
r.body["analyses_left"],
json!({"natal": 8, "synastry": 6, "forecast": 8, "question": 6, "tarot": 15}),
"{}",
r.body
);
let (price,): (i32,) =
sqlx::query_as("SELECT price_huf FROM package_orders WHERE package = 'couple'").fetch_one(&pool).await.unwrap();
assert_eq!(price, 6000);
@@ -1658,14 +1672,19 @@ async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
(StatusCode::PAYMENT_REQUIRED, Some("insufficient_credits"))
);
let r = app.post("/v1/payments/mock", Some(&anna), json!({"unit": "forecast"})).await;
assert_eq!(r.body["analyses_left"], json!({"natal": 1, "synastry": 0, "forecast": 1, "question": 0}), "{}", r.body);
assert_eq!(
r.body["analyses_left"],
json!({"natal": 1, "synastry": 0, "forecast": 1, "question": 0, "tarot": 0}),
"{}",
r.body
);
let r = app.call("POST", &analyses, Some(&anna), None).await;
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
assert_eq!((r.body["kind"].as_str(), r.body["forecast_id"].as_str()), (Some("forecast"), Some(id.as_str())));
let analysis = r.body["id"].as_str().unwrap().to_string();
assert_eq!(
app.get("/v1/credits", Some(&anna)).await.body["balance"],
json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 0})
json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0})
);
assert_eq!(app.call("POST", &analyses, Some(&anna), None).await.status, StatusCode::OK); // the same one, no charge
assert_eq!(app.get(&analyses, Some(&anna)).await.body["analyses"].as_array().unwrap().len(), 1);
@@ -2568,3 +2587,86 @@ async fn stripe_purchases_wait_for_the_opening(pool: PgPool) {
assert_eq!(stripe_form(&id, "consent_collection[terms_of_service]"), None);
assert_eq!(stripe_form(&id, "custom_text[terms_of_service_acceptance][message]"), None);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn tarot_readings_draw_on_the_server_and_use_tarot_units(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let anna = app.register("anna@example.com", "Anna").await;
app.chart(&anna, "Saját", true, "1990-07-01").await;
let body = json!({"spread": "trinity", "question": "Merre induljak tovább?"});
// No units: a package or the addon is needed.
let r = app.post("/v1/tarot/readings", Some(&anna), body.clone()).await;
assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED, "{}", r.body);
assert_eq!(r.body["error"]["code"], "insufficient_credits");
// The packages carry readings, the addon five more.
let packages = app.get("/v1/packages", None).await.body["packages"].clone();
let tarot_of = |id: &str| packages.as_array().unwrap().iter().find(|p| p["id"] == id).unwrap()["tarot"].clone();
assert_eq!((tarot_of("single"), tarot_of("couple"), tarot_of("family")), (json!(2), json!(5), json!(10)));
assert_eq!(tarot_of("addon_tarot"), json!(5));
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "addon_tarot"})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["analyses_left"]["tarot"], 5);
let r = app.post("/v1/tarot/readings", Some(&anna), json!({"spread": "nincs"})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
let long = "x".repeat(analysis_prompt::TAROT_QUESTION_MAX_CHARS + 1);
let r = app.post("/v1/tarot/readings", Some(&anna), json!({"spread": "daily", "question": long})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
let r = app.post("/v1/tarot/readings", Some(&anna), body.clone()).await;
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
assert_eq!(r.body["status"], "pending");
assert_eq!(r.body["spread_name"], "Sorsfonalak hármas");
assert_eq!(r.body["question"], "Merre induljak tovább?");
let cards = r.body["cards"].as_array().unwrap();
assert_eq!(cards.len(), 3);
assert_eq!(cards[1]["position"], "Jelenlegi fókusz");
let mut ids: Vec<&str> = cards.iter().map(|c| c["card"].as_str().unwrap()).collect();
assert!(ids.iter().all(|id| analysis_prompt::tarot::card(id).is_some()));
ids.dedup();
assert_eq!(ids.len(), 3);
assert!(r.body.get("sun").is_none() && r.body.get("model").is_none());
let id = r.body["id"].as_str().unwrap().to_string();
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["analyses_left"]["tarot"], 4);
// Stored for the worker: the analysis model, the reader's signs.
let (model, tarot, chart): (String, Value, Option<uuid::Uuid>) =
sqlx::query_as("SELECT model, tarot, chart_id FROM analyses WHERE id = $1::uuid")
.bind(&id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(model, app.state.config.analysis_model);
assert_eq!(
(&tarot["sun"], &tarot["moon"], &tarot["ascendant"]),
(&json!("cancer"), &json!("pisces"), &json!("aries"))
);
assert_eq!(chart, None);
// One at a time.
let r = app.post("/v1/tarot/readings", Some(&anna), json!({"spread": "daily"})).await;
assert_eq!(r.status, StatusCode::CONFLICT);
assert_eq!(r.body["error"]["code"], "tarot_in_progress");
let list = app.get("/v1/tarot/readings", Some(&anna)).await;
assert_eq!(list.body["readings"].as_array().unwrap().len(), 1);
assert_eq!(list.body["left"], 4);
assert_eq!(app.get(&format!("/v1/tarot/readings/{id}"), Some(&anna)).await.body["id"], id.as_str());
// Nobody else sees it, not even as an analysis.
let bela = app.register("bela@example.com", "Béla").await;
assert_eq!(app.get(&format!("/v1/tarot/readings/{id}"), Some(&bela)).await.status, StatusCode::NOT_FOUND);
assert_eq!(app.get(&format!("/v1/analyses/{id}"), Some(&anna)).await.status, StatusCode::NOT_FOUND);
assert_eq!(app.get("/v1/tarot/readings", Some(&bela)).await.body["readings"], json!([]));
// A recalculation keeps the readings; deleting the account removes them.
routes::recalculate(&app.state).await.unwrap();
let count = || async {
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM analyses WHERE kind = 'tarot'")
.fetch_one(&pool)
.await
.unwrap()
};
assert_eq!(count().await, 1);
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "DELETE"}))).await;
assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body);
assert_eq!(count().await, 0);
}