diff --git a/crates/db/migrations/0007_birth_data_changes.sql b/crates/db/migrations/0007_birth_data_changes.sql
new file mode 100644
index 0000000..0cde3b9
--- /dev/null
+++ b/crates/db/migrations/0007_birth_data_changes.sql
@@ -0,0 +1,15 @@
+-- Every time a user's own (primary) birth data is set or changed. The
+-- backend limits changes with it: after the first save, three corrections
+-- within an hour, then one per 24 hours (admins are not limited).
+
+CREATE TABLE birth_data_changes (
+ id uuid PRIMARY KEY,
+ user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+ chart_id uuid REFERENCES charts (id) ON DELETE SET NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX birth_data_changes_user_idx ON birth_data_changes (user_id, created_at);
+
+-- The current primary charts count as the first save.
+INSERT INTO birth_data_changes (id, user_id, chart_id, created_at)
+SELECT gen_random_uuid(), owner_id, id, created_at FROM charts WHERE is_primary;
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index 08472c0..90c9e85 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -85,6 +85,8 @@ services:
ANALYSIS_MODEL: ${ANALYSIS_MODEL:-}
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
+ # Stand-in payment (adds an analysis unit at once) until Stripe is connected.
+ MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
depends_on:
postgres:
condition: service_healthy
diff --git a/docker-compose.yml b/docker-compose.yml
index 7bd4b44..e4de700 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -53,6 +53,8 @@ services:
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
# E-mail + password login; off by default (Google, Apple and Facebook only).
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
+ # Stand-in payment (adds an analysis unit at once) until Stripe is connected.
+ MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
depends_on:
postgres:
condition: service_healthy
diff --git a/services/backend/README.md b/services/backend/README.md
index f16fb49..800b0a7 100644
--- a/services/backend/README.md
+++ b/services/backend/README.md
@@ -14,6 +14,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
| `COOKIE_DOMAIN` | – | pl. `.sorsfonalak.hu`, ha a frontend és az API más aldomainen fut |
| `SESSION_TTL_DAYS` | `30` | a munkamenet élettartama |
| `PASSWORD_LOGIN` | `false` | e-mail + jelszó regisztráció és belépés; élesben ki van kapcsolva (csak Google, Apple, Facebook), a jelszavas végpontok ilyenkor 403-at adnak |
+| `MOCK_PAYMENTS` | `false` | próbafizetés a Stripe bekötéséig: a `POST /v1/payments/mock` azonnal jóváír egy elemzési egységet (a compose-fájlokban egyelőre `true`) |
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
| `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) |
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
@@ -111,3 +112,8 @@ Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái
## Háttérmunkák
A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket (OpenRouter, strukturált JSON; hibánál visszaadja az egységet), és óránként takarít. Még hátravan az elemzés streamelése a frontend felé.
+
+## Korlátok
+
+- **Saját születési adatok módosítása:** az első mentés után egy órán belül még háromszor javíthatók, utána naponta egyszer (`birth_data_changes` tábla). A tiltott módosítás 429-et ad `birth_data_change_limit` kóddal, a felhasználónak szóló üzenettel („A rendszer csak napi egy módosítást engedélyez. …”). A `/v1/me` `birth_change` mezője mutatja, él-e a napi korlát. Más emberek képleteit ez nem érinti.
+- **Admin:** nincs módosítási korlát, és a részletes elemzés ingyenes (nem fogy egység).
diff --git a/services/backend/src/birth_changes.rs b/services/backend/src/birth_changes.rs
new file mode 100644
index 0000000..c0e3329
--- /dev/null
+++ b/services/backend/src/birth_changes.rs
@@ -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,
+}
+
+/// 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, 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 {
+ 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");
+ }
+}
diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs
index a6d4a2b..ae1d744 100644
--- a/services/backend/src/config.rs
+++ b/services/backend/src/config.rs
@@ -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,
@@ -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()],
diff --git a/services/backend/src/error.rs b/services/backend/src/error.rs
index 711ea22..b89e144 100644
--- a/services/backend/src/error.rs
+++ b/services/backend/src/error.rs
@@ -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"),
diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs
index fb77920..e06b226 100644
--- a/services/backend/src/main.rs
+++ b/services/backend/src/main.rs
@@ -8,6 +8,7 @@
//! `backend healthcheck` performs a local health check (for Docker).
mod auth;
+mod birth_changes;
mod config;
mod credits;
mod error;
diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs
index 9ef1e8f..cb135a6 100644
--- a/services/backend/src/routes/account.rs
+++ b/services/backend/src/routes/account.rs
@@ -28,12 +28,15 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> {
.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::>(),
"primary_chart_id": primary.map(|(id,)| id),
"analyses_left": balance.view(),
+ "birth_change": birth_change,
})))
}
diff --git a/services/backend/src/routes/analyses.rs b/services/backend/src/routes/analyses.rs
index bfc18a6..f5d1417 100644
--- a/services/backend/src/routes/analyses.rs
+++ b/services/backend/src/routes/analyses.rs
@@ -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)> {
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())))
}
diff --git a/services/backend/src/routes/charts.rs b/services/backend/src/routes/charts.rs
index 86a496c..30c8775 100644
--- a/services/backend/src/routes/charts.rs
+++ b/services/backend/src/routes/charts.rs
@@ -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 {
/// 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()))
}
diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs
index c08f341..13c120b 100644
--- a/services/backend/src/routes/mod.rs
+++ b/services/backend/src/routes/mod.rs
@@ -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) -> 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 {
"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,
}))
}
diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs
new file mode 100644
index 0000000..a3d16ae
--- /dev/null
+++ b/services/backend/src/routes/payments.rs
@@ -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,
+) -> ApiResult> {
+ 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() })))
+}
diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs
index 71009d1..d5b1c88 100644
--- a/services/backend/src/tests.rs
+++ b/services/backend/src/tests.rs
@@ -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);
+}
diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css
index 6c87341..4b331b1 100644
--- a/services/frontend/src/app/globals.css
+++ b/services/frontend/src/app/globals.css
@@ -192,6 +192,21 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.skeleton span:last-child { width: 60%; }
@keyframes pulse { 50% { opacity: 0.45; } }
@media (prefers-reduced-motion: reduce) { .skeleton span { animation: none; } }
+
+/* Loading while the LLM writes */
+.loading { display: flex; align-items: center; gap: 24px; padding: 8px 0; }
+.loading-wheel { width: 120px; height: 120px; flex: none; animation: spin 24s linear infinite; }
+.loading-compact .loading-wheel { width: 64px; height: 64px; }
+.loading-text { display: flex; flex-direction: column; gap: 6px; }
+.loading-text strong { font-family: var(--font-display); font-size: 24px; font-weight: 600; }
+.loading-text .muted { animation: pulse 2.4s ease-in-out infinite; }
+@keyframes spin { to { transform: rotate(360deg); } }
+@media (prefers-reduced-motion: reduce) { .loading-wheel, .loading-text .muted { animation: none; } }
+@media (max-width: 640px) { .loading { flex-direction: column; text-align: center; } }
+
+/* Payment step */
+.pay-box { display: flex; flex-direction: column; gap: 12px; padding: 16px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2); }
+.pay-line { display: flex; justify-content: space-between; gap: 12px; }
.chart-layout { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(280px, 1fr); gap: 24px; align-items: start; }
.chart-wheel-card { padding: 16px; gap: 10px; }
.chart-wheel { width: 100%; height: auto; display: block; max-width: 680px; margin: 0 auto; }
@@ -224,13 +239,10 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.w-axis-label { fill: var(--gold); font: 600 14px var(--font-body); letter-spacing: 0.5px; }
.w-house-num { fill: var(--muted); font: 500 12px var(--font-body); }
.w-aspect { stroke-linecap: round; }
-.w-aspect { transition: stroke-opacity 0.15s; }
.w-asp-trine { stroke: var(--harmonic); }
.w-asp-sextile { stroke: var(--harmonic); stroke-dasharray: 5 4; }
.w-asp-square { stroke: var(--square); }
.w-asp-opposition { stroke: var(--tense); }
-.w-point { outline: none; cursor: default; }
-.w-point:focus-visible .w-point-glyph { fill: var(--gold); }
.w-point-tick { stroke: var(--ink); stroke-width: 1.6; }
.w-leader { stroke: var(--muted); stroke-width: 0.7; stroke-opacity: 0.6; }
.w-point-glyph { fill: var(--ink); font-family: var(--font-symbols); font-size: 22px; }
diff --git a/services/frontend/src/app/kepletek/[id]/page.tsx b/services/frontend/src/app/kepletek/[id]/page.tsx
index e117e47..7142b4c 100644
--- a/services/frontend/src/app/kepletek/[id]/page.tsx
+++ b/services/frontend/src/app/kepletek/[id]/page.tsx
@@ -1,5 +1,4 @@
import type { Metadata } from "next";
-import Link from "next/link";
import { notFound } from "next/navigation";
import { BigThree, ChartTables } from "@/components/ChartTables";
@@ -8,7 +7,7 @@ import { DetailedAnalysis } from "@/components/DetailedAnalysis";
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
import { ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro";
import { backendGet, requireMe } from "@/lib/server";
-import type { Analysis, Chart } from "@/lib/types";
+import type { Analysis, Chart, PublicConfig } from "@/lib/types";
export const metadata: Metadata = { title: "Képlet" };
@@ -19,9 +18,10 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
const { id } = await params;
const me = await requireMe(`/kepletek/${id}`);
if (!UUID.test(id)) notFound();
- const [chart, analyses] = await Promise.all([
+ const [chart, analyses, config] = await Promise.all([
backendGet(`/v1/charts/${id}`),
backendGet<{ analyses: Analysis[] }>(`/v1/charts/${id}/analyses`),
+ backendGet("/v1/config"),
]);
if (!chart) notFound();
const list = analyses?.analyses ?? [];
@@ -47,12 +47,6 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
{" · "}
{place?.name ?? chart.birth_data.place ?? "–"}
{country ? `, ${countryName(country)}` : ""}
- {chart.is_primary && (
- <>
- {" · "}
- adatok javítása
- >
- )}
@@ -111,7 +105,13 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
-
+
Pozíciók
diff --git a/services/frontend/src/app/profil/BirthEditor.tsx b/services/frontend/src/app/profil/BirthEditor.tsx
index aa6eb6f..1d735e7 100644
--- a/services/frontend/src/app/profil/BirthEditor.tsx
+++ b/services/frontend/src/app/profil/BirthEditor.tsx
@@ -19,8 +19,19 @@ export interface SavedBirth {
dst: boolean;
}
-/** Shows the saved birth data, or the form to enter or correct it. Saving opens the chart page. */
-export function BirthEditor({ chart, chartId }: { chart: SavedBirth | null; chartId: string | null }) {
+/**
+ * Shows the saved birth data, or the form to enter or correct it. Saving opens
+ * the chart page. `notice`: the backend's text about the change limit, if any.
+ */
+export function BirthEditor({
+ chart,
+ chartId,
+ notice,
+}: {
+ chart: SavedBirth | null;
+ chartId: string | null;
+ notice: string | null;
+}) {
const router = useRouter();
const [editing, setEditing] = useState(chart === null);
@@ -38,6 +49,7 @@ export function BirthEditor({ chart, chartId }: { chart: SavedBirth | null; char
időszámítást) a születési hely alapján magunk határozzuk meg.
)}
+ {chart && notice && {notice}
}
setEditing(false) : undefined}
@@ -87,6 +99,7 @@ export function BirthEditor({ chart, chartId }: { chart: SavedBirth | null; char
+ {notice && {notice}
}
);
}
diff --git a/services/frontend/src/app/profil/page.tsx b/services/frontend/src/app/profil/page.tsx
index b6d28f8..473284c 100644
--- a/services/frontend/src/app/profil/page.tsx
+++ b/services/frontend/src/app/profil/page.tsx
@@ -73,6 +73,7 @@ export default async function ProfilePage() {
: null
}
chartId={chart?.id ?? null}
+ notice={me.birth_change.notice}
/>
diff --git a/services/frontend/src/components/AnalysisLoading.tsx b/services/frontend/src/components/AnalysisLoading.tsx
new file mode 100644
index 0000000..6e97a39
--- /dev/null
+++ b/services/frontend/src/components/AnalysisLoading.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+import { ZodiacWheel } from "./ZodiacWheel";
+
+/** Slowly turning wheel with the elapsed time, while the LLM writes. */
+export function AnalysisLoading({ title, text, compact = false }: { title?: string; text: string; compact?: boolean }) {
+ const [seconds, setSeconds] = useState(0);
+ useEffect(() => {
+ const t = setInterval(() => setSeconds((s) => s + 1), 1000);
+ return () => clearInterval(t);
+ }, []);
+ const elapsed = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
+
+ return (
+
+
+
+ {title &&
{title} }
+
+ {text}
+
+
+ {elapsed}
+
+
+
+ );
+}
diff --git a/services/frontend/src/components/ChartSummary.tsx b/services/frontend/src/components/ChartSummary.tsx
index a73d4c7..b971365 100644
--- a/services/frontend/src/components/ChartSummary.tsx
+++ b/services/frontend/src/components/ChartSummary.tsx
@@ -5,6 +5,7 @@ import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import type { Analysis } from "@/lib/types";
+import { AnalysisLoading } from "./AnalysisLoading";
import { Rich } from "./Rich";
const POLL_MS = 3000;
@@ -62,17 +63,12 @@ export function ChartSummary({ chartId, initial }: { chartId: string; initial: A
Rövid összefoglaló
-
- {gaveUp || summary?.status === "failed"
- ? "Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később."
- : "Az összefoglalód készül, ez néhány másodperc…"}
-
- {!gaveUp && summary?.status !== "failed" && (
-
-
-
-
-
+ {gaveUp || summary?.status === "failed" ? (
+
+ Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később.
+
+ ) : (
+
)}
>
)}
diff --git a/services/frontend/src/components/ChartWheel.tsx b/services/frontend/src/components/ChartWheel.tsx
index 96f538a..dcc87a2 100644
--- a/services/frontend/src/components/ChartWheel.tsx
+++ b/services/frontend/src/components/ChartWheel.tsx
@@ -116,13 +116,6 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
.filter((a) => WHEEL_ASPECTS.includes(a.aspect) && ends.has(a.point1) && ends.has(a.point2))
.map((a) => ({ ...a, strength: a.max_orb > 0 ? 1 - Math.min(a.orb / a.max_orb, 1) : 0.5 }))
.sort((x, y) => x.strength - y.strength);
- // Hovering or focusing a point shows only its aspects.
- const highlight = [...ends.keys()]
- .map((id) => {
- const on = `.chart-wheel:has(.p-${id}:hover, .p-${id}:focus-visible)`;
- return `${on} .w-aspect:not(.a-${id}){stroke-opacity:0.06}${on} .w-aspect.a-${id}{stroke-opacity:1}`;
- })
- .join("\n");
const description = points
.map((p) => `${pointName(p.id)} ${signName(p.sign)} ${dms(p.degree_in_sign_dms)}`)
@@ -192,7 +185,7 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
key={key}
x={f(x)}
y={f(y)}
- className={`w-axis-label p-${key}`}
+ className="w-axis-label"
dominantBaseline="central"
textAnchor="middle"
>
@@ -207,7 +200,6 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
)}
{/* Aspects */}
-
{aspects.map((a) => {
const [x1, y1] = xy(ends.get(a.point1)!, R_INNER, start);
@@ -220,7 +212,7 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
y1={f(y1)}
x2={f(x2)}
y2={f(y2)}
- className={`w-aspect w-asp-${a.aspect} a-${a.point1} a-${a.point2}`}
+ className={`w-aspect w-asp-${a.aspect}`}
strokeOpacity={(0.2 + 0.8 * s * s).toFixed(2)}
strokeWidth={(0.6 + 1.9 * s).toFixed(2)}
>
@@ -242,7 +234,7 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
const [ex, ey] = xy(placed[i], R_INNER, start);
const deg = Number.parseInt(p.degree_in_sign_dms, 10);
return (
-
+
{pointName(p.id)}: {dms(p.degree_in_sign_dms)} {signName(p.sign)}
{p.retrograde ? ", retrográd" : ""}
@@ -282,7 +274,7 @@ export function WheelLegend() {
))}
- Vastagabb vonal: szorosabb fényszög. Egy bolygóra mutatva csak az ő fényszögei látszanak.
+ Vastagabb vonal: szorosabb fényszög.
A körön a bolygók, az ASC és az MC főfényszögei vannak; az összes fényszög a táblázatban.
);
diff --git a/services/frontend/src/components/DetailedAnalysis.tsx b/services/frontend/src/components/DetailedAnalysis.tsx
index 3f19ef5..5d9f949 100644
--- a/services/frontend/src/components/DetailedAnalysis.tsx
+++ b/services/frontend/src/components/DetailedAnalysis.tsx
@@ -6,27 +6,35 @@ import { useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import type { Analysis } from "@/lib/types";
+import { AnalysisLoading } from "./AnalysisLoading";
import { AnalysisView } from "./AnalysisView";
const POLL_MS = 5000;
const MAX_POLLS = 120; // 10 minutes
+type Step = "offer" | "confirm" | "pay";
+
/**
- * The paid detailed analysis of a chart: offer (with the units left),
- * confirmation, progress while the worker writes it, and the finished text.
+ * The detailed analysis of a chart. A saved one is shown at once; otherwise
+ * the offer: admins start it free, users with units confirm, others pay
+ * (a stand-in payment for now). While the worker writes it, a loading wheel.
*/
export function DetailedAnalysis({
chartId,
initial,
left,
+ isAdmin,
+ canPay,
}: {
chartId: string;
initial: Analysis | null;
left: number;
+ isAdmin: boolean;
+ /** The stand-in payment is on (MOCK_PAYMENTS). */
+ canPay: boolean;
}) {
const [analysis, setAnalysis] = useState(initial);
- const [remaining, setRemaining] = useState(left);
- const [confirming, setConfirming] = useState(false);
+ const [step, setStep] = useState("offer");
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const waiting = analysis?.status === "pending" || analysis?.status === "running";
@@ -54,14 +62,13 @@ export function DetailedAnalysis({
};
}, [waiting, analysis]);
- async function request() {
+ async function start(pay: boolean) {
setBusy(true);
setError(null);
try {
- const next = await api(`/charts/${chartId}/analyses`, { method: "POST" });
- setAnalysis(next);
- if (next.credits_charged > 0) setRemaining((n) => n - 1);
- setConfirming(false);
+ if (pay) await api("/payments/mock", { body: { unit: "natal" } });
+ setAnalysis(await api(`/charts/${chartId}/analyses`, { method: "POST" }));
+ setStep("offer");
} catch (e) {
setError(errorText(e));
} finally {
@@ -78,67 +85,97 @@ export function DetailedAnalysis({
);
}
+ if (waiting) {
+ return (
+
+ );
+ }
+
return (
-
+
Részletes elemzés
- {waiting ? (
- <>
- Készül az elemzésed
-
- A mesterséges intelligencia most írja meg a hat fejezetet a képleted alapján. Ez általában 1–2 perc; nyugodtan
- elhagyhatod az oldalt, az elemzés elkészül és itt vár.
-
-
-
-
-
+
Az egész képleted, fejezetekre bontva
+
+ Kb. 1500 szó hat fejezetben: személyiség, érzelmek, gondolkodás, szerelem és kapcsolatok, hivatás, fejlődési út.
+ A végén erősségek, kihívások és útravaló. Csak a képleted pozíciói alapján készül.
+
+ {analysis?.status === "failed" && (
+
+ Az előző kérés nem sikerült{isAdmin ? "" : ", az elemzést visszaadtuk a keretedbe"}. Próbáld újra.
+
+ )}
+ {error && (
+
+ {error}
+
+ )}
+
+ {isAdmin ? (
+
+ start(false)} disabled={busy}>
+ {busy ? "Indítás…" : "Részletes elemzés készítése"}
+
+ Adminként ingyenes.
+
+ ) : left > 0 ? (
+ step === "confirm" ? (
+
+ start(false)} disabled={busy}>
+ {busy ? "Indítás…" : "Igen, kérem az elemzést"}
+
+ setStep("offer")} disabled={busy}>
+ Mégse
+
+ Ez felhasznál 1-et a {left} képletelemzésedből.
- >
- ) : (
- <>
-
Az egész képleted, fejezetekre bontva
-
- Kb. 1500 szó hat fejezetben: személyiség, érzelmek, gondolkodás, szerelem és kapcsolatok, hivatás, fejlődési
- út. A végén erősségek, kihívások és útravaló. Csak a képleted pozíciói alapján készül.
-
- {analysis?.status === "failed" && (
-
- Az előző kérés nem sikerült, az elemzést visszaadtuk a keretedbe. Próbáld újra.
-
- )}
- {error && (
-
- {error}
-
- )}
- {remaining > 0 ? (
- confirming ? (
-
-
- {busy ? "Indítás…" : "Igen, kérem az elemzést"}
-
- setConfirming(false)} disabled={busy}>
- Mégse
-
- Ez felhasznál 1-et a {remaining} képletelemzésedből.
-
- ) : (
-
- setConfirming(true)}>
- Részletes elemzés kérése
-
- Még {remaining} képletelemzésed van.
-
- )
- ) : (
-
-
- Példa megtekintése
-
-
A részletes elemzés fizetős; a csomagok hamarosan elérhetők.
+ ) : (
+
+ setStep("confirm")}>
+ Részletes elemzés kérése
+
+ Még {left} képletelemzésed van.
+
+ )
+ ) : canPay ? (
+ step === "pay" ? (
+
+
+ Részletes képletelemzés
+ 1 db
- )}
- >
+
+ start(true)} disabled={busy}>
+ {busy ? "Fizetés…" : "Fizetés"}
+
+ setStep("offer")} disabled={busy}>
+ Mégse
+
+
+
Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.
+
+ ) : (
+
+ setStep("pay")}>
+ Részletes elemzés kérése
+
+
+ Példa megtekintése
+
+
+ )
+ ) : (
+
+
+ Példa megtekintése
+
+ A részletes elemzés fizetős; a csomagok hamarosan elérhetők.
+
)}
);
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index 7f5cc1d..12cfe8f 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -17,6 +17,14 @@ export interface Me {
providers: string[];
primary_chart_id: string | null;
analyses_left: UnitBalance;
+ birth_change: BirthChange;
+}
+
+/** Limit on changing the own birth data (the notice text comes from the backend). */
+export interface BirthChange {
+ limited: boolean;
+ next_change_at: string | null;
+ notice: string | null;
}
/** Detailed analyses left, per kind. */
@@ -32,6 +40,7 @@ export interface PublicConfig {
summary_model: string;
password_login: boolean;
password_min_length: number;
+ mock_payments: boolean;
}
export interface Position {