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.");
|
||||
}
|
||||
|
||||
@@ -126,6 +126,27 @@ export default async function PrivacyPage() {
|
||||
<td>Hogy ezekre a címekre ne küldjünk több meghívót</td>
|
||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Értékeléseid (csillag, címkék, megjegyzés) és az ajánlási kérdésre adott válaszod; hogy vásárló
|
||||
vagy-e
|
||||
</td>
|
||||
<td>A szolgáltatás minőségének mérése és javítása</td>
|
||||
<td>Jogos érdek (6. cikk (1) f); a megadásuk önkéntes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Az értékelt elemzés vagy válasz szövege, ha az értékelésnél megengeded, hogy megnézzük</td>
|
||||
<td>Az adott elemzés hibáinak kivizsgálása, a szövegek javítása</td>
|
||||
<td>Hozzájárulás (6. cikk (1) a); az értékelés módosításával bármikor visszavonhatod</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
A Visszajelzés oldalon küldött üzeneteid, az oldal, ahonnan küldted, a böngésződ típusa és a
|
||||
válaszunk
|
||||
</td>
|
||||
<td>Hibák kijavítása, kérdések megválaszolása</td>
|
||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>IP-cím, böngésző adatai, a kérések ideje (szervernaplók)</td>
|
||||
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
|
||||
@@ -140,6 +161,10 @@ export default async function PrivacyPage() {
|
||||
csak a fizetés azonosítóját, összegét és a számlázási adataidat kapjuk meg. Ezeket a fiókod törlése után is
|
||||
megőrizzük a számviteli törvény szerinti ideig (8 évig).
|
||||
</p>
|
||||
<p>
|
||||
<strong>Visszajelzések:</strong> az értékeléseid és az üzeneteid nem nyilvánosak, csak mi látjuk őket. Egy
|
||||
elemzés szövegét csak akkor nézzük meg, ha az értékelésnél ezt megengeded.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Megosztott link:</strong> ha megosztasz egy képletet, a linken bárki, akinek elküldöd, látja a
|
||||
képlet rajzát és a legfrissebb rövid összefoglalót. Nevet és születési adatot nem tesz közzé, a keresők nem
|
||||
@@ -269,6 +294,10 @@ export default async function PrivacyPage() {
|
||||
bármikor leiratkozhatsz.
|
||||
</li>
|
||||
<li>A várólistán megadott címet a regisztrációdig, vagy amíg nem kéred a törlését.</li>
|
||||
<li>
|
||||
A Visszajelzés oldalon küldött üzeneteidet a fiókod törléséig. Az értékelések csillagait és címkéit a fiók
|
||||
törlése után név és megjegyzés nélkül, statisztikaként megtartjuk.
|
||||
</li>
|
||||
<li>A számlázáshoz szükséges adatokat a számviteli törvény szerinti ideig (8 évig) őrizzük.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -8,7 +8,11 @@ import type { AdminGift } from "@/lib/types";
|
||||
|
||||
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
|
||||
|
||||
const STORNO: Record<string, string> = { pending: "sztornó folyamatban", done: "sztornózva", failed: "sztornó hiba" };
|
||||
const STORNO: Record<string, string> = {
|
||||
pending: "sztornó folyamatban",
|
||||
done: "sztornózva",
|
||||
failed: "sztornó hiba",
|
||||
};
|
||||
|
||||
/** The gifts with their payment, invoice and storno, and the refund button. */
|
||||
export function AdminGifts() {
|
||||
@@ -20,7 +24,9 @@ export function AdminGifts() {
|
||||
|
||||
const load = useCallback(async (search: string) => {
|
||||
try {
|
||||
const r = await api<{ gifts: AdminGift[] }>(`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`);
|
||||
const r = await api<{ gifts: AdminGift[] }>(
|
||||
`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`,
|
||||
);
|
||||
setGifts(r.gifts);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
@@ -33,8 +39,12 @@ export function AdminGifts() {
|
||||
}, [q, load]);
|
||||
|
||||
async function refund(g: AdminGift) {
|
||||
const late = g.within_withdrawal ? "" : "\n\nFigyelem: a 14 napos elállási idő már letelt.";
|
||||
const money = g.checkout?.amount_huf ? ` (${huf(g.checkout.amount_huf)})` : "";
|
||||
const late = g.within_withdrawal
|
||||
? ""
|
||||
: "\n\nFigyelem: a 14 napos elállási idő már letelt.";
|
||||
const money = g.checkout?.amount_huf
|
||||
? ` (${huf(g.checkout.amount_huf)})`
|
||||
: "";
|
||||
if (
|
||||
!window.confirm(
|
||||
`Visszatéríted a(z) „${g.package.name}” ajándékot${money}? A ${g.code} kód érvénytelen lesz, a Stripe visszautalja az árát, a számla sztornózódik.${late}`,
|
||||
@@ -103,46 +113,74 @@ export function AdminGifts() {
|
||||
</td>
|
||||
<td>
|
||||
{g.package.name ?? g.package.id}
|
||||
{g.checkout?.amount_huf ? <span className="hint">{huf(g.checkout.amount_huf)}</span> : null}
|
||||
{g.checkout && g.checkout.live === false && <span className="hint">teszt fizetés</span>}
|
||||
{g.checkout?.amount_huf ? (
|
||||
<span className="hint">{huf(g.checkout.amount_huf)}</span>
|
||||
) : null}
|
||||
{g.checkout && g.checkout.live === false && (
|
||||
<span className="hint">teszt fizetés</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{g.buyer_email ?? <span className="muted">törölt fiók</span>}
|
||||
{g.buyer_email ?? (
|
||||
<span className="muted">törölt fiók</span>
|
||||
)}
|
||||
<span className="hint">
|
||||
→ {g.recipient_name ?? "?"}
|
||||
{g.recipient_email ? ` (${g.recipient_email})` : " (maga adja át)"}
|
||||
{g.recipient_email
|
||||
? ` (${g.recipient_email})`
|
||||
: " (maga adja át)"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="num">{formatDate(g.paid_at, true)}</td>
|
||||
<td>
|
||||
{g.status === "redeemed" ? (
|
||||
<>
|
||||
beváltva {g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
|
||||
{g.redeemed_by && <span className="hint">{g.redeemed_by}</span>}
|
||||
beváltva{" "}
|
||||
{g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
|
||||
{g.redeemed_by && (
|
||||
<span className="hint">{g.redeemed_by}</span>
|
||||
)}
|
||||
</>
|
||||
) : g.status === "refunded" ? (
|
||||
<>
|
||||
{g.refund_pending ? (
|
||||
<span className="msg-error">visszatérítés félbemaradt</span>
|
||||
<span className="msg-error">
|
||||
visszatérítés félbemaradt
|
||||
</span>
|
||||
) : (
|
||||
"visszatérítve"
|
||||
)}{" "}
|
||||
{g.refunded_at ? formatDate(g.refunded_at, true) : ""}
|
||||
{g.refund_pending && g.refund_error && <span className="hint">{g.refund_error}</span>}
|
||||
{g.refund_pending && g.refund_error && (
|
||||
<span className="hint">{g.refund_error}</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="promo-open">beváltatlan</span>
|
||||
<span className="hint">{g.within_withdrawal ? "14 napon belül" : "14 nap letelt"}</span>
|
||||
<span className="hint">
|
||||
{g.within_withdrawal
|
||||
? "14 napon belül"
|
||||
: "14 nap letelt"}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{g.invoice ? (
|
||||
<>
|
||||
{g.invoice.number ?? (g.invoice.status === "pending" ? "kiállítás alatt" : g.invoice.status)}
|
||||
{g.invoice.number ??
|
||||
(g.invoice.status === "pending"
|
||||
? "kiállítás alatt"
|
||||
: g.invoice.status)}
|
||||
{g.storno && (
|
||||
<span className={g.storno.status === "failed" ? "hint msg-error" : "hint"}>
|
||||
<span
|
||||
className={
|
||||
g.storno.status === "failed"
|
||||
? "hint msg-error"
|
||||
: "hint"
|
||||
}
|
||||
>
|
||||
{STORNO[g.storno.status] ?? g.storno.status}
|
||||
{g.storno.number ? `: ${g.storno.number}` : ""}
|
||||
{g.storno.error ? ` – ${g.storno.error}` : ""}
|
||||
@@ -161,7 +199,11 @@ export function AdminGifts() {
|
||||
onClick={() => refund(g)}
|
||||
disabled={busy !== null}
|
||||
>
|
||||
{busy === g.id ? "Folyamatban…" : g.status === "refunded" ? "Újrapróbálás" : "Visszatérítés"}
|
||||
{busy === g.id
|
||||
? "Folyamatban…"
|
||||
: g.status === "refunded"
|
||||
? "Újrapróbálás"
|
||||
: "Visszatérítés"}
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
|
||||
@@ -17,10 +17,12 @@ export default async function AdminGiftsPage() {
|
||||
<div className="page-head">
|
||||
<h1>Ajándékok</h1>
|
||||
<p className="muted">
|
||||
Az ajándékba vett csomagok. A vásárló a vásárlástól számított 14 napon belül, amíg a kódot nem váltották be,
|
||||
elállhat (ÁSZF 6.). Ilyenkor a „Visszatérítés” gomb érvényteleníti a kódot, a Stripe-on visszatéríti az árát,
|
||||
és a számlát sztornózza a Billingóban (a worker, a számla kiállítása után; a sztornót a Billingo e-mailben
|
||||
elküldi a vásárlónak). Beváltott ajándékot nem lehet visszatéríteni.
|
||||
Az ajándékba vett csomagok. A vásárló a vásárlástól számított 14 napon
|
||||
belül, amíg a kódot nem váltották be, elállhat (ÁSZF 6.). Ilyenkor a
|
||||
„Visszatérítés” gomb érvényteleníti a kódot, a Stripe-on visszatéríti
|
||||
az árát, és a számlát sztornózza a Billingóban (a worker, a számla
|
||||
kiállítása után; a sztornót a Billingo e-mailben elküldi a
|
||||
vásárlónak). Beváltott ajándékot nem lehet visszatéríteni.
|
||||
</p>
|
||||
</div>
|
||||
<AdminGifts />
|
||||
|
||||
@@ -0,0 +1,683 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/astro";
|
||||
import { CATEGORY_LABELS, KIND_LABELS, TAG_LABELS } from "@/lib/feedback";
|
||||
import type {
|
||||
AdminFeedbackMessage,
|
||||
AdminRating,
|
||||
FeedbackStatus,
|
||||
FeedbackSummary,
|
||||
} from "@/lib/types";
|
||||
|
||||
type Tab = "summary" | "ratings" | "messages";
|
||||
|
||||
const avg = (n: number) =>
|
||||
n.toLocaleString("hu-HU", {
|
||||
maximumFractionDigits: 2,
|
||||
minimumFractionDigits: 1,
|
||||
});
|
||||
const pct = (n: number) => `${Math.round(n * 100)}%`;
|
||||
const stars = (n: number) => "★".repeat(n) + "☆".repeat(5 - n);
|
||||
|
||||
const ADMIN_STATUS: Record<FeedbackStatus, string> = {
|
||||
new: "új",
|
||||
in_progress: "folyamatban",
|
||||
done: "megoldva",
|
||||
dismissed: "elvetve",
|
||||
};
|
||||
|
||||
/** Admin → Visszajelzések: the numbers, the ratings, the messages. */
|
||||
export function AdminFeedback() {
|
||||
const [tab, setTab] = useState<Tab>("summary");
|
||||
return (
|
||||
<>
|
||||
<div className="tabs-row" role="tablist" aria-label="Visszajelzések">
|
||||
{(
|
||||
[
|
||||
["summary", "Áttekintés"],
|
||||
["ratings", "Értékelések"],
|
||||
["messages", "Üzenetek"],
|
||||
] as [Tab, string][]
|
||||
).map(([t, label]) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === t}
|
||||
className={tab === t ? "btn btn-sm btn-primary" : "btn btn-sm"}
|
||||
onClick={() => setTab(t)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{tab === "summary" && <Summary />}
|
||||
{tab === "ratings" && <Ratings />}
|
||||
{tab === "messages" && <Messages />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Summary() {
|
||||
const [days, setDays] = useState(90);
|
||||
const [data, setData] = useState<FeedbackSummary | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
api<FeedbackSummary>(`/admin/feedback/summary?days=${days}`)
|
||||
.then(setData)
|
||||
.catch((e) => setError(errorText(e)));
|
||||
}, [days]);
|
||||
if (error) return <p className="msg msg-error">{error}</p>;
|
||||
if (!data) return <p className="muted">Betöltés…</p>;
|
||||
const total = data.by_kind.reduce((n, k) => n + k.count, 0);
|
||||
return (
|
||||
<div className="field" style={{ gap: 16 }}>
|
||||
<div className="row">
|
||||
<label htmlFor="fb-days" className="label">
|
||||
Időszak
|
||||
</label>
|
||||
<select
|
||||
id="fb-days"
|
||||
className="inp"
|
||||
style={{ maxWidth: 200 }}
|
||||
value={days}
|
||||
onChange={(e) => setDays(Number(e.target.value))}
|
||||
>
|
||||
<option value={7}>az utolsó 7 nap</option>
|
||||
<option value={30}>az utolsó 30 nap</option>
|
||||
<option value={90}>az utolsó 90 nap</option>
|
||||
<option value={3650}>mind</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<section className="card">
|
||||
<h2>Tartalomfajtánként</h2>
|
||||
{total === 0 ? (
|
||||
<p className="muted">Még nincs értékelés ebben az időszakban.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fajta</th>
|
||||
<th>Értékelés</th>
|
||||
<th>Átlag</th>
|
||||
<th>Elégedett (4–5)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.by_kind.map((k) => (
|
||||
<tr key={k.kind}>
|
||||
<td>{KIND_LABELS[k.kind] ?? k.kind}</td>
|
||||
<td className="num">{k.count}</td>
|
||||
<td className="num">
|
||||
{k.kind === "question" ? "–" : avg(k.average)}
|
||||
</td>
|
||||
<td className="num">{pct(k.satisfied_share)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{data.buyers.length > 0 && (
|
||||
<p className="hint">
|
||||
{data.buyers
|
||||
.map(
|
||||
(b) =>
|
||||
`${b.buyer ? "Vásárlók" : "Nem vásárlók"}: ${b.count} értékelés, átlag ${avg(b.average)}`,
|
||||
)
|
||||
.join(" · ")}
|
||||
</p>
|
||||
)}
|
||||
<p className="hint">
|
||||
A kérdésekre adott válaszoknál az „igen, hasznos” 5, a „nem” 1
|
||||
csillagnak számít.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{data.weeks.length > 0 && (
|
||||
<section className="card">
|
||||
<h2>Hetente</h2>
|
||||
<ul className="fb-weeks">
|
||||
{data.weeks.map((w) => (
|
||||
<li key={w.week}>
|
||||
<span className="num">{w.week}</span>
|
||||
<span
|
||||
className="fb-bar"
|
||||
style={{ width: `${(w.average / 5) * 100}%` }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="num">
|
||||
{avg(w.average)} ({w.count})
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{data.tags.length > 0 && (
|
||||
<section className="card">
|
||||
<h2>Címkék</h2>
|
||||
<div className="rate-tags">
|
||||
{data.tags.map((t) => (
|
||||
<span key={t.tag} className="badge">
|
||||
{TAG_LABELS[t.tag] ?? t.tag}: {t.count}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{data.by_model.length > 0 && (
|
||||
<section className="card">
|
||||
<h2>Modellenként és prompt-verziónként</h2>
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fajta</th>
|
||||
<th>Modell</th>
|
||||
<th>Prompt</th>
|
||||
<th>Értékelés</th>
|
||||
<th>Átlag</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.by_model.map((m) => (
|
||||
<tr key={`${m.kind}-${m.model}-${m.prompt_version}`}>
|
||||
<td>{KIND_LABELS[m.kind] ?? m.kind}</td>
|
||||
<td>
|
||||
<code>{m.model}</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>{m.prompt_version}</code>
|
||||
</td>
|
||||
<td className="num">{m.count}</td>
|
||||
<td className="num">{avg(m.average)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="card">
|
||||
<h2>Ajánlanád? (NPS)</h2>
|
||||
{data.nps.answered === 0 ? (
|
||||
<p className="muted">
|
||||
Még senki nem válaszolt.
|
||||
{data.nps.closed
|
||||
? ` ${data.nps.closed} felhasználó bezárta a kérdést.`
|
||||
: ""}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
<strong className="fb-nps">
|
||||
{Math.round(data.nps.score ?? 0)}
|
||||
</strong>{" "}
|
||||
<span className="muted">
|
||||
({data.nps.answered} válasz: {data.nps.promoters} ajánlaná
|
||||
(9–10), {data.nps.passives} semleges (7–8),{" "}
|
||||
{data.nps.detractors} nem ajánlaná (0–6); {data.nps.closed}{" "}
|
||||
bezárta)
|
||||
</span>
|
||||
</p>
|
||||
<p className="hint">
|
||||
Az NPS az ajánlók és a nem ajánlók arányának különbsége, −100 és
|
||||
100 között.
|
||||
</p>
|
||||
{data.nps.comments.length > 0 && (
|
||||
<ul className="fb-comments">
|
||||
{data.nps.comments.map((c, i) => (
|
||||
<li key={i}>
|
||||
<span className="badge">{c.score}</span> {c.comment}{" "}
|
||||
<span className="hint">{formatDate(c.created_at)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Ratings() {
|
||||
const [kind, setKind] = useState("");
|
||||
const [onlyLow, setOnlyLow] = useState(false);
|
||||
const [withComment, setWithComment] = useState(false);
|
||||
const [unreviewed, setUnreviewed] = useState(false);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [data, setData] = useState<{
|
||||
ratings: AdminRating[];
|
||||
total: number;
|
||||
limit: number;
|
||||
} | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [opened, setOpened] = useState<Record<string, unknown>>({});
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const q = new URLSearchParams();
|
||||
if (kind) q.set("kind", kind);
|
||||
if (onlyLow) q.set("max_stars", "2");
|
||||
if (withComment) q.set("with_comment", "true");
|
||||
if (unreviewed) q.set("unreviewed", "true");
|
||||
q.set("offset", String(offset));
|
||||
try {
|
||||
setData(await api(`/admin/ratings?${q}`));
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
}
|
||||
}, [kind, onlyLow, withComment, unreviewed, offset]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
async function reviewed(ids?: string[]) {
|
||||
try {
|
||||
await api("/admin/ratings/reviewed", { body: ids ? { ids } : {} });
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function open(r: AdminRating) {
|
||||
try {
|
||||
const content = await api(`/admin/ratings/${r.id}/content`);
|
||||
setOpened((all) => ({ ...all, [r.id]: content }));
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="card">
|
||||
<div className="row">
|
||||
<select
|
||||
className="inp"
|
||||
style={{ maxWidth: 220 }}
|
||||
value={kind}
|
||||
onChange={(e) => (setOffset(0), setKind(e.target.value))}
|
||||
aria-label="Fajta"
|
||||
>
|
||||
<option value="">Minden fajta</option>
|
||||
{Object.entries(KIND_LABELS).map(([k, label]) => (
|
||||
<option key={k} value={k}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={onlyLow}
|
||||
onChange={(e) => (setOffset(0), setOnlyLow(e.target.checked))}
|
||||
/>
|
||||
Csak 1–2 csillag
|
||||
</label>
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={withComment}
|
||||
onChange={(e) => (setOffset(0), setWithComment(e.target.checked))}
|
||||
/>
|
||||
Csak megjegyzéssel
|
||||
</label>
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={unreviewed}
|
||||
onChange={(e) => (setOffset(0), setUnreviewed(e.target.checked))}
|
||||
/>
|
||||
Csak amit még nem láttam
|
||||
</label>
|
||||
<button type="button" className="btn btn-sm" onClick={() => reviewed()}>
|
||||
Mind láttam
|
||||
</button>
|
||||
</div>
|
||||
{error && <p className="msg msg-error">{error}</p>}
|
||||
{!data ? (
|
||||
<p className="muted">Betöltés…</p>
|
||||
) : data.ratings.length === 0 ? (
|
||||
<p className="muted">Nincs ilyen értékelés.</p>
|
||||
) : (
|
||||
<>
|
||||
<ul className="fb-ratings">
|
||||
{data.ratings.map((r) => (
|
||||
<li
|
||||
key={r.id}
|
||||
className={r.reviewed ? "fb-rating" : "fb-rating is-new"}
|
||||
>
|
||||
<div className="fb-rating-head">
|
||||
<span
|
||||
className={r.stars <= 2 ? "fb-stars is-low" : "fb-stars"}
|
||||
aria-label={`${r.stars} csillag`}
|
||||
>
|
||||
{r.kind === "question"
|
||||
? r.stars >= 4
|
||||
? "👍"
|
||||
: "👎"
|
||||
: stars(r.stars)}
|
||||
</span>
|
||||
<strong>{KIND_LABELS[r.kind] ?? r.kind}</strong>
|
||||
<span className="hint">{formatDate(r.updated_at, true)}</span>
|
||||
{r.buyer && <span className="badge badge-gold">vásárló</span>}
|
||||
<span className="hint">
|
||||
{r.user ? r.user.email : "törölt fiók"} ·{" "}
|
||||
<code>{r.model}</code> · <code>{r.prompt_version}</code>
|
||||
</span>
|
||||
</div>
|
||||
{r.tags.length > 0 && (
|
||||
<div className="rate-tags">
|
||||
{r.tags.map((t) => (
|
||||
<span key={t} className="badge">
|
||||
{TAG_LABELS[t] ?? t}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{r.comment && <p className="feedback-body">{r.comment}</p>}
|
||||
<div className="form-actions">
|
||||
{r.readable ? (
|
||||
opened[r.id] ? null : (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => open(r)}
|
||||
>
|
||||
Szöveg megnyitása
|
||||
</button>
|
||||
)
|
||||
) : (
|
||||
<span className="hint">
|
||||
A szöveget nem engedte megnézni.
|
||||
</span>
|
||||
)}
|
||||
{!r.reviewed && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={() => reviewed([r.id])}
|
||||
>
|
||||
Láttam
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{opened[r.id] !== undefined && (
|
||||
<div className="fb-content">
|
||||
<ContentDump value={opened[r.id]} />
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{data.total > data.limit && (
|
||||
<div className="pager">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={offset === 0}
|
||||
onClick={() => setOffset(Math.max(0, offset - data.limit))}
|
||||
>
|
||||
Előző
|
||||
</button>
|
||||
<span className="num">
|
||||
{offset + 1}–{Math.min(offset + data.limit, data.total)} /{" "}
|
||||
{data.total}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={offset + data.limit >= data.total}
|
||||
onClick={() => setOffset(offset + data.limit)}
|
||||
>
|
||||
Következő
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Any analysis content as headings and paragraphs (every kind has its own shape). */
|
||||
function ContentDump({ value, label }: { value: unknown; label?: string }) {
|
||||
if (value === null || value === undefined || value === "") return null;
|
||||
if (
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean"
|
||||
) {
|
||||
return (
|
||||
<p>
|
||||
{label && <span className="hint">{label}: </span>}
|
||||
{String(value)}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return (
|
||||
<div className="fb-dump">
|
||||
{label && <p className="hint">{label}</p>}
|
||||
{value.map((v, i) => (
|
||||
<ContentDump key={i} value={v} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const entries = Object.entries(value as Record<string, unknown>);
|
||||
const title = entries.find(
|
||||
([k, v]) => (k === "title" || k === "heading") && typeof v === "string",
|
||||
);
|
||||
return (
|
||||
<div className="fb-dump">
|
||||
{label && <p className="hint">{label}</p>}
|
||||
{title && <h4>{String(title[1])}</h4>}
|
||||
{entries
|
||||
.filter(([k]) => !title || k !== title[0])
|
||||
.map(([k, v]) => (
|
||||
<ContentDump key={k} value={v} label={k} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Messages() {
|
||||
const [status, setStatus] = useState("open");
|
||||
const [messages, setMessages] = useState<AdminFeedbackMessage[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const r = await api<{ messages: AdminFeedbackMessage[] }>(
|
||||
`/admin/feedback?status=${status}`,
|
||||
);
|
||||
setMessages(r.messages);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
return (
|
||||
<section className="card">
|
||||
<div className="row">
|
||||
<label htmlFor="fb-status" className="label">
|
||||
Állapot
|
||||
</label>
|
||||
<select
|
||||
id="fb-status"
|
||||
className="inp"
|
||||
style={{ maxWidth: 220 }}
|
||||
value={status}
|
||||
onChange={(e) => setStatus(e.target.value)}
|
||||
>
|
||||
<option value="open">nyitott (új és folyamatban)</option>
|
||||
<option value="new">új</option>
|
||||
<option value="in_progress">folyamatban</option>
|
||||
<option value="done">megoldva</option>
|
||||
<option value="dismissed">elvetve</option>
|
||||
<option value="all">mind</option>
|
||||
</select>
|
||||
</div>
|
||||
{error && <p className="msg msg-error">{error}</p>}
|
||||
{!messages ? (
|
||||
<p className="muted">Betöltés…</p>
|
||||
) : messages.length === 0 ? (
|
||||
<p className="muted">Nincs ilyen üzenet.</p>
|
||||
) : (
|
||||
<ul className="feedback-list">
|
||||
{messages.map((m) => (
|
||||
<MessageItem key={m.id} message={m} onSaved={load} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageItem({
|
||||
message: m,
|
||||
onSaved,
|
||||
}: {
|
||||
message: AdminFeedbackMessage;
|
||||
onSaved: () => Promise<void>;
|
||||
}) {
|
||||
const [note, setNote] = useState(m.admin_note ?? "");
|
||||
const [reply, setReply] = useState(m.reply ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function save(status?: FeedbackStatus) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/admin/feedback/${m.id}`, {
|
||||
method: "PATCH",
|
||||
body: { ...(status ? { status } : {}), admin_note: note, reply },
|
||||
});
|
||||
await onSaved();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<li
|
||||
className={
|
||||
m.status === "new" ? "card feedback-item is-new" : "card feedback-item"
|
||||
}
|
||||
>
|
||||
<div className="feedback-item-head">
|
||||
<span className="badge">{CATEGORY_LABELS[m.category]}</span>
|
||||
<span className={m.status === "new" ? "badge badge-gold" : "badge"}>
|
||||
{ADMIN_STATUS[m.status]}
|
||||
</span>
|
||||
<span className="hint">{formatDate(m.created_at, true)}</span>
|
||||
<span className="hint">
|
||||
{m.user.name ? `${m.user.name} · ` : ""}
|
||||
{m.user.email}
|
||||
{m.user.buyer ? " · vásárló" : ""}
|
||||
</span>
|
||||
</div>
|
||||
<p className="feedback-body">{m.body}</p>
|
||||
{(m.page || m.user_agent) && (
|
||||
<p className="hint">
|
||||
{m.page && (
|
||||
<>
|
||||
Oldal: <code>{m.page}</code>{" "}
|
||||
</>
|
||||
)}
|
||||
{m.user_agent && <>· {m.user_agent}</>}
|
||||
</p>
|
||||
)}
|
||||
<div className="grid-2">
|
||||
<div className="field">
|
||||
<label htmlFor={`note-${m.id}`}>Belső jegyzet (csak te látod)</label>
|
||||
<textarea
|
||||
id={`note-${m.id}`}
|
||||
className="inp"
|
||||
rows={2}
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor={`reply-${m.id}`}>
|
||||
Válasz (a felhasználó a Visszajelzés oldalon látja)
|
||||
</label>
|
||||
<textarea
|
||||
id={`reply-${m.id}`}
|
||||
className="inp"
|
||||
rows={2}
|
||||
value={reply}
|
||||
onChange={(e) => setReply(e.target.value)}
|
||||
/>
|
||||
{m.replied_at && (
|
||||
<span className="hint">
|
||||
Elküldve: {formatDate(m.replied_at, true)} ·{" "}
|
||||
{m.reply_seen ? "elolvasta" : "még nem olvasta"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="msg msg-error">{error}</p>}
|
||||
<div className="form-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
disabled={busy}
|
||||
onClick={() => save()}
|
||||
>
|
||||
Mentés
|
||||
</button>
|
||||
{m.status !== "in_progress" && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy}
|
||||
onClick={() => save("in_progress")}
|
||||
>
|
||||
Folyamatban
|
||||
</button>
|
||||
)}
|
||||
{m.status !== "done" && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy}
|
||||
onClick={() => save("done")}
|
||||
>
|
||||
Megoldva
|
||||
</button>
|
||||
)}
|
||||
{m.status !== "dismissed" && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
disabled={busy}
|
||||
onClick={() => save("dismissed")}
|
||||
>
|
||||
Elvetés
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AdminNav } from "@/components/AdminNav";
|
||||
import { requireMe } from "@/lib/server";
|
||||
|
||||
import { AdminFeedback } from "./AdminFeedback";
|
||||
|
||||
export const metadata: Metadata = { title: "Visszajelzések" };
|
||||
|
||||
export default async function AdminFeedbackPage() {
|
||||
const me = await requireMe("/admin/visszajelzesek");
|
||||
if (!me.user.roles.includes("admin")) notFound();
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 1180 }}>
|
||||
<AdminNav current="/admin/visszajelzesek" />
|
||||
<div className="page-head">
|
||||
<h1>Visszajelzések</h1>
|
||||
<p className="muted">
|
||||
A felhasználók értékelései (csak a saját, kész tartalmukat
|
||||
értékelhetik, egyszer), az üzeneteik és az ajánlási kérdés. Semmi sem
|
||||
nyilvános. Egy elemzés szövegét csak akkor látod, ha a felhasználó
|
||||
megengedte.
|
||||
</p>
|
||||
</div>
|
||||
<AdminFeedback />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -12,8 +12,10 @@ import type { Package, PayMethod } from "@/lib/types";
|
||||
const MAX_MESSAGE = 300;
|
||||
const MAX_NAME = 60;
|
||||
|
||||
const looksLikeEmail = (s: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim());
|
||||
const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();
|
||||
const looksLikeEmail = (s: string) =>
|
||||
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim());
|
||||
const same = (a: string, b: string) =>
|
||||
a.trim().toLowerCase() === b.trim().toLowerCase();
|
||||
|
||||
/**
|
||||
* The gift order: which package, whom it is for and from whom, how it gets
|
||||
@@ -36,7 +38,10 @@ export function GiftForm({
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const id = useId();
|
||||
const start = packages.find((p) => p.id === initial) ?? packages.find((p) => p.id === "couple") ?? packages[0];
|
||||
const start =
|
||||
packages.find((p) => p.id === initial) ??
|
||||
packages.find((p) => p.id === "couple") ??
|
||||
packages[0];
|
||||
const [pkg, setPkg] = useState(start?.id ?? "");
|
||||
const [name, setName] = useState("");
|
||||
const [byEmail, setByEmail] = useState(true);
|
||||
@@ -66,16 +71,19 @@ export function GiftForm({
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const r = await api<{ id: string; url: string | null }>("/gifts/checkout", {
|
||||
body: {
|
||||
package: chosen.id,
|
||||
recipient_name: name.trim(),
|
||||
recipient_email: byEmail ? email.trim() : null,
|
||||
recipient_email_confirm: byEmail ? confirm.trim() : null,
|
||||
from_name: from.trim() || null,
|
||||
message: message.trim() || null,
|
||||
const r = await api<{ id: string; url: string | null }>(
|
||||
"/gifts/checkout",
|
||||
{
|
||||
body: {
|
||||
package: chosen.id,
|
||||
recipient_name: name.trim(),
|
||||
recipient_email: byEmail ? email.trim() : null,
|
||||
recipient_email_confirm: byEmail ? confirm.trim() : null,
|
||||
from_name: from.trim() || null,
|
||||
message: message.trim() || null,
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
if (r.url) {
|
||||
window.location.assign(r.url);
|
||||
return;
|
||||
@@ -93,8 +101,17 @@ export function GiftForm({
|
||||
<legend className="label">Melyik csomagot adod?</legend>
|
||||
<div className="gift-packages">
|
||||
{packages.map((p) => (
|
||||
<label key={p.id} className={p.id === pkg ? "gift-option is-chosen" : "gift-option"}>
|
||||
<input type="radio" name={`${id}-pkg`} value={p.id} checked={p.id === pkg} onChange={() => setPkg(p.id)} />
|
||||
<label
|
||||
key={p.id}
|
||||
className={p.id === pkg ? "gift-option is-chosen" : "gift-option"}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name={`${id}-pkg`}
|
||||
value={p.id}
|
||||
checked={p.id === pkg}
|
||||
onChange={() => setPkg(p.id)}
|
||||
/>
|
||||
<span className="gift-option-head">
|
||||
<strong>{p.name}</strong>
|
||||
<span className="num">{huf(p.price_huf)}</span>
|
||||
@@ -140,16 +157,28 @@ export function GiftForm({
|
||||
<legend className="label">Hogyan kapja meg?</legend>
|
||||
<div className="gift-ways">
|
||||
<label className={byEmail ? "gift-option is-chosen" : "gift-option"}>
|
||||
<input type="radio" name={`${id}-way`} checked={byEmail} onChange={() => setByEmail(true)} />
|
||||
<input
|
||||
type="radio"
|
||||
name={`${id}-way`}
|
||||
checked={byEmail}
|
||||
onChange={() => setByEmail(true)}
|
||||
/>
|
||||
<strong>E-mailben küldjük el neki</strong>
|
||||
<span className="hint">Fizetés után azonnal megkapja a kódot, mellé az utalványt PDF-ben.</span>
|
||||
<span className="hint">
|
||||
Fizetés után azonnal megkapja a kódot, mellé az utalványt PDF-ben.
|
||||
</span>
|
||||
</label>
|
||||
<label className={!byEmail ? "gift-option is-chosen" : "gift-option"}>
|
||||
<input type="radio" name={`${id}-way`} checked={!byEmail} onChange={() => setByEmail(false)} />
|
||||
<input
|
||||
type="radio"
|
||||
name={`${id}-way`}
|
||||
checked={!byEmail}
|
||||
onChange={() => setByEmail(false)}
|
||||
/>
|
||||
<strong>Én adom át</strong>
|
||||
<span className="hint">
|
||||
Letöltöd az utalványt PDF-ben: kinyomtathatod, vagy elküldheted te magad. Később innen is kérheted, hogy
|
||||
e-mailben küldjük el.
|
||||
Letöltöd az utalványt PDF-ben: kinyomtathatod, vagy elküldheted te
|
||||
magad. Később innen is kérheted, hogy e-mailben küldjük el.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
@@ -168,7 +197,9 @@ export function GiftForm({
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor={`${id}-confirm`}>Még egyszer, ellenőrzésképp</label>
|
||||
<label htmlFor={`${id}-confirm`}>
|
||||
Még egyszer, ellenőrzésképp
|
||||
</label>
|
||||
<input
|
||||
id={`${id}-confirm`}
|
||||
className="inp"
|
||||
@@ -180,8 +211,14 @@ export function GiftForm({
|
||||
aria-describedby={`${id}-confirm-msg`}
|
||||
required
|
||||
/>
|
||||
<span id={`${id}-confirm-msg`} className={mismatch ? "msg msg-error" : "hint"} aria-live="polite">
|
||||
{mismatch ? "A két cím nem egyezik." : "Hogy biztosan jó címre menjen."}
|
||||
<span
|
||||
id={`${id}-confirm-msg`}
|
||||
className={mismatch ? "msg msg-error" : "hint"}
|
||||
aria-live="polite"
|
||||
>
|
||||
{mismatch
|
||||
? "A két cím nem egyezik."
|
||||
: "Hogy biztosan jó címre menjen."}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -200,7 +237,8 @@ export function GiftForm({
|
||||
aria-describedby={`${id}-message-hint`}
|
||||
/>
|
||||
<span id={`${id}-message-hint`} className="hint">
|
||||
Rajta lesz az utalványon és a levélben. Link nem lehet benne. {message.length}/{MAX_MESSAGE}
|
||||
Rajta lesz az utalványon és a levélben. Link nem lehet benne.{" "}
|
||||
{message.length}/{MAX_MESSAGE}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -213,14 +251,25 @@ export function GiftForm({
|
||||
{chosen && (
|
||||
<p className="gift-total">
|
||||
<span className="muted">
|
||||
„{chosen.name}” csomag ajándékba{name.trim() ? `, ${name.trim()} részére` : ""}
|
||||
„{chosen.name}” csomag ajándékba
|
||||
{name.trim() ? `, ${name.trim()} részére` : ""}
|
||||
</span>
|
||||
<strong className="num">{huf(chosen.price_huf)}</strong>
|
||||
</p>
|
||||
)}
|
||||
{canPay ? (
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || !chosen || !emailOk || !name.trim()}>
|
||||
{busy ? (stripe ? "Átirányítás…" : "Fizetés…") : stripe ? "Tovább a fizetéshez" : "Megveszem ajándékba"}
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary"
|
||||
disabled={busy || !chosen || !emailOk || !name.trim()}
|
||||
>
|
||||
{busy
|
||||
? stripe
|
||||
? "Átirányítás…"
|
||||
: "Fizetés…"
|
||||
: stripe
|
||||
? "Tovább a fizetéshez"
|
||||
: "Megveszem ajándékba"}
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" className="btn" disabled>
|
||||
@@ -228,22 +277,29 @@ export function GiftForm({
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{canPay === "mock" && <p className="hint">Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.</p>}
|
||||
{canPay === "mock" && (
|
||||
<p className="hint">
|
||||
Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.
|
||||
</p>
|
||||
)}
|
||||
{stripe && (
|
||||
<p className="hint">
|
||||
<span aria-hidden="true">🔒</span> A fizetés a Stripe biztonságos oldalán történik. A számlát te kapod.
|
||||
<span aria-hidden="true">🔒</span> A fizetés a Stripe biztonságos
|
||||
oldalán történik. A számlát te kapod.
|
||||
{termsConsent && (
|
||||
<>
|
||||
{" "}
|
||||
A vásárlástól számított 14 napon belül, amíg a kódot nem váltották be, elállhatsz, és visszatérítjük az
|
||||
árát. A kód beváltásával az elállási jog megszűnik. <Link href="/aszf">ÁSZF</Link>
|
||||
A vásárlástól számított 14 napon belül, amíg a kódot nem váltották
|
||||
be, elállhatsz, és visszatérítjük az árát. A kód beváltásával az
|
||||
elállási jog megszűnik. <Link href="/aszf">ÁSZF</Link>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{canPay === "stripe_test" && (
|
||||
<p className="hint">
|
||||
Stripe tesztmód (csak adminoknak látszik): kártyaszám 4242 4242 4242 4242, bármilyen jövőbeli lejárat és CVC.
|
||||
Stripe tesztmód (csak adminoknak látszik): kártyaszám 4242 4242 4242
|
||||
4242, bármilyen jövőbeli lejárat és CVC.
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
|
||||
@@ -7,14 +7,19 @@ import type { Gift, Package, PublicConfig } from "@/lib/types";
|
||||
|
||||
import { GiftForm } from "./GiftForm";
|
||||
|
||||
export const metadata: Metadata = { title: "Ajándék csomag", robots: { index: false } };
|
||||
export const metadata: Metadata = {
|
||||
title: "Ajándék csomag",
|
||||
robots: { index: false },
|
||||
};
|
||||
|
||||
type Props = { searchParams: Promise<{ csomag?: string }> };
|
||||
|
||||
/** Buying a package as a gift; `?csomag=` picks the package (links on the package cards). */
|
||||
export default async function GiftPage({ searchParams }: Props) {
|
||||
const { csomag } = await searchParams;
|
||||
const me = await requireMe(csomag ? `/ajandek?csomag=${encodeURIComponent(csomag)}` : "/ajandek");
|
||||
const me = await requireMe(
|
||||
csomag ? `/ajandek?csomag=${encodeURIComponent(csomag)}` : "/ajandek",
|
||||
);
|
||||
const [catalog, config, mine] = await Promise.all([
|
||||
backendGet<{ packages: Package[] }>("/v1/packages"),
|
||||
backendGet<PublicConfig>("/v1/config"),
|
||||
@@ -29,8 +34,9 @@ export default async function GiftPage({ searchParams }: Props) {
|
||||
<span className="eyebrow">Ajándék</span>
|
||||
<h1>Ajándékozz csomagot</h1>
|
||||
<p className="muted">
|
||||
Születési képlet, személyre szóló elemzések, kapcsolati összevetés: ajándékba annak, akit szeretsz. Ő egy
|
||||
ajándékkódot kap egy nyomtatható utalvánnyal, és a saját fiókjában váltja be.
|
||||
Születési képlet, személyre szóló elemzések, kapcsolati összevetés:
|
||||
ajándékba annak, akit szeretsz. Ő egy ajándékkódot kap egy nyomtatható
|
||||
utalvánnyal, és a saját fiókjában váltja be.
|
||||
</p>
|
||||
{given > 0 && (
|
||||
<p className="hint">
|
||||
@@ -56,19 +62,26 @@ export default async function GiftPage({ searchParams }: Props) {
|
||||
height={594}
|
||||
alt="Minta ajándékutalvány: a csomag neve, a személyes üzenet, az ajándékkód és a QR-kód"
|
||||
/>
|
||||
<figcaption className="hint">Így néz ki az utalvány (A4-es PDF, nyomtatható)</figcaption>
|
||||
<figcaption className="hint">
|
||||
Így néz ki az utalvány (A4-es PDF, nyomtatható)
|
||||
</figcaption>
|
||||
</figure>
|
||||
<section className="card gift-how" aria-labelledby="gift-how-title">
|
||||
<h2 id="gift-how-title">Hogyan működik?</h2>
|
||||
<ol>
|
||||
<li>Kiválasztod a csomagot, és megírod, kinek szól.</li>
|
||||
<li>Fizetés után elkészül az ajándékkód és az utalvány.</li>
|
||||
<li>E-mailben elküldjük neki, vagy letöltöd a PDF-et, és te adod át.</li>
|
||||
<li>Belép vagy regisztrál, beváltja a kódot, és a csomag az övé.</li>
|
||||
<li>
|
||||
E-mailben elküldjük neki, vagy letöltöd a PDF-et, és te adod át.
|
||||
</li>
|
||||
<li>
|
||||
Belép vagy regisztrál, beváltja a kódot, és a csomag az övé.
|
||||
</li>
|
||||
</ol>
|
||||
<p className="hint">
|
||||
A kód nem jár le, és egyszer váltható be. A számlát te kapod. Ha meggondolod magad, 14 napon belül,
|
||||
beváltás előtt visszakérheted az árát: írj az info@sorsfonalak.hu címre.
|
||||
A kód nem jár le, és egyszer váltható be. A számlát te kapod. Ha
|
||||
meggondolod magad, 14 napon belül, beváltás előtt visszakérheted
|
||||
az árát: írj az info@sorsfonalak.hu címre.
|
||||
</p>
|
||||
</section>
|
||||
</aside>
|
||||
|
||||
@@ -6,8 +6,18 @@ import { api, errorText } from "@/lib/api";
|
||||
import type { Gift } from "@/lib/types";
|
||||
|
||||
const day = (iso: string) =>
|
||||
new Date(iso).toLocaleDateString("hu-HU", { timeZone: "Europe/Budapest", year: "numeric", month: "long", day: "numeric" });
|
||||
const time = (iso: string) => new Date(iso).toLocaleTimeString("hu-HU", { timeZone: "Europe/Budapest", hour: "2-digit", minute: "2-digit" });
|
||||
new Date(iso).toLocaleDateString("hu-HU", {
|
||||
timeZone: "Europe/Budapest",
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
const time = (iso: string) =>
|
||||
new Date(iso).toLocaleTimeString("hu-HU", {
|
||||
timeZone: "Europe/Budapest",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
|
||||
/** The user's gifts: code, state, the card to download, and sending it by e-mail. */
|
||||
export function GiftList({ gifts: initial }: { gifts: Gift[] }) {
|
||||
@@ -15,13 +25,25 @@ export function GiftList({ gifts: initial }: { gifts: Gift[] }) {
|
||||
return (
|
||||
<ul className="gift-list">
|
||||
{gifts.map((g) => (
|
||||
<GiftItem key={g.id} gift={g} onChange={(next) => setGifts((all) => all.map((x) => (x.id === next.id ? next : x)))} />
|
||||
<GiftItem
|
||||
key={g.id}
|
||||
gift={g}
|
||||
onChange={(next) =>
|
||||
setGifts((all) => all.map((x) => (x.id === next.id ? next : x)))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void }) {
|
||||
function GiftItem({
|
||||
gift,
|
||||
onChange,
|
||||
}: {
|
||||
gift: Gift;
|
||||
onChange: (g: Gift) => void;
|
||||
}) {
|
||||
const id = useId();
|
||||
const [sending, setSending] = useState(false);
|
||||
const [email, setEmail] = useState("");
|
||||
@@ -31,7 +53,9 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
|
||||
const [sent, setSent] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const open = gift.status === "open";
|
||||
const mismatch = confirm.trim() !== "" && email.trim().toLowerCase() !== confirm.trim().toLowerCase();
|
||||
const mismatch =
|
||||
confirm.trim() !== "" &&
|
||||
email.trim().toLowerCase() !== confirm.trim().toLowerCase();
|
||||
|
||||
async function send(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
@@ -39,7 +63,10 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
|
||||
setError(null);
|
||||
try {
|
||||
const next = await api<Gift>(`/gifts/${gift.id}/send`, {
|
||||
body: { recipient_email: email.trim(), recipient_email_confirm: confirm.trim() },
|
||||
body: {
|
||||
recipient_email: email.trim(),
|
||||
recipient_email_confirm: confirm.trim(),
|
||||
},
|
||||
});
|
||||
onChange(next);
|
||||
setSent(next.recipient_email);
|
||||
@@ -69,14 +96,23 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
|
||||
<div>
|
||||
<h2 className="gift-item-title">
|
||||
„{gift.package.name ?? gift.package.id}” csomag
|
||||
{gift.recipient_name && <span className="gift-item-for"> {gift.recipient_name} részére</span>}
|
||||
{gift.recipient_name && (
|
||||
<span className="gift-item-for">
|
||||
{" "}
|
||||
{gift.recipient_name} részére
|
||||
</span>
|
||||
)}
|
||||
</h2>
|
||||
<span className="hint">Vásárolva: {day(gift.paid_at)}</span>
|
||||
</div>
|
||||
{gift.status === "redeemed" ? (
|
||||
<span className="badge">Beváltva{gift.redeemed_at ? `: ${day(gift.redeemed_at)}` : ""}</span>
|
||||
<span className="badge">
|
||||
Beváltva{gift.redeemed_at ? `: ${day(gift.redeemed_at)}` : ""}
|
||||
</span>
|
||||
) : gift.status === "refunded" ? (
|
||||
<span className="badge">Visszatérítve{gift.refunded_at ? `: ${day(gift.refunded_at)}` : ""}</span>
|
||||
<span className="badge">
|
||||
Visszatérítve{gift.refunded_at ? `: ${day(gift.refunded_at)}` : ""}
|
||||
</span>
|
||||
) : (
|
||||
<span className="badge badge-gold">Még nincs beváltva</span>
|
||||
)}
|
||||
@@ -101,26 +137,46 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
|
||||
) : (
|
||||
"Nem e-mailben ment."
|
||||
)}
|
||||
{gift.from_name && <span className="hint"> · Kitől: {gift.from_name}</span>}
|
||||
{gift.from_name && (
|
||||
<span className="hint"> · Kitől: {gift.from_name}</span>
|
||||
)}
|
||||
</p>
|
||||
{gift.message && <blockquote className="gift-message">{gift.message}</blockquote>}
|
||||
{gift.message && (
|
||||
<blockquote className="gift-message">{gift.message}</blockquote>
|
||||
)}
|
||||
|
||||
{gift.status === "refunded" ? (
|
||||
<p className="hint">Elálltál a vásárlástól: a kód már nem érvényes, az árát visszatérítettük.</p>
|
||||
<p className="hint">
|
||||
Elálltál a vásárlástól: a kód már nem érvényes, az árát
|
||||
visszatérítettük.
|
||||
</p>
|
||||
) : (
|
||||
<div className="form-actions">
|
||||
<a className="btn btn-primary btn-sm" href={`/api/v1/gifts/${gift.id}/card.pdf`} download>
|
||||
<a
|
||||
className="btn btn-primary btn-sm"
|
||||
href={`/api/v1/gifts/${gift.id}/card.pdf`}
|
||||
download
|
||||
>
|
||||
Utalvány letöltése (PDF)
|
||||
</a>
|
||||
{open && gift.can_send && !sending && (
|
||||
<button type="button" className="btn btn-sm" onClick={() => setSending(true)}>
|
||||
{gift.recipient_email ? "Újraküldés e-mailben" : "Küldés e-mailben"}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => setSending(true)}
|
||||
>
|
||||
{gift.recipient_email
|
||||
? "Újraküldés e-mailben"
|
||||
: "Küldés e-mailben"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{open && !gift.can_send && gift.sendings > 0 && (
|
||||
<p className="hint">E-mailben már többször elküldtük. Ha nem érkezett meg, töltsd le az utalványt, és küldd el te.</p>
|
||||
<p className="hint">
|
||||
E-mailben már többször elküldtük. Ha nem érkezett meg, töltsd le az
|
||||
utalványt, és küldd el te.
|
||||
</p>
|
||||
)}
|
||||
{sent && (
|
||||
<p className="msg msg-ok" role="status">
|
||||
@@ -145,7 +201,9 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor={`${id}-confirm`}>Még egyszer, ellenőrzésképp</label>
|
||||
<label htmlFor={`${id}-confirm`}>
|
||||
Még egyszer, ellenőrzésképp
|
||||
</label>
|
||||
<input
|
||||
id={`${id}-confirm`}
|
||||
className="inp"
|
||||
@@ -156,11 +214,15 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
|
||||
aria-invalid={mismatch || undefined}
|
||||
required
|
||||
/>
|
||||
{mismatch && <span className="msg msg-error">A két cím nem egyezik.</span>}
|
||||
{mismatch && (
|
||||
<span className="msg msg-error">A két cím nem egyezik.</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{gift.send_again_at && (
|
||||
<p className="hint">Most küldtük el: {time(gift.send_again_at)} után küldheted újra.</p>
|
||||
<p className="hint">
|
||||
Most küldtük el: {time(gift.send_again_at)} után küldheted újra.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
@@ -168,10 +230,18 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
|
||||
</p>
|
||||
)}
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || mismatch || !email.trim()}>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={busy || mismatch || !email.trim()}
|
||||
>
|
||||
{busy ? "Küldés…" : "Elküldöm"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setSending(false)}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={() => setSending(false)}
|
||||
>
|
||||
Mégse
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,10 @@ import type { Gift } from "@/lib/types";
|
||||
|
||||
import { GiftList } from "./GiftList";
|
||||
|
||||
export const metadata: Metadata = { title: "Ajándékaim", robots: { index: false } };
|
||||
export const metadata: Metadata = {
|
||||
title: "Ajándékaim",
|
||||
robots: { index: false },
|
||||
};
|
||||
|
||||
/** The packages the user bought as gifts: codes, cards to download, sending them by e-mail. */
|
||||
export default async function MyGiftsPage() {
|
||||
@@ -19,8 +22,9 @@ export default async function MyGiftsPage() {
|
||||
<span className="eyebrow">Ajándék</span>
|
||||
<h1>Ajándékaim</h1>
|
||||
<p className="muted">
|
||||
Az ajándékba vett csomagjaid. Ha nem e-mailben adnád át, töltsd le az utalványt PDF-ben: kinyomtathatod, vagy
|
||||
elküldheted te magad. Amíg nem váltották be, e-mailben is elküldhetjük, akár másik címre.
|
||||
Az ajándékba vett csomagjaid. Ha nem e-mailben adnád át, töltsd le az
|
||||
utalványt PDF-ben: kinyomtathatod, vagy elküldheted te magad. Amíg nem
|
||||
váltották be, e-mailben is elküldhetjük, akár másik címre.
|
||||
</p>
|
||||
<div className="form-actions">
|
||||
<Link className="btn btn-primary" href="/ajandek">
|
||||
@@ -32,13 +36,17 @@ export default async function MyGiftsPage() {
|
||||
{gifts.length === 0 ? (
|
||||
<section className="card">
|
||||
<p className="muted">
|
||||
Még nem vettél ajándékot. Egy csomagot bárkinek megvehetsz: e-mailben kapja meg, vagy te adod át egy
|
||||
nyomtatható utalvánnyal. <Link href="/ajandek">Ajándékozás →</Link>
|
||||
Még nem vettél ajándékot. Egy csomagot bárkinek megvehetsz:
|
||||
e-mailben kapja meg, vagy te adod át egy nyomtatható utalvánnyal.{" "}
|
||||
<Link href="/ajandek">Ajándékozás →</Link>
|
||||
</p>
|
||||
</section>
|
||||
) : (
|
||||
// A new gift (back from paying) or a change starts the list afresh.
|
||||
<GiftList key={gifts.map((g) => `${g.id}:${g.status}:${g.sendings}`).join()} gifts={gifts} />
|
||||
<GiftList
|
||||
key={gifts.map((g) => `${g.id}:${g.status}:${g.sendings}`).join()}
|
||||
gifts={gifts}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -476,10 +476,19 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.danger-box { display: flex; flex-direction: column; gap: 12px; padding: 16px; border: 1px solid var(--danger); border-radius: var(--radius); }
|
||||
|
||||
/* Admin */
|
||||
.admin-nav { display: flex; gap: 4px; border-bottom: 1px solid var(--line); margin-bottom: 4px; overflow-x: auto; }
|
||||
/* The line under the menu is a shadow inside it: the current page's underline
|
||||
covers it without hanging out (that made a vertical scrollbar). */
|
||||
.admin-nav {
|
||||
display: flex; gap: 4px; margin-bottom: 4px; box-shadow: inset 0 -1px 0 var(--line);
|
||||
overflow-x: auto; overflow-y: hidden; scrollbar-width: thin;
|
||||
}
|
||||
.admin-nav a {
|
||||
padding: 10px 14px; min-height: 44px; display: inline-flex; align-items: center; color: var(--muted);
|
||||
text-decoration: none; border-bottom: 2px solid transparent; margin-bottom: -1px; white-space: nowrap;
|
||||
padding: 10px 14px; min-height: 44px; display: inline-flex; align-items: center; gap: 6px; color: var(--muted);
|
||||
text-decoration: none; border-bottom: 2px solid transparent; white-space: nowrap;
|
||||
}
|
||||
.admin-nav-count {
|
||||
min-width: 20px; height: 20px; padding: 0 6px; border-radius: 999px; background: var(--gold); color: var(--gold-ink);
|
||||
font-size: 12px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.admin-nav a:hover { color: var(--ink); }
|
||||
.admin-nav a[aria-current="page"] { color: var(--gold); border-bottom-color: var(--gold); }
|
||||
@@ -1581,3 +1590,83 @@ span.tarot-fan-card { cursor: default; }
|
||||
.gift-sample img { max-width: 240px; }
|
||||
.gift-submit .btn { width: 100%; }
|
||||
}
|
||||
|
||||
/* Feedback: rating what one got, the feedback page, the recommendation bar, the admin view */
|
||||
.rate { display: flex; flex-direction: column; gap: 10px; margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); }
|
||||
.rate-thumbs { margin-top: 10px; padding-top: 10px; }
|
||||
.rate-row { display: flex; align-items: center; gap: 10px 14px; flex-wrap: wrap; }
|
||||
.rate-question { font-size: 14px; color: var(--ink-2); }
|
||||
.rate-buttons { display: inline-flex; gap: 2px; }
|
||||
.rate-star, .rate-thumb {
|
||||
min-width: 40px; min-height: 40px; padding: 0 4px; border: 0; background: transparent; cursor: pointer;
|
||||
font-size: 24px; line-height: 1; color: var(--line-2); border-radius: 8px;
|
||||
}
|
||||
.rate-star.is-on { color: var(--gold); }
|
||||
.rate-star:hover, .rate-thumb:hover { background: rgba(217, 180, 106, 0.08); }
|
||||
.rate-thumb { font-size: 20px; filter: grayscale(1); opacity: 0.6; }
|
||||
.rate-thumb.is-on { filter: none; opacity: 1; background: rgba(217, 180, 106, 0.12); }
|
||||
.rate-star:focus-visible, .rate-thumb:focus-visible, .rate-tag:focus-visible { outline: 2px solid var(--gold); outline-offset: 2px; }
|
||||
.rate-details { display: flex; flex-direction: column; gap: 10px; }
|
||||
.rate-details .hint, .rate-details .check { margin: 0; }
|
||||
.rate-tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.rate-tag {
|
||||
min-height: 34px; padding: 0 12px; border-radius: 999px; border: 1px solid var(--line-2); background: transparent;
|
||||
color: var(--ink-2); font: 400 13px var(--font-body); cursor: pointer;
|
||||
}
|
||||
.rate-tag.is-on { border-color: var(--gold); color: var(--gold); background: rgba(217, 180, 106, 0.08); }
|
||||
.qa-answer .rate { margin-top: 10px; }
|
||||
.menu-dot { display: inline-block; width: 8px; height: 8px; margin-left: 6px; border-radius: 50%; background: var(--gold); vertical-align: middle; }
|
||||
.feedback-form { gap: 16px; }
|
||||
.feedback-kinds { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.feedback-kind {
|
||||
display: inline-flex; align-items: center; gap: 8px; min-height: 40px; padding: 0 14px; cursor: pointer;
|
||||
border: 1px solid var(--line-2); border-radius: 999px; font-size: 14px; color: var(--ink-2);
|
||||
}
|
||||
.feedback-kind input { accent-color: var(--gold); margin: 0; }
|
||||
.feedback-kind.is-on { border-color: var(--gold); color: var(--ink); }
|
||||
.feedback-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 12px; }
|
||||
.feedback-item { gap: 10px; padding: 18px 20px; }
|
||||
.feedback-item.is-new { border-color: rgba(217, 180, 106, 0.5); }
|
||||
.feedback-item-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.feedback-body { margin: 0; white-space: pre-line; color: var(--ink-2); }
|
||||
.feedback-reply { padding: 10px 14px; border-left: 2px solid var(--gold); background: rgba(217, 180, 106, 0.06); border-radius: 0 8px 8px 0; }
|
||||
.feedback-reply p { margin: 4px 0 0; white-space: pre-line; }
|
||||
.nps {
|
||||
max-width: 1180px; margin: 12px auto 0; padding: 12px 16px; display: flex; gap: 12px; align-items: flex-start;
|
||||
background: var(--panel); border: 1px solid rgba(217, 180, 106, 0.4); border-radius: 12px; width: calc(100% - 32px);
|
||||
}
|
||||
.nps-main { flex: 1; display: flex; flex-direction: column; gap: 8px; min-width: 0; }
|
||||
.nps-question, .nps-thanks { margin: 0; font-weight: 500; }
|
||||
.nps-thanks { flex: 1; align-self: center; }
|
||||
.nps-scale { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.nps-score {
|
||||
min-width: 38px; min-height: 38px; border-radius: 8px; border: 1px solid var(--line-2); background: var(--panel-2);
|
||||
color: var(--ink); font: 500 14px var(--font-body); cursor: pointer;
|
||||
}
|
||||
.nps-score:hover { border-color: var(--gold); color: var(--gold); }
|
||||
/* The scale's two ends under it, as wide as the eleven buttons. */
|
||||
.nps-scale-wrap { display: inline-flex; flex-direction: column; gap: 4px; align-self: flex-start; max-width: 100%; }
|
||||
.nps-ends { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.nps-comment { display: flex; flex-direction: column; gap: 6px; max-width: 560px; }
|
||||
.nps-close { border: 0; background: transparent; color: var(--muted); font-size: 24px; line-height: 1; cursor: pointer; min-width: 36px; min-height: 36px; border-radius: 8px; }
|
||||
.nps-close:hover { color: var(--ink); }
|
||||
.tabs-row { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.fb-weeks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||
.fb-weeks li { display: grid; grid-template-columns: 110px minmax(0, 1fr) 90px; gap: 10px; align-items: center; font-size: 14px; }
|
||||
.fb-bar { display: block; height: 10px; border-radius: 5px; background: var(--gold); min-width: 4px; }
|
||||
.fb-nps { font-size: 34px; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.fb-comments { margin: 0; padding-left: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; font-size: 14px; }
|
||||
.fb-ratings { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.fb-rating { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel-2); }
|
||||
.fb-rating.is-new { border-color: rgba(217, 180, 106, 0.5); }
|
||||
.fb-rating-head { display: flex; align-items: center; gap: 8px 12px; flex-wrap: wrap; }
|
||||
.fb-stars { color: var(--gold); letter-spacing: 1px; }
|
||||
.fb-stars.is-low { color: var(--danger); }
|
||||
.fb-content { max-height: 420px; overflow-y: auto; padding: 12px 14px; border: 1px solid var(--line); border-radius: var(--radius); font-size: 14px; }
|
||||
.fb-dump { display: flex; flex-direction: column; gap: 6px; }
|
||||
.fb-dump h4 { margin: 8px 0 0; font-family: var(--font-display); font-size: 18px; }
|
||||
.fb-dump p { margin: 0; white-space: pre-line; }
|
||||
@media (max-width: 640px) {
|
||||
.fb-weeks li { grid-template-columns: 90px minmax(0, 1fr) 70px; }
|
||||
.nps-score { min-width: 34px; }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Cormorant_Garamond, Inter } from "next/font/google";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { NightSky } from "@/components/NightSky";
|
||||
import { NpsBanner } from "@/components/NpsBanner";
|
||||
import { PaymentReturn } from "@/components/PaymentReturn";
|
||||
import { SiteHeader } from "@/components/SiteHeader";
|
||||
import { ValidationMessages } from "@/components/ValidationMessages";
|
||||
@@ -35,6 +36,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
<NightSky />
|
||||
<ValidationMessages />
|
||||
{me && <SiteHeader me={me} />}
|
||||
{me?.nps_due && <NpsBanner />}
|
||||
{children}
|
||||
{me && (
|
||||
<Suspense fallback={null}>
|
||||
|
||||
@@ -69,6 +69,21 @@ const DATA: [string, string, string][] = [
|
||||
"Not sending further invitations to them",
|
||||
"Legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"Your ratings (stars, tags, comment) and your answer to the recommendation question; whether you are a buyer",
|
||||
"Measuring and improving the quality of the service",
|
||||
"Legitimate interest (Art. 6(1)(f)); giving them is voluntary",
|
||||
],
|
||||
[
|
||||
"The text of the rated reading or answer, if you allow us to look at it when rating",
|
||||
"Looking into the faults of that reading, improving the texts",
|
||||
"Consent (Art. 6(1)(a)); you can withdraw it at any time by changing your rating",
|
||||
],
|
||||
[
|
||||
"The messages you send on the Feedback page, the page you sent them from, your browser type, and our reply",
|
||||
"Fixing bugs, answering questions",
|
||||
"Legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"IP address, browser details, request times (server logs)",
|
||||
"Security, troubleshooting, preventing abuse",
|
||||
@@ -133,6 +148,10 @@ export default async function PrivacyPolicyPage() {
|
||||
the payment's ID, the amount and your billing details, which we keep for the period required by
|
||||
accounting law (8 years), even after your account is deleted.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Feedback:</strong> your ratings and messages are not public; only we see them. We look at the text of a
|
||||
reading only if you allow it when rating.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Shared links:</strong> if you share a chart, anyone you send the link to sees the chart drawing and
|
||||
the latest short summary. It shows no name or birth data, search engines do not list it, and you can revoke
|
||||
@@ -262,6 +281,10 @@ export default async function PrivacyPolicyPage() {
|
||||
unsubscribe link.
|
||||
</li>
|
||||
<li>Waitlist addresses: until you sign up, or until you ask us to delete them.</li>
|
||||
<li>
|
||||
Messages sent on the Feedback page: until you delete your account. The stars and tags of ratings are kept
|
||||
after that as statistics, without your name and comment.
|
||||
</li>
|
||||
<li>Data needed for invoicing: for the period required by accounting law (8 years).</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { CATEGORY_LABELS, STATUS_LABELS } from "@/lib/feedback";
|
||||
import type { FeedbackCategory, FeedbackMessage } from "@/lib/types";
|
||||
|
||||
const MAX_BODY = 2000;
|
||||
|
||||
const PLACEHOLDERS: Record<FeedbackCategory, string> = {
|
||||
bug: "Mi történt, és mit vártál helyette? Melyik oldalon, milyen eszközön?",
|
||||
idea: "Mi hiányzik, mit csinálnál másképp?",
|
||||
question: "Miben segíthetünk?",
|
||||
other: "Amit el szeretnél mondani.",
|
||||
};
|
||||
|
||||
const day = (iso: string) =>
|
||||
new Date(iso).toLocaleDateString("hu-HU", {
|
||||
timeZone: "Europe/Budapest",
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
/** The form, then the user's earlier messages with their state and our replies. */
|
||||
export function Feedback({
|
||||
initialCategory,
|
||||
from,
|
||||
}: {
|
||||
initialCategory: FeedbackCategory;
|
||||
from: string | null;
|
||||
}) {
|
||||
const id = useId();
|
||||
const [category, setCategory] = useState<FeedbackCategory>(initialCategory);
|
||||
const [body, setBody] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sent, setSent] = useState(false);
|
||||
const [messages, setMessages] = useState<FeedbackMessage[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api<{ messages: FeedbackMessage[] }>("/feedback")
|
||||
.then((r) => {
|
||||
setMessages(r.messages);
|
||||
// The replies are read now.
|
||||
if (r.messages.some((m) => m.reply_new))
|
||||
api("/feedback/seen", { method: "POST", body: {} }).catch(() => {});
|
||||
})
|
||||
.catch(() => setMessages([]));
|
||||
}, []);
|
||||
|
||||
async function send(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setSent(false);
|
||||
try {
|
||||
const m = await api<FeedbackMessage>("/feedback", {
|
||||
body: { category, body, page: from },
|
||||
});
|
||||
setMessages((all) => [m, ...(all ?? [])]);
|
||||
setBody("");
|
||||
setSent(true);
|
||||
} catch (err) {
|
||||
setError(errorText(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<form className="card feedback-form" onSubmit={send}>
|
||||
<fieldset className="gift-set">
|
||||
<legend className="label">Miről szól?</legend>
|
||||
<div className="feedback-kinds">
|
||||
{(Object.keys(CATEGORY_LABELS) as FeedbackCategory[]).map((c) => (
|
||||
<label
|
||||
key={c}
|
||||
className={
|
||||
c === category ? "feedback-kind is-on" : "feedback-kind"
|
||||
}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name={`${id}-kind`}
|
||||
checked={c === category}
|
||||
onChange={() => setCategory(c)}
|
||||
/>
|
||||
{CATEGORY_LABELS[c]}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<div className="field">
|
||||
<label htmlFor={`${id}-body`}>Üzenet</label>
|
||||
<textarea
|
||||
id={`${id}-body`}
|
||||
className="inp"
|
||||
rows={6}
|
||||
maxLength={MAX_BODY}
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
placeholder={PLACEHOLDERS[category]}
|
||||
required
|
||||
/>
|
||||
<span className="hint">
|
||||
{from
|
||||
? `Az oldal, ahonnan jöttél (${from}), és a böngésződ típusa is velemegy, hogy könnyebb legyen megtalálni a hibát. `
|
||||
: ""}
|
||||
{body.length}/{MAX_BODY}
|
||||
</span>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{sent && (
|
||||
<p className="msg msg-ok" role="status">
|
||||
Köszönjük, megkaptuk! Ha válaszolunk, lent látod.
|
||||
</p>
|
||||
)}
|
||||
<div className="form-actions">
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary"
|
||||
disabled={busy || !body.trim()}
|
||||
>
|
||||
{busy ? "Küldés…" : "Elküldöm"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{messages && messages.length > 0 && (
|
||||
<section className="field" aria-labelledby="my-feedback-title">
|
||||
<h2 id="my-feedback-title">Korábbi üzeneteid</h2>
|
||||
<ul className="feedback-list">
|
||||
{messages.map((m) => (
|
||||
<li key={m.id} className="card feedback-item">
|
||||
<div className="feedback-item-head">
|
||||
<span className="badge">{CATEGORY_LABELS[m.category]}</span>
|
||||
<span
|
||||
className={
|
||||
m.status === "done" ? "badge badge-gold" : "badge"
|
||||
}
|
||||
>
|
||||
{STATUS_LABELS[m.status]}
|
||||
</span>
|
||||
<span className="hint">{day(m.created_at)}</span>
|
||||
</div>
|
||||
<p className="feedback-body">{m.body}</p>
|
||||
{m.reply && (
|
||||
<div
|
||||
className={
|
||||
m.reply_new ? "feedback-reply is-new" : "feedback-reply"
|
||||
}
|
||||
>
|
||||
<span className="eyebrow">
|
||||
A válaszunk{m.replied_at ? ` · ${day(m.replied_at)}` : ""}
|
||||
{m.reply_new ? " · új" : ""}
|
||||
</span>
|
||||
<p>{m.reply}</p>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Metadata } from "next";
|
||||
|
||||
import { requireMe } from "@/lib/server";
|
||||
import type { FeedbackCategory } from "@/lib/types";
|
||||
|
||||
import { Feedback } from "./Feedback";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Visszajelzés",
|
||||
robots: { index: false },
|
||||
};
|
||||
|
||||
type Props = { searchParams: Promise<{ tipus?: string; honnan?: string }> };
|
||||
|
||||
const CATEGORIES: FeedbackCategory[] = ["bug", "idea", "question", "other"];
|
||||
|
||||
/** Feedback to the operator: bugs, ideas, questions, and the replies to them. */
|
||||
export default async function FeedbackPage({ searchParams }: Props) {
|
||||
const { tipus, honnan } = await searchParams;
|
||||
await requireMe("/visszajelzes");
|
||||
const category = CATEGORIES.find((c) => c === tipus) ?? "bug";
|
||||
const from =
|
||||
honnan && honnan.startsWith("/") && !honnan.startsWith("//")
|
||||
? honnan.slice(0, 300)
|
||||
: null;
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 760 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Visszajelzés</span>
|
||||
<h1>Írj nekünk</h1>
|
||||
<p className="muted">
|
||||
Hibát találtál, van egy ötleted, vagy kérdésed van? Írd meg itt:
|
||||
elolvassuk, és ha válaszolunk, a válaszunkat ezen az oldalon látod.
|
||||
Amit írsz, csak mi látjuk.
|
||||
</p>
|
||||
</div>
|
||||
<Feedback initialCategory={category} from={from} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -2,11 +2,14 @@ import Link from "next/link";
|
||||
|
||||
import type { Role } from "@/lib/types";
|
||||
|
||||
import { FeedbackCount } from "./FeedbackCount";
|
||||
|
||||
const PAGES = [
|
||||
{ href: "/admin", label: "Felhasználók" },
|
||||
{ href: "/admin/meghivok", label: "Meghívók" },
|
||||
{ href: "/admin/promokodok", label: "Promókódok" },
|
||||
{ href: "/admin/ajandekok", label: "Ajándékok" },
|
||||
{ href: "/admin/visszajelzesek", label: "Visszajelzések", count: true },
|
||||
{ href: "/admin/hires-emberek", label: "Híres emberek", creator: true },
|
||||
{ href: "/admin/promptok", label: "Promptok" },
|
||||
{ href: "/admin/modellek", label: "Modellek" },
|
||||
@@ -26,6 +29,7 @@ export function AdminNav({ current, roles }: { current: string; roles?: Role[] }
|
||||
{PAGES.filter((p) => admin || ("creator" in p && p.creator)).map((p) => (
|
||||
<Link key={p.href} href={p.href} aria-current={p.href === current ? "page" : undefined}>
|
||||
{p.label}
|
||||
{"count" in p && p.count && <FeedbackCount />}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@@ -8,6 +8,8 @@ import type { PayMethod, Question, UnitBalance } from "@/lib/types";
|
||||
|
||||
import { AnalysisLoading } from "./AnalysisLoading";
|
||||
import { PackageChooser } from "./PackageCards";
|
||||
import { RateContent } from "./RateContent";
|
||||
import { ReportLink } from "./ReportLink";
|
||||
import { RegenerateButton } from "./RegenerateButton";
|
||||
import { RetryNotice } from "./RetryNotice";
|
||||
import { Paragraphs } from "./Rich";
|
||||
@@ -174,6 +176,7 @@ export function AnalysisQuestions({
|
||||
<RegenerateButton<Question> url={`/admin/questions/${q.id}/regenerate`} onStarted={replace} />
|
||||
)}
|
||||
<Paragraphs text={q.answer} />
|
||||
<RateContent questionId={q.id} thumbs />
|
||||
</div>
|
||||
) : q.status === "failed" ? (
|
||||
<div className="qa-answer">
|
||||
@@ -183,7 +186,7 @@ export function AnalysisQuestions({
|
||||
<p className="msg msg-error" role="alert">
|
||||
Erre többszöri próbálkozás után sem sikerült válaszolni
|
||||
{q.credits_charged > 0 ? ". A kérdést visszaadtuk, így ingyen újra felteheted" : ""}. Kérdezz újra egy
|
||||
kicsit később.
|
||||
kicsit később. Ha újra nem sikerül: <ReportLink />.
|
||||
</p>
|
||||
{isAdmin && q.error && <p className="hint">Hiba: {q.error}</p>}
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { api } from "@/lib/api";
|
||||
import type { Analysis } from "@/lib/types";
|
||||
|
||||
import { AnalysisLoading } from "./AnalysisLoading";
|
||||
import { RateContent } from "./RateContent";
|
||||
import { RegenerateButton } from "./RegenerateButton";
|
||||
import { RetryNotice } from "./RetryNotice";
|
||||
import { Rich } from "./Rich";
|
||||
@@ -90,6 +91,7 @@ export function ChartSummary({
|
||||
<p className="summary-text" lang={summary?.language}>
|
||||
<Rich text={content.summary ?? ""} />
|
||||
</p>
|
||||
{summary && <RateContent analysisId={summary.id} />}
|
||||
<ShareChart
|
||||
chartId={chartId}
|
||||
rewardGranted={shareRewardGranted}
|
||||
|
||||
@@ -10,6 +10,8 @@ import { AI_SHORT } from "./AiNote";
|
||||
import { AnalysisLoading } from "./AnalysisLoading";
|
||||
import { PackageChooser } from "./PackageCards";
|
||||
import { QuestionsDock } from "./QuestionsDock";
|
||||
import { RateContent } from "./RateContent";
|
||||
import { ReportLink } from "./ReportLink";
|
||||
import { RegenerateButton } from "./RegenerateButton";
|
||||
import { RetryNotice } from "./RetryNotice";
|
||||
import { AnalysisView } from "./AnalysisView";
|
||||
@@ -156,6 +158,7 @@ export function DetailedAnalysis({
|
||||
)}
|
||||
{note && <p className="hint">{note}</p>}
|
||||
<AnalysisView content={analysis.content} kind={target.kind} language={analysis.language} />
|
||||
<RateContent analysisId={analysis.id} />
|
||||
{questionsLeft !== undefined && (
|
||||
<QuestionsDock
|
||||
analysisId={analysis.id}
|
||||
@@ -200,7 +203,8 @@ export function DetailedAnalysis({
|
||||
Az elemzés többszöri próbálkozás után sem készült el.
|
||||
{analysis.credits_charged === 0
|
||||
? " Próbáld újra."
|
||||
: " A felhasznált egységet visszaadtuk, így ingyen újra kérheted."}
|
||||
: " A felhasznált egységet visszaadtuk, így ingyen újra kérheted."}{" "}
|
||||
Ha újra nem sikerül: <ReportLink />.
|
||||
</p>
|
||||
{isAdmin && analysis.error && <p className="hint">Hiba: {analysis.error}</p>}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
/** How much new feedback there is (the admin menu): messages and ratings to look at. */
|
||||
export function FeedbackCount() {
|
||||
const [count, setCount] = useState(0);
|
||||
useEffect(() => {
|
||||
api<{ total: number }>("/admin/feedback/count")
|
||||
.then((r) => setCount(r.total))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
if (count === 0) return null;
|
||||
return (
|
||||
<span className="admin-nav-count" aria-label={`${count} új`}>
|
||||
{count}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/**
|
||||
* "Would you recommend us?" (0–10), once, as a bar under the header (no
|
||||
* pop-up, no e-mail). Closing it counts: it does not come again.
|
||||
*/
|
||||
export function NpsBanner() {
|
||||
const [shown, setShown] = useState(true);
|
||||
const [score, setScore] = useState<number | null>(null);
|
||||
const [comment, setComment] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [thanks, setThanks] = useState(false);
|
||||
|
||||
async function send(value: number | null, withComment: boolean) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api("/nps", {
|
||||
body: {
|
||||
score: value,
|
||||
comment: withComment ? comment.trim() || null : null,
|
||||
},
|
||||
});
|
||||
if (value === null) setShown(false);
|
||||
else if (withComment) setThanks(true);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!shown) return null;
|
||||
if (thanks) {
|
||||
return (
|
||||
<aside className="nps" aria-label="Köszönjük">
|
||||
<p className="nps-thanks">
|
||||
Köszönjük, hogy segítesz jobbá tenni a Sorsfonalakat!
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm"
|
||||
onClick={() => setShown(false)}
|
||||
>
|
||||
Bezárás
|
||||
</button>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<aside className="nps" aria-labelledby="nps-question">
|
||||
<div className="nps-main">
|
||||
<p id="nps-question" className="nps-question">
|
||||
Mennyire ajánlanád a Sorsfonalakat egy barátodnak?
|
||||
</p>
|
||||
{score === null ? (
|
||||
<div className="nps-scale-wrap">
|
||||
<div
|
||||
className="nps-scale"
|
||||
role="group"
|
||||
aria-labelledby="nps-question"
|
||||
>
|
||||
{Array.from({ length: 11 }, (_, n) => (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
className="nps-score"
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setScore(n);
|
||||
await send(n, false);
|
||||
}}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="nps-ends hint" aria-hidden="true">
|
||||
<span>egyáltalán nem</span>
|
||||
<span>nagyon</span>
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
className="nps-comment"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
send(score, true);
|
||||
}}
|
||||
>
|
||||
<label htmlFor="nps-why" className="hint">
|
||||
Köszönjük! Mi a legfontosabb oka? (nem kötelező)
|
||||
</label>
|
||||
<div className="redeem-row">
|
||||
<input
|
||||
id="nps-why"
|
||||
className="inp"
|
||||
maxLength={1000}
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={busy}
|
||||
>
|
||||
Elküldöm
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{error && <p className="msg msg-error">{error}</p>}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="nps-close"
|
||||
aria-label="Bezárás"
|
||||
disabled={busy}
|
||||
onClick={() => (score === null ? send(null, false) : setShown(false))}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { HIGH_TAGS, LOW_TAGS, TAG_LABELS } from "@/lib/feedback";
|
||||
import type { Rating } from "@/lib/types";
|
||||
|
||||
const MAX_COMMENT = 1000;
|
||||
|
||||
/**
|
||||
* "Mennyire érezted magadra szabottnak?": the user rates what they got (an
|
||||
* analysis: 1–5 stars; an answer: thumbs). A click saves it at once; tags, a
|
||||
* comment and the permission to read the text can follow. Only the
|
||||
* operator sees it, nothing is public.
|
||||
*/
|
||||
export function RateContent({
|
||||
analysisId,
|
||||
questionId,
|
||||
thumbs = false,
|
||||
}: {
|
||||
analysisId?: string;
|
||||
questionId?: string;
|
||||
/** Thumbs up/down instead of stars (answers to questions). */
|
||||
thumbs?: boolean;
|
||||
}) {
|
||||
const id = useId();
|
||||
const [rating, setRating] = useState<Rating | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
const [comment, setComment] = useState("");
|
||||
const [mayRead, setMayRead] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const target = analysisId
|
||||
? { analysis_id: analysisId }
|
||||
: { question_id: questionId };
|
||||
|
||||
useEffect(() => {
|
||||
const query = analysisId
|
||||
? `analysis_ids=${analysisId}`
|
||||
: `question_ids=${questionId}`;
|
||||
api<{ ratings: Rating[] }>(`/ratings?${query}`)
|
||||
.then((r) => {
|
||||
const mine = r.ratings[0];
|
||||
if (!mine) return;
|
||||
setRating(mine);
|
||||
setTags(mine.tags);
|
||||
setComment(mine.comment ?? "");
|
||||
setMayRead(mine.may_read);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [analysisId, questionId]);
|
||||
|
||||
async function save(stars: number, details: boolean) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setSaved(false);
|
||||
try {
|
||||
const shown = stars >= 4 ? HIGH_TAGS : LOW_TAGS;
|
||||
const next = await api<Rating>("/ratings", {
|
||||
method: "PUT",
|
||||
body: {
|
||||
...target,
|
||||
stars,
|
||||
// Tags of the other side do not fit a changed rating.
|
||||
tags: tags.filter((t) => shown.includes(t)),
|
||||
comment: comment.trim() || null,
|
||||
may_read: mayRead,
|
||||
},
|
||||
});
|
||||
setRating(next);
|
||||
setTags(next.tags);
|
||||
if (details) {
|
||||
setSaved(true);
|
||||
setOpen(false);
|
||||
} else {
|
||||
setOpen(true);
|
||||
}
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const stars = rating?.stars ?? 0;
|
||||
const offered = stars >= 4 ? HIGH_TAGS : LOW_TAGS;
|
||||
const toggle = (tag: string) =>
|
||||
setTags((all) =>
|
||||
all.includes(tag) ? all.filter((t) => t !== tag) : [...all, tag],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={thumbs ? "rate rate-thumbs" : "rate"}>
|
||||
<div className="rate-row">
|
||||
<span className="rate-question" id={`${id}-q`}>
|
||||
{thumbs
|
||||
? "Hasznos volt a válasz?"
|
||||
: "Mennyire érezted magadra szabottnak?"}
|
||||
</span>
|
||||
<div className="rate-buttons" role="group" aria-labelledby={`${id}-q`}>
|
||||
{thumbs
|
||||
? [
|
||||
{ value: 5, label: "Igen", icon: "👍" },
|
||||
{ value: 1, label: "Nem", icon: "👎" },
|
||||
].map((b) => (
|
||||
<button
|
||||
key={b.value}
|
||||
type="button"
|
||||
className={
|
||||
stars === b.value ? "rate-thumb is-on" : "rate-thumb"
|
||||
}
|
||||
aria-pressed={stars === b.value}
|
||||
aria-label={b.label}
|
||||
disabled={busy}
|
||||
onClick={() => save(b.value, false)}
|
||||
>
|
||||
<span aria-hidden="true">{b.icon}</span>
|
||||
</button>
|
||||
))
|
||||
: [1, 2, 3, 4, 5].map((n) => (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
className={n <= stars ? "rate-star is-on" : "rate-star"}
|
||||
aria-pressed={n === stars}
|
||||
aria-label={`${n} csillag`}
|
||||
disabled={busy}
|
||||
onClick={() => save(n, false)}
|
||||
>
|
||||
<span aria-hidden="true">★</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{rating && !open && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm"
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
{rating.comment || rating.tags.length
|
||||
? "Módosítom"
|
||||
: "Hozzáfűzök valamit"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{open && rating && (
|
||||
<div className="rate-details">
|
||||
<p className="hint">
|
||||
Köszönjük! Ha szeretnéd, mondd el bővebben is (nem kötelező):
|
||||
</p>
|
||||
<div className="rate-tags">
|
||||
{offered.map((tag) => (
|
||||
<button
|
||||
key={tag}
|
||||
type="button"
|
||||
className={tags.includes(tag) ? "rate-tag is-on" : "rate-tag"}
|
||||
aria-pressed={tags.includes(tag)}
|
||||
onClick={() => toggle(tag)}
|
||||
>
|
||||
{TAG_LABELS[tag]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label htmlFor={`${id}-comment`} className="sr-only">
|
||||
Megjegyzés
|
||||
</label>
|
||||
<textarea
|
||||
id={`${id}-comment`}
|
||||
className="inp"
|
||||
rows={2}
|
||||
maxLength={MAX_COMMENT}
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
placeholder="Mi tetszett, mi nem? Mi hiányzott?"
|
||||
/>
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={mayRead}
|
||||
onChange={(e) => setMayRead(e.target.checked)}
|
||||
/>
|
||||
Megnézhetitek{" "}
|
||||
{thumbs ? "a kérdést és a választ" : "az elemzés szövegét"}, hogy
|
||||
javíthassatok rajta.
|
||||
</label>
|
||||
<div className="form-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={busy}
|
||||
onClick={() => save(stars, true)}
|
||||
>
|
||||
{busy ? "Mentés…" : "Elküldöm"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Most nem
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div aria-live="polite">
|
||||
{error && <p className="msg msg-error">{error}</p>}
|
||||
{saved && <p className="hint">Köszönjük a visszajelzést!</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
/** "Hiba jelzése": the feedback page, with this page as where it happened. */
|
||||
export function ReportLink({
|
||||
children = "Hiba jelzése",
|
||||
}: {
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
return (
|
||||
<Link
|
||||
href={`/visszajelzes?tipus=bug&honnan=${encodeURIComponent(pathname)}`}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -146,7 +146,11 @@ export function SiteHeader({ me }: { me: Me }) {
|
||||
<NavLinks links={links} />
|
||||
<div className="who">
|
||||
<PackageBadge me={me} />
|
||||
<UserMenu name={me.user.display_name || me.user.email} invoices={me.invoice_count > 0} />
|
||||
<UserMenu
|
||||
name={me.user.display_name || me.user.email}
|
||||
invoices={me.invoice_count > 0}
|
||||
replies={me.feedback_replies_unseen ?? 0}
|
||||
/>
|
||||
</div>
|
||||
<MobileMenu className="mobile-menu-app" sections={[{ links }]} />
|
||||
</header>
|
||||
|
||||
@@ -8,10 +8,10 @@ import { LogoutButton } from "./LogoutButton";
|
||||
|
||||
/**
|
||||
* The account menu under the user's name (top right): profile, invoices,
|
||||
* redeeming a code, giving a gift, logging out. Closes on a click outside, Escape, or
|
||||
* redeeming a code, giving a gift, feedback (a dot: a new reply), logging out. Closes on a click outside, Escape, or
|
||||
* moving to another page.
|
||||
*/
|
||||
export function UserMenu({ name, invoices }: { name: string; invoices: boolean }) {
|
||||
export function UserMenu({ name, invoices, replies = 0 }: { name: string; invoices: boolean; replies?: number }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const button = useRef<HTMLButtonElement>(null);
|
||||
@@ -40,6 +40,8 @@ export function UserMenu({ name, invoices }: { name: string; invoices: boolean }
|
||||
...(invoices ? [{ href: "/szamlak", label: "Számláim" }] : []),
|
||||
{ href: "/bevaltas", label: "Kód beváltása" },
|
||||
{ href: "/ajandek", label: "Ajándékozás" },
|
||||
// Where the user is goes with the message (for a bug).
|
||||
{ href: `/visszajelzes?honnan=${encodeURIComponent(pathname)}`, match: "/visszajelzes", label: "Visszajelzés", dot: replies > 0 },
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -58,6 +60,7 @@ export function UserMenu({ name, invoices }: { name: string; invoices: boolean }
|
||||
<path d="M4 20c1.5-4 4.5-6 8-6s6.5 2 8 6" />
|
||||
</svg>
|
||||
<span className="who-name-text">{name}</span>
|
||||
{replies > 0 && <span className="menu-dot" aria-label="új válasz a visszajelzésedre" />}
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" className="who-chevron">
|
||||
<path d="M6 9l6 6 6-6" />
|
||||
</svg>
|
||||
@@ -70,9 +73,14 @@ export function UserMenu({ name, invoices }: { name: string; invoices: boolean }
|
||||
href={item.href}
|
||||
role="menuitem"
|
||||
className="user-menu-item"
|
||||
aria-current={pathname.startsWith(item.href) ? "page" : undefined}
|
||||
aria-current={pathname.startsWith("match" in item && item.match ? item.match : item.href) ? "page" : undefined}
|
||||
>
|
||||
{item.label}
|
||||
{"dot" in item && item.dot && (
|
||||
<span className="menu-dot" aria-label="új válasz">
|
||||
{" "}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
))}
|
||||
<LogoutButton className="user-menu-item user-menu-logout" role="menuitem" />
|
||||
|
||||
@@ -8,6 +8,8 @@ import type { TarotReading } from "@/lib/tarot";
|
||||
import { AnalysisLoading } from "../AnalysisLoading";
|
||||
import { RegenerateButton } from "../RegenerateButton";
|
||||
import { RetryNotice } from "../RetryNotice";
|
||||
import { RateContent } from "../RateContent";
|
||||
import { ReportLink } from "../ReportLink";
|
||||
import { TarotResult } from "./TarotResult";
|
||||
|
||||
const POLL_MS = 3000;
|
||||
@@ -74,6 +76,7 @@ export function TarotLive({
|
||||
<>
|
||||
{regenerate}
|
||||
<TarotResult cards={reading.cards} question={reading.question} content={reading.content} />
|
||||
<RateContent analysisId={reading.id} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -84,7 +87,7 @@ export function TarotLive({
|
||||
<p className="msg msg-error" role="alert">
|
||||
A jóslást többszöri próbálkozás után sem sikerült megírni
|
||||
{reading.credits_charged > 0 ? ". A jóslást visszaadtuk, így ingyen újra húzhatsz" : ""}. Próbáld újra egy kicsit
|
||||
később.
|
||||
később. Ha újra nem sikerül: <ReportLink />.
|
||||
</p>
|
||||
{isAdmin && reading.error && <p className="hint">Hiba: {reading.error}</p>}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Words of the feedback: rating tags, what was rated, message kinds and states.
|
||||
|
||||
import type { FeedbackCategory, FeedbackStatus } from "./types";
|
||||
|
||||
/** Tags offered with a low rating (1–3 stars). */
|
||||
export const LOW_TAGS = [
|
||||
"too_general",
|
||||
"contradictory",
|
||||
"wrong_data",
|
||||
"hard_to_read",
|
||||
"too_long",
|
||||
"tone",
|
||||
];
|
||||
/** Tags offered with a high rating (4–5 stars). */
|
||||
export const HIGH_TAGS = ["accurate", "deep", "clear", "useful"];
|
||||
|
||||
export const TAG_LABELS: Record<string, string> = {
|
||||
too_general: "túl általános",
|
||||
contradictory: "ellentmondásos",
|
||||
wrong_data: "hibás adat (pl. rossz jegy vagy ház)",
|
||||
hard_to_read: "nehezen érthető",
|
||||
too_long: "túl hosszú",
|
||||
tone: "nem tetszett a hangnem",
|
||||
accurate: "pontos",
|
||||
deep: "mély",
|
||||
clear: "jól érthető",
|
||||
useful: "hasznos",
|
||||
};
|
||||
|
||||
export const KIND_LABELS: Record<string, string> = {
|
||||
summary: "Rövid összefoglaló",
|
||||
natal: "Képletelemzés",
|
||||
synastry: "Kapcsolati elemzés",
|
||||
forecast: "Éves előrejelzés",
|
||||
tarot: "Kártyajóslás",
|
||||
question: "Válasz kérdésre",
|
||||
};
|
||||
|
||||
export const CATEGORY_LABELS: Record<FeedbackCategory, string> = {
|
||||
bug: "Hiba",
|
||||
idea: "Ötlet",
|
||||
question: "Kérdés",
|
||||
other: "Egyéb",
|
||||
};
|
||||
|
||||
/** Message states as the sender sees them. */
|
||||
export const STATUS_LABELS: Record<FeedbackStatus, string> = {
|
||||
new: "Megkaptuk",
|
||||
in_progress: "Folyamatban",
|
||||
done: "Megoldva",
|
||||
dismissed: "Lezárva",
|
||||
};
|
||||
@@ -18,8 +18,8 @@ export const ARBITRATION_BOARD = {
|
||||
web: "https://panaszrendezes.hu",
|
||||
};
|
||||
|
||||
export const PRIVACY_UPDATED = "2026. november 22.";
|
||||
export const PRIVACY_UPDATED_EN = "22 November 2026";
|
||||
export const PRIVACY_UPDATED = "2026. november 24.";
|
||||
export const PRIVACY_UPDATED_EN = "24 November 2026";
|
||||
|
||||
/** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */
|
||||
export const TERMS_UPDATED = "2026. november 23.";
|
||||
|
||||
@@ -25,6 +25,10 @@ export interface Me {
|
||||
share_reward_granted: boolean;
|
||||
/** Invoices of the user's payments (the "Számláim" menu shows from the first). */
|
||||
invoice_count: number;
|
||||
/** Replies to the user's feedback not read yet. */
|
||||
feedback_replies_unseen: number;
|
||||
/** Ask the "would you recommend us?" question now. */
|
||||
nps_due: boolean;
|
||||
/** Natal analyses earned by bringing new users through shared links. */
|
||||
referral_rewards: { earned: number; limit: number };
|
||||
}
|
||||
@@ -790,3 +794,78 @@ export interface SkyEvents {
|
||||
moon_ingresses: SkyIngress[];
|
||||
retrogrades: SkyRetrograde[];
|
||||
}
|
||||
|
||||
/** The user's rating of an analysis or an answer (`GET/PUT /v1/ratings`). */
|
||||
export interface Rating {
|
||||
analysis_id: string | null;
|
||||
question_id: string | null;
|
||||
/** 1–5; an answer's thumbs: 1 or 5. */
|
||||
stars: number;
|
||||
tags: string[];
|
||||
comment: string | null;
|
||||
may_read: boolean;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export type FeedbackCategory = "bug" | "idea" | "question" | "other";
|
||||
export type FeedbackStatus = "new" | "in_progress" | "done" | "dismissed";
|
||||
|
||||
/** A message from the "Visszajelzés" page, as its sender sees it. */
|
||||
export interface FeedbackMessage {
|
||||
id: string;
|
||||
category: FeedbackCategory;
|
||||
body: string;
|
||||
page: string | null;
|
||||
status: FeedbackStatus;
|
||||
reply: string | null;
|
||||
replied_at: string | null;
|
||||
/** The reply has not been read yet. */
|
||||
reply_new: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** A message as admins see it. */
|
||||
export interface AdminFeedbackMessage extends Omit<FeedbackMessage, "reply_new"> {
|
||||
user_agent: string | null;
|
||||
admin_note: string | null;
|
||||
reply_seen: boolean;
|
||||
user: { email: string; name: string | null; buyer: boolean };
|
||||
}
|
||||
|
||||
/** A rating as admins see it. */
|
||||
export interface AdminRating {
|
||||
id: string;
|
||||
kind: string;
|
||||
model: string | null;
|
||||
prompt_version: string | null;
|
||||
stars: number;
|
||||
tags: string[];
|
||||
comment: string | null;
|
||||
may_read: boolean;
|
||||
/** The rated text can be opened (allowed, and still there). */
|
||||
readable: boolean;
|
||||
buyer: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
reviewed: boolean;
|
||||
user: { email: string; name: string | null } | null;
|
||||
}
|
||||
|
||||
/** The numbers of Admin → Visszajelzések. */
|
||||
export interface FeedbackSummary {
|
||||
days: number;
|
||||
by_kind: { kind: string; count: number; average: number; satisfied_share: number }[];
|
||||
by_model: { kind: string; model: string; prompt_version: string; count: number; average: number }[];
|
||||
weeks: { week: string; count: number; average: number }[];
|
||||
tags: { tag: string; count: number }[];
|
||||
buyers: { buyer: boolean; count: number; average: number }[];
|
||||
nps: {
|
||||
answered: number;
|
||||
promoters: number;
|
||||
passives: number;
|
||||
detractors: number;
|
||||
closed: number;
|
||||
score: number | null;
|
||||
comments: { score: number; comment: string; created_at: string }[];
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user