Weekly horoscope: its own page, a Monday e-mail, and one page for every e-mail setting
CI / test (push) Successful in 3m17s
CI / build (push) Skipped
CI / deploy (push) Skipped

- The week's sky on the member's own chart (horoscope-api POST /v1/week,
  astro_engine::week): the planets' aspects to the natal points with the day
  each is exact, positions, the Moon's signs, lunar phases, stations and sign
  changes; stored once per chart and week (weekly_skies, migration 0047).
- Its text is a 'weekly' analysis written by the summary's (cheap) model when
  the member opens /heti-horoszkop: one month per page, the newest week
  first, the waiting animation while it is written. In the menu, and linked
  from the chart page.
- Monday 7:00 e-mail (worker task 'weekly'): only that it is there; on by
  default for everyone with a chart, members of today too. Its footer opens
  /ertesitesek?token=…, where the weekly e-mail and every forum e-mail can
  be set without logging in; the mail client's one-click unsubscribe turns
  off the weekly one. Also a switch on the page and on the Profile page.
- Privacy notice (HU/EN) describes it; ratings, admin labels and the model
  page know the new kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-27 09:40:09 +00:00
co-authored by Claude Opus 5.5
parent 50c29e4595
commit 0358e137f1
46 changed files with 2368 additions and 70 deletions
+2 -1
View File
@@ -45,7 +45,8 @@ impl Function {
pub fn of(kind: Kind) -> Function {
match kind {
Kind::Summary => Function::Summary,
// The weekly horoscope is written by the summary's (cheaper) model.
Kind::Summary | Kind::Weekly => Function::Summary,
Kind::Question => Function::Question,
Kind::Natal | Kind::Synastry | Kind::Forecast | Kind::Celebrity => Function::Analysis,
}
+7
View File
@@ -41,6 +41,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
.await?;
let replies = super::feedback::unseen_replies(&mut conn, auth.id()).await?;
let nps_due = super::feedback::nps_due(&mut conn, auth.id()).await?;
let weekly_email: bool = sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1")
.bind(auth.id())
.fetch_one(&mut *conn)
.await?;
Ok(Json(json!({
"user": UserView::from(&auth.user),
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
@@ -59,6 +63,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
"feedback_replies_unseen": replies,
// Ask the "would you recommend us?" question now.
"nps_due": nps_due,
// Monday's e-mail about the weekly horoscope is on.
"weekly_email": weekly_email,
})))
}
@@ -169,6 +175,7 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
"exported_at": rfc3339(OffsetDateTime::now_utc()),
"user": UserView::from(&auth.user),
"last_login_at": rfc3339_opt(auth.user.last_login_at),
"weekly_horoscope_email": rows("SELECT json_build_object('on', weekly_email, 'last_sent_for_week', weekly_email_sent_on) FROM users WHERE id = $1").await?.into_iter().next(),
"login_methods": rows("SELECT json_build_object('provider', provider, 'email', email, 'created_at', created_at, 'last_used_at', last_used_at) FROM auth_identities WHERE user_id = $1").await?,
"sessions": rows("SELECT json_build_object('created_at', created_at, 'expires_at', expires_at, 'user_agent', user_agent) FROM sessions WHERE user_id = $1").await?,
"charts": rows("SELECT json_build_object('id', id, 'label', label, 'is_primary', is_primary, 'birth_data', birth_data, 'result', result, 'created_at', created_at) FROM charts WHERE owner_id = $1 AND kind <> 'celebrity'").await?,
+32 -5
View File
@@ -7,7 +7,8 @@
//! instead, free of charge, so the same chart is never paid for twice.
//!
//! Every saved chart also gets a free short summary (`summary` kind, written
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
//! by `SUMMARY_MODEL`); the detailed analyses are paid. The own chart's free
//! weekly horoscope (`weekly` kind, see [`super::weekly`]) uses the summary's model.
use analysis_prompt::Kind;
use axum::Json;
@@ -18,7 +19,7 @@ use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use time::OffsetDateTime;
use time::{Date, OffsetDateTime};
use uuid::Uuid;
use super::auth::validate_locale;
@@ -53,11 +54,14 @@ pub struct AnalysisRow {
pub next_attempt_at: OffsetDateTime,
/// When the current text was asked for (set again by a regeneration).
pub requested_at: OffsetDateTime,
/// The Monday of a weekly horoscope.
pub week_start: Option<Date>,
}
pub(super) const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
content, error, \
credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at";
credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at, \
week_start";
impl AnalysisRow {
pub fn view(&self) -> Value {
@@ -78,6 +82,7 @@ impl AnalysisRow {
"attempts": self.attempts,
"next_attempt_at": rfc3339(self.next_attempt_at),
"requested_at": rfc3339(self.requested_at),
"week_start": self.week_start.map(|d| d.to_string()),
})
}
}
@@ -143,6 +148,12 @@ pub(super) enum Target {
chart_id: Uuid,
hash: String,
},
/// The own chart's weekly horoscope (free); `hash` covers the chart and the week.
Weekly {
chart_id: Uuid,
hash: String,
week_start: Date,
},
}
async fn request(
@@ -197,6 +208,11 @@ pub(super) async fn queue(
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)),
Target::Celebrity { chart_id, hash } => ("celebrity", hash, Some(*chart_id), None, None),
Target::Weekly { chart_id, hash, .. } => ("weekly", hash, Some(*chart_id), None, None),
};
let week_start = match target {
Target::Weekly { week_start, .. } => Some(*week_start),
_ => None,
};
let (model, fallback) = &crate::models::models_for(state, Kind::parse(kind).expect("known kind")).await?;
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
@@ -225,8 +241,9 @@ pub(super) async fn queue(
let insert = format!(
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at, \
forecast_id, fallback_model) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) RETURNING {ANALYSIS_COLUMNS}"
forecast_id, fallback_model, week_start) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) \
RETURNING {ANALYSIS_COLUMNS}"
);
let id = Uuid::now_v7();
@@ -263,6 +280,7 @@ pub(super) async fn queue(
.bind(OffsetDateTime::now_utc())
.bind(forecast_id)
.bind(fallback)
.bind(week_start)
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
@@ -288,6 +306,7 @@ pub(super) async fn queue(
.bind(None::<OffsetDateTime>)
.bind(forecast_id)
.bind(fallback)
.bind(week_start)
.fetch_one(&mut *tx)
.await?;
if let Some(unit) = unit {
@@ -395,6 +414,14 @@ pub async fn request_for_forecast(
/// The hash of what the analysis is about (chart, comparison or forecast),
/// part of its cache key; `None` when that was deleted.
pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result<Option<String>, sqlx::Error> {
if row.kind == "weekly" {
let hash: Option<String> = sqlx::query_scalar("SELECT chart_hash FROM charts WHERE id = $1")
.bind(row.chart_id)
.fetch_optional(db)
.await?;
let week = row.week_start.map(|d| d.to_string()).unwrap_or_default();
return Ok(hash.map(|h| super::weekly::target_hash(&h, &week)));
}
let (query, id) = match row.kind.as_str() {
"synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id),
"forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id),
+2 -1
View File
@@ -349,7 +349,8 @@ async fn corrected_birth(
// The user's own comparisons with the person are deleted on correction (they
// no longer match), unless a paid analysis was written for one of them.
let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as(
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed') \
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind NOT IN ('summary', 'weekly') \
AND status <> 'failed') \
OR EXISTS (SELECT 1 FROM analyses a JOIN synastries s ON s.id = a.synastry_id \
WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed') \
OR EXISTS (SELECT 1 FROM analyses a JOIN forecasts f ON f.id = a.forecast_id \
+1 -1
View File
@@ -43,7 +43,7 @@ pub const TAGS: [&str; 10] = [
"useful",
];
/// What can be rated (analysis kinds, and answers to questions).
const RATED_KINDS: [&str; 5] = ["summary", "natal", "synastry", "forecast", "tarot"];
const RATED_KINDS: [&str; 6] = ["summary", "natal", "synastry", "forecast", "tarot", "weekly"];
const MAX_COMMENT: usize = 1000;
const MAX_MESSAGE: usize = 2000;
const MAX_REPLY: usize = 4000;
+8 -1
View File
@@ -20,6 +20,7 @@ mod invitations;
mod invoices_user;
mod jobs;
mod models;
mod notifications;
pub(crate) mod payments;
mod promo;
mod prompts;
@@ -29,6 +30,7 @@ mod shares;
pub mod sky;
mod synastries;
mod tarot;
mod weekly;
pub use recalculate::run as recalculate;
@@ -36,7 +38,7 @@ use std::sync::Arc;
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::http::{HeaderValue, Method, header};
use axum::routing::{delete, get, patch, post};
use axum::routing::{delete, get, patch, post, put};
use axum::{Json, Router};
use axum_extra::extract::WithRejection;
use serde_json::{Value, json};
@@ -101,6 +103,9 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
.route("/v1/charts/{id}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart))
.route("/v1/charts/{id}/summary", post(analyses::summary_for_chart))
.route("/v1/weekly", post(weekly::current))
.route("/v1/weekly/email", put(weekly::set_email))
.route("/v1/weekly/history", get(weekly::history))
.route("/v1/charts/{id}/forecasts", get(forecasts::list_for_chart).post(forecasts::create))
.route("/v1/forecasts/{id}", get(forecasts::get_one))
.route("/v1/forecasts/{id}/analyses", get(analyses::list_for_forecast).post(analyses::request_for_forecast))
@@ -145,6 +150,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
.route("/v1/public/invites/{token}", get(synastries::public_invite))
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
.route("/v1/public/weekly/unsubscribe", post(weekly::unsubscribe))
.route("/v1/public/notifications", get(notifications::get_settings).put(notifications::put_settings))
.route("/v1/public/invitations/{token}", get(invitations::public_view))
.route("/v1/public/waitlist", post(invitations::join_waitlist))
.route("/v1/public/chart", post(calculator::chart))
@@ -0,0 +1,131 @@
//! The page of every e-mail setting, opened from an e-mail's footer with the
//! user's `email_token` (no login needed): Monday's weekly horoscope e-mail
//! and, for forum members, the forum's e-mails (the same settings as on the
//! forum profile). The e-mails that belong to something the user does
//! (password, purchase, invoice) always go, so they are not listed.
use axum::Json;
use axum::extract::{Query, State};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use uuid::Uuid;
use super::{Body, St};
use crate::AppState;
use crate::error::{ApiError, ApiResult};
#[derive(Deserialize)]
pub struct TokenQuery {
token: String,
}
async fn user_of(state: &AppState, token: &str) -> Result<Uuid, ApiError> {
let token = Uuid::parse_str(token.trim()).map_err(|_| ApiError::NotFound("token"))?;
let user: Option<Uuid> =
sqlx::query_scalar("SELECT id FROM users WHERE email_token = $1").bind(token).fetch_optional(&state.db).await?;
user.ok_or(ApiError::NotFound("token"))
}
type ForumRow = (String, String, String, String, String, bool, bool);
async fn settings(state: &AppState, user: Uuid) -> Result<Value, ApiError> {
let weekly: bool =
sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await?;
let forum: Option<ForumRow> = sqlx::query_as(
"SELECT email_replies, email_followed, email_messages, email_mentions, email_listener, email_weekly, listener \
FROM forum.members WHERE user_id = $1",
)
.bind(user)
.fetch_optional(&state.db)
.await?;
Ok(json!({
"weekly_horoscope": weekly,
"forum": forum.map(|(replies, followed, messages, mentions, listener_mail, weekly, listener)| json!({
"replies": replies,
"followed": followed,
"messages": messages,
"mentions": mentions,
// Only volunteer listeners get these.
"listener": listener.then_some(listener_mail),
"weekly": weekly,
})),
}))
}
pub async fn get_settings(
State(state): St,
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let user = user_of(&state, &q.token).await?;
Ok(Json(settings(&state, user).await?))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Settings {
weekly_horoscope: bool,
#[serde(default)]
forum: Option<ForumSettings>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ForumSettings {
replies: String,
followed: String,
messages: String,
mentions: String,
#[serde(default)]
listener: Option<String>,
weekly: bool,
}
fn one_of(value: &str, allowed: &[&str], what: &str) -> Result<(), ApiError> {
if allowed.contains(&value) {
Ok(())
} else {
Err(ApiError::BadRequest(format!("{what} must be one of {}", allowed.join(", "))))
}
}
pub async fn put_settings(
State(state): St,
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
WithRejection(Json(req), _): Body<Settings>,
) -> ApiResult<Json<Value>> {
let user = user_of(&state, &q.token).await?;
if let Some(f) = &req.forum {
one_of(&f.replies, &["off", "daily", "instant"], "replies")?;
one_of(&f.followed, &["off", "daily"], "followed")?;
one_of(&f.messages, &["off", "instant"], "messages")?;
one_of(&f.mentions, &["off", "instant"], "mentions")?;
if let Some(l) = &f.listener {
one_of(l, &["off", "instant"], "listener")?;
}
}
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE users SET weekly_email = $2, updated_at = now() WHERE id = $1")
.bind(user)
.bind(req.weekly_horoscope)
.execute(&mut *tx)
.await?;
if let Some(f) = &req.forum {
sqlx::query(
"UPDATE forum.members SET email_replies = $2, email_followed = $3, email_messages = $4, \
email_mentions = $5, email_listener = coalesce($6, email_listener), email_weekly = $7 \
WHERE user_id = $1",
)
.bind(user)
.bind(&f.replies)
.bind(&f.followed)
.bind(&f.messages)
.bind(&f.mentions)
.bind(&f.listener)
.bind(f.weekly)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(Json(settings(&state, user).await?))
}
+227
View File
@@ -0,0 +1,227 @@
//! The free weekly horoscope of the member's own chart: the week's sky (from
//! the horoscope service, stored per chart and week in `weekly_skies`) and its
//! text (an analysis of kind `weekly`, written by the summary's model). It is
//! asked for when the weekly horoscope page opens, so it is only written for
//! those who look; Monday's e-mail (worker; on unless turned off) says no
//! more than that it is there. The page shows one month at a time, the
//! newest week first ([`history`]).
//!
//! Weeks run from Monday to Sunday, Hungarian time.
use axum::Json;
use axum::extract::{Query, State};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use time::Date;
use uuid::Uuid;
use super::analyses::{ANALYSIS_COLUMNS, AnalysisRow, Target, queue};
use super::charts::{ChartRow, owned_chart};
use super::{Body, St};
use crate::AppState;
use crate::auth::AuthUser;
use crate::error::{ApiError, ApiResult};
/// The Monday of the current week in Hungary.
const THIS_MONDAY: &str = "SELECT date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date";
/// What a weekly text is about, for its cache key: the chart and the week.
pub fn target_hash(chart_hash: &str, week_start: &str) -> String {
format!("{chart_hash}|week|{week_start}")
}
/// The week's sky on the chart, calculated once per chart, birth data and week.
async fn ensure_sky(state: &AppState, chart: &ChartRow, week: Date) -> Result<(), ApiError> {
let (exists,): (bool,) = sqlx::query_as(
"SELECT EXISTS (SELECT 1 FROM weekly_skies WHERE chart_id = $1 AND chart_hash = $2 AND week_start = $3)",
)
.bind(chart.id)
.bind(&chart.chart_hash)
.bind(week)
.fetch_one(&state.db)
.await?;
if exists {
return Ok(());
}
let mut result = state.horoscope.week(&json!({ "birth": chart.birth_data, "start": week.to_string() })).await?;
if let Some(obj) = result.as_object_mut() {
obj.remove("meta");
}
sqlx::query(
"INSERT INTO weekly_skies (chart_id, chart_hash, week_start, result) VALUES ($1, $2, $3, $4) \
ON CONFLICT DO NOTHING",
)
.bind(chart.id)
.bind(&chart.chart_hash)
.bind(week)
.bind(&result)
.execute(&state.db)
.await?;
Ok(())
}
async fn weekly_email(state: &AppState, user: Uuid) -> Result<bool, sqlx::Error> {
sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await
}
/// This week's horoscope of the own chart: queued if it does not exist yet
/// (or the last attempt failed); the page polls this until it is written.
pub async fn current(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let chart_id: Option<Uuid> = sqlx::query_scalar("SELECT id FROM charts WHERE owner_id = $1 AND is_primary")
.bind(auth.id())
.fetch_optional(&state.db)
.await?;
let chart = owned_chart(&state.db, chart_id.ok_or(ApiError::NotFound("chart"))?, auth.id()).await?;
let week: Date = sqlx::query_scalar(THIS_MONDAY).fetch_one(&state.db).await?;
ensure_sky(&state, &chart, week).await?;
let target = Target::Weekly {
chart_id: chart.id,
hash: target_hash(&chart.chart_hash, &week.to_string()),
week_start: week,
};
let (_, row) = queue(&state, auth.id(), &target, &auth.user.locale, None).await?;
let end = week.saturating_add(time::Duration::days(6));
Ok(Json(json!({
"week_start": week.to_string(),
"week_end": end.to_string(),
"analysis": row.view(),
"email": weekly_email(&state, auth.id()).await?,
})))
}
/// "2026-11".
fn month_key(date: Date) -> String {
format!("{:04}-{:02}", date.year(), u8::from(date.month()))
}
/// The first day of a "2026-11" month.
fn month_start(key: &str) -> Option<Date> {
let (y, m) = key.split_once('-')?;
let month = time::Month::try_from(m.parse::<u8>().ok()?).ok()?;
Date::from_calendar_date(y.parse().ok()?, month, 1).ok()
}
fn next_month(first: Date) -> Date {
let (y, m) = (first.year(), first.month());
let y = if m == time::Month::December { y + 1 } else { y };
Date::from_calendar_date(y, m.next(), 1).expect("the first of a month")
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MonthQuery {
/// "2026-11"; this month by default.
month: Option<String>,
}
/// One month of the member's weekly horoscopes (weeks counted by their
/// Monday), the newest first, and the months before and after that have any.
/// Only weeks the member opened have a text.
pub async fn history(
State(state): St,
auth: AuthUser,
WithRejection(Query(q), _): WithRejection<Query<MonthQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let this_week: Date = sqlx::query_scalar(THIS_MONDAY).fetch_one(&state.db).await?;
let current = month_start(&month_key(this_week)).expect("a valid month");
let first = match q.month.as_deref() {
Some(m) => month_start(m).ok_or_else(|| ApiError::BadRequest("month must look like 2026-11".into()))?,
None => current,
}
.min(current);
let next = next_month(first);
// Every own chart counts: the birth data may have changed meanwhile.
const MINE: &str = "kind = 'weekly' AND chart_id IN (SELECT id FROM charts WHERE owner_id = $1 AND kind = 'own')";
let rows: Vec<AnalysisRow> = sqlx::query_as(&format!(
"SELECT DISTINCT ON (week_start) {ANALYSIS_COLUMNS} FROM analyses \
WHERE {MINE} AND week_start >= $2 AND week_start < $3 \
ORDER BY week_start DESC, (status = 'done') DESC, created_at DESC"
))
.bind(auth.id())
.bind(first)
.bind(next)
.fetch_all(&state.db)
.await?;
let (older, newer): (Option<Date>, Option<Date>) = sqlx::query_as(&format!(
"SELECT (SELECT max(week_start) FROM analyses WHERE {MINE} AND week_start < $2), \
(SELECT min(week_start) FROM analyses WHERE {MINE} AND week_start >= $3)"
))
.bind(auth.id())
.bind(first)
.bind(next)
.fetch_one(&state.db)
.await?;
// This month always has a page (its week is written when it opens).
let newer = newer.map(month_key).or_else(|| (first < current).then(|| month_key(current)));
let weeks: Vec<Value> = rows
.iter()
.filter_map(|r| {
let start = r.week_start?;
Some(json!({
"week_start": start.to_string(),
"week_end": start.saturating_add(time::Duration::days(6)).to_string(),
"analysis": r.view(),
}))
})
.collect();
Ok(Json(json!({
"month": month_key(first),
"current_month": month_key(current),
"this_week": this_week.to_string(),
"weeks": weeks,
"older": older.map(month_key),
"newer": newer,
"email": weekly_email(&state, auth.id()).await?,
})))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EmailSwitch {
on: bool,
}
/// Turns Monday's e-mail on or off. Turned on, the first one comes next
/// Monday (this week's horoscope is already in front of the member).
pub async fn set_email(
State(state): St,
auth: AuthUser,
WithRejection(Json(req), _): Body<EmailSwitch>,
) -> ApiResult<Json<Value>> {
sqlx::query(&format!(
"UPDATE users SET weekly_email = $2, \
weekly_email_sent_on = CASE WHEN $2 THEN greatest(weekly_email_sent_on, ({THIS_MONDAY})) \
ELSE weekly_email_sent_on END, \
updated_at = now() \
WHERE id = $1"
))
.bind(auth.id())
.bind(req.on)
.execute(&state.db)
.await?;
Ok(Json(json!({ "email": req.on })))
}
#[derive(Deserialize)]
pub struct TokenQuery {
token: String,
}
/// "No more weekly horoscope e-mails", straight from the mail client's
/// unsubscribe button (RFC 8058 one-click POST); the footer link opens the
/// page of every e-mail setting ([`super::notifications`]). No login needed.
pub async fn unsubscribe(
State(state): St,
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let token = Uuid::parse_str(q.token.trim()).map_err(|_| ApiError::NotFound("token"))?;
let done = sqlx::query("UPDATE users SET weekly_email = false, updated_at = now() WHERE email_token = $1")
.bind(token)
.execute(&state.db)
.await?;
if done.rows_affected() == 0 {
return Err(ApiError::NotFound("token"));
}
Ok(Json(json!({ "unsubscribed": true })))
}
+148 -1
View File
@@ -90,6 +90,23 @@ async fn fake_forecast(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
)
}
/// Calls of the fake week endpoint (only `weekly_horoscope_of_the_own_chart` uses it).
static WEEK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
async fn fake_week(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
WEEK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let start = body["start"].as_str().unwrap_or("2026-11-30").to_string();
(
StatusCode::OK,
Json(json!({
"timezone": "Europe/Budapest",
"week": {"start": start, "end": "?", "contacts": [], "positions": [], "moon_sign": "leo",
"moon_ingresses": [], "ingresses": [], "lunations": [], "stations": []},
"meta": {}
})),
)
}
/// Calls of the fake sky endpoints (only `the_sky_is_shared_and_kept` uses them).
static SKY_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
@@ -254,6 +271,7 @@ async fn fake_services_with(s3: FakeS3) -> String {
)
.route("/v1/synastry", post(fake_synastry))
.route("/v1/forecast", post(fake_forecast))
.route("/v1/week", post(fake_week))
.route(
"/v1/sky",
get(|| async {
@@ -1107,7 +1125,7 @@ async fn export_and_delete_account(pool: PgPool) {
/// config and catalog, shared links, invitation pages, the waitlist and
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
/// logged-in user, so other apps cannot use them.
const PUBLIC_ROUTES: [&str; 24] = [
const PUBLIC_ROUTES: [&str; 26] = [
"/healthz",
// Stripe calls it; the signature proves it.
"/v1/payments/stripe/webhook",
@@ -1123,6 +1141,9 @@ const PUBLIC_ROUTES: [&str; 24] = [
"/v1/public/shares/{slug}/visit",
"/v1/public/invites/{token}",
"/v1/public/invitations/unsubscribe",
// The e-mail settings behind an e-mail's footer link: the token stands for the login.
"/v1/public/weekly/unsubscribe",
"/v1/public/notifications",
"/v1/public/invitations/{token}",
"/v1/public/waitlist",
// The public birth chart (limited per visitor address).
@@ -1957,6 +1978,132 @@ async fn invitation_only_signup(pool: PgPool) {
assert_eq!(app.outbox_url("admin@example.com", "invitation").await, "https://sorsfonalak.test/meghivo/minta");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn weekly_horoscope_of_the_own_chart(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let anna = app.register("anna@example.com", "Anna").await;
let bob = app.register("bob@example.com", "Bob").await;
// No own chart yet: nothing to write it from.
assert_eq!(app.call("POST", "/v1/weekly", Some(&bob), None).await.status, StatusCode::NOT_FOUND);
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
let calls = WEEK_CALLS.load(std::sync::atomic::Ordering::Relaxed);
let r = app.call("POST", "/v1/weekly", Some(&anna), None).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let parts: Vec<i32> = r.body["week_start"].as_str().unwrap().split('-').map(|p| p.parse().unwrap()).collect();
let month = time::Month::try_from(parts[1] as u8).unwrap();
let start = time::Date::from_calendar_date(parts[0], month, parts[2] as u8).unwrap();
assert_eq!(start.weekday(), time::Weekday::Monday);
assert_eq!(r.body["week_end"], start.saturating_add(time::Duration::days(6)).to_string());
let a = &r.body["analysis"];
assert_eq!((a["kind"].as_str(), a["status"].as_str()), (Some("weekly"), Some("pending")));
assert_eq!((a["chart_id"].as_str(), a["credits_charged"].as_i64()), (chart["id"].as_str(), Some(0)));
assert_eq!(a["week_start"], r.body["week_start"]);
// On by default.
assert_eq!(r.body["email"], true);
// Asked again: the same text, the sky calculated once.
let again = app.call("POST", "/v1/weekly", Some(&anna), None).await.body;
assert_eq!(again["analysis"]["id"], a["id"]);
assert_eq!(WEEK_CALLS.load(std::sync::atomic::Ordering::Relaxed), calls + 1);
// Written by the summary's model; not among the chart's analyses on its page, but listed.
let (weekly_model, summary_model): (String, String) = sqlx::query_as(
"SELECT w.model, s.model FROM analyses w JOIN analyses s ON s.chart_id = w.chart_id AND s.kind = 'summary' \
WHERE w.kind = 'weekly'",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(weekly_model, summary_model);
// The page: one month at a time, the newest week first; older months page back.
let month = app.get("/v1/weekly/history", Some(&anna)).await.body;
assert_eq!(month["month"], month["current_month"]);
assert_eq!(month["this_week"], r.body["week_start"]);
assert_eq!(month["weeks"].as_array().unwrap().len(), 1);
assert_eq!(month["weeks"][0]["analysis"]["id"], a["id"]);
assert_eq!((month["older"].is_null(), month["newer"].is_null()), (true, true));
let old_week = start.saturating_sub(time::Duration::days(35));
sqlx::query(
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, status, \
content, credits_charged, week_start) \
SELECT $1, 'weekly', c.id, c.owner_id, 'hu', 'm', 'v3', 'old', 'done', '{\"title\": \"Régi hét\"}', 0, $2 \
FROM charts c WHERE c.id = $3",
)
.bind(uuid::Uuid::now_v7())
.bind(old_week)
.bind(uuid::Uuid::parse_str(chart["id"].as_str().unwrap()).unwrap())
.execute(&pool)
.await
.unwrap();
let older_key = format!("{:04}-{:02}", old_week.year(), u8::from(old_week.month()));
let month = app.get("/v1/weekly/history", Some(&anna)).await.body;
assert_eq!(month["older"], older_key);
let back = app.get(&format!("/v1/weekly/history?month={older_key}"), Some(&anna)).await.body;
assert_eq!(back["weeks"][0]["analysis"]["content"]["title"], "Régi hét");
assert_eq!(back["weeks"][0]["week_start"], old_week.to_string());
assert_eq!(back["newer"], month["current_month"]);
// Not into the future; a bad month is refused; others see nothing of it.
assert_eq!(app.get("/v1/weekly/history?month=2999-01", Some(&anna)).await.body["month"], month["current_month"]);
assert_eq!(app.get("/v1/weekly/history?month=nope", Some(&anna)).await.status, StatusCode::BAD_REQUEST);
assert_eq!(app.get("/v1/weekly/history", Some(&bob)).await.body["weeks"], json!([]));
// Monday's e-mail: off and on again from the site.
let r = app.call("PUT", "/v1/weekly/email", Some(&anna), Some(json!({"on": false}))).await;
assert_eq!((r.status, &r.body["email"]), (StatusCode::OK, &json!(false)));
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["weekly_email"], false);
app.call("PUT", "/v1/weekly/email", Some(&anna), Some(json!({"on": true}))).await;
let (on, sent_on): (bool, Option<time::Date>) =
sqlx::query_as("SELECT weekly_email, weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
.fetch_one(&pool)
.await
.unwrap();
// Turned on again, the first one comes next Monday.
assert_eq!((on, sent_on), (true, Some(start)));
// The page of every e-mail setting, from the footer link (no login).
let (token,): (uuid::Uuid,) = sqlx::query_as("SELECT email_token FROM users WHERE email = 'anna@example.com'")
.fetch_one(&pool)
.await
.unwrap();
let page = format!("/v1/public/notifications?token={token}");
let r = app.get(&page, None).await;
assert_eq!((r.status, &r.body), (StatusCode::OK, &json!({"weekly_horoscope": true, "forum": null})));
assert_eq!(app.get("/v1/public/notifications?token=nope", None).await.status, StatusCode::NOT_FOUND);
assert_eq!(
app.get(&format!("/v1/public/notifications?token={}", uuid::Uuid::now_v7()), None).await.status,
StatusCode::NOT_FOUND
);
// A forum member sees the forum's e-mails too.
sqlx::query(
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar) \
SELECT id, 'Csillag', 'csillag', 'moon-gold' FROM users WHERE email = 'anna@example.com'",
)
.execute(&pool)
.await
.unwrap();
let r = app.get(&page, None).await.body;
assert_eq!(
r["forum"],
json!({"replies": "daily", "followed": "off", "messages": "instant", "mentions": "instant", "listener": null, "weekly": false})
);
let mut forum = r["forum"].clone();
forum["replies"] = json!("loud");
let bad = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true, "forum": forum}))).await;
assert_eq!(bad.status, StatusCode::BAD_REQUEST);
let off = json!({"replies": "off", "followed": "off", "messages": "off", "mentions": "off", "listener": null, "weekly": false});
let r = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": false, "forum": off}))).await;
assert_eq!((r.status, &r.body["weekly_horoscope"], &r.body["forum"]), (StatusCode::OK, &json!(false), &off));
// The mail client's one-click unsubscribe turns off the weekly e-mail only.
app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true}))).await;
let r = app.call("POST", &format!("/v1/public/weekly/unsubscribe?token={token}"), None, None).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(app.get(&page, None).await.body["weekly_horoscope"], false);
assert_eq!(
app.call("POST", "/v1/public/weekly/unsubscribe?token=nope", None, None).await.status,
StatusCode::NOT_FOUND
);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
+18 -5
View File
@@ -207,6 +207,17 @@ export default async function PrivacyPage() {
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
<td>Jogos érdek (6. cikk (1) f)</td>
</tr>
<tr>
<td>
Heti horoszkóp: a hét égboltja a saját képleteden, a belőle írt szöveg, és hogy kéred-e a hétfői
értesítő levelet
</td>
<td>
Az ingyenes heti horoszkóp; hétfőnként egy rövid levél, hogy itt az új (alapból küldjük, a levél
alján, a Heti horoszkóp oldalon vagy a Profil oldalon bármikor kikapcsolhatod)
</td>
<td>Szerződés teljesítése; a levélnél jogos érdek (6. cikk (1) f)</td>
</tr>
<tr>
<td>
Melyik oldalt nyitottad meg, honnan érkeztél, a böngésződ és az eszközöd típusa, az országod és az oldal
@@ -271,7 +282,8 @@ export default async function PrivacyPage() {
<p>
<strong>Mire használjuk:</strong> a fiókod létrehozására és arra, hogy belépéskor felismerjünk; az
e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed, elfogadták a meghívódat, vagy
válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted); a
válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted) és a
heti horoszkóp hétfői értesítőjéhez (ha nem kapcsoltad ki); a
nevedet a megjelenítéshez; a nyelvet az oldal és az elemzések nyelvéhez.
</p>
<p>
@@ -312,10 +324,11 @@ export default async function PrivacyPage() {
<section>
<h2>4. Az elemzések és a mesterséges intelligencia</h2>
<p>
A rövid összefoglalót, a részletes elemzéseket, a kártyajóslást és a kérdésekre adott válaszokat nagy nyelvi
modell (mesterséges intelligencia) írja. A modellhez a <strong>képlet csillagászati adatai</strong> jutnak
el (a bolygók jegye, foka, háza és fényszögei), kártyajóslásnál a kihúzott lapok, és ha kérdést teszel fel,
a kérdésed szövege. Nevet, e-mail-címet, születési dátumot, időpontot vagy helyet nem küldünk el. Kérjük, a
A rövid összefoglalót, a heti horoszkópot, a részletes elemzéseket, a kártyajóslást és a kérdésekre adott
válaszokat nagy nyelvi modell (mesterséges intelligencia) írja. A modellhez a{" "}
<strong>képlet csillagászati adatai</strong> jutnak el (a bolygók jegye, foka, háza és fényszögei), a heti
horoszkópnál a hét égboltja is (hol járnak a bolygók, és milyen fényszöget alkotnak a képleteddel),
kártyajóslásnál a kihúzott lapok, és ha kérdést teszel fel, a kérdésed szövege. Nevet, e-mail-címet, születési dátumot, időpontot vagy helyet nem küldünk el. Kérjük, a
kérdéseidbe se írj neveket vagy érzékeny adatot (például egészségügyi adatot). Az elemzés szórakoztató és
önismereti célú szöveg, nem minősül egészségügyi, pénzügyi, jogi vagy más szakmai tanácsnak.
</p>
@@ -12,6 +12,7 @@ const PAGE = 50;
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
const KINDS: Record<string, string> = {
summary: "összefoglaló",
weekly: "heti horoszkóp",
natal: "képletelemzés",
synastry: "kapcsolati",
forecast: "előrejelzés",
@@ -9,7 +9,11 @@ import type { CatalogModel, ModelFunction } from "@/lib/types";
import { RunningJobs } from "./RunningJobs";
const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = {
summary: { title: "Tömör összefoglaló", about: "Ingyenes, minden új képlethez magától elkészül. Olcsó, gyors modell elég." },
summary: {
title: "Tömör összefoglaló és heti horoszkóp",
about:
"Ingyenes: az összefoglaló minden új képlethez magától elkészül, a heti horoszkóp akkor, amikor a tag a héten megnyitja a képletét. Olcsó, gyors modell elég.",
},
analysis: {
title: "Elemzések és éves előrejelzés",
about: "Fizetős szövegek: részletes képletelemzés, kapcsolati elemzés és éves előrejelzés.",
@@ -7,6 +7,7 @@ import type { AdminJob } from "@/lib/types";
const KINDS: Record<AdminJob["kind"], string> = {
summary: "Összefoglaló",
weekly: "Heti horoszkóp",
natal: "Képletelemzés",
synastry: "Kapcsolati elemzés",
forecast: "Éves előrejelzés",
@@ -0,0 +1,214 @@
"use client";
import { useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
interface ForumMail {
replies: "off" | "daily" | "instant";
followed: "off" | "daily";
messages: "off" | "instant";
mentions: "off" | "instant";
/** Only for volunteer listeners. */
listener: "off" | "instant" | null;
weekly: boolean;
}
interface Settings {
weekly_horoscope: boolean;
forum: ForumMail | null;
}
/** Everything off: the weekly horoscope and every forum e-mail. */
function allOff(s: Settings): Settings {
return {
weekly_horoscope: false,
forum: s.forum
? {
replies: "off",
followed: "off",
messages: "off",
mentions: "off",
listener: s.forum.listener === null ? null : "off",
weekly: false,
}
: null,
};
}
/**
* The e-mail settings behind an e-mail's footer link: the token in the link
* stands for the login. Nothing changes until a button is pressed (mail
* providers' link scanners open every link).
*/
export function MailSettings({ token }: { token: string | null }) {
const [settings, setSettings] = useState<Settings | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState<string | null>(null);
const query = token ? `?token=${encodeURIComponent(token)}` : "";
useEffect(() => {
if (!token) return;
api<Settings>(`/public/notifications${query}`)
.then(setSettings)
.catch((e) => setLoadError(errorText(e)));
}, [token, query]);
if (!token) {
return (
<p className="msg msg-error" role="alert">
Hiányzik a link vége. Nyisd meg a teljes linket a levélből.
</p>
);
}
if (loadError) {
return (
<p className="msg msg-error" role="alert">
Ez a link nem érvényes. Nyisd meg a teljes linket a levélből, vagy lépj be, és a Profil oldalon állítsd be.
</p>
);
}
if (!settings) {
return <p className="muted">Betöltés…</p>;
}
async function save(next: Settings, done: string) {
setBusy(true);
setError(null);
setSaved(null);
try {
setSettings(await api<Settings>(`/public/notifications${query}`, { method: "PUT", body: next }));
setSaved(done);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
const forum = settings.forum;
const setForum = (patch: Partial<ForumMail>) => {
setSaved(null);
setSettings({ ...settings, forum: forum ? { ...forum, ...patch } : null });
};
return (
<div className="card field mail-settings" style={{ gap: 18 }}>
<fieldset className="mail-set">
<legend>Heti horoszkóp</legend>
<label className="check">
<input
type="checkbox"
checked={settings.weekly_horoscope}
onChange={(e) => {
setSaved(null);
setSettings({ ...settings, weekly_horoscope: e.target.checked });
}}
/>
<span>Hétfőnként szóljatok, ha itt az új heti horoszkópom</span>
</label>
</fieldset>
{forum && (
<fieldset className="mail-set">
<legend>Fórum</legend>
<label htmlFor="mail-replies">Ha valaki válaszol nekem (a szálamban vagy a hozzászólásomra)</label>
<select
id="mail-replies"
className="inp"
value={forum.replies}
onChange={(e) => setForum({ replies: e.target.value as ForumMail["replies"] })}
>
<option value="daily">Napi összesítőben, este</option>
<option value="instant">Azonnal (szálanként óránként legfeljebb egy levél)</option>
<option value="off">Ne küldjetek</option>
</select>
<label htmlFor="mail-followed">Új hozzászólás a követett szálaimban</label>
<select
id="mail-followed"
className="inp"
value={forum.followed}
onChange={(e) => setForum({ followed: e.target.value as ForumMail["followed"] })}
>
<option value="off">Ne küldjetek</option>
<option value="daily">Napi összesítőben, este</option>
</select>
<label htmlFor="mail-messages">Privát üzenet vagy beszélgetési kérés</label>
<select
id="mail-messages"
className="inp"
value={forum.messages}
onChange={(e) => setForum({ messages: e.target.value as ForumMail["messages"] })}
>
<option value="instant">Azonnal</option>
<option value="off">Ne küldjetek</option>
</select>
<label htmlFor="mail-mentions">Ha valaki megemlít</label>
<select
id="mail-mentions"
className="inp"
value={forum.mentions}
onChange={(e) => setForum({ mentions: e.target.value as ForumMail["mentions"] })}
>
<option value="instant">Azonnal</option>
<option value="off">Ne küldjetek</option>
</select>
{forum.listener !== null && (
<>
<label htmlFor="mail-listener">
Kísérőként: ha egy meghallgatást kérő szál két órája válasz nélkül vár
</label>
<select
id="mail-listener"
className="inp"
value={forum.listener}
onChange={(e) => setForum({ listener: e.target.value as "off" | "instant" })}
>
<option value="off">Ne küldjetek</option>
<option value="instant">Azonnal (hat óránként legfeljebb egy levél)</option>
</select>
</>
)}
<label className="check">
<input type="checkbox" checked={forum.weekly} onChange={(e) => setForum({ weekly: e.target.checked })} />
<span>Heti összefoglaló vasárnap este: a hét legélénkebb szálai</span>
</label>
</fieldset>
)}
<div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
<button
type="button"
className="btn btn-primary"
disabled={busy}
onClick={() => void save(settings, "Elmentettük a beállításaidat.")}
>
{busy ? "Mentés…" : "Mentés"}
</button>
<button
type="button"
className="btn"
disabled={busy}
onClick={() => void save(allOff(settings), "Leiratkoztál: ezekről nem küldünk több levelet.")}
>
Mindenről leiratkozom
</button>
</div>
{saved && (
<p className="msg msg-ok" role="status">
{saved}
</p>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<p className="hint" style={{ margin: 0 }}>
A jelszóval, a vásárlással és a számlával kapcsolatos leveleket ettől függetlenül megkapod.
</p>
</div>
);
}
@@ -0,0 +1,24 @@
import type { Metadata } from "next";
import { MailSettings } from "./MailSettings";
export const metadata: Metadata = { title: "Értesítések", robots: { index: false } };
/** Every e-mail setting, from the link in an e-mail's footer (no login needed). */
export default async function MailSettingsPage({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[]>>;
}) {
const raw = (await searchParams).token;
const token = Array.isArray(raw) ? raw[0] : raw;
return (
<main className="page" style={{ maxWidth: 640 }}>
<div className="page-head">
<h1>Értesítések</h1>
<p className="muted">Itt állíthatod be, miről kérsz levelet a Sorsfonalaktól.</p>
</div>
<MailSettings token={token ?? null} />
</main>
);
}
+23 -2
View File
@@ -1407,7 +1407,7 @@ span.tarot-fan-card { cursor: default; }
}
/* The ☰ menu: instead of the header's link rows where they no longer fit
on one line (logged out below 1240px; logged in below 1380px, with more
on one line (logged out below 1240px; logged in below 1520px, with more
links and the package). */
.mobile-menu { display: none; margin-left: auto; }
.mobile-menu-button {
@@ -1436,7 +1436,7 @@ span.tarot-fan-card { cursor: default; }
@media (max-width: 1500px) {
.site-header .pkg-pill-detail { display: none; }
}
@media (max-width: 1380px) {
@media (max-width: 1520px) {
.mobile-menu-app { display: block; }
.site-header .app-nav { display: none; }
.site-header .who { margin-left: auto; }
@@ -1858,3 +1858,24 @@ span.tarot-fan-card { cursor: default; }
}
.inapp-note p { margin: 0; color: var(--ink-2); }
.inapp-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
/* The weekly horoscope page (one month at a time) and its link on the chart page. */
.weekly-card { gap: 10px; }
.weekly-text p { margin: 0 0 10px; }
.weekly-text p:last-child { margin-bottom: 0; }
.weekly-pager { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 10px; }
.weekly-pager > :first-child { justify-self: start; }
.weekly-pager > :last-child { justify-self: end; }
.weekly-pager strong { font-family: var(--font-display); font-size: 22px; font-weight: 600; text-align: center; }
.weekly-teaser { display: flex; flex-direction: column; gap: 6px; text-decoration: none; color: var(--ink-2); border-color: rgba(217, 180, 106, 0.35); }
.weekly-teaser:hover { border-color: var(--gold); }
.weekly-teaser-more { color: var(--gold); font-weight: 500; }
@media (max-width: 480px) {
.weekly-pager { grid-template-columns: 1fr 1fr; }
.weekly-pager strong { grid-column: 1 / -1; grid-row: 1; }
}
/* The e-mail settings behind an e-mail's footer link. */
.mail-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; min-width: 0; }
.mail-set legend { font-family: var(--font-display); font-size: 20px; font-weight: 600; margin-bottom: 4px; }
.mail-set label:not(.check) { font-size: 14px; color: var(--ink-2); margin-top: 6px; }
@@ -0,0 +1,151 @@
"use client";
import Link from "next/link";
import { useEffect, useState } from "react";
import { MONTHS, WeekCard, WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
import { api, errorText } from "@/lib/api";
import type { Analysis } from "@/lib/types";
const POLL_MS = 3000;
const MAX_POLLS = 60;
interface Week {
week_start: string;
week_end: string;
analysis: Analysis;
}
interface Month {
month: string;
current_month: string;
this_week: string;
weeks: Week[];
older: string | null;
newer: string | null;
email: boolean;
}
/** "2026. november". */
function monthName(key: string): string {
const [y, m] = key.split("-").map(Number);
return `${y}. ${MONTHS[m - 1]}`;
}
/**
* One month of weekly horoscopes, the newest week first. In this month the
* week's horoscope is asked for first (queued if new), and polled until the
* worker has written it; meanwhile its card shows the waiting animation.
*/
export function WeeklyPage({ month, isAdmin }: { month: string | null; isAdmin: boolean }) {
const [data, setData] = useState<Month | null>(null);
const [error, setError] = useState<string | null>(null);
const [gaveUp, setGaveUp] = useState(false);
// Bumped when an admin has this week's text written again: polls anew.
const [round, setRound] = useState(0);
const query = month ? `?month=${month}` : "";
/** This week's horoscope into the list (it may not be there yet). */
const putWeek = (week: Week) =>
setData((d) => (d ? { ...d, weeks: [week, ...d.weeks.filter((w) => w.week_start !== week.week_start)] } : d));
useEffect(() => {
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let polls = 0;
const poll = async () => {
try {
const week = await api<Week & { email: boolean }>("/weekly", { method: "POST" });
if (stopped) return;
putWeek({ week_start: week.week_start, week_end: week.week_end, analysis: week.analysis });
if (week.analysis.status === "done") return;
} catch {
// try again on the next tick
}
if (++polls >= MAX_POLLS) return setGaveUp(true);
timer = setTimeout(poll, POLL_MS);
};
(async () => {
try {
const page = await api<Month>(`/weekly/history${query}`);
if (stopped) return;
setData(page);
if (page.month === page.current_month) await poll();
} catch (e) {
if (!stopped) setError(errorText(e));
}
})();
return () => {
stopped = true;
clearTimeout(timer);
};
}, [query, round]);
if (error) {
return (
<p className="msg msg-error" role="alert">
{error}
</p>
);
}
if (!data) {
return <p className="muted">Betöltés…</p>;
}
const restarted = (week: Week) => (a: Analysis) => {
setGaveUp(false);
setData((d) =>
d ? { ...d, weeks: d.weeks.map((w) => (w.week_start === week.week_start ? { ...w, analysis: a } : w)) } : d,
);
if (week.week_start === data.this_week) setRound((r) => r + 1);
};
const pager = (
<nav className="weekly-pager" aria-label="Hónapok">
{data.older ? (
<Link href={`/heti-horoszkop?honap=${data.older}`} className="btn btn-sm">
← Korábbi hónap
</Link>
) : (
<span />
)}
<strong>{monthName(data.month)}</strong>
{data.newer ? (
<Link
href={data.newer === data.current_month ? "/heti-horoszkop" : `/heti-horoszkop?honap=${data.newer}`}
className="btn btn-sm"
>
Újabb hónap →
</Link>
) : (
<span />
)}
</nav>
);
return (
<div className="field" style={{ gap: 18 }}>
{pager}
{data.weeks.length === 0 ? (
<p className="muted">Ebben a hónapban nem nézted meg a heti horoszkópodat.</p>
) : (
data.weeks.map((w) => (
<WeekCard
key={w.week_start}
start={w.week_start}
end={w.week_end}
analysis={w.analysis}
current={w.week_start === data.this_week}
gaveUp={w.week_start === data.this_week && gaveUp}
isAdmin={isAdmin}
onRestarted={restarted(w)}
/>
))
)}
{(data.older || data.newer) && data.weeks.length > 1 && pager}
<div className="card">
<WeeklyEmailSwitch initial={data.email} label="Hétfőnként szóljatok e-mailben, ha itt az új heti horoszkópom" />
</div>
</div>
);
}
@@ -0,0 +1,46 @@
import type { Metadata } from "next";
import Link from "next/link";
import { requireMe } from "@/lib/server";
import { WeeklyPage } from "./WeeklyPage";
export const metadata: Metadata = { title: "Heti horoszkóp" };
/**
* The member's weekly horoscopes, one month at a time, the newest first
* (`?honap=2026-11` pages back). This week's is written when the page opens.
*/
export default async function WeeklyHoroscopePage({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[]>>;
}) {
const me = await requireMe("/heti-horoszkop");
const raw = (await searchParams).honap;
const month = (Array.isArray(raw) ? raw[0] : raw) ?? null;
return (
<main className="page" style={{ maxWidth: 760 }}>
<div className="page-head">
<h1>Heti horoszkóp</h1>
<p className="muted">Hétfőnként új, a saját képletedből és a hét égboltjából.</p>
</div>
{me.primary_chart_id ? (
<WeeklyPage
key={month ?? "now"}
month={month && /^\d{4}-\d{2}$/.test(month) ? month : null}
isAdmin={me.user.roles.includes("admin")}
/>
) : (
<div className="card field" style={{ gap: 12 }}>
<p style={{ margin: 0 }}>A heti horoszkóphoz előbb add meg a születési adataidat.</p>
<div>
<Link href="/profil#birth" className="btn btn-primary">
Születési adatok megadása
</Link>
</div>
</div>
)}
</main>
);
}
@@ -87,6 +87,15 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
referralOpen={config?.referral_rewards ?? false}
referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
/>
{chart.id === me.primary_chart_id && (
<Link href="/heti-horoszkop" className="card weekly-teaser">
<span className="eyebrow">Heti horoszkóp</span>
<span>Hétfőnként új, a saját képletedből és a hét égboltjából.</span>
<span className="weekly-teaser-more">
Elolvasom a heti horoszkópomat<span aria-hidden="true"> →</span>
</span>
</Link>
)}
<BigThree chart={chart} />
{forumEnabled() && (
<div className="card ask-forum-card">
+11 -4
View File
@@ -124,6 +124,11 @@ const DATA: [string, string, string][] = [
"Security, troubleshooting, preventing abuse",
"Legitimate interest (Art. 6(1)(f))",
],
[
"Weekly horoscope: the week's sky on your own chart, the text written from it, and whether you want the Monday notice e-mail",
"The free weekly horoscope; a short e-mail on Mondays that the new one is there (sent by default; turn it off at any time in the e-mail's footer, on the Weekly horoscope page or on your Profile page)",
"Performance of the contract; for the e-mail, legitimate interest (Art. 6(1)(f))",
],
[
"Which page you opened, where you came from, your browser and device type, your country and how long the page took to load (visitor statistics)",
"Seeing how many people view each page and whether the site is fast enough",
@@ -234,7 +239,8 @@ export default async function PrivacyPolicyPage() {
<p>
<strong>How we use it:</strong> to create your account and recognise you when you sign in; your e-mail address
for service e-mails (for example when a reading is ready, an invitation was accepted, or someone replied on the
forum, when someone mentions you there, or the forum's weekly summary, if you asked for these); your name for
forum, when someone mentions you there, or the forum's weekly summary, if you asked for these) and for the
weekly horoscope's Monday notice (unless you turned it off); your name for
display;
your language for the language of the site and your readings.
</p>
@@ -276,10 +282,11 @@ export default async function PrivacyPolicyPage() {
<section>
<h2>4. Readings and artificial intelligence</h2>
<p>
The short summary, the detailed readings, tarot readings and the answers to your questions are written by a
large language model (artificial intelligence). The model receives the{" "}
The short summary, the weekly horoscope, the detailed readings, tarot readings and the answers to your
questions are written by a large language model (artificial intelligence). The model receives the{" "}
<strong>astronomical data of the chart</strong> (the signs, degrees, houses and aspects of the planets), for
a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail
the weekly horoscope also the week's sky (where the planets are and the aspects they make to your chart),
for a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail
address, birth date, time or place. Please do not write names or sensitive data (such as health data) into
your questions either. The readings are for entertainment and self-reflection and are not medical,
financial, legal or other professional advice.
+13
View File
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import Link from "next/link";
import { ROLE_LABELS, formatDate } from "@/lib/astro";
import { WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
import { backendGet, requireMe } from "@/lib/server";
import type { Chart } from "@/lib/types";
@@ -84,6 +85,18 @@ export default async function ProfilePage() {
/>
</section>
<section className="card" aria-labelledby="levelek-title" id="levelek">
<h2 id="levelek-title">Levelek</h2>
<WeeklyEmailSwitch
initial={me.weekly_email}
label="Heti horoszkóp: hétfőnként szólunk e-mailben, ha itt az új"
/>
<p className="hint" style={{ margin: 0 }}>
A levélben csak annyi áll, hogy elkészült; a horoszkópot belépés után a Heti horoszkóp oldalon olvashatod.
{!chart && " Ehhez előbb add meg a születési adataidat."}
</p>
</section>
<section className="card" aria-labelledby="adataim">
<h2 id="adataim">Adataim</h2>
<p className="muted">
@@ -3,6 +3,7 @@
export type NavIconName =
| "chart"
| "weekly"
| "persons"
| "compare"
| "tarot"
@@ -45,6 +46,13 @@ export function NavIcon({ name }: { name: NavIconName }) {
/>
</>
)}
{name === "weekly" && (
<>
<rect x="4" y="5" width="16" height="15" rx="2.2" />
<path d="M4 9.5h16M8.5 3v4M15.5 3v4" />
<path d="M12 12l.9 2 2.1.9-2.1.9-.9 2-.9-2-2.1-.9 2.1-.9z" 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" />
)}
@@ -148,11 +148,12 @@ const EXPLORE: NavItem[] = [
/**
* 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.
* Below 1520px 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: "/heti-horoszkop", label: "Heti horoszkóp", icon: "weekly" },
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
@@ -0,0 +1,155 @@
"use client";
import { useEffect, useState } from "react";
import { api, errorText } 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 { Paragraphs } from "./Rich";
export const MONTHS = [
"január",
"február",
"március",
"április",
"május",
"június",
"július",
"augusztus",
"szeptember",
"október",
"november",
"december",
];
/** "november 30. – december 6." or "december 7–13.". */
export function weekRange(start: string, end: string): string {
const [, m1, d1] = start.split("-").map(Number);
const [, m2, d2] = end.split("-").map(Number);
return m1 === m2 ? `${MONTHS[m1 - 1]} ${d1}–${d2}.` : `${MONTHS[m1 - 1]} ${d1}. – ${MONTHS[m2 - 1]} ${d2}.`;
}
/**
* Monday's e-mail about the weekly horoscope, on or off. Turned on, the first
* one comes next Monday.
*/
export function WeeklyEmailSwitch({ initial, label }: { initial: boolean; label: string }) {
const [on, setOn] = useState(initial);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => setOn(initial), [initial]);
async function toggle(next: boolean) {
setBusy(true);
setError(null);
setOn(next);
try {
await api("/weekly/email", { method: "PUT", body: { on: next } });
} catch (e) {
setOn(!next);
setError(errorText(e));
} finally {
setBusy(false);
}
}
return (
<div className="weekly-email">
<label className="check">
<input type="checkbox" checked={on} disabled={busy} onChange={(e) => void toggle(e.target.checked)} />
<span>{label}</span>
</label>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</div>
);
}
/**
* One week's horoscope: the text, or while the worker writes it the waiting
* animation (this week's, the page polls it), or a note when it failed.
*/
export function WeekCard({
start,
end,
analysis,
current = false,
gaveUp = false,
isAdmin = false,
onRestarted,
}: {
start: string;
end: string;
analysis: Analysis | null;
/** This week: marked, and it may still be written. */
current?: boolean;
/** The page stopped waiting for it. */
gaveUp?: boolean;
isAdmin?: boolean;
onRestarted?: (a: Analysis) => void;
}) {
const content = analysis?.status === "done" ? analysis.content : null;
const titleId = `week-${start}`;
return (
<article
className={current ? "card summary-card weekly-card weekly-current" : "card weekly-card"}
aria-labelledby={titleId}
aria-busy={!content && !gaveUp && analysis?.status !== "failed"}
>
<span className="eyebrow">
{weekRange(start, end)}
{current && " · ez a hét"}
</span>
{content ? (
<>
{isAdmin && analysis && onRestarted && (
<RegenerateButton<Analysis> url={`/admin/analyses/${analysis.id}/regenerate`} onStarted={onRestarted} />
)}
<h2 id={titleId} className="summary-title">
{content.title}
</h2>
<div className="summary-text weekly-text" lang={analysis?.language}>
<Paragraphs text={content.text ?? ""} />
</div>
{analysis && <RateContent analysisId={analysis.id} />}
</>
) : (
<>
<h2 id={titleId} className="sr-only">
Heti horoszkóp, {weekRange(start, end)}
</h2>
{gaveUp || analysis?.status === "failed" ? (
<p className="muted" role="status">
{current
? "A heti horoszkóp most nem készült el. Töltsd újra az oldalt egy kicsit később."
: "Ez a heti horoszkóp nem készült el."}
</p>
) : (
<>
<AnalysisLoading
compact
text="A heti horoszkópod készül, ez fél percig is eltarthat…"
since={analysis?.requested_at ?? analysis?.created_at}
/>
{analysis && (
<RetryNotice
status={analysis.status}
error={analysis.error}
nextAttemptAt={analysis.next_attempt_at}
isAdmin={isAdmin}
/>
)}
</>
)}
</>
)}
</article>
);
}
+1
View File
@@ -29,6 +29,7 @@ export const TAG_LABELS: Record<string, string> = {
export const KIND_LABELS: Record<string, string> = {
summary: "Rövid összefoglaló",
weekly: "Heti horoszkóp",
natal: "Képletelemzés",
synastry: "Kapcsolati elemzés",
forecast: "Éves előrejelzés",
+8 -2
View File
@@ -31,6 +31,8 @@ export interface Me {
nps_due: boolean;
/** Natal analyses earned by bringing new users through shared links. */
referral_rewards: { earned: number; limit: number };
/** Monday's e-mail about the weekly horoscope is on. */
weekly_email: boolean;
}
/** A package from the catalog (`GET /v1/packages`). */
@@ -258,7 +260,7 @@ export interface SynastryListItem {
export interface Analysis {
id: string;
kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity";
kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity" | "weekly";
status: "pending" | "running" | "done" | "failed";
model: string;
language: string;
@@ -272,6 +274,8 @@ export interface Analysis {
next_attempt_at?: string;
/** When the current text was asked for: the waiting page counts from here. */
requested_at?: string;
/** The Monday of a weekly horoscope. */
week_start?: string | null;
}
/** Admin: one failed attempt in the error log. */
@@ -325,7 +329,7 @@ export interface ModelFunction {
export interface AdminJob {
id: string;
type: "analysis" | "question";
kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity";
kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity" | "weekly";
status: "pending" | "running";
/** The model of the current attempt. */
model: string;
@@ -467,6 +471,8 @@ export interface AdminCelebrityRow {
export interface AnalysisContent {
title?: string;
summary?: string;
/** The weekly horoscope's paragraphs. */
text?: string;
sections?: Record<string, { title: string; body: string }>;
strengths?: string[];
challenges?: string[];
+1
View File
@@ -16,6 +16,7 @@ mod sky;
mod synastry;
#[cfg(test)]
mod tests;
mod week;
use std::path::PathBuf;
use std::sync::Arc;
+13
View File
@@ -17,6 +17,7 @@ use crate::forecast::{self, ForecastRequest, ForecastResponse};
use crate::natal::{self, NatalRequest, NatalResponse};
use crate::sky::{self, EventsQuery, EventsResponse, SkyQuery, SkyResponse};
use crate::synastry::{self, SynastryRequest, SynastryResponse};
use crate::week::{self, WeekRequest, WeekResponse};
type AppResult<T> = Result<Json<T>, ApiError>;
@@ -30,6 +31,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/natal", post(natal_chart))
.route("/v1/synastry", post(synastry_chart))
.route("/v1/forecast", post(forecast_year))
.route("/v1/week", post(week_of_chart))
.route("/v1/sky", get(sky_now))
.route("/v1/sky/events", get(sky_events))
.layer(cors())
@@ -167,6 +169,17 @@ async fn forecast_year(
Ok(Json(response))
}
async fn week_of_chart(
State(state): State<Arc<AppState>>,
body: Result<Json<WeekRequest>, JsonRejection>,
) -> AppResult<WeekResponse> {
let Json(request) = body?;
let response = tokio::task::spawn_blocking(move || week::calculate(&state, request))
.await
.map_err(|e| ApiError::Internal(e.to_string()))??;
Ok(Json(response))
}
async fn sky_now(
State(state): State<Arc<AppState>>,
query: Result<Query<SkyQuery>, QueryRejection>,
+27
View File
@@ -319,6 +319,33 @@ async fn forecast_year_with_solar_return() {
assert_eq!(status, StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn one_week_of_a_chart() {
let birth = json!({"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"});
let (status, d) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-11-30"}))).await;
assert_eq!(status, StatusCode::OK, "{d}");
assert_eq!(d["timezone"], "Europe/Budapest");
let w = &d["week"];
assert_eq!((w["start"].as_str(), w["end"].as_str()), (Some("2026-11-30"), Some("2026-12-06")));
assert_eq!(w["positions"].as_array().unwrap().len(), 9);
assert!(w["positions"][0]["house"].as_u64().is_some());
assert!(!w["moon_ingresses"].as_array().unwrap().is_empty());
// Unknown birth time: no houses.
let (status, u) = call(
"POST",
"/v1/week",
Some(json!({"birth": {"date": "1985-07-14", "country": "HU", "place": "Budapest"}, "start": "2026-11-30"})),
)
.await;
assert_eq!(status, StatusCode::OK, "{u}");
assert!(u["week"]["positions"][0]["house"].is_null());
// Not a Monday.
let (status, _) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-12-01"}))).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn sky_at_a_moment() {
// 2026-03-10 12:00 UTC: Mercury retrograde (26 Feb – 20 Mar), waning Moon.
+63
View File
@@ -0,0 +1,63 @@
//! `POST /v1/week`: one week of a natal chart, for the weekly horoscope: the
//! planets' aspects to the natal points (with the day each is exact), where
//! the planets stand, the Moon's sign changes, the lunar phases, and the
//! planets' stations and sign changes. The week runs from Monday 0:00 to the
//! next Monday on the clock of `tz` (default Europe/Budapest); the dates are
//! local days there.
use astro_engine::{Week, calculate_week};
use jiff::civil::Date;
use serde::{Deserialize, Serialize};
use crate::AppState;
use crate::error::ApiError;
use crate::natal::{self, NatalRequest};
use crate::sky::DEFAULT_TZ;
const UNIX_EPOCH_JD: f64 = 2_440_587.5;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WeekRequest {
/// Birth data as for `POST /v1/natal`.
pub birth: NatalRequest,
/// The Monday the week starts on, `YYYY-MM-DD`.
pub start: String,
#[serde(default)]
pub tz: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct WeekResponse {
pub timezone: String,
pub week: Week,
}
fn bad(msg: impl Into<String>) -> ApiError {
ApiError::BadRequest(msg.into())
}
pub fn calculate(state: &AppState, req: WeekRequest) -> Result<WeekResponse, ApiError> {
let start: Date = req.start.parse().map_err(|_| bad("start must be a date (YYYY-MM-DD)"))?;
if start.weekday() != jiff::civil::Weekday::Monday {
return Err(bad("start must be a Monday"));
}
if !(1900..=2100).contains(&start.year()) {
return Err(bad("start must be between 1900 and 2100"));
}
let zone_name = req.tz.unwrap_or_else(|| DEFAULT_TZ.to_string());
let tz = state.atlas.zones.get(&zone_name)?;
let natal = natal::calculate(state, req.birth).map_err(|e| e.for_person("birth"))?;
let jd_at = |date: Date| -> Result<(f64, f64), ApiError> {
let zoned = date.to_zoned(tz.clone()).map_err(|e| ApiError::Internal(e.to_string()))?;
let jd = zoned.timestamp().as_second() as f64 / 86_400.0 + UNIX_EPOCH_JD;
Ok((jd, f64::from(zoned.offset().seconds()) / 3600.0))
};
let (start_jd, offset) = jd_at(start)?;
let next = start.checked_add(jiff::Span::new().days(7)).map_err(|e| ApiError::Internal(e.to_string()))?;
let (end_jd, _) = jd_at(next)?;
let week = calculate_week(state.engine.as_ref(), &natal.chart, start_jd, end_jd, offset)
.map_err(|e| ApiError::Calculation(e.to_string()))?;
Ok(WeekResponse { timezone: zone_name, week })
}
+143
View File
@@ -583,6 +583,149 @@ fn aspect_lines(out: &mut String, aspects: &Value, heading: &str, limit: usize)
}
}
/// "Wednesday 2026-12-02": a local day with its weekday (the text names days by weekday).
fn day(date: &str) -> String {
let mut parts = date.splitn(3, '-').map(str::parse::<i32>);
let weekday = match (parts.next(), parts.next(), parts.next()) {
(Some(Ok(y)), Some(Ok(m)), Some(Ok(d))) => u8::try_from(m)
.ok()
.and_then(|m| time::Month::try_from(m).ok())
.and_then(|m| time::Date::from_calendar_date(y, m, u8::try_from(d).ok()?).ok())
.map(|d| d.weekday().to_string()),
_ => None,
};
weekday.map_or_else(|| date.to_string(), |w| format!("{w} {date}"))
}
/// ", natal house 5" when the house is known.
fn house_suffix(v: &Value) -> String {
v["house"].as_i64().map(|h| format!(", natal house {h}")).unwrap_or_default()
}
/// One week of a chart: the natal chart, then the stored week sky of the
/// horoscope service (`POST /v1/week`): where the planets stand, their
/// aspects to the natal points, the Moon's signs, lunar phases, stations and
/// sign changes.
pub fn weekly(chart: &Value, result: &Value) -> String {
let w = &result["week"];
let mut out = format!(
"WEEK: {} to {} (local days, Hungarian time).\n\n",
day(w["start"].as_str().unwrap_or("?")),
day(w["end"].as_str().unwrap_or("?"))
);
out.push_str(&natal(chart));
out.push_str("\nTHE WEEK'S SKY ON THIS CHART\n\nPlanets at the start of the week:\n");
for p in w["positions"].as_array().into_iter().flatten() {
let retro = if p["retrograde"].as_bool() == Some(true) { ", retrograde" } else { "" };
let _ = writeln!(
out,
"- {}: {}{retro}{}",
point_name(p["planet"].as_str().unwrap_or("?")),
position(p),
house_suffix(p)
);
}
out.push_str("\nTransits to the natal chart this week (orb 1°; in order of their peak):\n");
let contacts = w["contacts"].as_array().map(Vec::as_slice).unwrap_or_default();
if contacts.is_empty() {
out.push_str("- none\n");
}
for c in contacts {
let planet = c["planet"].as_str().unwrap_or("?");
let slow = ["jupiter", "saturn", "uranus", "neptune", "pluto"].contains(&planet);
let mut line = format!(
"- {} {} natal {} ({}{})",
point_name(planet),
words(c["aspect"].as_str().unwrap_or("?")),
point_name(c["natal_point"].as_str().unwrap_or("?")),
c["nature"].as_str().unwrap_or("neutral"),
if slow { ", slow planet: background of the week" } else { "" }
);
let exact: Vec<String> = c["exact"]
.as_array()
.into_iter()
.flatten()
.map(|e| {
let d = day(e["date"].as_str().unwrap_or("?"));
if e["retrograde"].as_bool() == Some(true) { format!("{d} (retrograde)") } else { d }
})
.collect();
if exact.is_empty() {
let _ = write!(
line,
": not exact this week, closest {:.1}° around {}",
c["min_orb"].as_f64().unwrap_or(0.0),
day(c["peak"].as_str().unwrap_or("?"))
);
} else {
let _ = write!(line, ": exact on {}", exact.join(", "));
}
if let Some(h) = c["house"].as_i64() {
let _ = write!(line, "; {} in natal house {h}", point_name(planet));
}
let _ = writeln!(out, "{line}");
}
let mut moon =
format!("\nThe Moon: in {} at the start of the week", capitalize(w["moon_sign"].as_str().unwrap_or("?")));
for i in w["moon_ingresses"].as_array().into_iter().flatten() {
let _ = write!(
moon,
"; enters {} on {}{}",
capitalize(i["sign"].as_str().unwrap_or("?")),
day(i["date"].as_str().unwrap_or("?")),
house_suffix(i)
);
}
let _ = writeln!(out, "{moon}.");
let lunations = w["lunations"].as_array().map(Vec::as_slice).unwrap_or_default();
if !lunations.is_empty() {
out.push_str("Lunar phases:\n");
for l in lunations {
let _ = writeln!(
out,
"- {} on {} at {}{}",
capitalize(&words(l["kind"].as_str().unwrap_or("?"))),
day(l["date"].as_str().unwrap_or("?")),
position(l),
house_suffix(l)
);
}
}
let stations = w["stations"].as_array().map(Vec::as_slice).unwrap_or_default();
if !stations.is_empty() {
out.push_str("Stations:\n");
for st in stations {
let turn = if st["retrograde"].as_bool() == Some(true) { "turns retrograde" } else { "turns direct" };
let _ = writeln!(
out,
"- {} {turn} on {} at {}",
point_name(st["planet"].as_str().unwrap_or("?")),
day(st["date"].as_str().unwrap_or("?")),
position(st)
);
}
}
let ingresses = w["ingresses"].as_array().map(Vec::as_slice).unwrap_or_default();
if !ingresses.is_empty() {
out.push_str("Sign changes:\n");
for i in ingresses {
let _ = writeln!(
out,
"- {} enters {} on {}{}",
point_name(i["planet"].as_str().unwrap_or("?")),
capitalize(i["sign"].as_str().unwrap_or("?")),
day(i["date"].as_str().unwrap_or("?")),
house_suffix(i)
);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
+25 -5
View File
@@ -54,6 +54,8 @@ pub struct Job {
pub attempts: i32,
/// A tarot reading's spread, question and cards (kind `tarot`).
pub tarot: Option<Value>,
/// The Monday of a weekly horoscope (kind `weekly`).
pub week_start: Option<time::Date>,
/// The default model, when the chosen one is another (see the module docs).
pub fallback_model: Option<String>,
pub on_fallback: bool,
@@ -114,8 +116,8 @@ pub struct PreviewJob {
/// Which analyses a claim may take.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lane {
/// The short summary of a chart and the tarot readings (questions are
/// claimed separately).
/// The short summary of a chart, the weekly horoscope and the tarot
/// readings (questions are claimed separately).
Quick,
/// The detailed analyses (famous people's too) and the yearly forecast.
Slow,
@@ -124,7 +126,7 @@ pub enum Lane {
impl Lane {
fn kinds(self) -> &'static [&'static str] {
match self {
Lane::Quick => &["summary", "tarot"],
Lane::Quick => &["summary", "weekly", "tarot"],
Lane::Slow => &["natal", "synastry", "forecast", "celebrity"],
}
}
@@ -165,7 +167,7 @@ impl Analyzer {
AND kind = ANY($1) \
ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, prompt_version, attempts, \
tarot, fallback_model, on_fallback, started_at",
tarot, week_start, fallback_model, on_fallback, started_at",
)
.bind(lane.kinds())
.fetch_optional(&self.db)
@@ -190,6 +192,7 @@ impl Analyzer {
Kind::Celebrity => self.celebrity_text(job.chart_id, &job.language).await?,
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
Kind::Forecast => self.forecast_text(job.forecast_id).await?,
Kind::Weekly => self.weekly_text(job.chart_id, job.week_start).await?,
Kind::Question => return Err(LlmError::Permanent("a question is not an analysis".into())),
};
let (base, revision) = prompt::split_version(&job.prompt_version);
@@ -220,6 +223,21 @@ impl Analyzer {
Ok(compact::natal(&chart))
}
/// A chart with the sky of one week on it (stored by the backend).
async fn weekly_text(&self, chart_id: Option<Uuid>, week: Option<time::Date>) -> Result<String, LlmError> {
let row: Option<(Value, Value)> = sqlx::query_as(
"SELECT w.result, c.result FROM weekly_skies w JOIN charts c ON c.id = w.chart_id \
WHERE w.chart_id = $1 AND w.week_start = $2 AND w.chart_hash = c.chart_hash",
)
.bind(chart_id)
.bind(week)
.fetch_optional(&self.db)
.await
.map_err(|e| LlmError::Transient(format!("database: {e}")))?;
let (sky, chart) = row.ok_or_else(|| LlmError::Permanent("the week's sky is missing".into()))?;
Ok(compact::weekly(&chart, &sky))
}
/// A famous person's chart with their name in front.
async fn celebrity_text(&self, chart_id: Option<Uuid>, language: &str) -> Result<String, LlmError> {
let name: String = sqlx::query_scalar("SELECT name FROM celebrities WHERE chart_id = $1")
@@ -285,7 +303,9 @@ impl Analyzer {
Kind::Forecast => self.forecast_text(job.forecast_id).await?,
Kind::Natal | Kind::Summary => self.natal_text(job.chart_id).await?,
Kind::Celebrity => self.celebrity_text(job.chart_id, &job.language).await?,
Kind::Question => return Err(LlmError::Permanent("a question has no test run".into())),
Kind::Question | Kind::Weekly => {
return Err(LlmError::Permanent(format!("a {} text has no test run", job.kind)));
}
};
let built = prompt::build(kind, &job.language, &text, Some(&job.system));
let mut c = self.llm.complete(&job.model, &built).await?;
+15 -4
View File
@@ -20,13 +20,22 @@ pub struct Tasks {
pub notify: bool,
/// The forum's daily e-mail digest.
pub forum: bool,
/// Monday's e-mail about the weekly horoscope.
pub weekly: bool,
}
impl Tasks {
pub const ALL: Tasks =
Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true, forum: true };
const NONE: Tasks =
Tasks { email: false, cleanup: false, analyses: false, invoices: false, notify: false, forum: false };
Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true, forum: true, weekly: true };
const NONE: Tasks = Tasks {
email: false,
cleanup: false,
analyses: false,
invoices: false,
notify: false,
forum: false,
weekly: false,
};
pub fn parse(raw: &str) -> anyhow::Result<Self> {
let mut tasks = Self::NONE;
@@ -38,9 +47,11 @@ impl Tasks {
"invoices" => tasks.invoices = true,
"notify" => tasks.notify = true,
"forum" => tasks.forum = true,
"weekly" => tasks.weekly = true,
other => {
anyhow::bail!(
"unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify, forum)"
"unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify, forum, \
weekly)"
)
}
}
+12
View File
@@ -5,6 +5,7 @@
//! * hourly cleanup of expired sessions, tokens, invites and old e-mails
//! * writing the requested text analyses with an LLM (OpenRouter)
//! * issuing the invoices of the payments in Billingo
//! * Monday's e-mail about the weekly horoscope
//!
//! `WORKER_TASKS` (e.g. `email,cleanup` or `analyses`) picks the jobs of one
//! process, so they can run in separate containers; all of them by default.
@@ -25,6 +26,7 @@ mod invoices;
mod notify;
mod ses;
mod telegram;
mod weekly;
mod templates {
pub use email_templates::*;
}
@@ -108,6 +110,7 @@ async fn main() -> anyhow::Result<()> {
invoices = tasks.invoices,
notify = tasks.notify,
forum = tasks.forum,
weekly = tasks.weekly,
"worker tasks"
);
match &config.smtp_url {
@@ -179,6 +182,15 @@ async fn main() -> anyhow::Result<()> {
None => tracing::warn!("PUBLIC_BASE_URL is not set: no forum task (its e-mail links need it)"),
}
match &config.public_base_url {
_ if !tasks.weekly => {}
Some(base) => {
tracing::info!("weekly horoscope e-mails enabled (Mondays)");
jobs.spawn(weekly::run(pool.clone(), base.clone(), stop.clone()));
}
None => tracing::warn!("PUBLIC_BASE_URL is not set: no weekly horoscope e-mails (their links need it)"),
}
let app = Router::new().route("/healthz", get(healthz)).with_state(pool);
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
tracing::info!(%addr, "worker running");
+156 -2
View File
@@ -352,13 +352,30 @@ fn worker_tasks_are_chosen_by_name() {
let mail = Tasks::parse("email, cleanup").unwrap();
assert_eq!(
mail,
Tasks { email: true, cleanup: true, analyses: false, invoices: false, notify: false, forum: false }
Tasks {
email: true,
cleanup: true,
analyses: false,
invoices: false,
notify: false,
forum: false,
weekly: false
}
);
assert_eq!(
Tasks::parse("analyses").unwrap(),
Tasks { email: false, cleanup: false, analyses: true, invoices: false, notify: false, forum: false }
Tasks {
email: false,
cleanup: false,
analyses: true,
invoices: false,
notify: false,
forum: false,
weekly: false
}
);
assert!(Tasks::parse("email,forum").unwrap().forum);
assert!(Tasks::parse("email,forum,weekly").unwrap().weekly);
assert!(Tasks::parse("email,invoices").unwrap().invoices);
assert!(Tasks::parse("email,cleanup,invoices,notify").unwrap().notify);
assert!(Tasks::parse("emails").is_err());
@@ -1196,4 +1213,141 @@ mod analyses {
.unwrap();
assert_eq!((status.as_str(), refund.as_deref()), ("failed", Some("tarot")));
}
/// A week sky as the horoscope service returns it (shortened).
fn week_sky() -> Value {
json!({
"timezone": "Europe/Budapest",
"week": {
"start": "2026-11-30", "end": "2026-12-06",
"contacts": [
{"planet": "mars", "natal_point": "sun", "aspect": "square", "nature": "tense",
"exact": [{"date": "2026-12-02", "retrograde": false}], "peak": "2026-12-02", "min_orb": 0.0, "house": 10},
{"planet": "saturn", "natal_point": "moon", "aspect": "trine", "nature": "harmonious",
"exact": [], "peak": "2026-11-30", "min_orb": 0.4, "house": 2}
],
"positions": [
{"planet": "sun", "longitude": 247.8, "sign": "sagittarius", "degree_in_sign": 7.8, "retrograde": false, "house": 5}
],
"moon_sign": "leo",
"moon_ingresses": [{"date": "2026-12-01", "planet": "moon", "sign": "virgo", "house": 11}],
"ingresses": [],
"lunations": [{"date": "2026-12-01", "kind": "last_quarter", "longitude": 159.0, "sign": "virgo", "degree_in_sign": 9.0, "house": 11}],
"stations": []
}
})
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn writes_the_weekly_horoscope(db: PgPool) {
let s = setup(&db).await;
sqlx::query("INSERT INTO weekly_skies (chart_id, chart_hash, week_start, result) VALUES ($1, 'hash1', '2026-11-30', $2)")
.bind(s.chart)
.bind(week_sky())
.execute(&db)
.await
.unwrap();
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, \
credits_charged, week_start) \
VALUES ($1, 'weekly', $2, $3, 'hu', 'test/cheap', 'v3', 'key', 0, '2026-11-30')",
)
.bind(id)
.bind(s.chart)
.bind(s.user)
.execute(&db)
.await
.unwrap();
let text = json!({"title": "Lendület és türelem", "text": "Első bekezdés.\n\nMásodik.\n\nHarmadik."});
let (fake, url) = fake_openrouter(vec![reply(&text)]).await;
let a = analyzer(&db, &url);
// A quick text: the quick lane takes it.
let job = a.claim(Lane::Quick).await.unwrap().expect("the weekly horoscope is due");
a.handle(job).await;
let (status, content): (String, Option<Value>) =
sqlx::query_as("SELECT status, content FROM analyses WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
assert_eq!((status.as_str(), content.unwrap()["title"].as_str()), ("done", Some("Lendület és türelem")));
let requests = fake.requests.lock().unwrap();
let body = &requests[0];
assert_eq!(body["model"], "test/cheap");
assert_eq!(body["response_format"]["json_schema"]["name"], "weekly_horoscope");
let system = body["messages"][0]["content"].as_str().unwrap();
let user = body["messages"][1]["content"].as_str().unwrap();
assert!(system.contains("heti horoszkópot") && system.contains("a hét napjainak nevével"), "{system}");
for line in [
"WEEK: Monday 2026-11-30 to Sunday 2026-12-06",
"- Sun: Pisces 24°42', house 8",
"- Sun: Sagittarius 7°48', natal house 5",
"- Mars square natal Sun (tense): exact on Wednesday 2026-12-02; Mars in natal house 10",
"- Saturn trine natal Moon (harmonious, slow planet: background of the week): not exact this week, closest 0.4° around Monday 2026-11-30",
"The Moon: in Leo at the start of the week; enters Virgo on Tuesday 2026-12-01, natal house 11.",
"- Last quarter on Tuesday 2026-12-01 at Virgo 9°00', natal house 11",
"Most írd meg a heti horoszkópot.",
] {
assert!(user.contains(line), "missing {line:?} in\n{user}");
}
for secret in ["1990", "14:30", "Szeged", "Hungary"] {
assert!(!user.contains(secret), "{secret} leaked");
}
}
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn monday_weekly_horoscope_emails_go_once_a_week(db: PgPool) {
let monday = time::Date::from_calendar_date(2026, time::Month::November, 30).unwrap();
let mut ids = Vec::new();
for (email, chart, on) in
[("anna@example.com", true, true), ("bela@example.com", false, true), ("cili@example.com", true, false)]
{
let id = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email, display_name, weekly_email) VALUES ($1, $2, 'Anna', $3)")
.bind(id)
.bind(email)
.bind(on)
.execute(&db)
.await
.unwrap();
if chart {
sqlx::query(
"INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
VALUES ($1, $2, 'Saját', true, 'own', '{}', '{}', 'h')",
)
.bind(Uuid::now_v7())
.bind(id)
.execute(&db)
.await
.unwrap();
}
ids.push(id);
}
// On by default: a member of today gets it too.
let (default_on,): (bool,) =
sqlx::query_as("SELECT weekly_email FROM users WHERE email = 'anna@example.com'").fetch_one(&db).await.unwrap();
assert!(default_on);
// Only who has a chart and did not turn it off; once a week.
assert_eq!(crate::weekly::queue_week(&db, "https://sorsfonalak.test/", monday).await.unwrap(), 1);
assert_eq!(crate::weekly::queue_week(&db, "https://sorsfonalak.test", monday).await.unwrap(), 0);
let (to, template, payload, token): (String, String, serde_json::Value, Uuid) = sqlx::query_as(
"SELECT o.to_email, o.template, o.payload, u.email_token FROM email_outbox o JOIN users u ON u.id = o.user_id",
)
.fetch_one(&db)
.await
.unwrap();
assert_eq!((to.as_str(), template.as_str()), ("anna@example.com", "weekly_horoscope"));
assert_eq!(payload["url"], "https://sorsfonalak.test/heti-horoszkop");
assert_eq!(
(payload["week_start"].as_str(), payload["week_end"].as_str()),
(Some("2026-11-30"), Some("2026-12-06"))
);
assert_eq!(payload["unsubscribe_url"], format!("https://sorsfonalak.test/ertesitesek?token={token}"));
let mail = render(&template, "hu", &payload).unwrap();
assert_eq!(mail.subject, "Itt a heti horoszkópod");
assert!(mail.unsubscribe_post_url.unwrap().ends_with(&format!("/api/v1/public/weekly/unsubscribe?token={token}")));
// The next Monday again.
let next = monday.saturating_add(time::Duration::days(7));
assert_eq!(crate::weekly::queue_week(&db, "https://sorsfonalak.test", next).await.unwrap(), 1);
}
+71
View File
@@ -0,0 +1,71 @@
//! Monday's e-mail about the weekly horoscope: from 7:00 Hungarian time on
//! Mondays, every member with their own chart who has not turned it off
//! (`users.weekly_email`, on by default) gets one short notice with a link to
//! the weekly horoscope page. Its footer leads to the page of every e-mail setting. The text
//! itself is written when they open that page (the backend queues it), so the
//! e-mail says only that it is there. Once a week each (`weekly_email_sent_on`);
//! a Monday missed (the worker was down all day) is not made up later.
use std::time::Duration;
use sqlx::PgPool;
use tokio::sync::watch;
/// From this hour (Hungarian time) on Mondays.
const FROM_HOUR: i32 = 7;
/// How often the job looks.
const EVERY: Duration = Duration::from_secs(600);
pub async fn run(db: PgPool, base: String, stop: watch::Receiver<bool>) {
loop {
match send_due(&db, &base).await {
Ok(0) => {}
Ok(n) => tracing::info!(queued = n, "weekly horoscope e-mails queued"),
Err(e) => tracing::error!(error = %e, "queueing the weekly horoscope e-mails"),
}
tokio::select! {
() = tokio::time::sleep(EVERY) => {}
() = crate::stopped(stop.clone()) => break,
}
}
}
/// Queues this Monday's e-mails that are due; how many.
pub async fn send_due(db: &PgPool, base: &str) -> Result<u64, sqlx::Error> {
// Today in Hungary, if it is a Monday past the hour.
let monday: Option<time::Date> = sqlx::query_scalar(
"SELECT CASE WHEN extract(isodow FROM l) = 1 AND extract(hour FROM l) >= $1 THEN l::date END \
FROM (SELECT now() AT TIME ZONE 'Europe/Budapest' AS l) t",
)
.bind(FROM_HOUR)
.fetch_one(db)
.await?;
let Some(monday) = monday else { return Ok(0) };
queue_week(db, base, monday).await
}
/// Queues the e-mail of the week starting on `monday` for everyone who gets
/// it and has not had it yet (one statement: marking and queueing go together).
pub async fn queue_week(db: &PgPool, base: &str, monday: time::Date) -> Result<u64, sqlx::Error> {
let done = sqlx::query(
"WITH due AS ( \
UPDATE users u SET weekly_email_sent_on = $1 \
WHERE u.weekly_email AND (u.weekly_email_sent_on IS NULL OR u.weekly_email_sent_on < $1) \
AND EXISTS (SELECT 1 FROM charts c WHERE c.owner_id = u.id AND c.is_primary) \
RETURNING u.id, u.email, u.locale, u.display_name, u.email_token) \
INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) \
SELECT gen_random_uuid(), id, email, 'weekly_horoscope', locale, jsonb_build_object( \
'url', $2 || '/heti-horoszkop', \
'display_name', display_name, \
'week_start', $1::text, \
'week_end', ($1 + 6)::text, \
'unsubscribe_url', $2 || '/ertesitesek?token=' || email_token, \
'unsubscribe_post_url', $2 || '/api/v1/public/weekly/unsubscribe?token=' || email_token) \
FROM due",
)
.bind(monday)
.bind(base.trim_end_matches('/'))
.execute(db)
.await?;
Ok(done.rows_affected())
}