Feedback in the system: ratings, messages, the recommendation question
- Under the summary, the detailed analyses, the forecast and tarot: "How tailored to you did it feel?" (1–5 stars); thumbs under answers. Only the owner rates, once (changeable); tags, a comment, and a permission to read the text; model and prompt version are kept with it - /visszajelzes: bug, idea, question, other (the page and the browser go with it, 10 a day); the state and the operator's reply show there, a dot in the account menu marks a new reply. No e-mail, no Telegram - One NPS question (0–10) in a bar under the header, after two finished contents; closing it counts - Admin → Visszajelzések: numbers by kind, week, tags, model and prompt, buyers and others, NPS; ratings with filters, the text only if allowed; messages with state, internal note and reply; a count in the admin menu - Nothing is public. Deleting an account keeps the stars without a name or comment; messages go. Privacy policy (hu, en) updated - The admin menu no longer shows a vertical scrollbar Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -39,6 +39,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
.bind(auth.id())
|
||||
.fetch_one(&mut *conn)
|
||||
.await?;
|
||||
let replies = super::feedback::unseen_replies(&mut conn, auth.id()).await?;
|
||||
let nps_due = super::feedback::nps_due(&mut conn, auth.id()).await?;
|
||||
Ok(Json(json!({
|
||||
"user": UserView::from(&auth.user),
|
||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||
@@ -53,6 +55,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
"referral_rewards": { "earned": referrals, "limit": super::shares::REFERRAL_LIMIT },
|
||||
// The "Számláim" menu shows up with the first invoice.
|
||||
"invoice_count": invoices,
|
||||
// Replies to the user's feedback not read yet (the menu marks them).
|
||||
"feedback_replies_unseen": replies,
|
||||
// Ask the "would you recommend us?" question now.
|
||||
"nps_due": nps_due,
|
||||
})))
|
||||
}
|
||||
|
||||
@@ -226,6 +232,15 @@ pub async fn delete_me(
|
||||
.bind(auth.id())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// Ratings and the recommendation answer stay for the statistics, without
|
||||
// a name and without what was written (messages go with the account).
|
||||
// Detached here: deleting the user and its analyses in one statement
|
||||
// would update a rating through both foreign keys at once.
|
||||
sqlx::query("UPDATE content_ratings SET user_id = NULL, comment = NULL, may_read = false WHERE user_id = $1")
|
||||
.bind(auth.id())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("UPDATE nps_answers SET comment = NULL WHERE user_id = $1").bind(auth.id()).execute(&mut *tx).await?;
|
||||
// Gifts stay redeemable, but whom they were for and the message go.
|
||||
sqlx::query(
|
||||
"UPDATE gifts SET recipient_name = NULL, recipient_email = NULL, from_name = NULL, message = NULL \
|
||||
|
||||
@@ -0,0 +1,762 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! 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<String>, max: usize, what: &str) -> Result<Option<String>, 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<bool, sqlx::Error> {
|
||||
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<Uuid>,
|
||||
question_id: Option<Uuid>,
|
||||
stars: i16,
|
||||
#[serde(default)]
|
||||
tags: Vec<String>,
|
||||
comment: Option<String>,
|
||||
#[serde(default)]
|
||||
may_read: bool,
|
||||
}
|
||||
|
||||
type RatingRow = (Option<Uuid>, Option<Uuid>, i16, Vec<String>, Option<String>, 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<Uuid>, 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<Uuid>, 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<RatingRequest>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
if !(1..=5).contains(&req.stars) {
|
||||
return Err(ApiError::BadRequest("stars must be 1 to 5".into()));
|
||||
}
|
||||
let mut tags: Vec<String> = 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<String>,
|
||||
question_ids: Option<String>,
|
||||
}
|
||||
|
||||
fn ids(list: Option<&str>) -> Vec<Uuid> {
|
||||
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<Query<RatingsQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let rows: Vec<RatingRow> = 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::<Vec<_>>() })))
|
||||
}
|
||||
|
||||
// --- messages ----------------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct NewMessage {
|
||||
category: String,
|
||||
body: String,
|
||||
/// The page the user came from.
|
||||
page: Option<String>,
|
||||
}
|
||||
|
||||
type MessageRow = (
|
||||
Uuid,
|
||||
String,
|
||||
String,
|
||||
Option<String>,
|
||||
String,
|
||||
Option<String>,
|
||||
Option<OffsetDateTime>,
|
||||
Option<OffsetDateTime>,
|
||||
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<NewMessage>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
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::<String>());
|
||||
let agent =
|
||||
headers.get(header::USER_AGENT).and_then(|v| v.to_str().ok()).map(|a| a.chars().take(300).collect::<String>());
|
||||
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<Json<Value>> {
|
||||
let rows: Vec<MessageRow> = 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::<Vec<_>>() })))
|
||||
}
|
||||
|
||||
/// The user has read the replies.
|
||||
pub async fn replies_seen(State(state): St, auth: AuthUser) -> ApiResult<StatusCode> {
|
||||
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<i64, sqlx::Error> {
|
||||
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, and has a couple of
|
||||
/// finished contents (the free summary does not count).
|
||||
pub async fn nps_due(conn: &mut PgConnection, user: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar(&format!(
|
||||
"SELECT NOT EXISTS (SELECT 1 FROM nps_answers WHERE user_id = $1) \
|
||||
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<i16>,
|
||||
comment: Option<String>,
|
||||
}
|
||||
|
||||
/// The answer to the recommendation question (or closing it): once.
|
||||
pub async fn nps(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<NpsAnswer>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
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<Json<Value>> {
|
||||
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<i32>,
|
||||
}
|
||||
|
||||
/// 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<Query<SummaryQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
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::<Vec<_>>(),
|
||||
"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::<Vec<_>>(),
|
||||
"weeks": weeks.into_iter().map(|(week, n, avg)| json!({ "week": week.to_string(), "count": n, "average": avg }))
|
||||
.collect::<Vec<_>>(),
|
||||
"tags": tags.into_iter().map(|(tag, n)| json!({ "tag": tag, "count": n })).collect::<Vec<_>>(),
|
||||
"buyers": buyers.into_iter().map(|(buyer, n, avg)| json!({ "buyer": buyer, "count": n, "average": avg }))
|
||||
.collect::<Vec<_>>(),
|
||||
"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::<Vec<_>>(),
|
||||
},
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AdminRatingsQuery {
|
||||
kind: Option<String>,
|
||||
/// At most this many stars (e.g. 2: the unhappy ones).
|
||||
max_stars: Option<i16>,
|
||||
/// Only the ones with a comment.
|
||||
with_comment: Option<bool>,
|
||||
/// Only the ones not reviewed yet.
|
||||
unreviewed: Option<bool>,
|
||||
limit: Option<i64>,
|
||||
offset: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct AdminRating {
|
||||
id: Uuid,
|
||||
kind: String,
|
||||
model: Option<String>,
|
||||
prompt_version: Option<String>,
|
||||
stars: i16,
|
||||
tags: Vec<String>,
|
||||
comment: Option<String>,
|
||||
may_read: bool,
|
||||
buyer: bool,
|
||||
created_at: OffsetDateTime,
|
||||
updated_at: OffsetDateTime,
|
||||
reviewed_at: Option<OffsetDateTime>,
|
||||
readable: bool,
|
||||
email: Option<String>,
|
||||
display_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Admin: the ratings, newest first, filtered.
|
||||
pub async fn admin_ratings(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
WithRejection(Query(query), _): WithRejection<Query<AdminRatingsQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
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<AdminRating> = 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<Value> = 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<Vec<Uuid>>,
|
||||
}
|
||||
|
||||
/// Admin: marks ratings as looked at.
|
||||
pub async fn admin_reviewed(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
WithRejection(Json(req), _): Body<Reviewed>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
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<Json<Value>> {
|
||||
let row: Option<(bool, Option<Uuid>, Option<Uuid>)> =
|
||||
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<Value>, String, Option<Value>)> =
|
||||
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<String>)> =
|
||||
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<String>,
|
||||
}
|
||||
|
||||
type AdminMessageRow = (
|
||||
Uuid,
|
||||
String,
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<OffsetDateTime>,
|
||||
Option<OffsetDateTime>,
|
||||
OffsetDateTime,
|
||||
String,
|
||||
Option<String>,
|
||||
bool,
|
||||
);
|
||||
|
||||
/// Admin: the messages, newest first.
|
||||
pub async fn admin_messages(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
WithRejection(Query(query), _): WithRejection<Query<AdminMessagesQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
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<AdminMessageRow> = 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<Value> = 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<String>,
|
||||
/// Only the operator sees it; an empty one clears it.
|
||||
admin_note: Option<String>,
|
||||
/// Shown to the user on the "Visszajelzés" page; an empty one clears it.
|
||||
reply: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<MessageUpdate>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
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)))
|
||||
}
|
||||
@@ -13,6 +13,7 @@ mod calculator;
|
||||
mod celebrities;
|
||||
mod charts;
|
||||
mod errors;
|
||||
mod feedback;
|
||||
mod forecasts;
|
||||
mod gifts;
|
||||
mod invitations;
|
||||
@@ -122,6 +123,17 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/gifts/checkout", post(gifts::checkout))
|
||||
.route("/v1/gifts/{id}/card.pdf", get(gifts::card))
|
||||
.route("/v1/gifts/{id}/send", post(gifts::send_again))
|
||||
.route("/v1/ratings", get(feedback::my_ratings).put(feedback::rate))
|
||||
.route("/v1/feedback", get(feedback::my_messages).post(feedback::send))
|
||||
.route("/v1/feedback/seen", post(feedback::replies_seen))
|
||||
.route("/v1/nps", post(feedback::nps))
|
||||
.route("/v1/admin/feedback", get(feedback::admin_messages))
|
||||
.route("/v1/admin/feedback/count", get(feedback::admin_count))
|
||||
.route("/v1/admin/feedback/summary", get(feedback::admin_summary))
|
||||
.route("/v1/admin/feedback/{id}", patch(feedback::admin_update_message))
|
||||
.route("/v1/admin/ratings", get(feedback::admin_ratings))
|
||||
.route("/v1/admin/ratings/reviewed", post(feedback::admin_reviewed))
|
||||
.route("/v1/admin/ratings/{id}/content", get(feedback::admin_rated_content))
|
||||
.route("/v1/admin/gifts", get(gifts::admin_list))
|
||||
.route("/v1/admin/gifts/{id}/refund", post(gifts::admin_refund))
|
||||
.route("/v1/admin/promo-codes", get(promo::list).post(promo::create))
|
||||
|
||||
@@ -3707,3 +3707,250 @@ async fn a_gift_paid_with_the_stand_in_is_refunded_without_stripe(pool: PgPool)
|
||||
assert_eq!((&r.body["gifts"][0]["refund_pending"], &r.body["gifts"][0]["checkout"]), (&json!(false), &Value::Null));
|
||||
assert_eq!(app.post(&url, Some(&admin), json!({})).await.body["error"]["code"], "gift_refunded");
|
||||
}
|
||||
|
||||
// --- feedback --------------------------------------------------------------------------------
|
||||
|
||||
async fn put_rating(app: &TestApp, token: &str, body: Value) -> Response {
|
||||
app.call("PUT", "/v1/ratings", Some(token), Some(body)).await
|
||||
}
|
||||
|
||||
async fn user_id(app: &TestApp, token: &str) -> uuid::Uuid {
|
||||
app.get("/v1/me", Some(token)).await.body["user"]["id"].as_str().unwrap().parse().unwrap()
|
||||
}
|
||||
|
||||
/// A finished (or not) analysis of `kind`, straight into the database.
|
||||
async fn analysis_row(app: &TestApp, kind: &str, chart: Option<&str>, by: uuid::Uuid, status: &str) -> String {
|
||||
let id = uuid::Uuid::now_v7();
|
||||
sqlx::query(
|
||||
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, status, \
|
||||
content, tarot) \
|
||||
VALUES ($1, $2, $3::uuid, $4, 'hu', 'vendor/model-a', 'v7', $1::text, $5, \
|
||||
CASE WHEN $5 = 'done' THEN '{\"summary\": \"Csendes erő.\"}'::jsonb END, \
|
||||
CASE WHEN $2 = 'tarot' THEN '{\"question\": \"Mi vár rám?\", \"spread\": 1, \"cards\": []}'::jsonb END)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(kind)
|
||||
.bind(chart)
|
||||
.bind(by)
|
||||
.bind(status)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
id.to_string()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn ratings_are_only_for_what_the_user_got(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let anna_id = user_id(&app, &anna).await;
|
||||
let chart = app.chart(&anna, "Anna", true, "1990-03-15").await["id"].as_str().unwrap().to_string();
|
||||
let natal = analysis_row(&app, "natal", Some(&chart), anna_id, "done").await;
|
||||
let pending = analysis_row(&app, "natal", Some(&chart), anna_id, "pending").await;
|
||||
let tarot = analysis_row(&app, "tarot", None, anna_id, "done").await;
|
||||
let question = uuid::Uuid::now_v7();
|
||||
sqlx::query(
|
||||
"INSERT INTO questions (id, analysis_id, asked_by, question, language, model, prompt_version, status, answer) \
|
||||
VALUES ($1, $2::uuid, $3, 'Mi az erősségem?', 'hu', 'vendor/model-b', 'q1', 'done', 'A kitartásod.')",
|
||||
)
|
||||
.bind(question)
|
||||
.bind(&natal)
|
||||
.bind(anna_id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let r = put_rating(
|
||||
&app,
|
||||
&anna,
|
||||
json!({"analysis_id": natal, "stars": 4, "tags": ["accurate", "deep"], "comment": " Talált! "}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(
|
||||
(&r.body["stars"], &r.body["comment"], &r.body["may_read"]),
|
||||
(&json!(4), &json!("Talált!"), &json!(false))
|
||||
);
|
||||
// Changed, not doubled.
|
||||
let r = put_rating(
|
||||
&app,
|
||||
&anna,
|
||||
json!({"analysis_id": natal, "stars": 2, "tags": ["too_general"], "comment": "Túl általános."}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.body["tags"], json!(["too_general"]));
|
||||
let n: i64 = sqlx::query_scalar("SELECT count(*) FROM content_ratings").fetch_one(&app.pool).await.unwrap();
|
||||
assert_eq!(n, 1);
|
||||
// Someone else's, unknown, unfinished or malformed: refused.
|
||||
assert_eq!(put_rating(&app, &bela, json!({"analysis_id": natal, "stars": 1})).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(put_rating(&app, &bela, json!({"analysis_id": tarot, "stars": 1})).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(
|
||||
put_rating(&app, &bela, json!({"question_id": question, "stars": 1})).await.status,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(put_rating(&app, &anna, json!({"analysis_id": pending, "stars": 3})).await.status, StatusCode::CONFLICT);
|
||||
assert_eq!(
|
||||
put_rating(&app, &anna, json!({"analysis_id": natal, "stars": 6})).await.status,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
assert_eq!(
|
||||
put_rating(&app, &anna, json!({"analysis_id": natal, "stars": 3, "tags": ["rossz"]})).await.status,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
let both = json!({"analysis_id": natal, "question_id": question, "stars": 3});
|
||||
assert_eq!(put_rating(&app, &anna, both).await.status, StatusCode::BAD_REQUEST);
|
||||
// A reading and an answer (thumbs up).
|
||||
assert_eq!(put_rating(&app, &anna, json!({"analysis_id": tarot, "stars": 5})).await.status, StatusCode::OK);
|
||||
let r = put_rating(&app, &anna, json!({"question_id": question, "stars": 5, "may_read": true})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let r = app.get(&format!("/v1/ratings?analysis_ids={natal},{tarot}&question_ids={question}"), Some(&anna)).await;
|
||||
assert_eq!(r.body["ratings"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(app.get(&format!("/v1/ratings?analysis_ids={natal}"), Some(&bela)).await.body["ratings"], json!([]));
|
||||
|
||||
// Admins: the numbers, the list, the text only if allowed.
|
||||
assert_eq!(app.get("/v1/admin/feedback/summary", Some(&anna)).await.status, StatusCode::FORBIDDEN);
|
||||
let r = app.get("/v1/admin/feedback/summary", Some(&admin)).await;
|
||||
let natal_row = r.body["by_kind"].as_array().unwrap().iter().find(|k| k["kind"] == "natal").unwrap().clone();
|
||||
assert_eq!((&natal_row["count"], &natal_row["average"]), (&json!(1), &json!(2.0)));
|
||||
assert!(
|
||||
r.body["by_model"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|m| m["model"] == "vendor/model-b" && m["kind"] == "question")
|
||||
);
|
||||
assert_eq!(r.body["tags"], json!([{"tag": "too_general", "count": 1}]));
|
||||
let r = app.get("/v1/admin/feedback/count", Some(&admin)).await;
|
||||
assert_eq!((&r.body["ratings"], &r.body["messages"]), (&json!(1), &json!(0)));
|
||||
let r = app.get("/v1/admin/ratings?max_stars=2", Some(&admin)).await;
|
||||
assert_eq!(r.body["total"], 1);
|
||||
let low = r.body["ratings"][0].clone();
|
||||
assert_eq!(
|
||||
(&low["comment"], &low["readable"], &low["user"]["email"]),
|
||||
(&json!("Túl általános."), &json!(false), &json!("anna@example.com"))
|
||||
);
|
||||
let r = app.get(&format!("/v1/admin/ratings/{}/content", low["id"].as_str().unwrap()), Some(&admin)).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let r = app.get("/v1/admin/ratings?kind=question", Some(&admin)).await;
|
||||
let answer = r.body["ratings"][0]["id"].as_str().unwrap().to_string();
|
||||
let r = app.get(&format!("/v1/admin/ratings/{answer}/content"), Some(&admin)).await;
|
||||
assert_eq!((&r.body["question"], &r.body["answer"]), (&json!("Mi az erősségem?"), &json!("A kitartásod.")));
|
||||
let r = app.post("/v1/admin/ratings/reviewed", Some(&admin), json!({})).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/admin/feedback/count", Some(&admin)).await.body["ratings"], 0);
|
||||
// A new rating is looked at again.
|
||||
put_rating(&app, &anna, json!({"analysis_id": natal, "stars": 1})).await;
|
||||
assert_eq!(app.get("/v1/admin/feedback/count", Some(&admin)).await.body["ratings"], 1);
|
||||
|
||||
// The account goes: the stars stay, without a name and a comment.
|
||||
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "DELETE"}))).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body);
|
||||
let left: Vec<(Option<uuid::Uuid>, Option<String>, bool)> =
|
||||
sqlx::query_as("SELECT user_id, comment, may_read FROM content_ratings").fetch_all(&app.pool).await.unwrap();
|
||||
assert_eq!(left.len(), 3);
|
||||
assert!(left.iter().all(|(user, comment, may_read)| user.is_none() && comment.is_none() && !may_read));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn feedback_messages_get_a_state_and_a_reply_in_the_app(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let r = app
|
||||
.call_with(
|
||||
"POST",
|
||||
"/v1/feedback",
|
||||
Some(&anna),
|
||||
Some(json!({"category": "bug", "body": " A képlet nem töltődik be.\r\nKöszi ", "page": "/kepletek/abc"})),
|
||||
&[("user-agent", "TestBrowser/1.0")],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!((&r.body["body"], &r.body["status"]), (&json!("A képlet nem töltődik be.\nKöszi"), &json!("new")));
|
||||
let id = r.body["id"].as_str().unwrap().to_string();
|
||||
let r = app.post("/v1/feedback", Some(&anna), json!({"category": "spam", "body": "x"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
let r = app.post("/v1/feedback", Some(&anna), json!({"category": "idea", "body": " "})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
let r = app
|
||||
.post("/v1/feedback", Some(&anna), json!({"category": "idea", "body": "Ötlet", "page": "//evil.example"}))
|
||||
.await;
|
||||
assert!(r.body["page"].is_null());
|
||||
|
||||
let r = app.get("/v1/admin/feedback", Some(&admin)).await;
|
||||
assert_eq!(r.body["messages"].as_array().unwrap().len(), 2);
|
||||
let bug = r.body["messages"].as_array().unwrap().iter().find(|m| m["id"] == json!(id)).unwrap().clone();
|
||||
assert_eq!((&bug["user_agent"], &bug["user"]["email"]), (&json!("TestBrowser/1.0"), &json!("anna@example.com")));
|
||||
assert_eq!(app.get("/v1/admin/feedback/count", Some(&admin)).await.body["messages"], 2);
|
||||
assert_eq!(app.get("/v1/admin/feedback", Some(&anna)).await.status, StatusCode::FORBIDDEN);
|
||||
|
||||
// The reply shows up for the user, marked new until read.
|
||||
let r = app
|
||||
.call(
|
||||
"PATCH",
|
||||
&format!("/v1/admin/feedback/{id}"),
|
||||
Some(&admin),
|
||||
Some(json!({"status": "done", "admin_note": "cache", "reply": "Javítottuk, köszönjük!"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let r = app.get("/v1/feedback", Some(&anna)).await;
|
||||
let mine = r.body["messages"].as_array().unwrap().iter().find(|m| m["id"] == json!(id)).unwrap().clone();
|
||||
assert_eq!(
|
||||
(&mine["status"], &mine["reply"], &mine["reply_new"]),
|
||||
(&json!("done"), &json!("Javítottuk, köszönjük!"), &json!(true))
|
||||
);
|
||||
assert!(mine.get("admin_note").is_none(), "the note is the operator's");
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["feedback_replies_unseen"], 1);
|
||||
assert_eq!(app.post("/v1/feedback/seen", Some(&anna), json!({})).await.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["feedback_replies_unseen"], 0);
|
||||
assert_eq!(
|
||||
app.get("/v1/admin/feedback?status=done", Some(&admin)).await.body["messages"].as_array().unwrap().len(),
|
||||
1
|
||||
);
|
||||
|
||||
// Ten a day.
|
||||
for _ in 0..8 {
|
||||
assert_eq!(
|
||||
app.post("/v1/feedback", Some(&anna), json!({"category": "other", "body": "még"})).await.status,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
}
|
||||
let r = app.post("/v1/feedback", Some(&anna), json!({"category": "other", "body": "még egy"})).await;
|
||||
assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("feedback_limit")));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn the_recommendation_question_comes_once_after_two_contents(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let (anna_id, bela_id) = (user_id(&app, &anna).await, user_id(&app, &bela).await);
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["nps_due"], false);
|
||||
analysis_row(&app, "tarot", None, anna_id, "done").await;
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["nps_due"], false);
|
||||
analysis_row(&app, "tarot", None, anna_id, "done").await;
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["nps_due"], true);
|
||||
let r = app.post("/v1/nps", Some(&anna), json!({"score": 9, "comment": "Nagyon tetszik."})).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["nps_due"], false);
|
||||
// Once: a second answer does not change it.
|
||||
app.post("/v1/nps", Some(&anna), json!({"score": 1})).await;
|
||||
assert_eq!(app.post("/v1/nps", Some(&anna), json!({"score": 11})).await.status, StatusCode::BAD_REQUEST);
|
||||
// Closed without an answer: not asked again.
|
||||
for _ in 0..2 {
|
||||
analysis_row(&app, "tarot", None, bela_id, "done").await;
|
||||
}
|
||||
assert_eq!(app.post("/v1/nps", Some(&bela), json!({"score": null})).await.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/me", Some(&bela)).await.body["nps_due"], false);
|
||||
let r = app.get("/v1/admin/feedback/summary", Some(&admin)).await;
|
||||
let nps = &r.body["nps"];
|
||||
assert_eq!(
|
||||
(&nps["answered"], &nps["promoters"], &nps["closed"], &nps["score"]),
|
||||
(&json!(1), &json!(1), &json!(1), &json!(100.0))
|
||||
);
|
||||
assert_eq!(nps["comments"][0]["comment"], "Nagyon tetszik.");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user