Files
sorsfonalak/services/backend/src/packages.rs
T
fecoandClaude Opus 5.5 c90232f40c Gift packages: buy a main package for someone, with a printable gift card
- /ajandek: the package, whom it is for and from whom, the recipient's
  address typed twice (or "I hand it over"), a message; paid on Stripe
  like any package, the invoice is the buyer's
- On payment the gift gets its own code (not a promo code: it cannot be
  withdrawn, and it adds the whole package); redeemed on /bevaltas
- The recipient's e-mail carries the message and the code, with the gift
  card attached as a PDF; the buyer's confirmation says it was a gift
- /ajandekaim: codes, state, the card to download, sending it by e-mail
  (again, or to another address) up to three times
- crates/gift-card draws the A4 card (example chart, questions avatar,
  QR code) as SVG and makes a PDF with krilla, fonts compiled in; the
  backend draws downloads on a blocking thread, the worker the e-mails
- Telegram notices say "(ajándék)"; unpaid gifts go after a week

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-23 20:28:11 +00:00

461 lines
15 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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,
/// A redeemed gift code (someone else paid for it).
Gift,
/// 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::Gift => "gift",
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.contents_items().join(", ")
}
/// What the package gives, item by item ("2 részletes képletelemzés").
pub fn contents_items(&self) -> Vec<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()
}
/// 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). Kept neutral: the main packages keep
/// their plain names, the add-ons share one name, and tarot readings are
/// listed as text content.
pub fn invoice_item(&self) -> (String, String) {
let name = match self.tier {
Tier::Main => format!("Online tartalomszolgáltatás – {} csomag", self.name),
Tier::Addon => "Online tartalomszolgáltatás – kiegészítő csomag".to_string(),
};
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, "egyedi szöveges tartalom"),
]
.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)
}
/// The name and description on Stripe's payment page and receipt: as on
/// the site, but tarot readings are called "kártya" there.
pub fn checkout_text(&self) -> (String, String) {
let plain = |s: &str| s.replace("kártyajóslás", "kártya");
(format!("Sorsfonalak – {}", plain(self.name)), plain(self.tagline))
}
/// 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 {
// A gift's price is on the buyer's checkout.
Source::Admin | Source::Promo | Source::Gift => 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 egyedi szöveges tartalom. Digitális tartalom."
);
let (name, comment) = find("addon_persons").unwrap().invoice_item();
assert_eq!(name, "Online tartalomszolgáltatás – kiegészítő csomag");
assert!(comment.ends_with("tartalmaihoz: 5 további személy felvétele. Digitális tartalom."), "{comment}");
// No profession and no fortune-telling is implied.
for package in &CATALOG {
let item = format!("{:?}", package.invoice_item()).to_lowercase();
assert!(!item.contains("asztrol") && !item.contains("jóslás") && !item.contains("kártya"), "{item}");
}
}
#[test]
fn stripe_says_kartya_instead_of_kartyajoslas() {
let (name, description) = find("addon_tarot").unwrap().checkout_text();
assert_eq!(name, "Sorsfonalak – +5 kártya");
assert_eq!(description, "Öt újabb kártya a saját kérdéseidre.");
assert_eq!(find("couple").unwrap().checkout_text().0, "Sorsfonalak – Páros");
assert!(CATALOG.iter().all(|p| !format!("{:?}", p.checkout_text()).contains("jóslás")));
}
}