diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index c11d870..63268d5 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -406,7 +406,7 @@ fn forum_listener(payload: &Value, url: String) -> Result ApiResult> { let people = super::authors(&state.db, present.iter().copied()).await?; let online: Vec = present.iter().filter_map(|id| people.get(id).cloned()).collect(); + // Volunteer listeners: threads asking to be heard, still without a reply. + let waiting = match &viewer.member { + Some(m) if m.listener => Some(waiting_count(&state, &viewer).await?), + _ => None, + }; + let replies = match &viewer.member { + Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?), + None => None, + }; Ok(Json(json!({ "viewer": viewer_json(&viewer), "followed": followed, + "replies": replies, + "waiting": waiting, "online": online, "topics": topics, "unanswered": cards_json(&state.db, unanswered).await?, @@ -234,17 +245,16 @@ pub async fn nav(state: St, viewer: Viewer) -> ApiResult> { } else { None }; - // Volunteer listeners: threads asking to be heard, still without a reply. - let waiting = match &viewer.member { - Some(m) if m.listener => Some(waiting_count(&state, &viewer).await?), - _ => None, + // The only count on the forum tab: unread answers to the member. + let replies = match &viewer.member { + Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?), + None => None, }; Ok(Json(json!({ "viewer": viewer_json(&viewer), - "followed": followed_counts(&state, &viewer).await?, + "replies": replies, "messages": messages, "reports": reports, - "waiting": waiting, }))) } diff --git a/services/forum/src/routes/members.rs b/services/forum/src/routes/members.rs index 0933c6e..1654892 100644 --- a/services/forum/src/routes/members.rs +++ b/services/forum/src/routes/members.rs @@ -164,7 +164,7 @@ pub async fn save_me( if req.listener == Some(true) { let newcomer = viewer.member.as_ref().is_none_or(|m| m.rank(OffsetDateTime::now_utc()).is_newcomer()); if newcomer && !viewer.is_moderator() { - return Err(ApiError::Forbidden("Meghallgatónak a Kereső rangtól jelentkezhetsz.".into())); + return Err(ApiError::Forbidden("Kísérőnek a Kereső rangtól jelentkezhetsz.".into())); } } if req.supporter_badge == Some(true) && !super::has_purchase(&state.db, user.id).await? { diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs index bf190e6..626011d 100644 --- a/services/forum/src/routes/mod.rs +++ b/services/forum/src/routes/mod.rs @@ -12,6 +12,7 @@ mod mentions; mod messages; mod moderation; mod posts; +mod replies; mod reports; mod threads; mod topics; @@ -48,6 +49,8 @@ pub fn router(state: Arc) -> Router { .route("/v1/forum/topics/{slug}/join", post(topics::join).delete(topics::leave)) .route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide)) .route("/v1/forum/followed", get(home::followed)) + .route("/v1/forum/replies", get(replies::list)) + .route("/v1/forum/replies/read", post(replies::read_all)) .route("/v1/forum/threads", post(threads::create)) .route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove)) .route("/v1/forum/threads/{id}/restore", post(threads::restore)) diff --git a/services/forum/src/routes/replies.rs b/services/forum/src/routes/replies.rs new file mode 100644 index 0000000..97466b7 --- /dev/null +++ b/services/forum/src/routes/replies.rs @@ -0,0 +1,134 @@ +//! "Válaszok": what answers the member. A reply to one of their posts (also +//! a reply to a reply of theirs, `reply_to_id`), a first-level reply in a +//! thread they opened, or a post that names them ("@Holdfény"). One stays +//! unread until the member has read that far in the thread; the forum menu +//! shows only this count. + +use axum::Json; +use axum::extract::{Query, State}; +use axum::http::StatusCode; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::PgPool; +use time::OffsetDateTime; +use uuid::Uuid; + +use super::{St, rfc3339, visible_topics}; +use crate::auth::Viewer; +use crate::error::{ApiError, ApiResult}; + +/// The posts that answer `$1`, from the threads the viewer may read. +fn answers(viewer: &Viewer) -> String { + format!( + "FROM forum.posts p \ + JOIN forum.threads th ON th.id = p.thread_id \ + JOIN forum.topics tp ON tp.id = th.topic_id \ + LEFT JOIN forum.posts target ON target.id = COALESCE(p.reply_to_id, p.parent_id) \ + LEFT JOIN forum.reads r ON r.user_id = $1 AND r.thread_id = p.thread_id \ + WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND NOT p.is_opening AND NOT p.system \ + AND p.author_id IS DISTINCT FROM $1 AND ({}) \ + AND (target.author_id = $1 \ + OR (p.parent_id IS NULL AND th.author_id = $1) \ + OR EXISTS (SELECT 1 FROM forum.mentions mn WHERE mn.post_id = p.id AND mn.user_id = $1))", + visible_topics(viewer) + ) +} + +const UNREAD: &str = "p.id > COALESCE(r.last_post_id, 0)"; + +/// How many answers wait unread (for the menu), at most 100. +pub async fn unread_count(db: &PgPool, viewer: &Viewer, me: Uuid) -> Result { + sqlx::query_scalar(&format!("SELECT count(*) FROM (SELECT 1 {} AND {UNREAD} LIMIT 100) x", answers(viewer))) + .bind(me) + .fetch_one(db) + .await +} + +#[derive(Deserialize)] +pub struct ListQuery { + #[serde(default)] + page: Option, +} + +#[derive(sqlx::FromRow)] +struct Row { + id: i64, + thread_id: i64, + title: String, + author_id: Option, + body: String, + created_at: OffsetDateTime, + kind: String, + unread: bool, +} + +const PAGE: i64 = 30; + +/// The member's answers, newest first. +pub async fn list( + State(state): St, + viewer: Viewer, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let member = viewer.require_member()?; + let page = q.page.unwrap_or(1).clamp(1, 1000); + let rows: Vec = sqlx::query_as(&format!( + "SELECT p.id, p.thread_id, th.title, p.author_id, p.body, p.created_at, \ + CASE WHEN target.author_id = $1 THEN 'reply' \ + WHEN p.parent_id IS NULL AND th.author_id = $1 THEN 'thread' \ + ELSE 'mention' END AS kind, \ + {UNREAD} AS unread \ + {} ORDER BY p.id DESC LIMIT {} OFFSET $2", + answers(&viewer), + PAGE + 1 + )) + .bind(member.user_id) + .bind((page - 1) * PAGE) + .fetch_all(&state.db) + .await?; + let more = rows.len() as i64 > PAGE; + let rows = &rows[..rows.len().min(PAGE as usize)]; + let authors = super::authors(&state.db, rows.iter().filter_map(|r| r.author_id)).await?; + let replies: Vec = rows + .iter() + .map(|r| { + json!({ + "id": r.id, + "thread": { "id": r.thread_id, "title": r.title, "slug": crate::text::slug(&r.title) }, + "author": r.author_id.and_then(|a| authors.get(&a).cloned()), + "excerpt": excerpt(&r.body), + "created_at": rfc3339(r.created_at), + "kind": r.kind, + "unread": r.unread, + }) + }) + .collect(); + let unread = unread_count(&state.db, &viewer, member.user_id).await?; + Ok(Json(json!({ "replies": replies, "unread": unread, "page": page, "more": more }))) +} + +/// "Mind olvasott": the threads with unread answers count as read up to them. +pub async fn read_all(State(state): St, viewer: Viewer) -> ApiResult { + let member = viewer.require_member()?; + sqlx::query(&format!( + "INSERT INTO forum.reads (user_id, thread_id, last_post_id) \ + SELECT $1, p.thread_id, max(p.id) {} AND {UNREAD} GROUP BY p.thread_id \ + ON CONFLICT (user_id, thread_id) DO UPDATE \ + SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()", + answers(&viewer) + )) + .bind(member.user_id) + .execute(&state.db) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +/// The start of a post, on one line. +fn excerpt(body: &str) -> String { + let line = body.split_whitespace().collect::>().join(" "); + match line.char_indices().nth(160) { + Some((at, _)) => format!("{}…", line[..at].trim_end()), + None => line, + } +} diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs index 8bdb183..eebfe76 100644 --- a/services/forum/src/tests.rs +++ b/services/forum/src/tests.rs @@ -1044,8 +1044,8 @@ async fn mentions_listeners_supporters_and_who_is_here(pool: PgPool) { .execute(&app.pool) .await .unwrap(); - assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["waiting"], 1); - assert!(app.get("/v1/forum/nav", Some(&cili)).await["waiting"].is_null()); + assert_eq!(app.get("/v1/forum/home", Some(&bea)).await["waiting"], 1); + assert!(app.get("/v1/forum/home", Some(&cili)).await["waiting"].is_null()); let shown = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await; assert!(shown["posts"].as_array().unwrap().iter().all(|p| p["author"]["supporter"] == false)); @@ -1080,3 +1080,53 @@ async fn mentions_listeners_supporters_and_who_is_here(pool: PgPool) { .collect(); assert!(here.contains(&"Zöldág".to_string()) && !here.contains(&"Csendesvíz".to_string())); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn answers_to_the_member(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; + let cili = app.member("cili@example.com", "Zöldág", &["user"]).await; + let answers = |v: Value| -> Vec<(i64, String, bool)> { + v["replies"] + .as_array() + .unwrap() + .iter() + .map(|r| (r["id"].as_i64().unwrap(), r["kind"].as_str().unwrap().to_string(), r["unread"] == true)) + .collect() + }; + + // Anna's thread: Bea replies to it, Anna answers, Cili answers Anna's answer + // (on the second level, under Bea's post) and names Bea elsewhere. + let thread = app.thread(&anna, "torzsasztal", "Téli levesek").await; + let first = app.reply(&bea, thread, "Gulyás.", None).await["id"].as_i64().unwrap(); + let second = app.reply(&anna, thread, "Az jó ötlet.", Some(first)).await["id"].as_i64().unwrap(); + let third = app.reply(&cili, thread, "Szerintem is.", Some(second)).await["id"].as_i64().unwrap(); + let fourth = app.reply(&cili, thread, "@Holdfény, babbal?", None).await["id"].as_i64().unwrap(); + + // Anna: Bea's reply in her thread (read once she answered it), Cili's answer + // to her, and Cili's first-level post in her thread. + assert_eq!( + answers(app.get("/v1/forum/replies", Some(&anna)).await), + vec![(fourth, "thread".into(), true), (third, "reply".into(), true), (first, "thread".into(), false)] + ); + assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 2); + // Bea: Anna answered her; Cili named her. Cili's answer was to Anna, not to her. + assert_eq!( + answers(app.get("/v1/forum/replies", Some(&bea)).await), + vec![(fourth, "mention".into(), true), (second, "reply".into(), true)] + ); + // Nothing for Cili; a visitor gets nothing. + assert_eq!(app.get("/v1/forum/nav", Some(&cili)).await["replies"], 0); + assert!(app.get("/v1/forum/nav", None).await["replies"].is_null()); + + // Reading the thread clears them; so does "Mind olvasott". + let (status, _) = + app.call("POST", &format!("/v1/forum/threads/{thread}/read"), Some(&anna), json!({ "post_id": fourth })).await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 0); + let (status, _) = app.call("POST", "/v1/forum/replies/read", Some(&bea), Value::Null).await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["replies"], 0); + assert_eq!(answers(app.get("/v1/forum/replies", Some(&bea)).await).len(), 2, "the list stays"); +} diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index f53acc0..d85894f 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -151,7 +151,7 @@ export default async function PrivacyPage() { Fórumprofilod: az álneved (a korábbiakat 90 napig, hogy más ne vehesse fel), az avatarod vagy a feltöltött saját képed (kicsinyítve, a kép rejtett adatai, például a helyszín nélkül), a - bemutatkozásod, a képletedből megosztott jegyek, hogy önkéntes meghallgató vagy-e, a Támogató + bemutatkozásod, a képletedből megosztott jegyek, hogy önkéntes kísérő vagy-e, a Támogató jelvény (ha bekapcsolod, mások látják, hogy vásároltál), a láthatatlan mód és az e-mail-értesítések beállítása @@ -221,7 +221,7 @@ export default async function PrivacyPage() { Fórum: amit a nyilvános témákban írsz, bárki láthatja, a keresők is; a csak tagoknak szóló témákat csak belépett felhasználók látják, a zárt témákat csak a jóváhagyott tagjaik. A hozzászólásaid mellett az álneved, az avatarod, a rangod, az általad megosztott jegyek és a bekapcsolt jelvényeid - (Meghallgató, Támogató) látszanak; a valódi neved, az e-mail-címed és a születési adataid nem, és a + (Kísérő, Támogató) látszanak; a valódi neved, az e-mail-címed és a születési adataid nem, és a 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 diff --git a/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx index 7d190c7..60ed1e2 100644 --- a/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx +++ b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx @@ -248,10 +248,10 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null }) @@ -315,7 +315,9 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null }) {listener && ( <> - +