Compare commits

..
Author SHA1 Message Date
fecoandClaude Opus 5.5 47bbe2f348 Merge main into prod: one-card reading text, reading in progress stays on the table
CI / test (push) Successful in 1m44s
CI / build (push) Successful in 2m21s
CI / deploy (push) Successful in 48s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-22 11:33:27 +00:00
fecoandClaude Opus 5.5 6c5f0b160e Tarot: a reading being written stays on the table
CI / test (push) Successful in 1m43s
CI / build (push) Successful in 7m2s
CI / deploy (push) Skipped
Opening the page while a reading is written shows that reading (cards and
progress), not the form for a new one; the 'Új jóslás' button appears
only once the reading is finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-22 11:31:15 +00:00
fecoandClaude Opus 5.5 f8386cbf55 One-card readings: no 'cards together' section
CI / test (push) Successful in 2m10s
CI / build (push) Successful in 8m53s
CI / deploy (push) Skipped
With a single card the synthesis is about how its message shows in practice
(prompt rule and schema description), and the section is titled
'A gyakorlatban' instead of 'A lapok együtt'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-22 11:23:29 +00:00
fecoandClaude Opus 5.5 f6fc2e46ac Merge main into prod: one-card tarot readings, header row on phones
CI / test (push) Successful in 1m47s
CI / build (push) Successful in 1m7s
CI / deploy (push) Successful in 45s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-22 11:07:34 +00:00
fecoandClaude Opus 5.5 f7b9af5e8c One-card tarot readings pass validation; free-tools row fits on phones
CI / test (push) Successful in 1m46s
CI / build (push) Successful in 6m10s
CI / deploy (push) Skipped
- The answer check wanted two items in every list, so the one-card daily
  reading always failed ($.cards: too few items). Two items are now asked
  only of string lists; other lists must not be empty.
- The visitors' header row (Ingyenes · Születési horoszkóp · Csillagjegyek)
  overflowed and scrolled sideways below 412 px; it fits down to 320 px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-22 11:06:01 +00:00
fecoandClaude Opus 5.5 2ca065894d Merge main into prod: Hungarian error messages, visible input focus
CI / test (push) Successful in 1m49s
CI / build (push) Successful in 54s
CI / deploy (push) Successful in 42s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-22 10:36:31 +00:00
fecoandClaude Opus 5.5 9716f503bc Hungarian error messages; visible focus on input fields
CI / test (push) Successful in 1m47s
CI / build (push) Successful in 10m21s
CI / deploy (push) Skipped
- The browser's own form checks (required, minLength, e-mail format) show
  Hungarian text on every page (ValidationMessages in the root layout).
- User-facing backend errors are Hungarian: e-mail/password login, password
  length, links, invitations, sharing, questions, limits. Google/Apple token
  failures log the reason and tell the user to retry.
- errorText covers not_found, horoscope_unavailable and internal errors.
- Input fields: lighter background and gold caret on focus, the example text
  steps aside, so a click visibly lands in the field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-22 10:14:15 +00:00
19 changed files with 203 additions and 48 deletions
+4 -2
View File
@@ -601,7 +601,7 @@ pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>)
/// Checks an answer against our schema subset (objects with required /// Checks an answer against our schema subset (objects with required
/// properties, strings with at least three letters, string arrays with at /// properties, strings with at least three letters, string arrays with at
/// least two items). A placeholder such as "x" counts as missing. /// least two items, other arrays not empty). A placeholder such as "x" counts as missing.
pub fn validate(schema: &Value, value: &Value) -> Result<(), String> { pub fn validate(schema: &Value, value: &Value) -> Result<(), String> {
fn walk(schema: &Value, value: &Value, path: &str) -> Result<(), String> { fn walk(schema: &Value, value: &Value, path: &str) -> Result<(), String> {
match schema["type"].as_str() { match schema["type"].as_str() {
@@ -615,7 +615,9 @@ pub fn validate(schema: &Value, value: &Value) -> Result<(), String> {
} }
Some("array") => { Some("array") => {
let items = value.as_array().ok_or_else(|| format!("{path}: expected an array"))?; let items = value.as_array().ok_or_else(|| format!("{path}: expected an array"))?;
if items.len() < 2 { // Lists of strings need two items; other lists (a one-card reading's cards) one.
let min = if schema["items"]["type"] == "string" { 2 } else { 1 };
if items.len() < min {
return Err(format!("{path}: too few items")); return Err(format!("{path}: too few items"));
} }
items.iter().enumerate().try_for_each(|(i, v)| walk(&schema["items"], v, &format!("{path}[{i}]"))) items.iter().enumerate().try_for_each(|(i, v)| walk(&schema["items"], v, &format!("{path}[{i}]")))
+32 -5
View File
@@ -264,7 +264,7 @@ pub fn tarot_schema() -> Value {
} }
} }
}, },
"synthesis": {"type": "string", "description": "How the cards read together, 1-3 paragraphs separated by a blank line"}, "synthesis": {"type": "string", "description": "How the cards read together (a single card: how its message shows in practice), 1-3 paragraphs separated by a blank line"},
"advice": {"type": "string", "description": "A closing, encouraging paragraph with one or two concrete steps"} "advice": {"type": "string", "description": "A closing, encouraging paragraph with one or two concrete steps"}
} }
}) })
@@ -281,6 +281,13 @@ fn length(cards: usize) -> (usize, usize) {
fn hungarian_system(cards: usize) -> String { fn hungarian_system(cards: usize) -> String {
let (min, max) = length(cards); let (min, max) = length(cards);
let together = if cards == 1 {
"- Egyetlen lap van, nincs mit egymáshoz mérni: a „synthesis” mezőben arról írj, hogyan jelenhet meg a lap \
üzenete a gyakorlatban, az olvasó napjában vagy a kérdése ügyében (helyzetek, érzések, amelyekre figyelhet)."
} else {
"- A lapok együtt mesélnek: mutasd meg, hogyan kapcsolódnak egymáshoz (ismétlődő elemek, színek, nagy árkánumok \
súlya, az álló és fordított lapok aránya)."
};
format!( format!(
"Tapasztalt, empatikus, lélektani szemléletű tarot-olvasó vagy, aki az asztrológiát is ismeri. A Sorsfonalak \ "Tapasztalt, empatikus, lélektani szemléletű tarot-olvasó vagy, aki az asztrológiát is ismeri. A Sorsfonalak \
alkalmazás számára személyes kártyajóslást írsz egy kirakásról, amelyet az olvasó kérdésére húzott. alkalmazás számára személyes kártyajóslást írsz egy kirakásról, amelyet az olvasó kérdésére húzott.
@@ -292,8 +299,7 @@ Szabályok:
kiindulópont: a saját tudásod a lapok hagyományos szimbolikájáról (Rider–Waite) kiegészítheti, de ne mondjon neki ellent. kiindulópont: a saját tudásod a lapok hagyományos szimbolikájáról (Rider–Waite) kiegészítheti, de ne mondjon neki ellent.
- Minden lapot a pozíciója fényében olvass, és mindig a kérdésre vonatkoztasd. Ha nincs kérdés, az olvasó jelenlegi \ - Minden lapot a pozíciója fényében olvass, és mindig a kérdésre vonatkoztasd. Ha nincs kérdés, az olvasó jelenlegi \
életszakaszáról szólj általánosan. életszakaszáról szólj általánosan.
- A lapok együtt mesélnek: mutasd meg, hogyan kapcsolódnak egymáshoz (ismétlődő elemek, színek, nagy árkánumok \ {together}
súlya, az álló és fordított lapok aránya).
- Az olvasó Napját, Holdját és Aszcendensét (ha meg van adva) egy-két helyen, finoman kapcsold a lapokhoz, például a \ - Az olvasó Napját, Holdját és Aszcendensét (ha meg van adva) egy-két helyen, finoman kapcsold a lapokhoz, például a \
lapok elemén vagy asztrológiai megfelelésén keresztül; ne írj belőle horoszkópot. lapok elemén vagy asztrológiai megfelelésén keresztül; ne írj belőle horoszkópot.
- Közvetlenül az olvasóhoz szólj, tegező formában (egyes szám második személyben, „te”). - Közvetlenül az olvasóhoz szólj, tegező formában (egyes szám második személyben, „te”).
@@ -313,6 +319,13 @@ elem legyen, ahány lap van, a pozíciók sorrendjében.{HUNGARIAN_TERMS}"
fn english_system(language: &str, cards: usize) -> String { fn english_system(language: &str, cards: usize) -> String {
let (min, max) = length(cards); let (min, max) = length(cards);
let together = if cards == 1 {
"- There is a single card, nothing to weigh it against: in \"synthesis\" write how its message may show in \
practice, in the reader's day or in the matter of the question (situations and feelings to watch for)."
} else {
"- Show how the cards tell one story together (recurring elements and suits, the weight of the major arcana, \
upright versus reversed cards)."
};
format!( format!(
"You are an experienced, empathetic tarot reader with a psychological approach who also knows astrology. You \ "You are an experienced, empathetic tarot reader with a psychological approach who also knows astrology. You \
write a personal tarot reading for the Sorsfonalak app about a spread the reader drew for their question. write a personal tarot reading for the Sorsfonalak app about a spread the reader drew for their question.
@@ -324,8 +337,7 @@ Rules:
starting point; your knowledge of the traditional (Rider-Waite) symbolism may add to them but must not contradict them. starting point; your knowledge of the traditional (Rider-Waite) symbolism may add to them but must not contradict them.
- Read each card in the light of its position and always relate it to the question. Without a question, speak about \ - Read each card in the light of its position and always relate it to the question. Without a question, speak about \
the reader's present phase of life. the reader's present phase of life.
- Show how the cards tell one story together (recurring elements and suits, the weight of the major arcana, upright \ {together}
versus reversed cards).
- Link the reader's Sun, Moon and Ascendant (when given) to the cards once or twice, gently, e.g. through the cards' \ - Link the reader's Sun, Moon and Ascendant (when given) to the cards once or twice, gently, e.g. through the cards' \
elements or astrological correspondences; do not write a horoscope. elements or astrological correspondences; do not write a horoscope.
- Address the reader directly, in the second person. - Address the reader directly, in the second person.
@@ -464,4 +476,19 @@ mod tests {
assert!(Reading::parse(&wrong).is_err()); assert!(Reading::parse(&wrong).is_err());
assert!(Reading::parse(&json!({"spread": "daily", "cards": [{"card": "nincs"}]})).is_err()); assert!(Reading::parse(&json!({"spread": "daily", "cards": [{"card": "nincs"}]})).is_err());
} }
#[test]
fn one_card_has_no_reading_together() {
assert!(hungarian_system(1).contains("Egyetlen lap van") && !hungarian_system(1).contains("együtt mesélnek"));
assert!(hungarian_system(3).contains("együtt mesélnek"));
assert!(english_system("en", 1).contains("single card") && !english_system("en", 1).contains("one story"));
}
#[test]
fn a_one_card_answer_is_valid() {
let text = "Egy bekezdés a lapról.";
let answer = |cards: Value| json!({"title": "Napi üzenet", "summary": text, "cards": cards, "synthesis": text, "advice": text});
assert_eq!(crate::validate(&tarot_schema(), &answer(json!([{"body": text}]))), Ok(()));
assert!(crate::validate(&tarot_schema(), &answer(json!([]))).is_err());
}
} }
+2 -2
View File
@@ -147,10 +147,10 @@ pub fn removal_cookie(config: &Config) -> Cookie<'static> {
pub fn validate_password(password: &str) -> Result<(), ApiError> { pub fn validate_password(password: &str) -> Result<(), ApiError> {
let len = password.chars().count(); let len = password.chars().count();
if len < MIN_PASSWORD_LEN { if len < MIN_PASSWORD_LEN {
return Err(ApiError::BadRequest(format!("the password must be at least {MIN_PASSWORD_LEN} characters long"))); return Err(ApiError::BadRequest(format!("A jelszó legalább {MIN_PASSWORD_LEN} karakter legyen.")));
} }
if len > MAX_PASSWORD_LEN { if len > MAX_PASSWORD_LEN {
return Err(ApiError::BadRequest(format!("the password must be at most {MAX_PASSWORD_LEN} characters long"))); return Err(ApiError::BadRequest(format!("A jelszó legfeljebb {MAX_PASSWORD_LEN} karakter lehet.")));
} }
Ok(()) Ok(())
} }
+2 -2
View File
@@ -25,11 +25,11 @@ pub enum ApiError {
Conflict { code: &'static str, message: String }, Conflict { code: &'static str, message: String },
#[error("{0}")] #[error("{0}")]
Gone(String), Gone(String),
#[error("the link is invalid or has expired")] #[error("Ez a link érvénytelen vagy lejárt.")]
InvalidToken, InvalidToken,
#[error("no {unit} analysis left (balance {balance})")] #[error("no {unit} analysis left (balance {balance})")]
InsufficientCredits { unit: &'static str, balance: i64 }, InsufficientCredits { unit: &'static str, balance: i64 },
#[error("too many attempts; try again later")] #[error("Túl sok próbálkozás. Próbáld újra később.")]
TooManyRequests, TooManyRequests,
/// A usage limit; the message is shown to the user as is. /// A usage limit; the message is shown to the user as is.
#[error("{message}")] #[error("{message}")]
+17 -6
View File
@@ -18,6 +18,11 @@ const GOOGLE_ISSUERS: &[&str] = &["accounts.google.com", "https://accounts.googl
const APPLE_ISSUERS: &[&str] = &["https://appleid.apple.com"]; const APPLE_ISSUERS: &[&str] = &["https://appleid.apple.com"];
const JWKS_MAX_AGE: Duration = Duration::from_secs(3600); const JWKS_MAX_AGE: Duration = Duration::from_secs(3600);
/// What the user sees when a token is rejected; the reason goes to the log.
fn failed(provider: &str) -> ApiError {
ApiError::InvalidCredentials(format!("Nem sikerült a belépés {provider}-fiókkal. Próbáld újra."))
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct IdClaims { pub struct IdClaims {
/// Stable account id at the provider. /// Stable account id at the provider.
@@ -111,7 +116,8 @@ impl IdTokenVerifier {
let found = keys.iter().find(|k| k.kid == kid).cloned(); let found = keys.iter().find(|k| k.kid == kid).cloned();
*self.cache.write().await = Some((Instant::now(), keys)); *self.cache.write().await = Some((Instant::now(), keys));
found.ok_or_else(|| { found.ok_or_else(|| {
ApiError::InvalidCredentials(format!("the {} token is signed with an unknown key", self.provider)) tracing::warn!(provider = self.provider, "id token signed with an unknown key");
failed(self.provider)
}) })
} }
@@ -120,14 +126,19 @@ impl IdTokenVerifier {
if !self.enabled() { if !self.enabled() {
return Err(ApiError::Forbidden(format!("{provider} login is not configured"))); return Err(ApiError::Forbidden(format!("{provider} login is not configured")));
} }
let invalid = let invalid = |e: jsonwebtoken::errors::Error| {
|e: jsonwebtoken::errors::Error| ApiError::InvalidCredentials(format!("invalid {provider} token: {e}")); tracing::warn!(provider, error = %e, "invalid id token");
failed(provider)
};
let header = decode_header(id_token).map_err(invalid)?; let header = decode_header(id_token).map_err(invalid)?;
if header.alg != Algorithm::RS256 { if header.alg != Algorithm::RS256 {
return Err(ApiError::InvalidCredentials(format!("invalid {provider} token: unexpected algorithm"))); tracing::warn!(provider, alg = ?header.alg, "id token with an unexpected algorithm");
return Err(failed(provider));
} }
let kid = let kid = header.kid.ok_or_else(|| {
header.kid.ok_or_else(|| ApiError::InvalidCredentials(format!("invalid {provider} token: no key id")))?; tracing::warn!(provider, "id token without a key id");
failed(provider)
})?;
let jwk = self.key(&kid).await?; let jwk = self.key(&kid).await?;
let key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(invalid)?; let key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(invalid)?;
let mut validation = Validation::new(Algorithm::RS256); let mut validation = Validation::new(Algorithm::RS256);
+2 -2
View File
@@ -113,9 +113,9 @@ pub async fn change_password(
.await?; .await?;
if let Some((hash,)) = existing { if let Some((hash,)) = existing {
let current = let current =
req.current_password.ok_or_else(|| ApiError::BadRequest("current_password is required".into()))?; req.current_password.ok_or_else(|| ApiError::BadRequest("Add meg a jelenlegi jelszavadat.".into()))?;
if !verify_password(current, hash).await? { if !verify_password(current, hash).await? {
return Err(ApiError::InvalidCredentials("the current password is wrong".into())); return Err(ApiError::InvalidCredentials("A jelenlegi jelszó hibás.".into()));
} }
} }
let hash = hash_password(req.new_password).await?; let hash = hash_password(req.new_password).await?;
+5 -3
View File
@@ -45,7 +45,7 @@ pub fn normalize_email(email: &str) -> Result<String, ApiError> {
!local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.') !local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.')
}) })
&& !email.chars().any(char::is_whitespace); && !email.chars().any(char::is_whitespace);
if valid { Ok(email) } else { Err(ApiError::BadRequest("invalid e-mail address".into())) } if valid { Ok(email) } else { Err(ApiError::BadRequest("Érvénytelen e-mail-cím.".into())) }
} }
pub fn validate_locale(state: &AppState, locale: Option<&str>) -> Result<String, ApiError> { pub fn validate_locale(state: &AppState, locale: Option<&str>) -> Result<String, ApiError> {
@@ -288,7 +288,7 @@ pub async fn login(
WithRejection(Json(req), _): Body<LoginRequest>, WithRejection(Json(req), _): Body<LoginRequest>,
) -> ApiResult<impl IntoResponse> { ) -> ApiResult<impl IntoResponse> {
password_login_enabled(&state)?; password_login_enabled(&state)?;
let invalid = || ApiError::InvalidCredentials("wrong e-mail address or password".into()); let invalid = || ApiError::InvalidCredentials("Hibás e-mail-cím vagy jelszó.".into());
let email = normalize_email(&req.email).map_err(|_| invalid())?; let email = normalize_email(&req.email).map_err(|_| invalid())?;
state.login_limiter.check(&email)?; state.login_limiter.check(&email)?;
@@ -405,7 +405,9 @@ async fn social_login(
let email = match (claims.email.as_deref(), claims.email_verified) { let email = match (claims.email.as_deref(), claims.email_verified) {
(Some(e), true) => normalize_email(e)?, (Some(e), true) => normalize_email(e)?,
_ => { _ => {
return Err(ApiError::InvalidCredentials(format!("the {provider} account has no verified e-mail address"))); return Err(ApiError::InvalidCredentials(format!(
"A {provider}-fiókodhoz nem tartozik megerősített e-mail-cím."
)));
} }
}; };
+1 -1
View File
@@ -42,7 +42,7 @@ pub async fn places(
) -> ApiResult<Json<Value>> { ) -> ApiResult<Json<Value>> {
let q = query.q.trim(); let q = query.q.trim();
if !valid_country(&query.country) || q.chars().count() < 2 || q.chars().count() > 80 { if !valid_country(&query.country) || q.chars().count() < 2 || q.chars().count() > 80 {
return Err(ApiError::BadRequest("a country code and 2 to 80 characters of a place name are needed".into())); return Err(ApiError::BadRequest("Válassz országot, és írj be 2–80 karaktert a település nevéből.".into()));
} }
state.places_limiter.hit(&visitor(&headers))?; state.places_limiter.hit(&visitor(&headers))?;
Ok(Json(state.horoscope.places(&query.country, q, query.limit.unwrap_or(8).min(10)).await?)) Ok(Json(state.horoscope.places(&query.country, q, query.limit.unwrap_or(8).min(10)).await?))
+2 -2
View File
@@ -97,7 +97,7 @@ pub async fn primary_chart(db: &PgPool, owner: Uuid) -> Result<Option<ChartRow>,
fn clean_label(label: &str) -> Result<String, ApiError> { fn clean_label(label: &str) -> Result<String, ApiError> {
let label: String = label.trim().chars().take(100).collect(); let label: String = label.trim().chars().take(100).collect();
if label.is_empty() { Err(ApiError::BadRequest("label must not be empty".into())) } else { Ok(label) } if label.is_empty() { Err(ApiError::BadRequest("A név nem lehet üres.".into())) } else { Ok(label) }
} }
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> { pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
@@ -195,7 +195,7 @@ pub async fn create(
if count >= state.config.max_charts_per_user { if count >= state.config.max_charts_per_user {
return Err(ApiError::conflict( return Err(ApiError::conflict(
"chart_limit_reached", "chart_limit_reached",
format!("at most {} charts can be saved", state.config.max_charts_per_user), format!("Legfeljebb {} képletet lehet menteni.", state.config.max_charts_per_user),
)); ));
} }
let free = state.config.free_person_slots; let free = state.config.free_person_slots;
+1 -1
View File
@@ -221,7 +221,7 @@ pub async fn create(
if count >= MAX_PER_CHART && !is_admin(&auth) { if count >= MAX_PER_CHART && !is_admin(&auth) {
return Err(ApiError::conflict( return Err(ApiError::conflict(
"forecast_limit_reached", "forecast_limit_reached",
format!("at most {MAX_PER_CHART} forecasts can be saved for a chart"), format!("Egy képlethez legfeljebb {MAX_PER_CHART} előrejelzés menthető."),
)); ));
} }
+2 -2
View File
@@ -115,7 +115,7 @@ pub async fn ask(
return Err(ApiError::NotFound("analysis")); return Err(ApiError::NotFound("analysis"));
} }
if !ASKABLE.contains(&analysis.kind.as_str()) { if !ASKABLE.contains(&analysis.kind.as_str()) {
return Err(ApiError::BadRequest("questions can be asked about a detailed analysis or a forecast".into())); return Err(ApiError::BadRequest("Kérdést részletes elemzésről vagy előrejelzésről lehet feltenni.".into()));
} }
if analysis.status != "done" { if analysis.status != "done" {
return Err(ApiError::conflict("analysis_not_ready", "Az elemzés még nem készült el.")); return Err(ApiError::conflict("analysis_not_ready", "Az elemzés még nem készült el."));
@@ -123,7 +123,7 @@ pub async fn ask(
let question = req.question.trim().replace("\r\n", "\n"); let question = req.question.trim().replace("\r\n", "\n");
let length = question.chars().count(); let length = question.chars().count();
if !(3..=QUESTION_MAX_CHARS).contains(&length) { if !(3..=QUESTION_MAX_CHARS).contains(&length) {
return Err(ApiError::BadRequest(format!("the question must be 3 to {QUESTION_MAX_CHARS} characters long"))); return Err(ApiError::BadRequest(format!("A kérdés 3–{QUESTION_MAX_CHARS} karakter hosszú lehet.")));
} }
let (open, total): (i64, i64) = sqlx::query_as( let (open, total): (i64, i64) = sqlx::query_as(
"SELECT count(*) FILTER (WHERE status IN ('pending', 'running')), count(*) FROM questions WHERE analysis_id = $1", "SELECT count(*) FILTER (WHERE status IN ('pending', 'running')), count(*) FROM questions WHERE analysis_id = $1",
+1 -1
View File
@@ -155,7 +155,7 @@ pub async fn create(
return Err(ApiError::NotFound("analysis")); return Err(ApiError::NotFound("analysis"));
} }
if analysis.status != "done" { if analysis.status != "done" {
return Err(ApiError::conflict("analysis_not_ready", "only finished analyses can be shared")); return Err(ApiError::conflict("analysis_not_ready", "Csak elkészült elemzést lehet megosztani."));
} }
(None, None, Some(req.target_id), "analysis") (None, None, Some(req.target_id), "analysis")
} }
+8 -8
View File
@@ -210,7 +210,7 @@ pub async fn create(
WithRejection(Json(req), _): Body<CreateSynastry>, WithRejection(Json(req), _): Body<CreateSynastry>,
) -> ApiResult<(StatusCode, Json<Value>)> { ) -> ApiResult<(StatusCode, Json<Value>)> {
if req.chart1_id == req.chart2_id { if req.chart1_id == req.chart2_id {
return Err(ApiError::BadRequest("a chart cannot be compared with itself".into())); return Err(ApiError::BadRequest("Egy képletet önmagával nem lehet összevetni.".into()));
} }
let chart1 = owned_chart(&state.db, req.chart1_id, auth.id()).await?; let chart1 = owned_chart(&state.db, req.chart1_id, auth.id()).await?;
let chart2 = owned_chart(&state.db, req.chart2_id, auth.id()).await?; let chart2 = owned_chart(&state.db, req.chart2_id, auth.id()).await?;
@@ -249,9 +249,9 @@ pub struct CreateInvite {
async fn chart_or_primary(db: &PgPool, chart_id: Option<Uuid>, user: Uuid) -> Result<ChartRow, ApiError> { async fn chart_or_primary(db: &PgPool, chart_id: Option<Uuid>, user: Uuid) -> Result<ChartRow, ApiError> {
match chart_id { match chart_id {
Some(id) => owned_chart(db, id, user).await, Some(id) => owned_chart(db, id, user).await,
None => primary_chart(db, user).await?.ok_or_else(|| { None => primary_chart(db, user)
ApiError::conflict("primary_chart_required", "create your own chart first (is_primary: true)") .await?
}), .ok_or_else(|| ApiError::conflict("primary_chart_required", "Előbb add meg a saját születési adataidat.")),
} }
} }
@@ -459,12 +459,12 @@ pub async fn accept_invite(
) -> ApiResult<(StatusCode, Json<Value>)> { ) -> ApiResult<(StatusCode, Json<Value>)> {
let invite = invite_by_token(&state.db, &req.token).await?; let invite = invite_by_token(&state.db, &req.token).await?;
match invite_status(invite.accepted_at, invite.expires_at) { match invite_status(invite.accepted_at, invite.expires_at) {
"accepted" => return Err(ApiError::Gone("this invitation has already been accepted".into())), "accepted" => return Err(ApiError::Gone("Ezt a meghívót már elfogadták.".into())),
"expired" => return Err(ApiError::Gone("this invitation has expired".into())), "expired" => return Err(ApiError::Gone("Ez a meghívó lejárt.".into())),
_ => {} _ => {}
} }
if invite.inviter_id == auth.id() { if invite.inviter_id == auth.id() {
return Err(ApiError::conflict("own_invitation", "you cannot accept your own invitation")); return Err(ApiError::conflict("own_invitation", "A saját meghívódat nem fogadhatod el."));
} }
let my_chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?; let my_chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
let inviter_chart = let inviter_chart =
@@ -489,7 +489,7 @@ pub async fn accept_invite(
if created { if created {
sqlx::query("DELETE FROM synastries WHERE id = $1").bind(row.id).execute(&state.db).await?; sqlx::query("DELETE FROM synastries WHERE id = $1").bind(row.id).execute(&state.db).await?;
} }
return Err(ApiError::Gone("this invitation has already been accepted".into())); return Err(ApiError::Gone("Ezt a meghívót már elfogadták.".into()));
} }
let inviter: Option<db::User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1")) let inviter: Option<db::User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1"))
.bind(invite.inviter_id) .bind(invite.inviter_id)
+15 -2
View File
@@ -132,7 +132,10 @@ textarea.inp { padding: 12px 14px; line-height: 1.55; min-height: 96px; resize:
/* A button beside input fields is as tall as they are */ /* A button beside input fields is as tall as they are */
.row > .btn:not(.btn-sm), .redeem-row > .btn { min-height: 48px; } .row > .btn:not(.btn-sm), .redeem-row > .btn { min-height: 48px; }
.inp::placeholder { color: #8a93ab; } .inp::placeholder { color: #8a93ab; }
.inp:focus { outline: none; border-color: var(--gold); box-shadow: 0 0 0 3px rgba(217, 180, 106, 0.25); } .inp:focus { outline: none; border-color: var(--gold); background-color: #182037; box-shadow: 0 0 0 3px rgba(217, 180, 106, 0.25); }
/* Clicking in must visibly change the field: the example text steps aside for the caret */
.inp:focus::placeholder { color: transparent; }
.inp { caret-color: var(--gold); }
.inp:disabled { opacity: 0.55; } .inp:disabled { opacity: 0.55; }
.check { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--ink-2); min-height: 32px; cursor: pointer; } .check { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--ink-2); min-height: 32px; cursor: pointer; }
.check input { width: 18px; height: 18px; accent-color: var(--gold); margin: 0; } .check input { width: 18px; height: 18px; accent-color: var(--gold); margin: 0; }
@@ -974,9 +977,19 @@ a.pair-row:hover strong { color: var(--gold); }
.lp-nav { display: none; } .lp-nav { display: none; }
/* On phones the free tools get their own row under the logo. */ /* On phones the free tools get their own row under the logo. */
.lp-header { flex-wrap: wrap; row-gap: 4px; } .lp-header { flex-wrap: wrap; row-gap: 4px; }
.lp-free { order: 3; flex-basis: 100%; padding-left: 0; border-left: 0; overflow-x: auto; scrollbar-width: none; } .lp-free { order: 3; flex-basis: 100%; padding-left: 0; border-left: 0; overflow-x: auto; scrollbar-width: none; gap: 0; }
.lp-free a { padding: 10px 7px; }
.lp-free-label { margin-right: 4px; }
.lp-header > .btn { margin-left: auto; } .lp-header > .btn { margin-left: auto; }
} }
/* The free-tools row fits on narrow phones too, without sideways scrolling */
@media (max-width: 380px) {
.lp-free a { font-size: 14px; padding: 10px 5px; }
.lp-free-label { font-size: 10px; padding: 2px 6px; letter-spacing: 0.5px; }
}
@media (max-width: 350px) {
.lp-free-label { display: none; }
}
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.lp *, .lp-orbit { animation: none !important; } .lp *, .lp-orbit { animation: none !important; }
.lp-rise, .lp-wheel .w-point { opacity: 1; transform: none; } .lp-rise, .lp-wheel .w-point { opacity: 1; transform: none; }
+2
View File
@@ -5,6 +5,7 @@ import { Suspense } from "react";
import { NightSky } from "@/components/NightSky"; import { NightSky } from "@/components/NightSky";
import { PaymentReturn } from "@/components/PaymentReturn"; import { PaymentReturn } from "@/components/PaymentReturn";
import { SiteHeader } from "@/components/SiteHeader"; import { SiteHeader } from "@/components/SiteHeader";
import { ValidationMessages } from "@/components/ValidationMessages";
import { getMe } from "@/lib/server"; import { getMe } from "@/lib/server";
import { siteUrl } from "@/lib/share"; import { siteUrl } from "@/lib/share";
@@ -32,6 +33,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
<html lang="hu" className={`${cormorant.variable} ${inter.variable}`}> <html lang="hu" className={`${cormorant.variable} ${inter.variable}`}>
<body> <body>
<NightSky /> <NightSky />
<ValidationMessages />
{me && <SiteHeader me={me} />} {me && <SiteHeader me={me} />}
{children} {children}
{me && ( {me && (
@@ -0,0 +1,83 @@
"use client";
import { useEffect } from "react";
type Field = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
/** Hungarian text for a field the browser found invalid. */
function message(el: Field): string {
const v = el.validity;
if (v.valueMissing) {
if (el instanceof HTMLSelectElement) return "Válassz a listából.";
if (el instanceof HTMLInputElement && el.type === "checkbox") return "Jelöld be a folytatáshoz.";
if (el instanceof HTMLInputElement && el.type === "radio") return "Válassz egyet.";
return "Töltsd ki ezt a mezőt.";
}
if (v.typeMismatch) {
if (el.type === "email") return "Adj meg egy érvényes e-mail-címet.";
if (el.type === "url") return "Adj meg egy érvényes webcímet.";
}
if (v.tooShort && !(el instanceof HTMLSelectElement)) {
return `Legalább ${el.minLength} karakter legyen (most ${el.value.length}).`;
}
if (v.tooLong && !(el instanceof HTMLSelectElement)) return `Legfeljebb ${el.maxLength} karakter lehet.`;
if (el instanceof HTMLInputElement) {
if (v.rangeUnderflow) return `A legkisebb megengedett érték: ${el.min}.`;
if (v.rangeOverflow) return `A legnagyobb megengedett érték: ${el.max}.`;
if (v.patternMismatch) return el.title || "A formátum nem megfelelő.";
if (v.badInput && el.type === "number") return "Számot adj meg.";
}
return "Az érték nem megfelelő.";
}
function isField(t: EventTarget | null): t is Field {
return t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement;
}
/**
* The browser's own form checks (required, minLength, type="email"…) speak
* the browser's language. This puts Hungarian text into those bubbles on
* every page; the checks themselves stay the browser's.
*/
export function ValidationMessages() {
useEffect(() => {
// Fields whose message was set here, so it can be cleared again.
const marked = new WeakSet<Field>();
const clear = (el: Field) => {
if (marked.has(el)) {
el.setCustomValidity("");
marked.delete(el);
}
};
const onInvalid = (e: Event) => {
const el = e.target;
if (!isField(el)) return;
clear(el);
// A message the page set itself (setCustomValidity) is kept.
if (el.validity.customError || el.validity.valid) return;
el.setCustomValidity(message(el));
marked.add(el);
};
const onEdit = (e: Event) => {
if (isField(e.target)) clear(e.target);
};
// A submit attempt checks the fields afresh: a value set by code (no input event) is not stuck.
const onClick = (e: Event) => {
const button = (e.target as Element | null)?.closest?.("button, input[type=submit]");
const form = (button as HTMLButtonElement | HTMLInputElement | null)?.form;
if (!form || (button as HTMLButtonElement).type !== "submit") return;
for (const el of Array.from(form.elements)) if (isField(el)) clear(el);
};
document.addEventListener("invalid", onInvalid, true);
document.addEventListener("input", onEdit, true);
document.addEventListener("change", onEdit, true);
document.addEventListener("click", onClick, true);
return () => {
document.removeEventListener("invalid", onInvalid, true);
document.removeEventListener("input", onEdit, true);
document.removeEventListener("change", onEdit, true);
document.removeEventListener("click", onClick, true);
};
}, []);
return null;
}
@@ -16,6 +16,8 @@ export function TarotResult({
question: string | null; question: string | null;
content: TarotContent; content: TarotContent;
}) { }) {
// A single card has nothing to read it with: its synthesis is about everyday life.
const together = cards.length === 1 ? "A gyakorlatban" : "A lapok együtt";
return ( return (
<article className="tarot-result"> <article className="tarot-result">
<header className="tarot-result-head"> <header className="tarot-result-head">
@@ -51,8 +53,8 @@ export function TarotResult({
</ol> </ol>
{content.synthesis && ( {content.synthesis && (
<section className="tarot-synthesis" aria-label="A lapok együtt"> <section className="tarot-synthesis" aria-label={together}>
<h3>A lapok együtt</h3> <h3>{together}</h3>
<Paragraphs text={content.synthesis} /> <Paragraphs text={content.synthesis} />
</section> </section>
)} )}
@@ -50,10 +50,12 @@ export function TarotTable({
const [spread, setSpread] = useState<SpreadId>("trinity"); const [spread, setSpread] = useState<SpreadId>("trinity");
const [topic, setTopic] = useState<TopicId>("general"); const [topic, setTopic] = useState<TopicId>("general");
const [question, setQuestion] = useState(""); const [question, setQuestion] = useState("");
const [phase, setPhase] = useState<Phase>("setup"); // A reading still being written is shown on the table, not the form for a new one.
const inProgress = initialReadings.find((r) => r.status === "pending" || r.status === "running") ?? null;
const [phase, setPhase] = useState<Phase>(inProgress ? "done" : "setup");
const [picked, setPicked] = useState<number[]>([]); const [picked, setPicked] = useState<number[]>([]);
const [current, setCurrent] = useState<TarotReading | null>(null); const [current, setCurrent] = useState<TarotReading | null>(inProgress);
const [revealed, setRevealed] = useState(0); const [revealed, setRevealed] = useState(inProgress?.cards.length ?? 0);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [buying, setBuying] = useState(false); const [buying, setBuying] = useState(false);
@@ -243,7 +245,9 @@ export function TarotTable({
? "A lapok…" ? "A lapok…"
: "A kirakásod"} : "A kirakásod"}
</h2> </h2>
{question.trim() && <p className="tarot-question">„{question.trim()}”</p>} {(current ? current.question : question.trim()) && (
<p className="tarot-question">„{current ? current.question : question.trim()}”</p>
)}
<p className="hint" role="status"> <p className="hint" role="status">
{phase === "picking" && {phase === "picking" &&
`Hangolódj a kérdésedre, és válassz ösztönösen. ${picked.length}/${chosen.cards}`} `Hangolódj a kérdésedre, és válassz ösztönösen. ${picked.length}/${chosen.cards}`}
@@ -265,9 +269,11 @@ export function TarotTable({
<> <>
<TarotLive key={current.id} initial={current} isAdmin={isAdmin} onChange={finished} /> <TarotLive key={current.id} initial={current} isAdmin={isAdmin} onChange={finished} />
<div className="form-actions"> <div className="form-actions">
{!writing && (
<button type="button" className="btn" onClick={again}> <button type="button" className="btn" onClick={again}>
Új jóslás Új jóslás
</button> </button>
)}
<Link href={`/kartyajoslas/${current.id}`} className="btn btn-ghost"> <Link href={`/kartyajoslas/${current.id}`} className="btn btn-ghost">
Külön oldalon Külön oldalon
</Link> </Link>
+7
View File
@@ -37,6 +37,13 @@ export function errorText(e: unknown): string {
return "Ehhez nincs jogosultságod."; return "Ehhez nincs jogosultságod.";
case "insufficient_credits": case "insufficient_credits":
return "Nincs több részletes elemzésed ebből a fajtából."; return "Nincs több részletes elemzésed ebből a fajtából.";
case "not_found":
return "Nem található. Lehet, hogy közben törölték.";
case "horoscope_unavailable":
return "A számítás most nem érhető el. Próbáld újra pár perc múlva.";
case "internal_error":
case "error":
return "Váratlan hiba történt. Próbáld újra később.";
default: default:
return e.message; return e.message;
} }