Weekly horoscope: its own page, a Monday e-mail, and one page for every e-mail setting
- 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:
@@ -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?,
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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?))
|
||||
}
|
||||
@@ -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 })))
|
||||
}
|
||||
Reference in New Issue
Block a user