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
+38 -28
View File
@@ -61,7 +61,7 @@ pub fn date_of(jd_ut: f64, offset_hours: f64) -> String {
}
/// The zodiac of the natal chart, geocentric (transits are not topocentric).
fn frame_of(natal: &NatalChart) -> Frame {
pub(crate) fn frame_of(natal: &NatalChart) -> Frame {
let o = natal.settings.options;
Frame { sidereal: (o.zodiac == ZodiacType::Sidereal).then_some(o.ayanamsa), topocentric: None }
}
@@ -70,7 +70,7 @@ fn natal_lon(natal: &NatalChart, id: PointId) -> Option<f64> {
natal.points.iter().find(|p| p.id == id).map(|p| p.position.longitude)
}
fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
pub(crate) fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
let houses = natal.houses.as_ref()?;
let mut cusps = [0.0; 12];
for (c, h) in cusps.iter_mut().zip(&houses.cusps) {
@@ -82,7 +82,7 @@ fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
/// The natal points transits and progressions are measured to: the ten
/// planets and, with a known birth time, the Ascendant and the Midheaven.
/// Without a birth time the Moon is left out (it may be 7° off).
fn natal_targets(natal: &NatalChart) -> Vec<(PointId, f64)> {
pub(crate) fn natal_targets(natal: &NatalChart) -> Vec<(PointId, f64)> {
let known = natal.angles.is_some();
let mut out: Vec<(PointId, f64)> = Body::PLANETS
.iter()
@@ -129,15 +129,15 @@ type Window = (f64, f64);
type Crossings = (Vec<Window>, Vec<(f64, bool)>);
/// Longitude and daily motion sampled at equal steps.
struct Samples {
pub(crate) struct Samples {
start: f64,
step: f64,
lon: Vec<f64>,
speed: Vec<f64>,
pub(crate) lon: Vec<f64>,
pub(crate) speed: Vec<f64>,
}
impl Samples {
fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
pub(crate) fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
let n = ((to - from) / step).ceil() as usize + 1;
let mut lon = Vec::with_capacity(n);
let mut speed = Vec::with_capacity(n);
@@ -149,7 +149,7 @@ impl Samples {
Ok(Self { start: from, step, lon, speed })
}
fn jd(&self, i: usize) -> f64 {
pub(crate) fn jd(&self, i: usize) -> f64 {
self.start + i as f64 * self.step
}
}
@@ -230,22 +230,30 @@ pub struct Contact {
#[serde(skip_serializing_if = "Option::is_none")]
pub house: Option<u8>,
#[serde(skip)]
peak_jd: f64,
pub(crate) peak_jd: f64,
}
/// One year of a natal chart.
struct Year<'a> {
engine: &'a dyn Ephemeris,
natal: &'a NatalChart,
frame: Frame,
start: f64,
end: f64,
offset: f64,
cusps: Option<[f64; 12]>,
/// What counts as a contact: the orb, the aspects, and whether the periods
/// within orb are listed.
pub(crate) struct ContactRule<'a> {
pub(crate) orb: f64,
pub(crate) aspects: &'a [AspectKind],
pub(crate) with_periods: bool,
}
/// One year of a natal chart (or any shorter span: see [`crate::week`]).
pub(crate) struct Year<'a> {
pub(crate) engine: &'a dyn Ephemeris,
pub(crate) natal: &'a NatalChart,
pub(crate) frame: Frame,
pub(crate) start: f64,
pub(crate) end: f64,
pub(crate) offset: f64,
pub(crate) cusps: Option<[f64; 12]>,
}
impl Year<'_> {
fn date(&self, jd: f64) -> String {
pub(crate) fn date(&self, jd: f64) -> String {
date_of(jd, self.offset)
}
@@ -254,17 +262,17 @@ impl Year<'_> {
}
/// Contacts of one moving planet (sampled in `s`) with the natal points.
fn contacts(
pub(crate) fn contacts(
&self,
planet: PointId,
s: &Samples,
lon_at: &dyn Fn(f64) -> Result<f64>,
targets: &[(PointId, f64)],
with_periods: bool,
rule: &ContactRule,
) -> Result<Vec<Contact>> {
let mut out = Vec::new();
for &(natal_point, natal) in targets {
for aspect in ASPECTS {
for &aspect in rule.aspects {
let a = aspect.angle();
let mut points = vec![natal + a];
if a != 0.0 && a != 180.0 {
@@ -272,7 +280,7 @@ impl Year<'_> {
}
let (mut windows, mut exact) = (Vec::new(), Vec::new());
for target in points {
let (w, e) = crossings(s, target, ORB, lon_at)?;
let (w, e) = crossings(s, target, rule.orb, lon_at)?;
windows.extend(w);
exact.extend(e);
}
@@ -289,7 +297,7 @@ impl Year<'_> {
.map(|i| (i, separation(s.lon[i], natal)))
.map(|(i, sep)| (i, (sep - a).abs()))
.min_by(|x, y| x.1.total_cmp(&y.1))
.unwrap_or((0, ORB));
.unwrap_or((0, rule.orb));
let (peak_jd, min_orb) = match exact.first() {
Some(&(jd, _)) => (jd, 0.0),
None => (s.jd(closest_i), closest),
@@ -301,7 +309,7 @@ impl Year<'_> {
aspect,
nature: aspect.nature(),
exact: exact.iter().map(|&(jd, retrograde)| Exact { date: self.date(jd), retrograde }).collect(),
periods: if with_periods {
periods: if rule.with_periods {
windows
.iter()
.map(|&(from, to)| DateRange { start: self.date(from), end: self.date(to) })
@@ -319,7 +327,7 @@ impl Year<'_> {
Ok(out)
}
fn position(&self, body: Body, jd: f64) -> Result<(f64, f64)> {
pub(crate) fn position(&self, body: Body, jd: f64) -> Result<(f64, f64)> {
let s = self.engine.position(body, jd, &self.frame)?;
Ok((s.longitude, s.speed_longitude))
}
@@ -333,7 +341,8 @@ impl Year<'_> {
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
let s = Samples::take(self.start - MARGIN_DAYS, self.end + MARGIN_DAYS, 1.0, &at)?;
let planet = PointId::from_planet(body);
contacts.extend(self.contacts(planet, &s, &lon_at, &targets, true)?);
let rule = ContactRule { orb: ORB, aspects: &ASPECTS, with_periods: true };
contacts.extend(self.contacts(planet, &s, &lon_at, &targets, &rule)?);
if let Some(cusps) = self.cusps {
houses.push(self.house_changes(planet, &s, &cusps));
}
@@ -378,7 +387,8 @@ impl Year<'_> {
// A progressed planet meeting its own natal place only matters for the Moon (the progressed lunar return).
let own: Vec<(PointId, f64)> =
targets.iter().copied().filter(|&(id, _)| id != planet || body == Body::Moon).collect();
contacts.extend(self.contacts(planet, &s, &lon_at, &own, false)?);
let rule = ContactRule { orb: ORB, aspects: &ASPECTS, with_periods: false };
contacts.extend(self.contacts(planet, &s, &lon_at, &own, &rule)?);
}
let start = ZodiacPosition::new(s.lon[0]);
let mut sign_changes = Vec::new();
+5 -2
View File
@@ -6,8 +6,9 @@
//! [`chart`] and is independent of the engine, so the engine can be replaced
//! without touching the chart logic. [`synastry`] compares two charts;
//! [`forecast`] looks at one year of a chart (solar return, transits,
//! progressions, profection, eclipses); [`sky`] is the sky by date, the same
//! for everyone (lunar phases, retrograde periods).
//! progressions, profection, eclipses); [`week`] is one week of a chart (the
//! weekly horoscope); [`sky`] is the sky by date, the same for everyone (lunar
//! phases, retrograde periods).
pub mod angle;
pub mod chart;
@@ -17,6 +18,7 @@ pub mod sky;
pub mod synastry;
pub mod time;
pub mod types;
pub mod week;
#[cfg(feature = "swisseph")]
pub mod swiss;
@@ -29,3 +31,4 @@ pub use engine::{
pub use forecast::{Forecast, calculate_forecast, solar_return};
pub use synastry::{Synastry, calculate_synastry};
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
pub use week::{Week, calculate_week};
+214
View File
@@ -0,0 +1,214 @@
//! One week of a natal chart, for the weekly horoscope: the planets' aspects
//! to the natal points during the week (with the day each is exact), where
//! the planets stand at the start, the Moon's sign changes, the main lunar
//! phases, and the planets' stations and sign changes.
//!
//! The aspects use the yearly forecast's machinery ([`crate::forecast`]) on a
//! seven-day span, with the Sun to Pluto as the moving planets (the Moon
//! would touch every natal point in a week, so only its signs are given).
//! Dates are calendar days at a fixed UTC offset given by the caller.
use serde::Serialize;
use crate::chart::{AspectKind, NatalChart, PointId, ZodiacPosition, house_of};
use crate::engine::{EngineError, Ephemeris};
use crate::forecast::{Contact, ContactRule, Samples, Year, cusps_of, frame_of, natal_targets};
use crate::sky::{LunationKind, RETROGRADING, lunations, moon_ingresses, stations};
use crate::types::{Body, ZodiacSign};
type Result<T> = std::result::Result<T, EngineError>;
/// The moving planets: everything but the Moon.
const MOVING: [Body; 9] = [
Body::Sun,
Body::Mercury,
Body::Venus,
Body::Mars,
Body::Jupiter,
Body::Saturn,
Body::Uranus,
Body::Neptune,
Body::Pluto,
];
/// The major aspects only: a week has room for the strong themes.
const ASPECTS: [AspectKind; 5] =
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
/// Orb of a contact, degrees: within it at some time during the week.
pub const WEEK_ORB: f64 = 1.0;
/// Sampling step, days (Mercury moves at most about 2° a day).
const STEP: f64 = 0.25;
/// Days sampled around the week, so a pass beginning before it is found whole.
const MARGIN_DAYS: f64 = 20.0;
/// A planet at the start of the week.
#[derive(Debug, Clone, Serialize)]
pub struct WeekPosition {
pub planet: PointId,
#[serde(flatten)]
pub position: ZodiacPosition,
pub retrograde: bool,
/// Natal house (birth time known).
#[serde(skip_serializing_if = "Option::is_none")]
pub house: Option<u8>,
}
/// A planet (or the Moon) entering a sign.
#[derive(Debug, Clone, Serialize)]
pub struct WeekIngress {
pub date: String,
pub planet: PointId,
pub sign: ZodiacSign,
#[serde(skip_serializing_if = "Option::is_none")]
pub house: Option<u8>,
}
/// A new moon, quarter or full moon.
#[derive(Debug, Clone, Serialize)]
pub struct WeekLunation {
pub date: String,
pub kind: LunationKind,
/// Where the Moon is.
#[serde(flatten)]
pub position: ZodiacPosition,
#[serde(skip_serializing_if = "Option::is_none")]
pub house: Option<u8>,
}
/// A planet standing still before turning retrograde or direct.
#[derive(Debug, Clone, Serialize)]
pub struct WeekStation {
pub date: String,
pub planet: PointId,
pub retrograde: bool,
#[serde(flatten)]
pub position: ZodiacPosition,
}
/// One week of a natal chart.
#[derive(Debug, Clone, Serialize)]
pub struct Week {
/// First and last day (Monday and Sunday).
pub start: String,
pub end: String,
/// The planets' aspects to the natal points, by their peak inside the week.
pub contacts: Vec<Contact>,
pub positions: Vec<WeekPosition>,
/// The Moon's sign at the start, and its sign changes.
pub moon_sign: ZodiacSign,
pub moon_ingresses: Vec<WeekIngress>,
/// The other planets' sign changes.
pub ingresses: Vec<WeekIngress>,
pub lunations: Vec<WeekLunation>,
pub stations: Vec<WeekStation>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// The week from `start_jd` (the first moment of Monday) to `end_jd` (the
/// first moment of the next Monday); dates are given at `offset_hours` from UTC.
pub fn calculate_week(
engine: &dyn Ephemeris,
natal: &NatalChart,
start_jd: f64,
end_jd: f64,
offset_hours: f64,
) -> Result<Week> {
if end_jd <= start_jd || end_jd - start_jd > 8.0 {
return Err(EngineError::Calculation("a week is at most eight days".into()));
}
let span = Year {
engine,
natal,
frame: frame_of(natal),
start: start_jd,
// The next Monday's first moment belongs to the next week.
end: end_jd - 1.0 / 86_400.0,
offset: offset_hours,
cusps: cusps_of(natal),
};
let house = |lon: f64| span.cusps.as_ref().map(|c| house_of(lon, c));
// The last day is the day before the next Monday.
let last_day = span.date(end_jd - 0.5 / 24.0);
let targets = natal_targets(natal);
let rule = ContactRule { orb: WEEK_ORB, aspects: &ASPECTS, with_periods: false };
let mut contacts = Vec::new();
let mut positions = Vec::new();
let mut ingresses = Vec::new();
for body in MOVING {
let at = |jd: f64| span.position(body, jd);
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
let s = Samples::take(start_jd - MARGIN_DAYS, end_jd + MARGIN_DAYS, STEP, &at)?;
let planet = PointId::from_planet(body);
contacts.extend(span.contacts(planet, &s, &lon_at, &targets, &rule)?);
let (lon, speed) = at(start_jd)?;
positions.push(WeekPosition {
planet,
position: ZodiacPosition::new(lon),
retrograde: speed < 0.0,
house: house(lon),
});
// Sign changes inside the week, to the sample (a few hours).
for i in 1..s.lon.len() {
let jd = s.jd(i);
if jd <= start_jd || jd > end_jd {
continue;
}
let sign = ZodiacSign::from_longitude(s.lon[i]);
if sign != ZodiacSign::from_longitude(s.lon[i - 1]) {
ingresses.push(WeekIngress { date: span.date(jd), planet, sign, house: house(s.lon[i]) });
}
}
}
contacts.sort_by(|a, b| a.peak_jd.total_cmp(&b.peak_jd));
let moon_start = span.position(Body::Moon, start_jd)?.0;
let moon_ingresses = moon_ingresses(engine, start_jd, end_jd)?
.into_iter()
.map(|(jd, sign)| {
let lon = span.position(Body::Moon, jd + 1.0 / 24.0).map(|(l, _)| l).unwrap_or(sign.index() as f64 * 30.0);
WeekIngress { date: span.date(jd), planet: PointId::Moon, sign, house: house(lon) }
})
.collect();
let lunations = lunations(engine, start_jd, end_jd)?
.into_iter()
.map(|l| WeekLunation {
date: span.date(l.jd_ut),
kind: l.kind,
position: ZodiacPosition::new(l.moon_longitude),
house: house(l.moon_longitude),
})
.collect();
let mut week_stations = Vec::new();
for body in RETROGRADING {
for st in stations(engine, body, start_jd, end_jd)? {
week_stations.push(WeekStation {
date: span.date(st.jd_ut),
planet: PointId::from_planet(body),
retrograde: st.retrograde,
position: ZodiacPosition::new(st.longitude),
});
}
}
week_stations.sort_by(|a, b| a.date.cmp(&b.date));
ingresses.sort_by(|a, b| a.date.cmp(&b.date));
let mut warnings = Vec::new();
if natal.angles.is_none() {
warnings
.push("Birth time unknown: no houses or angles, and the natal Moon is left out of the contacts.".into());
}
Ok(Week {
start: span.date(start_jd),
end: last_day,
contacts,
positions,
moon_sign: ZodiacSign::from_longitude(moon_start),
moon_ingresses,
ingresses,
lunations,
stations: week_stations,
warnings,
})
}
@@ -217,3 +217,37 @@ fn solar_return_and_forecast() {
assert!(f.eclipses.iter().any(|e| e.date == "2026-08-28"));
serde_json::to_string(&f).unwrap();
}
#[test]
fn one_week() {
use astro_engine::calculate_week;
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: true, options: ChartOptions::default() };
let natal = calculate_chart(engine(), &input).unwrap();
// Monday 30 November 2026, 0:00 in Budapest (UTC+1), to the next Monday.
let start = 2_461_374.5 - 1.0 / 24.0;
assert_eq!(astro_engine::forecast::date_of(start, 1.0), "2026-11-30");
let w = calculate_week(engine(), &natal, start, start + 7.0, 1.0).unwrap();
assert_eq!((w.start.as_str(), w.end.as_str()), ("2026-11-30", "2026-12-06"));
assert_eq!(w.positions.len(), 9);
assert!(w.positions.iter().all(|p| p.house.is_some()));
// Every contact is within orb during the week, with its peak and exact hits inside it.
assert!(!w.contacts.is_empty());
for c in &w.contacts {
assert!(c.min_orb <= 1.0, "{c:?}");
assert!(c.peak.as_str() >= w.start.as_str() && c.peak.as_str() <= w.end.as_str(), "{c:?}");
assert!(c.exact.iter().all(|e| e.date >= w.start && e.date <= w.end), "{c:?}");
assert_ne!(c.planet, astro_engine::chart::PointId::Moon);
}
// The Moon changes sign every two or three days, each time into the next sign.
assert!((2..=4).contains(&w.moon_ingresses.len()), "{:?}", w.moon_ingresses);
let mut sign = w.moon_sign;
for i in &w.moon_ingresses {
assert_eq!(i.sign.index(), (sign.index() + 1) % 12);
sign = i.sign;
}
// About one main lunar phase a week.
assert!((1..=2).contains(&w.lunations.len()), "{:?}", w.lunations);
let json = serde_json::to_value(&w).unwrap();
assert!(json["contacts"][0]["planet"].is_string());
assert!(json["positions"][0]["sign"].is_string());
}