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
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
//! 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)))
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
//! role. A thread in a topic the viewer may not read answers 404, so its
|
||||
//! existence is not revealed.
|
||||
|
||||
mod attachments;
|
||||
mod avatars;
|
||||
mod home;
|
||||
mod members;
|
||||
@@ -53,6 +54,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/forum/followed", get(home::followed))
|
||||
.route("/v1/forum/replies", get(replies::list))
|
||||
.route("/v1/forum/search", get(search::search))
|
||||
.route("/v1/forum/share-card/{slug}", get(attachments::preview))
|
||||
.route("/v1/forum/posts/{id}/share", axum::routing::delete(posts::detach_share))
|
||||
.route("/v1/forum/sitemap", get(search::sitemap))
|
||||
.route("/v1/forum/replies/read", post(replies::read_all))
|
||||
.route("/v1/forum/threads", post(threads::create))
|
||||
|
||||
@@ -99,6 +99,10 @@ pub async fn remove(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
// Deleting one's own question takes the shared chart's link down too.
|
||||
if own && let Some(share) = post.share_id {
|
||||
revoke_share(&mut *tx, share, user.id).await?;
|
||||
}
|
||||
let mut reporters = Vec::new();
|
||||
if !own {
|
||||
reporters = super::reports::resolve_for_post(&mut tx, id, user.id).await?;
|
||||
@@ -310,3 +314,34 @@ async fn set_helped(
|
||||
.await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
/// The sharer's link goes (as when revoked on the main site).
|
||||
async fn revoke_share(db: impl sqlx::PgExecutor<'_>, share: uuid::Uuid, owner: uuid::Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL")
|
||||
.bind(share)
|
||||
.bind(owner)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The author takes the shared chart off their question: the card goes, and
|
||||
/// the link stops working.
|
||||
pub async fn detach_share(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let user = viewer.require_user()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.author_id != Some(user.id) {
|
||||
return Err(ApiError::Forbidden("Csak a saját kérdésedről veheted le a képletet.".into()));
|
||||
}
|
||||
let Some(share) = post.share_id else { return Ok(StatusCode::NO_CONTENT) };
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET share_id = NULL WHERE id = $1").bind(id).execute(&mut *tx).await?;
|
||||
revoke_share(&mut *tx, share, user.id).await?;
|
||||
tx.commit().await?;
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
@@ -99,10 +99,12 @@ pub struct PostRow {
|
||||
pub system: bool,
|
||||
/// The post this one answered (which may sit on the same level).
|
||||
pub reply_to_id: Option<i64>,
|
||||
/// A chart, forecast or synastry shared with the question.
|
||||
pub share_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id, body, created_at, edited_at, helped_at, deleted_at, deleted_by, \
|
||||
delete_reason, system, reply_to_id";
|
||||
delete_reason, system, reply_to_id, share_id";
|
||||
|
||||
/// Posts as the thread page shows them: authors, reactions, the viewer's own
|
||||
/// reaction. A removed post keeps its place with the reason; only
|
||||
@@ -110,6 +112,8 @@ pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id,
|
||||
pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiResult<Vec<Value>> {
|
||||
let ids: Vec<i64> = posts.iter().map(|p| p.id).collect();
|
||||
let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?;
|
||||
let shares: Vec<Uuid> = posts.iter().filter(|p| p.deleted_at.is_none()).filter_map(|p| p.share_id).collect();
|
||||
let cards = super::attachments::cards(db, viewer, &shares).await?;
|
||||
let counts: Vec<(i64, String, i64)> =
|
||||
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
|
||||
.bind(&ids)
|
||||
@@ -187,6 +191,7 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
|
||||
"reply_to": reply_to,
|
||||
// The viewer muted the author: the page folds it up.
|
||||
"muted": p.author_id.is_some_and(|a| viewer.mutes.contains(&a)),
|
||||
"share": p.share_id.and_then(|id| cards.get(&id).cloned()),
|
||||
});
|
||||
if moderator {
|
||||
post["down"] = json!(down);
|
||||
@@ -315,6 +320,9 @@ pub struct CreateThread {
|
||||
body: String,
|
||||
#[serde(default)]
|
||||
intent: Option<String>,
|
||||
/// A share made for the forum on the main site (`/s/<slug>`).
|
||||
#[serde(default)]
|
||||
share: Option<String>,
|
||||
}
|
||||
|
||||
/// Starts a thread with its opening post; the author follows it.
|
||||
@@ -338,6 +346,10 @@ pub async fn create(
|
||||
}
|
||||
let title = text::title(&req.title)?;
|
||||
let body = text::body(&req.body)?;
|
||||
let share = match req.share.as_deref().filter(|s| !s.trim().is_empty()) {
|
||||
Some(slug) => Some(super::attachments::attachable(&state.db, member, slug).await?),
|
||||
None => None,
|
||||
};
|
||||
let intent = match req.intent.as_deref() {
|
||||
Some(i @ ("listen" | "advice")) => Some(i.to_string()),
|
||||
None | Some("") => listening.then(|| "listen".to_string()),
|
||||
@@ -356,11 +368,13 @@ pub async fn create(
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let post_id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, $3) RETURNING id",
|
||||
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body, share_id) \
|
||||
VALUES ($1, $2, true, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(member.user_id)
|
||||
.bind(&body)
|
||||
.bind(share)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
|
||||
|
||||
@@ -1209,3 +1209,108 @@ async fn search_mutes_and_archived_topics(pool: PgPool) {
|
||||
app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&admin), json!({ "archived": false })).await;
|
||||
app.reply(&bea, sleep, "Még egy szó.", None).await;
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn a_question_about_ones_chart(pool: PgPool) {
|
||||
let app = TestApp::new(pool);
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
|
||||
// Anna's chart (made-up data) and a share of it made for the forum; Bea's own share.
|
||||
let chart = Uuid::now_v7();
|
||||
let result = json!({
|
||||
"time": {"time_known": true},
|
||||
"points": [
|
||||
{"id": "sun", "sign": "leo", "degree_in_sign": 12.7, "house": 10},
|
||||
{"id": "moon", "sign": "pisces", "degree_in_sign": 3.2, "house": 5}
|
||||
],
|
||||
"angles": {"ascendant": {"sign": "scorpio", "degree_in_sign": 21.9}}
|
||||
});
|
||||
sqlx::query(
|
||||
"INSERT INTO charts (id, owner_id, label, birth_data, result, chart_hash, kind) \
|
||||
VALUES ($1, $2, 'Kovács Anna', '{}', $3, 'h', 'own')",
|
||||
)
|
||||
.bind(chart)
|
||||
.bind(anna.id)
|
||||
.bind(&result)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for (slug, owner, for_forum) in [("annaforum000001", anna.id, true), ("annaplain000001", anna.id, false)] {
|
||||
sqlx::query(
|
||||
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, for_forum) VALUES ($1, $2, $3, 'chart', $4, $5)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(owner)
|
||||
.bind(slug)
|
||||
.bind(chart)
|
||||
.bind(for_forum)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Only one's own forum share can go with a question.
|
||||
let preview = app.get("/v1/forum/share-card/annaforum000001", Some(&anna)).await;
|
||||
assert_eq!(preview["title"], "Születési képlet");
|
||||
assert_eq!(preview["points"][0], json!({"id": "sun", "sign": "leo", "degree": 12, "house": 10}));
|
||||
assert_eq!(preview["points"][2]["id"], "ascendant");
|
||||
assert!(!preview.to_string().contains("Kovács"), "no names");
|
||||
for (slug, who) in [("annaplain000001", &anna), ("annaforum000001", &bea), ("nincsilyen", &anna)] {
|
||||
let (status, _) = app.call("GET", &format!("/v1/forum/share-card/{slug}"), Some(who), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{slug}");
|
||||
}
|
||||
let (status, _) = app
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/forum/threads",
|
||||
Some(&bea),
|
||||
json!({ "topic": "egbolt-es-kepletek", "title": "Az övé", "body": "Kérdés", "share": "annaforum000001" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let (status, created) = app
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/forum/threads",
|
||||
Some(&anna),
|
||||
json!({
|
||||
"topic": "egbolt-es-kepletek",
|
||||
"title": "Mit jelent a Hold az ötödik házban?",
|
||||
"body": "Sokat gondolkodom rajta.",
|
||||
"share": "annaforum000001"
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::CREATED, "{created}");
|
||||
let id = created["id"].as_i64().unwrap();
|
||||
|
||||
// Members see the card; a visitor only that there is one.
|
||||
let shown = app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await;
|
||||
assert_eq!(shown["posts"][0]["share"]["slug"], "annaforum000001");
|
||||
assert_eq!(shown["posts"][0]["share"]["points"][1]["sign"], "pisces");
|
||||
let public = app.get(&format!("/v1/forum/threads/{id}"), None).await;
|
||||
assert_eq!(public["posts"][0]["share"], json!({ "kind": "chart", "locked": true }));
|
||||
assert!(!public.to_string().contains("annaforum000001"));
|
||||
|
||||
// Revoked on the main site: the card says so.
|
||||
sqlx::query("UPDATE shares SET revoked_at = now() WHERE slug = 'annaforum000001'")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let shown = app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await;
|
||||
assert_eq!(shown["posts"][0]["share"]["revoked"], true);
|
||||
assert!(shown["posts"][0]["share"].get("points").is_none());
|
||||
|
||||
// The author takes it off (only she may): the card goes, the link stops working.
|
||||
sqlx::query("UPDATE shares SET revoked_at = NULL WHERE slug = 'annaforum000001'").execute(&app.pool).await.unwrap();
|
||||
let opening = shown["posts"][0]["id"].as_i64().unwrap();
|
||||
let uri = format!("/v1/forum/posts/{opening}/share");
|
||||
assert_eq!(app.call("DELETE", &uri, Some(&bea), Value::Null).await.0, StatusCode::FORBIDDEN);
|
||||
assert_eq!(app.call("DELETE", &uri, Some(&anna), Value::Null).await.0, StatusCode::NO_CONTENT);
|
||||
assert!(app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await["posts"][0]["share"].is_null());
|
||||
let revoked: bool = sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'")
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(revoked);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user