Packages: from one analysis to unlimited, admin can give them
A fixed catalog (packages.rs, reasoning in docs/csomagok.md): Egy elemzés
2 990 Ft, Páros 6 990 Ft, Család 11 990 Ft (featured), Korlátlan 17 990 Ft
for a year, and two top-ups. Every grant is a package_orders row; units are
credit_ledger rows with reason 'package' and never expire. The unlimited
package is a time-limited 'unlimited' entitlement: analyses use no unit and
persons have no limit, with a daily fair-use cap (UNLIMITED_DAILY_LIMIT, 5);
buying it again extends it by a year.
- GET /v1/packages, mock payment by package id, /v1/me unlimited_until
- POST /v1/admin/users/{id}/packages: give a package as a gift
- /csomagok page; the paid step of an analysis offers three packages with
the bigger one featured; person packs use the catalog; admin user list
has a package column
- PERSON_PACK_SIZE is replaced by the catalog's +5 személy top-up
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -49,8 +49,8 @@ pub struct Config {
|
||||
pub max_charts_per_user: i64,
|
||||
/// `FREE_PERSON_SLOTS` (default 0): persons a user may add without a package.
|
||||
pub free_person_slots: i64,
|
||||
/// `PERSON_PACK_SIZE` (default 5): persons in one person package.
|
||||
pub person_pack_size: i64,
|
||||
/// `UNLIMITED_DAILY_LIMIT` (default 5): new detailed analyses a day with the unlimited package.
|
||||
pub unlimited_daily_limit: i64,
|
||||
}
|
||||
|
||||
fn var(name: &str) -> Option<String> {
|
||||
@@ -105,7 +105,7 @@ impl Config {
|
||||
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()),
|
||||
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
|
||||
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
|
||||
person_pack_size: parsed("PERSON_PACK_SIZE", 5)?,
|
||||
unlimited_daily_limit: parsed("UNLIMITED_DAILY_LIMIT", 5)?,
|
||||
};
|
||||
if config.session_ttl_days < 1 {
|
||||
bail!("SESSION_TTL_DAYS must be at least 1");
|
||||
@@ -135,7 +135,7 @@ impl Config {
|
||||
prompt_version: "v1".into(),
|
||||
max_charts_per_user: 50,
|
||||
free_person_slots: 5,
|
||||
person_pack_size: 5,
|
||||
unlimited_daily_limit: 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ mod config;
|
||||
mod credits;
|
||||
mod error;
|
||||
mod google;
|
||||
mod packages;
|
||||
mod persons;
|
||||
mod routes;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
//! 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<i64>,
|
||||
/// 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<i64> {
|
||||
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<Uuid>,
|
||||
note: Option<&str>,
|
||||
) -> Result<Uuid, ApiError> {
|
||||
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<Option<OffsetDateTime>, ApiError> {
|
||||
let until: Option<OffsetDateTime> = 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 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()));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Persons: charts of other people (name and birth data) a user adds next to
|
||||
//! their own. Each new person uses one `person` unit, bought in packages;
|
||||
//! deleting a person does not give it back. An unlimited package
|
||||
//! (`unlimited_persons` entitlement) and admins have no limit.
|
||||
//! deleting a person does not give it back. The `unlimited_persons`
|
||||
//! entitlement, a running unlimited package and admins have no limit.
|
||||
//!
|
||||
//! A person's birth data can be corrected within an hour of adding them,
|
||||
//! then it is locked (admins: any time).
|
||||
@@ -53,7 +53,8 @@ pub async fn slots(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Resul
|
||||
(SELECT COUNT(*) FROM credit_ledger WHERE user_id = $1 AND unit = 'person' AND reason = 'person'), \
|
||||
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger \
|
||||
WHERE user_id = $1 AND unit = 'person' AND reason <> 'person'), \
|
||||
EXISTS (SELECT 1 FROM entitlements WHERE user_id = $1 AND entitlement = 'unlimited_persons')",
|
||||
EXISTS (SELECT 1 FROM entitlements WHERE user_id = $1 \
|
||||
AND (entitlement = 'unlimited_persons' OR (entitlement = 'unlimited' AND expires_at > now())))",
|
||||
)
|
||||
.bind(auth.id())
|
||||
.fetch_one(conn)
|
||||
|
||||
@@ -32,6 +32,7 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let balance = credits::balance(&mut conn, auth.id()).await?;
|
||||
let birth_change = crate::birth_changes::view(&mut conn, &auth).await?;
|
||||
let persons = crate::persons::slots(&mut conn, &auth, state.config.free_person_slots).await?;
|
||||
let unlimited = crate::packages::unlimited_until(&mut conn, auth.id()).await?;
|
||||
Ok(Json(json!({
|
||||
"user": UserView::from(&auth.user),
|
||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||
@@ -39,6 +40,7 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
"analyses_left": balance.view(),
|
||||
"birth_change": birth_change,
|
||||
"persons": persons.view(),
|
||||
"unlimited_until": rfc3339_opt(unlimited),
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use super::{Body, IdPath, St};
|
||||
use crate::auth::AdminUser;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::packages::{self, Source};
|
||||
use crate::views::{rfc3339, rfc3339_opt};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -32,12 +33,26 @@ pub async fn list_users(
|
||||
let limit = query.limit.unwrap_or(50).clamp(1, 200);
|
||||
let offset = query.offset.unwrap_or(0).max(0);
|
||||
let pattern = query.q.as_deref().map(|q| format!("%{}%", q.trim().replace(['%', '_'], "")));
|
||||
type Row = (Uuid, String, Option<String>, Vec<String>, bool, OffsetDateTime, Option<OffsetDateTime>, i64, i64, i64);
|
||||
type Row = (
|
||||
Uuid,
|
||||
String,
|
||||
Option<String>,
|
||||
Vec<String>,
|
||||
bool,
|
||||
OffsetDateTime,
|
||||
Option<OffsetDateTime>,
|
||||
i64,
|
||||
i64,
|
||||
i64,
|
||||
Option<OffsetDateTime>,
|
||||
);
|
||||
let rows: Vec<Row> = 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, \
|
||||
(SELECT count(*) FROM charts c WHERE c.owner_id = u.id), \
|
||||
(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 = 'synastry'), \
|
||||
(SELECT e.expires_at FROM entitlements e \
|
||||
WHERE e.user_id = u.id AND e.entitlement = 'unlimited' AND e.expires_at > now()) \
|
||||
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",
|
||||
@@ -49,11 +64,12 @@ pub async fn list_users(
|
||||
.await?;
|
||||
let users: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry)| {
|
||||
.map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, unlimited)| {
|
||||
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},
|
||||
"unlimited_until": rfc3339_opt(unlimited),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -128,3 +144,37 @@ pub async fn adjust_credits(
|
||||
let balance = credits::balance(&mut *state.db.acquire().await?, id).await?;
|
||||
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "analyses_left": balance.view() }))))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct GrantPackage {
|
||||
package: String,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
/// Gives a user a package from the catalog (a gift: no payment, price 0).
|
||||
pub async fn grant_package(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<GrantPackage>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
|
||||
let exists: Option<(Uuid,)> =
|
||||
sqlx::query_as("SELECT id FROM users WHERE id = $1").bind(id).fetch_optional(&state.db).await?;
|
||||
exists.ok_or(ApiError::NotFound("user"))?;
|
||||
let note = req.note.map(|n| n.trim().chars().take(500).collect::<String>()).filter(|n| !n.is_empty());
|
||||
let mut tx = state.db.begin().await?;
|
||||
let order = packages::grant(&mut tx, id, package, Source::Admin, Some(admin.id()), note.as_deref()).await?;
|
||||
let balance = credits::balance(&mut tx, id).await?;
|
||||
let unlimited = packages::unlimited_until(&mut tx, id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(admin = %admin.id(), user = %id, package = package.id, "package granted");
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(json!({
|
||||
"order_id": order, "user_id": id, "package": package.id,
|
||||
"analyses_left": balance.view(), "unlimited_until": rfc3339_opt(unlimited),
|
||||
})),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::packages;
|
||||
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
|
||||
use db::Role;
|
||||
|
||||
@@ -118,9 +119,18 @@ async fn request(
|
||||
req: AnalysisRequest,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
|
||||
// Admins get detailed analyses free of charge.
|
||||
// Admins and a running unlimited package (within its daily cap) use no unit.
|
||||
let admin = auth.user.has_role(Role::Admin);
|
||||
let unlimited = !admin && {
|
||||
let mut conn = state.db.acquire().await?;
|
||||
let until = packages::unlimited_until(&mut conn, auth.id()).await?;
|
||||
if until.is_some() {
|
||||
packages::check_fair_use(&mut conn, auth.id(), state.config.unlimited_daily_limit).await?;
|
||||
}
|
||||
until.is_some()
|
||||
};
|
||||
let unit = match target {
|
||||
_ if auth.user.has_role(Role::Admin) => None,
|
||||
_ if admin || unlimited => None,
|
||||
Target::Synastry { .. } => Some(Unit::Synastry),
|
||||
_ => Some(Unit::Natal),
|
||||
};
|
||||
|
||||
@@ -50,6 +50,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/healthz", get(health))
|
||||
.route("/v1/config", get(public_config))
|
||||
.route("/v1/packages", get(payments::catalog))
|
||||
// login
|
||||
.route("/v1/auth/register", post(auth::register))
|
||||
.route("/v1/auth/login", post(auth::login))
|
||||
@@ -90,6 +91,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/admin/users", get(admin::list_users))
|
||||
.route("/v1/admin/users/{id}", patch(admin::update_user))
|
||||
.route("/v1/admin/users/{id}/credits", post(admin::adjust_credits))
|
||||
.route("/v1/admin/users/{id}/packages", post(admin::grant_package))
|
||||
.route("/v1/admin/prompts", get(prompts::list))
|
||||
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
|
||||
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
|
||||
@@ -127,7 +129,7 @@ async fn public_config(State(state): St) -> Json<Value> {
|
||||
"summary_model": c.summary_model,
|
||||
"password_login": c.password_login,
|
||||
"mock_payments": c.mock_payments,
|
||||
"person_pack_size": c.person_pack_size,
|
||||
"unlimited_daily_limit": c.unlimited_daily_limit,
|
||||
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1,38 +1,49 @@
|
||||
//! Payments. Until Stripe is connected, `MOCK_PAYMENTS=true` turns on a
|
||||
//! stand-in: "paying" grants what was bought right away (an analysis unit or
|
||||
//! a person package), so the paid flow can be used end to end.
|
||||
//! Packages and payments. Until Stripe is connected, `MOCK_PAYMENTS=true`
|
||||
//! turns on a stand-in: "paying" grants the package right away, so the paid
|
||||
//! flow can be used end to end.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St};
|
||||
use crate::auth::AuthUser;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::packages::{self, CATALOG, Source};
|
||||
use crate::persons;
|
||||
use crate::views::rfc3339;
|
||||
|
||||
/// The package catalog (public).
|
||||
pub async fn catalog() -> Json<Value> {
|
||||
Json(json!({ "packages": CATALOG.iter().map(packages::Package::view).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MockPayment {
|
||||
/// One analysis unit.
|
||||
/// A package id from the catalog.
|
||||
package: Option<String>,
|
||||
/// Shorthand: the cheapest package with one unit of this kind.
|
||||
unit: Option<Unit>,
|
||||
package: Option<Package>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Package {
|
||||
/// `PERSON_PACK_SIZE` more persons.
|
||||
Persons,
|
||||
/// Any number of persons.
|
||||
PersonsUnlimited,
|
||||
/// What the user has now: units left, person slots, the unlimited package.
|
||||
pub async fn holdings(state: &crate::AppState, auth: &AuthUser) -> Result<Value, ApiError> {
|
||||
let mut conn = state.db.acquire().await?;
|
||||
let balance = credits::balance(&mut conn, auth.id()).await?;
|
||||
let persons = persons::slots(&mut conn, auth, state.config.free_person_slots).await?;
|
||||
let until = packages::unlimited_until(&mut conn, auth.id()).await?;
|
||||
Ok(json!({
|
||||
"analyses_left": balance.view(),
|
||||
"persons": persons.view(),
|
||||
"unlimited_until": until.map(rfc3339),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Grants an analysis unit or a person package as a (pretend) purchase.
|
||||
/// Grants a package as a (pretend) purchase.
|
||||
pub async fn mock(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
@@ -41,38 +52,17 @@ pub async fn mock(
|
||||
if !state.config.mock_payments {
|
||||
return Err(ApiError::NotFound("payment method"));
|
||||
}
|
||||
let (unit, delta) = match (req.unit, req.package) {
|
||||
(Some(unit), None) => (Some(unit), 1),
|
||||
(None, Some(Package::Persons)) => (Some(Unit::Person), state.config.person_pack_size),
|
||||
(None, Some(Package::PersonsUnlimited)) => (None, 0),
|
||||
_ => return Err(ApiError::BadRequest("give either unit or package".into())),
|
||||
let id = match (req.package.as_deref(), req.unit) {
|
||||
(Some(id), None) => id,
|
||||
(None, Some(Unit::Natal)) => "single",
|
||||
(None, Some(Unit::Synastry)) => "addon_synastry",
|
||||
(None, Some(Unit::Person)) => "addon_persons",
|
||||
_ => return Err(ApiError::BadRequest("give either package or unit".into())),
|
||||
};
|
||||
let package = packages::find(id).ok_or(ApiError::NotFound("package"))?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
match unit {
|
||||
Some(unit) => {
|
||||
sqlx::query(
|
||||
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \
|
||||
VALUES ($1, $2, $3, $4, 'purchase', 'mock payment')",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(unit.as_str())
|
||||
.bind(delta as i32)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
None => {
|
||||
sqlx::query(
|
||||
"INSERT INTO entitlements (user_id, entitlement, note) VALUES ($1, 'unlimited_persons', 'mock payment') \
|
||||
ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(auth.id())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let balance = credits::balance(&mut tx, auth.id()).await?;
|
||||
let persons = persons::slots(&mut tx, &auth, state.config.free_person_slots).await?;
|
||||
packages::grant(&mut tx, auth.id(), package, Source::Mock, Some(auth.id()), Some("mock payment")).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({ "analyses_left": balance.view(), "persons": persons.view() })))
|
||||
tracing::info!(user = %auth.id(), package = package.id, "mock payment");
|
||||
Ok(Json(holdings(&state, &auth).await?))
|
||||
}
|
||||
|
||||
@@ -755,11 +755,7 @@ async fn admins_get_free_analyses_and_mock_payments_add_units(pool: PgPool) {
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn persons_use_package_slots(pool: PgPool) {
|
||||
let app = TestApp::with_config(pool, |c| {
|
||||
c.free_person_slots = 1;
|
||||
c.person_pack_size = 2;
|
||||
})
|
||||
.await;
|
||||
let app = TestApp::with_config(pool, |c| c.free_person_slots = 1).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
assert_eq!(own["kind"], "own");
|
||||
@@ -780,16 +776,15 @@ async fn persons_use_package_slots(pool: PgPool) {
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(persons(app.get("/v1/me", Some(&anna)).await.body)["left"], 0);
|
||||
|
||||
// a package adds two slots
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "persons"})).await;
|
||||
assert_eq!(r.body["persons"], json!({"used": 1, "limit": 3, "left": 2, "unlimited": false}), "{}", r.body);
|
||||
// a person package adds five slots
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "addon_persons"})).await;
|
||||
assert_eq!(r.body["persons"], json!({"used": 1, "limit": 6, "left": 5, "unlimited": false}), "{}", r.body);
|
||||
let second = app.chart(&anna, "Cili", false, "1986-01-01").await;
|
||||
app.chart(&anna, "Dani", false, "1987-01-01").await;
|
||||
let r = app.post("/v1/charts", Some(&anna), new_person("1988-01-01")).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT);
|
||||
assert_eq!(persons(app.get("/v1/me", Some(&anna)).await.body)["left"], 3);
|
||||
|
||||
// the unlimited package
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "persons_unlimited"})).await;
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "unlimited"})).await;
|
||||
assert_eq!(r.body["persons"], json!({"used": 3, "limit": null, "left": null, "unlimited": true}));
|
||||
app.chart(&anna, "Emma", false, "1988-01-01").await;
|
||||
let list = app.get("/v1/charts", Some(&anna)).await.body;
|
||||
@@ -991,3 +986,85 @@ async fn comparisons_with_persons(pool: PgPool) {
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_analysed")));
|
||||
assert_eq!(app.get("/v1/synastries", Some(&anna)).await.body["synastries"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
/// An admin (or not) gives `user` a package.
|
||||
async fn grant_package(app: &TestApp, token: &str, user: &str, package: &str) -> Response {
|
||||
let body = json!({"package": package, "note": "ajándék"});
|
||||
app.call("POST", &format!("/v1/admin/users/{user}/packages"), Some(token), Some(body)).await
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn packages_grant_units_and_unlimited(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let anna_id = app.get("/v1/me", Some(&anna)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
|
||||
// the catalog is public
|
||||
let r = app.get("/v1/packages", None).await;
|
||||
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", "unlimited", "addon_synastry", "addon_persons"]);
|
||||
assert_eq!(
|
||||
(&r.body["packages"][2]["badge"], &r.body["packages"][2]["per_analysis_huf"]),
|
||||
(&json!("Legnépszerűbb"), &json!(1090))
|
||||
);
|
||||
|
||||
// an admin gives a package as a gift
|
||||
assert_eq!(grant_package(&app, &anna, &anna_id, "family").await.status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(grant_package(&app, &admin, &anna_id, "gold").await.status, StatusCode::NOT_FOUND);
|
||||
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})),
|
||||
"{}",
|
||||
r.body
|
||||
);
|
||||
let me = app.get("/v1/me", Some(&anna)).await.body;
|
||||
assert_eq!((&me["persons"]["limit"], &me["unlimited_until"]), (&json!(10), &Value::Null)); // 5 free + 5
|
||||
let (source, price): (String, i32) =
|
||||
sqlx::query_as("SELECT source, price_huf FROM package_orders WHERE package = 'family'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((source.as_str(), price), ("admin", 0));
|
||||
|
||||
// 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}), "{}", 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, 6990);
|
||||
|
||||
// unlimited: a year, and a second one extends it
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let bela_id = app.get("/v1/me", Some(&bela)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
grant_package(&app, &admin, &bela_id, "unlimited").await;
|
||||
let r = grant_package(&app, &admin, &bela_id, "unlimited").await;
|
||||
let until = time::OffsetDateTime::parse(
|
||||
r.body["unlimited_until"].as_str().unwrap(),
|
||||
&time::format_description::well_known::Rfc3339,
|
||||
)
|
||||
.unwrap();
|
||||
let days = (until - time::OffsetDateTime::now_utc()).whole_days();
|
||||
assert!((725..=733).contains(&days), "{days}");
|
||||
assert_eq!(app.get("/v1/me", Some(&bela)).await.body["persons"]["unlimited"], true);
|
||||
|
||||
// analyses use no unit, up to the daily cap (3 in tests)
|
||||
for (i, date) in ["1980-01-01", "1981-01-01", "1982-01-01"].into_iter().enumerate() {
|
||||
let chart = app.chart(&bela, &format!("P{i}"), i == 0, date).await;
|
||||
let r = app
|
||||
.call("POST", &format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()), Some(&bela), None)
|
||||
.await;
|
||||
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(0)), "{}", r.body);
|
||||
}
|
||||
let fourth = app.chart(&bela, "P3", false, "1983-01-01").await;
|
||||
let uri = format!("/v1/charts/{}/analyses", fourth["id"].as_str().unwrap());
|
||||
let r = app.call("POST", &uri, Some(&bela), None).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::TOO_MANY_REQUESTS, Some("fair_use_limit")));
|
||||
|
||||
// after it ends, units are needed again
|
||||
sqlx::query("UPDATE entitlements SET expires_at = now() - interval '1 day'").execute(&pool).await.unwrap();
|
||||
let r = app.call("POST", &uri, Some(&bela), None).await;
|
||||
assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED);
|
||||
assert_eq!(app.get("/v1/me", Some(&bela)).await.body["unlimited_until"], Value::Null);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user