Yearly forecast: solar return, transits, progressions, profection, eclipses
- astro-engine: forecast module (solar return moment, slow-planet transits
with exact dates and periods, natal house ingresses, secondary
progressions, annual profection, eclipses via Swiss Ephemeris)
- horoscope-api: POST /v1/forecast, solar return chart cast for the place
of the birthday
- backend: forecasts table, /v1/charts/{id}/forecasts, /v1/forecasts/{id}
and its analyses using a new 'forecast' unit; current year of life open,
the next one 30 days before the birthday
- packages: Páros and Család include forecasts (6 000 / 11 000 Ft),
+1 éves előrejelzés add-on 2 500 Ft; Egy elemzés unchanged
- worker and prompt: forecast kind with five sections and forecast rules
(trends, no event predictions); no birth data, place or exact age sent
- frontend: /kepletek/{id}/elorejelzes with the solar return wheel, the
keys of the year, a monthly timeline, transit list and detailed forecast
- data export: forecasts added, model name removed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
//! `POST /v1/forecast`: one year of a natal chart, from the solar return in
|
||||
//! the given year to the next one: the solar return chart (cast for where the
|
||||
//! person is on the birthday), slow-planet transits, progressions, the annual
|
||||
//! profection and eclipses.
|
||||
|
||||
use astro_engine::chart::house_of;
|
||||
use astro_engine::{Forecast, calculate_forecast, solar_return};
|
||||
use geo_tz::tz::format_offset;
|
||||
use jiff::Timestamp;
|
||||
use jiff::tz::Offset;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::ApiError;
|
||||
use crate::natal::{self, Meta, NatalRequest, NatalResult};
|
||||
|
||||
/// Where the person is on the birthday; the birth place when not given.
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Location {
|
||||
pub country: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub place: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub region: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub geonames_id: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub latitude: Option<f64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub longitude: Option<f64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub timezone: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ForecastRequest {
|
||||
/// Birth data as for `POST /v1/natal`.
|
||||
pub birth: NatalRequest,
|
||||
/// The year starts at the solar return (birthday) in this calendar year.
|
||||
pub year: i32,
|
||||
#[serde(default)]
|
||||
pub location: Option<Location>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SolarReturn {
|
||||
/// The exact moment, RFC 3339 UTC.
|
||||
pub moment_utc: String,
|
||||
/// The same moment on the local clock of the place, `YYYY-MM-DDTHH:MM:SS`.
|
||||
pub local_time: String,
|
||||
pub timezone: String,
|
||||
pub utc_offset: String,
|
||||
/// Natal house the solar return Ascendant falls into.
|
||||
pub natal_house_of_ascendant: Option<u8>,
|
||||
/// The chart of the moment at the place.
|
||||
#[serde(flatten)]
|
||||
pub chart: NatalResult,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ForecastResponse {
|
||||
pub year: i32,
|
||||
/// `null` when the birth time is unknown: the moment may then be half a day off.
|
||||
pub solar_return: Option<SolarReturn>,
|
||||
/// Where the year is reckoned (dates are local to it).
|
||||
pub location: Location,
|
||||
pub forecast: Forecast,
|
||||
pub meta: Meta,
|
||||
}
|
||||
|
||||
fn bad(msg: impl Into<String>) -> ApiError {
|
||||
ApiError::BadRequest(msg.into())
|
||||
}
|
||||
|
||||
fn timestamp_of(jd: f64) -> Result<Timestamp, ApiError> {
|
||||
let seconds = ((jd - 2_440_587.5) * 86_400.0).round() as i64;
|
||||
Timestamp::from_second(seconds).map_err(|e| ApiError::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
pub fn calculate(state: &AppState, req: ForecastRequest) -> Result<ForecastResponse, ApiError> {
|
||||
let birth = req.birth;
|
||||
let options = birth.options;
|
||||
let natal = natal::calculate(state, birth.clone()).map_err(|e| e.for_person("birth"))?;
|
||||
let birth_year: i32 = natal.time.date[..4].parse().map_err(|_| ApiError::Internal("birth year".into()))?;
|
||||
if req.year <= birth_year || req.year > birth_year + 120 || req.year > 2398 {
|
||||
return Err(bad(format!("year must be after the birth year {birth_year} and at most 120 years later")));
|
||||
}
|
||||
let engine = state.engine.as_ref();
|
||||
let calc = |e: astro_engine::EngineError| ApiError::Calculation(e.to_string());
|
||||
let start = solar_return(engine, &natal.chart, req.year).map_err(calc)?;
|
||||
let end = solar_return(engine, &natal.chart, req.year + 1).map_err(calc)?;
|
||||
|
||||
let location = req.location.unwrap_or_else(|| Location {
|
||||
country: birth.country.clone(),
|
||||
place: birth.place.clone(),
|
||||
region: birth.region.clone(),
|
||||
geonames_id: birth.geonames_id,
|
||||
latitude: birth.latitude,
|
||||
longitude: birth.longitude,
|
||||
timezone: birth.timezone.clone(),
|
||||
});
|
||||
|
||||
// The chart of the solar return moment at the place: given in UTC, so no
|
||||
// local-time ambiguity can move it.
|
||||
let ts = timestamp_of(start)?;
|
||||
let utc = Offset::UTC.to_datetime(ts);
|
||||
let probe = NatalRequest {
|
||||
name: None,
|
||||
date: utc.date().to_string(),
|
||||
time: Some(utc.time().strftime("%H:%M:%S").to_string()),
|
||||
calendar: natal::Calendar::Gregorian,
|
||||
country: location.country.clone(),
|
||||
place: location.place.clone(),
|
||||
region: location.region.clone(),
|
||||
geonames_id: location.geonames_id,
|
||||
latitude: location.latitude,
|
||||
longitude: location.longitude,
|
||||
elevation: None,
|
||||
timezone: None,
|
||||
utc_offset: Some("+00:00".into()),
|
||||
ambiguous_time: Default::default(),
|
||||
options,
|
||||
};
|
||||
let mut chart = natal::calculate(state, probe).map_err(|e| e.for_person("location"))?;
|
||||
chart.time.notes.clear();
|
||||
let place = &chart.location;
|
||||
let zone = state
|
||||
.atlas
|
||||
.choose_zone(
|
||||
&place.country,
|
||||
location.timezone.as_deref(),
|
||||
place.place.as_ref(),
|
||||
(place.latitude, place.longitude),
|
||||
)?
|
||||
.zone;
|
||||
let tz = state.atlas.zones.get(&zone)?;
|
||||
let offset = tz.to_offset(ts);
|
||||
let local = tz.to_datetime(ts);
|
||||
|
||||
let forecast =
|
||||
calculate_forecast(engine, &natal.chart, start, end, f64::from(offset.seconds()) / 3600.0).map_err(calc)?;
|
||||
|
||||
let solar_return = natal.time.time_known.then(|| {
|
||||
let cusps = natal.chart.houses.as_ref().map(|h| {
|
||||
let mut c = [0.0; 12];
|
||||
for (x, cusp) in c.iter_mut().zip(&h.cusps) {
|
||||
*x = cusp.position.longitude;
|
||||
}
|
||||
c
|
||||
});
|
||||
let asc = chart.chart.angles.as_ref().map(|a| a.ascendant.position.longitude);
|
||||
SolarReturn {
|
||||
moment_utc: ts.to_string(),
|
||||
local_time: local.strftime("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||
timezone: zone.clone(),
|
||||
utc_offset: format_offset(offset),
|
||||
natal_house_of_ascendant: cusps.zip(asc).map(|(c, a)| house_of(a, &c)),
|
||||
chart,
|
||||
}
|
||||
});
|
||||
|
||||
Ok(ForecastResponse { year: req.year, solar_return, location, forecast, meta: natal::meta(state) })
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
//! `horoscope-api healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod error;
|
||||
mod forecast;
|
||||
mod natal;
|
||||
mod routes;
|
||||
mod synastry;
|
||||
|
||||
@@ -14,6 +14,7 @@ use tracing::Level;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::ApiError;
|
||||
use crate::forecast::{self, ForecastRequest, ForecastResponse};
|
||||
use crate::natal::{self, NatalRequest, NatalResponse};
|
||||
use crate::synastry::{self, SynastryRequest, SynastryResponse};
|
||||
|
||||
@@ -28,6 +29,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/timezones", get(timezones))
|
||||
.route("/v1/natal", post(natal_chart))
|
||||
.route("/v1/synastry", post(synastry_chart))
|
||||
.route("/v1/forecast", post(forecast_year))
|
||||
.layer(cors())
|
||||
.layer(
|
||||
TraceLayer::new_for_http()
|
||||
@@ -154,3 +156,14 @@ async fn synastry_chart(
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))??;
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
async fn forecast_year(
|
||||
State(state): State<Arc<AppState>>,
|
||||
body: Result<Json<ForecastRequest>, JsonRejection>,
|
||||
) -> AppResult<ForecastResponse> {
|
||||
let Json(request) = body?;
|
||||
let response = tokio::task::spawn_blocking(move || forecast::calculate(&state, request))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))??;
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
@@ -273,3 +273,48 @@ async fn synastry_unknown_time_and_errors() {
|
||||
let (status, _) = call("POST", "/v1/synastry", Some(json!({"person1": {"date": "1985-07-14"}}))).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forecast_year_with_solar_return() {
|
||||
let birth = json!({"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"});
|
||||
let (status, d) = call("POST", "/v1/forecast", Some(json!({"birth": birth, "year": 2026}))).await;
|
||||
assert_eq!(status, StatusCode::OK, "{d}");
|
||||
let sr = &d["solar_return"];
|
||||
assert_eq!(sr["timezone"], "Europe/Budapest");
|
||||
assert!(sr["local_time"].as_str().unwrap().starts_with("2026-07-14T"), "{sr}");
|
||||
assert_eq!(sr["utc_offset"], "+02:00");
|
||||
assert_eq!(sr["points"][0]["sign"], "cancer");
|
||||
assert!(sr["natal_house_of_ascendant"].as_u64().is_some());
|
||||
assert_eq!(sr["location"]["place"]["name"], "Budapest");
|
||||
let f = &d["forecast"];
|
||||
assert_eq!(f["start"], "2026-07-14");
|
||||
assert_eq!(f["age"], 41);
|
||||
assert_eq!(f["profection"]["lord"], "mars");
|
||||
assert!(!f["transits"].as_array().unwrap().is_empty());
|
||||
|
||||
// Elsewhere on the birthday: same moment, other houses.
|
||||
let (status, e) = call(
|
||||
"POST",
|
||||
"/v1/forecast",
|
||||
Some(json!({"birth": birth, "year": 2026, "location": {"country": "JP", "place": "Tokyo"}})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "{e}");
|
||||
assert_eq!(e["solar_return"]["moment_utc"], sr["moment_utc"]);
|
||||
assert_eq!(e["solar_return"]["timezone"], "Asia/Tokyo");
|
||||
assert_ne!(e["solar_return"]["angles"]["ascendant"]["sign"], sr["angles"]["ascendant"]["sign"]);
|
||||
|
||||
// Unknown birth time: no solar return chart, the rest is there.
|
||||
let (status, u) = call(
|
||||
"POST",
|
||||
"/v1/forecast",
|
||||
Some(json!({"birth": {"date": "1985-07-14", "country": "HU", "place": "Budapest"}, "year": 2026})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "{u}");
|
||||
assert!(u["solar_return"].is_null());
|
||||
assert!(u["forecast"]["profection"].is_null());
|
||||
|
||||
let (status, _) = call("POST", "/v1/forecast", Some(json!({"birth": birth, "year": 1985}))).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user