//! Yearly forecasts of a chart: one year of life from a solar return //! (birthday) to the next, calculated by the horoscope service for where the //! person is on the birthday. The calculation (solar return chart, transit //! timeline, progressions, profection, eclipses) is free; its detailed text //! analysis uses a `forecast` unit (see [`super::analyses`]). //! //! Users can calculate the year of life they are in, and the next one from //! [`NEXT_YEAR_DAYS`] days before the birthday; admins any year. use axum::Json; use axum::extract::State; use axum::http::StatusCode; use axum_extra::extract::WithRejection; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sqlx::PgPool; use time::{Date, Month, OffsetDateTime}; use uuid::Uuid; use super::charts::{ChartRow, find_chart, owned_chart}; use super::{Body, IdPath, St}; use crate::AppState; use crate::auth::AuthUser; use crate::error::{ApiError, ApiResult}; use crate::views::{rfc3339, sha256_hex}; use db::Role; /// The next year of life can be calculated this many days before the birthday. pub const NEXT_YEAR_DAYS: i64 = 30; /// At most this many forecasts (years and places) per chart. const MAX_PER_CHART: i64 = 20; #[derive(Debug, Clone, sqlx::FromRow)] pub struct ForecastRow { pub id: Uuid, pub chart_id: Uuid, pub year: i32, pub location: Option, pub result: Value, pub forecast_hash: String, pub created_at: OffsetDateTime, } const FORECAST_COLUMNS: &str = "id, chart_id, year, location, result, forecast_hash, created_at"; impl ForecastRow { /// Where the year is reckoned, for lists: the place name or the coordinates. fn place(&self) -> Value { let sr = &self.result["solar_return"]["location"]; let loc = &self.result["location"]; sr.pointer("/place/name").or(loc.get("place")).cloned().unwrap_or(Value::Null) } pub fn summary_view(&self) -> Value { let f = &self.result["forecast"]; json!({ "id": self.id, "chart_id": self.chart_id, "year": self.year, "start": f["start"], "end": f["end"], "place": self.place(), "birth_place": self.location.is_none(), "created_at": rfc3339(self.created_at), }) } pub fn view(&self) -> Value { let mut v = self.summary_view(); v["location"] = self.location.clone().unwrap_or(Value::Null); v["result"] = self.result.clone(); v } } pub async fn find_forecast(db: &PgPool, id: Uuid) -> Result, ApiError> { Ok(sqlx::query_as(&format!("SELECT {FORECAST_COLUMNS} FROM forecasts WHERE id = $1")) .bind(id) .fetch_optional(db) .await?) } /// A forecast of a chart of `owner`; 404 otherwise. pub async fn owned_forecast(db: &PgPool, id: Uuid, owner: Uuid) -> Result<(ForecastRow, ChartRow), ApiError> { let forecast = find_forecast(db, id).await?.ok_or(ApiError::NotFound("forecast"))?; let chart = find_chart(db, forecast.chart_id).await?.filter(|c| c.owner_id == owner); chart.map(|c| (forecast, c)).ok_or(ApiError::NotFound("forecast")) } /// The Gregorian birth date of a calculated chart. fn birth_date(chart: &ChartRow) -> Option { let text = chart.result.pointer("/time/date")?.as_str()?; let mut parts = text.split('-').map(str::parse::); let (y, m, d) = (parts.next()?.ok()?, parts.next()?.ok()?, parts.next()?.ok()?); Date::from_calendar_date(y, Month::try_from(m as u8).ok()?, d as u8).ok() } /// The birthday in a year (29 February is the 28th in common years). fn birthday(birth: Date, year: i32) -> Option { Date::from_calendar_date(year, birth.month(), birth.day()) .or_else(|_| Date::from_calendar_date(year, birth.month(), birth.day() - 1)) .ok() } /// The years (of the solar return starting them) a user can calculate on /// `today`: the current year of life, and the next one close to the birthday. pub fn open_years(birth: Date, today: Date) -> Vec { let Some(this) = birthday(birth, today.year()) else { return Vec::new() }; let current = if today >= this { today.year() } else { today.year() - 1 }; let mut years = Vec::new(); if current > birth.year() { years.push(current); } if birthday(birth, current + 1).is_some_and(|next| (next - today).whole_days() <= NEXT_YEAR_DAYS) { years.push(current + 1); } years } /// Where the person is on the birthday, as the horoscope service takes it. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct Location { country: String, #[serde(default, skip_serializing_if = "Option::is_none")] place: Option, #[serde(default, skip_serializing_if = "Option::is_none")] region: Option, #[serde(default, skip_serializing_if = "Option::is_none")] geonames_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] latitude: Option, #[serde(default, skip_serializing_if = "Option::is_none")] longitude: Option, } #[derive(Debug, Deserialize, Default)] #[serde(deny_unknown_fields)] pub struct CreateForecast { /// Defaults to the current year of life. year: Option, /// Defaults to the birth place. location: Option, } fn is_admin(auth: &AuthUser) -> bool { auth.user.has_role(Role::Admin) } /// The years open to this user for a chart (admins: also every earlier one is allowed on request). fn years_for(chart: &ChartRow) -> Vec { birth_date(chart).map(|b| open_years(b, OffsetDateTime::now_utc().date())).unwrap_or_default() } fn current_forecasts_query() -> String { format!( "SELECT {FORECAST_COLUMNS} FROM forecasts WHERE chart_id = $1 AND chart_hash = $2 ORDER BY year DESC, created_at" ) } /// The forecasts of a chart (for its current birth data) and the years that can be calculated. pub async fn list_for_chart( State(state): St, auth: AuthUser, WithRejection(axum::extract::Path(id), _): IdPath, ) -> ApiResult> { let chart = owned_chart(&state.db, id, auth.id()).await?; let rows: Vec = sqlx::query_as(¤t_forecasts_query()).bind(chart.id).bind(&chart.chart_hash).fetch_all(&state.db).await?; Ok(Json(json!({ "years": years_for(&chart), "birth_place": chart.result.pointer("/location/place/name"), "time_known": chart.result.pointer("/time/time_known"), "forecasts": rows.iter().map(ForecastRow::summary_view).collect::>(), }))) } /// Calculates a year (or returns it when already calculated). 201 or 200. pub async fn create( State(state): St, auth: AuthUser, WithRejection(axum::extract::Path(id), _): IdPath, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { let chart = owned_chart(&state.db, id, auth.id()).await?; let open = years_for(&chart); let year = match req.year { Some(y) if open.contains(&y) || is_admin(&auth) => y, Some(_) => { return Err(ApiError::Refused { code: "forecast_year_closed", message: "Az aktuális évre, és a születésnap előtti 30 napban a következőre kérhetsz előrejelzést." .into(), }); } None => *open.first().ok_or(ApiError::Refused { code: "forecast_year_closed", message: "Az első születésnap előtt még nincs éves előrejelzés.".into(), })?, }; let location = req.location.map(|l| serde_json::to_value(l).expect("serializable")); let location_key = location.as_ref().map_or_else(|| "birth".to_string(), |l| sha256_hex(&l.to_string())); let existing: Option = sqlx::query_as(&format!( "SELECT {FORECAST_COLUMNS} FROM forecasts \ WHERE chart_id = $1 AND chart_hash = $2 AND year = $3 AND location_key = $4" )) .bind(chart.id) .bind(&chart.chart_hash) .bind(year) .bind(&location_key) .fetch_optional(&state.db) .await?; if let Some(row) = existing { return Ok((StatusCode::OK, Json(row.view()))); } let (count,): (i64,) = sqlx::query_as("SELECT count(*) FROM forecasts WHERE chart_id = $1") .bind(chart.id) .fetch_one(&state.db) .await?; if count >= MAX_PER_CHART && !is_admin(&auth) { return Err(ApiError::conflict( "forecast_limit_reached", format!("at most {MAX_PER_CHART} forecasts can be saved for a chart"), )); } let (result, forecast_hash) = calculate(&state, &chart, year, location.as_ref(), &location_key).await?; let row: ForecastRow = sqlx::query_as(&format!( "INSERT INTO forecasts (id, chart_id, chart_hash, year, location, location_key, result, forecast_hash, created_by) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) \ ON CONFLICT (chart_id, chart_hash, year, location_key) DO UPDATE SET chart_id = EXCLUDED.chart_id \ RETURNING {FORECAST_COLUMNS}" )) .bind(Uuid::now_v7()) .bind(chart.id) .bind(&chart.chart_hash) .bind(year) .bind(&location) .bind(&location_key) .bind(&result) .bind(&forecast_hash) .bind(auth.id()) .fetch_one(&state.db) .await?; Ok((StatusCode::CREATED, Json(row.view()))) } /// One year of a stored chart as stored: `(result, forecast_hash)`. pub(super) async fn calculate( state: &AppState, chart: &ChartRow, year: i32, location: Option<&Value>, location_key: &str, ) -> Result<(Value, String), ApiError> { let mut request = json!({ "birth": chart.birth_data, "year": year }); if let Some(l) = location { request["location"] = l.clone(); } let mut result = state.horoscope.forecast(&request).await?; if let Some(obj) = result.as_object_mut() { obj.remove("meta"); } let hash = forecast_hash(&chart.chart_hash, year, location_key, &result); Ok((result, hash)) } /// Identifies a forecast independently of how the place was entered: the /// chart, the year and the resolved place and time zone of the solar return. fn forecast_hash(chart_hash: &str, year: i32, location_key: &str, result: &Value) -> String { let sr = &result["solar_return"]; let place = if sr.is_object() { format!( "{:.4}|{:.4}|{}", sr["location"]["latitude"].as_f64().unwrap_or_default(), sr["location"]["longitude"].as_f64().unwrap_or_default(), sr["timezone"].as_str().unwrap_or_default() ) } else { location_key.to_string() }; sha256_hex(&format!("forecast|{chart_hash}|{year}|{place}")) } pub async fn get_one( State(state): St, auth: AuthUser, WithRejection(axum::extract::Path(id), _): IdPath, ) -> ApiResult> { let (forecast, _) = owned_forecast(&state.db, id, auth.id()).await?; Ok(Json(forecast.view())) } #[cfg(test)] mod tests { use super::*; fn date(y: i32, m: u8, d: u8) -> Date { Date::from_calendar_date(y, Month::try_from(m).unwrap(), d).unwrap() } #[test] fn years_open_around_the_birthday() { let birth = date(1990, 3, 15); assert_eq!(open_years(birth, date(2026, 11, 18)), vec![2026]); assert_eq!(open_years(birth, date(2027, 3, 1)), vec![2026, 2027]); assert_eq!(open_years(birth, date(2027, 3, 15)), vec![2027]); assert_eq!(open_years(birth, date(2027, 2, 12)), vec![2026]); // Before the first birthday: only the first year, close to it. assert!(open_years(birth, date(1990, 6, 1)).is_empty()); assert_eq!(open_years(birth, date(1991, 3, 1)), vec![1991]); // 29 February assert_eq!(open_years(date(1992, 2, 29), date(2027, 2, 28)), vec![2027]); } }