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;