Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86f61c215a | ||
|
|
5feaa6836c | ||
|
|
c367c218ac | ||
|
|
e0605a7653 | ||
|
|
2d1373edd6 | ||
|
|
382bd31271 | ||
|
|
dff8f692b0 | ||
|
|
227e8b5b80 | ||
|
|
12d5d6a9d1 | ||
|
|
29731e32f3 | ||
|
|
6731955fce | ||
|
|
e1dee3a20d | ||
|
|
3a38518d07 | ||
|
|
2eaae68271 | ||
|
|
62ae4a438e | ||
|
|
3e4653fdb2 |
@@ -5,3 +5,8 @@ vendor/
|
||||
legacy/
|
||||
.git/
|
||||
**/*.md
|
||||
# The frontend builds from its own folder (with its own .dockerignore). The
|
||||
# Rust images use only its src/content (a crate includes the tarot deck), so
|
||||
# its dependencies and build output stay out: about 1 GB in every image layer.
|
||||
services/frontend/node_modules/
|
||||
services/frontend/.next/
|
||||
|
||||
@@ -136,8 +136,11 @@ jobs:
|
||||
docker images "$IMAGE_PREFIX-$svc" --format '{{.Repository}}:{{.Tag}}' | xargs -r docker rmi >/dev/null 2>&1 || true
|
||||
done
|
||||
docker image prune -f >/dev/null
|
||||
# A size cap, not an age: a busy day builds tens of gigabytes.
|
||||
docker builder prune -af --max-used-space 10GB >/dev/null || true
|
||||
# By age: with the containerd image store a size cap
|
||||
# (--max-used-space) prunes nothing. Rust builds no longer carry
|
||||
# the frontend's node_modules (.dockerignore), so a few days of
|
||||
# cache stay small; the cargo cache mounts of recent builds stay.
|
||||
docker builder prune -af --filter until=72h >/dev/null || true
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
-- Feedback, kept in the system only (no e-mail, no Telegram). Nothing of it
|
||||
-- is shown publicly: these are not reviews.
|
||||
|
||||
-- Ratings of what a user got: the short summary, a detailed analysis, a
|
||||
-- forecast, a synastry, a tarot reading (analyses), or an answer to a
|
||||
-- question. Only the one who got it rates it, once (a rating can be
|
||||
-- changed). Kind, model and prompt version are copied, so the statistics
|
||||
-- stay when the analysis is deleted.
|
||||
CREATE TABLE content_ratings (
|
||||
id uuid PRIMARY KEY,
|
||||
-- Cleared with the account (the comment goes too; the stars stay, without a name).
|
||||
user_id uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
analysis_id uuid REFERENCES analyses (id) ON DELETE SET NULL,
|
||||
question_id uuid REFERENCES questions (id) ON DELETE SET NULL,
|
||||
-- summary, natal, synastry, forecast, tarot or question.
|
||||
kind text NOT NULL,
|
||||
model text,
|
||||
prompt_version text,
|
||||
-- 1–5 stars; an answer's thumbs are 1 (down) or 5 (up).
|
||||
stars smallint NOT NULL CHECK (stars BETWEEN 1 AND 5),
|
||||
tags text[] NOT NULL DEFAULT '{}',
|
||||
comment text,
|
||||
-- The user lets the operator read the rated text (to improve it).
|
||||
may_read boolean NOT NULL DEFAULT false,
|
||||
-- Had paid for a package when rating.
|
||||
buyer boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
-- An admin has looked at it (the admin menu counts the ones to look at).
|
||||
reviewed_at timestamptz,
|
||||
CHECK (analysis_id IS NULL OR question_id IS NULL)
|
||||
);
|
||||
CREATE UNIQUE INDEX content_ratings_analysis_idx ON content_ratings (analysis_id, user_id)
|
||||
WHERE analysis_id IS NOT NULL AND user_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX content_ratings_question_idx ON content_ratings (question_id, user_id)
|
||||
WHERE question_id IS NOT NULL AND user_id IS NOT NULL;
|
||||
CREATE INDEX content_ratings_created_idx ON content_ratings (created_at DESC);
|
||||
|
||||
-- Messages through the "Visszajelzés" page: bugs, ideas, questions. The
|
||||
-- user sees their state and the operator's reply on the same page.
|
||||
CREATE TABLE feedback_messages (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
category text NOT NULL CHECK (category IN ('bug', 'idea', 'question', 'other')),
|
||||
body text NOT NULL,
|
||||
-- The page the user came from, and the browser (for bugs).
|
||||
page text,
|
||||
user_agent text,
|
||||
status text NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'in_progress', 'done', 'dismissed')),
|
||||
-- Only the operator sees it.
|
||||
admin_note text,
|
||||
reply text,
|
||||
replied_at timestamptz,
|
||||
-- The user has seen the reply.
|
||||
reply_seen_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX feedback_messages_status_idx ON feedback_messages (status, created_at DESC);
|
||||
CREATE INDEX feedback_messages_user_idx ON feedback_messages (user_id, created_at DESC);
|
||||
|
||||
-- "How likely are you to recommend Sorsfonalak to a friend?" (0–10), asked
|
||||
-- once in the app. A closed question is kept with no score: not asked again.
|
||||
CREATE TABLE nps_answers (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid UNIQUE REFERENCES users (id) ON DELETE SET NULL,
|
||||
score smallint CHECK (score BETWEEN 0 AND 10),
|
||||
comment text,
|
||||
buyer boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
-- A gift e-mailed later (e.g. on Christmas morning): when (NULL: at once),
|
||||
-- and the e-mail queued for it, to show whether it went out (the outbox row
|
||||
-- itself is cleaned up a week after sending).
|
||||
ALTER TABLE gifts
|
||||
ADD COLUMN send_at timestamptz,
|
||||
ADD COLUMN email_id uuid;
|
||||
@@ -320,6 +320,8 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
||||
payload["paid_on"].as_str().and_then(|d| date(lang, d)).ok_or(TemplateError::MissingField("paid_on"))?;
|
||||
let terms_url = field(payload, "terms_url")?;
|
||||
let invoices_url = field(payload, "invoices_url")?;
|
||||
// Gift withdrawals come through the feedback page (easier to handle there).
|
||||
let feedback_url = format!("{}/visszajelzes", terms_url.trim_end_matches("/aszf"));
|
||||
let greeting = |hu: bool| match (hu, name(payload, "display_name")) {
|
||||
(true, Some(n)) => format!("Szia {n}!"),
|
||||
(true, None) => "Szia!".to_owned(),
|
||||
@@ -334,7 +336,13 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
||||
.as_str()
|
||||
.map(|e| e.chars().filter(|c| !c.is_control()).take(254).collect::<String>());
|
||||
let whom = name(&payload["gift"], "recipient_name");
|
||||
(code, to, whom)
|
||||
// `2026-12-24 08:00`, Budapest clock: when it is e-mailed.
|
||||
let when = payload["gift"]["send_at"].as_str().and_then(|t| {
|
||||
let (day, clock) = t.split_once(' ')?;
|
||||
let clock: String = clock.chars().filter(|c| c.is_ascii_digit() || *c == ':').take(5).collect();
|
||||
Some((date(lang, day)?, clock))
|
||||
});
|
||||
(code, to, whom, when)
|
||||
});
|
||||
let contents_hu = contents.as_ref().map(|c| format!(" Tartalma: {c}.")).unwrap_or_default();
|
||||
let contents_en = contents.as_ref().map(|c| format!(" It contains: {c}.")).unwrap_or_default();
|
||||
@@ -359,9 +367,10 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
},
|
||||
(Lang::Hu, Some((code, to, whom))) => Content {
|
||||
(Lang::Hu, Some((code, to, whom, when))) => Content {
|
||||
subject: format!("Köszönjük a vásárlást: {package} (ajándék)"),
|
||||
preheader: Some(match &to {
|
||||
Some(e) if when.is_some() => format!("Az ajándékot időzítve küldjük el ide: {e}."),
|
||||
Some(e) => format!("Az ajándékot elküldtük ide: {e}."),
|
||||
None => "Az ajándékutalványt csatoltuk ehhez a levélhez.".into(),
|
||||
}),
|
||||
@@ -370,13 +379,15 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
||||
"Megkaptuk a fizetésed ({amount}, {paid_on}): a(z) „{package}” csomagot ajándékba vetted{}.{contents_hu} {}",
|
||||
whom.as_ref().map(|w| format!(" {w} részére")).unwrap_or_default(),
|
||||
match &to {
|
||||
Some(e) => format!("Az ajándékkódot az utalvánnyal együtt elküldtük ide: {e}. Ha nem e-mailben adnád át, az Ajándékaim oldalon letöltheted az utalványt PDF-ben."),
|
||||
Some(e) => match &when {
|
||||
Some((day, clock)) => format!("Az ajándékkódot az utalvánnyal együtt {day}, {clock}-kor küldjük el ide: {e}. Addig az Ajándékaim oldalon letöltheted az utalványt PDF-ben, vagy elküldheted azonnal is."),
|
||||
None => format!("Az ajándékkódot az utalvánnyal együtt elküldtük ide: {e}. Ha nem e-mailben adnád át, az Ajándékaim oldalon letöltheted az utalványt PDF-ben."),
|
||||
},
|
||||
None => "Az ajándékutalványt PDF-ben csatoltuk ehhez a levélhez, és az Ajándékaim oldalon is letöltheted: kinyomtathatod, vagy továbbküldheted annak, akinek szánod.".into(),
|
||||
}
|
||||
),
|
||||
quote: Some(
|
||||
"A vásárlástól számított 14 napon belül, amíg az ajándékkódot nem váltották be, elállhatsz a vásárlástól: írj az info@sorsfonalak.hu címre, és visszatérítjük az árát. A fizetés előtt kérted, hogy a kód beváltásakor a szolgáltatás azonnal megkezdődjön: a beváltással az elállási jog megszűnik."
|
||||
.into(),
|
||||
format!("A vásárlástól számított 14 napon belül, amíg az ajándékkódot nem váltották be, elállhatsz a vásárlástól: írd meg nekünk az oldalon, belépve ({feedback_url}), és visszatérítjük az árát. A fizetés előtt kérted, hogy a kód beváltásakor a szolgáltatás azonnal megkezdődjön: a beváltással az elállási jog megszűnik."),
|
||||
),
|
||||
points: None,
|
||||
code: code.map(|c| ("AJÁNDÉKKÓD", c)),
|
||||
@@ -409,7 +420,7 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
},
|
||||
(Lang::En, Some((code, to, whom))) => Content {
|
||||
(Lang::En, Some((code, to, whom, when))) => Content {
|
||||
subject: format!("Thank you for your purchase: {package} (gift)"),
|
||||
preheader: Some(match &to {
|
||||
Some(e) => format!("We sent the gift to {e}."),
|
||||
@@ -420,13 +431,15 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
|
||||
"We received your payment ({amount}, {paid_on}): you bought the “{package}” package as a gift{}.{contents_en} {}",
|
||||
whom.as_ref().map(|w| format!(" for {w}")).unwrap_or_default(),
|
||||
match &to {
|
||||
Some(e) => format!("We sent the gift code with the gift card to {e}. To hand it over another way, download the card as a PDF on the My gifts page."),
|
||||
Some(e) => match &when {
|
||||
Some((day, clock)) => format!("We send the gift code with the gift card to {e} on {day} at {clock}. Until then you can download the card on the My gifts page, or send it at once."),
|
||||
None => format!("We sent the gift code with the gift card to {e}. To hand it over another way, download the card as a PDF on the My gifts page."),
|
||||
},
|
||||
None => "The gift card is attached to this e-mail as a PDF, and you can download it on the My gifts page: print it, or forward it to the person it is for.".into(),
|
||||
}
|
||||
),
|
||||
quote: Some(
|
||||
"Within 14 days of the purchase, while the gift code is not redeemed, you may withdraw from the purchase: write to info@sorsfonalak.hu and we refund it. Before paying you asked for the service to start as soon as the code is redeemed: redeeming it ends the right of withdrawal."
|
||||
.into(),
|
||||
format!("Within 14 days of the purchase, while the gift code is not redeemed, you may withdraw from the purchase: tell us on the site, logged in ({feedback_url}), and we refund it. Before paying you asked for the service to start as soon as the code is redeemed: redeeming it ends the right of withdrawal."),
|
||||
),
|
||||
points: None,
|
||||
code: code.map(|c| ("GIFT CODE", c)),
|
||||
@@ -459,16 +472,21 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
|
||||
payload["contents"].as_str().map(|c| c.chars().filter(|c| !c.is_control()).take(300).collect::<String>());
|
||||
let from = name(payload, "from_name");
|
||||
let to = name(payload, "recipient_name");
|
||||
// Bought for Christmas: said so, with the wishes.
|
||||
let christmas = payload["christmas_year"].as_i64().is_some();
|
||||
let xmas = if christmas { "karácsonyi " } else { "" };
|
||||
Ok(match lang {
|
||||
Lang::Hu => Content {
|
||||
subject: match &from {
|
||||
Some(f) => format!("{f} ajándékot küldött neked: „{package}” csomag"),
|
||||
Some(f) => format!("{f} {xmas}ajándékot küldött neked: „{package}” csomag"),
|
||||
None if christmas => format!("Karácsonyi ajándékot kaptál: „{package}” csomag a Sorsfonalakon"),
|
||||
None => format!("Ajándékot kaptál: „{package}” csomag a Sorsfonalakon"),
|
||||
},
|
||||
preheader: Some("Születési képlet és személyre szóló elemzések: a kód beváltásával a tiéd.".into()),
|
||||
greeting: to.as_ref().map_or_else(|| "Szia!".into(), |t| format!("Szia {t}!")),
|
||||
intro: format!(
|
||||
"{} egy „{package}” csomagot a Sorsfonalakon.{}",
|
||||
"{}{} egy „{package}” csomagot a Sorsfonalakon.{}",
|
||||
if christmas { "Boldog karácsonyt! " } else { "" },
|
||||
match &from {
|
||||
Some(f) => format!("{f} ajándékozott neked"),
|
||||
None => "Ajándékba kaptál".into(),
|
||||
@@ -497,6 +515,7 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
|
||||
},
|
||||
Lang::En => Content {
|
||||
subject: match &from {
|
||||
Some(f) if christmas => format!("{f} sent you a Christmas gift: the “{package}” package"),
|
||||
Some(f) => format!("{f} sent you a gift: the “{package}” package"),
|
||||
None => format!("A gift for you: the “{package}” package on Sorsfonalak"),
|
||||
},
|
||||
@@ -1021,6 +1040,11 @@ mod tests {
|
||||
);
|
||||
assert!(hu.html.contains("<b>Ölel</b>") && hu.html.contains(">ABCD-EFGH-JKMN</div>"));
|
||||
assert!(hu.text.contains("PDF-ben is csatoltuk") && hu.text.contains("mert Ági a Sorsfonalakon"));
|
||||
let mut xmas = payload.clone();
|
||||
xmas["christmas_year"] = 2027.into();
|
||||
let hu = render("gift_package", "hu", &xmas).unwrap();
|
||||
assert_eq!(hu.subject, "Ági karácsonyi ajándékot küldött neked: „Páros” csomag");
|
||||
assert!(hu.text.contains("Boldog karácsonyt! Ági ajándékozott neked"));
|
||||
let anonymous = serde_json::json!({"url": "u", "package_name": "Család", "promo_code": "X1-<script>"});
|
||||
let hu = render("gift_package", "hu", &anonymous).unwrap();
|
||||
assert_eq!(hu.subject, "Ajándékot kaptál: „Család” csomag a Sorsfonalakon");
|
||||
@@ -1046,6 +1070,10 @@ mod tests {
|
||||
assert!(hu.text.contains("AJÁNDÉKKÓD: ABCD-EFGH-JKMN") && hu.text.contains("14 napon belül"));
|
||||
assert!(hu.text.contains("a beváltással az elállási jog megszűnik"));
|
||||
assert!(!hu.text.contains("jóváírtuk"));
|
||||
payload["gift"]["send_at"] = Value::from("2026-12-24 08:00");
|
||||
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
|
||||
assert!(hu.text.contains("2026. december 24., 08:00-kor küldjük el ide: bea@example.com"), "{}", hu.text);
|
||||
assert!(hu.text.contains("belépve (https://sorsfonalak.hu/visszajelzes)"), "{}", hu.text);
|
||||
payload["gift"]["recipient_email"] = Value::Null;
|
||||
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
|
||||
assert!(hu.text.contains("PDF-ben csatoltuk ehhez a levélhez"));
|
||||
|
||||
@@ -28,6 +28,7 @@ fn main() {
|
||||
code: &code,
|
||||
redeem_url: &url,
|
||||
recipient_name: Some(to.as_str()),
|
||||
christmas: std::env::var("CHRISTMAS").ok().and_then(|y| y.parse().ok()),
|
||||
from_name: Some(from.as_str()),
|
||||
message: (!message.is_empty()).then_some(message.as_str()),
|
||||
};
|
||||
|
||||
+97
-12
@@ -38,6 +38,8 @@ const GOLD: &str = "#a07a2c";
|
||||
const MUTED: &str = "#5f6578";
|
||||
const LINE: &str = "#d9c9a3";
|
||||
const PAPER: &str = "#fdfaf3";
|
||||
/// The Christmas snowflakes: gold, lighter than the text.
|
||||
const GOLD_SOFT: &str = "#c9a862";
|
||||
|
||||
/// Where the code box starts; the message fills the space above it.
|
||||
const CODE_TOP: f32 = 636.0;
|
||||
@@ -64,6 +66,27 @@ pub struct Card<'a> {
|
||||
pub from_name: Option<&'a str>,
|
||||
/// The buyer's message (line breaks kept).
|
||||
pub message: Option<&'a str>,
|
||||
/// A Christmas gift: the card is festive and wishes a happy new year
|
||||
/// (this one).
|
||||
pub christmas: Option<i32>,
|
||||
}
|
||||
|
||||
/// "2027-et", "2028-at": a year in the accusative, by how its last word sounds.
|
||||
pub fn year_accusative(year: i32) -> String {
|
||||
let ending = match year.rem_euclid(10) {
|
||||
1 | 4 | 7 | 9 => "et",
|
||||
2 => "t",
|
||||
3 | 8 => "at",
|
||||
5 => "öt",
|
||||
6 => "ot",
|
||||
// Tens: "…tízet", "…húszat", "…harmincat"…; hundreds and thousands: "…százat", "…ezret".
|
||||
_ => match (year / 10).rem_euclid(10) {
|
||||
1 | 4 | 7 | 9 => "et",
|
||||
0 if (year / 100).rem_euclid(10) == 0 => "et",
|
||||
_ => "at",
|
||||
},
|
||||
};
|
||||
format!("{year}-{ending}")
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -252,6 +275,11 @@ impl Message {
|
||||
let (text, signature) = match (message, from) {
|
||||
(Some(m), from) => (format!("„{m}”"), from.map(|f| format!("– {f}"))),
|
||||
(None, Some(f)) => (format!("Szeretettel küldi: {f}"), None),
|
||||
(None, None) if card.christmas.is_some() => (
|
||||
"Boldog karácsonyt! Fedezd fel, mit mesélnek rólad a csillagok, és mit hoz neked a következő év."
|
||||
.to_string(),
|
||||
None,
|
||||
),
|
||||
(None, None) => (
|
||||
"Fedezd fel, mit mesélnek rólad a csillagok: a születési képleted, személyre szóló elemzések, \
|
||||
és válaszok a kérdéseidre."
|
||||
@@ -323,6 +351,26 @@ fn star(x: f32, y: f32, r: f32, fill: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// A six-armed snowflake of gold lines, centred on (x, y).
|
||||
fn snowflake(x: f32, y: f32, r: f32, color: &str) -> String {
|
||||
let mut d = String::new();
|
||||
for k in 0..6 {
|
||||
let a = (k as f32 * 60.0 - 90.0).to_radians();
|
||||
let (sin, cos) = a.sin_cos();
|
||||
let _ = write!(d, "M{x} {y}L{} {}", x + r * cos, y + r * sin);
|
||||
// Two small branches on each arm.
|
||||
let (bx, by) = (x + r * 0.6 * cos, y + r * 0.6 * sin);
|
||||
for side in [-1.0_f32, 1.0] {
|
||||
let b = a + side * 0.75;
|
||||
let _ = write!(d, "M{bx} {by}L{} {}", bx + r * 0.32 * b.cos(), by + r * 0.32 * b.sin());
|
||||
}
|
||||
}
|
||||
format!(
|
||||
r#"<path d="{d}" fill="none" stroke="{color}" stroke-width="{}" stroke-linecap="round"/>"#,
|
||||
(r / 9.0).max(0.6)
|
||||
)
|
||||
}
|
||||
|
||||
/// The QR code of the redeem link as a path of `size` points at (x, y).
|
||||
fn qr(url: &str, x: f32, y: f32, size: f32) -> String {
|
||||
let Ok(code) = qrcode::QrCode::with_error_correction_level(url, qrcode::EcLevel::M) else {
|
||||
@@ -388,7 +436,7 @@ pub fn svg(card: &Card) -> String {
|
||||
);
|
||||
|
||||
// "AJÁNDÉKUTALVÁNY" between two short lines.
|
||||
let eyebrow = "AJÁNDÉKUTALVÁNY";
|
||||
let eyebrow = if card.christmas.is_some() { "KARÁCSONYI AJÁNDÉK" } else { "AJÁNDÉKUTALVÁNY" };
|
||||
let spacing = 3.2;
|
||||
let ew = width(Face::SansBold, eyebrow, 9.0, spacing) - spacing;
|
||||
let _ = write!(
|
||||
@@ -413,7 +461,12 @@ pub fn svg(card: &Card) -> String {
|
||||
for (x, y, r) in
|
||||
[(124.0, 164.0, 5.0), (462.0, 148.0, 6.5), (470.0, 304.0, 4.0), (134.0, 322.0, 6.0), (420.0, 350.0, 3.0)]
|
||||
{
|
||||
s.push_str(&star(x, y, r, LINE));
|
||||
// Christmas: snowflakes instead of stars, a little bigger.
|
||||
if card.christmas.is_some() {
|
||||
s.push_str(&snowflake(x, y, r * 1.9, GOLD_SOFT));
|
||||
} else {
|
||||
s.push_str(&star(x, y, r, LINE));
|
||||
}
|
||||
}
|
||||
let inner = WHEEL.split_once("viewBox=\"0 0 680 680\">").map_or("", |(_, rest)| rest);
|
||||
let inner = inner.trim_end().trim_end_matches("</svg>");
|
||||
@@ -451,17 +504,32 @@ pub fn svg(card: &Card) -> String {
|
||||
y += 15.0;
|
||||
}
|
||||
|
||||
// A divider with a small diamond.
|
||||
// A divider with a small diamond; at Christmas, the wishes on it.
|
||||
let divider = y + 10.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><path d="M{cx} {} l3.5 3.5 l-3.5 3.5 l-3.5 -3.5 z" fill="{GOLD}"/>"#,
|
||||
cx - 150.0,
|
||||
cx - 10.0,
|
||||
cx + 10.0,
|
||||
cx + 150.0,
|
||||
divider - 3.5
|
||||
);
|
||||
if let Some(year) = card.christmas {
|
||||
let wish = format!("Boldog karácsonyt és csillagos {}!", year_accusative(year));
|
||||
let ww = width(Face::SerifItalic, &wish, 16.0, 0.0);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><text x="{cx}" y="{}" text-anchor="middle" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="16" fill="{GOLD}">{}</text>"#,
|
||||
cx - ww / 2.0 - 70.0,
|
||||
cx - ww / 2.0 - 12.0,
|
||||
cx + ww / 2.0 + 12.0,
|
||||
cx + ww / 2.0 + 70.0,
|
||||
divider + 5.0,
|
||||
escape(&wish)
|
||||
);
|
||||
} else {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><path d="M{cx} {} l3.5 3.5 l-3.5 3.5 l-3.5 -3.5 z" fill="{GOLD}"/>"#,
|
||||
cx - 150.0,
|
||||
cx - 10.0,
|
||||
cx + 10.0,
|
||||
cx + 150.0,
|
||||
divider - 3.5
|
||||
);
|
||||
}
|
||||
|
||||
// The message next to the avatar, centred in the room above the code box.
|
||||
let room_top = divider + 22.0;
|
||||
@@ -568,6 +636,7 @@ mod tests {
|
||||
recipient_name: Some("Bea"),
|
||||
from_name: from,
|
||||
message,
|
||||
christmas: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -625,6 +694,22 @@ mod tests {
|
||||
usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_christmas_card_wishes_a_happy_new_year() {
|
||||
let contents = contents();
|
||||
let plain = svg(&card(&contents, None, None));
|
||||
assert!(plain.contains("AJÁNDÉKUTALVÁNY") && !plain.contains("karácsony"));
|
||||
let festive = Card { christmas: Some(2027), ..card(&contents, None, None) };
|
||||
let svg = svg(&festive);
|
||||
assert!(svg.contains("KARÁCSONYI AJÁNDÉK") && svg.contains("Boldog karácsonyt és csillagos 2027-et!"));
|
||||
assert!(svg.contains("mit hoz neked a következő év"));
|
||||
assert!(pdf(&festive).unwrap().starts_with(b"%PDF-"));
|
||||
assert_eq!(
|
||||
[2027, 2028, 2030, 2026, 2032, 2035, 2100, 2000].map(year_accusative),
|
||||
["2027-et", "2028-at", "2030-at", "2026-ot", "2032-t", "2035-öt", "2100-at", "2000-et"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_message_the_card_still_says_something() {
|
||||
let contents = contents();
|
||||
|
||||
+22
-5
@@ -7,6 +7,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
||||
## A vásárló: `/ajandek`
|
||||
|
||||
- **Hol indul:**
|
||||
- a főoldal ajándéksávja és a lábléc „Ajándékozás” pontja (nyilvános, lásd Karácsony);
|
||||
- a Csomagok oldal fő csomagjai alatt az „Ajándékba adom →” link (`/ajandek?csomag=couple`);
|
||||
- ugyanott az „Ajándékba is adhatod” doboz;
|
||||
- a fiókmenü „Ajándékozás” pontja.
|
||||
@@ -17,6 +18,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
||||
- **Hogyan kapja meg:**
|
||||
- „E-mailben küldjük el neki”: a címzett e-mail-címe kétszer, a kettőnek egyeznie kell (a szerver is ellenőrzi);
|
||||
- „Én adom át”: nincs címzett, a vásárló letölti az utalványt.
|
||||
- **Mikor kapja meg?** (csak e-mailnél): „Fizetés után azonnal”, vagy „Időzítve” (nap és időpont, a vásárló saját órája szerint, alapból 8:00). Karácsony előtt egy gomb is van: „Karácsony reggel (dec. 24., 8:00)”. Legalább 5 perccel későbbre (a böngésző 10 percet kér), legfeljebb egy évre előre.
|
||||
- **Személyes üzenet:** legfeljebb 300 karakter, link nélkül (mint a meghívóknál). Rajta van az utalványon és a levélben.
|
||||
- **Fizetés:** a Stripe-on, mint bármelyik csomagnál; a termék neve „Sorsfonalak – Páros (ajándék)”.
|
||||
- Az elfogadott szöveg itt más: „…kérem, hogy az ajándékkód beváltásakor a szolgáltatás azonnal megkezdődjön. Tudomásul veszem, hogy a beváltással a 14 napos elállási jog megszűnik.”
|
||||
@@ -25,6 +27,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
||||
- **Fizetés után:** visszatér az **Ajándékaim** oldalra (`/ajandekaim`), ahol a visszaigazolás megmondja, hova ment az ajándék.
|
||||
- **Visszaigazoló levél** (`purchase_confirmation`):
|
||||
- azt írja, hogy ajándékba vette, és benne van a kód;
|
||||
- időzítésnél: „…2026. december 24., 08:00-kor küldjük el ide: …” (magyar idő);
|
||||
- ha ő adja át, az utalvány PDF-ben csatolva van.
|
||||
|
||||
## Ajándékaim: `/ajandekaim`
|
||||
@@ -33,13 +36,14 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
||||
- a csomag, kinek szól, és a vásárlás napja;
|
||||
- az állapot: „Még nincs beváltva” vagy „Beváltva: dátum”;
|
||||
- a kód, másolás gombbal;
|
||||
- kinek ment e-mailben (és hányszor), vagy hogy ő adja át;
|
||||
- kinek ment e-mailben (és hányszor), vagy hogy ő adja át; időzítésnél „Időzítve: december 24. 8:00, ide: …”, sikertelen küldésnél hibaüzenet;
|
||||
- a küldő neve és az üzenet.
|
||||
- **Utalvány letöltése (PDF):** bármikor.
|
||||
- **Küldés e-mailben:** amíg nincs beváltva.
|
||||
- Újra ugyanoda, vagy másik címre (elírás); az „Én adom át” ajándékot is el lehet így küldeni.
|
||||
- A cím itt is kétszer kell.
|
||||
- Legfeljebb 3 levél ajándékonként, és kettő között legalább 10 perc.
|
||||
- Időzített, még ki nem ment levélnél a gomb „Küldés most”: a várakozó levelet visszavonja, és azonnal küldi (ez nem számít külön levélnek, és nem kell 10 percet várni). Ugyanígy, ha az első levél még ki sem ment, a javított cím kiváltja.
|
||||
|
||||
## A címzett
|
||||
|
||||
@@ -53,6 +57,15 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
||||
- Könyvelés: egy `package_orders` sor `gift` forrással, 0 Ft-tal (az ár a vásárló fizetésénél van).
|
||||
- Egy kód egyszer váltható be, és nem jár le.
|
||||
|
||||
## Karácsony
|
||||
|
||||
- **Az időszak:** november 15. és január 6. között (magyar idő) vett ajándék karácsonyi. A backend a fizetés idejéből számolja (`christmas_year`): novemberben és decemberben a következő év, januárban az aktuális.
|
||||
- **Az utalványon:** „KARÁCSONYI AJÁNDÉK” felirat, hópelyhek a csillagok helyett, és „Boldog karácsonyt és csillagos 2027-et!” (a toldalékot a `year_accusative` adja). Üzenet nélkül egy karácsonyi szöveg áll rajta.
|
||||
- **A levélben:** a tárgy „Anna karácsonyi ajándékot küldött neked: …”, a bevezető „Boldog karácsonyt! …”.
|
||||
- **A `/karacsony` oldal:** a kampány nyitóoldala (a sitemapban is): mit kap (képlet, a következő éve, kapcsolati elemzés), karácsony reggelre időzítés, a három csomag „Ezt adom ajándékba” gombbal. Az éves előrejelzés a születésnaptól egy évre szól; ezt hívjuk itt „a következő évének”.
|
||||
- **Nyilvános oldalak (a Google is látja):** a `/karacsony` és kijelentkezve az `/ajandek` egy bemutató oldal (`components/GiftLanding.tsx`, egész évben „Horoszkóp ajándékba”); a gombok a belépésen át (`/belepes?vissza=/ajandek?csomag=…`) az űrlapra visznek. Belépve az `/ajandek` az űrlap. Mindkettő a sitemapban van; rájuk linkel a főoldal ajándéksávja és a lábléc „Ajándékozás” pontja (karácsonykor a `/karacsony`-ra). A `/karacsony` Facebook-előnézete a `/kep/karacsony.png`.
|
||||
- Az időszakban a Csomagok oldal ajándékdoboza a `/karacsony` oldalra visz, a `/ajandek` oldal a karácsonyi mintát mutatja (`public/img/ajandek-karacsony.webp`, `CHRISTMAS=2027`). A frontend ugyanazt az időszakot használja (`lib/season.ts`).
|
||||
|
||||
## Az utalvány (PDF)
|
||||
|
||||
- **Mi van rajta:** egy A4-es, világos, nyomtatóbarát oldal:
|
||||
@@ -85,6 +98,9 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
||||
|
||||
## Admin
|
||||
|
||||
- **Időzített levelek** (Admin → Ajándékok, felül, ha van ilyen): óránként (magyar idő), hány levél vár, hány ment ki, hány hibás, az elmúlt 30 napra és előre. Az időpont után figyelni kell, hogy a „Kiment” megnőjön, és ne legyen hiba.
|
||||
- Soronként is látszik a levél állapota: „levél időzítve · időpont”, „küldés alatt”, „kiment”, „hiba”.
|
||||
- Visszatérítéskor a még ki nem ment időzített levél törlődik.
|
||||
- Az ajándékkódok nem jelennek meg az Admin → Promókódok listában; az ajándékok az Admin → Ajándékok oldalon vannak.
|
||||
|
||||
## Adatok
|
||||
@@ -93,6 +109,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
||||
- `gifts`: vásárló, csomag, a címzett neve és címe, a küldő neve, üzenet, fizetés ideje, a kód, a beváltás (ki, mikor, melyik rendelés), kiküldött levelek;
|
||||
- `stripe_checkouts.gift_id`: a fizetés ajándéka;
|
||||
- `gifts.refunded_at`, `refunded_by`, `refund_id`, `refund_error`: a visszatérítés;
|
||||
- `gifts.send_at`: az időzítés; `gifts.email_id`: az utolsó sorba állított levél (`email_outbox`; a levél a `next_attempt_at` időpontig vár, a worker 30 másodpercenként néz rá);
|
||||
- `invoice_cancellations`: a számla sztornója (állapot, próbálkozások, a Billingo sztornószámlája).
|
||||
- **A kód:** ugyanolyan formájú, mint a promókód (`ABCD-EFGH-JKLM`), és sosem egyezik eggyel sem (mindkét oldal ellenőrzi a másik táblát).
|
||||
- **Fiók törlése:** az ajándék beváltható marad, de a címzett neve és címe, a küldő neve és az üzenet törlődik.
|
||||
@@ -102,11 +119,11 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
|
||||
|
||||
| Végpont | Ki | Mit csinál |
|
||||
|---|---|---|
|
||||
| `POST /v1/gifts/checkout` `{package, recipient_name, recipient_email?, recipient_email_confirm?, from_name?, message?}` | belépett felhasználó | ajándék indítása; a válaszban a Stripe-oldal címe (`url`; tesztüzemben `null`, és már ki is fizette) |
|
||||
| `GET /v1/gifts` | belépett felhasználó | a kifizetett ajándékai |
|
||||
| `POST /v1/gifts/checkout` `{package, recipient_name, recipient_email?, recipient_email_confirm?, from_name?, message?, send_at?}` (RFC 3339) | belépett felhasználó | ajándék indítása; a válaszban a Stripe-oldal címe (`url`; tesztüzemben `null`, és már ki is fizette) |
|
||||
| `GET /v1/gifts` | belépett felhasználó | a kifizetett ajándékai (`send_at`, `email_state`, `christmas` is) |
|
||||
| `GET /v1/gifts/{id}/card.pdf` | a vásárló | az utalvány |
|
||||
| `POST /v1/gifts/{id}/send` `{recipient_email, recipient_email_confirm}` | a vásárló | küldés e-mailben (újra, vagy másik címre) |
|
||||
| `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | promókód vagy ajándékkód beváltása; ajándéknál `gift: {from_name}` is |
|
||||
| `GET /v1/payments/checkout/{id}` | a vásárló | a fizetés állapota; ajándéknál `gift: {id, recipient_name, recipient_email}` is |
|
||||
| `GET /v1/admin/gifts?q=` | admin | az ajándékok, fizetéssel, számlával, sztornóval |
|
||||
| `GET /v1/payments/checkout/{id}` | a vásárló | a fizetés állapota; ajándéknál `gift: {id, recipient_name, recipient_email, send_at}` is |
|
||||
| `GET /v1/admin/gifts?q=` | admin | az ajándékok, fizetéssel, számlával, sztornóval, a levél állapotával; `schedule`: az időzített levelek óránként |
|
||||
| `POST /v1/admin/gifts/{id}/refund` | admin | visszatérítés (csak beváltatlan ajándéknál; újrapróbálható, ha a Stripe visszautasította) |
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# Visszajelzések
|
||||
|
||||
A felhasználók elégedettségét a rendszeren belül mérjük: semmi nem megy e-mailben vagy Telegramon, és semmi nem nyilvános (ezek nem vélemények). Két alapelv:
|
||||
|
||||
- **Csak az értékel, aki megkapta a tartalmat:** belépve, a saját kész elemzését, válaszát vagy kártyajóslását, darabonként egyszer (később módosíthatja). Kívülálló nem tud tömegesen lepontozni.
|
||||
- **Belső marad:** a negatív vélemény nem rontja az oldal megítélését. Nyilvános értékelésekre külön szabályok vonatkoznának (fel kell tüntetni, hogyan ellenőrizzük őket); ezt így elkerüljük.
|
||||
|
||||
## 1. Értékelés a tartalmak alatt
|
||||
|
||||
- **Hol:** az ingyenes rövid összefoglaló, a részletes képletelemzés, a kapcsolati elemzés, az éves előrejelzés és a kártyajóslás végén egy kis doboz; a kérdésekre adott válaszok alatt 👍/👎.
|
||||
- **A kérdés:** „Mennyire érezted magadra szabottnak?” (1–5 csillag). Nem azt kérdezzük, hogy „igaz-e”: az asztrológia ingoványos terület.
|
||||
- **Egy kattintás menti a csillagot.** Utána kinyílik, nem kötelező:
|
||||
- **címkék:**
|
||||
- 1–3 csillagnál: *túl általános*, *ellentmondásos*, *hibás adat (pl. rossz jegy vagy ház)*, *nehezen érthető*, *túl hosszú*, *nem tetszett a hangnem*;
|
||||
- 4–5 csillagnál: *pontos*, *mély*, *jól érthető*, *hasznos*;
|
||||
- **megjegyzés:** max. 1000 karakter;
|
||||
- **„Megnézhetitek az elemzés szövegét, hogy javíthassatok rajta.”** Alapból nincs bejelölve.
|
||||
- **Másolat:** az értékelés mellé eltesszük, melyik modell és prompt-verzió írta a tartalmat, és hogy a felhasználó vásárló-e. Így a statisztika akkor is megmarad, ha az elemzést törlik.
|
||||
|
||||
## 2. Visszajelzés oldal (`/visszajelzes`)
|
||||
|
||||
- **Hol érhető el:**
|
||||
- a fiókmenü „Visszajelzés” pontja (a menü magával viszi, melyik oldalon volt a felhasználó);
|
||||
- a „Hiba jelzése” link a sikertelen elemzés, kártyajóslás és válasz üzeneténél;
|
||||
- a lábléc „Kapcsolat” linkje (a lábléc minden oldalon ott van): belépve ide visz, kijelentkezve a `/kapcsolat` oldalra, ami az info@sorsfonalak.hu címet mutatja, és hogy belépve az oldalon is írhat (Belépés gomb, utána ide jut).
|
||||
- **Az űrlap:**
|
||||
- típus: *Hiba*, *Ötlet*, *Kérdés*, *Egyéb*;
|
||||
- üzenet: max. 2000 karakter;
|
||||
- automatikusan velemegy az oldal, ahonnan jött, és a böngésző típusa. Születési adat nem.
|
||||
- **Korlát:** naponta legfeljebb 10 üzenet fiókonként.
|
||||
- **Korábbi üzenetek** ugyanezen az oldalon: az állapotuk (*Megkaptuk*, *Folyamatban*, *Megoldva*, *Lezárva*) és a válaszunk.
|
||||
- Új válasznál pötty jelenik meg a fiókmenüben; az oldal megnyitásával olvasottnak számít.
|
||||
- Nincs e-mail.
|
||||
|
||||
## 3. Ajánlási kérdés (NPS)
|
||||
|
||||
- **Kinek:** akinek már legalább 2 kész tartalma van (részletes elemzés, előrejelzés, kártyajóslás vagy válasz; az ingyenes összefoglaló nem számít). Az adminok és a szerzők nem kapják meg.
|
||||
- **Hogyan:** egyszer, egy bezárható dobozban az oldal legalján, a tartalom (a `main`) után és a lábléc előtt, külön: „Mennyire ajánlanád a Sorsfonalakat egy barátodnak?” (0–10), utána egy nem kötelező „Mi a legfontosabb oka?”. Fent túlságosan elvonta volna a figyelmet a tartalomról.
|
||||
- **Ha bezárja,** az is számít: nem jön elő újra.
|
||||
- **Pontszám:** a 9–10 ajánló, a 7–8 semleges, a 0–6 nem ajánló. Az NPS = (ajánlók − nem ajánlók) / válaszok × 100, −100 és 100 között.
|
||||
|
||||
## 4. Admin → Visszajelzések
|
||||
|
||||
Az admin menüben egy szám mutatja, mennyi az új: az új üzenetek, és az 1–2 csillagos vagy megjegyzéses értékelések, amelyeket még nem nézett meg.
|
||||
|
||||
- **Áttekintés** (7 / 30 / 90 nap / mind):
|
||||
- tartalomfajtánként: hány értékelés, átlag, az elégedettek (4–5) aránya;
|
||||
- vásárlók és nem vásárlók külön;
|
||||
- hetente;
|
||||
- a címkék gyakorisága;
|
||||
- modellenként és prompt-verziónként (így látszik, ha egy modell- vagy promptcsere rontott);
|
||||
- az NPS a megjegyzésekkel.
|
||||
- **Értékelések:**
|
||||
- szűrés: fajta, csak 1–2 csillag, csak megjegyzéses, csak még nem látott;
|
||||
- „Láttam” / „Mind láttam”;
|
||||
- a szöveg csak akkor nyitható meg, ha a felhasználó megengedte (a megnyitás naplózva van).
|
||||
- **Üzenetek:**
|
||||
- állapot szerint (nyitott, új, folyamatban, megoldva, elvetve, mind);
|
||||
- minden üzenetnél: belső jegyzet (csak az admin látja), válasz (a felhasználó a Visszajelzés oldalon látja), állapotváltás.
|
||||
|
||||
## Adatok
|
||||
|
||||
- **Táblák:**
|
||||
- `content_ratings`: értékelések, felhasználónként és tartalmanként egy;
|
||||
- `feedback_messages`: üzenetek, állapot, belső jegyzet, válasz;
|
||||
- `nps_answers`: az ajánlási kérdés, felhasználónként egy; bezárva pontszám nélkül.
|
||||
- **Fiók törlése:**
|
||||
- az értékelések és az NPS-válasz név és megjegyzés nélkül megmaradnak a statisztikához;
|
||||
- az üzenetek törlődnek.
|
||||
- **Adatvédelmi tájékoztató:** a 2. és a 7. pont írja le (2026. november 24.).
|
||||
|
||||
## API
|
||||
|
||||
| Végpont | Ki | Mit csinál |
|
||||
|---|---|---|
|
||||
| `PUT /v1/ratings` `{analysis_id \| question_id, stars, tags?, comment?, may_read?}` | a tartalom gazdája | értékelés (vagy módosítás) |
|
||||
| `GET /v1/ratings?analysis_ids=&question_ids=` | belépett felhasználó | a saját értékelései |
|
||||
| `POST /v1/feedback` `{category, body, page?}` / `GET /v1/feedback` | belépett felhasználó | üzenet küldése / a saját üzenetei a válaszokkal |
|
||||
| `POST /v1/feedback/seen` | belépett felhasználó | a válaszok olvasottak |
|
||||
| `POST /v1/nps` `{score: 0–10 \| null, comment?}` | belépett felhasználó | ajánlási kérdés (null: bezárta) |
|
||||
| `GET /v1/me` | belépett felhasználó | `feedback_replies_unseen`, `nps_due` |
|
||||
| `GET /v1/admin/feedback/count` | admin | az új tételek száma |
|
||||
| `GET /v1/admin/feedback/summary?days=` | admin | a számok |
|
||||
| `GET /v1/admin/ratings?kind=&max_stars=&with_comment=&unreviewed=` | admin | értékelések |
|
||||
| `POST /v1/admin/ratings/reviewed` `{ids?}` | admin | látottnak jelölés (ids nélkül: mind) |
|
||||
| `GET /v1/admin/ratings/{id}/content` | admin | az értékelt szöveg, ha a felhasználó megengedte |
|
||||
| `GET /v1/admin/feedback?status=` / `PATCH /v1/admin/feedback/{id}` `{status?, admin_note?, reply?}` | admin | üzenetek / állapot, jegyzet, válasz |
|
||||
@@ -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 \
|
||||
|
||||
@@ -132,18 +132,35 @@ pub async fn queue_email_to(
|
||||
locale: &str,
|
||||
payload: Value,
|
||||
) -> Result<(), ApiError> {
|
||||
queue_email_at(conn, user_id, to, template, locale, payload, None).await.map(drop)
|
||||
}
|
||||
|
||||
/// Queues an e-mail that the worker sends not before `at` (none: at once);
|
||||
/// returns its id.
|
||||
pub async fn queue_email_at(
|
||||
conn: &mut PgConnection,
|
||||
user_id: Option<Uuid>,
|
||||
to: &str,
|
||||
template: &str,
|
||||
locale: &str,
|
||||
payload: Value,
|
||||
at: Option<time::OffsetDateTime>,
|
||||
) -> Result<Uuid, ApiError> {
|
||||
let id = Uuid::now_v7();
|
||||
sqlx::query(
|
||||
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload, next_attempt_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, coalesce($7, now()))",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(id)
|
||||
.bind(user_id)
|
||||
.bind(to)
|
||||
.bind(template)
|
||||
.bind(locale)
|
||||
.bind(payload)
|
||||
.bind(at)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
Ok(())
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// The e-mails that carry a password link.
|
||||
|
||||
@@ -0,0 +1,764 @@
|
||||
//! Feedback, kept in the system (no e-mail, no Telegram), never shown
|
||||
//! publicly:
|
||||
//!
|
||||
//! * ratings of what a user got (summary, analyses, forecast, tarot: 1–5
|
||||
//! stars; answers to questions: thumbs), with tags and a comment; only the
|
||||
//! one who got it rates it, once (changeable). The rated text is readable
|
||||
//! for admins only if the user allows it (`may_read`);
|
||||
//! * messages from the "Visszajelzés" page (bug, idea, question), with a
|
||||
//! state and the operator's reply, both shown to the user there;
|
||||
//! * one "would you recommend us?" question (0–10, NPS), asked once in the
|
||||
//! app after a couple of finished contents (not of the team).
|
||||
//!
|
||||
//! Admins see it all on Admin → Visszajelzések; the admin menu counts what is
|
||||
//! new.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgConnection;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::analyses::{can_see, find_analysis};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::{AdminUser, AuthUser};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt};
|
||||
|
||||
/// Tags of a low and of a high rating (the frontend shows them in Hungarian).
|
||||
pub const TAGS: [&str; 10] = [
|
||||
"too_general",
|
||||
"contradictory",
|
||||
"wrong_data",
|
||||
"hard_to_read",
|
||||
"too_long",
|
||||
"tone",
|
||||
"accurate",
|
||||
"deep",
|
||||
"clear",
|
||||
"useful",
|
||||
];
|
||||
/// What can be rated (analysis kinds, and answers to questions).
|
||||
const RATED_KINDS: [&str; 5] = ["summary", "natal", "synastry", "forecast", "tarot"];
|
||||
const MAX_COMMENT: usize = 1000;
|
||||
const MAX_MESSAGE: usize = 2000;
|
||||
const MAX_REPLY: usize = 4000;
|
||||
/// Messages a user may send in 24 hours.
|
||||
const MESSAGES_PER_DAY: i64 = 10;
|
||||
/// The recommendation question comes after this many finished contents.
|
||||
const NPS_AFTER: i64 = 2;
|
||||
|
||||
/// User text: control characters out (line breaks kept), trimmed, at most `max` characters.
|
||||
fn clean_text(text: Option<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, has a couple of finished
|
||||
/// contents (the free summary does not count), and is no one of the team
|
||||
/// (admins and authors).
|
||||
pub async fn nps_due(conn: &mut PgConnection, user: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar(&format!(
|
||||
"SELECT NOT EXISTS (SELECT 1 FROM nps_answers WHERE user_id = $1) \
|
||||
AND NOT EXISTS (SELECT 1 FROM users WHERE id = $1 AND roles && ARRAY['admin', 'creator']) \
|
||||
AND (SELECT count(*) FROM analyses WHERE requested_by = $1 AND status = 'done' \
|
||||
AND kind IN ('natal', 'synastry', 'forecast', 'tarot')) \
|
||||
+ (SELECT count(*) FROM questions WHERE asked_by = $1 AND status = 'done') >= {NPS_AFTER}"
|
||||
))
|
||||
.bind(user)
|
||||
.fetch_one(conn)
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct NpsAnswer {
|
||||
/// 0–10; none: the question was closed.
|
||||
score: Option<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)))
|
||||
}
|
||||
@@ -26,7 +26,7 @@ use sqlx::PgConnection;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::auth::{normalize_email, queue_email_to};
|
||||
use super::auth::{normalize_email, queue_email_at};
|
||||
use super::promo::{CODE_LEN, display};
|
||||
use super::{Body, IdPath, St, payments};
|
||||
use crate::AppState;
|
||||
@@ -92,10 +92,31 @@ struct Gift {
|
||||
last_sent_at: Option<OffsetDateTime>,
|
||||
refunded_at: Option<OffsetDateTime>,
|
||||
refund_id: Option<String>,
|
||||
/// E-mailed not before this (none: at once).
|
||||
send_at: Option<OffsetDateTime>,
|
||||
/// The last e-mail queued for it.
|
||||
email_id: Option<Uuid>,
|
||||
/// That e-mail: `scheduled`, `sending`, `sent` or `failed` (none: no
|
||||
/// e-mail, or cleaned up a week after it went out).
|
||||
email_state: Option<String>,
|
||||
}
|
||||
|
||||
const COLUMNS: &str = "id, buyer_id, package, recipient_name, recipient_email, from_name, message, paid_at, code, \
|
||||
redeemed_at, sendings, last_sent_at, refunded_at, refund_id";
|
||||
redeemed_at, sendings, last_sent_at, refunded_at, refund_id, send_at, email_id, \
|
||||
(SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \
|
||||
WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \
|
||||
FROM email_outbox o WHERE o.id = gifts.email_id) AS email_state";
|
||||
|
||||
/// The year a Christmas gift wishes for ("csillagos 2027-et"), if bought
|
||||
/// between 15 November and 6 January (Budapest time; no summer time then).
|
||||
fn christmas_year(paid: OffsetDateTime) -> Option<i32> {
|
||||
let local = paid.to_offset(time::UtcOffset::from_hms(1, 0, 0).expect("an offset"));
|
||||
match (local.month(), local.day()) {
|
||||
(time::Month::November, 15..) | (time::Month::December, _) => Some(local.year() + 1),
|
||||
(time::Month::January, ..=6) => Some(local.year()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Gift {
|
||||
fn package(&self) -> Result<&'static Package, ApiError> {
|
||||
@@ -117,9 +138,15 @@ impl Gift {
|
||||
"recipient_name": self.recipient_name,
|
||||
"from_name": self.from_name,
|
||||
"message": self.message,
|
||||
"christmas_year": self.christmas(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// The year a Christmas gift wishes for (see `christmas_year`).
|
||||
fn christmas(&self) -> Option<i32> {
|
||||
christmas_year(self.paid_at.unwrap_or_else(OffsetDateTime::now_utc))
|
||||
}
|
||||
|
||||
fn status(&self) -> &'static str {
|
||||
match (self.redeemed_at, self.refunded_at) {
|
||||
(Some(_), _) => "redeemed",
|
||||
@@ -141,6 +168,8 @@ impl Gift {
|
||||
fn view(&self) -> Value {
|
||||
let status = self.status();
|
||||
let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc());
|
||||
// A timed e-mail still waiting can be sent now instead.
|
||||
let waiting = self.email_state.as_deref() == Some("scheduled");
|
||||
json!({
|
||||
"id": self.id,
|
||||
"package": { "id": self.package, "name": packages::find(&self.package).map(|p| p.name) },
|
||||
@@ -153,9 +182,12 @@ impl Gift {
|
||||
"status": status,
|
||||
"redeemed_at": rfc3339_opt(self.redeemed_at),
|
||||
"refunded_at": rfc3339_opt(self.refunded_at),
|
||||
"send_at": rfc3339_opt(self.send_at),
|
||||
"email_state": self.email_state,
|
||||
"christmas": self.christmas().is_some(),
|
||||
"sendings": self.sendings,
|
||||
"can_send": status == "open" && self.sendings < MAX_SENDINGS,
|
||||
"send_again_at": rfc3339_opt(next_send),
|
||||
"can_send": status == "open" && self.sendings - i32::from(waiting) < MAX_SENDINGS,
|
||||
"send_again_at": rfc3339_opt(next_send.filter(|_| !waiting)),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -185,6 +217,26 @@ pub struct GiftCheckout {
|
||||
recipient_email_confirm: Option<String>,
|
||||
from_name: Option<String>,
|
||||
message: Option<String>,
|
||||
/// E-mail it then (RFC 3339; none: right after paying), e.g. on Christmas morning.
|
||||
send_at: Option<String>,
|
||||
}
|
||||
|
||||
/// How far ahead a gift e-mail can be timed.
|
||||
const MAX_SCHEDULE: time::Duration = time::Duration::days(366);
|
||||
|
||||
/// A time to e-mail a gift: in the future (a few minutes at least), within a year.
|
||||
fn schedule(at: Option<&str>) -> Result<Option<OffsetDateTime>, ApiError> {
|
||||
let Some(at) = at.map(str::trim).filter(|a| !a.is_empty()) else { return Ok(None) };
|
||||
let at = OffsetDateTime::parse(at, &time::format_description::well_known::Rfc3339)
|
||||
.map_err(|_| ApiError::BadRequest("send_at must be an RFC 3339 time".into()))?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if at < now + time::Duration::minutes(5) {
|
||||
return Err(ApiError::BadRequest("Az időzítés legyen a jövőben.".into()));
|
||||
}
|
||||
if at > now + MAX_SCHEDULE {
|
||||
return Err(ApiError::BadRequest("Legfeljebb egy évre előre lehet időzíteni.".into()));
|
||||
}
|
||||
Ok(Some(at))
|
||||
}
|
||||
|
||||
/// Starts paying for a gift: returns the address of Stripe's payment page.
|
||||
@@ -200,6 +252,10 @@ pub async fn checkout(
|
||||
let to = recipient(req.recipient_email.as_deref(), req.recipient_email_confirm.as_deref())?;
|
||||
let from = clean_name(req.from_name)?;
|
||||
let message = super::invitations::clean_message(req.message)?;
|
||||
let send_at = schedule(req.send_at.as_deref())?;
|
||||
if send_at.is_some() && to.is_none() {
|
||||
return Err(ApiError::BadRequest("Időzíteni csak az e-mailben küldött ajándékot lehet.".into()));
|
||||
}
|
||||
// Whether this user may pay, before anything is written.
|
||||
let stripe = match payments::method(&state.config) {
|
||||
Some("stripe") => Some(payments::stripe_for(&state, &auth)?),
|
||||
@@ -208,8 +264,8 @@ pub async fn checkout(
|
||||
};
|
||||
let id = Uuid::now_v7();
|
||||
sqlx::query(
|
||||
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message, send_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(auth.id())
|
||||
@@ -218,6 +274,7 @@ pub async fn checkout(
|
||||
.bind(&to)
|
||||
.bind(&from)
|
||||
.bind(&message)
|
||||
.bind(send_at)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
let url = match stripe {
|
||||
@@ -242,6 +299,8 @@ pub struct Paid {
|
||||
pub recipient_name: Option<String>,
|
||||
pub recipient_email: Option<String>,
|
||||
pub card: Value,
|
||||
/// When it is e-mailed, on the Budapest clock (`2026-12-24 08:00`); none: at once.
|
||||
pub send_at_local: Option<String>,
|
||||
}
|
||||
|
||||
/// A new gift code, never the same as a promo code or another gift's.
|
||||
@@ -276,20 +335,38 @@ pub async fn fulfil(tx: &mut PgConnection, state: &AppState, id: Uuid) -> Result
|
||||
.await?;
|
||||
gift.code = Some(code);
|
||||
if let Some(to) = gift.recipient_email.clone() {
|
||||
send(tx, state, &gift, &to).await?;
|
||||
// Timed for a moment already past (paid late): at once.
|
||||
let at = gift.send_at.filter(|t| *t > OffsetDateTime::now_utc());
|
||||
send(tx, state, &gift, &to, at).await?;
|
||||
}
|
||||
tracing::info!(gift = %id, package = %gift.package, by_email = gift.recipient_email.is_some(), "gift paid");
|
||||
}
|
||||
let send_at_local: Option<String> = sqlx::query_scalar(
|
||||
"SELECT to_char(send_at AT TIME ZONE 'Europe/Budapest', 'YYYY-MM-DD HH24:MI') FROM gifts \
|
||||
WHERE id = $1 AND send_at > now()",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.flatten();
|
||||
Ok(Paid {
|
||||
code: display(gift.code()?),
|
||||
card: gift.card_payload(state)?,
|
||||
recipient_name: gift.recipient_name,
|
||||
recipient_email: gift.recipient_email,
|
||||
send_at_local,
|
||||
})
|
||||
}
|
||||
|
||||
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language.
|
||||
async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) -> Result<(), ApiError> {
|
||||
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language,
|
||||
/// not before `at` (none: at once).
|
||||
async fn send(
|
||||
tx: &mut PgConnection,
|
||||
state: &AppState,
|
||||
gift: &Gift,
|
||||
to: &str,
|
||||
at: Option<OffsetDateTime>,
|
||||
) -> Result<(), ApiError> {
|
||||
let locale: Option<String> = sqlx::query_scalar("SELECT locale FROM users WHERE id = $1")
|
||||
.bind(gift.buyer_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
@@ -304,16 +381,38 @@ async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) ->
|
||||
"from_name": gift.from_name,
|
||||
"message": gift.message,
|
||||
"gift_card": gift.card_payload(state)?,
|
||||
"christmas_year": gift.christmas(),
|
||||
});
|
||||
// Not the recipient's account (if they have one): no user id.
|
||||
queue_email_to(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload).await?;
|
||||
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now() WHERE id = $1")
|
||||
let email = queue_email_at(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload, at).await?;
|
||||
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now(), email_id = $2 WHERE id = $1")
|
||||
.bind(gift.id)
|
||||
.bind(email)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes back the gift's e-mail if it has not gone out yet (sent now
|
||||
/// instead, or refunded): a timed one would come later otherwise. It does
|
||||
/// not count as a sending then.
|
||||
async fn cancel_pending_email(conn: &mut PgConnection, gift: &Gift) -> Result<bool, sqlx::Error> {
|
||||
let Some(email) = gift.email_id else { return Ok(false) };
|
||||
let taken = sqlx::query("DELETE FROM email_outbox WHERE id = $1 AND sent_at IS NULL AND failed_at IS NULL")
|
||||
.bind(email)
|
||||
.execute(&mut *conn)
|
||||
.await?
|
||||
.rows_affected()
|
||||
== 1;
|
||||
if taken {
|
||||
sqlx::query("UPDATE gifts SET sendings = greatest(sendings - 1, 0) WHERE id = $1")
|
||||
.bind(gift.id)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
}
|
||||
Ok(taken)
|
||||
}
|
||||
|
||||
/// The user's paid gifts, newest first.
|
||||
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let gifts: Vec<Gift> = sqlx::query_as(&format!(
|
||||
@@ -339,6 +438,7 @@ pub async fn card(
|
||||
let code = display(gift.code()?);
|
||||
let url = redeem_url(&state, gift.code()?);
|
||||
let filename = format!("sorsfonalak-ajandek-{code}.pdf");
|
||||
let christmas = gift.christmas();
|
||||
let pdf = tokio::task::spawn_blocking(move || {
|
||||
let contents = package.contents_items();
|
||||
gift_card::pdf(&gift_card::Card {
|
||||
@@ -349,6 +449,7 @@ pub async fn card(
|
||||
recipient_name: gift.recipient_name.as_deref(),
|
||||
from_name: gift.from_name.as_deref(),
|
||||
message: gift.message.as_deref(),
|
||||
christmas,
|
||||
})
|
||||
})
|
||||
.await
|
||||
@@ -387,18 +488,26 @@ pub async fn send_again(
|
||||
return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották."));
|
||||
}
|
||||
gift.refused_if_refunded()?;
|
||||
if gift.sendings >= MAX_SENDINGS {
|
||||
// A timed e-mail still waiting is replaced by this one, not added to it.
|
||||
let waiting = gift.email_state.as_deref() == Some("scheduled");
|
||||
if gift.sendings - i32::from(waiting) >= MAX_SENDINGS {
|
||||
return Err(ApiError::conflict(
|
||||
"gift_send_limit",
|
||||
"Ezt az ajándékot már háromszor elküldtük e-mailben. Töltsd le az utalványt, és küldd el te magad.",
|
||||
));
|
||||
}
|
||||
if gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
|
||||
if !waiting && gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
|
||||
return Err(ApiError::conflict("gift_send_wait", "Pár perc múlva küldheted el újra."));
|
||||
}
|
||||
sqlx::query("UPDATE gifts SET recipient_email = $2 WHERE id = $1").bind(id).bind(&to).execute(&mut *tx).await?;
|
||||
// Now, instead of a timed e-mail still waiting.
|
||||
cancel_pending_email(&mut tx, &gift).await?;
|
||||
sqlx::query("UPDATE gifts SET recipient_email = $2, send_at = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(&to)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
gift.recipient_email = Some(to.clone());
|
||||
send(&mut tx, &state, &gift, &to).await?;
|
||||
send(&mut tx, &state, &gift, &to, None).await?;
|
||||
let gift = own_gift(&mut tx, id, auth.id(), false).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(user = %auth.id(), gift = %id, "gift sent by e-mail");
|
||||
@@ -469,6 +578,8 @@ struct AdminGift {
|
||||
storno_status: Option<String>,
|
||||
storno_number: Option<String>,
|
||||
storno_error: Option<String>,
|
||||
send_at: Option<OffsetDateTime>,
|
||||
email_state: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -493,7 +604,11 @@ pub async fn admin_list(
|
||||
g.redeemed_at, r.email AS redeemed_by, g.refunded_at, g.refund_id, g.refund_error, \
|
||||
c.id AS checkout_id, c.live, coalesce(c.amount_huf, c.price_huf) AS amount_huf, \
|
||||
i.invoice_number, i.status AS invoice_status, \
|
||||
x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error \
|
||||
x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error, \
|
||||
g.send_at, \
|
||||
(SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \
|
||||
WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \
|
||||
FROM email_outbox o WHERE o.id = g.email_id) AS email_state \
|
||||
FROM gifts g LEFT JOIN users b ON b.id = g.buyer_id LEFT JOIN users r ON r.id = g.redeemed_by \
|
||||
LEFT JOIN stripe_checkouts c ON c.gift_id = g.id LEFT JOIN invoices i ON i.checkout_id = c.id \
|
||||
LEFT JOIN invoice_cancellations x ON x.invoice_id = i.id \
|
||||
@@ -535,10 +650,29 @@ pub async fn admin_list(
|
||||
"checkout": g.checkout_id.map(|id| json!({ "id": id, "live": g.live, "amount_huf": g.amount_huf })),
|
||||
"invoice": g.invoice_status.map(|s| json!({ "number": g.invoice_number, "status": s })),
|
||||
"storno": g.storno_status.map(|s| json!({ "status": s, "number": g.storno_number, "error": g.storno_error })),
|
||||
"send_at": rfc3339_opt(g.send_at),
|
||||
"email_state": g.email_state,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "gifts": gifts, "withdrawal_days": WITHDRAWAL_DAYS })))
|
||||
// The timed e-mails by hour (Budapest clock): how many wait, went out or failed.
|
||||
let schedule: Vec<(String, i64, i64, i64)> = sqlx::query_as(
|
||||
"SELECT to_char(date_trunc('hour', g.send_at AT TIME ZONE 'Europe/Budapest'), 'YYYY-MM-DD HH24:MI'), \
|
||||
count(*) FILTER (WHERE o.id IS NOT NULL AND o.sent_at IS NULL AND o.failed_at IS NULL), \
|
||||
count(*) FILTER (WHERE o.sent_at IS NOT NULL OR (o.id IS NULL AND g.send_at <= now())), \
|
||||
count(*) FILTER (WHERE o.failed_at IS NOT NULL) \
|
||||
FROM gifts g LEFT JOIN email_outbox o ON o.id = g.email_id \
|
||||
WHERE g.send_at IS NOT NULL AND g.paid_at IS NOT NULL AND g.refunded_at IS NULL \
|
||||
AND g.send_at > now() - interval '30 days' \
|
||||
GROUP BY 1 ORDER BY 1",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let schedule: Vec<Value> = schedule
|
||||
.into_iter()
|
||||
.map(|(at, waiting, sent, failed)| json!({ "at": at, "waiting": waiting, "sent": sent, "failed": failed }))
|
||||
.collect();
|
||||
Ok(Json(json!({ "gifts": gifts, "schedule": schedule, "withdrawal_days": WITHDRAWAL_DAYS })))
|
||||
}
|
||||
|
||||
/// Admin: refunds a gift the buyer withdrew from. Refused once it is
|
||||
@@ -577,6 +711,8 @@ pub async fn admin_refund(
|
||||
.bind(admin.0.id())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// A timed e-mail not gone out yet stays unsent.
|
||||
cancel_pending_email(&mut tx, &gift).await?;
|
||||
if let Some((checkout_id, _)) = &checkout {
|
||||
let reason = format!("Elállás az ajándékcsomag vásárlásától (beváltás előtt), kód: {}", display(gift.code()?));
|
||||
sqlx::query(
|
||||
@@ -634,3 +770,25 @@ pub async fn admin_refund(
|
||||
json!({ "status": gift.status(), "refund_id": gift.refund_id, "refunded_at": rfc3339_opt(gift.refunded_at) }),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
|
||||
use super::christmas_year;
|
||||
|
||||
fn at(s: &str) -> OffsetDateTime {
|
||||
OffsetDateTime::parse(s, &Rfc3339).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn christmas_runs_from_mid_november_to_epiphany() {
|
||||
assert_eq!(christmas_year(at("2026-11-14T22:59:00Z")), None);
|
||||
assert_eq!(christmas_year(at("2026-11-14T23:00:00Z")), Some(2027));
|
||||
assert_eq!(christmas_year(at("2026-12-31T23:30:00Z")), Some(2027));
|
||||
assert_eq!(christmas_year(at("2027-01-06T22:59:00Z")), Some(2027));
|
||||
assert_eq!(christmas_year(at("2027-01-06T23:00:00Z")), None);
|
||||
assert_eq!(christmas_year(at("2027-07-01T12:00:00Z")), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -327,6 +327,7 @@ async fn confirm_by_email(
|
||||
"promo_code": gift.code,
|
||||
"recipient_name": gift.recipient_name,
|
||||
"recipient_email": gift.recipient_email,
|
||||
"send_at": gift.send_at_local,
|
||||
});
|
||||
// Handed over by the buyer: the card comes with the confirmation.
|
||||
if gift.recipient_email.is_none() {
|
||||
@@ -375,13 +376,16 @@ pub async fn checkout_status(
|
||||
}
|
||||
let gift = match gift_id {
|
||||
Some(id) => {
|
||||
let (name, to): (Option<String>, Option<String>) =
|
||||
sqlx::query_as("SELECT recipient_name, recipient_email FROM gifts WHERE id = $1")
|
||||
let (name, to, send_at): (Option<String>, Option<String>, Option<OffsetDateTime>) =
|
||||
sqlx::query_as("SELECT recipient_name, recipient_email, send_at FROM gifts WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.unwrap_or_default();
|
||||
Some(json!({ "id": id, "recipient_name": name, "recipient_email": to }))
|
||||
Some(json!({
|
||||
"id": id, "recipient_name": name, "recipient_email": to,
|
||||
"send_at": crate::views::rfc3339_opt(send_at.filter(|t| *t > OffsetDateTime::now_utc())),
|
||||
}))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
@@ -3413,7 +3413,7 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
confirmation["gift"],
|
||||
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com"})
|
||||
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com", "send_at": null})
|
||||
);
|
||||
assert!(confirmation["gift_card"].is_null(), "the recipient has the card");
|
||||
assert_eq!(confirmation["url"], "https://sorsfonalak.test/ajandekaim");
|
||||
@@ -3426,7 +3426,10 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
|
||||
.unwrap();
|
||||
assert_eq!(invoices, 1);
|
||||
let r = app.get(&format!("/v1/payments/checkout/{session}"), Some(&anna)).await;
|
||||
assert_eq!(r.body["gift"], json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com"}));
|
||||
assert_eq!(
|
||||
r.body["gift"],
|
||||
json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com", "send_at": null})
|
||||
);
|
||||
|
||||
let r = app.get("/v1/gifts", Some(&anna)).await;
|
||||
let gift = &r.body["gifts"][0];
|
||||
@@ -3459,8 +3462,10 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
|
||||
sqlx::query("UPDATE gifts SET last_sent_at = now() - interval '11 minutes'").execute(&app.pool).await.unwrap();
|
||||
let r = send("cili@example.com").await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(2)));
|
||||
// The first e-mail had not gone out yet (no worker here): the corrected address replaces it.
|
||||
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(1)));
|
||||
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
|
||||
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 0);
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/v1/gifts/{gift_id}/send"),
|
||||
@@ -3707,3 +3712,323 @@ 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);
|
||||
// Not the team: an admin is not asked.
|
||||
let admin_id = user_id(&app, &admin).await;
|
||||
for _ in 0..2 {
|
||||
analysis_row(&app, "tarot", None, admin_id, "done").await;
|
||||
}
|
||||
assert_eq!(app.get("/v1/me", Some(&admin)).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.");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn a_gift_can_be_e_mailed_at_a_chosen_time(pool: PgPool) {
|
||||
// The stand-in payment: paid at once.
|
||||
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 at = (time::OffsetDateTime::now_utc() + time::Duration::days(10))
|
||||
.replace_nanosecond(0)
|
||||
.unwrap()
|
||||
.format(&time::format_description::well_known::Rfc3339)
|
||||
.unwrap();
|
||||
let body = |send_at: &str, email: Option<&str>| {
|
||||
json!({"package": "couple", "recipient_name": "Bea", "recipient_email": email,
|
||||
"recipient_email_confirm": email, "send_at": send_at})
|
||||
};
|
||||
// In the past, or with nobody to e-mail: refused.
|
||||
let past = app.post("/v1/gifts/checkout", Some(&anna), body("2020-01-01T08:00:00Z", Some("bea@example.com"))).await;
|
||||
assert_eq!(past.status, StatusCode::BAD_REQUEST);
|
||||
let nobody = app.post("/v1/gifts/checkout", Some(&anna), body(&at, None)).await;
|
||||
assert_eq!(nobody.status, StatusCode::BAD_REQUEST);
|
||||
|
||||
let r = app.post("/v1/gifts/checkout", Some(&anna), body(&at, Some("bea@example.com"))).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let id = r.body["id"].as_str().unwrap().to_string();
|
||||
// Queued for that moment, not sent yet.
|
||||
let (due, sent): (time::OffsetDateTime, Option<time::OffsetDateTime>) = sqlx::query_as(
|
||||
"SELECT next_attempt_at, sent_at FROM email_outbox WHERE to_email = 'bea@example.com' AND template = 'gift_package'",
|
||||
)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((due.format(&time::format_description::well_known::Rfc3339).unwrap(), sent), (at.clone(), None));
|
||||
let r = app.get("/v1/gifts", Some(&anna)).await;
|
||||
let gift = &r.body["gifts"][0];
|
||||
assert_eq!(
|
||||
(&gift["email_state"], &gift["send_at"], &gift["can_send"]),
|
||||
(&json!("scheduled"), &json!(at), &json!(true))
|
||||
);
|
||||
let r = app.get("/v1/admin/gifts", Some(&admin)).await;
|
||||
assert_eq!(r.body["gifts"][0]["email_state"], "scheduled");
|
||||
let slot = &r.body["schedule"][0];
|
||||
assert_eq!((&slot["waiting"], &slot["sent"]), (&json!(1), &json!(0)));
|
||||
|
||||
// Sent now after all: the timed one is taken back (one e-mail, not two), and it is no extra sending.
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/v1/gifts/{id}/send"),
|
||||
Some(&anna),
|
||||
json!({"recipient_email": "bea@example.com", "recipient_email_confirm": "bea@example.com"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(
|
||||
(&r.body["send_at"], &r.body["sendings"], &r.body["email_state"]),
|
||||
(&Value::Null, &json!(1), &json!("sending"))
|
||||
);
|
||||
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 1);
|
||||
|
||||
// A timed gift refunded before it goes out: the e-mail stays unsent.
|
||||
let r = app.post("/v1/gifts/checkout", Some(&anna), body(&at, Some("cili@example.com"))).await;
|
||||
let other = r.body["id"].as_str().unwrap().to_string();
|
||||
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
|
||||
let r = app.post(&format!("/v1/admin/gifts/{other}/refund"), Some(&admin), json!({})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 0);
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
@@ -3,7 +3,9 @@ import Link from "next/link";
|
||||
import { ChartWheel } from "@/components/ChartWheel";
|
||||
import { Rich } from "@/components/Rich";
|
||||
import { TarotCard, TarotCardBack } from "@/components/tarot/TarotCard";
|
||||
import { Logo, PublicHeader } from "@/components/SiteHeader";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { ChristmasTree } from "@/components/ChristmasTree";
|
||||
import { isChristmasTime } from "@/lib/season";
|
||||
import example from "@/content/pelda.json";
|
||||
import { tarotCard } from "@/lib/tarot";
|
||||
import type { AnalysisContent, ChartResult } from "@/lib/types";
|
||||
@@ -42,6 +44,8 @@ const SYNASTRY_TOPICS = ["Vonzás", "Kommunikáció", "Érzelmi kötődés", "S
|
||||
/** The home page for visitors: what the site does, shown on the example chart. */
|
||||
/** `loggedIn`: the layout shows the app's header, and the buttons lead to the user's chart instead of the login. */
|
||||
export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean; loggedIn?: boolean }) {
|
||||
// In the Christmas season the gift band leads to the Christmas page.
|
||||
const xmas = isChristmasTime();
|
||||
const chart = example.chart as unknown as ChartResult;
|
||||
const analysis = example.analysis as AnalysisContent;
|
||||
const sections = ["emotions", "love"].map((k) => analysis.sections?.[k]).filter((s) => s !== undefined);
|
||||
@@ -442,6 +446,35 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="lp-band lp-alt lp-gift" aria-labelledby="gift-band-title">
|
||||
<div className="lp-wrap lp-gift-inner">
|
||||
{xmas && <ChristmasTree size={72} />}
|
||||
<div className="lp-gift-text">
|
||||
<span className="eyebrow">{xmas ? "Karácsonyi ajándék" : "Ajándék"}</span>
|
||||
<h2 id="gift-band-title" className="lp-h2">
|
||||
{xmas ? "Ajándékozz csillagokat karácsonyra" : "Horoszkópot ajándékba"}
|
||||
</h2>
|
||||
<p className="lp-text">
|
||||
Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve, egy szép, nyomtatható
|
||||
utalvánnyal.{" "}
|
||||
{xmas ? "Az e-mailt karácsony reggelre is időzítheted." : "E-mailben küldjük el neki, vagy te adod át."}
|
||||
</p>
|
||||
<Link href={xmas ? "/karacsony" : "/ajandek"} className="btn lp-btn">
|
||||
{xmas ? "Karácsonyi ajándék" : "Ajándékozás"}
|
||||
</Link>
|
||||
</div>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
className="lp-gift-card"
|
||||
src={xmas ? "/img/ajandek-karacsony.webp" : "/img/ajandek-utalvany.webp"}
|
||||
width={200}
|
||||
height={283}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="lp-band">
|
||||
<div className="lp-wrap lp-stack">
|
||||
<h2 className="lp-h2 lp-center">Így működik</h2>
|
||||
@@ -499,29 +532,15 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer className="lp-footer">
|
||||
<div className="lp-wrap lp-partners">
|
||||
<span className="hint">Fizetés</span>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/logos/stripe.svg" alt="Stripe" width="62" height="26" className="lp-partner" />
|
||||
<span className="hint">Számlázás</span>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/logos/billingo.svg" alt="Billingo" width="80" height="26" className="lp-partner" />
|
||||
</div>
|
||||
<div className="lp-wrap lp-footer-inner">
|
||||
<Logo />
|
||||
<nav aria-label="Lábléc" className="lp-footer-nav">
|
||||
<Link href="/szuletesi-horoszkop">Születési horoszkóp</Link>
|
||||
<Link href="/csillagjegyek">Csillagjegyek</Link>
|
||||
<Link href="/pelda">Példaelemzés</Link>
|
||||
<Link href="/kartyajoslas/pelda">Példajóslás</Link>
|
||||
<Link href="/aszf">ÁSZF</Link>
|
||||
<Link href="/adatvedelem">Adatvédelem</Link>
|
||||
{!loggedIn && <Link href="/belepes">Belépés</Link>}
|
||||
</nav>
|
||||
<span className="hint">© {new Date().getFullYear()} Sorsfonalak</span>
|
||||
</div>
|
||||
</footer>
|
||||
{/* Who takes the payments and makes the invoices, above the common footer. */}
|
||||
<div className="lp-wrap lp-partners">
|
||||
<span className="hint">Fizetés</span>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/logos/stripe.svg" alt="Stripe" width="62" height="26" className="lp-partner" />
|
||||
<span className="hint">Számlázás</span>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src="/logos/billingo.svg" alt="Billingo" width="80" height="26" className="lp-partner" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,11 +8,26 @@ 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" };
|
||||
/** The timed gift e-mails of one hour. */
|
||||
type Slot = { at: string; waiting: number; sent: number; failed: number };
|
||||
|
||||
const EMAIL: Record<string, string> = {
|
||||
scheduled: "levél időzítve",
|
||||
sending: "levél küldés alatt",
|
||||
sent: "levél kiment",
|
||||
failed: "levél 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() {
|
||||
const [gifts, setGifts] = useState<AdminGift[] | null>(null);
|
||||
const [schedule, setSchedule] = useState<Slot[]>([]);
|
||||
const [q, setQ] = useState("");
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -20,8 +35,11 @@ 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[]; schedule: Slot[] }>(
|
||||
`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`,
|
||||
);
|
||||
setGifts(r.gifts);
|
||||
setSchedule(r.schedule ?? []);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
}
|
||||
@@ -33,8 +51,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}`,
|
||||
@@ -56,121 +78,203 @@ export function AdminGifts() {
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="card">
|
||||
<div className="field">
|
||||
<label htmlFor="gift-search">Keresés</label>
|
||||
<input
|
||||
id="gift-search"
|
||||
className="inp"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{done && (
|
||||
<p className="msg msg-ok" role="status">
|
||||
{done}
|
||||
</p>
|
||||
)}
|
||||
{gifts === null ? (
|
||||
<p className="muted">Betöltés…</p>
|
||||
) : gifts.length === 0 ? (
|
||||
<p className="muted">Nincs ilyen ajándék.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Kód</th>
|
||||
<th>Csomag</th>
|
||||
<th>Vásárló → címzett</th>
|
||||
<th>Fizetve</th>
|
||||
<th>Állapot</th>
|
||||
<th>Számla</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{gifts.map((g) => (
|
||||
<tr key={g.id}>
|
||||
<td>
|
||||
<code className="promo-code">{g.code}</code>
|
||||
</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>}
|
||||
</td>
|
||||
<td>
|
||||
{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)"}
|
||||
</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>}
|
||||
</>
|
||||
) : g.status === "refunded" ? (
|
||||
<>
|
||||
{g.refund_pending ? (
|
||||
<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>}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="promo-open">beváltatlan</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.storno && (
|
||||
<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}` : ""}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="muted">–</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{(g.status === "open" || g.refund_pending) && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => refund(g)}
|
||||
disabled={busy !== null}
|
||||
>
|
||||
{busy === g.id ? "Folyamatban…" : g.status === "refunded" ? "Újrapróbálás" : "Visszatérítés"}
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
<>
|
||||
{schedule.length > 0 && (
|
||||
<section className="card" aria-labelledby="schedule-title">
|
||||
<h2 id="schedule-title">Időzített levelek</h2>
|
||||
<p className="hint">
|
||||
Az időzítve küldött ajándéklevelek óránként (magyar idő, az elmúlt
|
||||
30 nap és ami még jön). Figyeld, hogy a kiment levelek száma az
|
||||
időpont után megnőjön, és ne legyen hiba.
|
||||
</p>
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Időpont</th>
|
||||
<th>Vár</th>
|
||||
<th>Kiment</th>
|
||||
<th>Hiba</th>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</thead>
|
||||
<tbody>
|
||||
{schedule.map((s) => (
|
||||
<tr key={s.at}>
|
||||
<td className="num">{s.at}</td>
|
||||
<td className="num">{s.waiting || "–"}</td>
|
||||
<td className="num">{s.sent || "–"}</td>
|
||||
<td className={s.failed ? "num msg-error" : "num"}>
|
||||
{s.failed || "–"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</section>
|
||||
<section className="card">
|
||||
<div className="field">
|
||||
<label htmlFor="gift-search">Keresés</label>
|
||||
<input
|
||||
id="gift-search"
|
||||
className="inp"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{done && (
|
||||
<p className="msg msg-ok" role="status">
|
||||
{done}
|
||||
</p>
|
||||
)}
|
||||
{gifts === null ? (
|
||||
<p className="muted">Betöltés…</p>
|
||||
) : gifts.length === 0 ? (
|
||||
<p className="muted">Nincs ilyen ajándék.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Kód</th>
|
||||
<th>Csomag</th>
|
||||
<th>Vásárló → címzett</th>
|
||||
<th>Fizetve</th>
|
||||
<th>Állapot</th>
|
||||
<th>Számla</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{gifts.map((g) => (
|
||||
<tr key={g.id}>
|
||||
<td>
|
||||
<code className="promo-code">{g.code}</code>
|
||||
</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>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{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)"}
|
||||
</span>
|
||||
{g.email_state && (
|
||||
<span
|
||||
className={
|
||||
g.email_state === "failed"
|
||||
? "hint msg-error"
|
||||
: "hint"
|
||||
}
|
||||
>
|
||||
{EMAIL[g.email_state]}
|
||||
{g.send_at ? ` · ${formatDate(g.send_at, true)}` : ""}
|
||||
</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>
|
||||
)}
|
||||
</>
|
||||
) : g.status === "refunded" ? (
|
||||
<>
|
||||
{g.refund_pending ? (
|
||||
<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>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="promo-open">beváltatlan</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.storno && (
|
||||
<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}` : ""}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="muted">–</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{(g.status === "open" || g.refund_pending) && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => refund(g)}
|
||||
disabled={busy !== null}
|
||||
>
|
||||
{busy === g.id
|
||||
? "Folyamatban…"
|
||||
: g.status === "refunded"
|
||||
? "Újrapróbálás"
|
||||
: "Visszatérítés"}
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -7,13 +7,29 @@ import { useEffect, useId, useState } from "react";
|
||||
import { huf } from "@/components/PackageCards";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { contents } from "@/lib/packageContents";
|
||||
import { christmasMorning } from "@/lib/season";
|
||||
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();
|
||||
|
||||
/** `2026-12-24` on the browser's clock. */
|
||||
const localDay = (d: Date) =>
|
||||
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
|
||||
/** "dec. 24. 8:00" */
|
||||
const whenText = (d: Date) =>
|
||||
d.toLocaleString("hu-HU", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
});
|
||||
|
||||
/**
|
||||
* The gift order: which package, whom it is for and from whom, how it gets
|
||||
@@ -36,7 +52,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);
|
||||
@@ -44,6 +63,10 @@ export function GiftForm({
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [from, setFrom] = useState(defaultFrom.slice(0, MAX_NAME));
|
||||
const [message, setMessage] = useState("");
|
||||
const [timed, setTimed] = useState(false);
|
||||
const xmas = christmasMorning();
|
||||
const [day, setDay] = useState(xmas ? localDay(xmas) : "");
|
||||
const [clock, setClock] = useState("08:00");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Back from Stripe's page (the browser may restore this page as it was).
|
||||
@@ -59,6 +82,14 @@ export function GiftForm({
|
||||
const mismatch = byEmail && confirm.trim() !== "" && !same(email, confirm);
|
||||
const emailOk = !byEmail || (looksLikeEmail(email) && same(email, confirm));
|
||||
const stripe = canPay === "stripe" || canPay === "stripe_test";
|
||||
// The chosen moment on the buyer's own clock.
|
||||
const sendAt = day && clock ? new Date(`${day}T${clock}`) : null;
|
||||
const ahead = sendAt ? sendAt.getTime() - Date.now() : 0;
|
||||
const timeOk =
|
||||
sendAt !== null &&
|
||||
!Number.isNaN(ahead) &&
|
||||
ahead > 10 * 60 * 1000 &&
|
||||
ahead < 365 * 86400 * 1000;
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
@@ -66,16 +97,20 @@ 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,
|
||||
send_at: byEmail && timed && sendAt ? sendAt.toISOString() : null,
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
if (r.url) {
|
||||
window.location.assign(r.url);
|
||||
return;
|
||||
@@ -93,8 +128,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 +184,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 +224,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,12 +238,93 @@ 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>
|
||||
)}
|
||||
{byEmail && (
|
||||
<div className="gift-when">
|
||||
<span className="label">Mikor kapja meg?</span>
|
||||
<div className="gift-when-choices">
|
||||
<label
|
||||
className={!timed ? "feedback-kind is-on" : "feedback-kind"}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name={`${id}-when`}
|
||||
checked={!timed}
|
||||
onChange={() => setTimed(false)}
|
||||
/>
|
||||
Fizetés után azonnal
|
||||
</label>
|
||||
<label
|
||||
className={timed ? "feedback-kind is-on" : "feedback-kind"}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name={`${id}-when`}
|
||||
checked={timed}
|
||||
onChange={() => setTimed(true)}
|
||||
/>
|
||||
Időzítve
|
||||
</label>
|
||||
{xmas && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => {
|
||||
setTimed(true);
|
||||
setDay(localDay(xmas));
|
||||
setClock("08:00");
|
||||
}}
|
||||
>
|
||||
Karácsony reggel (dec. 24., 8:00)
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{timed && (
|
||||
<div className="gift-when-fields">
|
||||
<div className="field">
|
||||
<label htmlFor={`${id}-day`}>Nap</label>
|
||||
<input
|
||||
id={`${id}-day`}
|
||||
className="inp"
|
||||
type="date"
|
||||
value={day}
|
||||
min={localDay(new Date())}
|
||||
onChange={(e) => setDay(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor={`${id}-clock`}>Időpont</label>
|
||||
<input
|
||||
id={`${id}-clock`}
|
||||
className="inp"
|
||||
type="time"
|
||||
step={900}
|
||||
value={clock}
|
||||
onChange={(e) => setClock(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<span className={timed && !timeOk ? "msg msg-error" : "hint"}>
|
||||
{timed
|
||||
? timeOk
|
||||
? "A te időd szerint. Addig az Ajándékaim oldalon letöltheted az utalványt, vagy elküldheted azonnal is."
|
||||
: "Válassz egy jövőbeli időpontot (legfeljebb egy évre előre)."
|
||||
: "Ha későbbre szánod, időzítsd, vagy válaszd az „Én adom át” lehetőséget."}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<div className="field">
|
||||
@@ -200,7 +339,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 +353,34 @@ 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` : ""}
|
||||
{byEmail && timed && sendAt && timeOk
|
||||
? ` · küldés: ${whenText(sendAt)}`
|
||||
: ""}
|
||||
</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() ||
|
||||
(byEmail && timed && !timeOk)
|
||||
}
|
||||
>
|
||||
{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 +388,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>
|
||||
|
||||
@@ -1,20 +1,50 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { GiftLanding } from "@/components/GiftLanding";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { payMethod } from "@/lib/payments";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import { isChristmasTime } from "@/lib/season";
|
||||
import { backendGet, getMe } from "@/lib/server";
|
||||
import { siteUrl } from "@/lib/share";
|
||||
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 async function generateMetadata(): Promise<Metadata> {
|
||||
const base = await siteUrl();
|
||||
const title = "Horoszkóp ajándékba";
|
||||
const description =
|
||||
"Ajándékozz születési képletet, személyre szóló elemzést és éves előrejelzést. Nyomtatható utalvány, e-mailben időzítve vagy személyesen átadva.";
|
||||
return {
|
||||
title,
|
||||
description,
|
||||
alternates: { canonical: `${base}/ajandek` },
|
||||
openGraph: { type: "website", siteName: "Sorsfonalak", locale: "hu_HU", url: `${base}/ajandek`, title, description },
|
||||
};
|
||||
}
|
||||
|
||||
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 getMe();
|
||||
if (!me) {
|
||||
// Visitors (and search engines) get the page about giving; the form needs a login.
|
||||
const catalog = await backendGet<{ packages: Package[] }>("/v1/packages");
|
||||
return (
|
||||
<>
|
||||
<PublicHeader />
|
||||
<GiftLanding
|
||||
packages={(catalog?.packages ?? []).filter((p) => p.tier === "main")}
|
||||
loggedIn={false}
|
||||
christmas={false}
|
||||
season={isChristmasTime()}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
const [catalog, config, mine] = await Promise.all([
|
||||
backendGet<{ packages: Package[] }>("/v1/packages"),
|
||||
backendGet<PublicConfig>("/v1/config"),
|
||||
@@ -22,15 +52,18 @@ export default async function GiftPage({ searchParams }: Props) {
|
||||
]);
|
||||
const packages = (catalog?.packages ?? []).filter((p) => p.tier === "main");
|
||||
const given = mine?.gifts.length ?? 0;
|
||||
// Gifts bought now get the Christmas card.
|
||||
const xmas = isChristmasTime();
|
||||
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 1080 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Ajándék</span>
|
||||
<span className="eyebrow">{xmas ? "Karácsonyi ajándék" : "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">
|
||||
@@ -51,24 +84,35 @@ export default async function GiftPage({ searchParams }: Props) {
|
||||
<figure className="gift-sample">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src="/img/ajandek-utalvany.webp"
|
||||
src={xmas ? "/img/ajandek-karacsony.webp" : "/img/ajandek-utalvany.webp"}
|
||||
width={420}
|
||||
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:{" "}
|
||||
<Link href="/visszajelzes?tipus=other&honnan=/ajandekaim">
|
||||
írd meg nekünk itt
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
</section>
|
||||
</aside>
|
||||
|
||||
@@ -6,8 +6,27 @@ 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",
|
||||
});
|
||||
/** "december 24., 8:00" */
|
||||
const when = (iso: string) =>
|
||||
new Date(iso).toLocaleString("hu-HU", {
|
||||
timeZone: "Europe/Budapest",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
});
|
||||
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 +34,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 +62,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 +72,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 +105,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>
|
||||
)}
|
||||
@@ -91,7 +136,19 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void
|
||||
</div>
|
||||
|
||||
<p className="gift-to">
|
||||
{gift.recipient_email ? (
|
||||
{gift.recipient_email &&
|
||||
gift.email_state === "scheduled" &&
|
||||
gift.send_at ? (
|
||||
<>
|
||||
Időzítve: <strong>{when(gift.send_at)}</strong>, ide:{" "}
|
||||
<strong>{gift.recipient_email}</strong>
|
||||
</>
|
||||
) : gift.recipient_email && gift.email_state === "failed" ? (
|
||||
<>
|
||||
Nem sikerült elküldeni ide: <strong>{gift.recipient_email}</strong>.
|
||||
Ellenőrizd a címet, és küldd újra.
|
||||
</>
|
||||
) : gift.recipient_email ? (
|
||||
<>
|
||||
E-mailben elküldve ide: <strong>{gift.recipient_email}</strong>
|
||||
{gift.sendings > 1 ? ` (${gift.sendings}×)` : ""}
|
||||
@@ -101,26 +158,48 @@ 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.email_state === "scheduled"
|
||||
? "Küldés most"
|
||||
: 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 +224,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 +237,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 +253,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>
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { JsonLd, PublicFooter } from "@/components/PublicFooter";
|
||||
import { JsonLd } from "@/components/PublicFooter";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { ZODIAC, ZODIAC_BY_SLUG } from "@/content/zodiac";
|
||||
import { SIGNS } from "@/lib/astro";
|
||||
@@ -130,7 +130,6 @@ export default async function SignPage({ params }: { params: Promise<{ jegy: str
|
||||
<Link href={`/csillagjegyek/${next.slug}`}>{next.name} →</Link>
|
||||
</nav>
|
||||
</main>
|
||||
<PublicFooter />
|
||||
<JsonLd
|
||||
data={{
|
||||
"@context": "https://schema.org",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicFooter } from "@/components/PublicFooter";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { ZODIAC } from "@/content/zodiac";
|
||||
import { SIGNS } from "@/lib/astro";
|
||||
@@ -46,7 +45,6 @@ export default async function SignsPage() {
|
||||
))}
|
||||
</ul>
|
||||
</main>
|
||||
<PublicFooter />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import { AiNote } from "@/components/AiNote";
|
||||
import { PackageCards } from "@/components/PackageCards";
|
||||
import { RedeemCode } from "@/components/RedeemCode";
|
||||
import { payMethod } from "@/lib/payments";
|
||||
import { isChristmasTime } from "@/lib/season";
|
||||
import { ChristmasTree } from "@/components/ChristmasTree";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import type { Package, PublicConfig } from "@/lib/types";
|
||||
|
||||
@@ -50,6 +52,7 @@ export default async function PackagesPage() {
|
||||
]);
|
||||
const packages = catalog?.packages ?? [];
|
||||
const canPay = payMethod(config, me);
|
||||
const xmas = isChristmasTime();
|
||||
const left = me.analyses_left;
|
||||
const slots = me.persons;
|
||||
|
||||
@@ -99,15 +102,17 @@ export default async function PackagesPage() {
|
||||
<PackageCards packages={packages} canPay={canPay} giftLinks />
|
||||
|
||||
<section className="card gift-banner" aria-labelledby="gift-title">
|
||||
<div>
|
||||
<h2 id="gift-title">Ajándékba is adhatod</h2>
|
||||
{xmas && <ChristmasTree />}
|
||||
<div className="gift-banner-text">
|
||||
<h2 id="gift-title">{xmas ? "Karácsonyi ajándék a csillagokból" : "Ajándékba is adhatod"}</h2>
|
||||
<p className="muted">
|
||||
A három fő csomag bármelyikét megveheted másnak: e-mailben elküldjük neki egy nyomtatható utalvánnyal, vagy
|
||||
letöltöd, és te adod át. A kódot ő váltja be a saját fiókjában, és nem jár le.
|
||||
{xmas && " Karácsony reggelre is időzítheted."}
|
||||
</p>
|
||||
</div>
|
||||
<Link className="btn" href="/ajandek">
|
||||
Megajándékozok valakit
|
||||
<Link className="btn" href={xmas ? "/karacsony" : "/ajandek"}>
|
||||
{xmas ? "Karácsonyi ajándék" : "Megajándékozok valakit"}
|
||||
</Link>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -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); }
|
||||
@@ -1075,6 +1084,8 @@ a.pair-row:hover strong { color: var(--gold); }
|
||||
.lp-emblem-outer { fill: none; stroke: var(--gold); stroke-opacity: 0.5; stroke-width: 1; }
|
||||
.lp-disclaimer { max-width: 560px; }
|
||||
.lp-footer { border-top: 1px solid var(--line); padding: 28px 0; }
|
||||
/* The floating "Kérdezz" button must not cover the footer's last line. */
|
||||
body:has(.qdock-fab) .site-footer { padding-bottom: 88px; }
|
||||
.lp-footer-inner { display: flex; gap: 16px; flex-wrap: wrap; align-items: center; justify-content: space-between; }
|
||||
.lp-footer-nav { display: flex; gap: 18px; flex-wrap: wrap; font-size: 14px; }
|
||||
.lp-footer-nav a { color: var(--muted); text-decoration: none; }
|
||||
@@ -1152,7 +1163,8 @@ a.pair-row:hover strong { color: var(--gold); }
|
||||
}
|
||||
|
||||
/* Home page footer: payment and invoicing partners */
|
||||
.lp-partners { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 10px 16px; padding-bottom: 20px; margin-bottom: 20px; border-bottom: 1px solid var(--line); }
|
||||
/* On the home page, right above the common footer (whose top line separates them). */
|
||||
.lp-partners { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 10px 16px; padding: 24px 16px; }
|
||||
.lp-partner { height: 26px; width: auto; opacity: 0.65; transition: opacity 0.2s; }
|
||||
.lp-partner:hover { opacity: 1; }
|
||||
.lp-partners .hint + .lp-partner { margin-right: 18px; }
|
||||
@@ -1522,6 +1534,8 @@ span.tarot-fan-card { cursor: default; }
|
||||
.gift-banner h2 { font-size: 24px; }
|
||||
.gift-banner p { margin: 6px 0 0; }
|
||||
.gift-banner .btn { flex: none; }
|
||||
.gift-banner-text { flex: 1; }
|
||||
.gift-banner .xmas-tree { flex: none; filter: drop-shadow(0 0 10px rgba(217, 180, 106, 0.25)); }
|
||||
.gift-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 24px; align-items: start; }
|
||||
.gift-aside { display: flex; flex-direction: column; gap: 16px; }
|
||||
.gift-sample { margin: 0; display: flex; flex-direction: column; gap: 8px; align-items: center; }
|
||||
@@ -1574,6 +1588,7 @@ span.tarot-fan-card { cursor: default; }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.gift-banner { flex-direction: column; align-items: stretch; }
|
||||
.gift-banner .xmas-tree { align-self: center; }
|
||||
.gift-packages, .gift-ways { grid-template-columns: 1fr; }
|
||||
.gift-packages .gift-option-head { flex-direction: row; align-items: baseline; justify-content: space-between; }
|
||||
.gift-aside { flex-direction: column; }
|
||||
@@ -1581,3 +1596,191 @@ 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; }
|
||||
/* At the bottom of the page, before the footer. */
|
||||
.nps {
|
||||
max-width: 1180px; margin: 8px auto 24px; 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; }
|
||||
}
|
||||
.contact-card p { margin: 0; }
|
||||
|
||||
/* The app header (logged in): a starry band with a gold edge, menu items with
|
||||
gold marks, the free pages in one dropdown, and the Moon today. */
|
||||
.app-header {
|
||||
background:
|
||||
radial-gradient(1px 1px at 22% 28%, rgba(236, 230, 216, 0.6), transparent 60%),
|
||||
radial-gradient(1px 1px at 47% 72%, rgba(236, 230, 216, 0.4), transparent 60%),
|
||||
radial-gradient(1.5px 1.5px at 66% 20%, rgba(217, 180, 106, 0.7), transparent 60%),
|
||||
radial-gradient(1px 1px at 83% 70%, rgba(236, 230, 216, 0.45), transparent 60%),
|
||||
radial-gradient(1px 1px at 95% 30%, rgba(236, 230, 216, 0.5), transparent 60%),
|
||||
rgba(15, 21, 40, 0.95);
|
||||
border-bottom-color: transparent;
|
||||
}
|
||||
.app-header::after {
|
||||
content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 1px; pointer-events: none;
|
||||
background: linear-gradient(90deg, rgba(217, 180, 106, 0), rgba(217, 180, 106, 0.6) 30%, rgba(217, 180, 106, 0.6) 70%, rgba(217, 180, 106, 0));
|
||||
}
|
||||
.nav-icon { width: 17px; height: 17px; flex: none; color: rgba(217, 180, 106, 0.8); fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linejoin: round; stroke-linecap: round; }
|
||||
.nav-icon.sym { width: auto; height: auto; font-size: 17px; line-height: 1; text-align: center; min-width: 17px; }
|
||||
.nav-icon .nav-icon-fill { fill: currentColor; stroke: none; }
|
||||
.app-nav { gap: 2px; align-items: center; }
|
||||
.app-nav > a, .nav-group-button {
|
||||
display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 10px 11px;
|
||||
color: var(--ink-2); text-decoration: none; border-radius: 8px 8px 0 0; border-bottom: 2px solid transparent; font-size: 15px;
|
||||
}
|
||||
.app-nav > a:hover, .nav-group-button:hover { color: var(--ink); background: rgba(217, 180, 106, 0.06); }
|
||||
.app-nav > a[aria-current="page"], .nav-group-button.is-active {
|
||||
color: var(--ink); background: none; border-bottom-color: var(--gold); box-shadow: 0 7px 12px -9px rgba(217, 180, 106, 0.9);
|
||||
}
|
||||
.app-nav > a[aria-current="page"] .nav-icon, .nav-group-button.is-active .nav-icon { color: var(--gold); }
|
||||
.nav-group { position: relative; }
|
||||
.nav-group-button { background: none; border-top: 0; border-left: 0; border-right: 0; font-family: inherit; cursor: pointer; }
|
||||
.nav-group-button[aria-expanded="true"] { color: var(--gold); background: rgba(217, 180, 106, 0.1); border-radius: 8px; }
|
||||
.nav-group-chevron { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.nav-group-button[aria-expanded="true"] .nav-group-chevron { transform: rotate(180deg); }
|
||||
.nav-dropdown {
|
||||
position: absolute; left: 0; top: calc(100% + 8px); z-index: 30; width: 340px; padding: 8px;
|
||||
display: flex; flex-direction: column; gap: 2px; background: var(--panel); border: 1px solid var(--line-2);
|
||||
border-radius: 14px; box-shadow: 0 18px 44px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
.nav-dropdown-title { padding: 6px 10px 8px; font-size: 11px; font-weight: 600; letter-spacing: 1.2px; text-transform: uppercase; color: var(--gold); }
|
||||
.nav-dropdown-item { display: flex; gap: 12px; align-items: flex-start; padding: 10px; border-radius: 10px; color: var(--ink); text-decoration: none; }
|
||||
.nav-dropdown-item:hover, .nav-dropdown-item[aria-current="page"] { background: rgba(255, 255, 255, 0.04); color: var(--gold); }
|
||||
.nav-dropdown-item .nav-icon { margin-top: 2px; width: 20px; height: 20px; font-size: 19px; color: var(--gold); }
|
||||
.nav-dropdown-text { display: flex; flex-direction: column; gap: 2px; font-size: 15px; }
|
||||
.nav-dropdown-text .hint { font-size: 13px; }
|
||||
.moon-chip {
|
||||
display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px 0 8px; border-radius: 999px;
|
||||
background: rgba(217, 180, 106, 0.08); color: var(--ink); text-decoration: none; font-size: 13px; white-space: nowrap;
|
||||
}
|
||||
.moon-chip:hover { background: rgba(217, 180, 106, 0.14); color: var(--ink); }
|
||||
.moon-chip-glyph { color: var(--gold); font-size: 15px; }
|
||||
.moon-phase-icon { width: 20px; height: 20px; flex: none; }
|
||||
.moon-phase-icon .moon-dark { fill: #1a2238; stroke: var(--gold); stroke-width: 1; }
|
||||
.moon-phase-icon .moon-lit { fill: var(--gold); }
|
||||
@media (max-width: 1760px) { .app-header .who .moon-chip-text { display: none; } .app-header .who .moon-chip { padding: 0 10px 0 8px; } }
|
||||
/* The grouped ☰ menu of the app. */
|
||||
.mobile-menu-panel > .moon-chip { align-self: stretch; min-height: 48px; padding: 0 14px; font-size: 14px; border-radius: 12px; }
|
||||
.mobile-menu-list { display: flex; flex-direction: column; }
|
||||
.mobile-menu-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
|
||||
.mobile-menu-grid a { border: 1px solid var(--line); font-size: 15px; }
|
||||
.mobile-menu-panel a { gap: 12px; }
|
||||
.mobile-menu-panel a .nav-icon { color: var(--gold); }
|
||||
.mobile-menu-label { flex: 1; min-width: 0; }
|
||||
.mobile-menu-note { font-size: 13px; color: var(--gold); white-space: nowrap; }
|
||||
/* Laptops (1440px): the items closer, so the row still fits next to the account. */
|
||||
@media (max-width: 1520px) {
|
||||
.app-nav > a, .nav-group-button { padding: 10px 7px; gap: 6px; font-size: 14.5px; }
|
||||
.app-header { gap: 16px; }
|
||||
.app-header .who { gap: 8px; }
|
||||
}
|
||||
/* The ☰ panel covers the page fully (the header's blur showed it through). */
|
||||
.mobile-menu-panel { background: #0f1528; }
|
||||
/* When the gift e-mail goes: at once, or timed (e.g. Christmas morning). */
|
||||
.gift-when { display: flex; flex-direction: column; gap: 10px; padding-top: 6px; }
|
||||
.gift-when-choices { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.gift-when-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 220px)); gap: 12px; }
|
||||
@media (max-width: 640px) { .gift-when-fields { grid-template-columns: 1fr 1fr; } }
|
||||
/* The Christmas campaign page */
|
||||
.xmas-hero { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 32px; align-items: center; }
|
||||
.xmas-hero-text { display: flex; flex-direction: column; gap: 14px; }
|
||||
.xmas-hero h1 { font-size: clamp(40px, 5vw, 60px); }
|
||||
.xmas-hero .lead { font-size: 18px; line-height: 1.6; color: var(--ink-2); margin: 0; }
|
||||
.xmas-points { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
|
||||
.xmas-points .card { gap: 8px; }
|
||||
.xmas-points h2 { font-size: 24px; }
|
||||
.xmas-points p { margin: 0; line-height: 1.6; }
|
||||
.xmas-delivery ul { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 8px; color: var(--ink-2); }
|
||||
.xmas-packages { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
|
||||
@media (max-width: 900px) {
|
||||
.xmas-hero { grid-template-columns: 1fr; }
|
||||
.xmas-sample img { max-width: 260px; }
|
||||
.xmas-points, .xmas-packages { grid-template-columns: 1fr; }
|
||||
}
|
||||
/* The home page gift band */
|
||||
.lp-gift-inner { display: flex; align-items: center; gap: 32px; }
|
||||
.lp-gift-text { flex: 1; display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
|
||||
.lp-gift-text .lp-text { margin: 0; }
|
||||
.lp-gift .xmas-tree { flex: none; filter: drop-shadow(0 0 14px rgba(217, 180, 106, 0.3)); }
|
||||
.lp-gift-card { flex: none; width: 200px; height: auto; border-radius: 6px; transform: rotate(3deg); box-shadow: 0 18px 40px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(217, 180, 106, 0.25); }
|
||||
.xmas-hero-text .xmas-tree { filter: drop-shadow(0 0 10px rgba(217, 180, 106, 0.3)); }
|
||||
@media (max-width: 760px) {
|
||||
.lp-gift-inner { flex-direction: column; text-align: center; }
|
||||
.lp-gift-text { align-items: center; }
|
||||
.lp-gift-card { width: 160px; }
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { notFound } from "next/navigation";
|
||||
|
||||
import { AnalysisView } from "@/components/AnalysisView";
|
||||
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
|
||||
import { JsonLd, PublicFooter } from "@/components/PublicFooter";
|
||||
import { JsonLd } from "@/components/PublicFooter";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { SIGNS, signName } from "@/lib/astro";
|
||||
import { birthLine, celebrityImageVersion, loadCelebrity } from "@/lib/celebrities";
|
||||
@@ -135,7 +135,6 @@ export default async function CelebrityPage({ params }: Props) {
|
||||
A portrét mesterséges intelligencia írta, kizárólag a születési képlet alapján, nem az életrajz ismeretében.
|
||||
</p>
|
||||
</main>
|
||||
<PublicFooter />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { Metadata } from "next";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicFooter } from "@/components/PublicFooter";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { SIGNS, signName } from "@/lib/astro";
|
||||
import { loadCelebrities } from "@/lib/celebrities";
|
||||
@@ -69,7 +68,6 @@ export default async function CelebritiesPage() {
|
||||
</ul>
|
||||
)}
|
||||
</main>
|
||||
<PublicFooter />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicFooter } from "@/components/PublicFooter";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { YearNav } from "@/components/YearNav";
|
||||
import { MOON_PHASES, SIGNS } from "@/lib/astro";
|
||||
@@ -119,7 +118,6 @@ export function MoonCalendar({ year, events, sky, me }: { year: number; events:
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
<PublicFooter />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { OPERATOR } from "@/lib/legal";
|
||||
import { getMe } from "@/lib/server";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Kapcsolat",
|
||||
description: "Kérdésed, ötleted van, vagy hibát találtál? Írj nekünk e-mailt, vagy belépve üzenetet az oldalon.",
|
||||
alternates: { canonical: "/kapcsolat" },
|
||||
};
|
||||
|
||||
/** Contact: logged in, the feedback page; otherwise the e-mail address, and that logging in lets one write on the site. */
|
||||
export default async function ContactPage() {
|
||||
if (await getMe()) redirect("/visszajelzes");
|
||||
return (
|
||||
<>
|
||||
<PublicHeader />
|
||||
<main className="page" style={{ maxWidth: 760 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Kapcsolat</span>
|
||||
<h1>Írj nekünk</h1>
|
||||
<p className="muted">Kérdésed vagy ötleted van, esetleg hibát találtál? Szívesen segítünk.</p>
|
||||
</div>
|
||||
<section className="card contact-card">
|
||||
<p>
|
||||
E-mailben ezen a címen érsz el minket:{" "}
|
||||
<a href={`mailto:${OPERATOR.email}`}>
|
||||
<strong>{OPERATOR.email}</strong>
|
||||
</a>
|
||||
</p>
|
||||
<p className="muted">
|
||||
Ha belépsz, az oldalon is küldhetsz nekünk szöveges üzenetet, és a válaszunkat is ott látod.
|
||||
</p>
|
||||
<div className="form-actions">
|
||||
<Link className="btn btn-primary" href="/belepes?vissza=%2Fvisszajelzes">
|
||||
Belépés
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { Metadata } from "next";
|
||||
|
||||
import { GiftLanding } from "@/components/GiftLanding";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { isChristmasTime } from "@/lib/season";
|
||||
import { backendGet, getMe } from "@/lib/server";
|
||||
import { siteUrl } from "@/lib/share";
|
||||
import type { Package } from "@/lib/types";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const base = await siteUrl();
|
||||
const title = "Karácsonyi ajándék a csillagokból";
|
||||
const description =
|
||||
"Ajándékozz születési képletet, személyre szóló elemzést, és azt, mit hoz neki a következő éve. Nyomtatható utalvány, karácsony reggelre időzíthető levél.";
|
||||
const image = {
|
||||
url: `${base}/kep/karacsony.png?v=1`,
|
||||
width: 1200,
|
||||
height: 630,
|
||||
alt: title,
|
||||
};
|
||||
return {
|
||||
title,
|
||||
description,
|
||||
alternates: { canonical: `${base}/karacsony` },
|
||||
openGraph: {
|
||||
type: "website",
|
||||
siteName: "Sorsfonalak",
|
||||
locale: "hu_HU",
|
||||
url: `${base}/karacsony`,
|
||||
title,
|
||||
description,
|
||||
images: [image],
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
title,
|
||||
description,
|
||||
images: [image.url],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The Christmas campaign: the gift packages, with the year ahead as the hook. */
|
||||
export default async function ChristmasPage() {
|
||||
const [me, catalog] = await Promise.all([
|
||||
getMe(),
|
||||
backendGet<{ packages: Package[] }>("/v1/packages"),
|
||||
]);
|
||||
return (
|
||||
<>
|
||||
{!me && <PublicHeader />}
|
||||
<GiftLanding
|
||||
packages={(catalog?.packages ?? []).filter((p) => p.tier === "main")}
|
||||
loggedIn={me !== null}
|
||||
christmas
|
||||
season={isChristmasTime()}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// The link preview image of the Christmas page (og:image), drawn from the
|
||||
// example chart. The page links it with a version (?v=…).
|
||||
import example from "@/content/pelda.json";
|
||||
import { chartCard } from "@/lib/ogCard";
|
||||
import type { ChartResult } from "@/lib/types";
|
||||
|
||||
export async function GET() {
|
||||
return chartCard({
|
||||
chart: example.chart as unknown as ChartResult,
|
||||
timeKnown: true,
|
||||
eyebrow: "KARÁCSONYI AJÁNDÉK",
|
||||
title: "Ajándék a csillagokból.",
|
||||
text: "Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve. Nyomtatható utalvánnyal, karácsony reggelre időzítve.",
|
||||
lines: [
|
||||
{ glyph: "☉", label: "Születési képlet" },
|
||||
{ glyph: "♃", label: "A következő éve" },
|
||||
{ glyph: "♀", label: "Kapcsolati elemzés" },
|
||||
],
|
||||
cacheControl: "public, max-age=86400, s-maxage=604800",
|
||||
});
|
||||
}
|
||||
@@ -3,10 +3,13 @@ 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 { SiteFooter } from "@/components/PublicFooter";
|
||||
import { SiteHeader } from "@/components/SiteHeader";
|
||||
import { ValidationMessages } from "@/components/ValidationMessages";
|
||||
import { getMe } from "@/lib/server";
|
||||
import { loadSky } from "@/lib/sky";
|
||||
import { siteUrl } from "@/lib/share";
|
||||
|
||||
import "./globals.css";
|
||||
@@ -29,13 +32,18 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const me = await getMe();
|
||||
// The Moon today in the header (cached for five minutes).
|
||||
const sky = me ? await loadSky() : null;
|
||||
return (
|
||||
<html lang="hu" className={`${cormorant.variable} ${inter.variable}`}>
|
||||
<body>
|
||||
<NightSky />
|
||||
<ValidationMessages />
|
||||
{me && <SiteHeader me={me} />}
|
||||
{me && <SiteHeader me={me} sky={sky} />}
|
||||
{children}
|
||||
{/* At the very bottom, apart from the page content: up top it drew the eye away. */}
|
||||
{me?.nps_due && <NpsBanner />}
|
||||
<SiteFooter loggedIn={me !== null} />
|
||||
{me && (
|
||||
<Suspense fallback={null}>
|
||||
<PaymentReturn />
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicFooter } from "@/components/PublicFooter";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { YearNav } from "@/components/YearNav";
|
||||
import { POINTS } from "@/lib/astro";
|
||||
@@ -112,7 +111,6 @@ export function RetrogradeCalendar({
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
<PublicFooter />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
priority: 0.6,
|
||||
})),
|
||||
{ url: `${base}/aszf`, changeFrequency: "yearly", priority: 0.2 },
|
||||
|
||||
{ url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 },
|
||||
{ url: `${base}/karacsony`, changeFrequency: "monthly", priority: 0.7 },
|
||||
{ url: `${base}/ajandek`, changeFrequency: "monthly", priority: 0.6 },
|
||||
{ url: `${base}/adatvedelem`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
|
||||
{ url: `${base}/privacy`, changeFrequency: "yearly", priority: 0.2, alternates: privacy },
|
||||
];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { JsonLd, PublicFooter } from "@/components/PublicFooter";
|
||||
import { JsonLd } from "@/components/PublicFooter";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { getMe } from "@/lib/server";
|
||||
import { siteUrl } from "@/lib/share";
|
||||
@@ -92,7 +92,6 @@ export default async function BirthChartPage() {
|
||||
))}
|
||||
</section>
|
||||
</main>
|
||||
<PublicFooter />
|
||||
<JsonLd
|
||||
data={{
|
||||
"@context": "https://schema.org",
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/** A Christmas tree in the site's gold line style, with a star on top. */
|
||||
export function ChristmasTree({ size = 64 }: { size?: number }) {
|
||||
return (
|
||||
<svg
|
||||
className="xmas-tree"
|
||||
width={size}
|
||||
height={size * 1.25}
|
||||
viewBox="0 0 64 80"
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
stroke="#d9b46a"
|
||||
strokeWidth="2"
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
>
|
||||
{/* The star */}
|
||||
<path
|
||||
d="M32 2 L34.4 8 L40.6 8.6 L35.9 12.7 L37.3 18.8 L32 15.6 L26.7 18.8 L28.1 12.7 L23.4 8.6 L29.6 8 Z"
|
||||
fill="#d9b46a"
|
||||
/>
|
||||
{/* Three tiers */}
|
||||
<path
|
||||
d="M32 20 L44 34 L38 34 L50 49 L42 49 L56 65 L8 65 L22 49 L14 49 L26 34 L20 34 Z"
|
||||
fill="rgba(217,180,106,0.08)"
|
||||
/>
|
||||
{/* Garland */}
|
||||
<path
|
||||
d="M23 41 Q33 45 42 39 M17 56 Q31 61 47 54"
|
||||
strokeWidth="1.2"
|
||||
opacity="0.7"
|
||||
/>
|
||||
{/* Baubles */}
|
||||
<g stroke="none">
|
||||
<circle cx="29" cy="30" r="1.8" fill="#ece6d8" />
|
||||
<circle cx="36" cy="44" r="2" fill="#d9b46a" />
|
||||
<circle cx="25" cy="50" r="1.8" fill="#ece6d8" />
|
||||
<circle cx="41" cy="59" r="2" fill="#ece6d8" />
|
||||
<circle cx="20" cy="61" r="1.8" fill="#d9b46a" />
|
||||
</g>
|
||||
{/* Trunk */}
|
||||
<path d="M28 65 L28 74 L36 74 L36 65" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -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,181 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { ChristmasTree } from "@/components/ChristmasTree";
|
||||
import { contents } from "@/lib/packageContents";
|
||||
import type { Package } from "@/lib/types";
|
||||
|
||||
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
|
||||
|
||||
/** Where a "give this" button leads: the gift form, through the login when logged out. */
|
||||
export function giftHref(loggedIn: boolean, packageId?: string): string {
|
||||
const form = packageId
|
||||
? `/ajandek?csomag=${encodeURIComponent(packageId)}`
|
||||
: "/ajandek";
|
||||
return loggedIn ? form : `/belepes?vissza=${encodeURIComponent(form)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The public page about giving a package (crawlable, no login): `/karacsony`
|
||||
* in the Christmas campaign, `/ajandek` for visitors all year.
|
||||
*/
|
||||
export function GiftLanding({
|
||||
packages,
|
||||
loggedIn,
|
||||
christmas,
|
||||
season,
|
||||
}: {
|
||||
packages: Package[];
|
||||
loggedIn: boolean;
|
||||
/** The Christmas page: wording, card and tree. */
|
||||
christmas: boolean;
|
||||
/** It is Christmas time (a timed Christmas e-mail can be mentioned). */
|
||||
season: boolean;
|
||||
}) {
|
||||
return (
|
||||
<main className="page xmas-page" style={{ maxWidth: 1080 }}>
|
||||
<section className="xmas-hero">
|
||||
<div className="xmas-hero-text">
|
||||
{christmas && <ChristmasTree size={44} />}
|
||||
<span className="eyebrow">
|
||||
{christmas ? "Karácsonyi ajándék" : "Ajándék"}
|
||||
</span>
|
||||
<h1>
|
||||
{christmas ? "Ajándék a csillagokból" : "Horoszkóp ajándékba"}
|
||||
</h1>
|
||||
<p className="lead">
|
||||
{christmas
|
||||
? "Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve. Annak, akit szeretsz, egy szép, nyomtatható utalvánnyal."
|
||||
: "Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve. Születésnapra, évfordulóra vagy csak úgy, egy szép, nyomtatható utalvánnyal."}
|
||||
</p>
|
||||
<div className="form-actions">
|
||||
<Link className="btn btn-primary" href={giftHref(loggedIn)}>
|
||||
Megajándékozok valakit
|
||||
</Link>
|
||||
<a className="btn" href="#csomagok">
|
||||
A csomagok
|
||||
</a>
|
||||
</div>
|
||||
{!loggedIn && (
|
||||
<p className="hint">
|
||||
Az ajándékozáshoz be kell lépned, vagy regisztrálnod.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<figure className="gift-sample xmas-sample">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={
|
||||
christmas
|
||||
? "/img/ajandek-karacsony.webp"
|
||||
: "/img/ajandek-utalvany.webp"
|
||||
}
|
||||
width={420}
|
||||
height={594}
|
||||
alt={
|
||||
christmas
|
||||
? "Minta karácsonyi ajándékutalvány: Boldog karácsonyt és csillagos 2027-et, a csomag, az üzenet és az ajándékkód"
|
||||
: "Minta ajándékutalvány: a képlet, a csomag, a személyes üzenet és az ajándékkód"
|
||||
}
|
||||
/>
|
||||
<figcaption className="hint">
|
||||
{christmas
|
||||
? "A karácsonyi utalvány (A4-es PDF, nyomtatható)"
|
||||
: "Az utalvány (A4-es PDF, nyomtatható)"}
|
||||
</figcaption>
|
||||
</figure>
|
||||
</section>
|
||||
|
||||
<section className="xmas-points" aria-label="Mit kap?">
|
||||
<div className="card">
|
||||
<h2>A születési képlete</h2>
|
||||
<p className="muted">
|
||||
Percre pontosan kiszámolva és megrajzolva, mellé egy részletes
|
||||
elemzés hat fejezetben: személyiség, érzelmek, gondolkodás,
|
||||
szerelem, hivatás, fejlődés.
|
||||
</p>
|
||||
</div>
|
||||
<div className="card">
|
||||
<h2>A következő éve</h2>
|
||||
<p className="muted">
|
||||
Az éves előrejelzés a születésnapjától egy évre szól: mit hoznak a
|
||||
bolygók, mire figyeljen, negyedévenként idővonallal. A Páros és a
|
||||
Család csomagban benne van.
|
||||
</p>
|
||||
</div>
|
||||
<div className="card">
|
||||
<h2>Kettőtökről</h2>
|
||||
<p className="muted">
|
||||
A Páros csomagban kapcsolati elemzés is jár: mi vonz, hol súrlódtok,
|
||||
és mit ad a kapcsolat. Szép ajándék párnak, testvérnek, barátnak.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
className="card xmas-delivery"
|
||||
aria-labelledby="gift-delivery-title"
|
||||
>
|
||||
<h2 id="gift-delivery-title">
|
||||
{christmas ? "Karácsony reggelre" : "Így kapja meg"}
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Időzítve e-mailben:</strong>{" "}
|
||||
{christmas
|
||||
? "a levél az utalvánnyal december 24-én reggel érkezik meg hozzá (vagy amikor választod)."
|
||||
: `a levél az utalvánnyal akkor érkezik meg hozzá, amikor választod, például a születésnapja reggelén${season ? " vagy karácsony reggel" : ""}. Vagy azonnal, fizetés után.`}
|
||||
</li>
|
||||
<li>
|
||||
<strong>Te adod át:</strong>{" "}
|
||||
{christmas
|
||||
? "letöltöd az utalványt, kinyomtatod, és a fa alá teszed."
|
||||
: "letöltöd az utalványt, kinyomtatod, és személyesen adod oda."}
|
||||
</li>
|
||||
<li>
|
||||
<strong>Ő váltja be:</strong> belép vagy regisztrál, beírja a kódot,
|
||||
és a csomag az övé. A kód nem jár le.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section
|
||||
id="csomagok"
|
||||
className="field"
|
||||
aria-labelledby="gift-packages-title"
|
||||
style={{ gap: 16 }}
|
||||
>
|
||||
<h2 id="gift-packages-title">Melyiket adnád?</h2>
|
||||
<div className="xmas-packages">
|
||||
{packages.map((p) => (
|
||||
<article
|
||||
key={p.id}
|
||||
className={p.badge ? "pkg pkg-featured" : "pkg"}
|
||||
>
|
||||
<h3 className="pkg-name">{p.name}</h3>
|
||||
<p className="muted pkg-tagline">{p.tagline}</p>
|
||||
<div className="pkg-price">
|
||||
<strong>{huf(p.price_huf)}</strong>
|
||||
</div>
|
||||
<ul className="pkg-list">
|
||||
{contents(p).map((line) => (
|
||||
<li key={line}>{line}</li>
|
||||
))}
|
||||
</ul>
|
||||
<Link
|
||||
className={p.badge ? "btn btn-primary" : "btn"}
|
||||
href={giftHref(loggedIn, p.id)}
|
||||
>
|
||||
Ezt adom ajándékba
|
||||
</Link>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
<p className="hint">
|
||||
A számlát te kapod. Ha meggondolod magad, a vásárlástól számított 14
|
||||
napon belül, beváltás előtt visszakérheted az árát.{" "}
|
||||
<Link href="/aszf">ÁSZF</Link>
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -4,10 +4,14 @@ import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
|
||||
import { NavIcon, type NavIconName } from "./NavIcon";
|
||||
|
||||
export interface MenuSection {
|
||||
/** A small heading above the group (e.g. "Ingyenes"). */
|
||||
title?: string;
|
||||
links: { href: string; label: string }[];
|
||||
/** Two columns of tiles instead of a list. */
|
||||
grid?: boolean;
|
||||
links: { href: string; label: string; icon?: NavIconName; note?: string }[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -15,7 +19,16 @@ export interface MenuSection {
|
||||
* hidden there, see globals.css). Closes on a click outside, Escape, or
|
||||
* moving to another page. `className` sets the width from which it shows.
|
||||
*/
|
||||
export function MobileMenu({ sections, className }: { sections: MenuSection[]; className: string }) {
|
||||
export function MobileMenu({
|
||||
sections,
|
||||
className,
|
||||
lead,
|
||||
}: {
|
||||
sections: MenuSection[];
|
||||
className: string;
|
||||
/** Shown first in the panel (the Moon today). */
|
||||
lead?: React.ReactNode;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const button = useRef<HTMLButtonElement>(null);
|
||||
@@ -61,19 +74,24 @@ export function MobileMenu({ sections, className }: { sections: MenuSection[]; c
|
||||
</button>
|
||||
{open && (
|
||||
<nav id={panelId} className="mobile-menu-panel" aria-label="Menü">
|
||||
{lead}
|
||||
{sections.map((s, i) => (
|
||||
<div key={i} className="mobile-menu-group">
|
||||
{s.title && <span className="lp-free-label">{s.title}</span>}
|
||||
{s.links.map((l) => (
|
||||
<Link
|
||||
key={l.href}
|
||||
href={l.href}
|
||||
aria-current={current(l.href) ? "page" : undefined}
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
{l.label}
|
||||
</Link>
|
||||
))}
|
||||
<div className={s.grid ? "mobile-menu-grid" : "mobile-menu-list"}>
|
||||
{s.links.map((l) => (
|
||||
<Link
|
||||
key={l.href}
|
||||
href={l.href}
|
||||
aria-current={current(l.href) ? "page" : undefined}
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
{l.icon && <NavIcon name={l.icon} />}
|
||||
<span className="mobile-menu-label">{l.label}</span>
|
||||
{l.note && <span className="mobile-menu-note">{l.note}</span>}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { SIGNS } from "@/lib/astro";
|
||||
import { SIGN_IN, withArticle } from "@/lib/skyText";
|
||||
import type { SkyNow } from "@/lib/types";
|
||||
|
||||
/** The Moon as it is lit now: the lit part on the right while waxing, on the left while waning. */
|
||||
export function MoonPhaseIcon({
|
||||
illumination,
|
||||
waxing,
|
||||
}: {
|
||||
illumination: number;
|
||||
waxing: boolean;
|
||||
}) {
|
||||
const r = 8.5;
|
||||
const k = Math.min(1, Math.max(0, illumination));
|
||||
const rx = Math.abs(1 - 2 * k) * r;
|
||||
// The outer edge on the lit side, then the terminator back.
|
||||
const outer = waxing ? 1 : 0;
|
||||
const terminator = waxing ? (k > 0.5 ? 1 : 0) : k > 0.5 ? 0 : 1;
|
||||
const d = `M12 ${12 - r}A${r} ${r} 0 0 ${outer} 12 ${12 + r}A${rx} ${r} 0 0 ${terminator} 12 ${12 - r}Z`;
|
||||
return (
|
||||
<svg className="moon-phase-icon" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r={r} className="moon-dark" />
|
||||
<path d={d} className="moon-lit" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Ma: Hold a ♉ Bikában" in the header (the moon calendar behind it). Narrow
|
||||
* screens show the phase and the sign's glyph only.
|
||||
*/
|
||||
export function MoonChip({ sky }: { sky: SkyNow }) {
|
||||
const moon = sky.moon;
|
||||
const sign = moon.position.sign;
|
||||
const where = withArticle(SIGN_IN[sign] ?? sign);
|
||||
return (
|
||||
<Link
|
||||
href="/holdnaptar"
|
||||
className="moon-chip"
|
||||
aria-label={`Ma a Hold ${where} jár: holdnaptár`}
|
||||
>
|
||||
<MoonPhaseIcon illumination={moon.illumination} waxing={moon.waxing} />
|
||||
<span className="moon-chip-text" aria-hidden="true">
|
||||
Ma: Hold {where.split(" ")[0]}{" "}
|
||||
</span>
|
||||
<span className="moon-chip-glyph sym" aria-hidden="true">
|
||||
{SIGNS[sign]?.glyph}
|
||||
{"︎"}
|
||||
</span>
|
||||
<span className="moon-chip-text" aria-hidden="true">
|
||||
{" "}
|
||||
{SIGN_IN[sign]}
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Small gold marks before the menu items: astrological glyphs where one fits,
|
||||
// otherwise a line drawing.
|
||||
|
||||
export type NavIconName =
|
||||
| "chart"
|
||||
| "persons"
|
||||
| "compare"
|
||||
| "tarot"
|
||||
| "explore"
|
||||
| "signs"
|
||||
| "famous"
|
||||
| "moon"
|
||||
| "retro"
|
||||
| "packages"
|
||||
| "admin";
|
||||
|
||||
const GLYPHS: Partial<Record<NavIconName, string>> = {
|
||||
chart: "☉",
|
||||
persons: "☽",
|
||||
compare: "☌",
|
||||
explore: "✧",
|
||||
signs: "♈",
|
||||
retro: "☿",
|
||||
};
|
||||
|
||||
export function NavIcon({ name }: { name: NavIconName }) {
|
||||
const glyph = GLYPHS[name];
|
||||
if (glyph) {
|
||||
return (
|
||||
<span className="nav-icon sym" aria-hidden="true">
|
||||
{glyph}
|
||||
{"︎"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<svg className="nav-icon" viewBox="0 0 24 24" aria-hidden="true">
|
||||
{name === "tarot" && (
|
||||
<>
|
||||
<rect x="5" y="3" width="14" height="18" rx="2.2" />
|
||||
<path
|
||||
d="M12 8l1.2 2.8 2.8 1.2-2.8 1.2L12 16l-1.2-2.8L8 12l2.8-1.2z"
|
||||
className="nav-icon-fill"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{name === "famous" && (
|
||||
<path d="M12 3l2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6 6.6 19.5l1.2-6L3.3 9.3l6.1-.7z" />
|
||||
)}
|
||||
{name === "moon" && (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="8.5" />
|
||||
<path
|
||||
d="M12 3.5a8.5 8.5 0 0 1 0 17a5 8.5 0 0 0 0-17z"
|
||||
className="nav-icon-fill"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{name === "packages" && (
|
||||
<>
|
||||
<path d="M12 2.5l8.5 4.7v9.6L12 21.5l-8.5-4.7V7.2z" />
|
||||
<path d="M3.5 7.2L12 12l8.5-4.8M12 12v9.5" />
|
||||
</>
|
||||
)}
|
||||
{name === "admin" && (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M12 2.5v3M12 18.5v3M2.5 12h3M18.5 12h3M5.3 5.3l2.1 2.1M16.6 16.6l2.1 2.1M5.3 18.7l2.1-2.1M16.6 7.4l2.1-2.1" />
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -2,16 +2,136 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
|
||||
export function NavLinks({ links }: { links: { href: string; label: string }[] }) {
|
||||
import { NavIcon, type NavIconName } from "./NavIcon";
|
||||
|
||||
export interface NavItem {
|
||||
href: string;
|
||||
label: string;
|
||||
icon: NavIconName;
|
||||
/** One line under the label in a dropdown. */
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export interface NavGroup {
|
||||
label: string;
|
||||
icon: NavIconName;
|
||||
/** The dropdown's small heading. */
|
||||
title: string;
|
||||
items: NavItem[];
|
||||
}
|
||||
|
||||
const isGroup = (e: NavItem | NavGroup): e is NavGroup => "items" in e;
|
||||
|
||||
/**
|
||||
* The app's menu row: items with a gold mark, and a group (the free pages)
|
||||
* that opens on a click as a dropdown. Closes on a click outside, Escape or
|
||||
* moving to another page.
|
||||
*/
|
||||
export function NavLinks({ entries }: { entries: (NavItem | NavGroup)[] }) {
|
||||
const pathname = usePathname();
|
||||
const here = (href: string) => pathname.startsWith(href);
|
||||
return (
|
||||
<nav className="nav app-nav" aria-label="Fő navigáció">
|
||||
{links.map((l) => (
|
||||
<Link key={l.href} href={l.href} aria-current={pathname.startsWith(l.href) ? "page" : undefined}>
|
||||
{l.label}
|
||||
</Link>
|
||||
))}
|
||||
{entries.map((e) =>
|
||||
isGroup(e) ? (
|
||||
<Dropdown
|
||||
key={e.label}
|
||||
group={e}
|
||||
active={e.items.some((i) => here(i.href))}
|
||||
here={here}
|
||||
/>
|
||||
) : (
|
||||
<Link
|
||||
key={e.href}
|
||||
href={e.href}
|
||||
aria-current={here(e.href) ? "page" : undefined}
|
||||
>
|
||||
<NavIcon name={e.icon} />
|
||||
{e.label}
|
||||
</Link>
|
||||
),
|
||||
)}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
function Dropdown({
|
||||
group,
|
||||
active,
|
||||
here,
|
||||
}: {
|
||||
group: NavGroup;
|
||||
active: boolean;
|
||||
here: (href: string) => boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const button = useRef<HTMLButtonElement>(null);
|
||||
const id = useId();
|
||||
const pathname = usePathname();
|
||||
|
||||
useEffect(() => setOpen(false), [pathname]);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const outside = (e: PointerEvent) => {
|
||||
if (box.current && !box.current.contains(e.target as Node))
|
||||
setOpen(false);
|
||||
};
|
||||
const escape = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
setOpen(false);
|
||||
button.current?.focus();
|
||||
}
|
||||
};
|
||||
document.addEventListener("pointerdown", outside);
|
||||
document.addEventListener("keydown", escape);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", outside);
|
||||
document.removeEventListener("keydown", escape);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<div className="nav-group" ref={box}>
|
||||
<button
|
||||
ref={button}
|
||||
type="button"
|
||||
className={active ? "nav-group-button is-active" : "nav-group-button"}
|
||||
aria-expanded={open}
|
||||
aria-controls={id}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
>
|
||||
<NavIcon name={group.icon} />
|
||||
{group.label}
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
className="nav-group-chevron"
|
||||
>
|
||||
<path d="M6 9l6 6 6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
{open && (
|
||||
<div id={id} className="nav-dropdown">
|
||||
<span className="nav-dropdown-title">{group.title}</span>
|
||||
{group.items.map((i) => (
|
||||
<Link
|
||||
key={i.href}
|
||||
href={i.href}
|
||||
className="nav-dropdown-item"
|
||||
aria-current={here(i.href) ? "page" : undefined}
|
||||
>
|
||||
<NavIcon name={i.icon} />
|
||||
<span className="nav-dropdown-text">
|
||||
<span>{i.label}</span>
|
||||
{i.note && <span className="hint">{i.note}</span>}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/**
|
||||
* "Would you recommend us?" (0–10), once, as a box at the bottom of the page,
|
||||
* after its content and before the footer (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>
|
||||
);
|
||||
}
|
||||
@@ -184,8 +184,7 @@ export function PackageCards({
|
||||
{termsConsent && (
|
||||
<>
|
||||
{" "}
|
||||
A csomagot azonnal megkapod, ezért a fizetésnél kéred a teljesítés megkezdését, és ezzel lemondasz a 14
|
||||
napos elállási jogról. <Link href="/aszf">ÁSZF</Link>
|
||||
<Link href="/aszf">ÁSZF</Link>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
|
||||
@@ -44,13 +44,20 @@ export function PaymentReturn() {
|
||||
const r = await api<{
|
||||
status: string;
|
||||
name: string | null;
|
||||
gift: { id: string; recipient_name: string | null; recipient_email: string | null } | null;
|
||||
gift: {
|
||||
id: string;
|
||||
recipient_name: string | null;
|
||||
recipient_email: string | null;
|
||||
send_at: string | null;
|
||||
} | null;
|
||||
}>(`/payments/checkout/${encodeURIComponent(value)}`);
|
||||
if (stopped) return;
|
||||
if (r.status === "paid") {
|
||||
const text = !r.gift
|
||||
? `Köszönjük! Jóváírtuk: ${r.name ?? "a csomagod"}.`
|
||||
: r.gift.recipient_email
|
||||
: r.gift.recipient_email && r.gift.send_at
|
||||
? `Köszönjük! Az ajándékot ${new Date(r.gift.send_at).toLocaleString("hu-HU", { month: "long", day: "numeric", hour: "numeric", minute: "2-digit" })}-kor küldjük el ide: ${r.gift.recipient_email}.`
|
||||
: r.gift.recipient_email
|
||||
? `Köszönjük! Az ajándékot elküldtük ide: ${r.gift.recipient_email}. Az utalványt lent le is töltheted.`
|
||||
: "Köszönjük! Az ajándékutalvány elkészült: lent letöltheted, és átadhatod.";
|
||||
setNotice({ kind: "ok", text });
|
||||
|
||||
@@ -1,23 +1,37 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { Logo } from "@/components/SiteHeader";
|
||||
import { isChristmasTime } from "@/lib/season";
|
||||
|
||||
/** The footer of the public content pages (calculator, signs): their links help visitors and search engines. */
|
||||
export function PublicFooter() {
|
||||
/**
|
||||
* The footer of every page (the root layout draws it): the free content
|
||||
* pages (they help visitors and search engines), contact and the legal
|
||||
* pages. Logged in, the birth chart link leads to the user's own chart, and
|
||||
* contact straight to the feedback page.
|
||||
*/
|
||||
export function SiteFooter({ loggedIn }: { loggedIn: boolean }) {
|
||||
return (
|
||||
<footer className="lp-footer">
|
||||
<footer className="lp-footer site-footer">
|
||||
<div className="lp-wrap lp-footer-inner">
|
||||
<Logo />
|
||||
<nav aria-label="Lábléc" className="lp-footer-nav">
|
||||
<Link href="/szuletesi-horoszkop">Születési horoszkóp</Link>
|
||||
{/* Logged in: the user's own chart (the free calculator would start empty). */}
|
||||
{loggedIn ? (
|
||||
<Link href="/keplet">Születési horoszkópom</Link>
|
||||
) : (
|
||||
<Link href="/szuletesi-horoszkop">Születési horoszkóp</Link>
|
||||
)}
|
||||
<Link href="/csillagjegyek">Csillagjegyek</Link>
|
||||
<Link href="/hires-emberek">Híres emberek</Link>
|
||||
<Link href="/holdnaptar">Holdnaptár</Link>
|
||||
<Link href="/retrograd">Retrográd bolygók</Link>
|
||||
<Link href="/pelda">Példaelemzés</Link>
|
||||
<Link href="/kartyajoslas/pelda">Példajóslás</Link>
|
||||
<Link href={isChristmasTime() ? "/karacsony" : "/ajandek"}>Ajándékozás</Link>
|
||||
<Link href={loggedIn ? "/visszajelzes" : "/kapcsolat"}>Kapcsolat</Link>
|
||||
<Link href="/aszf">ÁSZF</Link>
|
||||
<Link href="/adatvedelem">Adatvédelem</Link>
|
||||
{!loggedIn && <Link href="/belepes">Belépés</Link>}
|
||||
</nav>
|
||||
<span className="hint">© {new Date().getFullYear()} Sorsfonalak</span>
|
||||
</div>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import type { Me } from "@/lib/types";
|
||||
import type { Me, SkyNow } from "@/lib/types";
|
||||
|
||||
import { MobileMenu } from "./MobileMenu";
|
||||
import { NavLinks } from "./NavLinks";
|
||||
import { MoonChip } from "./MoonChip";
|
||||
import { type NavGroup, type NavItem, NavLinks } from "./NavLinks";
|
||||
import { UserMenu } from "./UserMenu";
|
||||
|
||||
/** The mark: the orbit, the thread (an S, with the crossbar an f) and a star on the rim. */
|
||||
@@ -128,27 +129,63 @@ function PackageBadge({ me }: { me: Me }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function SiteHeader({ me }: { me: Me }) {
|
||||
const links = [
|
||||
{ href: "/keplet", label: "Képletem" },
|
||||
{ href: "/szemelyek", label: "Személyek" },
|
||||
{ href: "/osszevetesek", label: "Összevetések" },
|
||||
{ href: "/kartyajoslas", label: "Kártyajóslás" },
|
||||
{ href: "/csillagjegyek", label: "Csillagjegyek" },
|
||||
{ href: "/hires-emberek", label: "Híres emberek" },
|
||||
{ href: "/csomagok", label: "Csomagok" },
|
||||
/** The free pages: in the menu row one dropdown, in the ☰ menu a group of tiles. */
|
||||
const EXPLORE: NavItem[] = [
|
||||
{ href: "/csillagjegyek", label: "Csillagjegyek", icon: "signs", note: "A tizenkét jegy jellemzése" },
|
||||
{ href: "/hires-emberek", label: "Híres emberek", icon: "famous", note: "Ismert emberek képlete és elemzése" },
|
||||
{ href: "/holdnaptar", label: "Holdnaptár", icon: "moon", note: "Holdfázisok, fogyatkozások, holdjegyek" },
|
||||
{ href: "/retrograd", label: "Retrográd bolygók", icon: "retro", note: "Mikor retrográd a Merkúr és a többi" },
|
||||
];
|
||||
|
||||
/**
|
||||
* The header of the logged-in app: the menu with gold marks (the free pages
|
||||
* in one "Felfedezés" dropdown), the Moon today, the package and the account.
|
||||
* Below 1380px the menu moves behind ☰, grouped.
|
||||
*/
|
||||
export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
|
||||
const own: NavItem[] = [
|
||||
{ href: "/keplet", label: "Képletem", icon: "chart" },
|
||||
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
||||
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
||||
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
||||
];
|
||||
if (me.user.roles.includes("admin")) links.push({ href: "/admin", label: "Admin" });
|
||||
else if (me.user.roles.includes("creator")) links.push({ href: "/admin/hires-emberek", label: "Szerző" });
|
||||
const packages: NavItem = { href: "/csomagok", label: "Csomagok", icon: "packages" };
|
||||
const team: NavItem[] = me.user.roles.includes("admin")
|
||||
? [{ href: "/admin", label: "Admin", icon: "admin" }]
|
||||
: me.user.roles.includes("creator")
|
||||
? [{ href: "/admin/hires-emberek", label: "Szerző", icon: "admin" }]
|
||||
: [];
|
||||
const entries: (NavItem | NavGroup)[] = [
|
||||
...own,
|
||||
{ label: "Felfedezés", icon: "explore", title: "Ingyenes, mindenkinek", items: EXPLORE },
|
||||
packages,
|
||||
...team,
|
||||
];
|
||||
const { natal, synastry } = me.analyses_left;
|
||||
const left = natal + synastry;
|
||||
const packageNote = me.package ? `${me.package.name} · ${left} elemzés` : left > 0 ? `${left} elemzés` : undefined;
|
||||
return (
|
||||
<header className="site-header">
|
||||
<header className="site-header app-header">
|
||||
<Logo />
|
||||
<NavLinks links={links} />
|
||||
<NavLinks entries={entries} />
|
||||
<div className="who">
|
||||
{sky && <MoonChip sky={sky} />}
|
||||
<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 }]} />
|
||||
<MobileMenu
|
||||
className="mobile-menu-app"
|
||||
lead={sky ? <MoonChip sky={sky} /> : undefined}
|
||||
sections={[
|
||||
{ title: "Saját", links: own },
|
||||
{ title: "Felfedezés · ingyenes", grid: true, links: EXPLORE.map(({ note: _note, ...l }) => l) },
|
||||
{ links: [{ ...packages, note: packageNote }, ...team] },
|
||||
]}
|
||||
/>
|
||||
</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.";
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// The Christmas season of the gift campaign (Budapest dates; the backend
|
||||
// marks the gifts by the same window).
|
||||
|
||||
const parts = (now: Date) => {
|
||||
const [y, m, d] = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: "Europe/Budapest",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
})
|
||||
.format(now)
|
||||
.split("-")
|
||||
.map(Number);
|
||||
return { y, m, d };
|
||||
};
|
||||
|
||||
/** 15 November to 6 January: gifts are Christmas gifts (festive card, e-mail). */
|
||||
export function isChristmasTime(now = new Date()): boolean {
|
||||
const { m, d } = parts(now);
|
||||
return (m === 11 && d >= 15) || m === 12 || (m === 1 && d <= 6);
|
||||
}
|
||||
|
||||
/** Christmas morning (24 December, 8:00 Budapest) of this season, if still ahead. */
|
||||
export function christmasMorning(now = new Date()): Date | null {
|
||||
const { y, m } = parts(now);
|
||||
if (m !== 11 && m !== 12) return null;
|
||||
// 8:00 in Budapest is 7:00 UTC in December (winter time).
|
||||
const at = new Date(Date.UTC(y, 11, 24, 7, 0));
|
||||
return at.getTime() > now.getTime() + 10 * 60 * 1000 ? at : null;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -656,8 +660,12 @@ export interface AdminGift {
|
||||
checkout: { id: string; live: boolean | null; amount_huf: number | null } | null;
|
||||
invoice: { number: string | null; status: string } | null;
|
||||
storno: { status: string; number: string | null; error: string | null } | null;
|
||||
send_at: string | null;
|
||||
email_state: EmailState | null;
|
||||
}
|
||||
|
||||
export type EmailState = "scheduled" | "sending" | "sent" | "failed";
|
||||
|
||||
/** A package the user bought as a gift (`GET /v1/gifts`). */
|
||||
export interface Gift {
|
||||
id: string;
|
||||
@@ -674,6 +682,12 @@ export interface Gift {
|
||||
status: "open" | "redeemed" | "refunded";
|
||||
redeemed_at: string | null;
|
||||
refunded_at: string | null;
|
||||
/** E-mailed at this time (null: at once). */
|
||||
send_at: string | null;
|
||||
/** The e-mail: waiting for its time, going out, gone out or failed (null: none, or long gone out). */
|
||||
email_state: EmailState | null;
|
||||
/** Bought for Christmas (the card is festive). */
|
||||
christmas: boolean;
|
||||
/** E-mails sent so far. */
|
||||
sendings: number;
|
||||
/** Whether it can be sent by e-mail (again). */
|
||||
@@ -790,3 +804,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 }[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -137,6 +137,7 @@ async fn gift_card(id: Uuid, payload: &Value) -> Option<Pdf> {
|
||||
recipient_name: to.as_deref(),
|
||||
from_name: from.as_deref(),
|
||||
message: message.as_deref(),
|
||||
christmas: card["christmas_year"].as_i64().and_then(|y| i32::try_from(y).ok()),
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
let code: String = code.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
|
||||
|
||||
Reference in New Issue
Block a user