//! Feedback, kept in the system (no e-mail, no Telegram), never shown //! publicly: //! //! * ratings of what a user got (summary, analyses, forecast, tarot: 1–5 //! stars; answers to questions: thumbs), with tags and a comment; only the //! one who got it rates it, once (changeable). The rated text is readable //! for admins only if the user allows it (`may_read`); //! * messages from the "Visszajelzés" page (bug, idea, question), with a //! state and the operator's reply, both shown to the user there; //! * one "would you recommend us?" question (0–10, NPS), asked once in the //! app after a couple of finished contents (not of the team). //! //! Admins see it all on Admin → Visszajelzések; the admin menu counts what is //! new. use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::{HeaderMap, StatusCode, header}; use axum_extra::extract::WithRejection; use serde::Deserialize; use serde_json::{Value, json}; use sqlx::PgConnection; use time::OffsetDateTime; use uuid::Uuid; use super::analyses::{can_see, find_analysis}; use super::{Body, IdPath, St}; use crate::auth::{AdminUser, AuthUser}; use crate::error::{ApiError, ApiResult}; use crate::views::{rfc3339, rfc3339_opt}; /// Tags of a low and of a high rating (the frontend shows them in Hungarian). pub const TAGS: [&str; 10] = [ "too_general", "contradictory", "wrong_data", "hard_to_read", "too_long", "tone", "accurate", "deep", "clear", "useful", ]; /// What can be rated (analysis kinds, and answers to questions). const RATED_KINDS: [&str; 5] = ["summary", "natal", "synastry", "forecast", "tarot"]; const MAX_COMMENT: usize = 1000; const MAX_MESSAGE: usize = 2000; const MAX_REPLY: usize = 4000; /// Messages a user may send in 24 hours. const MESSAGES_PER_DAY: i64 = 10; /// The recommendation question comes after this many finished contents. const NPS_AFTER: i64 = 2; /// User text: control characters out (line breaks kept), trimmed, at most `max` characters. fn clean_text(text: Option, max: usize, what: &str) -> Result, ApiError> { let Some(text) = text else { return Ok(None) }; let text: String = text.replace("\r\n", "\n").chars().filter(|&c| c == '\n' || !c.is_control()).collect(); let text = text.trim().to_string(); if text.chars().count() > max { return Err(ApiError::BadRequest(format!("{what} legfeljebb {max} karakter lehet."))); } Ok((!text.is_empty()).then_some(text)) } /// Whether the user has paid for a package. async fn is_buyer(conn: &mut PgConnection, user: Uuid) -> Result { sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')") .bind(user) .fetch_one(conn) .await } // --- ratings ----------------------------------------------------------------------------------- #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct RatingRequest { analysis_id: Option, question_id: Option, stars: i16, #[serde(default)] tags: Vec, comment: Option, #[serde(default)] may_read: bool, } type RatingRow = (Option, Option, i16, Vec, Option, bool, OffsetDateTime); fn rating_view(row: RatingRow) -> Value { let (analysis_id, question_id, stars, tags, comment, may_read, updated_at) = row; json!({ "analysis_id": analysis_id, "question_id": question_id, "stars": stars, "tags": tags, "comment": comment, "may_read": may_read, "updated_at": rfc3339(updated_at), }) } const RATING_COLUMNS: &str = "analysis_id, question_id, stars, tags, comment, may_read, updated_at"; /// What a rating is of: kind, model and prompt version, if the user may rate it. async fn rated( state: &crate::AppState, auth: &AuthUser, req: &RatingRequest, ) -> Result<(String, String, String), ApiError> { match (req.analysis_id, req.question_id) { (Some(id), None) => { let row: Option<(String, String, Option, String, String)> = sqlx::query_as( "SELECT kind, status, requested_by, coalesce(model_used, model), prompt_version FROM analyses WHERE id = $1", ) .bind(id) .fetch_optional(&state.db) .await?; let (kind, status, requested_by, model, prompt) = row.ok_or(ApiError::NotFound("analysis"))?; let mine = if kind == "tarot" { requested_by == Some(auth.id()) } else { let analysis = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?; can_see(&state.db, &analysis, auth.id()).await? }; if !mine || !RATED_KINDS.contains(&kind.as_str()) { return Err(ApiError::NotFound("analysis")); } if status != "done" { return Err(ApiError::conflict("not_ready", "Csak kész elemzést lehet értékelni.")); } Ok((kind, model, prompt)) } (None, Some(id)) => { let row: Option<(Option, String, String, String)> = sqlx::query_as( "SELECT asked_by, status, coalesce(model_used, model), prompt_version FROM questions WHERE id = $1", ) .bind(id) .fetch_optional(&state.db) .await?; let (asked_by, status, model, prompt) = row.ok_or(ApiError::NotFound("question"))?; if asked_by != Some(auth.id()) { return Err(ApiError::NotFound("question")); } if status != "done" { return Err(ApiError::conflict("not_ready", "Csak kész választ lehet értékelni.")); } Ok(("question".into(), model, prompt)) } _ => Err(ApiError::BadRequest("give either analysis_id or question_id".into())), } } /// Rates (or re-rates) something the user got. pub async fn rate( State(state): St, auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult> { if !(1..=5).contains(&req.stars) { return Err(ApiError::BadRequest("stars must be 1 to 5".into())); } let mut tags: Vec = Vec::new(); for tag in &req.tags { if !TAGS.contains(&tag.as_str()) { return Err(ApiError::BadRequest(format!("unknown tag '{tag}'"))); } if !tags.contains(tag) { tags.push(tag.clone()); } } let comment = clean_text(req.comment.clone(), MAX_COMMENT, "A megjegyzés")?; let (kind, model, prompt) = rated(&state, &auth, &req).await?; let mut conn = state.db.acquire().await?; let buyer = is_buyer(&mut conn, auth.id()).await?; let target = if req.analysis_id.is_some() { "analysis_id" } else { "question_id" }; let row: RatingRow = sqlx::query_as(&format!( "INSERT INTO content_ratings (id, user_id, analysis_id, question_id, kind, model, prompt_version, stars, tags, \ comment, may_read, buyer) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) \ ON CONFLICT ({target}, user_id) WHERE {target} IS NOT NULL AND user_id IS NOT NULL DO UPDATE SET \ stars = EXCLUDED.stars, tags = EXCLUDED.tags, comment = EXCLUDED.comment, may_read = EXCLUDED.may_read, \ buyer = EXCLUDED.buyer, updated_at = now(), reviewed_at = NULL \ RETURNING {RATING_COLUMNS}" )) .bind(Uuid::now_v7()) .bind(auth.id()) .bind(req.analysis_id) .bind(req.question_id) .bind(&kind) .bind(&model) .bind(&prompt) .bind(req.stars) .bind(&tags) .bind(&comment) .bind(req.may_read) .bind(buyer) .fetch_one(&mut *conn) .await?; Ok(Json(rating_view(row))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct RatingsQuery { /// Comma separated ids. analysis_ids: Option, question_ids: Option, } fn ids(list: Option<&str>) -> Vec { list.unwrap_or("").split(',').filter_map(|s| s.trim().parse().ok()).take(100).collect() } /// The user's own ratings of the given analyses and answers. pub async fn my_ratings( State(state): St, auth: AuthUser, WithRejection(Query(query), _): WithRejection, ApiError>, ) -> ApiResult> { let rows: Vec = sqlx::query_as(&format!( "SELECT {RATING_COLUMNS} FROM content_ratings \ WHERE user_id = $1 AND (analysis_id = ANY($2) OR question_id = ANY($3))" )) .bind(auth.id()) .bind(ids(query.analysis_ids.as_deref())) .bind(ids(query.question_ids.as_deref())) .fetch_all(&state.db) .await?; Ok(Json(json!({ "ratings": rows.into_iter().map(rating_view).collect::>() }))) } // --- messages ---------------------------------------------------------------------------------- #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct NewMessage { category: String, body: String, /// The page the user came from. page: Option, } type MessageRow = ( Uuid, String, String, Option, String, Option, Option, Option, OffsetDateTime, ); const MESSAGE_COLUMNS: &str = "id, category, body, page, status, reply, replied_at, reply_seen_at, created_at"; fn message_view(row: MessageRow) -> Value { let (id, category, body, page, status, reply, replied_at, seen_at, created_at) = row; json!({ "id": id, "category": category, "body": body, "page": page, "status": status, "reply": reply, "replied_at": rfc3339_opt(replied_at), "reply_new": replied_at.is_some() && seen_at.is_none(), "created_at": rfc3339(created_at), }) } /// A message from the "Visszajelzés" page. pub async fn send( State(state): St, auth: AuthUser, headers: HeaderMap, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { if !["bug", "idea", "question", "other"].contains(&req.category.as_str()) { return Err(ApiError::BadRequest(format!("unknown category '{}'", req.category))); } let body = clean_text(Some(req.body), MAX_MESSAGE, "Az üzenet")? .ok_or_else(|| ApiError::BadRequest("Írd meg az üzenetet.".into()))?; // A path of this site only. let page = req .page .filter(|p| p.starts_with('/') && !p.starts_with("//")) .map(|p| p.chars().take(300).collect::()); let agent = headers.get(header::USER_AGENT).and_then(|v| v.to_str().ok()).map(|a| a.chars().take(300).collect::()); let mut tx = state.db.begin().await?; sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?; let today: i64 = sqlx::query_scalar( "SELECT count(*) FROM feedback_messages WHERE user_id = $1 AND created_at > now() - interval '24 hours'", ) .bind(auth.id()) .fetch_one(&mut *tx) .await?; if today >= MESSAGES_PER_DAY { return Err(ApiError::conflict( "feedback_limit", "Ma már sok üzenetet küldtél. Holnap újra írhatsz, vagy írj az info@sorsfonalak.hu címre.", )); } let row: MessageRow = sqlx::query_as(&format!( "INSERT INTO feedback_messages (id, user_id, category, body, page, user_agent) VALUES ($1, $2, $3, $4, $5, $6) \ RETURNING {MESSAGE_COLUMNS}" )) .bind(Uuid::now_v7()) .bind(auth.id()) .bind(&req.category) .bind(&body) .bind(&page) .bind(&agent) .fetch_one(&mut *tx) .await?; tx.commit().await?; tracing::info!(user = %auth.id(), category = %req.category, "feedback message"); Ok((StatusCode::CREATED, Json(message_view(row)))) } /// The user's messages, newest first, with their state and the replies. pub async fn my_messages(State(state): St, auth: AuthUser) -> ApiResult> { let rows: Vec = sqlx::query_as(&format!( "SELECT {MESSAGE_COLUMNS} FROM feedback_messages WHERE user_id = $1 ORDER BY created_at DESC LIMIT 100" )) .bind(auth.id()) .fetch_all(&state.db) .await?; Ok(Json(json!({ "messages": rows.into_iter().map(message_view).collect::>() }))) } /// The user has read the replies. pub async fn replies_seen(State(state): St, auth: AuthUser) -> ApiResult { sqlx::query( "UPDATE feedback_messages SET reply_seen_at = now() \ WHERE user_id = $1 AND replied_at IS NOT NULL AND reply_seen_at IS NULL", ) .bind(auth.id()) .execute(&state.db) .await?; Ok(StatusCode::NO_CONTENT) } /// Replies the user has not read yet (the menu marks them). pub async fn unseen_replies(conn: &mut PgConnection, user: Uuid) -> Result { sqlx::query_scalar( "SELECT count(*) FROM feedback_messages WHERE user_id = $1 AND replied_at IS NOT NULL AND reply_seen_at IS NULL", ) .bind(user) .fetch_one(conn) .await } // --- the recommendation question (NPS) ----------------------------------------------------------- /// Whether to ask the user now: not asked before, has a couple of finished /// contents (the free summary does not count), and is no one of the team /// (admins and authors). pub async fn nps_due(conn: &mut PgConnection, user: Uuid) -> Result { sqlx::query_scalar(&format!( "SELECT NOT EXISTS (SELECT 1 FROM nps_answers WHERE user_id = $1) \ AND NOT EXISTS (SELECT 1 FROM users WHERE id = $1 AND roles && ARRAY['admin', 'creator']) \ AND (SELECT count(*) FROM analyses WHERE requested_by = $1 AND status = 'done' \ AND kind IN ('natal', 'synastry', 'forecast', 'tarot')) \ + (SELECT count(*) FROM questions WHERE asked_by = $1 AND status = 'done') >= {NPS_AFTER}" )) .bind(user) .fetch_one(conn) .await } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct NpsAnswer { /// 0–10; none: the question was closed. score: Option, comment: Option, } /// The answer to the recommendation question (or closing it): once. pub async fn nps( State(state): St, auth: AuthUser, WithRejection(Json(req), _): Body, ) -> ApiResult { if req.score.is_some_and(|s| !(0..=10).contains(&s)) { return Err(ApiError::BadRequest("score must be 0 to 10".into())); } let comment = clean_text(req.comment, MAX_COMMENT, "A megjegyzés")?; let mut conn = state.db.acquire().await?; let buyer = is_buyer(&mut conn, auth.id()).await?; sqlx::query( "INSERT INTO nps_answers (id, user_id, score, comment, buyer) VALUES ($1, $2, $3, $4, $5) \ ON CONFLICT (user_id) DO UPDATE SET score = coalesce(nps_answers.score, EXCLUDED.score), \ comment = coalesce(nps_answers.comment, EXCLUDED.comment)", ) .bind(Uuid::now_v7()) .bind(auth.id()) .bind(req.score) .bind(&comment) .bind(buyer) .execute(&mut *conn) .await?; Ok(StatusCode::NO_CONTENT) } // --- admin ------------------------------------------------------------------------------------- /// Admin: what is new (the admin menu shows the number): messages not looked /// at, and low or commented ratings not reviewed. pub async fn admin_count(State(state): St, _admin: AdminUser) -> ApiResult> { let (messages, ratings): (i64, i64) = sqlx::query_as( "SELECT (SELECT count(*) FROM feedback_messages WHERE status = 'new'), \ (SELECT count(*) FROM content_ratings WHERE reviewed_at IS NULL AND (stars <= 2 OR comment IS NOT NULL))", ) .fetch_one(&state.db) .await?; Ok(Json(json!({ "messages": messages, "ratings": ratings, "total": messages + ratings }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct SummaryQuery { /// The period in days (default 90). days: Option, } /// Admin: the numbers: ratings by kind, by model and prompt, by week, the /// tags, buyers and others, and the recommendation question. pub async fn admin_summary( State(state): St, _admin: AdminUser, WithRejection(Query(query), _): WithRejection, ApiError>, ) -> ApiResult> { let days = query.days.unwrap_or(90).clamp(1, 3650); let since = "created_at > now() - make_interval(days => $1)"; let by_kind: Vec<(String, i64, f64, i64)> = sqlx::query_as(&format!( "SELECT kind, count(*), avg(stars)::float8, count(*) FILTER (WHERE stars >= 4) FROM content_ratings \ WHERE {since} GROUP BY kind ORDER BY count(*) DESC" )) .bind(days) .fetch_all(&state.db) .await?; let by_model: Vec<(String, String, String, i64, f64)> = sqlx::query_as(&format!( "SELECT kind, coalesce(model, '?'), coalesce(prompt_version, '?'), count(*), avg(stars)::float8 \ FROM content_ratings WHERE {since} GROUP BY 1, 2, 3 ORDER BY 1, count(*) DESC" )) .bind(days) .fetch_all(&state.db) .await?; let weeks: Vec<(time::Date, i64, f64)> = sqlx::query_as(&format!( "SELECT date_trunc('week', created_at AT TIME ZONE 'Europe/Budapest')::date, count(*), avg(stars)::float8 \ FROM content_ratings WHERE {since} GROUP BY 1 ORDER BY 1" )) .bind(days) .fetch_all(&state.db) .await?; let tags: Vec<(String, i64)> = sqlx::query_as(&format!( "SELECT tag, count(*) FROM content_ratings, unnest(tags) AS tag WHERE {since} GROUP BY tag ORDER BY count(*) DESC" )) .bind(days) .fetch_all(&state.db) .await?; let buyers: Vec<(bool, i64, f64)> = sqlx::query_as(&format!( "SELECT buyer, count(*), avg(stars)::float8 FROM content_ratings WHERE {since} GROUP BY buyer" )) .bind(days) .fetch_all(&state.db) .await?; let (answered, promoters, detractors, closed): (i64, i64, i64, i64) = sqlx::query_as(&format!( "SELECT count(score), count(*) FILTER (WHERE score >= 9), count(*) FILTER (WHERE score <= 6), \ count(*) FILTER (WHERE score IS NULL) FROM nps_answers WHERE {since}" )) .bind(days) .fetch_one(&state.db) .await?; let nps_comments: Vec<(i16, String, OffsetDateTime)> = sqlx::query_as(&format!( "SELECT score, comment, created_at FROM nps_answers WHERE {since} AND score IS NOT NULL AND comment IS NOT NULL \ ORDER BY created_at DESC LIMIT 30" )) .bind(days) .fetch_all(&state.db) .await?; let nps_score = (answered > 0).then(|| ((promoters - detractors) * 100) as f64 / answered as f64); Ok(Json(json!({ "days": days, "by_kind": by_kind.into_iter().map(|(kind, n, avg, happy)| json!({ "kind": kind, "count": n, "average": avg, "satisfied_share": happy as f64 / n.max(1) as f64, })).collect::>(), "by_model": by_model.into_iter().map(|(kind, model, prompt, n, avg)| json!({ "kind": kind, "model": model, "prompt_version": prompt, "count": n, "average": avg, })).collect::>(), "weeks": weeks.into_iter().map(|(week, n, avg)| json!({ "week": week.to_string(), "count": n, "average": avg })) .collect::>(), "tags": tags.into_iter().map(|(tag, n)| json!({ "tag": tag, "count": n })).collect::>(), "buyers": buyers.into_iter().map(|(buyer, n, avg)| json!({ "buyer": buyer, "count": n, "average": avg })) .collect::>(), "nps": { "answered": answered, "promoters": promoters, "detractors": detractors, "passives": answered - promoters - detractors, "closed": closed, "score": nps_score, "comments": nps_comments.into_iter().map(|(score, comment, at)| json!({ "score": score, "comment": comment, "created_at": rfc3339(at), })).collect::>(), }, }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct AdminRatingsQuery { kind: Option, /// At most this many stars (e.g. 2: the unhappy ones). max_stars: Option, /// Only the ones with a comment. with_comment: Option, /// Only the ones not reviewed yet. unreviewed: Option, limit: Option, offset: Option, } #[derive(sqlx::FromRow)] struct AdminRating { id: Uuid, kind: String, model: Option, prompt_version: Option, stars: i16, tags: Vec, comment: Option, may_read: bool, buyer: bool, created_at: OffsetDateTime, updated_at: OffsetDateTime, reviewed_at: Option, readable: bool, email: Option, display_name: Option, } /// Admin: the ratings, newest first, filtered. pub async fn admin_ratings( State(state): St, _admin: AdminUser, WithRejection(Query(query), _): WithRejection, ApiError>, ) -> ApiResult> { let limit = query.limit.unwrap_or(50).clamp(1, 200); let offset = query.offset.unwrap_or(0).max(0); let filter = "FROM content_ratings r LEFT JOIN users u ON u.id = r.user_id \ WHERE ($1::text IS NULL OR r.kind = $1) AND ($2::smallint IS NULL OR r.stars <= $2) \ AND (NOT $3 OR r.comment IS NOT NULL) AND (NOT $4 OR r.reviewed_at IS NULL)"; let rows: Vec = sqlx::query_as(&format!( "SELECT r.id, r.kind, r.model, r.prompt_version, r.stars, r.tags, r.comment, r.may_read, r.buyer, r.created_at, \ r.updated_at, r.reviewed_at, \ r.may_read AND (r.analysis_id IS NOT NULL OR r.question_id IS NOT NULL) AS readable, \ u.email, u.display_name \ {filter} ORDER BY r.updated_at DESC LIMIT $5 OFFSET $6" )) .bind(query.kind.as_deref().filter(|k| !k.is_empty())) .bind(query.max_stars) .bind(query.with_comment.unwrap_or(false)) .bind(query.unreviewed.unwrap_or(false)) .bind(limit) .bind(offset) .fetch_all(&state.db) .await?; let total: i64 = sqlx::query_scalar(&format!("SELECT count(*) {filter}")) .bind(query.kind.as_deref().filter(|k| !k.is_empty())) .bind(query.max_stars) .bind(query.with_comment.unwrap_or(false)) .bind(query.unreviewed.unwrap_or(false)) .fetch_one(&state.db) .await?; let ratings: Vec = rows .into_iter() .map(|r| { json!({ "id": r.id, "kind": r.kind, "model": r.model, "prompt_version": r.prompt_version, "stars": r.stars, "tags": r.tags, "comment": r.comment, "may_read": r.may_read, "readable": r.readable, "buyer": r.buyer, "created_at": rfc3339(r.created_at), "updated_at": rfc3339(r.updated_at), "reviewed": r.reviewed_at.is_some(), "user": r.email.map(|e| json!({ "email": e, "name": r.display_name })), }) }) .collect(); Ok(Json(json!({ "ratings": ratings, "total": total, "limit": limit, "offset": offset }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct Reviewed { /// These ratings; none: all of them. ids: Option>, } /// Admin: marks ratings as looked at. pub async fn admin_reviewed( State(state): St, _admin: AdminUser, WithRejection(Json(req), _): Body, ) -> ApiResult { sqlx::query( "UPDATE content_ratings SET reviewed_at = now() WHERE reviewed_at IS NULL AND ($1::uuid[] IS NULL OR id = ANY($1))", ) .bind(req.ids) .execute(&state.db) .await?; Ok(StatusCode::NO_CONTENT) } /// Admin: the rated text, only if the user allowed it. pub async fn admin_rated_content( State(state): St, admin: AdminUser, WithRejection(Path(id), _): IdPath, ) -> ApiResult> { let row: Option<(bool, Option, Option)> = sqlx::query_as("SELECT may_read, analysis_id, question_id FROM content_ratings WHERE id = $1") .bind(id) .fetch_optional(&state.db) .await?; let (may_read, analysis_id, question_id) = row.ok_or(ApiError::NotFound("rating"))?; if !may_read { return Err(ApiError::Forbidden("A felhasználó nem engedte, hogy a szöveget megnézd.".into())); } tracing::info!(admin = %admin.0.id(), rating = %id, "rated content read"); if let Some(analysis_id) = analysis_id { let row: Option<(String, Option, String, Option)> = sqlx::query_as("SELECT kind, content, language, tarot FROM analyses WHERE id = $1") .bind(analysis_id) .fetch_optional(&state.db) .await?; let (kind, content, language, tarot) = row.ok_or(ApiError::NotFound("analysis"))?; // A reading's question and cards, without anything else of the user. let tarot = tarot.map(|t| json!({ "question": t["question"], "spread": t["spread"], "cards": t["cards"] })); return Ok(Json(json!({ "kind": kind, "language": language, "content": content, "tarot": tarot }))); } if let Some(question_id) = question_id { let row: Option<(String, Option)> = sqlx::query_as("SELECT question, answer FROM questions WHERE id = $1") .bind(question_id) .fetch_optional(&state.db) .await?; let (question, answer) = row.ok_or(ApiError::NotFound("question"))?; return Ok(Json(json!({ "kind": "question", "question": question, "answer": answer }))); } Err(ApiError::NotFound("content")) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct AdminMessagesQuery { /// `open` (new and in progress: default), `new`, `in_progress`, `done`, `dismissed` or `all`. status: Option, } type AdminMessageRow = ( Uuid, String, String, Option, Option, String, Option, Option, Option, Option, OffsetDateTime, String, Option, bool, ); /// Admin: the messages, newest first. pub async fn admin_messages( State(state): St, _admin: AdminUser, WithRejection(Query(query), _): WithRejection, ApiError>, ) -> ApiResult> { let status = query.status.unwrap_or_else(|| "open".into()); if !["open", "new", "in_progress", "done", "dismissed", "all"].contains(&status.as_str()) { return Err(ApiError::BadRequest(format!("unknown status '{status}'"))); } let rows: Vec = sqlx::query_as( "SELECT m.id, m.category, m.body, m.page, m.user_agent, m.status, m.admin_note, m.reply, m.replied_at, \ m.reply_seen_at, m.created_at, u.email, u.display_name, \ EXISTS (SELECT 1 FROM package_orders o WHERE o.user_id = m.user_id AND o.source = 'stripe') \ FROM feedback_messages m JOIN users u ON u.id = m.user_id \ WHERE $1 = 'all' OR ($1 = 'open' AND m.status IN ('new', 'in_progress')) OR m.status = $1 \ ORDER BY m.created_at DESC LIMIT 200", ) .bind(&status) .fetch_all(&state.db) .await?; let messages: Vec = rows .into_iter() .map(|(id, category, body, page, agent, status, note, reply, replied, seen, created, email, name, buyer)| { json!({ "id": id, "category": category, "body": body, "page": page, "user_agent": agent, "status": status, "admin_note": note, "reply": reply, "replied_at": rfc3339_opt(replied), "reply_seen": seen.is_some(), "created_at": rfc3339(created), "user": { "email": email, "name": name, "buyer": buyer }, }) }) .collect(); Ok(Json(json!({ "messages": messages, "status": status }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct MessageUpdate { status: Option, /// Only the operator sees it; an empty one clears it. admin_note: Option, /// Shown to the user on the "Visszajelzés" page; an empty one clears it. reply: Option, } /// Admin: a message's state, note or reply. pub async fn admin_update_message( State(state): St, admin: AdminUser, WithRejection(Path(id), _): IdPath, WithRejection(Json(req), _): Body, ) -> ApiResult> { if let Some(status) = &req.status && !["new", "in_progress", "done", "dismissed"].contains(&status.as_str()) { return Err(ApiError::BadRequest(format!("unknown status '{status}'"))); } let note = req.admin_note.map(|n| clean_text(Some(n), MAX_REPLY, "A jegyzet")).transpose()?; let reply = req.reply.map(|r| clean_text(Some(r), MAX_REPLY, "A válasz")).transpose()?; let result = sqlx::query( "UPDATE feedback_messages SET \ status = coalesce($2, status), \ admin_note = CASE WHEN $3 THEN $4 ELSE admin_note END, \ replied_at = CASE WHEN $5 AND $6::text IS DISTINCT FROM reply \ THEN (CASE WHEN $6::text IS NULL THEN NULL ELSE now() END) ELSE replied_at END, \ reply_seen_at = CASE WHEN $5 AND $6::text IS DISTINCT FROM reply THEN NULL ELSE reply_seen_at END, \ reply = CASE WHEN $5 THEN $6 ELSE reply END, \ updated_at = now() \ WHERE id = $1", ) .bind(id) .bind(&req.status) .bind(note.is_some()) .bind(note.flatten()) .bind(reply.is_some()) .bind(reply.flatten()) .execute(&state.db) .await?; if result.rows_affected() == 0 { return Err(ApiError::NotFound("message")); } tracing::info!(admin = %admin.0.id(), message = %id, "feedback message updated"); let row: MessageRow = sqlx::query_as(&format!("SELECT {MESSAGE_COLUMNS} FROM feedback_messages WHERE id = $1")) .bind(id) .fetch_one(&state.db) .await?; Ok(Json(message_view(row))) }