Detailed analysis button, loading wheel, birth data change limits
Backend: - own birth data: three corrections within an hour of the first save, then one change per 24 hours (birth_data_changes); 429 birth_data_change_limit with the user-facing message; /v1/me birth_change shows the notice; admins are not limited - admins get detailed analyses free (no unit spent) - POST /v1/payments/mock (MOCK_PAYMENTS): stand-in payment that adds a unit, until Stripe is connected; on in the compose files for now Frontend: - detailed analysis offer: admin starts it free, users with units confirm, others go through the (stand-in) payment step - turning wheel with elapsed time while the summary or the analysis is being written - no "adatok javítása" on the chart page (only in the profile), limit notice there; wheel hover highlighting removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
//! Limits on changing a user's own birth data.
|
||||
//!
|
||||
//! The first save is free. Within an hour of it the user may correct the data
|
||||
//! three more times; after that, once per 24 hours. Admins are not limited.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgConnection;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::ApiError;
|
||||
use crate::views::rfc3339;
|
||||
use db::Role;
|
||||
|
||||
const GRACE_PERIOD: Duration = Duration::hours(1);
|
||||
const GRACE_CHANGES: usize = 3;
|
||||
const DAILY: Duration = Duration::hours(24);
|
||||
|
||||
pub const DAILY_NOTICE: &str = "A rendszer csak napi egy módosítást engedélyez.";
|
||||
|
||||
/// Where a user stands with changing their birth data.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Status {
|
||||
/// The grace period is over (or used up): one change per day.
|
||||
pub daily: bool,
|
||||
/// When the next change is possible; `None`: now.
|
||||
pub next_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
/// The rule itself, over the times of the earlier saves (oldest first).
|
||||
pub fn evaluate(saves: &[OffsetDateTime], now: OffsetDateTime) -> Status {
|
||||
let (Some(&first), Some(&last)) = (saves.first(), saves.last()) else {
|
||||
return Status { daily: false, next_at: None };
|
||||
};
|
||||
let corrections = saves.len() - 1;
|
||||
if now - first < GRACE_PERIOD && corrections < GRACE_CHANGES {
|
||||
return Status { daily: false, next_at: None };
|
||||
}
|
||||
let next = last + DAILY;
|
||||
Status { daily: true, next_at: (next > now).then_some(next) }
|
||||
}
|
||||
|
||||
async fn saves(conn: &mut PgConnection, user_id: Uuid) -> Result<Vec<OffsetDateTime>, ApiError> {
|
||||
let rows: Vec<(OffsetDateTime,)> =
|
||||
sqlx::query_as("SELECT created_at FROM birth_data_changes WHERE user_id = $1 ORDER BY created_at")
|
||||
.bind(user_id)
|
||||
.fetch_all(conn)
|
||||
.await?;
|
||||
Ok(rows.into_iter().map(|(t,)| t).collect())
|
||||
}
|
||||
|
||||
/// "23 óra 5 perc" / "40 perc" (rounded up to a minute).
|
||||
fn wait_text(wait: Duration) -> String {
|
||||
let minutes = (wait.whole_seconds() + 59) / 60;
|
||||
let (h, m) = (minutes / 60, minutes % 60);
|
||||
match (h, m) {
|
||||
(0, m) => format!("{m} perc"),
|
||||
(h, 0) => format!("{h} óra"),
|
||||
(h, m) => format!("{h} óra {m} perc"),
|
||||
}
|
||||
}
|
||||
|
||||
fn limit_error(next_at: OffsetDateTime, now: OffsetDateTime) -> ApiError {
|
||||
ApiError::Limited {
|
||||
code: "birth_data_change_limit",
|
||||
message: format!("{DAILY_NOTICE} Legközelebb {} múlva módosíthatod.", wait_text(next_at - now)),
|
||||
}
|
||||
}
|
||||
|
||||
/// For `/v1/me`: whether the daily limit applies and, if so, the notice to show.
|
||||
pub async fn view(conn: &mut PgConnection, auth: &AuthUser) -> Result<Value, ApiError> {
|
||||
if auth.user.has_role(Role::Admin) {
|
||||
return Ok(json!({ "limited": false, "next_change_at": null, "notice": null }));
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let status = evaluate(&saves(conn, auth.id()).await?, now);
|
||||
let notice = match status.next_at {
|
||||
Some(next) => Some(format!("{DAILY_NOTICE} Legközelebb {} múlva módosíthatod.", wait_text(next - now))),
|
||||
None if status.daily => Some(DAILY_NOTICE.to_string()),
|
||||
None => None,
|
||||
};
|
||||
Ok(json!({
|
||||
"limited": status.daily,
|
||||
"next_change_at": status.next_at.map(rfc3339),
|
||||
"notice": notice,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Checks the limit and records the change, inside the transaction that
|
||||
/// makes `chart_id` the user's own chart. Locks the user row, so parallel
|
||||
/// saves are counted one after the other.
|
||||
pub async fn record(tx: &mut PgConnection, auth: &AuthUser, chart_id: Uuid) -> Result<(), ApiError> {
|
||||
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?;
|
||||
if !auth.user.has_role(Role::Admin) {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if let Some(next) = evaluate(&saves(tx, auth.id()).await?, now).next_at {
|
||||
return Err(limit_error(next, now));
|
||||
}
|
||||
}
|
||||
sqlx::query("INSERT INTO birth_data_changes (id, user_id, chart_id) VALUES ($1, $2, $3)")
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(chart_id)
|
||||
.execute(tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn at(minutes: i64) -> OffsetDateTime {
|
||||
OffsetDateTime::UNIX_EPOCH + Duration::minutes(minutes)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_save_is_free() {
|
||||
assert_eq!(evaluate(&[], at(0)), Status { daily: false, next_at: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_corrections_within_the_first_hour() {
|
||||
let now = at(30);
|
||||
assert_eq!(evaluate(&[at(0)], now).next_at, None);
|
||||
assert_eq!(evaluate(&[at(0), at(5), at(10)], now).next_at, None);
|
||||
// the third correction used up the grace period
|
||||
let s = evaluate(&[at(0), at(5), at(10), at(20)], now);
|
||||
assert!(s.daily);
|
||||
assert_eq!(s.next_at, Some(at(20) + DAILY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_the_first_hour_once_a_day() {
|
||||
assert_eq!(evaluate(&[at(0)], at(61)), Status { daily: true, next_at: Some(at(24 * 60)) });
|
||||
assert_eq!(evaluate(&[at(0)], at(24 * 60)), Status { daily: true, next_at: None });
|
||||
assert_eq!(evaluate(&[at(0), at(24 * 60 + 5)], at(30 * 60)).next_at, Some(at(48 * 60 + 5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_is_written_in_hours_and_minutes() {
|
||||
assert_eq!(wait_text(Duration::minutes(40)), "40 perc");
|
||||
assert_eq!(wait_text(Duration::hours(3)), "3 óra");
|
||||
assert_eq!(wait_text(Duration::seconds(23 * 3600 + 4 * 60 + 1)), "23 óra 5 perc");
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ pub struct Config {
|
||||
/// `PASSWORD_LOGIN` (default `false`): e-mail and password registration and
|
||||
/// login. Off in production, where only Google, Apple and Facebook are offered.
|
||||
pub password_login: bool,
|
||||
/// `MOCK_PAYMENTS` (default `false`): a stand-in payment that adds an
|
||||
/// analysis unit at once, until Stripe is connected.
|
||||
pub mock_payments: bool,
|
||||
/// `GOOGLE_CLIENT_IDS`: comma-separated OAuth client ids accepted as the
|
||||
/// ID token audience; empty disables Google login.
|
||||
pub google_client_ids: Vec<String>,
|
||||
@@ -87,6 +90,7 @@ impl Config {
|
||||
cookie_domain: var("COOKIE_DOMAIN"),
|
||||
session_ttl_days: parsed("SESSION_TTL_DAYS", 30)?,
|
||||
password_login: parsed("PASSWORD_LOGIN", false)?,
|
||||
mock_payments: parsed("MOCK_PAYMENTS", false)?,
|
||||
google_client_ids: list("GOOGLE_CLIENT_IDS"),
|
||||
google_jwks_url: var("GOOGLE_JWKS_URL")
|
||||
.unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()),
|
||||
@@ -115,6 +119,7 @@ impl Config {
|
||||
cookie_domain: None,
|
||||
session_ttl_days: 30,
|
||||
password_login: true,
|
||||
mock_payments: true,
|
||||
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
|
||||
google_jwks_url,
|
||||
bootstrap_admin_emails: vec!["admin@example.com".into()],
|
||||
|
||||
@@ -28,6 +28,9 @@ pub enum ApiError {
|
||||
InsufficientCredits { unit: &'static str, balance: i64 },
|
||||
#[error("too many attempts; try again later")]
|
||||
TooManyRequests,
|
||||
/// A usage limit; the message is shown to the user as is.
|
||||
#[error("{message}")]
|
||||
Limited { code: &'static str, message: String },
|
||||
/// Birth data rejected by the horoscope service; its error object is passed through.
|
||||
#[error("invalid birth data")]
|
||||
BirthData { status: StatusCode, body: Value },
|
||||
@@ -54,6 +57,7 @@ impl ApiError {
|
||||
ApiError::InvalidToken => (StatusCode::BAD_REQUEST, "invalid_token"),
|
||||
ApiError::InsufficientCredits { .. } => (StatusCode::PAYMENT_REQUIRED, "insufficient_credits"),
|
||||
ApiError::TooManyRequests => (StatusCode::TOO_MANY_REQUESTS, "too_many_requests"),
|
||||
ApiError::Limited { code, .. } => (StatusCode::TOO_MANY_REQUESTS, code),
|
||||
ApiError::BirthData { status, .. } => (*status, "invalid_birth_data"),
|
||||
ApiError::HoroscopeUnavailable(_) => (StatusCode::BAD_GATEWAY, "horoscope_unavailable"),
|
||||
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//! `backend healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod auth;
|
||||
mod birth_changes;
|
||||
mod config;
|
||||
mod credits;
|
||||
mod error;
|
||||
|
||||
@@ -28,12 +28,15 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
.bind(auth.id())
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let balance = credits::balance(&mut *state.db.acquire().await?, auth.id()).await?;
|
||||
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?;
|
||||
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,
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Text analyses (LLM) of charts and synastries.
|
||||
//!
|
||||
//! A request creates a `pending` analysis and spends one unit of its kind
|
||||
//! (`natal` or `synastry`, see [`credits`]); the worker
|
||||
//! (`natal` or `synastry`, see [`credits`]; admins pay nothing); the worker
|
||||
//! writes the text later. A finished analysis with the same cache key (same
|
||||
//! chart or synastry hash, prompt version, model and language) is copied
|
||||
//! instead, free of charge, so the same chart is never paid for twice.
|
||||
@@ -29,6 +29,7 @@ use crate::auth::AuthUser;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
|
||||
use db::Role;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct AnalysisRow {
|
||||
@@ -117,12 +118,14 @@ 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.
|
||||
let unit = match target {
|
||||
Target::Synastry { .. } => Unit::Synastry,
|
||||
_ => Unit::Natal,
|
||||
_ if auth.user.has_role(Role::Admin) => None,
|
||||
Target::Synastry { .. } => Some(Unit::Synastry),
|
||||
_ => Some(Unit::Natal),
|
||||
};
|
||||
let model = state.config.analysis_model.clone();
|
||||
let (status, row) = queue(state, auth.id(), &target, &language, &model, Some(unit)).await?;
|
||||
let (status, row) = queue(state, auth.id(), &target, &language, &model, unit).await?;
|
||||
Ok((status, Json(row.view())))
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use uuid::Uuid;
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::birth_changes;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{chart_hash, chart_highlights, rfc3339};
|
||||
|
||||
@@ -130,7 +131,8 @@ fn clean_birth(birth: Value) -> Result<Value, ApiError> {
|
||||
|
||||
/// Saves a new chart. If the user already has a chart with exactly the same
|
||||
/// birth data, that one is returned (and made primary if asked) instead of
|
||||
/// calculating it again.
|
||||
/// calculating it again. Replacing the user's own chart counts against the
|
||||
/// birth data change limit ([`birth_changes`]).
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
@@ -157,6 +159,7 @@ pub async fn create(
|
||||
.bind(chart.id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
birth_changes::record(&mut tx, &auth, row.id).await?;
|
||||
tx.commit().await?;
|
||||
queue_summary(&state, &auth, &row).await;
|
||||
return Ok((StatusCode::OK, Json(row.owner_view())));
|
||||
@@ -194,6 +197,9 @@ pub async fn create(
|
||||
.bind(hash)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if req.is_primary {
|
||||
birth_changes::record(&mut tx, &auth, row.id).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
queue_summary(&state, &auth, &row).await;
|
||||
Ok((StatusCode::CREATED, Json(row.owner_view())))
|
||||
@@ -243,6 +249,9 @@ pub async fn update(
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if is_primary && !chart.is_primary {
|
||||
birth_changes::record(&mut tx, &auth, id).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(row.owner_view()))
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ mod admin;
|
||||
mod analyses;
|
||||
mod auth;
|
||||
mod charts;
|
||||
mod payments;
|
||||
mod shares;
|
||||
mod synastries;
|
||||
|
||||
@@ -63,6 +64,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/me/password", post(account::change_password))
|
||||
.route("/v1/me/export", get(account::export))
|
||||
.route("/v1/credits", get(account::credits))
|
||||
.route("/v1/payments/mock", post(payments::mock))
|
||||
// charts
|
||||
.route("/v1/charts", get(charts::list).post(charts::create))
|
||||
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
|
||||
@@ -119,6 +121,7 @@ async fn public_config(State(state): St) -> Json<Value> {
|
||||
"analysis_model": c.analysis_model,
|
||||
"summary_model": c.summary_model,
|
||||
"password_login": c.password_login,
|
||||
"mock_payments": c.mock_payments,
|
||||
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! 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.
|
||||
|
||||
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};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MockPayment {
|
||||
unit: Unit,
|
||||
}
|
||||
|
||||
/// Adds one unit of the given kind as a (pretend) purchase.
|
||||
pub async fn mock(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<MockPayment>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
if !state.config.mock_payments {
|
||||
return Err(ApiError::NotFound("payment method"));
|
||||
}
|
||||
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?;
|
||||
let balance = credits::balance(&mut tx, auth.id()).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({ "analyses_left": balance.view() })))
|
||||
}
|
||||
@@ -400,6 +400,8 @@ async fn charts_are_private(pool: PgPool) {
|
||||
.await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::NOT_FOUND, Some("place_not_found")));
|
||||
|
||||
// (the fourth change of the own chart; the limit is tested in birth_data_changes_are_limited)
|
||||
sqlx::query("DELETE FROM birth_data_changes").execute(&app.pool).await.unwrap();
|
||||
let r = app
|
||||
.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(json!({"label": "Én", "is_primary": true})))
|
||||
.await;
|
||||
@@ -652,3 +654,101 @@ async fn synastry_analyses_use_synastry_units(pool: PgPool) {
|
||||
assert_eq!((r.status, r.body["kind"].as_str()), (StatusCode::ACCEPTED, Some("synastry")));
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], json!({"natal": 1, "synastry": 0}));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn birth_data_changes_are_limited(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["birth_change"]["limited"], json!(false));
|
||||
|
||||
// the first save and three corrections within the hour are free
|
||||
let first = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
for date in ["1990-03-16", "1990-03-17", "1990-03-18"] {
|
||||
app.chart(&anna, "Saját", true, date).await;
|
||||
}
|
||||
// saving the current data again is not a change
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/charts",
|
||||
Some(&anna),
|
||||
json!({"label": "Saját", "is_primary": true,
|
||||
"birth": {"date": "1990-03-18", "time": "14:30", "country": "HU", "place": "Szeged"}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
|
||||
// the fourth correction: once a day from now on
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/charts",
|
||||
Some(&anna),
|
||||
json!({"label": "Saját", "is_primary": true,
|
||||
"birth": {"date": "1990-03-19", "time": "14:30", "country": "HU", "place": "Szeged"}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS, "{}", r.body);
|
||||
assert_eq!(r.body["error"]["code"], json!("birth_data_change_limit"));
|
||||
let message = r.body["error"]["message"].as_str().unwrap();
|
||||
assert!(message.starts_with("A rendszer csak napi egy módosítást engedélyez."), "{message}");
|
||||
assert!(message.ends_with("óra múlva módosíthatod."), "{message}");
|
||||
// switching back to an older chart is a change too
|
||||
let r = app
|
||||
.call(
|
||||
"PATCH",
|
||||
&format!("/v1/charts/{}", first["id"].as_str().unwrap()),
|
||||
Some(&anna),
|
||||
Some(json!({"is_primary": true})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
|
||||
// other people's charts are not limited
|
||||
app.chart(&anna, "Béla", false, "1985-08-02").await;
|
||||
|
||||
let me = app.get("/v1/me", Some(&anna)).await.body;
|
||||
assert_eq!(me["birth_change"]["limited"], json!(true));
|
||||
assert!(me["birth_change"]["notice"].as_str().unwrap().contains("napi egy"));
|
||||
|
||||
// a day later it works again
|
||||
sqlx::query("UPDATE birth_data_changes SET created_at = created_at - interval '25 hours'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
app.chart(&anna, "Saját", true, "1990-03-19").await;
|
||||
|
||||
// admins are not limited
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
for day in 10..16 {
|
||||
app.chart(&admin, "Saját", true, &format!("1980-01-{day}")).await;
|
||||
}
|
||||
assert_eq!(app.get("/v1/me", Some(&admin)).await.body["birth_change"]["notice"], Value::Null);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn admins_get_free_analyses_and_mock_payments_add_units(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
||||
let r =
|
||||
app.call("POST", &format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()), Some(&admin), None).await;
|
||||
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(0)), "{}", r.body);
|
||||
|
||||
// a user "pays", which adds a unit, then requests the analysis
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let chart = app.chart(&anna, "Saját", true, "1991-05-01").await;
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"unit": "natal"})).await;
|
||||
assert_eq!(
|
||||
(r.status, &r.body["analyses_left"]),
|
||||
(StatusCode::OK, &json!({"natal": 1, "synastry": 0})),
|
||||
"{}",
|
||||
r.body
|
||||
);
|
||||
let r =
|
||||
app.call("POST", &format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()), Some(&anna), None).await;
|
||||
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(1)), "{}", r.body);
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], json!({"natal": 0, "synastry": 0}));
|
||||
|
||||
// without MOCK_PAYMENTS there is no such payment
|
||||
let app = TestApp::with_config(app.pool.clone(), |c| c.mock_payments = false).await;
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"unit": "natal"})).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user