//! 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, or a time-limited `unlimited` //! entitlement: analyses and persons without limit, with a daily fair-use cap. 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_990; const SYNASTRY_PRICE: i64 = 3_490; const PERSON_PRICE: i64 = 398; // 1 990 Ft for five #[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 persons: i64, /// Months of unlimited analyses and persons. pub unlimited_months: Option, /// Badge on the card ("Legnépszerűbb"). pub badge: Option<&'static str>, } pub const CATALOG: [Package; 6] = [ 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_990, natal: 1, synastry: 0, persons: 0, unlimited_months: None, badge: None, }, Package { id: "couple", name: "Páros", tagline: "Te és ő: mindkettőtök képlete és a kapcsolati elemzés.", tier: Tier::Main, price_huf: 6_990, natal: 2, synastry: 1, persons: 1, unlimited_months: None, badge: None, }, Package { id: "family", name: "Család", tagline: "Az egész család: öt személy, mindenki képlete, és öt kapcsolat.", tier: Tier::Main, price_huf: 11_990, natal: 6, synastry: 5, persons: 5, unlimited_months: None, badge: Some("Legnépszerűbb"), }, Package { id: "unlimited", name: "Korlátlan", tagline: "Egy évig bárki, bármennyi elemzés és összevetés.", tier: Tier::Main, price_huf: 17_990, natal: 0, synastry: 0, persons: 0, unlimited_months: Some(12), badge: None, }, Package { id: "addon_synastry", name: "+1 kapcsolati elemzés", tagline: "Egy újabb összevetés részletes elemzése.", tier: Tier::Addon, price_huf: 3_490, natal: 0, synastry: 1, persons: 0, unlimited_months: None, 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_990, natal: 0, synastry: 0, persons: 5, unlimited_months: None, 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 (`None` for the unlimited one). fn list_price(&self) -> Option { self.unlimited_months .is_none() .then(|| self.natal * NATAL_PRICE + self.synastry * SYNASTRY_PRICE + self.persons * PERSON_PRICE) } pub fn view(&self) -> Value { let analyses = self.natal + self.synastry; let savings = self .list_price() .filter(|&list| list > self.price_huf) .map(|list| ((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, "persons": self.persons, "unlimited_months": self.unlimited_months, "badge": self.badge, "list_price_huf": self.list_price(), "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?; for (unit, n) in [(Unit::Natal, package.natal), (Unit::Synastry, package.synastry), (Unit::Person, package.persons)] { 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?; } if let Some(months) = package.unlimited_months { // Buying again extends from the current end, not from today. sqlx::query( "INSERT INTO entitlements (user_id, entitlement, note, created_by, expires_at) \ VALUES ($1, 'unlimited', $2, $3, now() + make_interval(months => $4)) \ ON CONFLICT (user_id, entitlement) DO UPDATE SET \ expires_at = greatest(entitlements.expires_at, now()) + make_interval(months => $4), \ note = EXCLUDED.note, created_by = EXCLUDED.created_by", ) .bind(user_id) .bind(package.name) .bind(created_by) .bind(months as i32) .execute(&mut *tx) .await?; } Ok(order) } /// Until when the user's unlimited package runs (`None`: none, or it ended). pub async fn unlimited_until(conn: &mut PgConnection, user_id: Uuid) -> Result, ApiError> { let until: Option = sqlx::query_scalar( "SELECT expires_at FROM entitlements \ WHERE user_id = $1 AND entitlement = 'unlimited' AND expires_at > now()", ) .bind(user_id) .fetch_optional(conn) .await? .flatten(); Ok(until) } /// The package to show for the user (header, profile): the running /// unlimited one, or else 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, unlimited_until: Option, ) -> 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?; Ok(orders.into_iter().find_map(|(id, at)| { let p = find(&id).filter(|p| p.tier == Tier::Main)?; // While an unlimited package runs, only that is shown; an ended one never. (p.unlimited_months.is_some() == unlimited_until.is_some()).then_some((p, at)) })) } /// The fair-use cap of the unlimited package: new detailed analyses in 24 hours. pub async fn check_fair_use(conn: &mut PgConnection, user_id: Uuid, daily_limit: i64) -> Result<(), ApiError> { let (count,): (i64,) = sqlx::query_as( "SELECT count(*) FROM analyses WHERE requested_by = $1 AND kind IN ('natal', 'synastry') \ AND created_at > now() - interval '24 hours'", ) .bind(user_id) .fetch_one(conn) .await?; if count >= daily_limit { return Err(ApiError::Limited { code: "fair_use_limit", message: format!( "A korlátlan csomaggal naponta legfeljebb {daily_limit} új részletes elemzés kérhető. Holnap folytathatod." ), }); } Ok(()) } #[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"], 68); assert_eq!(find("couple").unwrap().view()["savings_percent"], 29); assert!(find("single").unwrap().view()["savings_percent"].is_null()); assert!(find("unlimited").unwrap().view()["list_price_huf"].is_null()); assert!(CATALOG.iter().all(|p| find(p.id).is_some())); } }