//! 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, /// Gross price (27% VAT included). 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, /// Badge on the card ("Legnépszerűbb"). pub badge: Option<&'static str>, } pub const CATALOG: [Package; 7] = [ 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, 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, 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, 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, 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, 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, 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, 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, "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, } impl Source { fn as_str(self) -> &'static str { match self { Source::Admin => "admin", Source::Mock => "mock", } } } /// Records an order and gives its contents, inside the caller's transaction. pub async fn grant( tx: &mut PgConnection, user_id: Uuid, package: &Package, source: Source, created_by: Option, note: Option<&str>, ) -> Result { let order = Uuid::now_v7(); let price = match source { Source::Admin => 0, Source::Mock => 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?; let contents = [ (Unit::Natal, package.natal), (Unit::Synastry, package.synastry), (Unit::Forecast, package.forecast), (Unit::Person, package.persons), (Unit::Question, package.questions), ]; 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, 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); } }