//! 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; use axum::http::StatusCode; use axum_extra::extract::WithRejection; use serde::Deserialize; use serde_json::{Value, json}; use sqlx::{PgExecutor, PgPool}; use time::OffsetDateTime; 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::persons; use crate::views::{chart_hash, chart_highlights, rfc3339}; #[derive(Debug, Clone, sqlx::FromRow)] pub struct ChartRow { pub id: Uuid, 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, pub created_at: OffsetDateTime, pub updated_at: OffsetDateTime, } 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. pub fn owner_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_data": self.birth_data, "highlights": chart_highlights(&self.result), "chart": self.result, "chart_hash": self.chart_hash, "created_at": rfc3339(self.created_at), "updated_at": rfc3339(self.updated_at), }) } /// Until when a person's birth data can be corrected (admins: any time). fn editable_until(&self) -> Option { (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), }) } } pub async fn find_chart(db: impl PgExecutor<'_>, id: Uuid) -> Result, ApiError> { Ok(sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts WHERE id = $1")).bind(id).fetch_optional(db).await?) } /// A chart of `owner`; 404 for missing charts and charts of others. pub async fn owned_chart(db: &PgPool, id: Uuid, owner: Uuid) -> Result { find_chart(db, id).await?.filter(|c| c.owner_id == owner).ok_or(ApiError::NotFound("chart")) } pub async fn primary_chart(db: &PgPool, owner: Uuid) -> Result, ApiError> { Ok(sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts WHERE owner_id = $1 AND is_primary")) .bind(owner) .fetch_optional(db) .await?) } fn clean_label(label: &str) -> Result { let label: String = label.trim().chars().take(100).collect(); if label.is_empty() { Err(ApiError::BadRequest("label must not be empty".into())) } else { Ok(label) } } pub async fn list(State(state): St, auth: AuthUser) -> ApiResult> { let rows: Vec = sqlx::query_as(&format!( "SELECT {CHART_COLUMNS} FROM charts WHERE owner_id = $1 ORDER BY is_primary DESC, created_at DESC" )) .bind(auth.id()) .fetch_all(&state.db) .await?; Ok(Json(json!({ "charts": rows.iter().map(ChartRow::summary_view).collect::>() }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateChart { /// Shown in lists, e.g. "Saját" or "Anna". label: String, /// The user's own chart (replaces the previous one as primary). #[serde(default)] is_primary: bool, /// Birth data in the format of the horoscope service's `POST /v1/natal` /// (date, time, country, place, ..., options). birth: Value, } /// Calculates a chart from birth data; the `name` field is dropped so no /// personal name reaches the calculation (or, later, the LLM). pub async fn calculate(state: &AppState, birth: Value) -> Result<(Value, Value, String), ApiError> { let birth = clean_birth(birth)?; let result = state.horoscope.natal(&birth).await?; let hash = chart_hash(&result); Ok((birth, result, hash)) } /// Queues the free short summary; a failure here does not fail the save /// (the chart page asks for the summary again). async fn queue_summary(state: &AppState, auth: &AuthUser, chart: &ChartRow) { if let Err(e) = super::analyses::ensure_summary(state, auth, chart).await { tracing::warn!(chart = %chart.id, error = %e, "queueing the chart summary failed"); } } fn clean_birth(birth: Value) -> Result { let Value::Object(mut birth) = birth else { return Err(ApiError::BadRequest("birth must be an object".into())); }; birth.remove("name"); Ok(Value::Object(birth)) } /// 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. Replacing the user's own chart counts against the /// birth data change limit ([`birth_changes`]). pub async fn create( State(state): St, auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { let label = clean_label(&req.label)?; let birth = clean_birth(req.birth)?; let kind = if req.is_primary { "own" } else { "person" }; let existing: Option = 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?; sqlx::query("UPDATE charts SET is_primary = false, updated_at = now() WHERE owner_id = $1 AND is_primary") .bind(auth.id()) .execute(&mut *tx) .await?; let row: ChartRow = sqlx::query_as(&format!( "UPDATE charts SET is_primary = true, updated_at = now() WHERE id = $1 RETURNING {CHART_COLUMNS}" )) .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()))); } queue_summary(&state, &auth, &chart).await; return Ok((StatusCode::OK, Json(chart.owner_view()))); } let (count,): (i64,) = sqlx::query_as("SELECT count(*) FROM charts WHERE owner_id = $1").bind(auth.id()).fetch_one(&state.db).await?; if count >= state.config.max_charts_per_user { return Err(ApiError::conflict( "chart_limit_reached", 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?; if req.is_primary { sqlx::query("UPDATE charts SET is_primary = false, updated_at = now() WHERE owner_id = $1 AND is_primary") .bind(auth.id()) .execute(&mut *tx) .await?; } let row: ChartRow = sqlx::query_as(&format!( "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) .fetch_one(&mut *tx) .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; Ok((StatusCode::CREATED, Json(row.owner_view()))) } pub async fn get_one( State(state): St, auth: AuthUser, WithRejection(axum::extract::Path(id), _): IdPath, ) -> ApiResult> { Ok(Json(owned_chart(&state.db, id, auth.id()).await?.owner_view())) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct UpdateChart { label: Option, is_primary: Option, /// 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, } /// 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, WithRejection(axum::extract::Path(id), _): IdPath, WithRejection(Json(req), _): Body, ) -> ApiResult> { let chart = owned_chart(&state.db, id, auth.id()).await?; let label = match &req.label { Some(l) => clean_label(l)?, None => chart.label.clone(), }; let is_primary = req.is_primary.unwrap_or(chart.is_primary); // The same birth data again (e.g. only the name changed): no recalculation, // and the analyses and comparisons stay. A new calculation that gives the // same chart keeps them too. let birth = req.birth.map(clean_birth).transpose()?.filter(|b| *b != chart.birth_data); let recalculated = match birth { Some(birth) => Some(corrected_birth(&state, &auth, &chart, birth).await?), None => None, }; let chart_changed = recalculated.as_ref().is_some_and(|(_, _, hash)| *hash != chart.chart_hash); let mut tx = state.db.begin().await?; if let Some((birth, result, hash)) = &recalculated { if chart_changed { // The old summary, the comparisons (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("DELETE FROM synastries WHERE chart1_id = $1 OR chart2_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()) .execute(&mut *tx) .await?; } let row: ChartRow = sqlx::query_as(&format!( "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) .bind(id) .fetch_one(&mut *tx) .await?; if is_primary && !chart.is_primary { birth_changes::record(&mut tx, &auth, id).await?; } tx.commit().await?; if chart_changed { 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); // The user's own comparisons with the person are deleted on correction (they // no longer match), unless a paid analysis was written for one of them. let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as( "SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed') \ OR EXISTS (SELECT 1 FROM analyses a JOIN synastries s ON s.id = a.synastry_id \ WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed'), \ EXISTS (SELECT 1 FROM synastries WHERE (chart1_id = $1 OR chart2_id = $1) AND owner_id <> $2)", ) .bind(chart.id) .bind(auth.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 foreign_synastry { return Err(ApiError::conflict( "person_in_synastry", "A személy szerepel valaki más összevetésében, 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, auth: AuthUser, WithRejection(axum::extract::Path(id), _): IdPath, ) -> ApiResult { let result = sqlx::query("DELETE FROM charts WHERE id = $1 AND owner_id = $2") .bind(id) .bind(auth.id()) .execute(&state.db) .await?; if result.rows_affected() == 0 { return Err(ApiError::NotFound("chart")); } Ok(StatusCode::NO_CONTENT) }