From 863002c1e715f9bdf070d5208b8dcb3c2da493bf Mon Sep 17 00:00:00 2001 From: feco Date: Thu, 26 Nov 2026 14:52:00 +0000 Subject: [PATCH] Forum: asking about one's own chart, forecast or comparison MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - "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 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- docs/kozosseg.md | 22 ++- services/backend/src/routes/shares.rs | 93 ++++++++++-- services/backend/src/tests.rs | 28 ++++ services/forum/src/routes/attachments.rs | 132 ++++++++++++++++++ services/forum/src/routes/mod.rs | 3 + services/forum/src/routes/posts.rs | 35 +++++ services/forum/src/routes/threads.rs | 18 ++- services/forum/src/tests.rs | 105 ++++++++++++++ .../frontend/src/app/adatvedelem/page.tsx | 17 ++- .../src/app/api/v1/[...path]/route.ts | 4 +- services/frontend/src/app/forum/forum.css | 14 ++ .../src/app/forum/uj/NewThreadForm.tsx | 25 +++- services/frontend/src/app/forum/uj/page.tsx | 21 ++- services/frontend/src/app/globals.css | 7 + .../app/kepletek/[id]/elorejelzes/page.tsx | 8 ++ .../frontend/src/app/kepletek/[id]/page.tsx | 8 ++ .../src/app/osszevetesek/[id]/page.tsx | 8 ++ services/frontend/src/app/privacy/page.tsx | 13 +- services/frontend/src/app/s/[slug]/page.tsx | 126 ++++++++++++++++- .../frontend/src/components/AskOnForum.tsx | 91 ++++++++++++ .../src/components/forum/ShareCard.tsx | 79 +++++++++++ .../src/components/forum/ThreadView.tsx | 19 ++- services/frontend/src/lib/forum.ts | 14 ++ services/frontend/src/lib/share.ts | 13 +- 24 files changed, 871 insertions(+), 32 deletions(-) create mode 100644 services/forum/src/routes/attachments.rs create mode 100644 services/frontend/src/components/AskOnForum.tsx create mode 100644 services/frontend/src/components/forum/ShareCard.tsx diff --git a/docs/kozosseg.md b/docs/kozosseg.md index 5eebe7b..aa77a14 100644 --- a/docs/kozosseg.md +++ b/docs/kozosseg.md @@ -165,12 +165,32 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több - **Heti összefoglaló e-mail:** vasárnap este, a hét legélénkebb szálaival és a válaszra várókkal. Alapból ki van kapcsolva, az e-mail-értesítések között kapcsolható be. - **Jogi szövegek:** az adatkezelési tájékoztató (magyar és angol) és az ÁSZF 8.1 pontja kiegészült (saját kép, jelvények, említések, zárt témák, heti összefoglaló). Az adatexport ezeket is tartalmazza. +### Ami elkészült (7. kör) + +- **Egyetlen jelzés a menüben:** a „Válaszok” fül száma azt mutatja, hány olvasatlan válasz érkezett neked: valaki a hozzászólásodra vagy a száladban válaszolt, vagy megemlített. A lista a `/forum/valaszok` oldalon van, „Mind olvasott” gombbal; a követett szálak ennek második nézete. A kísérők a főoldali saját kártyájukon látják, hány szál vár első válaszra. +- **Válasz a 2. szinten:** a szövegdoboz az ág aljára kerül; másik ágra kattintva átkerül oda, a félig megírt szöveg megmarad. +- **Mobil billentyűzet:** gépelés közben eltűnik a fórum alsó menüje, és a szövegdoboz a küldés gombbal együtt a billentyűzet fölé görgetődik (`KeyboardSafe`, az egész oldalon). +- **„Kísérő”** lett a „Meghallgató” jelvény neve. + +### Ami elkészült (8. kör) + +- **Oldaltérkép:** a nyilvános témák és szálak bekerültek a `sitemap.xml`-be; a fórum saját oldalait (beállítások, üzenetek, válaszok, keresés stb.) a `robots.txt` kizárja. +- **Keresés** (`/forum/kereses`, nagyító a fórum fejlécében): szálcímek és hozzászólások abból, amit a látogató olvashat. Magyar szótövezés, és ékezet nélkül, szókezdetre is talál („alvas” → „alvásban”). Szálanként egy találat, kiemelt szavakkal. Az elnémított tagokat kihagyja. +- **Némítás** (hozzászólás ⋯ menüje, profil; a lista a beállításokban): az elnémított tag szálai eltűnnek a listákból, a hozzászólásai összecsukva látszanak, a válaszai és említései nem számítanak és nem küldenek e-mailt. Ő erről nem tud. +- **Archiválás** (admin, Moderálás → Témák): a téma olvasható marad, de új szál és válasz nem írható bele; a főoldalon összecsukva, „Archivált témák” alatt látszik. +- **Kérdés a saját képletről:** a képlet, az éves előrejelzés és az összevetés oldalán „Kérdezek róla a fórumon” gomb. Egy ablak elmondja, mi kerül ki, aztán az oldal fórumos megosztó linket készít (`shares.for_forum`: soha nincs benne születési adat, név vagy cím), és új szálat nyit az „Égbolt és képletek” témában, a linkkel csatolva. + - A hozzászólásban kártya: Nap, Hold, Aszcendens jeggyel, fokkal és házzal, a rövid összefoglaló címe, és „Megnyitom” a megosztó oldalra. Csak belépett tagok látják; a látogatók és a keresők csak annyit, hogy van csatolt képlet. + - A szerző leveheti („Képlet levétele”); ha törli a kérdést, a link is megszűnik. + - A megosztó oldal (`/s/…`) mostantól az összevetést (közös kerék, fényszögek, nevek nélkül) és az éves előrejelzést (kulcsok, idővonal, tranzitok, a részletes szöveg, a születésnapi helyszín nélkül) is megmutatja. +- **A válasz-e-mail** a második szinten annak megy, akinek valóban válaszoltak. +- **Adatvédelem:** a tájékoztató (magyar és angol) kiegészült a csatolt képlettel és a némítással. + ### Élesítéskor - `FORUM_URL=http://forum:8083` az éles `.env`-be. - Az adatvédelmi tájékoztató dátumát (`PRIVACY_UPDATED` és `PRIVACY_UPDATED_EN` a `legal.ts`-ben) szintén az élesítés napjára kell írni. - Az ÁSZF hatálybalépési dátumát (`TERMS_UPDATED` a `services/frontend/src/lib/legal.ts`-ben és `TERMS_VERSION` a `services/backend/src/routes/payments.rs`-ben) az élesítés napjára kell átírni, ha az nem 2026. november 26. -- Ha közben a `main`-re új migráció került, a fórumé (0038–0042) ütközhet vele, és át kell számozni. +- Ha közben a `main`-re új migráció került, a fórumé (0038–0043) ütközhet vele, és át kell számozni. A 0043 az `unaccent` bővítményt is létrehozza (megbízható bővítmény, az adatbázis tulajdonosa létrehozhatja). - A fórum szolgáltatásnak kell az `S3_ENDPOINT`, `S3_BUCKET`, `S3_REGION` (az éles `.env`-ben, ugyanaz, mint a backendé) és a kulcsok (`.env.secrets`); a workernek a `BACKEND_URL` (a compose fájlban már benne van). ### Ami még hátravan diff --git a/services/backend/src/routes/shares.rs b/services/backend/src/routes/shares.rs index 8e00436..675d3bf 100644 --- a/services/backend/src/routes/shares.rs +++ b/services/backend/src/routes/shares.rs @@ -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, synastry_id: Option, analysis_id: Option, + forecast_id: Option, title: Option, show_birth_data: bool, + for_forum: bool, view_count: i64, created_at: OffsetDateTime, revoked_at: Option, owner_ip_hash: Option>, } -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, ) -> ApiResult<(StatusCode, Json)> { - 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::()).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 = 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 { 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, Option)> = 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) } diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index fec85a4..58b3cae 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -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; diff --git a/services/forum/src/routes/attachments.rs b/services/forum/src/routes/attachments.rs new file mode 100644 index 0000000..5fee90c --- /dev/null +++ b/services/forum/src/routes/attachments.rs @@ -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, + year: Option, + summary_title: Option, +} + +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, bool) { + let time_known = natal.pointer("/time/time_known").and_then(Value::as_bool).unwrap_or(false); + let mut points: Vec = ["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, sqlx::Error> { + if ids.is_empty() { + return Ok(HashMap::new()); + } + let rows: Vec = + 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 { + 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, ApiError>, +) -> ApiResult> { + 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))) +} diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs index d1ebcc4..5cec032 100644 --- a/services/forum/src/routes/mod.rs +++ b/services/forum/src/routes/mod.rs @@ -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) -> 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)) diff --git a/services/forum/src/routes/posts.rs b/services/forum/src/routes/posts.rs index 89b4c0e..6ad4c17 100644 --- a/services/forum/src/routes/posts.rs +++ b/services/forum/src/routes/posts.rs @@ -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 { + 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) +} diff --git a/services/forum/src/routes/threads.rs b/services/forum/src/routes/threads.rs index 3b59831..d893283 100644 --- a/services/forum/src/routes/threads.rs +++ b/services/forum/src/routes/threads.rs @@ -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, + /// A chart, forecast or synastry shared with the question. + pub share_id: Option, } 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> { let ids: Vec = posts.iter().map(|p| p.id).collect(); let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?; + let shares: Vec = 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, + /// A share made for the forum on the main site (`/s/`). + #[serde(default)] + share: Option, } /// 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?; diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs index 4253079..9d315b6 100644 --- a/services/forum/src/tests.rs +++ b/services/forum/src/tests.rs @@ -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); +} diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index d85894f..b223d3c 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -161,11 +161,19 @@ export default async function PrivacyPage() { 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 A fórum működése, a rangok, az újdonságok jelzése Szerződés teljesítése + + + A fórumkérdéseidhez csatolt képlet, éves előrejelzés vagy összevetés megosztó linkje + + Hogy a tagok lássák, amiről kérdezel; a csatolás a saját döntésed + Szerződés teljesítése + Zárt témákba küldött jelentkezéseid (a pár szavas indoklással) és a tagságaid A zárt témák: a moderátorok döntenek a felvételről @@ -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 ÁSZF 8. pontjában 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{" "} + ÁSZF 8. pontjában vannak.

diff --git a/services/frontend/src/app/api/v1/[...path]/route.ts b/services/frontend/src/app/api/v1/[...path]/route.ts index 7c9b8ac..aedf18a 100644 --- a/services/frontend/src/app/api/v1/[...path]/route.ts +++ b/services/frontend/src/app/api/v1/[...path]/route.ts @@ -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 }); diff --git a/services/frontend/src/app/forum/forum.css b/services/frontend/src/app/forum/forum.css index 3467027..ced2533 100644 --- a/services/frontend/src/app/forum/forum.css +++ b/services/frontend/src/app/forum/forum.css @@ -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; } diff --git a/services/frontend/src/app/forum/uj/NewThreadForm.tsx b/services/frontend/src/app/forum/uj/NewThreadForm.tsx index 0582740..b8f7206 100644 --- a/services/frontend/src/app/forum/uj/NewThreadForm.tsx +++ b/services/frontend/src/app/forum/uj/NewThreadForm.tsx @@ -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(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 (
+ {share && ( +
+ setShare(null)} /> + + 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. + +
+ )}
Téma
diff --git a/services/frontend/src/app/forum/uj/page.tsx b/services/frontend/src/app/forum/uj/page.tsx index b059207..c53a3c9 100644 --- a/services/frontend/src/app/forum/uj/page.tsx +++ b/services/frontend/src/app/forum/uj/page.tsx @@ -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(`/v1/forum/share-card/${encodeURIComponent(kepletkartya)}`).catch(() => null) + : null; return (

Új szál

{viewer.member?.banned ? (

Most nem írhatsz a fórumba.

) : ( - + )}
); diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 27fee0e..174a650 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -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; } diff --git a/services/frontend/src/app/kepletek/[id]/elorejelzes/page.tsx b/services/frontend/src/app/kepletek/[id]/elorejelzes/page.tsx index d389fc4..c080549 100644 --- a/services/frontend/src/app/kepletek/[id]/elorejelzes/page.tsx +++ b/services/frontend/src/app/kepletek/[id]/elorejelzes/page.tsx @@ -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({ )}
+ {forumEnabled() && ( +
+

Kérdésed van az évedről? Kérdezd meg a fórum tagjait.

+ +
+ )} {(list.years.length > 0 || others.length > 0) && (
Másik év vagy helyszín diff --git a/services/frontend/src/app/kepletek/[id]/page.tsx b/services/frontend/src/app/kepletek/[id]/page.tsx index 594c068..09cef86 100644 --- a/services/frontend/src/app/kepletek/[id]/page.tsx +++ b/services/frontend/src/app/kepletek/[id]/page.tsx @@ -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} /> + {forumEnabled() && ( +
+

Kérdésed van a képletről? Kérdezd meg a fórum tagjait.

+ +
+ )}
diff --git a/services/frontend/src/app/osszevetesek/[id]/page.tsx b/services/frontend/src/app/osszevetesek/[id]/page.tsx index db69cea..4822e6b 100644 --- a/services/frontend/src/app/osszevetesek/[id]/page.tsx +++ b/services/frontend/src/app/osszevetesek/[id]/page.tsx @@ -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:

)}
+ {forumEnabled() && ( +
+

Kérdésed van kettőtök képletéről? Kérdezd meg a fórum tagjait.

+ +
+ )} diff --git a/services/frontend/src/app/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index ebfba74..0b84271 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -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 terms (ÁSZF, in Hungarian).

diff --git a/services/frontend/src/app/s/[slug]/page.tsx b/services/frontend/src/app/s/[slug]/page.tsx index 3f6e626..1edb871 100644 --- a/services/frontend/src/app/s/[slug]/page.tsx +++ b/services/frontend/src/app/s/[slug]/page.tsx @@ -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 { 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 { 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 ; + } + if (share?.kind === "forecast" && share.forecast) { + return ; + } 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 ( + <> + + {!loggedIn && } +
+
+ Megosztott összevetés +

Két képlet egymásra vetítve

+
+
+
+ + +
+
+
+ Számokban +

{s.synastry.summary.aspect_count} fényszög a két képlet között

+ +
+
+
+
+

Fényszögek

+ +
+

Ezt az összevetést a tulajdonosa osztotta meg, nevek és születési adatok nélkül.

+
+ + ); +} + +/** 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 ( + <> + + {!loggedIn && } +
+
+ Megosztott éves előrejelzés +

+ {f.year}–{f.year + 1} +

+

+ {longDay(fc.start)} – {longDay(fc.end)} +

+
+
+ {sr ? ( +
+ +

Szolár képlet: a Nap ekkor ér vissza pontosan a születéskori helyére.

+
+ ) : ( +
+

Szolár képlet nincs, mert a születési idő ismeretlen.

+
+ )} +
+ +
+
+ {text && ( +
+ +
+ )} +
+

Idővonal

+ +
+
+

Tranzitok

+ +
+

+ 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."} +

+
+ + ); +} diff --git a/services/frontend/src/components/AskOnForum.tsx b/services/frontend/src/components/AskOnForum.tsx new file mode 100644 index 0000000..aa80fc4 --- /dev/null +++ b/services/frontend/src/components/AskOnForum.tsx @@ -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 = { + 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(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 ( + <> + + {open && ( + setOpen(false)}> +
+

+ 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. +

+

+ 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. +

+ {error && ( +

+ {error} +

+ )} +
+ + +
+
+
+ )} + + ); +} diff --git a/services/frontend/src/components/forum/ShareCard.tsx b/services/frontend/src/components/forum/ShareCard.tsx new file mode 100644 index 0000000..c7c8adf --- /dev/null +++ b/services/frontend/src/components/forum/ShareCard.tsx @@ -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 = { + chart: "Csatolt képlet", + synastry: "Csatolt összevetés", + forecast: "Csatolt előrejelzés", +}; + +const POINT_LABEL: Record = { 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 ( +
+ {EYEBROW[share.kind]} + + A kérdéshez csatolt képlet belépés után látható. + +
+ ); + } + if (share.revoked) { + return ( +
+ {EYEBROW[share.kind]} + A szerző levette a csatolt képletet. +
+ ); + } + const points = share.points ?? []; + return ( +
+
+ {EYEBROW[share.kind]} + {onRemove && ( + + )} +
+ {share.title} + {share.summary && „{share.summary}”} + {points.length > 0 && ( +
    + {points.map((p) => ( +
  • + {" "} + {POINT_LABEL[p.id] ?? p.id}{" "} + {" "} + {signName(p.sign)} + {p.degree !== null && ` ${p.degree}°`} + {p.house !== null && · {p.house}. ház} +
  • + ))} +
+ )} + {share.kind !== "synastry" && share.time_known === false && ( + A születési idő ismeretlen, ezért házak és Aszcendens nincsenek. + )} + {share.slug && ( + + Megnyitom › + + )} +
+ ); +} diff --git a/services/frontend/src/components/forum/ThreadView.tsx b/services/frontend/src/components/forum/ThreadView.tsx index d833103..94e0ba4 100644 --- a/services/frontend/src/components/forum/ThreadView.tsx +++ b/services/frontend/src/components/forum/ThreadView.tsx @@ -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 && + post.body !== null && ( + <> + + {post.share && } + + ) )} {!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; diff --git a/services/frontend/src/lib/forum.ts b/services/frontend/src/lib/forum.ts index fed14e4..4d97a23 100644 --- a/services/frontend/src/lib/forum.ts +++ b/services/frontend/src/lib/forum.ts @@ -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 { diff --git a/services/frontend/src/lib/share.ts b/services/frontend/src/lib/share.ts index 325411f..3706350 100644 --- a/services/frontend/src/lib/share.ts +++ b/services/frontend/src/lib/share.ts @@ -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}$/;