Files
sorsfonalak/services/forum/src/routes/attachments.rs
T
fecoandClaude Opus 5.5 67cb3c6b8c Forum: the attached chart's wheel in the question
A question with a shared chart shows the chart's wheel, one with a shared
synastry the two charts on one wheel, at a fixed size beside the details
(above them on phones). The forum sends the wheel's data (positions, angles,
houses, aspects; never birth date, time or place) to logged-in members only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 16:57:04 +00:00

173 lines
6.5 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! A question about one's own chart, yearly forecast or synastry: the opening
//! post carries a share made for the forum on the main site (no birth data,
//! no names). The post shows it as a card to logged-in members only; a
//! visitor (and a search engine) sees that there is one. The sharer can
//! revoke it on the main site; the card then says so.
use std::collections::HashMap;
use axum::Json;
use axum::extract::{Path, State};
use axum_extra::extract::WithRejection;
use serde_json::{Value, json};
use sqlx::PgPool;
use uuid::Uuid;
use super::St;
use crate::auth::{Member, Viewer};
use crate::error::{ApiError, ApiResult};
#[derive(sqlx::FromRow)]
struct CardRow {
id: Uuid,
slug: String,
kind: String,
revoked: bool,
natal: Option<Value>,
year: Option<i32>,
summary_title: Option<String>,
/// A synastry: the two charts and the aspects between them.
chart1: Option<Value>,
chart2: Option<Value>,
pair_aspects: Option<Value>,
}
const CARD_SELECT: &str = "SELECT s.id, s.slug, s.kind, s.revoked_at IS NOT NULL AS revoked, \
COALESCE(c.result, fc.result) AS natal, f.year, \
CASE s.kind \
WHEN 'chart' THEN (SELECT a.content->>'title' FROM analyses a WHERE a.chart_id = s.chart_id \
AND a.kind = 'summary' AND a.status = 'done' ORDER BY a.completed_at DESC LIMIT 1) \
WHEN 'forecast' THEN (SELECT a.content->>'title' FROM analyses a WHERE a.forecast_id = s.forecast_id \
AND a.kind = 'forecast' AND a.status = 'done' ORDER BY a.completed_at DESC LIMIT 1) \
END AS summary_title, \
c1.result AS chart1, c2.result AS chart2, sy.result->'aspects' AS pair_aspects \
FROM shares s \
LEFT JOIN charts c ON c.id = s.chart_id \
LEFT JOIN forecasts f ON f.id = s.forecast_id \
LEFT JOIN charts fc ON fc.id = f.chart_id \
LEFT JOIN synastries sy ON sy.id = s.synastry_id \
LEFT JOIN charts c1 ON c1.id = sy.chart1_id \
LEFT JOIN charts c2 ON c2.id = sy.chart2_id";
/// Sun, Moon and (with a known birth time) the Ascendant: sign, degree, house.
fn big_three(natal: &Value) -> (Vec<Value>, bool) {
let time_known = natal.pointer("/time/time_known").and_then(Value::as_bool).unwrap_or(false);
let mut points: Vec<Value> = ["sun", "moon"]
.iter()
.filter_map(|id| natal["points"].as_array()?.iter().find(|p| p["id"] == *id))
.map(|p| {
json!({
"id": p["id"],
"sign": p["sign"],
"degree": p["degree_in_sign"].as_f64().map(|d| d.floor() as i64),
"house": if time_known { p["house"].clone() } else { Value::Null },
})
})
.collect();
let asc = &natal["angles"]["ascendant"];
if time_known && asc.is_object() {
points.push(json!({
"id": "ascendant",
"sign": asc["sign"],
"degree": asc["degree_in_sign"].as_f64().map(|d| d.floor() as i64),
"house": null,
}));
}
(points, time_known)
}
/// What the wheel is drawn from: the positions, angles, houses and aspects
/// (never the birth date, time or place).
fn wheel(chart: &Value) -> Value {
json!({
"points": chart["points"],
"angles": chart["angles"],
"houses": chart["houses"],
"aspects": chart["aspects"],
})
}
fn time_known(chart: &Value) -> bool {
chart.pointer("/time/time_known").and_then(Value::as_bool).unwrap_or(false)
}
fn card(row: &CardRow) -> Value {
if row.revoked {
return json!({ "slug": row.slug, "kind": row.kind, "revoked": true });
}
let title = match (row.kind.as_str(), row.year) {
("synastry", _) => "Két képlet összevetése".to_string(),
("forecast", Some(year)) => format!("Éves előrejelzés · {year}–{}", year + 1),
_ => "Születési képlet".to_string(),
};
let (points, known) = row.natal.as_ref().map(big_three).unwrap_or_default();
// The drawing itself: the chart's wheel, or the two charts on one wheel.
let chart = match (row.kind.as_str(), &row.natal) {
("chart", Some(natal)) => wheel(natal),
_ => Value::Null,
};
let pair = match (&row.chart1, &row.chart2) {
(Some(a), Some(b)) if row.kind == "synastry" => json!({
"chart1": wheel(a),
"chart2": wheel(b),
"time1": time_known(a),
"time2": time_known(b),
"aspects": row.pair_aspects.clone().unwrap_or(Value::Array(Vec::new())),
}),
_ => Value::Null,
};
json!({
"slug": row.slug,
"kind": row.kind,
"revoked": false,
"title": title,
"summary": row.summary_title,
"points": points,
"time_known": known,
"chart": chart,
"pair": pair,
})
}
/// The cards of these shares, as the viewer may see them: in full for
/// logged-in members, only that there is one for visitors.
pub async fn cards(db: &PgPool, viewer: &Viewer, ids: &[Uuid]) -> Result<HashMap<Uuid, Value>, sqlx::Error> {
if ids.is_empty() {
return Ok(HashMap::new());
}
let rows: Vec<CardRow> =
sqlx::query_as(&format!("{CARD_SELECT} WHERE s.id = ANY($1)")).bind(ids).fetch_all(db).await?;
Ok(rows
.iter()
.map(|r| {
let shown = if viewer.logged_in() { card(r) } else { json!({ "kind": r.kind, "locked": true }) };
(r.id, shown)
})
.collect())
}
/// A share the member made for the forum and has not revoked: its id.
pub async fn attachable(db: &PgPool, member: &Member, slug: &str) -> ApiResult<Uuid> {
let row: Option<(Uuid, Uuid, bool, bool)> =
sqlx::query_as("SELECT id, owner_id, for_forum, revoked_at IS NOT NULL FROM shares WHERE slug = $1")
.bind(slug.trim())
.fetch_optional(db)
.await?;
match row {
Some((id, owner, true, false)) if owner == member.user_id => Ok(id),
_ => Err(ApiError::bad("Ez a képlet nem csatolható. Indítsd újra a kérdést a képlet oldaláról.")),
}
}
/// The card of a share about to be attached (the new thread page shows it).
pub async fn preview(
State(state): St,
viewer: Viewer,
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<Json<Value>> {
let member = viewer.require_member()?;
let id = attachable(&state.db, member, &slug).await?;
let row: CardRow = sqlx::query_as(&format!("{CARD_SELECT} WHERE s.id = $1")).bind(id).fetch_one(&state.db).await?;
Ok(Json(card(&row)))
}