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:
feco
2026-11-26 14:52:00 +00:00
co-authored by Claude Opus 5.5
parent 9ca3f478be
commit 863002c1e7
24 changed files with 871 additions and 32 deletions
+82 -11
View File
@@ -13,6 +13,12 @@
//! per user: a click proves little. A natal analysis is earned by bringing a
//! new user (`REFERRAL_REWARDS`): someone who signs up from a shared link and
//! makes their own chart, at most [`REFERRAL_LIMIT`] times.
//!
//! A share made for the forum (`for_forum`, a question about one's chart,
//! forecast or synastry) never shows birth data, and its public view leaves
//! out the chart names: they may be real names next to a nickname. A yearly
//! forecast can be shared too: its calculation and its detailed text, without
//! the place of the birthday.
use axum::Json;
use axum::extract::{Path, State};
@@ -27,6 +33,7 @@ use uuid::Uuid;
use super::analyses::{can_see, find_analysis};
use super::charts::{ChartRow, find_chart, owned_chart};
use super::forecasts::{ForecastRow, find_forecast, owned_forecast};
use super::synastries::{VisibleSynastry, load_synastry, visible_synastry};
use super::{Body, IdPath, St};
use crate::auth::{AuthUser, user_agent};
@@ -39,6 +46,7 @@ pub enum ShareKind {
Chart,
Synastry,
Analysis,
Forecast,
}
#[derive(Debug, sqlx::FromRow)]
@@ -50,16 +58,18 @@ struct ShareRow {
chart_id: Option<Uuid>,
synastry_id: Option<Uuid>,
analysis_id: Option<Uuid>,
forecast_id: Option<Uuid>,
title: Option<String>,
show_birth_data: bool,
for_forum: bool,
view_count: i64,
created_at: OffsetDateTime,
revoked_at: Option<OffsetDateTime>,
owner_ip_hash: Option<Vec<u8>>,
}
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
view_count, created_at, revoked_at, owner_ip_hash";
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, forecast_id, title, \
show_birth_data, for_forum, view_count, created_at, revoked_at, owner_ip_hash";
use super::client_ip;
@@ -113,8 +123,10 @@ impl ShareRow {
"chart_id": self.chart_id,
"synastry_id": self.synastry_id,
"analysis_id": self.analysis_id,
"forecast_id": self.forecast_id,
"title": self.title,
"show_birth_data": self.show_birth_data,
"for_forum": self.for_forum,
"view_count": self.view_count,
"created_at": rfc3339(self.created_at),
"revoked_at": rfc3339_opt(self.revoked_at),
@@ -132,6 +144,9 @@ pub struct CreateShare {
/// Show birth date, time and place (only ever of the sharer's own charts).
#[serde(default)]
show_birth_data: bool,
/// For a forum post: no birth data, no names, no title.
#[serde(default)]
for_forum: bool,
}
pub async fn create(
@@ -140,14 +155,22 @@ pub async fn create(
headers: HeaderMap,
WithRejection(Json(req), _): Body<CreateShare>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
let (mut chart_id, mut synastry_id, mut analysis_id, mut forecast_id) = (None, None, None, None);
let kind = match req.kind {
ShareKind::Chart => {
owned_chart(&state.db, req.target_id, auth.id()).await?;
(Some(req.target_id), None, None, "chart")
chart_id = Some(req.target_id);
"chart"
}
ShareKind::Synastry => {
visible_synastry(&state.db, req.target_id, auth.id()).await?;
(None, Some(req.target_id), None, "synastry")
synastry_id = Some(req.target_id);
"synastry"
}
ShareKind::Forecast => {
owned_forecast(&state.db, req.target_id, auth.id()).await?;
forecast_id = Some(req.target_id);
"forecast"
}
ShareKind::Analysis => {
let analysis = find_analysis(&state.db, req.target_id).await?.ok_or(ApiError::NotFound("analysis"))?;
@@ -157,14 +180,18 @@ pub async fn create(
if analysis.status != "done" {
return Err(ApiError::conflict("analysis_not_ready", "Csak elkészült elemzést lehet megosztani."));
}
(None, None, Some(req.target_id), "analysis")
analysis_id = Some(req.target_id);
"analysis"
}
};
let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty());
// A forum share: never birth data, and no title of the sharer's own.
let (title, show_birth_data) = if req.for_forum { (None, false) } else { (title, req.show_birth_data) };
let open: Option<ShareRow> = sqlx::query_as(&format!(
"SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \
AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \
AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \
AND forecast_id IS NOT DISTINCT FROM $8 AND for_forum = $9 \
ORDER BY created_at DESC LIMIT 1"
))
.bind(auth.id())
@@ -173,7 +200,9 @@ pub async fn create(
.bind(synastry_id)
.bind(analysis_id)
.bind(&title)
.bind(req.show_birth_data)
.bind(show_birth_data)
.bind(forecast_id)
.bind(req.for_forum)
.fetch_optional(&state.db)
.await?;
if let Some(row) = open {
@@ -182,8 +211,8 @@ pub async fn create(
let slug = new_slug();
let row: ShareRow = sqlx::query_as(&format!(
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
owner_ip_hash) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING {SHARE_COLUMNS}"
owner_ip_hash, forecast_id, for_forum) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING {SHARE_COLUMNS}"
))
.bind(Uuid::now_v7())
.bind(auth.id())
@@ -193,8 +222,10 @@ pub async fn create(
.bind(synastry_id)
.bind(analysis_id)
.bind(title)
.bind(req.show_birth_data)
.bind(show_birth_data)
.bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip)))
.bind(forecast_id)
.bind(req.for_forum)
.fetch_one(&state.db)
.await?;
Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url))))
@@ -229,7 +260,27 @@ fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value {
// Birth data only of the sharer's own chart, never of a partner's or of a
// person they added (that is someone else's data).
let show = share.show_birth_data && chart.owner_id == share.owner_id && chart.kind == "own";
json!({ "label": chart.label, "chart": public_chart(&chart.result, show) })
// A forum share leaves out the names (they may be real names next to a nickname).
let label = if share.for_forum { Value::Null } else { Value::from(chart.label.clone()) };
json!({ "label": label, "chart": public_chart(&chart.result, show) })
}
/// A yearly forecast without where it was reckoned: the solar return chart
/// without its place and time zone, and the year's calculation.
fn public_forecast_block(forecast: &ForecastRow) -> Value {
let sr = &forecast.result["solar_return"];
let solar_return = if sr.is_object() {
let mut chart = public_chart(sr, false);
if let Some(obj) = chart.as_object_mut() {
for key in ["local_time", "timezone", "utc_offset", "moment_utc", "location"] {
obj.remove(key);
}
}
chart
} else {
Value::Null
};
json!({ "year": forecast.year, "forecast": forecast.result["forecast"], "solar_return": solar_return })
}
fn public_synastry_block(s: &VisibleSynastry, share: &ShareRow) -> Value {
@@ -269,6 +320,26 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
body["synastry"] = public_synastry_block(&s, share);
}
} else if let Some(forecast_id) = share.forecast_id {
let forecast = find_forecast(db, forecast_id).await?.ok_or(ApiError::NotFound("share"))?;
body["forecast"] = public_forecast_block(&forecast);
// The detailed text of the year, if it was written.
let analysis: Option<(String, Option<Value>, Option<OffsetDateTime>)> = sqlx::query_as(
"SELECT language, content, completed_at FROM analyses \
WHERE forecast_id = $1 AND kind = 'forecast' AND status = 'done' ORDER BY completed_at DESC LIMIT 1",
)
.bind(forecast_id)
.fetch_optional(db)
.await?;
body["analysis"] = match analysis {
Some((language, content, completed_at)) => json!({
"kind": "forecast",
"language": language,
"content": content,
"completed_at": rfc3339_opt(completed_at),
}),
None => Value::Null,
};
}
Ok(body)
}
+28
View File
@@ -1011,6 +1011,21 @@ async fn public_shares(pool: PgPool) {
);
assert_eq!(app.get(&format!("/v1/public/shares/{slug}"), None).await.status, StatusCode::NOT_FOUND);
assert_eq!(app.get("/v1/public/shares/nincs-ilyen", None).await.status, StatusCode::NOT_FOUND);
// A share for the forum: its own link, never birth data, no names, no title.
let r = app
.post(
"/v1/shares",
Some(&anna),
json!({"kind": "chart", "target_id": chart_id, "for_forum": true, "show_birth_data": true, "title": "Én"}),
)
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
assert_eq!((r.body["for_forum"].as_bool(), r.body["show_birth_data"].as_bool()), (Some(true), Some(false)));
let r = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await;
assert!(r.body["chart"]["label"].is_null(), "{}", r.body);
assert!(r.body["chart"]["chart"].get("birth").is_none());
assert!(r.body["title"].is_null());
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -1968,6 +1983,19 @@ async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
assert_eq!(app.get(&uri, Some(&bob)).await.status, StatusCode::NOT_FOUND);
assert_eq!(app.get(&format!("/v1/forecasts/{id}"), Some(&anna)).await.body["year"], json!(year));
// A forecast can be shared (not by others), without where it was reckoned.
let r = app.post("/v1/shares", Some(&bob), json!({"kind": "forecast", "target_id": away.body["id"]})).await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
let r = app
.post("/v1/shares", Some(&anna), json!({"kind": "forecast", "target_id": away.body["id"], "for_forum": true}))
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let shared = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await.body;
assert_eq!(shared["kind"], "forecast");
assert_eq!(shared["forecast"]["forecast"]["start"], format!("{year}-03-15"));
assert!(!shared.to_string().contains("Tokió"), "the place stays private: {shared}");
assert!(shared["analysis"].is_null(), "no detailed text yet");
// the detailed text uses a forecast unit, not a natal one
let analyses = format!("/v1/forecasts/{id}/analyses");
grant_units(&app, &anna, "natal", 1).await;
+132
View File
@@ -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)))
}
+3
View File
@@ -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))
+35
View File
@@ -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)
}
+16 -2
View File
@@ -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?;
+105
View File
@@ -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);
}
+15 -2
View File
@@ -161,11 +161,19 @@ export default async function PrivacyPage() {
<tr>
<td>
A fórumon írt szálaid és hozzászólásaid, a reakcióid és „Ez segített” jelöléseid, a pontjaid és a
rangod; kiket említettél (@álnév); hogy mit olvastál el, és mely szálakat követed
rangod; kiket említettél (@álnév); hogy mit olvastál el, mely szálakat követed, és kiket
némítottál el
</td>
<td>A fórum működése, a rangok, az újdonságok jelzése</td>
<td>Szerződés teljesítése</td>
</tr>
<tr>
<td>
A fórumkérdéseidhez csatolt képlet, éves előrejelzés vagy összevetés megosztó linkje
</td>
<td>Hogy a tagok lássák, amiről kérdezel; a csatolás a saját döntésed</td>
<td>Szerződés teljesítése</td>
</tr>
<tr>
<td>Zárt témákba küldött jelentkezéseid (a pár szavas indoklással) és a tagságaid</td>
<td>A zárt témák: a moderátorok döntenek a felvételről</td>
@@ -225,7 +233,12 @@ export default async function PrivacyPage() {
képletedből soha nem mutatunk fokokat. A privát üzeneteidet csak a beszélgetés két résztvevője látja; a
moderátorok csak akkor, ha valaki egy üzenetet jelent, és akkor is csak a jelentett üzenetet és az előtte
lévő néhányat. A moderátorok (az üzemeltető által kijelölt tagok) a valódi nevedet és az e-mail-címedet nem
látják. A fórum szabályai az <Link href="/aszf#forum">ÁSZF 8. pontjában</Link> vannak.
látják. Ha egy kérdésedhez csatolod a képletedet, az éves előrejelzésedet vagy egy összevetést, azt csak a
belépett tagok látják: a rajzot fokokkal és házakkal, a rövid összefoglalót vagy az előrejelzés szövegét,
nevek, születési dátum, idő és hely nélkül. A fokokból egy jártas asztrológus nagyjából kiszámolhatja a
születési napot és időt, az előrejelzés kezdőnapjából pedig a születésnap kiderül. A csatolt képletet
bármikor leveheted, és a kérdés törlésével a link is megszűnik. A fórum szabályai az{" "}
<Link href="/aszf#forum">ÁSZF 8. pontjában</Link> vannak.
</p>
</section>
@@ -61,7 +61,9 @@ async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[]
});
for (const cookie of res.headers.getSetCookie()) out.append("set-cookie", cookie);
// A revoked link must disappear at once from the cached share pages.
if (req.method === "DELETE" && path[0] === "shares" && res.ok) revalidateTag(SHARES_TAG, { expire: 0 });
// A revoked link (also a chart taken off a forum question, or the question deleted) goes from the cache.
const revokes = path[0] === "shares" || (path[0] === "forum" && path[1] === "posts");
if (req.method === "DELETE" && revokes && res.ok) revalidateTag(SHARES_TAG, { expire: 0 });
// An admin's change to a famous person shows on the public pages at once.
if (req.method !== "GET" && path[0] === "admin" && path[1] === "celebrities" && res.ok) {
revalidateTag(CELEBRITIES_TAG, { expire: 0 });
+14
View File
@@ -687,3 +687,17 @@ a.fh-online-item:hover { color: var(--gold); }
.fh-archived summary { min-height: 44px; display: flex; align-items: center; color: var(--ink-2); font-size: 15px; cursor: pointer; }
.fh-archived .fh-links { list-style: none; margin: 0; padding: 0; }
.fh-archived li + li .fh-link { border-top: 1px solid var(--line); }
/* --- a chart shared with a question --- */
.fshare {
display: flex; flex-direction: column; align-items: flex-start; gap: 6px; margin-top: 12px; padding: 14px 16px;
border: 1px solid var(--line-2); border-radius: 14px; background: var(--f-tint);
}
.fshare-quiet { background: none; border-style: dashed; }
.fshare-head { display: flex; align-items: center; justify-content: space-between; width: 100%; }
.fshare-title { font-size: 16px; }
.fshare-summary { font-family: var(--font-display); font-size: 19px; color: var(--ink-2); }
.fshare-points { list-style: none; margin: 2px 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 16px; font-size: 15px; }
.fshare-open { margin-top: 4px; }
.fnew-share { display: flex; flex-direction: column; gap: 8px; }
.fnew-share .fshare { margin-top: 0; }
@@ -6,12 +6,23 @@ import { useState } from "react";
import { api, errorText } from "@/lib/api";
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
import { type ForumTopic, threadHref } from "@/lib/forum";
import { ShareCard } from "@/components/forum/ShareCard";
import { type ForumTopic, type ShareCardData, threadHref } from "@/lib/forum";
type Intent = "listen" | "advice" | "";
export function NewThreadForm({ topics, initialTopic }: { topics: ForumTopic[]; initialTopic: string }) {
export function NewThreadForm({
topics,
initialTopic,
share: initialShare,
}: {
topics: ForumTopic[];
initialTopic: string;
/** A chart, forecast or synastry shared for the question (from its page). */
share?: { slug: string; card: ShareCardData } | null;
}) {
const router = useRouter();
const [share, setShare] = useState(initialShare ?? null);
const [topic, setTopic] = useState(initialTopic);
const listening = topics.find((t) => t.slug === topic)?.listening ?? false;
const [intent, setIntent] = useState<Intent>(listening ? "listen" : "");
@@ -37,6 +48,7 @@ export function NewThreadForm({ topics, initialTopic }: { topics: ForumTopic[];
title: convertEmoticons(title, title.length, true).text,
body: convertEmoticons(body, body.length, true).text,
intent: intent || null,
share: share?.slug ?? null,
},
});
router.push(threadHref(created));
@@ -49,6 +61,15 @@ export function NewThreadForm({ topics, initialTopic }: { topics: ForumTopic[];
return (
<form className="fnew" onSubmit={submit}>
{share && (
<div className="fnew-share">
<ShareCard share={share.card} onRemove={() => setShare(null)} />
<span className="hint">
A belépett tagok látják a hozzászólásod alatt. Írd le, mire vagy kíváncsi: minél konkrétabb a kérdés, annál
jobb válaszokat kapsz.
</span>
</div>
)}
<fieldset className="fnew-set">
<legend>Téma</legend>
<div className="fnew-topics">
+16 -5
View File
@@ -1,18 +1,21 @@
import { redirect } from "next/navigation";
import type { ForumTopic, ForumViewer } from "@/lib/forum";
import type { ForumTopic, ForumViewer, ShareCardData } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
import { NewThreadForm } from "./NewThreadForm";
export const metadata = { title: "Új szál", robots: { index: false } };
type Props = { searchParams: Promise<{ tema?: string }> };
type Props = { searchParams: Promise<{ tema?: string; kepletkartya?: string }> };
/** Starting a thread: a nickname first, then topic, wish, title and text. */
export default async function NewThreadPage({ searchParams }: Props) {
const { tema } = await searchParams;
const back = `/forum/uj${tema ? `?tema=${encodeURIComponent(tema)}` : ""}`;
const { tema, kepletkartya } = await searchParams;
const query = new URLSearchParams();
if (tema) query.set("tema", tema);
if (kepletkartya) query.set("kepletkartya", kepletkartya);
const back = `/forum/uj${query.size ? `?${query}` : ""}`;
const res = await forumGet<{ topics: ForumTopic[] }>("/v1/forum/topics");
const nav = await forumGet<{ viewer: ForumViewer }>("/v1/forum/nav");
const viewer = nav.ok ? nav.data.viewer : null;
@@ -20,13 +23,21 @@ export default async function NewThreadPage({ searchParams }: Props) {
if (viewer.needs_nickname) redirect(`/forum/beallitasok?vissza=${encodeURIComponent(back)}`);
const topics = res.ok ? res.data.topics.filter((t) => t.readable && !t.archived) : [];
const initial = topics.find((t) => t.slug === tema)?.slug ?? topics[0]?.slug ?? "";
// A question about one's chart: the share made for it on the chart page.
const card = kepletkartya
? await forumGet<ShareCardData>(`/v1/forum/share-card/${encodeURIComponent(kepletkartya)}`).catch(() => null)
: null;
return (
<div className="fh">
<h1 className="fpage-title">Új szál</h1>
{viewer.member?.banned ? (
<p className="fh-banner fh-banner-warn">Most nem írhatsz a fórumba.</p>
) : (
<NewThreadForm topics={topics} initialTopic={initial} />
<NewThreadForm
topics={topics}
initialTopic={initial}
share={card?.ok && kepletkartya ? { slug: kepletkartya, card: card.data } : null}
/>
)}
</div>
);
+7
View File
@@ -1796,3 +1796,10 @@ span.tarot-fan-card { cursor: default; }
.lp-gift-text { align-items: center; }
.lp-gift-card { width: 160px; }
}
/* "Kérdezek róla a fórumon" (chart, forecast and comparison pages). */
.ask-forum { display: inline-flex; align-items: center; gap: 8px; }
.ask-forum svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.ask-forum-card { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; }
.ask-forum-body { display: flex; flex-direction: column; gap: 12px; }
.ask-forum-actions { display: flex; justify-content: flex-end; gap: 8px; flex-wrap: wrap; margin-top: 4px; }
@@ -2,11 +2,13 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { AskOnForum } from "@/components/AskOnForum";
import { ChartWheel } from "@/components/ChartWheel";
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
import { ForecastKeys, ForecastTimeline, ForecastTransits, longDay } from "@/components/ForecastViews";
import { Tabs } from "@/components/Tabs";
import { payMethod } from "@/lib/payments";
import { forumEnabled } from "@/lib/forumServer";
import { backendGet, requireMe } from "@/lib/server";
import type { Analysis, Chart, ForecastDetail, ForecastList, PublicConfig } from "@/lib/types";
@@ -94,6 +96,12 @@ export default async function ForecastPage({
)}
<div className="field chart-side">
<ForecastKeys forecast={fc} solarReturn={sr} />
{forumEnabled() && (
<div className="card ask-forum-card">
<p className="muted">Kérdésed van az évedről? Kérdezd meg a fórum tagjait.</p>
<AskOnForum kind="forecast" targetId={forecast.id} />
</div>
)}
{(list.years.length > 0 || others.length > 0) && (
<details className="card">
<summary>Másik év vagy helyszín</summary>
@@ -3,6 +3,7 @@ import Link from "next/link";
import { notFound } from "next/navigation";
import { AspectGrid, AspectList, BigThree, PositionTables } from "@/components/ChartTables";
import { AskOnForum } from "@/components/AskOnForum";
import { ChartSummary } from "@/components/ChartSummary";
import { ChartSwitcher } from "@/components/ChartSwitcher";
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
@@ -12,6 +13,7 @@ import { SkyToday } from "@/components/SkyToday";
import { Tabs } from "@/components/Tabs";
import { ASPECTS, ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro";
import { payMethod } from "@/lib/payments";
import { forumEnabled } from "@/lib/forumServer";
import { backendGet, requireMe } from "@/lib/server";
import { loadSky } from "@/lib/sky";
import type { Analysis, Chart, ChartListItem, PublicConfig } from "@/lib/types";
@@ -86,6 +88,12 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
/>
<BigThree chart={chart} />
{forumEnabled() && (
<div className="card ask-forum-card">
<p className="muted">Kérdésed van a képletről? Kérdezd meg a fórum tagjait.</p>
<AskOnForum kind="chart" targetId={chart.id} />
</div>
)}
</div>
</section>
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { AskOnForum } from "@/components/AskOnForum";
import { SignTrio } from "@/components/ChartCard";
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
import { CompositeTables, CrossGrid, HouseOverlays, InterAspectList, NatureBar } from "@/components/SynastryTables";
@@ -9,6 +10,7 @@ import { SynastryLegend, SynastryWheel } from "@/components/SynastryWheel";
import { Tabs } from "@/components/Tabs";
import { ASPECTS, formatBirthDate } from "@/lib/astro";
import { payMethod } from "@/lib/payments";
import { forumEnabled } from "@/lib/forumServer";
import { backendGet, requireMe } from "@/lib/server";
import { sideName, sideTimeKnown } from "@/lib/synastry";
import type { Analysis, ChartListItem, PublicConfig, Synastry, SynastrySide } from "@/lib/types";
@@ -112,6 +114,12 @@ export default async function ComparisonPage({ params }: { params: Promise<{ id:
</p>
)}
</div>
{forumEnabled() && (
<div className="card ask-forum-card">
<p className="muted">Kérdésed van kettőtök képletéről? Kérdezd meg a fórum tagjait.</p>
<AskOnForum kind="synastry" targetId={synastry.id} />
</div>
)}
</div>
</section>
+11 -2
View File
@@ -90,10 +90,15 @@ const DATA: [string, string, string][] = [
"Performance of the contract",
],
[
"Your forum threads and posts, your reactions and “Ez segített” (it helped) marks, your points and rank; whom you mentioned (@nickname); what you have read, and the threads you follow",
"Your forum threads and posts, your reactions and “Ez segített” (it helped) marks, your points and rank; whom you mentioned (@nickname); what you have read, the threads you follow, and the members you muted",
"Running the forum, the ranks, showing what is new",
"Performance of the contract",
],
[
"The share link of a chart, yearly forecast or comparison you attach to a forum question",
"So that members see what you are asking about; attaching it is your choice",
"Performance of the contract",
],
[
"Your requests to join restricted topics (with the few words you add) and your memberships",
"Restricted topics: the moderators decide who joins",
@@ -194,7 +199,11 @@ export default async function PrivacyPolicyPage() {
you switched on (Kísérő – companion, Támogató – supporter); never your real name, e-mail address or birth data, and never the
degrees of your chart. Your private messages are seen only by the two people in the conversation; moderators
see a message only when someone reports it, and then only that message and the few before it. Moderators
(members appointed by the operator) do not see your real name or e-mail address. The forum rules are in
(members appointed by the operator) do not see your real name or e-mail address. If you attach your chart,
yearly forecast or a comparison to a question, only logged-in members see it: the drawing with degrees and
houses, the short summary or the forecast text, without names, birth date, time or place. A practised
astrologer can roughly work out the birth date and time from the degrees, and a forecast's first day is the
birthday. You can take it off at any time, and deleting the question ends the link. The forum rules are in
point 8 of the <Link href="/aszf#forum">terms (ÁSZF, in Hungarian)</Link>.
</p>
</section>
+125 -1
View File
@@ -2,13 +2,18 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { AnalysisView } from "@/components/AnalysisView";
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
import { ForecastKeys, ForecastTimeline, ForecastTransits, longDay } from "@/components/ForecastViews";
import { InterAspectList, NatureBar } from "@/components/SynastryTables";
import { SynastryLegend, SynastryWheel } from "@/components/SynastryWheel";
import { Rich } from "@/components/Rich";
import { ShareVisit } from "@/components/ShareVisit";
import { PublicHeader } from "@/components/SiteHeader";
import { SIGNS, signName } from "@/lib/astro";
import { getMe } from "@/lib/server";
import { bigThree, imageVersion, loadShare, plain, shorten, siteUrl } from "@/lib/share";
import { type PublicShare, bigThree, imageVersion, loadShare, plain, shorten, siteUrl } from "@/lib/share";
import type { Synastry } from "@/lib/types";
type Props = { params: Promise<{ slug: string }> };
@@ -16,6 +21,13 @@ type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const share = await loadShare(slug);
if (share?.kind === "synastry" && share.synastry) {
return { title: "Megosztott összevetés", robots: { index: false, follow: false } };
}
if (share?.kind === "forecast" && share.forecast) {
const y = share.forecast.year;
return { title: `Megosztott éves előrejelzés · ${y}–${y + 1}`, robots: { index: false, follow: false } };
}
if (!share?.chart) return { title: "A link nem érhető el", robots: { index: false } };
const base = await siteUrl();
const title = share.summary?.title ?? "Születési képlet";
@@ -39,6 +51,12 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
export default async function SharedChartPage({ params }: Props) {
const { slug } = await params;
const [share, me] = await Promise.all([loadShare(slug), getMe()]);
if (share?.kind === "synastry" && share.synastry) {
return <SharedSynastry slug={slug} share={share} loggedIn={me !== null} />;
}
if (share?.kind === "forecast" && share.forecast) {
return <SharedForecast slug={slug} share={share} loggedIn={me !== null} />;
}
const chart = share?.chart?.chart;
if (!share || !chart) notFound();
const summary = share.summary;
@@ -106,3 +124,109 @@ export default async function SharedChartPage({ params }: Props) {
</>
);
}
/** A shared comparison: the two charts on one wheel and the aspects between them, without names. */
function SharedSynastry({ slug, share, loggedIn }: { slug: string; share: PublicShare; loggedIn: boolean }) {
const s = share.synastry!;
const name1 = s.chart1.label ?? "Első képlet";
const name2 = s.chart2.label ?? "Második képlet";
const time1 = s.chart1.chart.time_known;
const time2 = s.chart2.chart.time_known;
// The tables read only the result.
const synastry = { synastry: s.synastry } as unknown as Synastry;
return (
<>
<ShareVisit slug={slug} />
{!loggedIn && <PublicHeader />}
<main className="page" style={{ maxWidth: 1180 }}>
<div className="page-head">
<span className="eyebrow">Megosztott összevetés</span>
<h1>Két képlet egymásra vetítve</h1>
</div>
<section className="chart-layout" aria-label="Kettős képletrajz">
<div className="card chart-wheel-card">
<SynastryWheel
chart1={s.chart1.chart}
chart2={s.chart2.chart}
time1={time1}
time2={time2}
aspects={s.synastry.aspects}
name1={name1}
name2={name2}
/>
<SynastryLegend name1={name1} name2={name2} time1={time1} />
</div>
<div className="field chart-side">
<div className="card summary-card">
<span className="eyebrow">Számokban</span>
<h2 className="summary-title">{s.synastry.summary.aspect_count} fényszög a két képlet között</h2>
<NatureBar summary={s.synastry.summary} />
</div>
</div>
</section>
<section className="card" aria-label="Fényszögek">
<h2>Fényszögek</h2>
<InterAspectList synastry={synastry} name1={name1} name2={name2} />
</section>
<p className="hint">Ezt az összevetést a tulajdonosa osztotta meg, nevek és születési adatok nélkül.</p>
</main>
</>
);
}
/** A shared yearly forecast: the year's keys, timeline and transits, and the detailed text if it was written. */
function SharedForecast({ slug, share, loggedIn }: { slug: string; share: PublicShare; loggedIn: boolean }) {
const f = share.forecast!;
const fc = f.forecast;
const sr = f.solar_return;
const text = share.analysis?.content ?? null;
return (
<>
<ShareVisit slug={slug} />
{!loggedIn && <PublicHeader />}
<main className="page" style={{ maxWidth: 1180 }}>
<div className="page-head">
<span className="eyebrow">Megosztott éves előrejelzés</span>
<h1>
{f.year}–{f.year + 1}
</h1>
<p className="muted">
{longDay(fc.start)} – {longDay(fc.end)}
</p>
</div>
<section className="chart-layout" aria-label="Szolár képlet">
{sr ? (
<div className="card chart-wheel-card">
<ChartWheel chart={sr} timeKnown title="Szolár képlet" />
<p className="hint">Szolár képlet: a Nap ekkor ér vissza pontosan a születéskori helyére.</p>
</div>
) : (
<div className="card">
<p className="muted">Szolár képlet nincs, mert a születési idő ismeretlen.</p>
</div>
)}
<div className="field chart-side">
<ForecastKeys forecast={fc} solarReturn={sr} />
</div>
</section>
{text && (
<section className="card" aria-label="Előrejelzés">
<AnalysisView content={text} kind="forecast" language={share.analysis?.language} />
</section>
)}
<section className="card" aria-label="Idővonal">
<h2>Idővonal</h2>
<ForecastTimeline forecast={fc} />
</section>
<section className="card" aria-label="Tranzitok">
<h2>Tranzitok</h2>
<ForecastTransits forecast={fc} />
</section>
<p className="hint">
Ezt az előrejelzést a tulajdonosa osztotta meg, név, születési adatok és helyszín nélkül.
{text && " A szöveget mesterséges intelligencia írta a képlet alapján."}
</p>
</main>
</>
);
}
@@ -0,0 +1,91 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
import { Modal } from "./Modal";
type Kind = "chart" | "synastry" | "forecast";
const WHAT: Record<Kind, { button: string; shown: string; extra?: string }> = {
chart: {
button: "Kérdezek róla a fórumon",
shown: "a képleted rajzát a bolygók fokaival és házaival, és a rövid összefoglalót, ha már van",
},
synastry: {
button: "Kérdezek róla a fórumon",
shown: "a két képlet közös rajzát, a köztük lévő fényszögeket és házakat",
extra: "A másik fél nevét és születési adatait sem mutatjuk, de az ő képlete is látszik.",
},
forecast: {
button: "Kérdezek róla a fórumon",
shown: "az év kulcsait, az idővonalat, a tranzitokat és a részletes előrejelzést, ha már elkészült",
extra: "Az előrejelzés éve a születésnapodon kezdődik, ezért abból a születésnapod kiderül.",
},
};
/**
* "Kérdezek róla a fórumon": a link made for the forum (no birth data, no
* names), then a new thread in "Égbolt és képletek" with it attached.
*/
export function AskOnForum({ kind, targetId }: { kind: Kind; targetId: string }) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const what = WHAT[kind];
async function go() {
setBusy(true);
setError(null);
try {
const share = await api<{ slug: string }>("/shares", { body: { kind, target_id: targetId, for_forum: true } });
router.push(`/forum/uj?tema=egbolt-es-kepletek&kepletkartya=${encodeURIComponent(share.slug)}`);
} catch (e) {
setError(errorText(e));
setBusy(false);
}
}
return (
<>
<button type="button" className="btn btn-sm ask-forum" onClick={() => setOpen(true)}>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
</svg>
{what.button}
</button>
{open && (
<Modal title="Kérdés a fórumon" onClose={() => setOpen(false)}>
<div className="ask-forum-body">
<p>
A kérdésed mellé csatoljuk {what.shown}. A fórum belépett tagjai látják, a látogatók és a keresők nem.
</p>
<p className="hint">
Neved, születési dátumod, időd és helyed nem kerül ki.
{what.extra && ` ${what.extra}`} A fokokból egy jártas asztrológus nagyjából kiszámolhatja a születési
napot és időt. A csatolt képletet bármikor leveheted a kérdésedről, és ha törlöd a kérdést, a link is
megszűnik.
</p>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="ask-forum-actions">
<button type="button" className="btn btn-ghost" onClick={() => setOpen(false)}>
Mégse
</button>
<button type="button" className="btn btn-primary" disabled={busy} onClick={go}>
{busy ? "Egy pillanat…" : "Tovább a kérdéshez"}
</button>
</div>
</div>
</Modal>
)}
</>
);
}
@@ -0,0 +1,79 @@
import Link from "next/link";
import { POINTS, SIGNS, signName } from "@/lib/astro";
import type { ShareCardData } from "@/lib/forum";
const EYEBROW: Record<ShareCardData["kind"], string> = {
chart: "Csatolt képlet",
synastry: "Csatolt összevetés",
forecast: "Csatolt előrejelzés",
};
const POINT_LABEL: Record<string, string> = { sun: "Nap", moon: "Hold", ascendant: "Aszcendens" };
/**
* The chart, forecast or synastry a question came with: the big three with
* degrees and houses, the summary's title, and the shared page. Members only;
* a visitor sees that there is one.
*/
export function ShareCard({ share, onRemove }: { share: ShareCardData; onRemove?: () => void }) {
if (share.locked) {
return (
<div className="fshare fshare-quiet">
<span className="eyebrow">{EYEBROW[share.kind]}</span>
<span className="hint">
A kérdéshez csatolt képlet <Link href="/belepes">belépés</Link> után látható.
</span>
</div>
);
}
if (share.revoked) {
return (
<div className="fshare fshare-quiet">
<span className="eyebrow">{EYEBROW[share.kind]}</span>
<span className="hint">A szerző levette a csatolt képletet.</span>
</div>
);
}
const points = share.points ?? [];
return (
<div className="fshare">
<div className="fshare-head">
<span className="eyebrow">{EYEBROW[share.kind]}</span>
{onRemove && (
<button type="button" className="fp-link" onClick={onRemove} aria-label="Képlet levétele">
×
</button>
)}
</div>
<strong className="fshare-title">{share.title}</strong>
{share.summary && <span className="fshare-summary">„{share.summary}”</span>}
{points.length > 0 && (
<ul className="fshare-points">
{points.map((p) => (
<li key={p.id}>
<span className="sym" aria-hidden="true">
{POINTS[p.id]?.glyph ?? ""}
</span>{" "}
{POINT_LABEL[p.id] ?? p.id}{" "}
<span className="sym" aria-hidden="true">
{SIGNS[p.sign]?.glyph ?? ""}
</span>{" "}
{signName(p.sign)}
{p.degree !== null && ` ${p.degree}°`}
{p.house !== null && <span className="hint"> · {p.house}. ház</span>}
</li>
))}
</ul>
)}
{share.kind !== "synastry" && share.time_known === false && (
<span className="hint">A születési idő ismeretlen, ezért házak és Aszcendens nincsenek.</span>
)}
{share.slug && (
<Link href={`/s/${share.slug}`} className="btn btn-sm fshare-open" target="_blank" rel="noopener">
Megnyitom ›
</Link>
)}
</div>
);
}
@@ -13,6 +13,7 @@ import { PostBody } from "./PostBody";
import type { LiveNotice } from "./ForumNav";
import { ReactionIcon } from "./ReactionIcon";
import { ReportForm } from "./ReportButton";
import { ShareCard } from "./ShareCard";
import { TypingLine, useTypingSender, useTypingWatch } from "./typing";
import { Badge, RankBadge } from "./Badges";
@@ -27,6 +28,8 @@ type Actions = {
remove: (post: ForumPost) => void;
restore: (post: ForumPost) => void;
helped: (post: ForumPost) => void;
/** The author takes the shared chart off their question. */
detachShare: (post: ForumPost) => void;
/** Mute or unmute the post's author. */
mute: (post: ForumPost) => void;
};
@@ -228,6 +231,8 @@ function PostCard({
menuItems.push({ label: post.helped ? "Mégsem segített" : "Ez segített", run: () => actions.helped(post) });
}
if (post.own && writer && !thread.locked) menuItems.push({ label: "Szerkesztés", run: () => setEditing(true) });
if (post.own && post.share && !post.share.revoked)
menuItems.push({ label: "Képlet levétele", run: () => actions.detachShare(post) });
if (post.own) menuItems.push({ label: "Törlés", run: () => actions.remove(post), danger: true });
if (viewer.logged_in && !post.own) menuItems.push({ label: "Jelentés", run: () => setReporting(true) });
if (viewer.member && !post.own && author && !post.system)
@@ -328,7 +333,12 @@ function PostCard({
}}
/>
) : (
post.body !== null && <PostBody text={post.body} mentions={post.mentions} />
post.body !== null && (
<>
<PostBody text={post.body} mentions={post.mentions} />
{post.share && <ShareCard share={post.share} />}
</>
)
)}
</div>
{!editing && (!post.deleted || menuItems.length > 0) && (
@@ -534,6 +544,13 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
await api(`/forum/posts/${post.id}/restore`, { method: "POST" });
await reload();
}),
detachShare: (post) => {
if (!window.confirm("Leveszed a csatolt képletet? A kártya eltűnik, és a link sem működik többé.")) return;
void run(async () => {
await api(`/forum/posts/${post.id}/share`, { method: "DELETE" });
await reload();
});
},
mute: (post) => {
const nickname = post.author?.nickname;
if (!nickname) return;
+14
View File
@@ -117,6 +117,20 @@ export interface ForumPost {
reply_to?: { id: number; nickname: string | null } | null;
/** The viewer muted the author: shown folded up. */
muted?: boolean;
/** A chart, forecast or synastry shared with the question. */
share?: ShareCardData | null;
}
/** A shared chart in a post: in full for members, `locked` for visitors, `revoked` when taken down. */
export interface ShareCardData {
slug?: string;
kind: "chart" | "synastry" | "forecast";
locked?: boolean;
revoked?: boolean;
title?: string;
summary?: string | null;
points?: { id: string; sign: string; degree: number | null; house: number | null }[];
time_known?: boolean;
}
export interface ThreadPage {
+9 -4
View File
@@ -6,7 +6,7 @@ import { headers } from "next/headers";
import { cache } from "react";
import { BACKEND_URL } from "./server";
import type { ChartResult } from "./types";
import type { AnalysisContent, ChartResult, Forecast, SolarReturn, SynastryResult } from "./types";
export interface PublicSummary {
id: string;
@@ -16,13 +16,18 @@ export interface PublicSummary {
completed_at: string | null;
}
/** `GET /v1/public/shares/{slug}` of a shared chart. */
type SharedChart = { label: string | null; chart: ChartResult & { time_known: boolean } };
/** `GET /v1/public/shares/{slug}`: a chart, a comparison or a yearly forecast. */
export interface PublicShare {
kind: "chart" | "synastry" | "analysis";
kind: "chart" | "synastry" | "analysis" | "forecast";
title: string | null;
created_at: string;
chart?: { label: string; chart: ChartResult & { time_known: boolean } };
chart?: SharedChart;
summary?: PublicSummary | null;
synastry?: { chart1: SharedChart; chart2: SharedChart; synastry: SynastryResult };
forecast?: { year: number; forecast: Forecast; solar_return: SolarReturn | null };
analysis?: { kind: string; language: string; content: AnalysisContent | null; completed_at: string | null } | null;
}
const SLUG = /^[A-Za-z0-9_-]{8,64}$/;