//! Natal charts of a user: their own (primary) chart and charts of others //! they entered (partner, family). 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::error::{ApiError, ApiResult}; 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, 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, 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, "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), }) } pub fn summary_view(&self) -> Value { json!({ "id": self.id, "label": self.label, "is_primary": self.is_primary, "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)) } 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. 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 existing: Option = 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?; 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?; tx.commit().await?; return Ok((StatusCode::OK, Json(row.owner_view()))); } 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 (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, birth_data, result, chart_hash) \ VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING {CHART_COLUMNS}" )) .bind(Uuid::now_v7()) .bind(auth.id()) .bind(label) .bind(req.is_primary) .bind(birth) .bind(result) .bind(hash) .fetch_one(&mut *tx) .await?; tx.commit().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, } /// 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). 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); let mut tx = state.db.begin().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, updated_at = now() WHERE id = $3 RETURNING {CHART_COLUMNS}" )) .bind(label) .bind(is_primary) .bind(id) .fetch_one(&mut *tx) .await?; tx.commit().await?; Ok(Json(row.owner_view())) } /// 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) }