Files
sorsfonalak/services/forum/src/routes/attachments.rs
T
fecoandClaude Opus 5.5 863002c1e7 Forum: asking about one's own chart, forecast or comparison
- "Kérdezek róla a fórumon" on the chart, yearly forecast and comparison
  pages: after a window that says what goes out, a share link made for the
  forum (never birth data, names or a title) and a new thread in "Égbolt és
  képletek" with it attached.
- The question shows a card (Sun, Moon, Ascendant with sign, degree and
  house, the summary's title, a link to the shared page) to logged-in
  members only; visitors and search engines see only that there is one.
  The author can take it off, and deleting the question ends the link.
- The shared page (/s/...) now shows comparisons (one wheel, the aspects,
  no names) and yearly forecasts (keys, timeline, transits, the detailed
  text; without the birthday's place); the backend shares forecasts.
- The privacy notice (HU, EN) covers attached charts and muted members.

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

133 lines
5.1 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>,
}
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 \
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";
/// 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)
}
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, time_known) = row.natal.as_ref().map(big_three).unwrap_or_default();
json!({
"slug": row.slug,
"kind": row.kind,
"revoked": false,
"title": title,
"summary": row.summary_title,
"points": points,
"time_known": time_known,
})
}
/// 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)))
}