Persons: other people's charts with package slots, list page, switcher
- charts.kind own/person; a new person uses a 'person' unit (not refunded on delete); person packages and an unlimited entitlement; admins unlimited - a person's birth data can be corrected within an hour (admins any time) - /kepletek list with tiles, /kepletek/uj, correction page, mock person packages, chart page title switches between charts keeping the tab Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -45,8 +45,12 @@ pub struct Config {
|
||||
pub summary_model: String,
|
||||
/// `ANALYSIS_PROMPT_VERSION` (default `v2`); part of the analysis cache key.
|
||||
pub prompt_version: String,
|
||||
/// `MAX_CHARTS_PER_USER` (default 50).
|
||||
/// `MAX_CHARTS_PER_USER` (default 1000): a safety cap, also for unlimited packages.
|
||||
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,
|
||||
}
|
||||
|
||||
fn var(name: &str) -> Option<String> {
|
||||
@@ -99,7 +103,9 @@ impl Config {
|
||||
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
|
||||
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()),
|
||||
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()),
|
||||
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 50)?,
|
||||
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)?,
|
||||
};
|
||||
if config.session_ttl_days < 1 {
|
||||
bail!("SESSION_TTL_DAYS must be at least 1");
|
||||
@@ -128,6 +134,8 @@ impl Config {
|
||||
summary_model: "anthropic/claude-summary".into(),
|
||||
prompt_version: "v1".into(),
|
||||
max_charts_per_user: 50,
|
||||
free_person_slots: 5,
|
||||
person_pack_size: 5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ use crate::error::ApiError;
|
||||
pub enum Unit {
|
||||
Natal,
|
||||
Synastry,
|
||||
/// A slot for adding a person (see [`crate::persons`]).
|
||||
Person,
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
@@ -21,6 +23,7 @@ impl Unit {
|
||||
match self {
|
||||
Unit::Natal => "natal",
|
||||
Unit::Synastry => "synastry",
|
||||
Unit::Person => "person",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +33,8 @@ impl Unit {
|
||||
pub struct Balance {
|
||||
pub natal: i64,
|
||||
pub synastry: i64,
|
||||
/// Bought person slots (not the slots left; see [`crate::persons::slots`]).
|
||||
pub person: i64,
|
||||
}
|
||||
|
||||
impl Balance {
|
||||
@@ -37,6 +42,7 @@ impl Balance {
|
||||
match unit {
|
||||
Unit::Natal => self.natal,
|
||||
Unit::Synastry => self.synastry,
|
||||
Unit::Person => self.person,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,15 +52,16 @@ impl Balance {
|
||||
}
|
||||
|
||||
pub async fn balance(conn: &mut PgConnection, user_id: Uuid) -> Result<Balance, ApiError> {
|
||||
let (natal, synastry): (i64, i64) = sqlx::query_as(
|
||||
let (natal, synastry, person): (i64, i64, i64) = sqlx::query_as(
|
||||
"SELECT COALESCE(SUM(delta) FILTER (WHERE unit = 'natal'), 0)::bigint, \
|
||||
COALESCE(SUM(delta) FILTER (WHERE unit = 'synastry'), 0)::bigint \
|
||||
COALESCE(SUM(delta) FILTER (WHERE unit = 'synastry'), 0)::bigint, \
|
||||
COALESCE(SUM(delta) FILTER (WHERE unit = 'person' AND reason <> 'person'), 0)::bigint \
|
||||
FROM credit_ledger WHERE user_id = $1",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_one(conn)
|
||||
.await?;
|
||||
Ok(Balance { natal, synastry })
|
||||
Ok(Balance { natal, synastry, person })
|
||||
}
|
||||
|
||||
/// Spends one unit inside the caller's transaction. The user row is locked
|
||||
|
||||
@@ -13,6 +13,7 @@ mod config;
|
||||
mod credits;
|
||||
mod error;
|
||||
mod google;
|
||||
mod persons;
|
||||
mod routes;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! A person's birth data can be corrected within an hour of adding them,
|
||||
//! then it is locked (admins: any time).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgConnection;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::ApiError;
|
||||
use db::Role;
|
||||
|
||||
/// How long after adding a person their birth data can be corrected.
|
||||
pub const EDIT_WINDOW: Duration = Duration::hours(1);
|
||||
|
||||
pub const LIMIT_MESSAGE: &str = "Elérted a felvehető személyek számát. További személyekhez bővítsd a csomagodat.";
|
||||
pub const LOCKED_MESSAGE: &str = "A személy születési adatai csak a felvételt követő egy órán belül javíthatók.";
|
||||
|
||||
/// A user's person slots.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Slots {
|
||||
/// Persons added so far (deleted ones included).
|
||||
pub used: i64,
|
||||
/// Free slots plus the bought (or granted) ones.
|
||||
pub granted: i64,
|
||||
pub unlimited: bool,
|
||||
}
|
||||
|
||||
impl Slots {
|
||||
/// Slots left; `None`: no limit.
|
||||
pub fn left(self) -> Option<i64> {
|
||||
(!self.unlimited).then(|| (self.granted - self.used).max(0))
|
||||
}
|
||||
|
||||
pub fn view(self) -> Value {
|
||||
json!({
|
||||
"used": self.used,
|
||||
"limit": (!self.unlimited).then_some(self.granted),
|
||||
"left": self.left(),
|
||||
"unlimited": self.unlimited,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn slots(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Result<Slots, ApiError> {
|
||||
let (used, bought, entitled): (i64, i64, bool) = sqlx::query_as(
|
||||
"SELECT \
|
||||
(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')",
|
||||
)
|
||||
.bind(auth.id())
|
||||
.fetch_one(conn)
|
||||
.await?;
|
||||
Ok(Slots { used, granted: free + bought, unlimited: entitled || auth.user.has_role(Role::Admin) })
|
||||
}
|
||||
|
||||
/// Fails when no slot is left (a quick check before calculating a chart).
|
||||
pub async fn check(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Result<(), ApiError> {
|
||||
if slots(conn, auth, free).await?.left() == Some(0) {
|
||||
return Err(ApiError::conflict("person_limit_reached", LIMIT_MESSAGE));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Uses a slot for the new person `chart_id`, inside the transaction that
|
||||
/// saves it. The user row is locked, so parallel saves cannot overspend.
|
||||
pub async fn spend(tx: &mut PgConnection, auth: &AuthUser, free: i64, chart_id: Uuid) -> Result<(), ApiError> {
|
||||
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?;
|
||||
check(tx, auth, free).await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, chart_id) VALUES ($1, $2, 'person', -1, 'person', $3)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(chart_id)
|
||||
.execute(tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the birth data of a person added at `created_at` can still be corrected.
|
||||
pub fn editable(auth: &AuthUser, created_at: OffsetDateTime, now: OffsetDateTime) -> bool {
|
||||
auth.user.has_role(Role::Admin) || now - created_at < EDIT_WINDOW
|
||||
}
|
||||
@@ -31,12 +31,14 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let mut conn = state.db.acquire().await?;
|
||||
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?;
|
||||
Ok(Json(json!({
|
||||
"user": UserView::from(&auth.user),
|
||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||
"primary_chart_id": primary.map(|(id,)| id),
|
||||
"analyses_left": balance.view(),
|
||||
"birth_change": birth_change,
|
||||
"persons": persons.view(),
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Natal charts of a user: their own (primary) chart and charts of others
|
||||
//! they entered (partner, family). Calculated by the horoscope service.
|
||||
//! Natal charts of a user: their own chart (kind `own`; the current one is
|
||||
//! primary) and charts of other people they added (kind `person`, see
|
||||
//! [`crate::persons`]). Calculated by the horoscope service.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
@@ -16,6 +17,7 @@ use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::birth_changes;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::persons;
|
||||
use crate::views::{chart_hash, chart_highlights, rfc3339};
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
@@ -24,6 +26,8 @@ pub struct ChartRow {
|
||||
pub owner_id: Uuid,
|
||||
pub label: String,
|
||||
pub is_primary: bool,
|
||||
/// `own` or `person`.
|
||||
pub kind: String,
|
||||
pub birth_data: Value,
|
||||
pub result: Value,
|
||||
pub chart_hash: String,
|
||||
@@ -31,7 +35,8 @@ pub struct ChartRow {
|
||||
pub updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
const CHART_COLUMNS: &str = "id, owner_id, label, is_primary, birth_data, result, chart_hash, created_at, updated_at";
|
||||
const CHART_COLUMNS: &str =
|
||||
"id, owner_id, label, is_primary, kind, birth_data, result, chart_hash, created_at, updated_at";
|
||||
|
||||
impl ChartRow {
|
||||
/// Full view for the owner.
|
||||
@@ -40,6 +45,8 @@ impl ChartRow {
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"is_primary": self.is_primary,
|
||||
"kind": self.kind,
|
||||
"editable_until": self.editable_until().map(rfc3339),
|
||||
"birth_data": self.birth_data,
|
||||
"highlights": chart_highlights(&self.result),
|
||||
"chart": self.result,
|
||||
@@ -49,11 +56,23 @@ impl ChartRow {
|
||||
})
|
||||
}
|
||||
|
||||
/// Until when a person's birth data can be corrected (admins: any time).
|
||||
fn editable_until(&self) -> Option<OffsetDateTime> {
|
||||
(self.kind == "person").then(|| self.created_at + persons::EDIT_WINDOW)
|
||||
}
|
||||
|
||||
pub fn summary_view(&self) -> Value {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"is_primary": self.is_primary,
|
||||
"kind": self.kind,
|
||||
"editable_until": self.editable_until().map(rfc3339),
|
||||
"birth": {
|
||||
"date": self.birth_data.get("date"),
|
||||
"time": self.birth_data.get("time"),
|
||||
"place": self.result.pointer("/location/place/name"),
|
||||
},
|
||||
"highlights": chart_highlights(&self.result),
|
||||
"created_at": rfc3339(self.created_at),
|
||||
})
|
||||
@@ -140,12 +159,15 @@ pub async fn create(
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let label = clean_label(&req.label)?;
|
||||
let birth = clean_birth(req.birth)?;
|
||||
let existing: Option<ChartRow> =
|
||||
sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts WHERE owner_id = $1 AND birth_data = $2 LIMIT 1"))
|
||||
.bind(auth.id())
|
||||
.bind(&birth)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let kind = if req.is_primary { "own" } else { "person" };
|
||||
let existing: Option<ChartRow> = sqlx::query_as(&format!(
|
||||
"SELECT {CHART_COLUMNS} FROM charts WHERE owner_id = $1 AND kind = $2 AND birth_data = $3 LIMIT 1"
|
||||
))
|
||||
.bind(auth.id())
|
||||
.bind(kind)
|
||||
.bind(&birth)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
if let Some(chart) = existing {
|
||||
if req.is_primary && !chart.is_primary {
|
||||
let mut tx = state.db.begin().await?;
|
||||
@@ -175,6 +197,10 @@ pub async fn create(
|
||||
format!("at most {} charts can be saved", state.config.max_charts_per_user),
|
||||
));
|
||||
}
|
||||
let free = state.config.free_person_slots;
|
||||
if kind == "person" {
|
||||
persons::check(&mut *state.db.acquire().await?, &auth, free).await?;
|
||||
}
|
||||
let (birth, result, hash) = calculate(&state, birth).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
@@ -185,13 +211,14 @@ pub async fn create(
|
||||
.await?;
|
||||
}
|
||||
let row: ChartRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO charts (id, owner_id, label, is_primary, birth_data, result, chart_hash) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING {CHART_COLUMNS}"
|
||||
"INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING {CHART_COLUMNS}"
|
||||
))
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(label)
|
||||
.bind(req.is_primary)
|
||||
.bind(kind)
|
||||
.bind(birth)
|
||||
.bind(result)
|
||||
.bind(hash)
|
||||
@@ -199,6 +226,8 @@ pub async fn create(
|
||||
.await?;
|
||||
if req.is_primary {
|
||||
birth_changes::record(&mut tx, &auth, row.id).await?;
|
||||
} else {
|
||||
persons::spend(&mut tx, &auth, free, row.id).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
queue_summary(&state, &auth, &row).await;
|
||||
@@ -218,10 +247,14 @@ pub async fn get_one(
|
||||
pub struct UpdateChart {
|
||||
label: Option<String>,
|
||||
is_primary: Option<bool>,
|
||||
/// Corrected birth data of a person, within an hour of adding them
|
||||
/// (admins: any time). The user's own data is changed by saving a new
|
||||
/// own chart instead (analyses belong to the old one).
|
||||
birth: Option<Value>,
|
||||
}
|
||||
|
||||
/// Renames the chart or changes which chart is the user's own. Birth data is
|
||||
/// not editable: a corrected chart is a new chart (analyses belong to the old one).
|
||||
/// Renames the chart, changes which chart is the user's own (a person made
|
||||
/// primary becomes `own`) or corrects a person's birth data.
|
||||
pub async fn update(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
@@ -234,7 +267,22 @@ pub async fn update(
|
||||
None => chart.label.clone(),
|
||||
};
|
||||
let is_primary = req.is_primary.unwrap_or(chart.is_primary);
|
||||
let recalculated = match req.birth {
|
||||
Some(birth) => Some(corrected_birth(&state, &auth, &chart, birth).await?),
|
||||
None => None,
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
if let Some((birth, result, hash)) = &recalculated {
|
||||
// The old summary (and an admin's analyses) no longer match the chart.
|
||||
sqlx::query("DELETE FROM analyses WHERE chart_id = $1").bind(id).execute(&mut *tx).await?;
|
||||
sqlx::query("UPDATE charts SET birth_data = $1, result = $2, chart_hash = $3 WHERE id = $4")
|
||||
.bind(birth)
|
||||
.bind(result)
|
||||
.bind(hash)
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
if is_primary && !chart.is_primary {
|
||||
sqlx::query("UPDATE charts SET is_primary = false, updated_at = now() WHERE owner_id = $1 AND is_primary")
|
||||
.bind(auth.id())
|
||||
@@ -242,7 +290,8 @@ pub async fn update(
|
||||
.await?;
|
||||
}
|
||||
let row: ChartRow = sqlx::query_as(&format!(
|
||||
"UPDATE charts SET label = $1, is_primary = $2, updated_at = now() WHERE id = $3 RETURNING {CHART_COLUMNS}"
|
||||
"UPDATE charts SET label = $1, is_primary = $2, kind = CASE WHEN $2 THEN 'own' ELSE kind END, \
|
||||
updated_at = now() WHERE id = $3 RETURNING {CHART_COLUMNS}"
|
||||
))
|
||||
.bind(label)
|
||||
.bind(is_primary)
|
||||
@@ -253,9 +302,48 @@ pub async fn update(
|
||||
birth_changes::record(&mut tx, &auth, id).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
if recalculated.is_some() {
|
||||
queue_summary(&state, &auth, &row).await;
|
||||
}
|
||||
Ok(Json(row.owner_view()))
|
||||
}
|
||||
|
||||
/// Checks that a person's birth data may still be corrected and calculates the new chart.
|
||||
async fn corrected_birth(
|
||||
state: &AppState,
|
||||
auth: &AuthUser,
|
||||
chart: &ChartRow,
|
||||
birth: Value,
|
||||
) -> Result<(Value, Value, String), ApiError> {
|
||||
if chart.kind != "person" {
|
||||
return Err(ApiError::BadRequest("the own birth data is changed by saving a new own chart".into()));
|
||||
}
|
||||
if !persons::editable(auth, chart.created_at, OffsetDateTime::now_utc()) {
|
||||
return Err(ApiError::conflict("person_locked", persons::LOCKED_MESSAGE));
|
||||
}
|
||||
let admin = auth.user.has_role(db::Role::Admin);
|
||||
let (analysed, in_synastry): (bool, bool) = sqlx::query_as(
|
||||
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed'), \
|
||||
EXISTS (SELECT 1 FROM synastries WHERE chart1_id = $1 OR chart2_id = $1)",
|
||||
)
|
||||
.bind(chart.id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
if analysed && !admin {
|
||||
return Err(ApiError::conflict(
|
||||
"person_analysed",
|
||||
"Ehhez a személyhez már készült részletes elemzés, ezért az adatai nem módosíthatók.",
|
||||
));
|
||||
}
|
||||
if in_synastry {
|
||||
return Err(ApiError::conflict(
|
||||
"person_in_synastry",
|
||||
"A személy szerepel egy összevetésben, ezért az adatai nem módosíthatók.",
|
||||
));
|
||||
}
|
||||
calculate(state, birth).await
|
||||
}
|
||||
|
||||
/// Deletes the chart with its synastries, analyses and shares.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
|
||||
@@ -122,6 +122,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,
|
||||
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Payments. Until Stripe is connected, `MOCK_PAYMENTS=true` turns on a
|
||||
//! stand-in: "paying" adds one analysis unit right away, so the paid flow can
|
||||
//! be used end to end.
|
||||
//! 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.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
@@ -13,14 +13,26 @@ use super::{Body, St};
|
||||
use crate::auth::AuthUser;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::persons;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MockPayment {
|
||||
unit: Unit,
|
||||
/// One analysis unit.
|
||||
unit: Option<Unit>,
|
||||
package: Option<Package>,
|
||||
}
|
||||
|
||||
/// Adds one unit of the given kind as a (pretend) purchase.
|
||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Package {
|
||||
/// `PERSON_PACK_SIZE` more persons.
|
||||
Persons,
|
||||
/// Any number of persons.
|
||||
PersonsUnlimited,
|
||||
}
|
||||
|
||||
/// Grants an analysis unit or a person package as a (pretend) purchase.
|
||||
pub async fn mock(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
@@ -29,16 +41,38 @@ 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 mut tx = state.db.begin().await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) VALUES ($1, $2, $3, 1, 'purchase', 'mock payment')",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(req.unit.as_str())
|
||||
.execute(&mut *tx)
|
||||
.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?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({ "analyses_left": balance.view() })))
|
||||
Ok(Json(json!({ "analyses_left": balance.view(), "persons": persons.view() })))
|
||||
}
|
||||
|
||||
@@ -752,3 +752,78 @@ async fn admins_get_free_analyses_and_mock_payments_add_units(pool: PgPool) {
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"unit": "natal"})).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[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 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");
|
||||
let persons = |me: Value| me["persons"].clone();
|
||||
assert_eq!(
|
||||
persons(app.get("/v1/me", Some(&anna)).await.body),
|
||||
json!({"used": 0, "limit": 1, "left": 1, "unlimited": false})
|
||||
);
|
||||
|
||||
// the free slot, then the limit; deleting does not give the slot back
|
||||
let first = app.chart(&anna, "Béla", false, "1985-08-02").await;
|
||||
assert_eq!((&first["kind"], first["editable_until"].is_string()), (&json!("person"), true));
|
||||
let new_person = |date: &str| json!({"label": "Cili", "birth": {"date": date, "time": "14:30", "country": "HU", "place": "Szeged"}});
|
||||
let r = app.post("/v1/charts", Some(&anna), new_person("1986-01-01")).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_limit_reached")));
|
||||
assert_eq!(r.body["error"]["message"], crate::persons::LIMIT_MESSAGE);
|
||||
let r = app.call("DELETE", &format!("/v1/charts/{}", first["id"].as_str().unwrap()), Some(&anna), None).await;
|
||||
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);
|
||||
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);
|
||||
|
||||
// the unlimited package
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "persons_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;
|
||||
let kinds: Vec<&str> = list["charts"].as_array().unwrap().iter().map(|c| c["kind"].as_str().unwrap()).collect();
|
||||
assert_eq!(kinds, ["own", "person", "person", "person"]);
|
||||
assert_eq!(list["charts"][1]["birth"]["date"], "1988-01-01");
|
||||
|
||||
// a person's birth data can be corrected within an hour, then it is locked
|
||||
let id = second["id"].as_str().unwrap();
|
||||
let corrected = json!({"birth": {"date": "1986-01-02", "time": "10:00", "country": "HU", "place": "Szeged"}});
|
||||
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(corrected.clone())).await;
|
||||
assert_eq!((r.status, &r.body["birth_data"]["date"]), (StatusCode::OK, &json!("1986-01-02")), "{}", r.body);
|
||||
sqlx::query("UPDATE charts SET created_at = now() - interval '2 hours' WHERE id = $1::uuid")
|
||||
.bind(id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(corrected.clone())).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_locked")));
|
||||
let r =
|
||||
app.call("PATCH", &format!("/v1/charts/{}", own["id"].as_str().unwrap()), Some(&anna), Some(corrected)).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
|
||||
// admins: no limit, corrections any time
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
assert_eq!(persons(app.get("/v1/me", Some(&admin)).await.body)["unlimited"], true);
|
||||
let p = app.chart(&admin, "Feri", false, "1970-01-01").await;
|
||||
let pid = p["id"].as_str().unwrap();
|
||||
sqlx::query("UPDATE charts SET created_at = now() - interval '2 days' WHERE id = $1::uuid")
|
||||
.bind(pid)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let corrected = json!({"birth": {"date": "1970-01-02", "time": "10:00", "country": "HU", "place": "Szeged"}});
|
||||
let r = app.call("PATCH", &format!("/v1/charts/{pid}"), Some(&admin), Some(corrected)).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user