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
432 lines
14 KiB
Rust
432 lines
14 KiB
Rust
//! Packages: what a user can buy (or an admin can give). The catalog is
|
||
//! fixed here; see `docs/csomagok.md` for the reasoning behind it.
|
||
//!
|
||
//! A package gives analysis units and person slots (`credit_ledger` rows
|
||
//! with reason `package`) that never expire. There is no unlimited package on
|
||
//! purpose: it would be easy to resell (e.g. by an astrologer).
|
||
|
||
use serde_json::{Value, json};
|
||
use sqlx::PgConnection;
|
||
use time::OffsetDateTime;
|
||
use uuid::Uuid;
|
||
|
||
use crate::credits::Unit;
|
||
use crate::error::ApiError;
|
||
|
||
/// List prices of the single items, for showing what a package saves.
|
||
const NATAL_PRICE: i64 = 2_000;
|
||
const SYNASTRY_PRICE: i64 = 2_500;
|
||
/// A yearly forecast bought alone costs more than one in a package.
|
||
const FORECAST_PRICE: i64 = 2_500;
|
||
const PERSON_PRICE: i64 = 300; // 1 500 Ft for five
|
||
/// Questions every package of the main ladder comes with (not counted in the
|
||
/// "bought one by one" price: they are a bonus).
|
||
const QUESTIONS_INCLUDED: i64 = 3;
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum Tier {
|
||
/// The main ladder, shown side by side.
|
||
Main,
|
||
/// Top-ups for those who already have something.
|
||
Addon,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy)]
|
||
pub struct Package {
|
||
pub id: &'static str,
|
||
pub name: &'static str,
|
||
pub tagline: &'static str,
|
||
pub tier: Tier,
|
||
/// The price paid (with VAT if `INVOICE_VAT` is a rate; none under AAM).
|
||
pub price_huf: i64,
|
||
pub natal: i64,
|
||
pub synastry: i64,
|
||
pub forecast: i64,
|
||
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; 8] = [
|
||
Package {
|
||
id: "single",
|
||
name: "Egy elemzés",
|
||
tagline: "Egy részletes képletelemzés: neked vagy egy felvett személynek.",
|
||
tier: Tier::Main,
|
||
price_huf: 2_000,
|
||
natal: 1,
|
||
synastry: 0,
|
||
forecast: 0,
|
||
persons: 0,
|
||
questions: QUESTIONS_INCLUDED,
|
||
tarot: 2,
|
||
badge: None,
|
||
},
|
||
Package {
|
||
id: "couple",
|
||
name: "Páros",
|
||
tagline: "Te és ő: mindkettőtök képlete, éves előrejelzése és a kapcsolati elemzés.",
|
||
tier: Tier::Main,
|
||
price_huf: 6_000,
|
||
natal: 2,
|
||
synastry: 1,
|
||
forecast: 2,
|
||
persons: 1,
|
||
questions: QUESTIONS_INCLUDED,
|
||
tarot: 5,
|
||
badge: None,
|
||
},
|
||
Package {
|
||
id: "family",
|
||
name: "Család",
|
||
tagline: "Az egész család: öt személy, mindenki képlete és éves előrejelzése, és öt kapcsolat.",
|
||
tier: Tier::Main,
|
||
price_huf: 11_000,
|
||
natal: 6,
|
||
synastry: 5,
|
||
forecast: 6,
|
||
persons: 5,
|
||
questions: QUESTIONS_INCLUDED,
|
||
tarot: 10,
|
||
badge: Some("Legnépszerűbb"),
|
||
},
|
||
Package {
|
||
id: "addon_synastry",
|
||
name: "+1 kapcsolati elemzés",
|
||
tagline: "Egy újabb összevetés részletes elemzése.",
|
||
tier: Tier::Addon,
|
||
price_huf: 2_500,
|
||
natal: 0,
|
||
synastry: 1,
|
||
forecast: 0,
|
||
persons: 0,
|
||
questions: 0,
|
||
tarot: 0,
|
||
badge: None,
|
||
},
|
||
Package {
|
||
id: "addon_forecast",
|
||
name: "+1 éves előrejelzés",
|
||
tagline: "Egy év születésnaptól születésnapig: szolár, tranzitok, progresszió.",
|
||
tier: Tier::Addon,
|
||
price_huf: FORECAST_PRICE,
|
||
natal: 0,
|
||
synastry: 0,
|
||
forecast: 1,
|
||
persons: 0,
|
||
questions: 0,
|
||
tarot: 0,
|
||
badge: None,
|
||
},
|
||
Package {
|
||
id: "addon_persons",
|
||
name: "+5 személy",
|
||
tagline: "Még öt ember képlete (az elemzés külön jár).",
|
||
tier: Tier::Addon,
|
||
price_huf: 1_500,
|
||
natal: 0,
|
||
synastry: 0,
|
||
forecast: 0,
|
||
persons: 5,
|
||
questions: 0,
|
||
tarot: 0,
|
||
badge: None,
|
||
},
|
||
Package {
|
||
id: "addon_questions",
|
||
name: "+5 kérdés",
|
||
tagline: "Öt újabb kérdés az elemzéseidről és előrejelzéseidről.",
|
||
tier: Tier::Addon,
|
||
price_huf: 1_000,
|
||
natal: 0,
|
||
synastry: 0,
|
||
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,
|
||
},
|
||
];
|
||
|
||
pub fn find(id: &str) -> Option<&'static Package> {
|
||
CATALOG.iter().find(|p| p.id == id)
|
||
}
|
||
|
||
impl Package {
|
||
/// What the contents would cost one by one.
|
||
fn list_price(&self) -> i64 {
|
||
self.natal * NATAL_PRICE
|
||
+ self.synastry * SYNASTRY_PRICE
|
||
+ self.forecast * FORECAST_PRICE
|
||
+ self.persons * PERSON_PRICE
|
||
}
|
||
|
||
pub fn view(&self) -> Value {
|
||
let analyses = self.natal + self.synastry + self.forecast;
|
||
let list = self.list_price();
|
||
let savings = (list > self.price_huf).then(|| ((list - self.price_huf) * 100 + list / 2) / list);
|
||
json!({
|
||
"id": self.id,
|
||
"name": self.name,
|
||
"tagline": self.tagline,
|
||
"tier": match self.tier { Tier::Main => "main", Tier::Addon => "addon" },
|
||
"price_huf": self.price_huf,
|
||
"natal": self.natal,
|
||
"synastry": self.synastry,
|
||
"forecast": self.forecast,
|
||
"persons": self.persons,
|
||
"questions": self.questions,
|
||
"tarot": self.tarot,
|
||
"badge": self.badge,
|
||
"list_price_huf": list,
|
||
"savings_percent": savings,
|
||
"per_analysis_huf": (analyses > 0).then(|| (self.price_huf + analyses / 2) / analyses),
|
||
})
|
||
}
|
||
}
|
||
|
||
/// Who gives the package.
|
||
#[derive(Debug, Clone, Copy)]
|
||
pub enum Source {
|
||
Admin,
|
||
Mock,
|
||
/// A redeemed promo code.
|
||
Promo,
|
||
/// Paid through Stripe Checkout.
|
||
Stripe,
|
||
}
|
||
|
||
impl Source {
|
||
fn as_str(self) -> &'static str {
|
||
match self {
|
||
Source::Admin => "admin",
|
||
Source::Mock => "mock",
|
||
Source::Promo => "promo",
|
||
Source::Stripe => "stripe",
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Package {
|
||
/// What the package gives, as a phrase: "2 részletes képletelemzés, 1 kapcsolati elemzés, …".
|
||
pub fn contents_text(&self) -> String {
|
||
[
|
||
(self.natal, "részletes képletelemzés"),
|
||
(self.synastry, "kapcsolati elemzés"),
|
||
(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)
|
||
.map(|(n, what)| format!("{n} {what}"))
|
||
.collect::<Vec<_>>()
|
||
.join(", ")
|
||
}
|
||
|
||
/// The invoice item: a name that says what the service is (online,
|
||
/// software-made content; no profession implied), and what the package
|
||
/// contains (Áfa tv. 169. § e).
|
||
pub fn invoice_item(&self) -> (String, String) {
|
||
let name = match self.tier {
|
||
Tier::Main => format!("Online tartalomszolgáltatás – {} csomag", self.name),
|
||
Tier::Addon => format!("Online tartalomszolgáltatás – {} kiegészítő", self.name),
|
||
};
|
||
let lines: Vec<String> = [
|
||
(self.natal, "képletelemzés"),
|
||
(self.synastry, "kapcsolati elemzés"),
|
||
(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)
|
||
.map(|(n, what)| format!("{n} {what}"))
|
||
.collect();
|
||
let comment = format!(
|
||
"Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: {}. \
|
||
Digitális tartalom.",
|
||
lines.join(", ")
|
||
);
|
||
(name, comment)
|
||
}
|
||
|
||
/// What the package gives, unit by unit.
|
||
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),
|
||
]
|
||
}
|
||
}
|
||
|
||
/// Records an order and adds its contents, inside the caller's transaction.
|
||
pub async fn grant(
|
||
tx: &mut PgConnection,
|
||
user_id: Uuid,
|
||
package: &Package,
|
||
source: Source,
|
||
created_by: Option<Uuid>,
|
||
note: Option<&str>,
|
||
) -> Result<Uuid, ApiError> {
|
||
record(tx, user_id, package, source, created_by, note, &package.contents()).await
|
||
}
|
||
|
||
/// Fills the user's units up to what the package gives (promo codes): a unit
|
||
/// below the package's amount is raised to it, used units come back, more
|
||
/// than that stays as it is. `persons_left` is the free person slots now
|
||
/// (`None`: unlimited, nothing to add). Returns the order and what was added
|
||
/// (nothing at all: no order is recorded).
|
||
pub async fn top_up(
|
||
tx: &mut PgConnection,
|
||
user_id: Uuid,
|
||
package: &Package,
|
||
persons_left: Option<i64>,
|
||
note: Option<&str>,
|
||
) -> Result<Option<(Uuid, Vec<(Unit, i64)>)>, ApiError> {
|
||
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user_id).execute(&mut *tx).await?;
|
||
let balance = crate::credits::balance(tx, user_id).await?;
|
||
let added: Vec<(Unit, i64)> = package
|
||
.contents()
|
||
.into_iter()
|
||
.map(|(unit, n)| {
|
||
let have = match unit {
|
||
Unit::Person => persons_left.unwrap_or(i64::MAX),
|
||
unit => balance.of(unit),
|
||
};
|
||
(unit, (n - have).max(0))
|
||
})
|
||
.filter(|&(_, n)| n > 0)
|
||
.collect();
|
||
if added.is_empty() {
|
||
return Ok(None);
|
||
}
|
||
let order = record(tx, user_id, package, Source::Promo, None, note, &added).await?;
|
||
Ok(Some((order, added)))
|
||
}
|
||
|
||
async fn record(
|
||
tx: &mut PgConnection,
|
||
user_id: Uuid,
|
||
package: &Package,
|
||
source: Source,
|
||
created_by: Option<Uuid>,
|
||
note: Option<&str>,
|
||
contents: &[(Unit, i64)],
|
||
) -> Result<Uuid, ApiError> {
|
||
let order = Uuid::now_v7();
|
||
let price = match source {
|
||
Source::Admin | Source::Promo => 0,
|
||
Source::Mock | Source::Stripe => package.price_huf,
|
||
};
|
||
sqlx::query(
|
||
"INSERT INTO package_orders (id, user_id, package, source, price_huf, note, created_by) \
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||
)
|
||
.bind(order)
|
||
.bind(user_id)
|
||
.bind(package.id)
|
||
.bind(source.as_str())
|
||
.bind(price as i32)
|
||
.bind(note)
|
||
.bind(created_by)
|
||
.execute(&mut *tx)
|
||
.await?;
|
||
for &(unit, n) in contents {
|
||
if n == 0 {
|
||
continue;
|
||
}
|
||
sqlx::query(
|
||
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, order_id, note, created_by) \
|
||
VALUES ($1, $2, $3, $4, 'package', $5, $6, $7)",
|
||
)
|
||
.bind(Uuid::now_v7())
|
||
.bind(user_id)
|
||
.bind(unit.as_str())
|
||
.bind(n as i32)
|
||
.bind(order)
|
||
.bind(package.name)
|
||
.bind(created_by)
|
||
.execute(&mut *tx)
|
||
.await?;
|
||
}
|
||
Ok(order)
|
||
}
|
||
|
||
/// The package to show for the user (header, profile): the latest bought or
|
||
/// given package of the main ladder (top-ups do not count). `None`: no package.
|
||
pub async fn current(
|
||
conn: &mut PgConnection,
|
||
user_id: Uuid,
|
||
) -> Result<Option<(&'static Package, OffsetDateTime)>, ApiError> {
|
||
let orders: Vec<(String, OffsetDateTime)> =
|
||
sqlx::query_as("SELECT package, created_at FROM package_orders WHERE user_id = $1 ORDER BY created_at DESC")
|
||
.bind(user_id)
|
||
.fetch_all(conn)
|
||
.await?;
|
||
// Orders of packages no longer sold (the former unlimited one) are skipped.
|
||
Ok(orders.into_iter().find_map(|(id, at)| find(&id).filter(|p| p.tier == Tier::Main).map(|p| (p, at))))
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn bigger_packages_are_cheaper_per_analysis() {
|
||
let per = |id: &str| find(id).unwrap().view()["per_analysis_huf"].as_i64().unwrap();
|
||
assert!(per("single") > per("couple") && per("couple") > per("family"));
|
||
assert_eq!(find("family").unwrap().view()["savings_percent"], 73);
|
||
assert_eq!(find("couple").unwrap().view()["savings_percent"], 49);
|
||
// Alone a forecast costs more than a natal analysis.
|
||
assert!(find("addon_forecast").unwrap().price_huf > find("single").unwrap().price_huf);
|
||
assert!(find("single").unwrap().view()["savings_percent"].is_null());
|
||
assert!(find("unlimited").is_none());
|
||
assert!(CATALOG.iter().all(|p| find(p.id).is_some()));
|
||
// Every package of the ladder comes with questions; more can be bought.
|
||
assert!(CATALOG.iter().filter(|p| p.tier == Tier::Main).all(|p| p.questions == QUESTIONS_INCLUDED));
|
||
assert_eq!(find("addon_questions").unwrap().questions, 5);
|
||
}
|
||
|
||
#[test]
|
||
fn invoice_items_say_what_was_bought() {
|
||
let (name, comment) = find("couple").unwrap().invoice_item();
|
||
assert_eq!(name, "Online tartalomszolgáltatás – Páros csomag");
|
||
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, \
|
||
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ő");
|
||
assert!(comment.ends_with("tartalmaihoz: 5 további személy felvétele. Digitális tartalom."), "{comment}");
|
||
// No profession is implied.
|
||
assert!(CATALOG.iter().all(|p| !format!("{:?}", p.invoice_item()).to_lowercase().contains("asztrol")));
|
||
}
|
||
}
|