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:
@@ -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::*;
|
||||
|
||||
@@ -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?;
|
||||
|
||||
@@ -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)"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
Reference in New Issue
Block a user