Files
sorsfonalak/services/horoscope-api/src/forecast.rs
T

166 lines
6.1 KiB
Rust
Raw Normal View History

//! `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) })
}