From b0fc547b73701005757e7ddb4fdfff2fd2d68696 Mon Sep 17 00:00:00 2001 From: feco Date: Fri, 20 Nov 2026 14:35:50 +0000 Subject: [PATCH] Tarot readings: AI-written, drawn on the server, sold as units MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- Cargo.lock | 1 + crates/analysis-prompt/src/lib.rs | 13 +- crates/analysis-prompt/src/tarot.rs | 387 ++++++ crates/db/migrations/0031_tarot.sql | 21 + docs/csomagok.md | 9 +- docs/kartyajoslas.md | 17 + services/backend/Cargo.toml | 1 + services/backend/src/credits.rs | 23 +- services/backend/src/packages.rs | 35 +- services/backend/src/routes/account.rs | 11 +- services/backend/src/routes/admin.rs | 10 +- services/backend/src/routes/analyses.rs | 19 +- services/backend/src/routes/mod.rs | 3 + services/backend/src/routes/payments.rs | 1 + services/backend/src/routes/recalculate.rs | 5 +- services/backend/src/routes/tarot.rs | 212 ++++ services/backend/src/tests.rs | 128 +- .../frontend/src/app/admin/AdminUsers.tsx | 5 +- services/frontend/src/app/csomagok/page.tsx | 5 + services/frontend/src/app/globals.css | 72 ++ .../src/app/kartyajoslas/[id]/page.tsx | 35 + .../frontend/src/app/kartyajoslas/page.tsx | 37 + .../src/app/kartyajoslas/pelda/page.tsx | 55 + services/frontend/src/app/sitemap.ts | 1 + .../frontend/src/components/PackageCards.tsx | 1 + .../frontend/src/components/SiteHeader.tsx | 1 + .../src/components/tarot/TarotCard.tsx | 1124 +++++++++++++++++ .../src/components/tarot/TarotLive.tsx | 103 ++ .../src/components/tarot/TarotResult.tsx | 67 + .../src/components/tarot/TarotTable.tsx | 327 +++++ services/frontend/src/content/tarot-deck.json | 80 ++ .../frontend/src/content/tarot-pelda.json | 42 + services/frontend/src/lib/tarot.ts | 71 ++ services/frontend/src/lib/types.ts | 4 + services/worker/src/analysis/mod.rs | 15 +- services/worker/src/tests.rs | 62 + 36 files changed, 2957 insertions(+), 46 deletions(-) create mode 100644 crates/analysis-prompt/src/tarot.rs create mode 100644 crates/db/migrations/0031_tarot.sql create mode 100644 docs/kartyajoslas.md create mode 100644 services/backend/src/routes/tarot.rs create mode 100644 services/frontend/src/app/kartyajoslas/[id]/page.tsx create mode 100644 services/frontend/src/app/kartyajoslas/page.tsx create mode 100644 services/frontend/src/app/kartyajoslas/pelda/page.tsx create mode 100644 services/frontend/src/components/tarot/TarotCard.tsx create mode 100644 services/frontend/src/components/tarot/TarotLive.tsx create mode 100644 services/frontend/src/components/tarot/TarotResult.tsx create mode 100644 services/frontend/src/components/tarot/TarotTable.tsx create mode 100644 services/frontend/src/content/tarot-deck.json create mode 100644 services/frontend/src/content/tarot-pelda.json create mode 100644 services/frontend/src/lib/tarot.ts diff --git a/Cargo.lock b/Cargo.lock index e9b1a74..6c82e09 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -175,6 +175,7 @@ dependencies = [ "http-body-util", "jsonwebtoken", "password-hash", + "rand 0.9.5", "reqwest", "serde", "serde_json", diff --git a/crates/analysis-prompt/src/lib.rs b/crates/analysis-prompt/src/lib.rs index d5a7d67..e163b0a 100644 --- a/crates/analysis-prompt/src/lib.rs +++ b/crates/analysis-prompt/src/lib.rs @@ -8,6 +8,9 @@ use serde_json::{Value, json}; +pub mod tarot; +pub use tarot::{Reading as TarotReading, TAROT_QUESTION_MAX_CHARS, build_tarot, tarot_schema}; + /// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key). pub const PROMPT_VERSION: &str = "v3"; @@ -316,7 +319,7 @@ például a Szaturnusz-visszatérés vagy az Uránusz-szembenállás: nevezd is - Ha nincs szolár képlet (ismeretlen születési idő), az évet a tranzitokra és a progressziókra építsd, és ne említs \ házakat, Aszcendenst és MC-t."; -const HUNGARIAN_TERMS: &str = " +pub(crate) const HUNGARIAN_TERMS: &str = " Nyelvhelyesség és szakszavak: - Ügyelj a helyes toldalékokra és a magánhangzó-illeszkedésre; magyar idézőjelet („…”) és nagykötőjelet (–) használj. @@ -341,7 +344,13 @@ felett”), progresszió (a progresszív Hold), profekció, az év ura, napfogya Szaturnusz-visszatérés. - A dátumokat magyarosan írd: „március 12.”, „március 12-től április 30-ig”, „2027 januárja”."; -fn language_name(language: &str) -> &'static str { +/// "cancer" → "Cancer". +pub(crate) fn capitalize(s: &str) -> String { + let mut chars = s.chars(); + chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default() +} + +pub(crate) fn language_name(language: &str) -> &'static str { match language { "hu" => "Hungarian", _ => "English", diff --git a/crates/analysis-prompt/src/tarot.rs b/crates/analysis-prompt/src/tarot.rs new file mode 100644 index 0000000..77588a7 --- /dev/null +++ b/crates/analysis-prompt/src/tarot.rs @@ -0,0 +1,387 @@ +//! Tarot readings: the deck, the spreads, the prompt and the answer schema. +//! +//! The backend draws the cards and stores them with the question (the +//! `tarot` column of the analysis, see [`Reading`]); the worker writes the +//! reading with the model of the detailed analyses. + +use std::sync::OnceLock; + +use serde_json::{Value, json}; + +use crate::{HUNGARIAN_TERMS, Prompt}; + +/// The 78 cards, shared with the frontend (which draws them from the same file). +const DECK_JSON: &str = include_str!("../../../services/frontend/src/content/tarot-deck.json"); + +/// Longest question, in characters. +pub const TAROT_QUESTION_MAX_CHARS: usize = 300; + +/// A card of the deck (the fields the prompt and the views need). +#[derive(Debug, Clone)] +pub struct Card { + pub id: String, + pub name_hu: String, + pub name_en: String, + pub element: String, + pub astro: String, + pub keywords: Vec, + pub upright: String, + pub reversed: String, +} + +pub fn deck() -> &'static [Card] { + static DECK: OnceLock> = OnceLock::new(); + DECK.get_or_init(|| { + let raw: Vec = serde_json::from_str(DECK_JSON).expect("tarot-deck.json is valid JSON"); + let text = |c: &Value, k: &str| c[k].as_str().unwrap_or_default().to_string(); + raw.iter() + .map(|c| Card { + id: text(c, "id"), + name_hu: text(c, "nameHu"), + name_en: text(c, "nameEn"), + element: text(c, "element"), + astro: text(c, "astroRuler"), + keywords: c["keywords"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(), + upright: text(c, "upright"), + reversed: text(c, "reversed"), + }) + .collect() + }) +} + +pub fn card(id: &str) -> Option<&'static Card> { + deck().iter().find(|c| c.id == id) +} + +/// A place in a spread. +#[derive(Debug, Clone, Copy)] +pub struct Position { + pub title: &'static str, + /// What the card in this place tells about. + pub about: &'static str, +} + +#[derive(Debug, Clone, Copy)] +pub struct Spread { + pub id: &'static str, + pub name: &'static str, + pub positions: &'static [Position], +} + +pub const SPREADS: [Spread; 3] = [ + Spread { + id: "daily", + name: "Napi iránymutatás", + positions: &[Position { + title: "A nap üzenete", + about: "Mire hangolódj ma, és milyen minőség támogat leginkább.", + }], + }, + Spread { + id: "trinity", + name: "Sorsfonalak hármas", + positions: &[ + Position { title: "Gyökér és előzmény", about: "Honnan ered a mostani helyzet energiája." }, + Position { title: "Jelenlegi fókusz", about: "Mi zajlik most a felszínen és a mélyben." }, + Position { title: "Kibontakozás", about: "Merre tart a folyamat, ha tudatosan együttműködsz vele." }, + ], + }, + Spread { + id: "astro_cross", + name: "Képlet-kereszt", + positions: &[ + Position { title: "Központi téma", about: "A kérdés szíve és a jelenlegi sorspont." }, + Position { + title: "Hold-mélység (belső)", about: "Tudattalan érzelmi mozgatórugók és megérzések." + }, + Position { + title: "Nap-tér (tudatos)", about: "Amire már rálátsz, és ami felé az akaratod irányul." + }, + Position { + title: "Kvadrát (kihívás)", about: "A súrlódás, amely cselekvésre és növekedésre hív." + }, + Position { + title: "Aszcendens (útmutatás)", about: "A legtisztább következő lépés kifelé és előre." + }, + ], + }, +]; + +pub fn spread(id: &str) -> Option<&'static Spread> { + SPREADS.iter().find(|s| s.id == id) +} + +/// The Hungarian name of a zodiac sign as the charts store it ("cancer"). +pub fn sign_hu(sign: &str) -> &'static str { + match sign.to_ascii_lowercase().as_str() { + "aries" => "Kos", + "taurus" => "Bika", + "gemini" => "Ikrek", + "cancer" => "Rák", + "leo" => "Oroszlán", + "virgo" => "Szűz", + "libra" => "Mérleg", + "scorpio" => "Skorpió", + "sagittarius" => "Nyilas", + "capricorn" => "Bak", + "aquarius" => "Vízöntő", + "pisces" => "Halak", + _ => "?", + } +} + +/// What a reading is written from (the `tarot` column of the analysis): +/// `{"spread": "trinity", "question": "…" | null, "cards": [{"card": "major-2", +/// "reversed": false}, …], "sun": "cancer", "moon": "pisces", "ascendant": "aries" | null}`. +/// The cards are in the order of the spread's positions. +pub struct Reading<'a> { + pub spread: &'static Spread, + pub question: Option<&'a str>, + /// (card, reversed) per position. + pub cards: Vec<(&'static Card, bool)>, + pub sun: Option<&'a str>, + pub moon: Option<&'a str>, + pub ascendant: Option<&'a str>, +} + +impl<'a> Reading<'a> { + pub fn parse(value: &'a Value) -> Result { + let spread_id = value["spread"].as_str().unwrap_or_default(); + let spread = spread(spread_id).ok_or_else(|| format!("unknown spread '{spread_id}'"))?; + let cards = value["cards"] + .as_array() + .ok_or("no cards")? + .iter() + .map(|c| { + let id = c["card"].as_str().unwrap_or_default(); + card(id) + .map(|card| (card, c["reversed"].as_bool().unwrap_or(false))) + .ok_or_else(|| format!("unknown card '{id}'")) + }) + .collect::, _>>()?; + if cards.len() != spread.positions.len() { + return Err(format!("{} cards for a spread of {}", cards.len(), spread.positions.len())); + } + let text = |k: &str| value[k].as_str().map(str::trim).filter(|s| !s.is_empty()); + Ok(Self { + spread, + question: text("question"), + cards, + sun: text("sun"), + moon: text("moon"), + ascendant: text("ascendant"), + }) + } +} + +/// The JSON schema of a reading (strict mode: every property required). +pub fn tarot_schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["title", "summary", "cards", "synthesis", "advice"], + "properties": { + "title": {"type": "string", "description": "Short, evocative title for this reading (at most 8 words)"}, + "summary": {"type": "string", "description": "2-3 sentences: the heart of the answer"}, + "cards": { + "type": "array", + "description": "One item per card, in the order of the positions", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["body"], + "properties": { + "body": {"type": "string", "description": "1-2 paragraphs about this card in its position"} + } + } + }, + "synthesis": {"type": "string", "description": "How the cards read together, 1-3 paragraphs separated by a blank line"}, + "advice": {"type": "string", "description": "A closing, encouraging paragraph with one or two concrete steps"} + } + }) +} + +/// Words of the whole reading, by the number of cards. +fn length(cards: usize) -> (usize, usize) { + match cards { + 1 => (250, 400), + 2..=3 => (450, 700), + _ => (650, 950), + } +} + +fn hungarian_system(cards: usize) -> String { + let (min, max) = length(cards); + format!( + "Tapasztalt, empatikus, lélektani szemléletű tarot-olvasó vagy, aki az asztrológiát is ismeri. A Sorsfonalak \ +alkalmazás számára személyes kártyajóslást írsz egy kirakásról, amelyet az olvasó kérdésére húzott. + +Magyarul írj, természetes, igényes magyarsággal, ahogy egy magyar anyanyelvű szerző írna: a szöveg ne hasson fordításnak. + +Szabályok: +- Csak a megadott lapokat értelmezd, a megadott pozíciókban és állásban (álló vagy fordított). A lapok alapjelentése \ +kiindulópont: a saját tudásod a lapok hagyományos szimbolikájáról (Rider–Waite) kiegészítheti, de ne mondjon neki ellent. +- Minden lapot a pozíciója fényében olvass, és mindig a kérdésre vonatkoztasd. Ha nincs kérdés, az olvasó jelenlegi \ +életszakaszáról szólj általánosan. +- A lapok együtt mesélnek: mutasd meg, hogyan kapcsolódnak egymáshoz (ismétlődő elemek, színek, nagy árkánumok \ +súlya, az álló és fordított lapok aránya). +- Az olvasó Napját, Holdját és Aszcendensét (ha meg van adva) egy-két helyen, finoman kapcsold a lapokhoz, például a \ +lapok elemén vagy asztrológiai megfelelésén keresztül; ne írj belőle horoszkópot. +- Közvetlenül az olvasóhoz szólj, tegező formában (egyes szám második személyben, „te”). +- A tarot tükör, nem ítélet: lehetőségekről, hajlamokról és választásokról írj, soha ne biztos jövőbeli eseményekről. \ +Ne jósolj betegséget, halált, balesetet, terhességet, válást vagy pénzügyi nyereséget és veszteséget, és ne adj orvosi, \ +jogi vagy pénzügyi tanácsot. Ha a kérdés ilyesmire irányul, a lelki oldalára válaszolj, és jelezd, hogy a konkrét \ +döntéshez szakember kell. +- Hangnem: meleg, őszinte, megerősítő és konkrét; a nehéz lapoknál is mutasd meg a kiutat. Kerüld a közhelyeket és a \ +töltelékszöveget. +- A szövegek egyszerű bekezdések, üres sorral elválasztva, címsor és felsorolás nélkül; **félkövért** takarékosan \ +használhatsz. A lapok nevét a magyar nevükön írd. +- Terjedelem: az egész jóslás kb. {min}–{max} szó. +- Egyetlen, a megadott sémának megfelelő JSON-objektummal válaszolj, semmi mással; a „cards” tömbben pontosan annyi \ +elem legyen, ahány lap van, a pozíciók sorrendjében.{HUNGARIAN_TERMS}" + ) +} + +fn english_system(language: &str, cards: usize) -> String { + let (min, max) = length(cards); + format!( + "You are an experienced, empathetic tarot reader with a psychological approach who also knows astrology. You \ +write a personal tarot reading for the Sorsfonalak app about a spread the reader drew for their question. + +Write in {language}. + +Rules: +- Read only the given cards, in their positions and orientation (upright or reversed). The base meanings are the \ +starting point; your knowledge of the traditional (Rider-Waite) symbolism may add to them but must not contradict them. +- Read each card in the light of its position and always relate it to the question. Without a question, speak about \ +the reader's present phase of life. +- Show how the cards tell one story together (recurring elements and suits, the weight of the major arcana, upright \ +versus reversed cards). +- Link the reader's Sun, Moon and Ascendant (when given) to the cards once or twice, gently, e.g. through the cards' \ +elements or astrological correspondences; do not write a horoscope. +- Address the reader directly, in the second person. +- Tarot is a mirror, not a verdict: write about possibilities, tendencies and choices, never certain future events. \ +Do not predict illness, death, accidents, pregnancy, divorce or financial gains and losses, and give no medical, legal \ +or financial advice; if the question asks for that, answer its emotional side and say a professional is needed for the \ +decision itself. +- Tone: warm, honest, encouraging and specific; show the way forward even with hard cards. Avoid clichés and filler. +- Plain paragraphs separated by a blank line, no headings or lists; use **bold** sparingly. +- Length: about {min}-{max} words in all. +- Answer with a single JSON object matching the schema and nothing else; the \"cards\" array has exactly one item per \ +card, in the order of the positions.", + language = crate::language_name(language), + ) +} + +/// The prompt of a reading. +pub fn build_tarot(language: &str, reading: &Reading) -> Prompt { + let hu = language == "hu"; + let mut user = String::new(); + let none = if hu { "nincs megadva" } else { "not given" }; + match reading.question { + Some(q) => user.push_str(&format!("{}: {}\n\n", if hu { "A kérdés" } else { "The question" }, q.trim())), + None => user.push_str(if hu { + "Nincs konkrét kérdés: az olvasó a jelenlegi életszakaszára kér útmutatást.\n\n" + } else { + "No specific question: the reader asks for guidance about their present phase of life.\n\n" + }), + } + let sign = |s: Option<&str>| { + s.map_or(none.to_string(), |s| if hu { sign_hu(s).to_string() } else { crate::capitalize(s) }) + }; + user.push_str(&format!( + "{}: {} {}, {} {}, {} {}\n\n", + if hu { "Az olvasó képlete" } else { "The reader's chart" }, + if hu { "Nap:" } else { "Sun:" }, + sign(reading.sun), + if hu { "Hold:" } else { "Moon:" }, + sign(reading.moon), + if hu { "Aszcendens:" } else { "Ascendant:" }, + sign(reading.ascendant), + )); + user.push_str(&format!( + "{}: {} ({} {})\n", + if hu { "Kirakás" } else { "Spread" }, + reading.spread.name, + reading.cards.len(), + if hu { "lap" } else { "cards" }, + )); + for (i, (position, (card, reversed))) in reading.spread.positions.iter().zip(&reading.cards).enumerate() { + let orientation = match (hu, reversed) { + (true, true) => "fordított", + (true, false) => "álló", + (false, true) => "reversed", + (false, false) => "upright", + }; + user.push_str(&format!( + "\n{n}. {title} ({about})\n {name} ({en}), {orientation}\n {kw}: {keywords}\n {el}: {element}; {astro_label}: {astro}\n {meaning_label}: {meaning}\n", + n = i + 1, + title = position.title, + about = position.about, + name = card.name_hu, + en = card.name_en, + kw = if hu { "Kulcsszavak" } else { "Keywords" }, + keywords = card.keywords.join(", "), + el = if hu { "Elem" } else { "Element" }, + element = card.element, + astro_label = if hu { "Asztrológiai megfelelés" } else { "Astrological correspondence" }, + astro = card.astro, + meaning_label = if hu { "Alapjelentés ebben az állásban" } else { "Base meaning in this orientation (Hungarian)" }, + meaning = if *reversed { &card.reversed } else { &card.upright }, + )); + } + user.push_str(if hu { "\nMost írd meg a jóslást." } else { "\nWrite the reading now." }); + Prompt { + system: if hu { hungarian_system(reading.cards.len()) } else { english_system(language, reading.cards.len()) }, + user, + schema_name: "tarot_reading", + schema: tarot_schema(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_deck_has_78_distinct_cards_with_meanings() { + let deck = deck(); + assert_eq!(deck.len(), 78); + let mut ids: Vec<&str> = deck.iter().map(|c| c.id.as_str()).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 78); + assert!(deck.iter().all(|c| !c.name_hu.is_empty() && !c.upright.is_empty() && !c.reversed.is_empty())); + assert_eq!(card("major-2").unwrap().name_hu, "A Főpapnő"); + } + + #[test] + fn readings_parse_and_build_a_prompt() { + let value = json!({"spread": "trinity", "question": "Merre induljak tovább?", + "cards": [{"card": "major-0", "reversed": false}, {"card": "cups-3", "reversed": true}, + {"card": "major-17", "reversed": false}], + "sun": "cancer", "moon": "pisces", "ascendant": null}); + let reading = Reading::parse(&value).unwrap(); + let prompt = build_tarot("hu", &reading); + assert!(prompt.user.contains("A kérdés: Merre induljak tovább?")); + assert!(prompt.user.contains("Nap: Rák, Hold: Halak, Aszcendens: nincs megadva")); + assert!(prompt.user.contains("2. Jelenlegi fókusz")); + assert!(prompt.user.contains("fordított")); + assert!(prompt.user.contains(&card("cups-3").unwrap().reversed)); + assert!(prompt.system.contains("650") || prompt.system.contains("450")); + assert_eq!(prompt.schema["required"][2], "cards"); + + let english = build_tarot("en", &reading); + assert!(english.user.contains("Sun: Cancer") && english.system.contains("English")); + + let wrong = json!({"spread": "daily", "cards": [{"card": "major-0"}, {"card": "major-1"}]}); + assert!(Reading::parse(&wrong).is_err()); + assert!(Reading::parse(&json!({"spread": "daily", "cards": [{"card": "nincs"}]})).is_err()); + } +} diff --git a/crates/db/migrations/0031_tarot.sql b/crates/db/migrations/0031_tarot.sql new file mode 100644 index 0000000..964db1f --- /dev/null +++ b/crates/db/migrations/0031_tarot.sql @@ -0,0 +1,21 @@ +-- Tarot readings: a `tarot` analysis (stored with the other analyses, so +-- the worker, retries, fallback and refunds work the same) holds the spread, +-- the question, the cards drawn by the server and the reader's Sun, Moon and +-- Ascendant in `tarot`. Each reading uses one `tarot` unit. +ALTER TABLE analyses DROP CONSTRAINT analyses_kind_check; +ALTER TABLE analyses ADD CONSTRAINT analyses_kind_check + CHECK (kind IN ('natal', 'synastry', 'summary', 'forecast', 'tarot')); +ALTER TABLE analyses ADD COLUMN tarot jsonb; +ALTER TABLE analyses DROP CONSTRAINT analyses_target; +ALTER TABLE analyses ADD CONSTRAINT analyses_target CHECK ( + (kind IN ('natal', 'summary') AND chart_id IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL) + OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND forecast_id IS NULL) + OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL) + OR (kind = 'tarot' AND tarot IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND forecast_id IS NULL) +); + +ALTER TABLE credit_ledger DROP CONSTRAINT credit_ledger_unit_check; +ALTER TABLE credit_ledger ADD CONSTRAINT credit_ledger_unit_check + CHECK (unit IN ('natal', 'synastry', 'forecast', 'person', 'question', 'tarot')); + +CREATE INDEX analyses_tarot_idx ON analyses (requested_by, created_at DESC) WHERE kind = 'tarot'; diff --git a/docs/csomagok.md b/docs/csomagok.md index 1eaddc2..67b2a2e 100644 --- a/docs/csomagok.md +++ b/docs/csomagok.md @@ -10,18 +10,21 @@ Egy részletes képletelemzés és egy kapcsolati elemzés is kb. **$0,21 (≈ 8 | Csomag | Tartalom | Ár | Elemzésenként | Külön megvéve | Megtakarítás | |---|---|---|---|---|---| -| Egy elemzés | 1 képletelemzés, 3 kérdés | 2 000 Ft | 2 000 Ft | – | – | -| Páros | 2 képletelemzés, 2 éves előrejelzés, 1 kapcsolati, 1 személy, 3 kérdés | 6 000 Ft | 1 200 Ft | 11 800 Ft | 49% | -| **Család** (Legnépszerűbb) | 6 képletelemzés, 6 éves előrejelzés, 5 kapcsolati, 5 személy, 3 kérdés | 11 000 Ft | 647 Ft | 41 000 Ft | 73% | +| Egy elemzés | 1 képletelemzés, 3 kérdés, 2 kártyajóslás | 2 000 Ft | 2 000 Ft | – | – | +| Páros | 2 képletelemzés, 2 éves előrejelzés, 1 kapcsolati, 1 személy, 3 kérdés, 5 kártyajóslás | 6 000 Ft | 1 200 Ft | 11 800 Ft | 49% | +| **Család** (Legnépszerűbb) | 6 képletelemzés, 6 éves előrejelzés, 5 kapcsolati, 5 személy, 3 kérdés, 10 kártyajóslás | 11 000 Ft | 647 Ft | 41 000 Ft | 73% | | +1 kapcsolati elemzés | kiegészítő | 2 500 Ft | | | | | +1 éves előrejelzés | kiegészítő | 2 500 Ft | | | | | +5 személy | kiegészítő | 1 500 Ft | | | | | +5 kérdés | kiegészítő | 1 000 Ft | | | | +| +5 kártyajóslás | kiegészítő | 1 000 Ft | | | | A „külön megvéve” ár egységárakból jön: képletelemzés 2 000 Ft, kapcsolati elemzés 2 500 Ft, éves előrejelzés 2 500 Ft, személy 300 Ft (`NATAL_PRICE`, `SYNASTRY_PRICE`, `FORECAST_PRICE`, `PERSON_PRICE`). A kérdések (2026 novembere óta) minden csomagban ráadásként járnak (`QUESTIONS_INCLUDED` = 3), a „külön megvéve” árban és a megtakarításban nem szerepelnek. Egy kérdés a kész képletelemzésre vagy éves előrejelzésre vonatkozik, a választ ugyanaz a modell írja, amelyik az elemzést (legfeljebb 250 szó); költsége kb. $0,04–0,07 (15–25 Ft). Részletek: `docs/kerdesek.md`. +A kártyajóslások (2026 novembere óta) szintén ráadásként járnak (Egy elemzés 2, Páros 5, Család 10), a megtakarításban nem szerepelnek. Részletek: `docs/kartyajoslas.md`. + Az éves előrejelzés (2026 novembere óta) a Páros és a Család csomagban mindenkinek benne van; külön megvéve drágább, mint egy képletelemzés. Az Egy elemzés csomag változatlanul egy képletelemzés 2 000 Ft-ért. Részletek: `docs/elorejelzes.md`. ## Miért így (a nagyobb felé terelés) diff --git a/docs/kartyajoslas.md b/docs/kartyajoslas.md new file mode 100644 index 0000000..0ec02a0 --- /dev/null +++ b/docs/kartyajoslas.md @@ -0,0 +1,17 @@ +# Kártyajóslás + +A `/kartyajoslas` oldalon a felhasználó kirakást választ, opcionálisan kérdést ír (legfeljebb 300 karakter), és a legyezőbe terített, lefordított pakliból kiválasztja a lapokat. Ezután a lapok sorban felfordulnak, és elkészül a személyre szabott jóslás. A korábbi jóslások ugyanitt listázódnak, egyenként a `/kartyajoslas/{id}` oldalon nyithatók meg. A nyilvános példa a `/kartyajoslas/pelda` oldalon van (`src/content/tarot-pelda.json`). + +## Működés + +- **A lapokat a szerver húzza** (`POST /v1/tarot/readings`, `services/backend/src/routes/tarot.rs`): megkeveri a 78 lapot, kiveszi a kirakáshoz kellő számút, mindegyik 28% eséllyel fordított. A legyezőből választás csak a pillanatot választja ki, így nem lehet ingyen újrahúzni, amíg tetsző lap nem jön. +- **Tárolás:** a jóslás egy `tarot` fajtájú sor az `analyses` táblában, a kirakással, a kérdéssel, a lapokkal és az olvasó Napjának, Holdjának és Aszcendensének jegyével (a saját képletéből, az Aszcendenst csak ismert születési időnél) a `tarot` oszlopban (migráció: 0031). Képlethez nem kötődik, ezért az újraszámolás nem törli, fióktörléskor viszont törlődik. +- **Egység:** egy jóslás egy `tarot` egységet használ, a kirakás méretétől függetlenül. Egyszerre egy jóslás készülhet. A sikertelen jóslás egysége visszajár (a worker, mint az elemzéseknél). +- **Modell:** ugyanaz, amelyik a részletes elemzéseket írja (admin felületen az „elemzés” funkció modellje és tartaléka); külön modellbeállítása nincs. A worker a gyors sávban írja (`Lane::Quick`), hogy ne várjon a hosszú elemzések mögött. +- **Prompt:** `crates/analysis-prompt/src/tarot.rs`. A modell a lapok alapjelentését (a pakli JSON-ból), a pozíciókat, a kérdést és a három jegyet kapja; válasza: cím, összefoglaló, laponként egy-két bekezdés, a lapok együtt, útravaló. A rendszerprompt az adminon nem szerkeszthető (első kör). +- **Pakli:** `services/frontend/src/content/tarot-deck.json`, ezt a Rust-crate is beolvassa (`include_str!`), így a felület és a prompt ugyanazokat a neveket és jelentéseket használja. A lapok rajza: `src/components/tarot/TarotCard.tsx` (a `../tarot` tervezőstúdió „Égi Asztrolábium” változata). +- **Admin:** a jóslás az elemzésekhez hasonlóan újraíratható (`/v1/admin/analyses/{id}/regenerate`), az egységek az admin felhasználólistán adhatók („kártyajóslás”). + +## Csomagok + +Egy elemzés: 2, Páros: 5, Család: 10 jóslás; külön: „+5 kártyajóslás” 1 000 Ft. A számlán a tétel leírásában „kártyaértelmezés” szerepel (nem „jóslás”). diff --git a/services/backend/Cargo.toml b/services/backend/Cargo.toml index ba06e2d..2197b90 100644 --- a/services/backend/Cargo.toml +++ b/services/backend/Cargo.toml @@ -11,6 +11,7 @@ db.workspace = true analysis-prompt.workspace = true email-templates.workspace = true hmac.workspace = true +rand.workspace = true horoscope-client.workspace = true service-kit.workspace = true anyhow.workspace = true diff --git a/services/backend/src/credits.rs b/services/backend/src/credits.rs index 541a812..ea3bba6 100644 --- a/services/backend/src/credits.rs +++ b/services/backend/src/credits.rs @@ -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 { - 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 diff --git a/services/backend/src/packages.rs b/services/backend/src/packages.rs index 2596424..8c6a13d 100644 --- a/services/backend/src/packages.rs +++ b/services/backend/src/packages.rs @@ -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ő"); diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs index 17c0b6d..b844188 100644 --- a/services/backend/src/routes/account.rs +++ b/services/backend/src/routes/account.rs @@ -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)))) } diff --git a/services/backend/src/routes/admin.rs b/services/backend/src/routes/admin.rs index dd70db9..be93380 100644 --- a/services/backend/src/routes/admin.rs +++ b/services/backend/src/routes/admin.rs @@ -46,6 +46,7 @@ pub async fn list_users( i64, i64, i64, + i64, ); let rows: Vec = 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 = 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(); diff --git a/services/backend/src/routes/analyses.rs b/services/backend/src/routes/analyses.rs index 32587d8..7a3ed39 100644 --- a/services/backend/src/routes/analyses.rs +++ b/services/backend/src/routes/analyses.rs @@ -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())) } diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 30f5dc1..aa43fdd 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -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) -> 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)) diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index 40670f2..65ed79d 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -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"))?; diff --git a/services/backend/src/routes/recalculate.rs b/services/backend/src/routes/recalculate.rs index 3112ff8..12a5353 100644 --- a/services/backend/src/routes/recalculate.rs +++ b/services/backend/src/routes/recalculate.rs @@ -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?; diff --git a/services/backend/src/routes/tarot.rs b/services/backend/src/routes/tarot.rs new file mode 100644 index 0000000..0fecd4d --- /dev/null +++ b/services/backend/src/routes/tarot.rs @@ -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, + pub error: Option, + pub credits_charged: i32, + pub attempts: i32, + pub created_at: OffsetDateTime, + pub completed_at: Option, +} + +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 = 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 { + 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, Option, Option), ApiError> { + let chart: Option = 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> { + let rows: Vec = 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::>(), "left": left }))) +} + +pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult> { + 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, +} + +/// Draws the cards and queues the reading (one `tarot` unit). +pub async fn create( + State(state): St, + auth: AuthUser, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + 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()))) +} diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 1d44837..3948e0d 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -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) = + 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); +} diff --git a/services/frontend/src/app/admin/AdminUsers.tsx b/services/frontend/src/app/admin/AdminUsers.tsx index a1c578e..3ab6d8b 100644 --- a/services/frontend/src/app/admin/AdminUsers.tsx +++ b/services/frontend/src/app/admin/AdminUsers.tsx @@ -8,13 +8,14 @@ import { ROLE_LABELS, formatDate } from "@/lib/astro"; import type { AdminUser, Package, Role } from "@/lib/types"; const EDITABLE_ROLES: Role[] = ["user", "creator", "admin"]; -type UnitKind = "natal" | "synastry" | "forecast" | "question"; +type UnitKind = "natal" | "synastry" | "forecast" | "question" | "tarot"; const UNITS: { value: UnitKind; label: string }[] = [ { value: "natal", label: "képlet" }, { value: "synastry", label: "szinasztria" }, { value: "forecast", label: "előrejelzés" }, { value: "question", label: "kérdés" }, + { value: "tarot", label: "kártyajóslás" }, ]; export function AdminUsers({ selfId }: { selfId: string }) { @@ -183,6 +184,8 @@ function UserRow({ előrejelzés {user.analyses_left.forecast ?? 0}
kérdés {user.analyses_left.question ?? 0} +
+ jóslás {user.analyses_left.tarot ?? 0}