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:
@@ -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?))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user