diff --git a/crates/astro-engine/src/lib.rs b/crates/astro-engine/src/lib.rs index 499f0f0..d87df2e 100644 --- a/crates/astro-engine/src/lib.rs +++ b/crates/astro-engine/src/lib.rs @@ -6,12 +6,14 @@ //! [`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). +//! progressions, profection, eclipses); [`sky`] is the sky by date, the same +//! for everyone (lunar phases, retrograde periods). pub mod angle; pub mod chart; pub mod engine; pub mod forecast; +pub mod sky; pub mod synastry; pub mod time; pub mod types; diff --git a/crates/astro-engine/src/sky.rs b/crates/astro-engine/src/sky.rs new file mode 100644 index 0000000..82b6138 --- /dev/null +++ b/crates/astro-engine/src/sky.rs @@ -0,0 +1,265 @@ +//! The sky by date, the same for everyone (tropical, geocentric): the lunar +//! phases, the Moon's sign changes, the stations of the planets and their +//! retrograde periods with the shadows around them. Used by the public moon +//! and retrograde calendars and by the "today in the sky" card. +//! +//! Every event is found by sampling at a step shorter than the shortest gap +//! between two events of its kind, then bisecting to well under a second. + +use serde::Serialize; + +use crate::angle::normalize; +use crate::chart::{MoonPhaseName, phase_name}; +use crate::engine::{EngineError, Ephemeris, Frame}; +use crate::types::{Body, ZodiacSign}; + +type Result = std::result::Result; + +const FRAME: Frame = Frame::TROPICAL_GEOCENTRIC; + +/// The planets that turn retrograde (seen from the Earth, the Sun and the Moon never do). +pub const RETROGRADING: [Body; 8] = + [Body::Mercury, Body::Venus, Body::Mars, Body::Jupiter, Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto]; + +/// Days around a window scanned for stations, so that a retrograde period +/// (Pluto's is the longest, about 160 days) overlapping it is found whole. +const STATION_MARGIN: f64 = 200.0; +/// Bisection steps: a day halved 40 times is far below a second. +const BISECT_STEPS: usize = 40; + +/// Signed difference `a - b` in `[-180, 180)`. +fn diff(a: f64, b: f64) -> f64 { + (a - b + 180.0).rem_euclid(360.0) - 180.0 +} + +/// The moment in `[lo, hi]` where `f` turns from negative to non-negative. +fn bisect(mut lo: f64, mut hi: f64, f: impl Fn(f64) -> Result) -> Result { + for _ in 0..BISECT_STEPS { + let mid = (lo + hi) / 2.0; + if f(mid)? < 0.0 { + lo = mid; + } else { + hi = mid; + } + } + Ok((lo + hi) / 2.0) +} + +fn longitude(engine: &dyn Ephemeris, body: Body, jd: f64) -> Result { + Ok(engine.position(body, jd, &FRAME)?.longitude) +} + +fn speed(engine: &dyn Ephemeris, body: Body, jd: f64) -> Result { + Ok(engine.position(body, jd, &FRAME)?.speed_longitude) +} + +/// Moon minus Sun, `[0, 360)`. +fn elongation(engine: &dyn Ephemeris, jd: f64) -> Result { + Ok(normalize(longitude(engine, Body::Moon, jd)? - longitude(engine, Body::Sun, jd)?)) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LunationKind { + NewMoon, + FirstQuarter, + FullMoon, + LastQuarter, +} + +impl LunationKind { + const ALL: [LunationKind; 4] = + [LunationKind::NewMoon, LunationKind::FirstQuarter, LunationKind::FullMoon, LunationKind::LastQuarter]; +} + +/// A main lunar phase at its exact moment. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Lunation { + pub kind: LunationKind, + pub jd_ut: f64, + pub moon_longitude: f64, +} + +/// The new moons, quarters and full moons between two moments, in time order. +pub fn lunations(engine: &dyn Ephemeris, from: f64, to: f64) -> Result> { + // The elongation grows 11–15° a day: at half a day no quarter is skipped. + const STEP: f64 = 0.5; + let mut out = Vec::new(); + let mut t0 = from; + let mut q0 = (elongation(engine, t0)? / 90.0).floor() as usize % 4; + while t0 < to { + let t1 = (t0 + STEP).min(to); + let q1 = (elongation(engine, t1)? / 90.0).floor() as usize % 4; + if q1 != q0 { + let target = 90.0 * q1 as f64; + let jd = bisect(t0, t1, |t| Ok(diff(elongation(engine, t)?, target)))?; + out.push(Lunation { + kind: LunationKind::ALL[q1], + jd_ut: jd, + moon_longitude: longitude(engine, Body::Moon, jd)?, + }); + } + t0 = t1; + q0 = q1; + } + Ok(out) +} + +/// The moments the Moon enters a sign, with the sign entered, in time order. +pub fn moon_ingresses(engine: &dyn Ephemeris, from: f64, to: f64) -> Result> { + // The Moon moves 12–15° a day; a sign takes it two days or more. + const STEP: f64 = 0.25; + let mut out = Vec::new(); + let mut t0 = from; + let mut s0 = ZodiacSign::from_longitude(longitude(engine, Body::Moon, t0)?); + while t0 < to { + let t1 = (t0 + STEP).min(to); + let s1 = ZodiacSign::from_longitude(longitude(engine, Body::Moon, t1)?); + if s1 != s0 { + let target = 30.0 * s1.index() as f64; + let jd = bisect(t0, t1, |t| Ok(diff(longitude(engine, Body::Moon, t)?, target)))?; + out.push((jd, s1)); + } + t0 = t1; + s0 = s1; + } + Ok(out) +} + +/// A planet standing still before turning retrograde or direct. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Station { + pub body: Body, + pub jd_ut: f64, + pub longitude: f64, + /// Turns retrograde here (otherwise direct). + pub retrograde: bool, +} + +/// The stations of a planet between two moments, in time order. +pub fn stations(engine: &dyn Ephemeris, body: Body, from: f64, to: f64) -> Result> { + scan_stations(engine, body, from, to, usize::MAX) +} + +/// The first station of a planet after a moment, looking ahead at most `days`. +pub fn next_station(engine: &dyn Ephemeris, body: Body, jd: f64, days: f64) -> Result> { + Ok(scan_stations(engine, body, jd, jd + days, 1)?.into_iter().next()) +} + +/// At most `limit` stations, from the first one after `from`. +fn scan_stations(engine: &dyn Ephemeris, body: Body, from: f64, to: f64, limit: usize) -> Result> { + // Retrograde and direct runs last three weeks or more: two days skip none. + const STEP: f64 = 2.0; + let mut out = Vec::new(); + let mut t0 = from; + let mut v0 = speed(engine, body, t0)?; + while t0 < to { + let t1 = (t0 + STEP).min(to); + let v1 = speed(engine, body, t1)?; + if (v0 < 0.0) != (v1 < 0.0) { + let retrograde = v1 < 0.0; + // Bisect on a function that turns non-negative at the station. + let jd = bisect(t0, t1, |t| { + let v = speed(engine, body, t)?; + Ok(if retrograde { -v } else { v }) + })?; + out.push(Station { body, jd_ut: jd, longitude: longitude(engine, body, jd)?, retrograde }); + if out.len() >= limit { + break; + } + } + t0 = t1; + v0 = v1; + } + Ok(out) +} + +/// A retrograde period and its shadow: the stretch of the zodiac the planet +/// covers three times (forward, backward, forward again). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RetrogradePeriod { + pub body: Body, + pub station_retrograde: Station, + pub station_direct: Station, + /// The planet first reaches the degree where it will turn direct. + pub shadow_start: f64, + /// The planet gets back to the degree where it turned retrograde. + pub shadow_end: f64, +} + +/// The moment the planet, moving forward, reaches `target`: searched from +/// `from` backward (`dir` = -1) or forward (`dir` = 1) a day at a time. +fn reaches(engine: &dyn Ephemeris, body: Body, target: f64, from: f64, dir: f64) -> Result { + // f grows through zero as the planet passes the target moving forward. + let f = |t: f64| Ok(diff(longitude(engine, body, t)?, target)); + let mut a = from; + let mut fa = f(a)?; + for _ in 0..400 { + let b = a + dir; + let fb = f(b)?; + // A change of sign near the target (not across the opposite point). + if (fa < 0.0) != (fb < 0.0) && (fa - fb).abs() < 90.0 { + let (lo, hi) = if dir < 0.0 { (b, a) } else { (a, b) }; + return bisect(lo, hi, f); + } + (a, fa) = (b, fb); + } + Err(EngineError::Calculation(format!("{body:?} did not reach {target:.2}° in 400 days"))) +} + +/// The retrograde periods of a planet that overlap `[from, to]`, in time order. +pub fn retrograde_periods(engine: &dyn Ephemeris, body: Body, from: f64, to: f64) -> Result> { + let all = stations(engine, body, from - STATION_MARGIN, to + STATION_MARGIN)?; + let mut out = Vec::new(); + for pair in all.windows(2) { + let (r, d) = (pair[0], pair[1]); + if !r.retrograde || d.retrograde || d.jd_ut < from || r.jd_ut > to { + continue; + } + out.push(RetrogradePeriod { + body, + station_retrograde: r, + station_direct: d, + shadow_start: reaches(engine, body, d.longitude, r.jd_ut, -1.0)?, + shadow_end: reaches(engine, body, r.longitude, d.jd_ut, 1.0)?, + }); + } + Ok(out) +} + +/// The Moon at a moment: phase and sign. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MoonNow { + pub longitude: f64, + pub elongation: f64, + pub phase: MoonPhaseName, + pub illumination: f64, +} + +pub fn moon_now(engine: &dyn Ephemeris, jd: f64) -> Result { + let sun = longitude(engine, Body::Sun, jd)?; + let moon = longitude(engine, Body::Moon, jd)?; + Ok(MoonNow { + longitude: moon, + elongation: normalize(moon - sun), + phase: phase_name(sun, moon), + illumination: engine.illumination(Body::Moon, jd)?, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bisection_finds_the_crossing() { + let t = bisect(0.0, 1.0, |t| Ok(t - 0.3)).unwrap(); + assert!((t - 0.3).abs() < 1e-9); + } + + #[test] + fn signed_difference_wraps() { + assert_eq!(diff(5.0, 355.0), 10.0); + assert_eq!(diff(355.0, 5.0), -10.0); + } +} diff --git a/crates/astro-engine/tests/sky.rs b/crates/astro-engine/tests/sky.rs new file mode 100644 index 0000000..47a9443 --- /dev/null +++ b/crates/astro-engine/tests/sky.rs @@ -0,0 +1,152 @@ +//! The sky calendar against known 2026 events (stations checked with the +//! upstream `swetest`, eclipses from the published eclipse tables). +//! +//! Requires the ephemeris files from `scripts/fetch-deps.sh` (data/ephe). + +use std::path::PathBuf; +use std::sync::OnceLock; + +use astro_engine::sky::{LunationKind, lunations, moon_ingresses, next_station, retrograde_periods, stations}; +use astro_engine::swiss::SwissEphemeris; +use astro_engine::time::gregorian_from_jdn; +use astro_engine::{Body, Ephemeris, Frame, ZodiacSign}; + +fn engine() -> &'static SwissEphemeris { + static ENGINE: OnceLock = OnceLock::new(); + ENGINE.get_or_init(|| { + let dir = std::env::var_os("ASTRO_EPHE_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../data/ephe")); + SwissEphemeris::new(dir).expect("ephemeris files (run scripts/fetch-deps.sh)") + }) +} + +/// 0h UT of a calendar day. +fn jd(y: i32, m: i32, d: i32) -> f64 { + // Fliegel–Van Flandern, valid for Gregorian dates. + let a = (14 - m) / 12; + let (y2, m2) = (y + 4800 - a, m + 12 * a - 3); + let jdn = d + (153 * m2 + 2) / 5 + 365 * y2 + y2 / 4 - y2 / 100 + y2 / 400 - 32045; + f64::from(jdn) - 0.5 +} + +/// `YYYY-MM-DD` of a moment, UT. +fn day(jd_ut: f64) -> String { + let (y, m, d) = gregorian_from_jdn((jd_ut + 0.5).floor() as i64); + format!("{y:04}-{m:02}-{d:02}") +} + +#[test] +fn lunations_of_2026_include_the_eclipses() { + let all = lunations(engine(), jd(2026, 1, 1), jd(2027, 1, 1)).unwrap(); + // About 12.4 lunations a year, four phases each. + assert!((48..=51).contains(&all.len()), "{}", all.len()); + // The phases follow each other in order, a week or so apart. + for w in all.windows(2) { + let next = |k| match k { + LunationKind::NewMoon => LunationKind::FirstQuarter, + LunationKind::FirstQuarter => LunationKind::FullMoon, + LunationKind::FullMoon => LunationKind::LastQuarter, + LunationKind::LastQuarter => LunationKind::NewMoon, + }; + assert_eq!(w[1].kind, next(w[0].kind)); + let gap = w[1].jd_ut - w[0].jd_ut; + assert!((6.0..9.0).contains(&gap), "{gap}"); + } + let full: Vec = all.iter().filter(|l| l.kind == LunationKind::FullMoon).map(|l| day(l.jd_ut)).collect(); + let new: Vec = all.iter().filter(|l| l.kind == LunationKind::NewMoon).map(|l| day(l.jd_ut)).collect(); + // Total lunar eclipse on 3 March, total solar eclipse on 12 August, and + // the "blue moon" (second full moon of May) on 31 May. + assert!(full.contains(&"2026-03-03".to_string()), "{full:?}"); + assert!(full.contains(&"2026-05-31".to_string()), "{full:?}"); + assert!(new.contains(&"2026-08-12".to_string()), "{new:?}"); + // At the exact moment the Moon and the Sun are in line. + let e = engine(); + for l in &all { + let sun = e.position(Body::Sun, l.jd_ut, &Frame::TROPICAL_GEOCENTRIC).unwrap().longitude; + let target = match l.kind { + LunationKind::NewMoon => 0.0, + LunationKind::FirstQuarter => 90.0, + LunationKind::FullMoon => 180.0, + LunationKind::LastQuarter => 270.0, + }; + let off = ((l.moon_longitude - sun - target) + 540.0).rem_euclid(360.0) - 180.0; + assert!(off.abs() < 1e-4, "{off}"); + } + // The eclipses fall on these lunations. + for ecl in e.eclipses(jd(2026, 1, 1), jd(2027, 1, 1)).unwrap() { + assert!(all.iter().any(|l| (l.jd_ut - ecl.jd_ut).abs() < 0.5), "{ecl:?}"); + } +} + +#[test] +fn the_moon_changes_sign_every_two_or_three_days() { + let all = moon_ingresses(engine(), jd(2026, 3, 1), jd(2026, 4, 1)).unwrap(); + assert!((13..=15).contains(&all.len()), "{}", all.len()); + for w in all.windows(2) { + assert_eq!(w[1].1.index(), (w[0].1.index() + 1) % 12); + let gap = w[1].0 - w[0].0; + assert!((1.9..3.0).contains(&gap), "{gap}"); + } + let e = engine(); + for &(t, sign) in &all { + let lon = e.position(Body::Moon, t, &Frame::TROPICAL_GEOCENTRIC).unwrap().longitude; + assert_eq!(ZodiacSign::from_longitude(lon + 1e-4), sign); + assert!(((lon - 30.0 * sign.index() as f64 + 540.0).rem_euclid(360.0) - 180.0).abs() < 1e-4); + } +} + +#[test] +fn mercury_turns_retrograde_three_times_in_2026() { + let periods = retrograde_periods(engine(), Body::Mercury, jd(2026, 1, 1), jd(2027, 1, 1)).unwrap(); + let days: Vec<(String, String)> = + periods.iter().map(|p| (day(p.station_retrograde.jd_ut), day(p.station_direct.jd_ut))).collect(); + assert_eq!( + days, + [ + ("2026-02-26".into(), "2026-03-20".into()), + ("2026-06-29".into(), "2026-07-23".into()), + ("2026-10-24".into(), "2026-11-13".into()), + ] + ); + for p in &periods { + // Retrograde between the stations, direct before and after. + let e = engine(); + let v = |t| e.position(Body::Mercury, t, &Frame::TROPICAL_GEOCENTRIC).unwrap().speed_longitude; + let mid = (p.station_retrograde.jd_ut + p.station_direct.jd_ut) / 2.0; + assert!(v(mid) < 0.0 && v(p.station_retrograde.jd_ut - 1.0) > 0.0 && v(p.station_direct.jd_ut + 1.0) > 0.0); + // The shadow: about two weeks on each side, at the stations' degrees. + let before = p.station_retrograde.jd_ut - p.shadow_start; + let after = p.shadow_end - p.station_direct.jd_ut; + assert!((8.0..25.0).contains(&before) && (8.0..25.0).contains(&after), "{before} {after}"); + let lon = |t| e.position(Body::Mercury, t, &Frame::TROPICAL_GEOCENTRIC).unwrap().longitude; + assert!((lon(p.shadow_start) - p.station_direct.longitude).abs() < 1e-4); + assert!((lon(p.shadow_end) - p.station_retrograde.longitude).abs() < 1e-4); + } +} + +#[test] +fn slow_planets_and_overlapping_periods() { + // Every planet turns retrograde at most once or so in a year; Saturn and + // the outer planets once, with a period of four to six months. + for body in [Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto] { + let periods = retrograde_periods(engine(), body, jd(2026, 1, 1), jd(2027, 1, 1)).unwrap(); + assert!(!periods.is_empty(), "{body:?}"); + for p in &periods { + let len = p.station_direct.jd_ut - p.station_retrograde.jd_ut; + assert!((120.0..170.0).contains(&len), "{body:?} {len}"); + assert!(p.shadow_start < p.station_retrograde.jd_ut && p.shadow_end > p.station_direct.jd_ut); + } + } + // A period that began before the window still counts. + let mercury = retrograde_periods(engine(), Body::Mercury, jd(2026, 3, 10), jd(2026, 3, 11)).unwrap(); + assert_eq!(mercury.len(), 1); + assert_eq!(day(mercury[0].station_retrograde.jd_ut), "2026-02-26"); + // Stations alternate, and the next one is found from any moment. + let all = stations(engine(), Body::Mercury, jd(2026, 1, 1), jd(2027, 1, 1)).unwrap(); + assert_eq!(all.len(), 6); + assert!(all.windows(2).all(|w| w[0].retrograde != w[1].retrograde)); + let next = next_station(engine(), Body::Mercury, jd(2026, 3, 1), 200.0).unwrap().unwrap(); + assert!(!next.retrograde); + assert_eq!(day(next.jd_ut), "2026-03-20"); +} diff --git a/crates/horoscope-client/src/lib.rs b/crates/horoscope-client/src/lib.rs index 66a097c..7a06085 100644 --- a/crates/horoscope-client/src/lib.rs +++ b/crates/horoscope-client/src/lib.rs @@ -1,4 +1,4 @@ -//! Client of the horoscope-api service (`POST /v1/natal`, `POST /v1/synastry`). +//! Client of the horoscope-api service (charts, forecasts, the sky by date). //! //! Requests and responses are passed as JSON: the horoscope service validates //! the birth data itself, and its error objects are handed back unchanged so @@ -48,6 +48,16 @@ impl HoroscopeClient { self.post("/v1/forecast", request).await } + /// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon). + pub async fn sky(&self) -> Result { + self.get("/v1/sky", &[]).await + } + + /// `GET /v1/sky/events?year=`: a year's lunar phases, Moon sign changes and retrograde periods. + pub async fn sky_events(&self, year: i32) -> Result { + self.get("/v1/sky/events", &[("year", &year.to_string())]).await + } + /// `GET /v1/countries` pub async fn countries(&self) -> Result { self.get("/v1/countries", &[]).await diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index aadad7f..034138c 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -56,6 +56,8 @@ pub struct AppState { pub stripe: stripe::Client, /// Uploaded photos; `None` when no object storage is configured. pub storage: Option, + /// The sky by date, the same for everyone (see `routes::sky`). + pub sky: routes::sky::SkyCache, } impl AppState { @@ -71,6 +73,7 @@ impl AppState { models: models::Catalog::new(&config.openrouter_models_url), stripe: stripe::Client::default(), storage: config.storage.clone().map(storage::Storage::new), + sky: Default::default(), db, config, } diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 73380e1..bbcadf4 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -24,6 +24,7 @@ mod prompts; mod questions; mod recalculate; mod shares; +pub mod sky; mod synastries; mod tarot; @@ -130,6 +131,8 @@ pub fn router(state: Arc) -> Router { .route("/v1/public/chart", post(calculator::chart)) .route("/v1/public/geo/countries", get(calculator::countries)) .route("/v1/public/geo/places", get(calculator::places)) + .route("/v1/public/sky", get(sky::now)) + .route("/v1/public/sky/events", get(sky::events)) .route("/v1/public/celebrities", get(celebrities::public_list)) .route("/v1/public/celebrities/{slug}", get(celebrities::public_view)) .route("/v1/public/photos/{*key}", get(celebrities::photo)) diff --git a/services/backend/src/routes/sky.rs b/services/backend/src/routes/sky.rs new file mode 100644 index 0000000..c64daa9 --- /dev/null +++ b/services/backend/src/routes/sky.rs @@ -0,0 +1,69 @@ +//! The sky by date for the public calendars (`/holdnaptar`, `/retrograd`) and +//! the "today in the sky" card: the horoscope service's answer, the same for +//! everyone, kept in memory (the sky now for a few minutes, a year's events +//! for good), so page views and repeated calls do not recalculate it. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use axum::Json; +use axum::extract::{Query, State}; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::Value; +use time::OffsetDateTime; + +use super::St; +use crate::error::{ApiError, ApiResult}; + +/// How long the sky "now" is reused. +const NOW_TTL: Duration = Duration::from_secs(5 * 60); +/// Years served around the current one. +const YEARS_AROUND: i32 = 5; + +#[derive(Default)] +pub struct SkyCache { + now: Mutex>, + years: Mutex>, +} + +pub async fn now(State(state): St) -> ApiResult> { + if let Some((at, sky)) = state.sky.now.lock().unwrap().as_ref() + && at.elapsed() < NOW_TTL + { + return Ok(Json(sky.clone())); + } + let sky = state.horoscope.sky().await?; + *state.sky.now.lock().unwrap() = Some((Instant::now(), sky.clone())); + Ok(Json(sky)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EventsQuery { + year: i32, +} + +pub async fn events( + State(state): St, + WithRejection(Query(query), _): WithRejection, ApiError>, +) -> ApiResult> { + let current = OffsetDateTime::now_utc().year(); + if (query.year - current).abs() > YEARS_AROUND { + return Err(ApiError::BadRequest(format!( + "year must be between {} and {}", + current - YEARS_AROUND, + current + YEARS_AROUND + ))); + } + if let Some(events) = state.sky.years.lock().unwrap().get(&query.year) { + return Ok(Json(events.clone())); + } + let events = state.horoscope.sky_events(query.year).await?; + let mut years = state.sky.years.lock().unwrap(); + // Years that fell out of the window as time went on. + years.retain(|y, _| (y - current).abs() <= YEARS_AROUND); + years.insert(query.year, events.clone()); + Ok(Json(events)) +} diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index d143fc2..59ea1ac 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -90,6 +90,9 @@ async fn fake_forecast(Json(body): Json) -> (StatusCode, Json) { ) } +/// 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); + async fn fake_jwks() -> Json { Json( json!({"keys": [{"kid": "test-key", "kty": "RSA", "alg": "RS256", "use": "sig", "n": GOOGLE_KEY_N.trim(), "e": "AQAB"}]}), @@ -221,6 +224,20 @@ async fn fake_services_with(s3: FakeS3) -> String { ) .route("/v1/synastry", post(fake_synastry)) .route("/v1/forecast", post(fake_forecast)) + .route( + "/v1/sky", + get(|| async { + let n = SKY_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Json(json!({"call": n, "planets": [], "moon": {"phase": "full_moon"}})) + }), + ) + .route( + "/v1/sky/events", + get(|axum::extract::Query(q): axum::extract::Query>| async move { + SKY_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Json(json!({"year": q["year"].parse::().unwrap(), "lunations": []})) + }), + ) .route("/jwks", get(fake_jwks)); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); @@ -1009,7 +1026,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; 22] = [ +const PUBLIC_ROUTES: [&str; 24] = [ "/healthz", // Stripe calls it; the signature proves it. "/v1/payments/stripe/webhook", @@ -1035,6 +1052,9 @@ const PUBLIC_ROUTES: [&str; 22] = [ "/v1/public/celebrities", "/v1/public/celebrities/{slug}", "/v1/public/photos/{*key}", + // The sky by date, the same for everyone (the moon and retrograde calendars). + "/v1/public/sky", + "/v1/public/sky/events", ]; #[sqlx::test(migrator = "db::MIGRATOR")] @@ -3237,3 +3257,29 @@ async fn the_user_list_pages_with_a_total(pool: PgPool) { assert_eq!(r.body["total"].as_i64(), Some(1)); assert_eq!(r.body["stats"], json!({ "users": 5, "buyers": 1, "test_buyers": 1 })); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn the_sky_is_shared_and_kept(pool: PgPool) { + let app = TestApp::new(pool).await; + let calls = || SKY_CALLS.load(std::sync::atomic::Ordering::Relaxed); + let before = calls(); + // No login needed; the second call is answered from memory. + let r = app.get("/v1/public/sky", None).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(r.body["moon"]["phase"], "full_moon"); + let again = app.get("/v1/public/sky", None).await; + assert_eq!(again.body, r.body); + assert_eq!(calls() - before, 1); + + let year = time::OffsetDateTime::now_utc().year(); + let r = app.get(&format!("/v1/public/sky/events?year={}", year + 1), None).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(r.body["year"], year + 1); + app.get(&format!("/v1/public/sky/events?year={}", year + 1), None).await; + assert_eq!(calls() - before, 2); + for bad in [format!("year={}", year + 6), format!("year={}", year - 6), "year=abc".into(), String::new()] { + let r = app.get(&format!("/v1/public/sky/events?{bad}"), None).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST, "{bad}: {}", r.body); + } + assert_eq!(calls() - before, 2); +} diff --git a/services/frontend/src/app/Landing.tsx b/services/frontend/src/app/Landing.tsx index cd4d663..ae48aef 100644 --- a/services/frontend/src/app/Landing.tsx +++ b/services/frontend/src/app/Landing.tsx @@ -153,6 +153,20 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean; Megnézem → + + Holdnaptár + + Újhold, telihold és fogyatkozások pontos időponttal, és hogy ma melyik csillagjegyben jár a Hold. + + Megnézem → + + + Retrográd bolygók + + Mikor retrográd a Merkúr és a többi bolygó: kezdet, vég és árnyékszakasz, magyar idő szerint. + + Megnézem → + diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 7edff36..982d343 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -1422,3 +1422,92 @@ span.tarot-fan-card { cursor: default; } .site-header { gap: 8px; padding-left: 12px; padding-right: 12px; } .logo { font-size: 22px; } } + +/* The sky: "today in the sky" on the own chart, the moon and retrograde calendars. */ +.sky-today-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; } +.sky-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(280px, 100%), 1fr)); gap: 24px; } +.sky-col { display: flex; flex-direction: column; gap: 10px; min-width: 0; } +.sky-col p { margin: 0; line-height: 1.55; } +.sky-lead { display: flex; align-items: center; gap: 10px; font-size: 18px; } +.sky-glyph { font-family: var(--font-symbols); font-size: 26px; color: var(--gold); line-height: 1; } +.sky-glyph-sm { font-family: var(--font-symbols); color: var(--gold); } +.sky-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; } +.sky-list li { + display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; padding: 6px 0; + border-bottom: 1px solid var(--line); font-size: 14px; +} +.sky-list li:last-child { border-bottom: 0; } +.sky-list .num { color: var(--ink-2); font-variant-numeric: tabular-nums; } +.sky-transits { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 14px; } +.sky-transits li { display: flex; flex-direction: column; gap: 3px; line-height: 1.5; } +.sky-transits strong { font-weight: 600; } +.sky-more { margin-top: auto; font-size: 14px; } + +.sky-page h2 { font-size: 26px; } +.sky-now { flex-direction: row; align-items: flex-start; gap: 20px; border-color: rgba(217, 180, 106, 0.35); } +.sky-now-glyph { font-family: var(--font-symbols); font-size: 44px; color: var(--gold); line-height: 1; flex: none; } +.sky-now-body { display: flex; flex-direction: column; gap: 10px; flex: 1; min-width: 0; } +.sky-now-body p { margin: 0; line-height: 1.55; } +.year-nav { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; } +.year-nav > :first-child { justify-self: start; } +.year-nav > :last-child { justify-self: end; } +.year-nav strong { font-family: var(--font-display); font-size: 26px; } +.sky-events { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; } +.sky-events li { + display: grid; grid-template-columns: 28px minmax(0, 1fr) auto; gap: 4px 12px; align-items: baseline; + padding: 10px 0; border-bottom: 1px solid var(--line); +} +.sky-events li:last-child { border-bottom: 0; } +.sky-event-glyph, .moon-phase-glyph { font-family: var(--font-symbols); color: var(--gold); font-size: 20px; line-height: 1; } +.sky-events .num { color: var(--ink-2); font-variant-numeric: tabular-nums; } +.moon-months { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); gap: 16px; } +.moon-month { gap: 12px; } +.moon-month h2 { font-size: 24px; } +.moon-phases { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; } +.moon-phases li { + display: grid; grid-template-columns: 28px minmax(0, 1fr) auto; grid-template-areas: "g n d" ". p p"; + gap: 2px 12px; align-items: baseline; padding: 8px 0; border-bottom: 1px solid var(--line); +} +.moon-phases li:last-child { border-bottom: 0; } +.moon-phases .moon-phase-glyph { grid-area: g; } +.moon-phase-name { grid-area: n; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.moon-phases .num { grid-area: d; text-align: right; font-variant-numeric: tabular-nums; color: var(--ink-2); } +.moon-phases .hint { grid-area: p; } +.moon-phases li.is-eclipse .moon-phase-name { color: var(--gold); } +.moon-ingresses summary { + cursor: pointer; color: var(--muted); font-size: 14px; min-height: 32px; display: flex; align-items: center; gap: 8px; + list-style: none; +} +.moon-ingresses summary::-webkit-details-marker { display: none; } +.moon-ingresses summary::before { content: "▸"; color: var(--gold); transition: transform 0.15s; } +.moon-ingresses[open] summary::before { transform: rotate(90deg); } +.moon-ingresses summary:hover { color: var(--ink); } +.moon-ingresses ul { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 4px; font-size: 14px; } +.moon-ingresses li { display: grid; grid-template-columns: 120px minmax(0, 1fr); gap: 12px; } +.moon-ingresses .num { color: var(--ink-2); font-variant-numeric: tabular-nums; } +.sky-prose p { line-height: 1.7; color: var(--ink-2); margin: 0; } +.sky-prose h2 { margin-top: 8px; } +.sky-defs { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(220px, 100%), 1fr)); gap: 12px; margin: 0; } +.sky-defs > div { background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; } +.sky-defs dt { font-weight: 600; margin-bottom: 4px; } +.sky-defs dt span { font-family: var(--font-symbols); color: var(--gold); } +.sky-defs dd { margin: 0; color: var(--ink-2); line-height: 1.55; font-size: 14px; } +.retro-planet { gap: 12px; } +.retro-planet-head { display: flex; align-items: center; gap: 12px; } +.retro-glyph { font-family: var(--font-symbols); font-size: 28px; color: var(--gold); line-height: 1; } +.retro-planet > p { margin: 0; line-height: 1.6; } +.retro-periods { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; } +.retro-periods li { + display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; border: 1px solid var(--line); + border-radius: var(--radius); background: var(--panel-2); +} +.retro-periods li.is-active { border-color: var(--gold); } +.retro-dates { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; } +@media (max-width: 640px) { + .sky-now { flex-direction: column; gap: 10px; } + .sky-now-glyph { font-size: 36px; } + .moon-phases li { grid-template-columns: 24px minmax(0, 1fr); grid-template-areas: "g n" ". d" ". p"; } + .moon-phases .num { text-align: left; } + .sky-events li { grid-template-columns: 24px minmax(0, 1fr); } + .sky-events li .num { grid-column: 2; } +} diff --git a/services/frontend/src/app/holdnaptar/MoonCalendar.tsx b/services/frontend/src/app/holdnaptar/MoonCalendar.tsx new file mode 100644 index 0000000..70c51ff --- /dev/null +++ b/services/frontend/src/app/holdnaptar/MoonCalendar.tsx @@ -0,0 +1,227 @@ +import Link from "next/link"; + +import { PublicFooter } from "@/components/PublicFooter"; +import { PublicHeader } from "@/components/SiteHeader"; +import { YearNav } from "@/components/YearNav"; +import { MOON_PHASES, SIGNS } from "@/lib/astro"; +import { YEARS_AROUND, currentYear } from "@/lib/sky"; +import { + LUNATION_GLYPHS, + LUNATION_NAMES, + MONTH_NAMES, + MOON_IN_SIGN, + PHASE_MEANING, + SIGN_IN, + SIGN_INTO, + eclipseName, + localDate, + positionText, + withArticle, +} from "@/lib/skyText"; +import type { Me, SkyEvents, SkyIngress, SkyNow } from "@/lib/types"; + +/** + * The moon calendar of a year: the main phases with the eclipses, month by + * month, and when the Moon changes sign. With `sky` (the current year) the + * Moon of today comes first. + */ +export function MoonCalendar({ year, events, sky, me }: { year: number; events: SkyEvents | null; sky: SkyNow | null; me: Me | null }) { + const current = currentYear(); + const eclipses = events?.lunations.filter((l) => l.eclipse) ?? []; + return ( + <> + {!me && } +
+
+ Holdnaptár +

Holdnaptár {year}

+

+ Újhold, telihold és a negyedek pontos időpontja magyar idő szerint, a nap- és holdfogyatkozásokkal, és hogy + mikor melyik csillagjegyben jár a Hold. +

+
+ + {sky && } + + + + {!events ? ( +

+ A naptár most nem tölthető be. Próbáld újra pár perc múlva. +

+ ) : ( + <> + {eclipses.length > 0 && ( +
+

Fogyatkozások {year}

+
    + {eclipses.map((l) => ( +
  • + + + {capitalize(eclipseName(l.eclipse!))} + + {" "} + {withArticle(SIGN_IN[l.position.sign] ?? l.position.sign)} + + + {localDate(l.local_time, { weekday: true, time: true })} +
  • + ))} +
+

+ Az időpont a fogyatkozás legnagyobb fázisa. Hogy Magyarországról is látszik-e, az a fogyatkozás útvonalától + függ. +

+
+ )} + +
+ {MONTH_NAMES.map((name, i) => ( + + ))} +
+ + )} + +
+

Mit jelentenek a holdfázisok?

+

+ A Hold nagyjából 29,5 nap alatt kerüli meg a Földet a Naphoz képest. Újholdkor a Nap és a Hold egy irányban + áll, ezért a Holdból semmi sem látszik; teliholdkor szemben állnak, és a teljes korong világít. A két negyed + ezek között félúton van. +

+
+ {(["new_moon", "first_quarter", "full_moon", "last_quarter"] as const).map((k) => ( +
+
+ {LUNATION_NAMES[k]} +
+
{PHASE_MEANING[k]}
+
+ ))} +
+

Mi az a holdjegy?

+

+ A Hold két-két és fél naponta lép át a következő csillagjegybe, így egy hónap alatt mind a tizenkettőt bejárja. + Az asztrológiai hagyomány szerint a napok hangulatát a Hold aktuális jegye színezi. A születéskori holdjegyed + pedig az érzelmi alkatodról mesél. +

+

Milyen idő szerint?

+

+ Minden időpont magyar idő szerint értendő, télen közép-európai (UTC+1), nyáron nyári időszámítással (UTC+2). A + számítás svájci efemerisszel készül, percre pontos. +

+

+ A bolygók látszólagos hátráló mozgásáról a retrográd naptárban olvashatsz. +

+
+
+ + + ); +} + +/** The Moon now: sign, phase, the next sign change and the next new and full moon. */ +function MoonToday({ sky }: { sky: SkyNow }) { + const moon = sky.moon; + const sign = moon.position.sign; + const next = moon.next_phases.filter((p) => p.kind === "new_moon" || p.kind === "full_moon"); + return ( +
+ +
+

Ma a Hold {withArticle(SIGN_IN[sign] ?? sign)} jár

+

+ {MOON_PHASES[moon.phase] ?? moon.phase}, {Math.round(moon.illumination * 100)}% megvilágítás. {MOON_IN_SIGN[sign]} +

+
    + {moon.sign_change && ( +
  • + Jegyváltás + + {localDate(moon.sign_change.local_time, { short: true, time: true })}:{" "} + {withArticle(SIGN_INTO[moon.sign_change.sign] ?? moon.sign_change.sign)} + +
  • + )} + {next.map((p) => ( +
  • + {LUNATION_NAMES[p.kind]} + + {localDate(p.local_time, { short: true, time: true })}, {SIGNS[p.position.sign]?.hu} + {p.eclipse ? ` (${eclipseName(p.eclipse)})` : ""} + +
  • + ))} +
+
+
+ ); +} + +/** One month: the main phases, then (folded) the Moon's sign changes. */ +function MoonMonth({ name, month, events }: { name: string; month: number; events: SkyEvents }) { + const prefix = `${events.year}-${String(month).padStart(2, "0")}`; + const phases = events.lunations.filter((l) => l.local_time.startsWith(prefix)); + const ingresses = events.moon_ingresses.filter((m) => m.local_time.startsWith(prefix)); + const start = signAtStart(events.moon_ingresses, prefix); + return ( +
+

{name}

+
    + {phases.map((l) => ( +
  • + + + {LUNATION_NAMES[l.kind]} + {l.eclipse && {eclipseName(l.eclipse)}} + + {localDate(l.local_time, { weekday: true, time: true })} + {positionText(l.position)} +
  • + ))} +
+
+ A Hold jegyváltásai +
    + {start && ( +
  • + {localDate(`${prefix}-01`, { short: true })} + {withArticle(SIGN_IN[start] ?? start)} jár +
  • + )} + {ingresses.map((m) => ( +
  • + {localDate(m.local_time, { short: true, time: true })} + + {SIGNS[m.sign]?.glyph} {withArticle(SIGN_INTO[m.sign] ?? m.sign)} lép + +
  • + ))} +
+
+
+ ); +} + +/** The Moon's sign at the start of a month: the last sign entered before it. */ +function signAtStart(all: SkyIngress[], prefix: string): string | null { + const before = all.filter((m) => m.local_time < prefix); + if (before.length > 0) return before[before.length - 1].sign; + // January: one sign before the first one entered. + const first = all[0]; + if (!first) return null; + const order = Object.keys(SIGNS); + return order[(order.indexOf(first.sign) + 11) % 12]; +} + +function capitalize(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1); +} diff --git a/services/frontend/src/app/holdnaptar/[ev]/page.tsx b/services/frontend/src/app/holdnaptar/[ev]/page.tsx new file mode 100644 index 0000000..79504d2 --- /dev/null +++ b/services/frontend/src/app/holdnaptar/[ev]/page.tsx @@ -0,0 +1,26 @@ +import type { Metadata } from "next"; +import { notFound, permanentRedirect } from "next/navigation"; + +import { getMe } from "@/lib/server"; +import { calendarYear, currentYear, loadSkyEvents } from "@/lib/sky"; + +import { MoonCalendar } from "../MoonCalendar"; + +export async function generateMetadata({ params }: { params: Promise<{ ev: string }> }): Promise { + const year = calendarYear((await params).ev); + if (!year) return {}; + return { + title: `Holdnaptár ${year}: újhold, telihold, fogyatkozások pontos időponttal`, + description: `Holdnaptár ${year}: mikor van újhold és telihold, a negyedek és a nap- és holdfogyatkozások magyar idő szerint, és mikor melyik jegyben jár a Hold.`, + alternates: { canonical: `/holdnaptar/${year}` }, + }; +} + +/** The moon calendar of another year (the current one is `/holdnaptar`). */ +export default async function MoonCalendarYearPage({ params }: { params: Promise<{ ev: string }> }) { + const year = calendarYear((await params).ev); + if (!year) notFound(); + if (year === currentYear()) permanentRedirect("/holdnaptar"); + const [me, events] = await Promise.all([getMe(), loadSkyEvents(year)]); + return ; +} diff --git a/services/frontend/src/app/holdnaptar/page.tsx b/services/frontend/src/app/holdnaptar/page.tsx new file mode 100644 index 0000000..2ded19c --- /dev/null +++ b/services/frontend/src/app/holdnaptar/page.tsx @@ -0,0 +1,22 @@ +import type { Metadata } from "next"; + +import { getMe } from "@/lib/server"; +import { currentYear, loadSky, loadSkyEvents } from "@/lib/sky"; + +import { MoonCalendar } from "./MoonCalendar"; + +export async function generateMetadata(): Promise { + const year = currentYear(); + return { + title: `Holdnaptár ${year}: újhold, telihold, fogyatkozások pontos időponttal`, + description: `Holdnaptár ${year}: mikor van újhold és telihold, a negyedek, a nap- és holdfogyatkozások magyar idő szerint, és melyik csillagjegyben jár ma a Hold.`, + alternates: { canonical: "/holdnaptar" }, + }; +} + +/** The moon calendar of the current year, with the Moon of today. */ +export default async function MoonCalendarPage() { + const year = currentYear(); + const [me, events, sky] = await Promise.all([getMe(), loadSkyEvents(year), loadSky()]); + return ; +} diff --git a/services/frontend/src/app/kepletek/[id]/page.tsx b/services/frontend/src/app/kepletek/[id]/page.tsx index 0d46824..594c068 100644 --- a/services/frontend/src/app/kepletek/[id]/page.tsx +++ b/services/frontend/src/app/kepletek/[id]/page.tsx @@ -8,10 +8,12 @@ import { ChartSwitcher } from "@/components/ChartSwitcher"; import { DetailedAnalysis } from "@/components/DetailedAnalysis"; import { ChartWheel, WheelLegend } from "@/components/ChartWheel"; import { CompareButton } from "@/components/CompareButton"; +import { SkyToday } from "@/components/SkyToday"; import { Tabs } from "@/components/Tabs"; import { ASPECTS, ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro"; import { payMethod } from "@/lib/payments"; import { backendGet, requireMe } from "@/lib/server"; +import { loadSky } from "@/lib/sky"; import type { Analysis, Chart, ChartListItem, PublicConfig } from "@/lib/types"; export const metadata: Metadata = { title: "Képlet" }; @@ -25,11 +27,12 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri const { id } = await params; const me = await requireMe(`/kepletek/${id}`); if (!UUID.test(id)) notFound(); - const [chart, analyses, config, chartList] = await Promise.all([ + const [chart, analyses, config, chartList, sky] = await Promise.all([ backendGet(`/v1/charts/${id}`), backendGet<{ analyses: Analysis[] }>(`/v1/charts/${id}/analyses`), backendGet("/v1/config"), backendGet<{ charts: ChartListItem[] }>("/v1/charts"), + loadSky(), ]); const charts = chartList?.charts ?? []; const persons = charts.filter((c) => c.kind === "person"); @@ -169,6 +172,8 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri )} + {chart.is_primary && sky && } +
+ {!me && } +
+
+ Retrográd bolygók +

Merkúr retrográd {year} és a többi retrográd bolygó

+

+ Mikor retrográd a Merkúr, a Vénusz, a Mars és a lassú bolygók {yearIn(year)}: pontos kezdés és vég magyar idő + szerint, a jegyekkel és az árnyékszakaszokkal. +

+
+ + {sky && } + + + + {!events ? ( +

+ A naptár most nem tölthető be. Próbáld újra pár perc múlva. +

+ ) : ( + PLANETS.map((id) => { + const periods = events.retrogrades.filter((r) => r.planet === id); + return ( +
+
+ +

+ {POINTS[id]?.hu} retrográd {year} +

+
+

{RETROGRADE_MEANING[id]}

+ {periods.length === 0 ? ( +

+ {capitalize(planet(id))} {yearIn(year)} nem retrográd. +

+ ) : ( +
    + {periods.map((r) => ( + + ))} +
+ )} +
+ ); + }) + )} + +
+

Mit jelent, hogy egy bolygó retrográd?

+

+ A Földről nézve a bolygók időnként megállni, majd visszafelé haladni látszanak a csillagok előtt, aztán újra + megállnak, és folytatják útjukat előre. Valójában egyik bolygó sem fordul meg: a látszat abból adódik, hogy a + Föld és a bolygó különböző sebességgel kering a Nap körül, és az egyik „megelőzi” a másikat. +

+

+ A Merkúr évente háromszor, nagyjából három hétre fordul vissza, a Vénusz másfél évente hat hétre, a Mars két + évente két-két és fél hónapra. A Jupiter és a lassabb bolygók minden évben négy-öt hónapig retrográdok, ezért + ezeket kevésbé érezzük személyesnek. +

+

Mi az árnyékszakasz?

+

+ A retrográd mozgás alatt a bolygó egy szakaszt kétszer tesz meg: előre, vissza, majd megint előre. Az + árnyékszakasz az az idő, amikor a bolygó a retrográd előtt már, illetve utána még ezen a szakaszon jár. Sokan + már a kezdetén érzik a retrográd témáit, és csak az árnyék végén tekintik lezártnak. +

+

Amit nem érdemes elhinni

+

+ A retrográd Merkúr nem okoz katasztrófát, és nem kell miatta mindent elhalasztani. Az asztrológiai hagyomány + szerint inkább átnézésre, javításra, régi szálak elvarrására alkalmas időszak. Egy fontos szerződés vagy utazás + előtt elég kicsit alaposabbnak lenni. +

+

+ A holdfázisok és a fogyatkozások pontos időpontja a holdnaptárban található. +

+
+
+ + + ); +} + +/** Which planets are retrograde now, until when, and when Mercury turns next. */ +function RetroNow({ sky }: { sky: SkyNow }) { + const retro = sky.planets.filter((p) => p.retrograde); + const mercury = sky.planets.find((p) => p.id === "mercury"); + const year = sky.local_time.slice(0, 4); + const opts = (local: string) => ({ year: local.slice(0, 4) !== year }); + return ( +
+ +
+

+ {mercury?.retrograde ? "Most retrográd a Merkúr" : "Most nem retrográd a Merkúr"} +

+ {mercury?.next_station && ( +

+ {mercury.retrograde + ? `${capitalize(until(mercury.next_station.local_time, opts(mercury.next_station.local_time)))}, utána újra előre halad.` + : `A következő Merkúr-retrográd kezdete: ${localDate(mercury.next_station.local_time, opts(mercury.next_station.local_time))}, ${withArticle(SIGN_IN[mercury.next_station.position.sign] ?? "")}.`} +

+ )} + {retro.length === 0 ? ( +

Most egy bolygó sem retrográd.

+ ) : ( +
    + {retro.map((p) => ( +
  • + + {POINTS[p.id]?.hu} {withArticle(SIGN_IN[p.position.sign] ?? "")} + + {p.next_station && ( + {until(p.next_station.local_time, opts(p.next_station.local_time))} + )} +
  • + ))} +
+ )} +
+
+ ); +} + +function RetroPeriod({ r, year, now }: { r: SkyRetrograde; year: number; now: string | null }) { + const y = String(year); + const date = (local: string, time = false) => localDate(local, { time, year: local.slice(0, 4) !== y }); + const days = Math.round((Date.parse(r.station_direct.moment_utc) - Date.parse(r.station_retrograde.moment_utc)) / 86400000); + const active = now !== null && r.station_retrograde.local_time <= now && now < r.station_direct.local_time; + const shadow = now !== null && !active && r.shadow_start.local_time <= now && now < r.shadow_end.local_time; + return ( +
  • +
    + + {date(r.station_retrograde.local_time, true)} – {date(r.station_direct.local_time, true)} + + {active && most tart} + {shadow && most árnyékban} +
    + + {days} nap · {positionText(r.station_retrograde.position)} → {positionText(r.station_direct.position)} + + + Árnyékszakasz: {date(r.shadow_start.local_time)} – {date(r.shadow_end.local_time)} + +
  • + ); +} + +function capitalize(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1); +} diff --git a/services/frontend/src/app/retrograd/[ev]/page.tsx b/services/frontend/src/app/retrograd/[ev]/page.tsx new file mode 100644 index 0000000..30a2aa1 --- /dev/null +++ b/services/frontend/src/app/retrograd/[ev]/page.tsx @@ -0,0 +1,26 @@ +import type { Metadata } from "next"; +import { notFound, permanentRedirect } from "next/navigation"; + +import { getMe } from "@/lib/server"; +import { calendarYear, currentYear, loadSkyEvents } from "@/lib/sky"; + +import { RetrogradeCalendar } from "../RetrogradeCalendar"; + +export async function generateMetadata({ params }: { params: Promise<{ ev: string }> }): Promise { + const year = calendarYear((await params).ev); + if (!year) return {}; + return { + title: `Merkúr retrográd ${year}: mikor retrográd a Merkúr és a többi bolygó?`, + description: `Merkúr retrográd ${year}: a retrográd időszakok pontos kezdete és vége magyar idő szerint, árnyékszakaszokkal, a Vénusztól a Plútóig.`, + alternates: { canonical: `/retrograd/${year}` }, + }; +} + +/** The retrograde periods of another year (the current one is `/retrograd`). */ +export default async function RetrogradeYearPage({ params }: { params: Promise<{ ev: string }> }) { + const year = calendarYear((await params).ev); + if (!year) notFound(); + if (year === currentYear()) permanentRedirect("/retrograd"); + const [me, events] = await Promise.all([getMe(), loadSkyEvents(year)]); + return ; +} diff --git a/services/frontend/src/app/retrograd/page.tsx b/services/frontend/src/app/retrograd/page.tsx new file mode 100644 index 0000000..f73fb05 --- /dev/null +++ b/services/frontend/src/app/retrograd/page.tsx @@ -0,0 +1,22 @@ +import type { Metadata } from "next"; + +import { getMe } from "@/lib/server"; +import { currentYear, loadSky, loadSkyEvents } from "@/lib/sky"; + +import { RetrogradeCalendar } from "./RetrogradeCalendar"; + +export async function generateMetadata(): Promise { + const year = currentYear(); + return { + title: `Merkúr retrográd ${year}: mikor retrográd a Merkúr és a többi bolygó?`, + description: `Merkúr retrográd ${year}: a retrográd időszakok pontos kezdete és vége magyar idő szerint, árnyékszakaszokkal, a Vénusztól a Plútóig. Melyik bolygó retrográd most?`, + alternates: { canonical: "/retrograd" }, + }; +} + +/** The retrograde periods of the current year, with the planets retrograde now. */ +export default async function RetrogradePage() { + const year = currentYear(); + const [me, events, sky] = await Promise.all([getMe(), loadSkyEvents(year), loadSky()]); + return ; +} diff --git a/services/frontend/src/app/sitemap.ts b/services/frontend/src/app/sitemap.ts index f31cfd6..8913298 100644 --- a/services/frontend/src/app/sitemap.ts +++ b/services/frontend/src/app/sitemap.ts @@ -2,6 +2,7 @@ import type { MetadataRoute } from "next"; import { ZODIAC } from "@/content/zodiac"; import { loadCelebrities } from "@/lib/celebrities"; +import { currentYear } from "@/lib/sky"; import { siteUrl } from "@/lib/share"; /** The public pages for search engines; everything else needs a login. */ @@ -10,6 +11,7 @@ export default async function sitemap(): Promise { const privacy = { languages: { hu: `${base}/adatvedelem`, en: `${base}/privacy` } }; // The sitemap still works when the backend does not answer. const people = await loadCelebrities().catch(() => []); + const next = currentYear() + 1; return [ { url: `${base}/`, changeFrequency: "weekly", priority: 1 }, { url: `${base}/pelda`, changeFrequency: "monthly", priority: 0.8 }, @@ -17,6 +19,10 @@ export default async function sitemap(): Promise { { url: `${base}/szuletesi-horoszkop`, changeFrequency: "monthly", priority: 0.9 }, { url: `${base}/csillagjegyek`, changeFrequency: "monthly", priority: 0.8 }, ...ZODIAC.map((z) => ({ url: `${base}/csillagjegyek/${z.slug}`, changeFrequency: "monthly" as const, priority: 0.7 })), + { url: `${base}/holdnaptar`, changeFrequency: "daily", priority: 0.8 }, + { url: `${base}/holdnaptar/${next}`, changeFrequency: "monthly", priority: 0.6 }, + { url: `${base}/retrograd`, changeFrequency: "daily", priority: 0.8 }, + { url: `${base}/retrograd/${next}`, changeFrequency: "monthly", priority: 0.6 }, { url: `${base}/hires-emberek`, changeFrequency: "weekly", priority: 0.7 }, ...people.map((p) => ({ url: `${base}/hires-emberek/${p.slug}`, diff --git a/services/frontend/src/components/PublicFooter.tsx b/services/frontend/src/components/PublicFooter.tsx index 93c5a2a..11532d0 100644 --- a/services/frontend/src/components/PublicFooter.tsx +++ b/services/frontend/src/components/PublicFooter.tsx @@ -12,6 +12,8 @@ export function PublicFooter() { Születési horoszkóp Csillagjegyek Híres emberek + Holdnaptár + Retrográd bolygók Példaelemzés Példajóslás ÁSZF diff --git a/services/frontend/src/components/SiteHeader.tsx b/services/frontend/src/components/SiteHeader.tsx index 436247a..1efb954 100644 --- a/services/frontend/src/components/SiteHeader.tsx +++ b/services/frontend/src/components/SiteHeader.tsx @@ -41,7 +41,7 @@ export function PublicHeader({ current, }: { onHome?: boolean; - current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires"; + current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires" | "holdnaptar" | "retrograd"; }) { const home = onHome ? "" : "/"; const here = (page: typeof current) => (current === page ? "page" : undefined); @@ -88,6 +88,8 @@ export function PublicHeader({ { href: "/szuletesi-horoszkop", label: "Születési horoszkóp" }, { href: "/csillagjegyek", label: "Csillagjegyek" }, { href: "/hires-emberek", label: "Híres emberek" }, + { href: "/holdnaptar", label: "Holdnaptár" }, + { href: "/retrograd", label: "Retrográd bolygók" }, ], }, ]} diff --git a/services/frontend/src/components/SkyToday.tsx b/services/frontend/src/components/SkyToday.tsx new file mode 100644 index 0000000..770d272 --- /dev/null +++ b/services/frontend/src/components/SkyToday.tsx @@ -0,0 +1,151 @@ +import Link from "next/link"; + +import { MOON_PHASES, POINTS, SIGNS, orbText } from "@/lib/astro"; +import { + HOUSE_THEMES, + LUNATION_NAMES, + MOON_IN_SIGN, + SIGN_IN, + SIGN_INTO, + dayWord, + localDate, + transitLine, + transitMeaning, + until, + withArticle, +} from "@/lib/skyText"; +import { natalHouse, todaysTransits } from "@/lib/transits"; +import type { ChartResult, SkyNow } from "@/lib/types"; + +/** + * "Today in the sky" on the user's own chart: the Moon (sign, phase, the natal + * house it crosses), the tightest transits to the chart, and the retrograde + * planets. Calculated from the shared sky; nothing is stored, no AI. + */ +export function SkyToday({ sky, chart, timeKnown }: { sky: SkyNow; chart: ChartResult; timeKnown: boolean }) { + const moon = sky.moon; + const sign = moon.position.sign; + const house = timeKnown ? natalHouse(chart, moon.position.longitude) : null; + const transits = todaysTransits(sky.planets, chart, timeKnown); + const retro = sky.planets.filter((p) => p.retrograde); + const mercury = sky.planets.find((p) => p.id === "mercury"); + const nextMercury = mercury && !mercury.retrograde ? mercury.next_station : null; + const full = moon.next_phases.find((p) => p.kind === "full_moon"); + const fresh = moon.next_phases.find((p) => p.kind === "new_moon"); + const thisYear = sky.local_time.slice(0, 4); + + return ( +
    +
    +

    Ma az égen

    + Frissítve {sky.local_time.slice(11, 16)}-kor +
    +
    +
    + A Hold +

    + + Hold {withArticle(SIGN_IN[sign] ?? sign)} +

    +

    + {MOON_PHASES[moon.phase] ?? moon.phase}, {Math.round(moon.illumination * 100)}% megvilágítás.{" "} + {MOON_IN_SIGN[sign]} +

    + {house && ( +

    + Ma a {house}. házadban jár: {HOUSE_THEMES[house]} kerülnek előtérbe. +

    + )} + {moon.sign_change && ( +

    + {capitalize(dayWord(moon.sign_change.local_time, sky.local_time))} {moon.sign_change.local_time.slice(11, 16)}-kor + lép {withArticle(SIGN_INTO[moon.sign_change.sign] ?? moon.sign_change.sign)}. +

    + )} +
      + {[full, fresh] + .filter((p) => p !== undefined) + .sort((a, b) => a.local_time.localeCompare(b.local_time)) + .map((p) => ( +
    • + {LUNATION_NAMES[p.kind]} + + {localDate(p.local_time, { short: true, time: true })}, {SIGNS[p.position.sign]?.hu} + +
    • + ))} +
    + + Holdnaptár → + +
    + +
    + A képletedhez + {transits.length === 0 ? ( +

    Most nincs szoros fényszög az égbolt és a képleted között.

    + ) : ( +
      + {transits.map((t) => ( +
    • + {transitLine(t.transiting, t.aspect, t.natal)} + {transitMeaning(t.transiting, t.aspect, t.natal)} + + {t.applying ? "Erősödik" : "Már gyengül"}, {orbText(t.orb)} a pontostól. + +
    • + ))} +
    + )} + {!timeKnown && ( +

    Születési idő nélkül a Holdad és az aszcendensed kimarad, mert nem pontos.

    + )} +
    + +
    + Retrográd bolygók + {retro.length === 0 ? ( +

    Most egy bolygó sem retrográd.

    + ) : ( +
      + {retro.map((p) => ( +
    • + + {" "} + {POINTS[p.id]?.hu} {withArticle(SIGN_IN[p.position.sign] ?? "")} + + {p.next_station && ( + + {until(p.next_station.local_time, { + short: true, + year: p.next_station.local_time.slice(0, 4) !== thisYear, + })} + + )} +
    • + ))} +
    + )} + {nextMercury && ( +

    + A következő Merkúr-retrográd:{" "} + {localDate(nextMercury.local_time, { year: nextMercury.local_time.slice(0, 4) !== thisYear })},{" "} + {withArticle(SIGN_IN[nextMercury.position.sign] ?? "")}. +

    + )} + + Retrográd naptár → + +
    +
    +
    + ); +} + +function capitalize(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1); +} diff --git a/services/frontend/src/components/YearNav.tsx b/services/frontend/src/components/YearNav.tsx new file mode 100644 index 0000000..f28e4ed --- /dev/null +++ b/services/frontend/src/components/YearNav.tsx @@ -0,0 +1,25 @@ +import Link from "next/link"; + +/** Previous and next year of a calendar page; the current year is the page without a year. */ +export function YearNav({ base, year, current, around }: { base: string; year: number; current: number; around: number }) { + const href = (y: number) => (y === current ? base : `${base}/${y}`); + return ( + + ); +} diff --git a/services/frontend/src/lib/sky.ts b/services/frontend/src/lib/sky.ts new file mode 100644 index 0000000..d515c12 --- /dev/null +++ b/services/frontend/src/lib/sky.ts @@ -0,0 +1,41 @@ +// The sky by date from the backend, for the moon and retrograde calendars and +// the "today in the sky" card. The same for everyone, so it is cached. +import "server-only"; + +import { BACKEND_URL } from "./server"; +import type { SkyEvents, SkyNow } from "./types"; + +/** Years the calendar pages have, around the current one (as the backend). */ +export const YEARS_AROUND = 5; + +/** The year in Hungary now. */ +export function currentYear(): number { + return Number(new Intl.DateTimeFormat("en", { year: "numeric", timeZone: "Europe/Budapest" }).format(new Date())); +} + +/** A year the calendar pages have (`/holdnaptar/2027`), or `null`. */ +export function calendarYear(text: string): number | null { + if (!/^\d{4}$/.test(text)) return null; + const year = Number(text); + return Math.abs(year - currentYear()) <= YEARS_AROUND ? year : null; +} + +/** The sky now (a few minutes old at most); `null` when the backend does not answer. */ +export async function loadSky(): Promise { + try { + const res = await fetch(`${BACKEND_URL}/v1/public/sky`, { next: { revalidate: 300 } }); + return res.ok ? ((await res.json()) as SkyNow) : null; + } catch { + return null; + } +} + +/** A year's lunar phases, Moon sign changes and retrograde periods. */ +export async function loadSkyEvents(year: number): Promise { + try { + const res = await fetch(`${BACKEND_URL}/v1/public/sky/events?year=${year}`, { next: { revalidate: 86400 } }); + return res.ok ? ((await res.json()) as SkyEvents) : null; + } catch { + return null; + } +} diff --git a/services/frontend/src/lib/skyText.ts b/services/frontend/src/lib/skyText.ts new file mode 100644 index 0000000..5611655 --- /dev/null +++ b/services/frontend/src/lib/skyText.ts @@ -0,0 +1,261 @@ +// Hungarian words and short texts for the sky calendars and the "today in +// the sky" card. No AI: fixed sentences put together from parts. + +import { POINTS, SIGNS } from "./astro"; +import type { LunationKind, SkyLunation, SkyPosition } from "./types"; + +/** "in Aries": `Kosban`. */ +export const SIGN_IN: Record = { + aries: "Kosban", + taurus: "Bikában", + gemini: "Ikrekben", + cancer: "Rákban", + leo: "Oroszlánban", + virgo: "Szűzben", + libra: "Mérlegben", + scorpio: "Skorpióban", + sagittarius: "Nyilasban", + capricorn: "Bakban", + aquarius: "Vízöntőben", + pisces: "Halakban", +}; + +/** "into Aries": `Kosba`. */ +export const SIGN_INTO: Record = { + aries: "Kosba", + taurus: "Bikába", + gemini: "Ikrekbe", + cancer: "Rákba", + leo: "Oroszlánba", + virgo: "Szűzbe", + libra: "Mérlegbe", + scorpio: "Skorpióba", + sagittarius: "Nyilasba", + capricorn: "Bakba", + aquarius: "Vízöntőbe", + pisces: "Halakba", +}; + +/** The mood of the days with the Moon in a sign. */ +export const MOON_IN_SIGN: Record = { + aries: "Lendület és türelmetlenség. Jó nap elkezdeni valamit.", + taurus: "Nyugalom, kényelem, érzéki örömök. Ráérősebb tempó.", + gemini: "Kíváncsiság, beszélgetések, sok apró ügy egyszerre.", + cancer: "Otthon, család, érzékenység. Jólesik a biztonság.", + leo: "Önkifejezés, játékosság, a figyelem öröme.", + virgo: "Rendrakás, részletek, a test és a napi rutin.", + libra: "Kapcsolatok, harmónia, kompromisszumok.", + scorpio: "Mélység és intenzitás: erősebb érzések, kevesebb felszínesség.", + sagittarius: "Derűlátás, tanulás, kalandvágy.", + capricorn: "Kötelességek, tervezés, kitartó munka.", + aquarius: "Szabadság, barátok, szokatlan ötletek.", + pisces: "Álmodozás, együttérzés, megérzések.", +}; + +/** What a phase of the Moon is good for, in the astrological tradition. */ +export const PHASE_MEANING: Record = { + new_moon: "Újrakezdés: jó pillanat szándékot megfogalmazni, valami újat elindítani.", + waxing_crescent: "Az elindított dolgok szárba szöknek: lendület, első lépések.", + first_quarter: "Próbatétel: ami elindult, most döntéseket és kitartást kér.", + waxing_gibbous: "Csiszolás és finomhangolás a kiteljesedés előtt.", + full_moon: "Tetőpont: felfokozott érzelmek, minden láthatóbbá válik.", + waning_gibbous: "Az eredmények ideje: megosztás, hála, tanulságok.", + last_quarter: "Rendrakás: amitől ideje elbúcsúzni, attól most könnyebb.", + waning_crescent: "Pihenés és elengedés a következő újhold előtt.", +}; + +export const LUNATION_NAMES: Record = { + new_moon: "Újhold", + first_quarter: "Első negyed", + full_moon: "Telihold", + last_quarter: "Utolsó negyed", +}; + +/** Moon glyphs of the four main phases: the filled part is the lit one (gold on the dark page). */ +export const LUNATION_GLYPHS: Record = { + new_moon: "○", + first_quarter: "◑", + full_moon: "●", + last_quarter: "◐", +}; + +export function eclipseName(e: NonNullable): string { + const type = { total: "teljes", annular: "gyűrűs", hybrid: "hibrid", partial: "részleges", penumbral: "félárnyékos" }[ + e.eclipse_type + ]; + return `${type} ${e.kind === "solar" ? "napfogyatkozás" : "holdfogyatkozás"}`; +} + +/** What a natal house is about, as the subject of "kerülnek előtérbe". */ +export const HOUSE_THEMES: Record = { + 1: "a hangulatod és a megjelenésed", + 2: "a pénzügyeid és az anyagi biztonságod", + 3: "a beszélgetések és a rövid utak", + 4: "az otthonod és a családod", + 5: "az örömeid és a kreativitásod", + 6: "a munkád és a napi teendőid", + 7: "a párkapcsolatod és a társaid", + 8: "a közös anyagiak és az intimitás", + 9: "a tanulás és az utazás", + 10: "a hivatásod és a céljaid", + 11: "a barátaid és a közösségeid", + 12: "a pihenés és a belső világod", +}; + +/** What a planet brings when it moves over a chart (one noun, for the sentences). */ +const TRANSIT_THEME: Record = { + sun: "az önkifejezés", + moon: "a hangulat", + mercury: "a kommunikáció", + venus: "a szeretet", + mars: "a lendület", + jupiter: "a bizalom", + saturn: "a felelősség", + uranus: "a változás", + neptune: "a képzelet", + pluto: "az átalakulás", +}; + +/** What a point of the birth chart stands for (yours). */ +const NATAL_THEME: Record = { + sun: "az önazonosságod", + moon: "az érzelmeid", + mercury: "a gondolkodásod", + venus: "a kapcsolataid", + mars: "a cselekvőkészséged", + jupiter: "az optimizmusod", + saturn: "a kötelességtudatod", + uranus: "a függetlenséged", + neptune: "az érzékenységed", + pluto: "a belső erőd", + ascendant: "a fellépésed", + midheaven: "a hivatásod", +}; + +/** "with your natal Moon": the point in the instrumental, with "your". */ +const NATAL_WITH: Record = { + sun: "Napoddal", + moon: "Holdaddal", + mercury: "Merkúroddal", + venus: "Vénuszoddal", + mars: "Marsoddal", + jupiter: "Jupitereddel", + saturn: "Szaturnuszoddal", + uranus: "Uránuszoddal", + neptune: "Neptunuszoddal", + pluto: "Plútóddal", + ascendant: "aszcendenseddel", + midheaven: "MC-ddel", +}; + +/** The aspect as "in trine" (`trigonban`). */ +const ASPECT_IN: Record = { + conjunction: "együttállásban", + sextile: "szextilben", + square: "kvadrátban", + trine: "trigonban", + opposition: "szembenállásban", +}; + +/** "A tranzit Vénusz trigonban áll a születési Holdaddal." */ +export function transitLine(transiting: string, aspect: string, natal: string): string { + return `A tranzit ${POINTS[transiting]?.hu ?? transiting} ${ASPECT_IN[aspect] ?? aspect} áll a születési ${NATAL_WITH[natal] ?? natal}.`; +} + +/** One sentence on what the aspect suggests. */ +export function transitMeaning(transiting: string, aspect: string, natal: string): string { + const a = TRANSIT_THEME[transiting] ?? transiting; + const b = NATAL_THEME[natal] ?? natal; + if (aspect === "conjunction") return `Egybefonódik ${a} és ${b}.`; + if (aspect === "trine" || aspect === "sextile") return `Könnyen összhangba kerül ${a} és ${b}.`; + return `Súrlódás lehet ${a} és ${b} között; megéri tudatosan kezelni.`; +} + +/** What a retrograde period of the planet is said to bring. */ +export const RETROGRADE_MEANING: Record = { + mercury: + "Kommunikáció, utazás, technika, szerződések: gyakoribb félreértések, késések, előkerülő régi ügyek. Jó idő átnézni, javítani, újragondolni.", + venus: + "Kapcsolatok és értékek: régi szerelmek, kapcsolati kérdések kerülhetnek elő. A nagy vásárlásokat, látványos változtatásokat a külsőn sokan elhalasztják.", + mars: "Energia és cselekvés: a lendület befelé fordul, régi konfliktusok kerülhetnek elő. Inkább befejezni érdemes, mint új harcba kezdeni.", + jupiter: "Növekedés, hit, tanulás: a kifelé terjeszkedés helyett belső fejlődés, a meggyőződések átgondolása.", + saturn: "Felelősség és struktúra: a kötelezettségek, határok és hosszú távú tervek felülvizsgálata.", + uranus: "Változás és szabadság: a változások belül érlelődnek, mielőtt kifelé is megmutatkoznának.", + neptune: "Álmok és illúziók: a köd ritkul, könnyebb tisztán látni, mi volt csak vágyálom.", + pluto: "Átalakulás és hatalom: régi minták kerülnek felszínre, mély, belső átalakulás.", +}; + +/** `"2026-03-03T12:38"` as a date in Hungarian (no time zone shift: the text is local already). */ +export function localDate( + local: string, + opts: { time?: boolean; weekday?: boolean; year?: boolean; short?: boolean } = {}, +): string { + const [date, clock = "00:00"] = local.split("T"); + const [y, m, d] = date.split("-").map(Number); + const [h, min] = clock.split(":").map(Number); + const text = new Intl.DateTimeFormat("hu-HU", { + ...(opts.year ? { year: "numeric" } : {}), + month: opts.short ? "short" : "long", + day: "numeric", + ...(opts.weekday ? { weekday: "long" } : {}), + timeZone: "UTC", + }).format(new Date(Date.UTC(y, m - 1, d))); + return opts.time ? `${text} ${String(h).padStart(2, "0")}:${String(min).padStart(2, "0")}` : text; +} + +/** `Halak 8°29′`. */ +export function positionText(p: SkyPosition): string { + const deg = Math.floor(p.degree_in_sign); + const min = Math.floor((p.degree_in_sign - deg) * 60); + return `${SIGNS[p.sign]?.hu ?? p.sign} ${deg}°${String(min).padStart(2, "0")}′`; +} + +/** Hungarian month names, January first. */ +export const MONTH_NAMES = [ + "Január", + "Február", + "Március", + "Április", + "Május", + "Június", + "Július", + "Augusztus", + "Szeptember", + "Október", + "November", + "December", +]; + +/** `a Kosba`, `az Ikrekbe`: the article before a Hungarian word. */ +export function withArticle(word: string): string { + return `${/^[aáeéiíoóöőuúüű]/i.test(word) ? "az" : "a"} ${word}`; +} + +/** "ma", "holnap" or the date, for a local time relative to another one. */ +export function dayWord(local: string, today: string): string { + const day = (t: string) => { + const [y, m, d] = t.slice(0, 10).split("-").map(Number); + return Date.UTC(y, m - 1, d); + }; + const diff = Math.round((day(local) - day(today)) / 86400000); + if (diff === 0) return "ma"; + if (diff === 1) return "holnap"; + return localDate(local, { short: true }); +} + +/** `december 13-ig`: a date with "until" (the date's closing dot dropped). */ +export function until(local: string, opts: Parameters[1] = {}): string { + return `${localDate(local, opts).replace(/\.$/, "")}-ig`; +} + +/** `2026-ban`, `2027-ben`: a year with "in", by how its last word sounds. */ +export function yearIn(year: number): string { + const last = year % 10; + const tens = Math.floor(year / 10) % 10; + let back: boolean; + if (last !== 0) back = [3, 6, 8].includes(last); + else if (tens !== 0) back = [2, 3, 6, 8].includes(tens); + // "…száz": -ban, "…ezer": -ben. + else back = Math.floor(year / 100) % 10 !== 0; + return `${year}-${back ? "ban" : "ben"}`; +} diff --git a/services/frontend/src/lib/transits.ts b/services/frontend/src/lib/transits.ts new file mode 100644 index 0000000..c3dc674 --- /dev/null +++ b/services/frontend/src/lib/transits.ts @@ -0,0 +1,98 @@ +// Today's transits to a birth chart: the planets now against the chart's +// planets and angles. A plain calculation on data the page already has. + +import type { ChartResult, SkyPlanet } from "./types"; + +export interface Transit { + transiting: string; + natal: string; + aspect: "conjunction" | "sextile" | "square" | "trine" | "opposition"; + /** Degrees from exact. */ + orb: number; + /** Getting closer (otherwise past exact and fading). */ + applying: boolean; +} + +const ASPECTS: [Transit["aspect"], number][] = [ + ["conjunction", 0], + ["sextile", 60], + ["square", 90], + ["trine", 120], + ["opposition", 180], +]; + +/** Orbs for a day's view: the faster the planet, the shorter it stays in one. */ +const ORB: Record = { + moon: 2, + sun: 2, + mercury: 2, + venus: 2, + mars: 2, + jupiter: 1.5, + saturn: 1.5, + uranus: 1, + neptune: 1, + pluto: 1, +}; + +const PLANETS = Object.keys(ORB); + +/** Angular distance `[0, 180]`. */ +function separation(a: number, b: number): number { + const d = Math.abs(a - b) % 360; + return d > 180 ? 360 - d : d; +} + +/** The chart points measured to: the ten planets, and with a birth time the Ascendant and the MC (the Moon only then). */ +function natalPoints(chart: ChartResult, timeKnown: boolean): [string, number][] { + const out: [string, number][] = chart.points + .filter((p) => PLANETS.includes(p.id) && (timeKnown || p.id !== "moon")) + .map((p) => [p.id, p.longitude]); + if (timeKnown && chart.angles) { + for (const id of ["ascendant", "midheaven"]) { + const a = chart.angles[id]; + if (a && typeof a === "object") out.push([id, a.longitude]); + } + } + return out; +} + +/** The tightest transits now, closest first (relative to the orb allowed). */ +export function todaysTransits(sky: SkyPlanet[], chart: ChartResult, timeKnown: boolean, limit = 3): Transit[] { + const found: (Transit & { score: number })[] = []; + for (const t of sky) { + const maxOrb = ORB[t.id]; + if (maxOrb === undefined) continue; + // Where it will be in about an hour: closer or farther from exact. + const later = t.position.longitude + t.speed / 24; + for (const [natal, lon] of natalPoints(chart, timeKnown)) { + for (const [aspect, angle] of ASPECTS) { + const orb = Math.abs(separation(t.position.longitude, lon) - angle); + if (orb > maxOrb) continue; + const applying = Math.abs(separation(later, lon) - angle) < orb; + found.push({ transiting: t.id, natal, aspect, orb, applying, score: orb / maxOrb }); + } + } + } + // The Moon passes everything within hours: one of its aspects at most. + let moon = 0; + return found + .sort((a, b) => a.score - b.score) + .filter((t) => t.transiting !== "moon" || moon++ === 0) + .slice(0, limit) + .map(({ score: _, ...t }) => t); +} + +/** The natal house a longitude falls in (1–12), or `null` without houses. */ +export function natalHouse(chart: ChartResult, longitude: number): number | null { + const cusps = chart.houses?.cusps; + if (!cusps || cusps.length !== 12) return null; + const sorted = [...cusps].sort((a, b) => a.house - b.house).map((c) => c.longitude); + for (let i = 0; i < 12; i++) { + const start = sorted[i]; + const end = sorted[(i + 1) % 12]; + const span = (end - start + 360) % 360; + if ((longitude - start + 360) % 360 < span) return i + 1; + } + return null; +} diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index 8b5cfa1..a5f7d4c 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -669,3 +669,75 @@ export interface Invoice { gross_huf: number; paid_at: string; } + +/** The sky by date (`/v1/public/sky…`): tropical, geocentric, the same for everyone. */ +export interface SkyPosition { + longitude: number; + sign: string; + degree_in_sign: number; + degree_in_sign_dms: string; +} + +export interface SkyMoment { + moment_utc: string; + /** `YYYY-MM-DDTHH:MM` on the Hungarian clock. */ + local_time: string; +} + +export interface SkyStation extends SkyMoment { + /** Turns retrograde here (otherwise direct). */ + retrograde: boolean; + position: SkyPosition; +} + +export type LunationKind = "new_moon" | "first_quarter" | "full_moon" | "last_quarter"; + +export interface SkyLunation extends SkyMoment { + kind: LunationKind; + position: SkyPosition; + eclipse: { kind: "solar" | "lunar"; eclipse_type: "total" | "annular" | "hybrid" | "partial" | "penumbral" } | null; +} + +export interface SkyIngress extends SkyMoment { + sign: string; +} + +export interface SkyPlanet { + id: string; + position: SkyPosition; + /** Degrees a day (negative: retrograde). */ + speed: number; + retrograde: boolean; + next_station: SkyStation | null; +} + +export interface SkyNow extends SkyMoment { + timezone: string; + utc_offset: string; + planets: SkyPlanet[]; + moon: { + position: SkyPosition; + phase: string; + illumination: number; + elongation: number; + waxing: boolean; + sign_change: SkyIngress | null; + next_phases: SkyLunation[]; + }; +} + +export interface SkyRetrograde { + planet: string; + station_retrograde: SkyStation; + station_direct: SkyStation; + shadow_start: SkyMoment; + shadow_end: SkyMoment; +} + +export interface SkyEvents { + year: number; + timezone: string; + lunations: SkyLunation[]; + moon_ingresses: SkyIngress[]; + retrogrades: SkyRetrograde[]; +} diff --git a/services/horoscope-api/src/main.rs b/services/horoscope-api/src/main.rs index ca769aa..8bdff47 100644 --- a/services/horoscope-api/src/main.rs +++ b/services/horoscope-api/src/main.rs @@ -12,6 +12,7 @@ mod error; mod forecast; mod natal; mod routes; +mod sky; mod synastry; #[cfg(test)] mod tests; diff --git a/services/horoscope-api/src/routes.rs b/services/horoscope-api/src/routes.rs index 3411be8..1a186c1 100644 --- a/services/horoscope-api/src/routes.rs +++ b/services/horoscope-api/src/routes.rs @@ -15,6 +15,7 @@ use crate::AppState; use crate::error::ApiError; use crate::forecast::{self, ForecastRequest, ForecastResponse}; use crate::natal::{self, NatalRequest, NatalResponse}; +use crate::sky::{self, EventsQuery, EventsResponse, SkyQuery, SkyResponse}; use crate::synastry::{self, SynastryRequest, SynastryResponse}; type AppResult = Result, ApiError>; @@ -29,6 +30,8 @@ pub fn router(state: Arc) -> Router { .route("/v1/natal", post(natal_chart)) .route("/v1/synastry", post(synastry_chart)) .route("/v1/forecast", post(forecast_year)) + .route("/v1/sky", get(sky_now)) + .route("/v1/sky/events", get(sky_events)) .layer(cors()) // The request log: masked paths, health checks only when they fail. .layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog)) @@ -163,3 +166,25 @@ async fn forecast_year( .map_err(|e| ApiError::Internal(e.to_string()))??; Ok(Json(response)) } + +async fn sky_now( + State(state): State>, + query: Result, QueryRejection>, +) -> AppResult { + let Query(query) = query?; + let response = tokio::task::spawn_blocking(move || sky::now(&state, query)) + .await + .map_err(|e| ApiError::Internal(e.to_string()))??; + Ok(Json(response)) +} + +async fn sky_events( + State(state): State>, + query: Result, QueryRejection>, +) -> AppResult { + let Query(query) = query?; + let response = tokio::task::spawn_blocking(move || sky::events(&state, query)) + .await + .map_err(|e| ApiError::Internal(e.to_string()))??; + Ok(Json(response)) +} diff --git a/services/horoscope-api/src/sky.rs b/services/horoscope-api/src/sky.rs new file mode 100644 index 0000000..a3bf7ab --- /dev/null +++ b/services/horoscope-api/src/sky.rs @@ -0,0 +1,296 @@ +//! The sky by date, the same for everyone (tropical, geocentric): +//! +//! * `GET /v1/sky?at=&tz=`: the sky at a moment (default now): where the +//! planets are, which are retrograde and their next station, the Moon's +//! phase, when it changes sign, and the next main phases; +//! * `GET /v1/sky/events?year=&tz=`: a calendar year's lunar phases (with the +//! eclipses on them), the Moon's sign changes and the retrograde periods +//! with their shadows. +//! +//! Local times are on the clock of `tz` (default Europe/Budapest). + +use astro_engine::chart::{MoonPhaseName, ZodiacPosition}; +use astro_engine::sky::{ + LunationKind, RETROGRADING, Station, lunations, moon_ingresses, moon_now, next_station, retrograde_periods, +}; +use astro_engine::{Body, EclipseKind, EclipseType, Frame, ZodiacSign}; +use geo_tz::tz::format_offset; +use jiff::Timestamp; +use jiff::tz::TimeZone; +use serde::{Deserialize, Serialize}; + +use crate::AppState; +use crate::error::ApiError; + +pub const DEFAULT_TZ: &str = "Europe/Budapest"; +/// The calendar years served. +pub const YEARS: std::ops::RangeInclusive = 1900..=2100; +/// Far enough ahead for every planet's next station (Mars may run direct for two years). +const STATION_HORIZON_DAYS: f64 = 800.0; + +const UNIX_EPOCH_JD: f64 = 2_440_587.5; + +fn jd_of(ts: Timestamp) -> f64 { + ts.as_second() as f64 / 86_400.0 + UNIX_EPOCH_JD +} + +fn timestamp_of(jd: f64) -> Result { + Timestamp::from_second(((jd - UNIX_EPOCH_JD) * 86_400.0).round() as i64) + .map_err(|e| ApiError::Internal(e.to_string())) +} + +fn calc(e: astro_engine::EngineError) -> ApiError { + ApiError::Calculation(e.to_string()) +} + +/// A moment in UTC and on the local clock (to the minute). +#[derive(Debug, Serialize)] +pub struct Moment { + pub moment_utc: String, + /// `YYYY-MM-DDTHH:MM`, rounded to the minute. + pub local_time: String, +} + +fn moment(jd: f64, tz: &TimeZone) -> Result { + let ts = timestamp_of(jd)?; + let minute = Timestamp::from_second((ts.as_second() + 30).div_euclid(60) * 60) + .map_err(|e| ApiError::Internal(e.to_string()))?; + Ok(Moment { moment_utc: ts.to_string(), local_time: tz.to_datetime(minute).strftime("%Y-%m-%dT%H:%M").to_string() }) +} + +#[derive(Debug, Serialize)] +pub struct StationOut { + #[serde(flatten)] + pub moment: Moment, + /// Turns retrograde (`true`) or direct here. + pub retrograde: bool, + pub position: ZodiacPosition, +} + +fn station(s: &Station, tz: &TimeZone) -> Result { + Ok(StationOut { + moment: moment(s.jd_ut, tz)?, + retrograde: s.retrograde, + position: ZodiacPosition::new(s.longitude), + }) +} + +#[derive(Debug, Serialize)] +pub struct EclipseOut { + pub kind: EclipseKind, + pub eclipse_type: EclipseType, +} + +#[derive(Debug, Serialize)] +pub struct LunationOut { + pub kind: LunationKind, + #[serde(flatten)] + pub moment: Moment, + /// Where the Moon is. + pub position: ZodiacPosition, + /// The eclipse at this new or full moon, if any. + pub eclipse: Option, +} + +/// The lunations between two moments, with the eclipses on them. +fn lunations_out(state: &AppState, from: f64, to: f64, tz: &TimeZone) -> Result, ApiError> { + let engine = state.engine.as_ref(); + let eclipses = engine.eclipses(from - 1.0, to + 1.0).map_err(calc)?; + lunations(engine, from, to) + .map_err(calc)? + .into_iter() + .map(|l| { + let eclipse = eclipses + .iter() + .find(|e| { + let on = match e.kind { + EclipseKind::Solar => LunationKind::NewMoon, + EclipseKind::Lunar => LunationKind::FullMoon, + }; + on == l.kind && (e.jd_ut - l.jd_ut).abs() < 0.6 + }) + .map(|e| EclipseOut { kind: e.kind, eclipse_type: e.eclipse_type }); + Ok(LunationOut { + kind: l.kind, + moment: moment(l.jd_ut, tz)?, + position: ZodiacPosition::new(l.moon_longitude), + eclipse, + }) + }) + .collect() +} + +#[derive(Debug, Serialize)] +pub struct IngressOut { + #[serde(flatten)] + pub moment: Moment, + pub sign: ZodiacSign, +} + +#[derive(Debug, Serialize)] +pub struct PlanetNow { + pub id: Body, + pub position: ZodiacPosition, + /// Degrees a day (negative: retrograde). + pub speed: f64, + pub retrograde: bool, + /// The next station (the end of a retrograde period, or the start of the next one). + pub next_station: Option, +} + +#[derive(Debug, Serialize)] +pub struct MoonOut { + pub position: ZodiacPosition, + pub phase: MoonPhaseName, + /// Illuminated fraction of the disc (0..1). + pub illumination: f64, + /// Moon minus Sun, degrees. + pub elongation: f64, + pub waxing: bool, + /// When the Moon enters the next sign. + pub sign_change: Option, + /// The next four main phases. + pub next_phases: Vec, +} + +#[derive(Debug, Serialize)] +pub struct SkyResponse { + #[serde(flatten)] + pub moment: Moment, + pub timezone: String, + pub utc_offset: String, + pub planets: Vec, + pub moon: MoonOut, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SkyQuery { + /// RFC 3339; now when not given. + pub at: Option, + pub tz: Option, +} + +fn zone(state: &AppState, name: Option<&str>) -> Result<(String, TimeZone), ApiError> { + let name = name.unwrap_or(DEFAULT_TZ); + Ok((name.to_string(), state.atlas.zones.get(name)?)) +} + +pub fn now(state: &AppState, query: SkyQuery) -> Result { + let (zone_name, tz) = zone(state, query.tz.as_deref())?; + let ts = match query.at.as_deref() { + Some(at) => at.parse::().map_err(|_| ApiError::BadRequest("at must be an RFC 3339 time".into()))?, + None => Timestamp::now(), + }; + let jd = jd_of(ts); + let year = tz.to_datetime(ts).year(); + if !YEARS.contains(&i32::from(year)) { + return Err(ApiError::BadRequest(format!("at must be between {} and {}", YEARS.start(), YEARS.end()))); + } + let engine = state.engine.as_ref(); + let planets = Body::PLANETS + .iter() + .map(|&body| { + let s = engine.position(body, jd, &Frame::TROPICAL_GEOCENTRIC).map_err(calc)?; + let next = if RETROGRADING.contains(&body) { + next_station(engine, body, jd, STATION_HORIZON_DAYS).map_err(calc)? + } else { + None + }; + Ok(PlanetNow { + id: body, + position: ZodiacPosition::new(s.longitude), + speed: s.speed_longitude, + retrograde: s.speed_longitude < 0.0, + next_station: next.as_ref().map(|n| station(n, &tz)).transpose()?, + }) + }) + .collect::, ApiError>>()?; + + let m = moon_now(engine, jd).map_err(calc)?; + let sign_change = moon_ingresses(engine, jd, jd + 3.0) + .map_err(calc)? + .first() + .map(|&(t, sign)| Ok::<_, ApiError>(IngressOut { moment: moment(t, &tz)?, sign })) + .transpose()?; + let mut next_phases = lunations_out(state, jd, jd + 31.0, &tz)?; + next_phases.truncate(4); + let moon = MoonOut { + position: ZodiacPosition::new(m.longitude), + phase: m.phase, + illumination: m.illumination, + elongation: m.elongation, + waxing: m.elongation < 180.0, + sign_change, + next_phases, + }; + Ok(SkyResponse { + moment: moment(jd, &tz)?, + timezone: zone_name, + utc_offset: format_offset(tz.to_offset(ts)), + planets, + moon, + }) +} + +#[derive(Debug, Serialize)] +pub struct RetrogradeOut { + pub planet: Body, + pub station_retrograde: StationOut, + pub station_direct: StationOut, + /// The planet first reaches the degree where it turns direct. + pub shadow_start: Moment, + /// The planet is back at the degree where it turned retrograde. + pub shadow_end: Moment, +} + +#[derive(Debug, Serialize)] +pub struct EventsResponse { + pub year: i32, + pub timezone: String, + pub lunations: Vec, + pub moon_ingresses: Vec, + /// The retrograde periods overlapping the year, by planet, then by time. + pub retrogrades: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EventsQuery { + pub year: i32, + pub tz: Option, +} + +pub fn events(state: &AppState, query: EventsQuery) -> Result { + if !YEARS.contains(&query.year) { + return Err(ApiError::BadRequest(format!("year must be between {} and {}", YEARS.start(), YEARS.end()))); + } + let (zone_name, tz) = zone(state, query.tz.as_deref())?; + let start_of = |year: i32| -> Result { + let zoned = + jiff::civil::date(year as i16, 1, 1).to_zoned(tz.clone()).map_err(|e| ApiError::Internal(e.to_string()))?; + Ok(jd_of(zoned.timestamp())) + }; + let (from, to) = (start_of(query.year)?, start_of(query.year + 1)?); + let engine = state.engine.as_ref(); + + let lunations = lunations_out(state, from, to, &tz)?; + let moon_ingresses = moon_ingresses(engine, from, to) + .map_err(calc)? + .into_iter() + .map(|(t, sign)| Ok(IngressOut { moment: moment(t, &tz)?, sign })) + .collect::, ApiError>>()?; + let mut retrogrades = Vec::new(); + for body in RETROGRADING { + for p in retrograde_periods(engine, body, from, to).map_err(calc)? { + retrogrades.push(RetrogradeOut { + planet: body, + station_retrograde: station(&p.station_retrograde, &tz)?, + station_direct: station(&p.station_direct, &tz)?, + shadow_start: moment(p.shadow_start, &tz)?, + shadow_end: moment(p.shadow_end, &tz)?, + }); + } + } + Ok(EventsResponse { year: query.year, timezone: zone_name, lunations, moon_ingresses, retrogrades }) +} diff --git a/services/horoscope-api/src/tests.rs b/services/horoscope-api/src/tests.rs index 7d8e02c..a304f88 100644 --- a/services/horoscope-api/src/tests.rs +++ b/services/horoscope-api/src/tests.rs @@ -318,3 +318,77 @@ async fn forecast_year_with_solar_return() { let (status, _) = call("POST", "/v1/forecast", Some(json!({"birth": birth, "year": 1985}))).await; assert_eq!(status, StatusCode::BAD_REQUEST); } + +#[tokio::test] +async fn sky_at_a_moment() { + // 2026-03-10 12:00 UTC: Mercury retrograde (26 Feb – 20 Mar), waning Moon. + let (status, d) = call("GET", "/v1/sky?at=2026-03-10T12:00:00Z", None).await; + assert_eq!(status, StatusCode::OK, "{d}"); + assert_eq!(d["timezone"], "Europe/Budapest"); + assert_eq!(d["utc_offset"], "+01:00"); + assert_eq!(d["local_time"], "2026-03-10T13:00"); + let planets = d["planets"].as_array().unwrap(); + assert_eq!(planets.len(), 10); + let mercury = planets.iter().find(|p| p["id"] == "mercury").unwrap(); + assert_eq!(mercury["retrograde"], true); + assert_eq!(mercury["position"]["sign"], "pisces"); + assert_eq!(mercury["next_station"]["retrograde"], false); + assert!(mercury["next_station"]["local_time"].as_str().unwrap().starts_with("2026-03-2"), "{mercury}"); + let sun = planets.iter().find(|p| p["id"] == "sun").unwrap(); + assert_eq!(sun["retrograde"], false); + assert!(sun["next_station"].is_null()); + let moon = &d["moon"]; + assert_eq!(moon["waxing"], false); + assert!(moon["sign_change"]["local_time"].as_str().unwrap() > "2026-03-10T13:00"); + let phases = moon["next_phases"].as_array().unwrap(); + assert_eq!(phases.len(), 4); + assert_eq!(phases[0]["kind"], "last_quarter"); + // The new moon of 19 March is not an eclipse; 3 March was (and is past). + assert!(phases.iter().all(|p| p["eclipse"].is_null()), "{phases:?}"); + + let (status, _) = call("GET", "/v1/sky?at=tegnap", None).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, _) = call("GET", "/v1/sky?tz=Mars/Olympus", None).await; + assert!(status.is_client_error(), "{status}"); + let (status, now) = call("GET", "/v1/sky", None).await; + assert_eq!(status, StatusCode::OK, "{now}"); +} + +#[tokio::test] +async fn sky_events_of_a_year() { + let (status, d) = call("GET", "/v1/sky/events?year=2026", None).await; + assert_eq!(status, StatusCode::OK, "{d}"); + assert_eq!(d["year"], 2026); + let lunations = d["lunations"].as_array().unwrap(); + assert!(lunations.iter().all(|l| l["local_time"].as_str().unwrap().starts_with("2026-"))); + // The total lunar eclipse at the full moon of 3 March (12:38 in Budapest), + // the total solar eclipse at the new moon of 12 August. + let eclipse = |date: &str| { + lunations.iter().find(|l| l["local_time"].as_str().unwrap().starts_with(date) && !l["eclipse"].is_null()) + }; + let march = eclipse("2026-03-03").expect("lunar eclipse"); + assert_eq!((march["kind"].as_str(), march["eclipse"]["kind"].as_str()), (Some("full_moon"), Some("lunar"))); + assert_eq!(march["eclipse"]["eclipse_type"], "total"); + assert_eq!(march["position"]["sign"], "virgo"); + let august = eclipse("2026-08-12").expect("solar eclipse"); + assert_eq!(august["eclipse"]["eclipse_type"], "total"); + assert_eq!(lunations.iter().filter(|l| !l["eclipse"].is_null()).count(), 4); + + let ingresses = d["moon_ingresses"].as_array().unwrap(); + assert!((155..=170).contains(&ingresses.len()), "{}", ingresses.len()); + + let retro = d["retrogrades"].as_array().unwrap(); + let mercury: Vec<&Value> = retro.iter().filter(|r| r["planet"] == "mercury").collect(); + assert_eq!(mercury.len(), 3); + assert!(mercury[0]["station_retrograde"]["local_time"].as_str().unwrap().starts_with("2026-02-26")); + assert_eq!(mercury[0]["station_retrograde"]["retrograde"], true); + assert!(mercury[0]["shadow_start"]["local_time"].as_str().unwrap() < "2026-02-26"); + // Every planet but the Sun and the Moon; Venus turns retrograde in October. + assert!(retro.iter().any(|r| r["planet"] == "venus")); + assert!(retro.iter().any(|r| r["planet"] == "pluto")); + + for bad in ["/v1/sky/events?year=1800", "/v1/sky/events", "/v1/sky/events?year=2026&x=1"] { + let (status, _) = call("GET", bad, None).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}"); + } +}