//! Synastries (two charts compared) and "how compatible are we?" invitations. //! //! A synastry is visible to its owner and to the owners of both charts: when //! an invitation is accepted, the inviter owns the synastry and the invitee //! sees it through their own chart. Birth data of a chart is shown only to //! its owner; the other side gets the positions only. use axum::Json; use axum::extract::{Path, State}; use axum::http::StatusCode; use axum_extra::extract::WithRejection; use db::USER_COLUMNS; use serde::Deserialize; use serde_json::{Map, Value, json}; use sqlx::PgPool; use time::OffsetDateTime; use uuid::Uuid; use super::charts::{ChartRow, find_chart, owned_chart, primary_chart}; use super::{Body, IdPath, St}; use crate::AppState; use crate::auth::AuthUser; use crate::error::{ApiError, ApiResult}; use crate::views::{public_chart, rfc3339, rfc3339_opt, synastry_hash}; const INVITE_TTL: time::Duration = time::Duration::days(14); #[derive(Debug, Clone, sqlx::FromRow)] pub struct SynastryRow { pub id: Uuid, pub owner_id: Uuid, pub chart1_id: Uuid, pub chart2_id: Uuid, pub result: Value, pub synastry_hash: String, pub created_at: OffsetDateTime, } const SYNASTRY_COLUMNS: &str = "id, owner_id, chart1_id, chart2_id, result, synastry_hash, created_at"; /// A synastry with its two charts. pub struct VisibleSynastry { pub synastry: SynastryRow, pub chart1: ChartRow, pub chart2: ChartRow, } impl VisibleSynastry { pub fn is_member(&self, user: Uuid) -> bool { self.synastry.owner_id == user || self.chart1.owner_id == user || self.chart2.owner_id == user } } pub async fn load_synastry(db: &PgPool, id: Uuid) -> Result, ApiError> { let row: Option = sqlx::query_as(&format!("SELECT {SYNASTRY_COLUMNS} FROM synastries WHERE id = $1")) .bind(id) .fetch_optional(db) .await?; let Some(synastry) = row else { return Ok(None) }; let chart1 = find_chart(db, synastry.chart1_id).await?.ok_or(ApiError::NotFound("chart"))?; let chart2 = find_chart(db, synastry.chart2_id).await?.ok_or(ApiError::NotFound("chart"))?; Ok(Some(VisibleSynastry { synastry, chart1, chart2 })) } /// 404 unless `user` may see the synastry. pub async fn visible_synastry(db: &PgPool, id: Uuid, user: Uuid) -> Result { load_synastry(db, id).await?.filter(|s| s.is_member(user)).ok_or(ApiError::NotFound("synastry")) } async fn display_name(db: &PgPool, user: Uuid) -> Result, ApiError> { let row: Option<(Option,)> = sqlx::query_as("SELECT display_name FROM users WHERE id = $1").bind(user).fetch_optional(db).await?; Ok(row.and_then(|(n,)| n)) } /// A chart as seen by `viewer`: the owner gets everything, others the /// positions without birth data, labelled with the owner's display name. async fn chart_for_viewer(db: &PgPool, chart: &ChartRow, viewer: Uuid) -> Result { if chart.owner_id == viewer { let mut v = chart.owner_view(); v["owned"] = Value::Bool(true); return Ok(v); } let label = match display_name(db, chart.owner_id).await? { Some(name) if chart.is_primary => name, _ => chart.label.clone(), }; Ok(json!({ "id": chart.id, "label": label, "owned": false, "chart": public_chart(&chart.result, false) })) } async fn synastry_view(db: &PgPool, s: &VisibleSynastry, viewer: Uuid) -> Result { Ok(json!({ "id": s.synastry.id, "owned": s.synastry.owner_id == viewer, "chart1": chart_for_viewer(db, &s.chart1, viewer).await?, "chart2": chart_for_viewer(db, &s.chart2, viewer).await?, "synastry": s.synastry.result, "synastry_hash": s.synastry.synastry_hash, "created_at": rfc3339(s.synastry.created_at), })) } fn without(value: &Value, keys: &[&str]) -> Value { let mut map: Map = value.as_object().cloned().unwrap_or_default(); for k in keys { map.remove(*k); } Value::Object(map) } /// Returns the synastry of the two charts, calculating and storing it when /// it does not exist yet (in either order). `bool` = newly created. pub async fn compute_synastry( state: &AppState, owner: Uuid, chart1: &ChartRow, chart2: &ChartRow, ) -> Result<(SynastryRow, bool), ApiError> { let existing = |a: Uuid, b: Uuid| async move { sqlx::query_as::<_, SynastryRow>(&format!( "SELECT {SYNASTRY_COLUMNS} FROM synastries \ WHERE (chart1_id = $1 AND chart2_id = $2) OR (chart1_id = $2 AND chart2_id = $1)" )) .bind(a) .bind(b) .fetch_optional(&state.db) .await }; if let Some(row) = existing(chart1.id, chart2.id).await? { return Ok((row, false)); } let request = json!({ "person1": without(&chart1.birth_data, &["options"]), "person2": without(&chart2.birth_data, &["options"]), "options": chart1.birth_data.get("options").cloned().unwrap_or_else(|| json!({})), }); let response = state.horoscope.synastry(&request).await?; let result = without(&response, &["person1", "person2", "meta"]); let hash = synastry_hash(&chart1.chart_hash, &chart2.chart_hash, &result["settings"]); let inserted: Option = sqlx::query_as(&format!( "INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \ VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (chart1_id, chart2_id) DO NOTHING RETURNING {SYNASTRY_COLUMNS}" )) .bind(Uuid::now_v7()) .bind(owner) .bind(chart1.id) .bind(chart2.id) .bind(result) .bind(hash) .fetch_optional(&state.db) .await?; match inserted { Some(row) => Ok((row, true)), // Created concurrently. None => Ok((existing(chart1.id, chart2.id).await?.ok_or(ApiError::NotFound("synastry"))?, false)), } } pub async fn list(State(state): St, auth: AuthUser) -> ApiResult> { type Row = (Uuid, bool, Uuid, String, Uuid, Uuid, String, Uuid, Value, OffsetDateTime); let rows: Vec = sqlx::query_as( "SELECT s.id, s.owner_id = $1, c1.id, c1.label, c1.owner_id, c2.id, c2.label, c2.owner_id, \ s.result -> 'summary', s.created_at \ FROM synastries s JOIN charts c1 ON c1.id = s.chart1_id JOIN charts c2 ON c2.id = s.chart2_id \ WHERE s.owner_id = $1 OR c1.owner_id = $1 OR c2.owner_id = $1 ORDER BY s.created_at DESC", ) .bind(auth.id()) .fetch_all(&state.db) .await?; let me = auth.id(); let list: Vec = rows .into_iter() .map(|(id, owned, c1, l1, o1, c2, l2, o2, summary, at)| { json!({ "id": id, "owned": owned, "chart1": { "id": c1, "label": l1, "owned": o1 == me }, "chart2": { "id": c2, "label": l2, "owned": o2 == me }, "summary": summary, "created_at": rfc3339(at), }) }) .collect(); Ok(Json(json!({ "synastries": list }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateSynastry { chart1_id: Uuid, chart2_id: Uuid, } /// Compares two of the user's own charts. pub async fn create( State(state): St, auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { if req.chart1_id == req.chart2_id { return Err(ApiError::BadRequest("a chart cannot be compared with itself".into())); } let chart1 = owned_chart(&state.db, req.chart1_id, auth.id()).await?; let chart2 = owned_chart(&state.db, req.chart2_id, auth.id()).await?; let (row, created) = compute_synastry(&state, auth.id(), &chart1, &chart2).await?; let s = visible_synastry(&state.db, row.id, auth.id()).await?; let status = if created { StatusCode::CREATED } else { StatusCode::OK }; Ok((status, Json(synastry_view(&state.db, &s, auth.id()).await?))) } pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult> { let s = visible_synastry(&state.db, id, auth.id()).await?; Ok(Json(synastry_view(&state.db, &s, auth.id()).await?)) } /// Either side may remove the synastry (and with it the link between them). pub async fn remove(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult { visible_synastry(&state.db, id, auth.id()).await?; sqlx::query("DELETE FROM synastries WHERE id = $1").bind(id).execute(&state.db).await?; Ok(StatusCode::NO_CONTENT) } // --- invitations ----------------------------------------------------------------------------- #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateInvite { /// Defaults to the user's primary chart. chart_id: Option, message: Option, } async fn chart_or_primary(db: &PgPool, chart_id: Option, user: Uuid) -> Result { match chart_id { Some(id) => owned_chart(db, id, user).await, None => primary_chart(db, user).await?.ok_or_else(|| { ApiError::conflict("primary_chart_required", "create your own chart first (is_primary: true)") }), } } pub async fn create_invite( State(state): St, auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { let chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?; let message = req.message.map(|m| m.trim().chars().take(500).collect::()).filter(|m| !m.is_empty()); let token = db::new_token(); let id = Uuid::now_v7(); let expires_at = OffsetDateTime::now_utc() + INVITE_TTL; sqlx::query( "INSERT INTO synastry_invites (id, inviter_id, inviter_chart_id, token_hash, message, expires_at) \ VALUES ($1, $2, $3, $4, $5, $6)", ) .bind(id) .bind(auth.id()) .bind(chart.id) .bind(db::token_hash(&token)) .bind(&message) .bind(expires_at) .execute(&state.db) .await?; Ok(( StatusCode::CREATED, Json(json!({ "id": id, "token": token, "url": format!("{}/invite/{token}", state.config.public_base_url), "chart_id": chart.id, "message": message, "expires_at": rfc3339(expires_at), })), )) } fn invite_status(accepted_at: Option, expires_at: OffsetDateTime) -> &'static str { if accepted_at.is_some() { "accepted" } else if expires_at <= OffsetDateTime::now_utc() { "expired" } else { "pending" } } pub async fn list_invites(State(state): St, auth: AuthUser) -> ApiResult> { type Row = ( Uuid, Uuid, Option, OffsetDateTime, OffsetDateTime, Option, Option, Option, ); let rows: Vec = sqlx::query_as( "SELECT i.id, i.inviter_chart_id, i.message, i.created_at, i.expires_at, i.accepted_at, i.synastry_id, \ u.display_name \ FROM synastry_invites i LEFT JOIN users u ON u.id = i.accepted_by \ WHERE i.inviter_id = $1 ORDER BY i.created_at DESC", ) .bind(auth.id()) .fetch_all(&state.db) .await?; let list: Vec = rows .into_iter() .map(|(id, chart_id, message, created, expires, accepted, synastry_id, accepted_by)| { json!({ "id": id, "chart_id": chart_id, "message": message, "status": invite_status(accepted, expires), "created_at": rfc3339(created), "expires_at": rfc3339(expires), "accepted_at": rfc3339_opt(accepted), "accepted_by": accepted_by, "synastry_id": synastry_id, }) }) .collect(); Ok(Json(json!({ "invites": list }))) } pub async fn revoke_invite( State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath, ) -> ApiResult { let result = sqlx::query( "UPDATE synastry_invites SET expires_at = now() \ WHERE id = $1 AND inviter_id = $2 AND accepted_at IS NULL AND expires_at > now()", ) .bind(id) .bind(auth.id()) .execute(&state.db) .await?; if result.rows_affected() == 0 { return Err(ApiError::NotFound("pending invitation")); } Ok(StatusCode::NO_CONTENT) } #[derive(sqlx::FromRow)] struct InviteRow { id: Uuid, inviter_id: Uuid, inviter_chart_id: Uuid, message: Option, expires_at: OffsetDateTime, accepted_at: Option, inviter_name: Option, } async fn invite_by_token(db: &PgPool, token: &str) -> Result { sqlx::query_as( "SELECT i.id, i.inviter_id, i.inviter_chart_id, i.message, i.expires_at, i.accepted_at, \ u.display_name AS inviter_name \ FROM synastry_invites i JOIN users u ON u.id = i.inviter_id WHERE i.token_hash = $1", ) .bind(db::token_hash(token.trim())) .fetch_optional(db) .await? .ok_or(ApiError::NotFound("invitation")) } /// Public landing data of an invitation link (no login, no birth data). pub async fn public_invite(State(state): St, Path(token): Path) -> ApiResult> { let invite = invite_by_token(&state.db, &token).await?; Ok(Json(json!({ "inviter_name": invite.inviter_name, "message": invite.message, "status": invite_status(invite.accepted_at, invite.expires_at), "expires_at": rfc3339(invite.expires_at), }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct AcceptInvite { token: String, /// Defaults to the invitee's primary chart. chart_id: Option, } /// The invitee accepts: their chart is compared with the inviter's, and the /// synastry becomes visible to both. pub async fn accept_invite( State(state): St, auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { let invite = invite_by_token(&state.db, &req.token).await?; match invite_status(invite.accepted_at, invite.expires_at) { "accepted" => return Err(ApiError::Gone("this invitation has already been accepted".into())), "expired" => return Err(ApiError::Gone("this invitation has expired".into())), _ => {} } if invite.inviter_id == auth.id() { return Err(ApiError::conflict("own_invitation", "you cannot accept your own invitation")); } let my_chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?; let inviter_chart = find_chart(&state.db, invite.inviter_chart_id).await?.ok_or(ApiError::NotFound("invitation"))?; let (row, _) = compute_synastry(&state, invite.inviter_id, &inviter_chart, &my_chart).await?; let mut tx = state.db.begin().await?; sqlx::query( "UPDATE synastry_invites SET accepted_at = now(), accepted_by = $1, synastry_id = $2 \ WHERE id = $3 AND accepted_at IS NULL", ) .bind(auth.id()) .bind(row.id) .bind(invite.id) .execute(&mut *tx) .await?; let inviter: Option = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1")) .bind(invite.inviter_id) .fetch_optional(&mut *tx) .await?; if let Some(inviter) = inviter { let url = format!("{}/synastry/{}", state.config.public_base_url, row.id); super::auth::queue_email( &mut tx, &inviter, "invite_accepted", json!({ "url": url, "invitee_name": auth.user.display_name }), ) .await?; } tx.commit().await?; let s = visible_synastry(&state.db, row.id, auth.id()).await?; Ok((StatusCode::CREATED, Json(synastry_view(&state.db, &s, auth.id()).await?))) }