Weekly horoscope: its own page, a Monday e-mail, and one page for every e-mail setting
- The week's sky on the member's own chart (horoscope-api POST /v1/week, astro_engine::week): the planets' aspects to the natal points with the day each is exact, positions, the Moon's signs, lunar phases, stations and sign changes; stored once per chart and week (weekly_skies, migration 0047). - Its text is a 'weekly' analysis written by the summary's (cheap) model when the member opens /heti-horoszkop: one month per page, the newest week first, the waiting animation while it is written. In the menu, and linked from the chart page. - Monday 7:00 e-mail (worker task 'weekly'): only that it is there; on by default for everyone with a chart, members of today too. Its footer opens /ertesitesek?token=…, where the weekly e-mail and every forum e-mail can be set without logging in; the mail client's one-click unsubscribe turns off the weekly one. Also a switch on the page and on the Profile page. - Privacy notice (HU/EN) describes it; ratings, admin labels and the model page know the new kind. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -28,6 +28,10 @@ pub enum Kind {
|
||||
/// A detailed analysis of a famous person's chart, about them in the third
|
||||
/// person, for the public pages (the name comes with the data, see [`with_name`]).
|
||||
Celebrity,
|
||||
/// The free weekly horoscope: the week's sky on the member's own chart, a
|
||||
/// title and a few paragraphs. Written by the summary's model; its prompt
|
||||
/// is not edited on the admin page (so it is not in [`Kind::ALL`]).
|
||||
Weekly,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
@@ -44,6 +48,7 @@ impl Kind {
|
||||
Kind::Forecast => "forecast",
|
||||
Kind::Question => "question",
|
||||
Kind::Celebrity => "celebrity",
|
||||
Kind::Weekly => "weekly",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +60,7 @@ impl Kind {
|
||||
"forecast" => Some(Kind::Forecast),
|
||||
"question" => Some(Kind::Question),
|
||||
"celebrity" => Some(Kind::Celebrity),
|
||||
"weekly" => Some(Kind::Weekly),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -153,7 +159,7 @@ fn sections_in(kind: Kind, language: &str) -> Vec<(&'static str, &'static str)>
|
||||
Kind::Natal | Kind::Celebrity => &NATAL_SECTIONS_HU,
|
||||
Kind::Synastry => &SYNASTRY_SECTIONS_HU,
|
||||
Kind::Forecast => &FORECAST_SECTIONS_HU,
|
||||
Kind::Summary | Kind::Question => &[],
|
||||
Kind::Summary | Kind::Question | Kind::Weekly => &[],
|
||||
};
|
||||
sections(kind).iter().zip(hu).map(|(&(key, en), &hu)| (key, if language == "hu" { hu } else { en })).collect()
|
||||
}
|
||||
@@ -163,7 +169,7 @@ fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
|
||||
Kind::Natal | Kind::Celebrity => &NATAL_SECTIONS,
|
||||
Kind::Synastry => &SYNASTRY_SECTIONS,
|
||||
Kind::Forecast => &FORECAST_SECTIONS,
|
||||
Kind::Summary | Kind::Question => &[],
|
||||
Kind::Summary | Kind::Question | Kind::Weekly => &[],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,6 +190,17 @@ pub fn schema(kind: Kind) -> Value {
|
||||
}
|
||||
});
|
||||
}
|
||||
if kind == Kind::Weekly {
|
||||
return json!({
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["title", "text"],
|
||||
"properties": {
|
||||
"title": {"type": "string", "description": "Short, evocative title for this week (at most 6 words)"},
|
||||
"text": {"type": "string", "description": "3 short paragraphs separated by a blank line, 150-220 words in all"}
|
||||
}
|
||||
});
|
||||
}
|
||||
if kind == Kind::Summary {
|
||||
return json!({
|
||||
"type": "object",
|
||||
@@ -269,6 +286,13 @@ fn hungarian_system(kind: Kind) -> String {
|
||||
előrejelzés kb. 1500–2000 szó.",
|
||||
),
|
||||
Kind::Question => unreachable!("questions have their own prompt"),
|
||||
Kind::Weekly => (
|
||||
"személyes heti horoszkópot (a hét égboltja az olvasó saját születési képletén; ingyenes, hétfőnként új)",
|
||||
SECOND_PERSON_HU,
|
||||
"Terjedelem: 3 rövid bekezdés, összesen 150–220 szó. Az első a hét fő témája a két-három legerősebb \
|
||||
tranzitból; a második a hét kulcsnapjai (a hét napjainak nevével: „szerdán”, „a hét végén”); a harmadik \
|
||||
egy konkrét, a hétre szóló javaslat. Ne sorold fel az összes tranzitot.",
|
||||
),
|
||||
Kind::Celebrity => (
|
||||
"portrét egy híres ember születési képletéről (az olvasó nem ő maga, hanem egy érdeklődő látogató)",
|
||||
THIRD_PERSON_HU,
|
||||
@@ -315,6 +339,9 @@ használhatsz.
|
||||
if kind == Kind::Celebrity {
|
||||
text.push_str(CELEBRITY_RULES_HU);
|
||||
}
|
||||
if kind == Kind::Weekly {
|
||||
text.push_str(WEEKLY_RULES_HU);
|
||||
}
|
||||
text.push_str(HUNGARIAN_TERMS);
|
||||
if kind == Kind::Forecast {
|
||||
text.push_str(HUNGARIAN_FORECAST_TERMS);
|
||||
@@ -341,6 +368,23 @@ rajzolódik ki, aki…”), mert lehet, hogy már nem él. Ne állíts semmit az
|
||||
kijelentést.
|
||||
- Az „advice” mező nem neki szóló tanács, hanem zárógondolat: egy bekezdés, amely összefogja a portrét.";
|
||||
|
||||
const WEEKLY_RULES_HU: &str = "
|
||||
|
||||
A heti horoszkóp szabályai:
|
||||
- Ez nem jellemrajz, hanem a hétről szól: a születési képletet csak ott említsd, ahol egy tranzit érinti.
|
||||
- Úgy súlyozz, ahogy egy asztrológus: a lassú bolygók (Jupitertől a Plútóig) tranzitjai a hét háttere; a gyors \
|
||||
bolygók pontos fényszögei a Napra, a Holdra, az Aszcendensre, az MC-re és a horoszkóp uralkodójára a hét eseményes \
|
||||
napjai; a Hold jegyváltásai a hét hangulatának hullámzása; az újhold, a telihold és a retrográd fordulók csak akkor \
|
||||
hangsúlyosak, ha a képletet érintik.
|
||||
- Témákról, hangulatokról és lehetőségekről írj, ne biztos eseményekről: „jó nap arra, hogy”, „hozhat”, „azt kéri \
|
||||
tőled”. Semmit betegségről, halálról, balesetről, terhességről, pénz nyereségéről vagy elvesztéséről. A feszült \
|
||||
fényszögeket is kihívásként és lehetőségként írd le, ne riogass.
|
||||
- Csak az adatokban szereplő napokat használd. A napokat a hét napjainak nevével említsd (hétfő, kedd, …), \
|
||||
dátumszám nélkül.
|
||||
- Ne reklámozz, és ne említs más elemzést vagy szolgáltatást.
|
||||
- Kifejezések: tranzit („a Mars tranzitja a Napod felett”), retrográd, újhold, telihold, a Hold jegyváltása. A \
|
||||
születési képlet pontjait „a születési Vénuszod”, „a Holdad” formában említsd, ne „natális”-ként.";
|
||||
|
||||
const FORECAST_RULES_HU: &str = "
|
||||
|
||||
Az előrejelzés szabályai:
|
||||
@@ -408,6 +452,10 @@ pub fn default_system(kind: Kind, language: &str) -> String {
|
||||
}
|
||||
let (role, reader) = match kind {
|
||||
Kind::Question => unreachable!("questions have their own prompt"),
|
||||
Kind::Weekly => (
|
||||
"a personal weekly horoscope (the week's sky on the reader's own natal chart; free, new every Monday)",
|
||||
"Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
|
||||
),
|
||||
Kind::Celebrity => (
|
||||
"a portrait of a famous person's natal chart (the reader is not that person but an interested visitor)",
|
||||
"Write about them in the third person singular, by name: the full name in the summary, later also the \
|
||||
@@ -455,6 +503,9 @@ and no medical, legal or financial advice.
|
||||
length = match kind {
|
||||
Kind::Forecast => "Length: each section 2-4 paragraphs (about 150-250 words), the timeline exactly 4 \
|
||||
paragraphs; the whole forecast about 1500-2000 words.",
|
||||
Kind::Weekly => "Length: 3 short paragraphs, 150-220 words in all. The first is the main theme of the \
|
||||
week from the two or three strongest transits; the second the key days (by weekday name: \"on \
|
||||
Wednesday\", \"at the weekend\"); the third one concrete suggestion for the week. Do not list every transit.",
|
||||
Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \
|
||||
(if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \
|
||||
a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \
|
||||
@@ -468,9 +519,25 @@ and no medical, legal or financial advice.
|
||||
if kind == Kind::Celebrity {
|
||||
text.push_str(CELEBRITY_RULES);
|
||||
}
|
||||
if kind == Kind::Weekly {
|
||||
text.push_str(WEEKLY_RULES);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
const WEEKLY_RULES: &str = "
|
||||
|
||||
Weekly horoscope rules:
|
||||
- This is not a portrait but the week: mention the natal chart only where a transit touches it.
|
||||
- Weigh as an astrologer would: the slow planets' transits (Jupiter to Pluto) are the background of the week; the \
|
||||
fast planets' exact aspects to the Sun, Moon, Ascendant, Midheaven and chart ruler mark its eventful days; the Moon's \
|
||||
sign changes are the ebb and flow of the mood; new and full moons and stations matter where they touch the chart.
|
||||
- Write about themes, moods and opportunities, never certain events: \"a good day to\", \"may bring\", \"asks you \
|
||||
to\". Nothing about illness, death, accidents, pregnancy, or winning or losing money. Describe tense aspects as \
|
||||
challenges and chances, without alarm.
|
||||
- Use only the days in the data, and name them by weekday (Monday, Tuesday, ...), without dates.
|
||||
- No sales talk, and do not mention any other analysis or service.";
|
||||
|
||||
const CELEBRITY_RULES: &str = "
|
||||
|
||||
Rules for a famous person's portrait:
|
||||
@@ -651,6 +718,8 @@ pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>)
|
||||
user.push_str(chart_text);
|
||||
if kind == Kind::Summary {
|
||||
user.push_str(if hu { "\nMost írd meg a rövid összefoglalót." } else { "\nWrite the short summary now." });
|
||||
} else if kind == Kind::Weekly {
|
||||
user.push_str(if hu { "\nMost írd meg a heti horoszkópot." } else { "\nWrite the weekly horoscope now." });
|
||||
} else {
|
||||
user.push_str(if hu {
|
||||
"\nA megírandó fejezetek ebben a sorrendben (JSON-kulcs: tartalom):\n"
|
||||
@@ -672,6 +741,7 @@ pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>)
|
||||
Kind::Summary => "chart_summary",
|
||||
Kind::Question => "question_answer",
|
||||
Kind::Forecast => "forecast_analysis",
|
||||
Kind::Weekly => "weekly_horoscope",
|
||||
},
|
||||
schema: schema(kind),
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn date_of(jd_ut: f64, offset_hours: f64) -> String {
|
||||
}
|
||||
|
||||
/// The zodiac of the natal chart, geocentric (transits are not topocentric).
|
||||
fn frame_of(natal: &NatalChart) -> Frame {
|
||||
pub(crate) fn frame_of(natal: &NatalChart) -> Frame {
|
||||
let o = natal.settings.options;
|
||||
Frame { sidereal: (o.zodiac == ZodiacType::Sidereal).then_some(o.ayanamsa), topocentric: None }
|
||||
}
|
||||
@@ -70,7 +70,7 @@ fn natal_lon(natal: &NatalChart, id: PointId) -> Option<f64> {
|
||||
natal.points.iter().find(|p| p.id == id).map(|p| p.position.longitude)
|
||||
}
|
||||
|
||||
fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
||||
pub(crate) fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
||||
let houses = natal.houses.as_ref()?;
|
||||
let mut cusps = [0.0; 12];
|
||||
for (c, h) in cusps.iter_mut().zip(&houses.cusps) {
|
||||
@@ -82,7 +82,7 @@ fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
||||
/// The natal points transits and progressions are measured to: the ten
|
||||
/// planets and, with a known birth time, the Ascendant and the Midheaven.
|
||||
/// Without a birth time the Moon is left out (it may be 7° off).
|
||||
fn natal_targets(natal: &NatalChart) -> Vec<(PointId, f64)> {
|
||||
pub(crate) fn natal_targets(natal: &NatalChart) -> Vec<(PointId, f64)> {
|
||||
let known = natal.angles.is_some();
|
||||
let mut out: Vec<(PointId, f64)> = Body::PLANETS
|
||||
.iter()
|
||||
@@ -129,15 +129,15 @@ type Window = (f64, f64);
|
||||
type Crossings = (Vec<Window>, Vec<(f64, bool)>);
|
||||
|
||||
/// Longitude and daily motion sampled at equal steps.
|
||||
struct Samples {
|
||||
pub(crate) struct Samples {
|
||||
start: f64,
|
||||
step: f64,
|
||||
lon: Vec<f64>,
|
||||
speed: Vec<f64>,
|
||||
pub(crate) lon: Vec<f64>,
|
||||
pub(crate) speed: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Samples {
|
||||
fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
|
||||
pub(crate) fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
|
||||
let n = ((to - from) / step).ceil() as usize + 1;
|
||||
let mut lon = Vec::with_capacity(n);
|
||||
let mut speed = Vec::with_capacity(n);
|
||||
@@ -149,7 +149,7 @@ impl Samples {
|
||||
Ok(Self { start: from, step, lon, speed })
|
||||
}
|
||||
|
||||
fn jd(&self, i: usize) -> f64 {
|
||||
pub(crate) fn jd(&self, i: usize) -> f64 {
|
||||
self.start + i as f64 * self.step
|
||||
}
|
||||
}
|
||||
@@ -230,22 +230,30 @@ pub struct Contact {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub house: Option<u8>,
|
||||
#[serde(skip)]
|
||||
peak_jd: f64,
|
||||
pub(crate) peak_jd: f64,
|
||||
}
|
||||
|
||||
/// One year of a natal chart.
|
||||
struct Year<'a> {
|
||||
engine: &'a dyn Ephemeris,
|
||||
natal: &'a NatalChart,
|
||||
frame: Frame,
|
||||
start: f64,
|
||||
end: f64,
|
||||
offset: f64,
|
||||
cusps: Option<[f64; 12]>,
|
||||
/// What counts as a contact: the orb, the aspects, and whether the periods
|
||||
/// within orb are listed.
|
||||
pub(crate) struct ContactRule<'a> {
|
||||
pub(crate) orb: f64,
|
||||
pub(crate) aspects: &'a [AspectKind],
|
||||
pub(crate) with_periods: bool,
|
||||
}
|
||||
|
||||
/// One year of a natal chart (or any shorter span: see [`crate::week`]).
|
||||
pub(crate) struct Year<'a> {
|
||||
pub(crate) engine: &'a dyn Ephemeris,
|
||||
pub(crate) natal: &'a NatalChart,
|
||||
pub(crate) frame: Frame,
|
||||
pub(crate) start: f64,
|
||||
pub(crate) end: f64,
|
||||
pub(crate) offset: f64,
|
||||
pub(crate) cusps: Option<[f64; 12]>,
|
||||
}
|
||||
|
||||
impl Year<'_> {
|
||||
fn date(&self, jd: f64) -> String {
|
||||
pub(crate) fn date(&self, jd: f64) -> String {
|
||||
date_of(jd, self.offset)
|
||||
}
|
||||
|
||||
@@ -254,17 +262,17 @@ impl Year<'_> {
|
||||
}
|
||||
|
||||
/// Contacts of one moving planet (sampled in `s`) with the natal points.
|
||||
fn contacts(
|
||||
pub(crate) fn contacts(
|
||||
&self,
|
||||
planet: PointId,
|
||||
s: &Samples,
|
||||
lon_at: &dyn Fn(f64) -> Result<f64>,
|
||||
targets: &[(PointId, f64)],
|
||||
with_periods: bool,
|
||||
rule: &ContactRule,
|
||||
) -> Result<Vec<Contact>> {
|
||||
let mut out = Vec::new();
|
||||
for &(natal_point, natal) in targets {
|
||||
for aspect in ASPECTS {
|
||||
for &aspect in rule.aspects {
|
||||
let a = aspect.angle();
|
||||
let mut points = vec![natal + a];
|
||||
if a != 0.0 && a != 180.0 {
|
||||
@@ -272,7 +280,7 @@ impl Year<'_> {
|
||||
}
|
||||
let (mut windows, mut exact) = (Vec::new(), Vec::new());
|
||||
for target in points {
|
||||
let (w, e) = crossings(s, target, ORB, lon_at)?;
|
||||
let (w, e) = crossings(s, target, rule.orb, lon_at)?;
|
||||
windows.extend(w);
|
||||
exact.extend(e);
|
||||
}
|
||||
@@ -289,7 +297,7 @@ impl Year<'_> {
|
||||
.map(|i| (i, separation(s.lon[i], natal)))
|
||||
.map(|(i, sep)| (i, (sep - a).abs()))
|
||||
.min_by(|x, y| x.1.total_cmp(&y.1))
|
||||
.unwrap_or((0, ORB));
|
||||
.unwrap_or((0, rule.orb));
|
||||
let (peak_jd, min_orb) = match exact.first() {
|
||||
Some(&(jd, _)) => (jd, 0.0),
|
||||
None => (s.jd(closest_i), closest),
|
||||
@@ -301,7 +309,7 @@ impl Year<'_> {
|
||||
aspect,
|
||||
nature: aspect.nature(),
|
||||
exact: exact.iter().map(|&(jd, retrograde)| Exact { date: self.date(jd), retrograde }).collect(),
|
||||
periods: if with_periods {
|
||||
periods: if rule.with_periods {
|
||||
windows
|
||||
.iter()
|
||||
.map(|&(from, to)| DateRange { start: self.date(from), end: self.date(to) })
|
||||
@@ -319,7 +327,7 @@ impl Year<'_> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn position(&self, body: Body, jd: f64) -> Result<(f64, f64)> {
|
||||
pub(crate) fn position(&self, body: Body, jd: f64) -> Result<(f64, f64)> {
|
||||
let s = self.engine.position(body, jd, &self.frame)?;
|
||||
Ok((s.longitude, s.speed_longitude))
|
||||
}
|
||||
@@ -333,7 +341,8 @@ impl Year<'_> {
|
||||
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
||||
let s = Samples::take(self.start - MARGIN_DAYS, self.end + MARGIN_DAYS, 1.0, &at)?;
|
||||
let planet = PointId::from_planet(body);
|
||||
contacts.extend(self.contacts(planet, &s, &lon_at, &targets, true)?);
|
||||
let rule = ContactRule { orb: ORB, aspects: &ASPECTS, with_periods: true };
|
||||
contacts.extend(self.contacts(planet, &s, &lon_at, &targets, &rule)?);
|
||||
if let Some(cusps) = self.cusps {
|
||||
houses.push(self.house_changes(planet, &s, &cusps));
|
||||
}
|
||||
@@ -378,7 +387,8 @@ impl Year<'_> {
|
||||
// A progressed planet meeting its own natal place only matters for the Moon (the progressed lunar return).
|
||||
let own: Vec<(PointId, f64)> =
|
||||
targets.iter().copied().filter(|&(id, _)| id != planet || body == Body::Moon).collect();
|
||||
contacts.extend(self.contacts(planet, &s, &lon_at, &own, false)?);
|
||||
let rule = ContactRule { orb: ORB, aspects: &ASPECTS, with_periods: false };
|
||||
contacts.extend(self.contacts(planet, &s, &lon_at, &own, &rule)?);
|
||||
}
|
||||
let start = ZodiacPosition::new(s.lon[0]);
|
||||
let mut sign_changes = Vec::new();
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
//! [`chart`] and is independent of the engine, so the engine can be replaced
|
||||
//! without touching the chart logic. [`synastry`] compares two charts;
|
||||
//! [`forecast`] looks at one year of a chart (solar return, transits,
|
||||
//! progressions, profection, eclipses); [`sky`] is the sky by date, the same
|
||||
//! for everyone (lunar phases, retrograde periods).
|
||||
//! progressions, profection, eclipses); [`week`] is one week of a chart (the
|
||||
//! weekly horoscope); [`sky`] is the sky by date, the same for everyone (lunar
|
||||
//! phases, retrograde periods).
|
||||
|
||||
pub mod angle;
|
||||
pub mod chart;
|
||||
@@ -17,6 +18,7 @@ pub mod sky;
|
||||
pub mod synastry;
|
||||
pub mod time;
|
||||
pub mod types;
|
||||
pub mod week;
|
||||
|
||||
#[cfg(feature = "swisseph")]
|
||||
pub mod swiss;
|
||||
@@ -29,3 +31,4 @@ pub use engine::{
|
||||
pub use forecast::{Forecast, calculate_forecast, solar_return};
|
||||
pub use synastry::{Synastry, calculate_synastry};
|
||||
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
|
||||
pub use week::{Week, calculate_week};
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//! One week of a natal chart, for the weekly horoscope: the planets' aspects
|
||||
//! to the natal points during the week (with the day each is exact), where
|
||||
//! the planets stand at the start, the Moon's sign changes, the main lunar
|
||||
//! phases, and the planets' stations and sign changes.
|
||||
//!
|
||||
//! The aspects use the yearly forecast's machinery ([`crate::forecast`]) on a
|
||||
//! seven-day span, with the Sun to Pluto as the moving planets (the Moon
|
||||
//! would touch every natal point in a week, so only its signs are given).
|
||||
//! Dates are calendar days at a fixed UTC offset given by the caller.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::chart::{AspectKind, NatalChart, PointId, ZodiacPosition, house_of};
|
||||
use crate::engine::{EngineError, Ephemeris};
|
||||
use crate::forecast::{Contact, ContactRule, Samples, Year, cusps_of, frame_of, natal_targets};
|
||||
use crate::sky::{LunationKind, RETROGRADING, lunations, moon_ingresses, stations};
|
||||
use crate::types::{Body, ZodiacSign};
|
||||
|
||||
type Result<T> = std::result::Result<T, EngineError>;
|
||||
|
||||
/// The moving planets: everything but the Moon.
|
||||
const MOVING: [Body; 9] = [
|
||||
Body::Sun,
|
||||
Body::Mercury,
|
||||
Body::Venus,
|
||||
Body::Mars,
|
||||
Body::Jupiter,
|
||||
Body::Saturn,
|
||||
Body::Uranus,
|
||||
Body::Neptune,
|
||||
Body::Pluto,
|
||||
];
|
||||
/// The major aspects only: a week has room for the strong themes.
|
||||
const ASPECTS: [AspectKind; 5] =
|
||||
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
|
||||
/// Orb of a contact, degrees: within it at some time during the week.
|
||||
pub const WEEK_ORB: f64 = 1.0;
|
||||
/// Sampling step, days (Mercury moves at most about 2° a day).
|
||||
const STEP: f64 = 0.25;
|
||||
/// Days sampled around the week, so a pass beginning before it is found whole.
|
||||
const MARGIN_DAYS: f64 = 20.0;
|
||||
|
||||
/// A planet at the start of the week.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct WeekPosition {
|
||||
pub planet: PointId,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
pub retrograde: bool,
|
||||
/// Natal house (birth time known).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
/// A planet (or the Moon) entering a sign.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct WeekIngress {
|
||||
pub date: String,
|
||||
pub planet: PointId,
|
||||
pub sign: ZodiacSign,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
/// A new moon, quarter or full moon.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct WeekLunation {
|
||||
pub date: String,
|
||||
pub kind: LunationKind,
|
||||
/// Where the Moon is.
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
/// A planet standing still before turning retrograde or direct.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct WeekStation {
|
||||
pub date: String,
|
||||
pub planet: PointId,
|
||||
pub retrograde: bool,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
}
|
||||
|
||||
/// One week of a natal chart.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Week {
|
||||
/// First and last day (Monday and Sunday).
|
||||
pub start: String,
|
||||
pub end: String,
|
||||
/// The planets' aspects to the natal points, by their peak inside the week.
|
||||
pub contacts: Vec<Contact>,
|
||||
pub positions: Vec<WeekPosition>,
|
||||
/// The Moon's sign at the start, and its sign changes.
|
||||
pub moon_sign: ZodiacSign,
|
||||
pub moon_ingresses: Vec<WeekIngress>,
|
||||
/// The other planets' sign changes.
|
||||
pub ingresses: Vec<WeekIngress>,
|
||||
pub lunations: Vec<WeekLunation>,
|
||||
pub stations: Vec<WeekStation>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The week from `start_jd` (the first moment of Monday) to `end_jd` (the
|
||||
/// first moment of the next Monday); dates are given at `offset_hours` from UTC.
|
||||
pub fn calculate_week(
|
||||
engine: &dyn Ephemeris,
|
||||
natal: &NatalChart,
|
||||
start_jd: f64,
|
||||
end_jd: f64,
|
||||
offset_hours: f64,
|
||||
) -> Result<Week> {
|
||||
if end_jd <= start_jd || end_jd - start_jd > 8.0 {
|
||||
return Err(EngineError::Calculation("a week is at most eight days".into()));
|
||||
}
|
||||
let span = Year {
|
||||
engine,
|
||||
natal,
|
||||
frame: frame_of(natal),
|
||||
start: start_jd,
|
||||
// The next Monday's first moment belongs to the next week.
|
||||
end: end_jd - 1.0 / 86_400.0,
|
||||
offset: offset_hours,
|
||||
cusps: cusps_of(natal),
|
||||
};
|
||||
let house = |lon: f64| span.cusps.as_ref().map(|c| house_of(lon, c));
|
||||
// The last day is the day before the next Monday.
|
||||
let last_day = span.date(end_jd - 0.5 / 24.0);
|
||||
let targets = natal_targets(natal);
|
||||
let rule = ContactRule { orb: WEEK_ORB, aspects: &ASPECTS, with_periods: false };
|
||||
|
||||
let mut contacts = Vec::new();
|
||||
let mut positions = Vec::new();
|
||||
let mut ingresses = Vec::new();
|
||||
for body in MOVING {
|
||||
let at = |jd: f64| span.position(body, jd);
|
||||
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
||||
let s = Samples::take(start_jd - MARGIN_DAYS, end_jd + MARGIN_DAYS, STEP, &at)?;
|
||||
let planet = PointId::from_planet(body);
|
||||
contacts.extend(span.contacts(planet, &s, &lon_at, &targets, &rule)?);
|
||||
|
||||
let (lon, speed) = at(start_jd)?;
|
||||
positions.push(WeekPosition {
|
||||
planet,
|
||||
position: ZodiacPosition::new(lon),
|
||||
retrograde: speed < 0.0,
|
||||
house: house(lon),
|
||||
});
|
||||
// Sign changes inside the week, to the sample (a few hours).
|
||||
for i in 1..s.lon.len() {
|
||||
let jd = s.jd(i);
|
||||
if jd <= start_jd || jd > end_jd {
|
||||
continue;
|
||||
}
|
||||
let sign = ZodiacSign::from_longitude(s.lon[i]);
|
||||
if sign != ZodiacSign::from_longitude(s.lon[i - 1]) {
|
||||
ingresses.push(WeekIngress { date: span.date(jd), planet, sign, house: house(s.lon[i]) });
|
||||
}
|
||||
}
|
||||
}
|
||||
contacts.sort_by(|a, b| a.peak_jd.total_cmp(&b.peak_jd));
|
||||
|
||||
let moon_start = span.position(Body::Moon, start_jd)?.0;
|
||||
let moon_ingresses = moon_ingresses(engine, start_jd, end_jd)?
|
||||
.into_iter()
|
||||
.map(|(jd, sign)| {
|
||||
let lon = span.position(Body::Moon, jd + 1.0 / 24.0).map(|(l, _)| l).unwrap_or(sign.index() as f64 * 30.0);
|
||||
WeekIngress { date: span.date(jd), planet: PointId::Moon, sign, house: house(lon) }
|
||||
})
|
||||
.collect();
|
||||
let lunations = lunations(engine, start_jd, end_jd)?
|
||||
.into_iter()
|
||||
.map(|l| WeekLunation {
|
||||
date: span.date(l.jd_ut),
|
||||
kind: l.kind,
|
||||
position: ZodiacPosition::new(l.moon_longitude),
|
||||
house: house(l.moon_longitude),
|
||||
})
|
||||
.collect();
|
||||
let mut week_stations = Vec::new();
|
||||
for body in RETROGRADING {
|
||||
for st in stations(engine, body, start_jd, end_jd)? {
|
||||
week_stations.push(WeekStation {
|
||||
date: span.date(st.jd_ut),
|
||||
planet: PointId::from_planet(body),
|
||||
retrograde: st.retrograde,
|
||||
position: ZodiacPosition::new(st.longitude),
|
||||
});
|
||||
}
|
||||
}
|
||||
week_stations.sort_by(|a, b| a.date.cmp(&b.date));
|
||||
ingresses.sort_by(|a, b| a.date.cmp(&b.date));
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
if natal.angles.is_none() {
|
||||
warnings
|
||||
.push("Birth time unknown: no houses or angles, and the natal Moon is left out of the contacts.".into());
|
||||
}
|
||||
Ok(Week {
|
||||
start: span.date(start_jd),
|
||||
end: last_day,
|
||||
contacts,
|
||||
positions,
|
||||
moon_sign: ZodiacSign::from_longitude(moon_start),
|
||||
moon_ingresses,
|
||||
ingresses,
|
||||
lunations,
|
||||
stations: week_stations,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
@@ -217,3 +217,37 @@ fn solar_return_and_forecast() {
|
||||
assert!(f.eclipses.iter().any(|e| e.date == "2026-08-28"));
|
||||
serde_json::to_string(&f).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_week() {
|
||||
use astro_engine::calculate_week;
|
||||
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: true, options: ChartOptions::default() };
|
||||
let natal = calculate_chart(engine(), &input).unwrap();
|
||||
// Monday 30 November 2026, 0:00 in Budapest (UTC+1), to the next Monday.
|
||||
let start = 2_461_374.5 - 1.0 / 24.0;
|
||||
assert_eq!(astro_engine::forecast::date_of(start, 1.0), "2026-11-30");
|
||||
let w = calculate_week(engine(), &natal, start, start + 7.0, 1.0).unwrap();
|
||||
assert_eq!((w.start.as_str(), w.end.as_str()), ("2026-11-30", "2026-12-06"));
|
||||
assert_eq!(w.positions.len(), 9);
|
||||
assert!(w.positions.iter().all(|p| p.house.is_some()));
|
||||
// Every contact is within orb during the week, with its peak and exact hits inside it.
|
||||
assert!(!w.contacts.is_empty());
|
||||
for c in &w.contacts {
|
||||
assert!(c.min_orb <= 1.0, "{c:?}");
|
||||
assert!(c.peak.as_str() >= w.start.as_str() && c.peak.as_str() <= w.end.as_str(), "{c:?}");
|
||||
assert!(c.exact.iter().all(|e| e.date >= w.start && e.date <= w.end), "{c:?}");
|
||||
assert_ne!(c.planet, astro_engine::chart::PointId::Moon);
|
||||
}
|
||||
// The Moon changes sign every two or three days, each time into the next sign.
|
||||
assert!((2..=4).contains(&w.moon_ingresses.len()), "{:?}", w.moon_ingresses);
|
||||
let mut sign = w.moon_sign;
|
||||
for i in &w.moon_ingresses {
|
||||
assert_eq!(i.sign.index(), (sign.index() + 1) % 12);
|
||||
sign = i.sign;
|
||||
}
|
||||
// About one main lunar phase a week.
|
||||
assert!((1..=2).contains(&w.lunations.len()), "{:?}", w.lunations);
|
||||
let json = serde_json::to_value(&w).unwrap();
|
||||
assert!(json["contacts"][0]["planet"].is_string());
|
||||
assert!(json["positions"][0]["sign"].is_string());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
-- The free weekly horoscope: the week's sky on a member's own chart (from
|
||||
-- the horoscope service), its text (an analysis of kind 'weekly', written by
|
||||
-- the summary's model), and the Monday e-mail that says it is there (on for
|
||||
-- everyone, the members of today too; it can be turned off).
|
||||
|
||||
CREATE TABLE weekly_skies (
|
||||
chart_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||
-- The chart's data when it was calculated: new birth data, new week sky.
|
||||
chart_hash text NOT NULL,
|
||||
-- The Monday the week starts on (Hungarian time).
|
||||
week_start date NOT NULL,
|
||||
result jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (chart_id, chart_hash, week_start)
|
||||
);
|
||||
|
||||
ALTER TABLE analyses ADD COLUMN week_start date;
|
||||
|
||||
ALTER TABLE analyses DROP CONSTRAINT analyses_kind_check;
|
||||
ALTER TABLE analyses ADD CONSTRAINT analyses_kind_check
|
||||
CHECK (kind IN ('natal', 'synastry', 'summary', 'forecast', 'tarot', 'celebrity', 'weekly'));
|
||||
|
||||
ALTER TABLE analyses DROP CONSTRAINT analyses_target;
|
||||
ALTER TABLE analyses ADD CONSTRAINT analyses_target CHECK (
|
||||
(kind IN ('natal', 'summary', 'celebrity') AND chart_id IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND forecast_id IS NULL)
|
||||
OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
|
||||
OR (kind = 'tarot' AND tarot IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||
OR (kind = 'weekly' AND chart_id IS NOT NULL AND week_start IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||
);
|
||||
|
||||
-- The Monday e-mail: on unless the member turns it off. The token opens the
|
||||
-- page of every e-mail setting from an e-mail's footer (no login needed).
|
||||
ALTER TABLE users ADD COLUMN weekly_email boolean NOT NULL DEFAULT true;
|
||||
ALTER TABLE users ADD COLUMN weekly_email_sent_on date;
|
||||
ALTER TABLE users ADD COLUMN email_token uuid NOT NULL DEFAULT gen_random_uuid();
|
||||
CREATE UNIQUE INDEX users_email_token ON users (email_token);
|
||||
@@ -182,6 +182,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
|
||||
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
||||
("gift", _) => gift(lang, payload, url)?,
|
||||
("gift_package", _) => gift_package(lang, payload, url)?,
|
||||
("weekly_horoscope", _) => weekly_horoscope(lang, payload, url)?,
|
||||
// The forum is Hungarian only.
|
||||
("forum_reply", _) => forum_reply(payload, url)?,
|
||||
("forum_digest", _) => forum_digest(payload, url)?,
|
||||
@@ -602,6 +603,117 @@ fn name(payload: &Value, field: &str) -> Option<String> {
|
||||
(!name.is_empty()).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// Monday's notice that the weekly horoscope is there: only that, the text
|
||||
/// itself is read on the site after logging in.
|
||||
fn weekly_horoscope(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let start = field(payload, "week_start")?;
|
||||
let end = field(payload, "week_end")?;
|
||||
let range = week_range(lang, &start, &end).ok_or(TemplateError::MissingField("week_start"))?;
|
||||
let greeting = match (lang, name(payload, "display_name")) {
|
||||
(Lang::Hu, Some(n)) => format!("Szia {n}!"),
|
||||
(Lang::Hu, None) => "Szia!".to_owned(),
|
||||
(Lang::En, Some(n)) => format!("Hi {n},"),
|
||||
(Lang::En, None) => "Hi,".to_owned(),
|
||||
};
|
||||
let unsubscribe_url = field(payload, "unsubscribe_url")?;
|
||||
let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
|
||||
Ok(match lang {
|
||||
Lang::Hu => Content {
|
||||
subject: "Itt a heti horoszkópod".into(),
|
||||
preheader: Some(format!("{range}: belépés után a Heti horoszkóp oldalon olvashatod.")),
|
||||
greeting,
|
||||
intro: format!(
|
||||
"Itt a heti horoszkópod {} {range} közötti hétre. Belépés után a Heti horoszkóp oldalon olvashatod.",
|
||||
// "az április 6–12.", "a november 30."
|
||||
if range.starts_with(['a', 'á', 'e', 'é', 'i', 'í', 'o', 'ó', 'ö', 'ő', 'u', 'ú', 'ü', 'ű']) {
|
||||
"az"
|
||||
} else {
|
||||
"a"
|
||||
}
|
||||
),
|
||||
quote: None,
|
||||
points: None,
|
||||
code: None,
|
||||
button: "Megnézem",
|
||||
url,
|
||||
note: "A saját képletedből és a hét égboltjából készül.".into(),
|
||||
reason: Some(
|
||||
"Azért kapod ezt a levelet, mert van képleted a Sorsfonalakon. Ha nem kéred, az alábbi linken vagy a \
|
||||
Profil oldalon kikapcsolhatod."
|
||||
.into(),
|
||||
),
|
||||
unsubscribe: Some(("Leiratkozás, értesítések beállítása", unsubscribe_url)),
|
||||
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||
},
|
||||
Lang::En => Content {
|
||||
subject: "Your weekly horoscope is here".into(),
|
||||
preheader: Some(format!("{range}: log in to read it on the Weekly horoscope page.")),
|
||||
greeting,
|
||||
intro: format!(
|
||||
"Your weekly horoscope for {range} is here. Log in to read it on the Weekly horoscope page."
|
||||
),
|
||||
quote: None,
|
||||
points: None,
|
||||
code: None,
|
||||
button: "Read it",
|
||||
url,
|
||||
note: "It is written from your own chart and the week's sky.".into(),
|
||||
reason: Some(
|
||||
"You get this e-mail because you have a chart on Sorsfonalak. If you do not want it, turn it off with \
|
||||
the link below or on your Profile page."
|
||||
.into(),
|
||||
),
|
||||
unsubscribe: Some(("Unsubscribe, e-mail settings", unsubscribe_url)),
|
||||
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// "november 30. – december 6." or "december 7–13." (no year).
|
||||
fn week_range(lang: Lang, start: &str, end: &str) -> Option<String> {
|
||||
let parse = |iso: &str| -> Option<(usize, u32)> {
|
||||
let mut parts = iso.splitn(3, '-').skip(1);
|
||||
let m: usize = parts.next()?.parse().ok()?;
|
||||
let d: u32 = parts.next()?.get(..2)?.parse().ok()?;
|
||||
Some((m.checked_sub(1).filter(|&i| i < 12)?, d))
|
||||
};
|
||||
let ((m1, d1), (m2, d2)) = (parse(start)?, parse(end)?);
|
||||
const HU: [&str; 12] = [
|
||||
"január",
|
||||
"február",
|
||||
"március",
|
||||
"április",
|
||||
"május",
|
||||
"június",
|
||||
"július",
|
||||
"augusztus",
|
||||
"szeptember",
|
||||
"október",
|
||||
"november",
|
||||
"december",
|
||||
];
|
||||
const EN: [&str; 12] = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
];
|
||||
Some(match (lang, m1 == m2) {
|
||||
(Lang::Hu, true) => format!("{} {d1}–{d2}.", HU[m1]),
|
||||
(Lang::Hu, false) => format!("{} {d1}. – {} {d2}.", HU[m1], HU[m2]),
|
||||
(Lang::En, true) => format!("{d1}–{d2} {}", EN[m1]),
|
||||
(Lang::En, false) => format!("{d1} {} – {d2} {}", EN[m1], EN[m2]),
|
||||
})
|
||||
}
|
||||
|
||||
/// The confirmation of a purchase: what was bought, and that the buyer asked
|
||||
/// for immediate delivery and so gave up the 14-day withdrawal right (the
|
||||
/// confirmation 45/2014. Korm. rendelet 29. § asks for).
|
||||
@@ -1227,6 +1339,31 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weekly_horoscope_only_says_it_is_there() {
|
||||
let payload = json!({
|
||||
"url": "https://sorsfonalak.test/heti-horoszkop",
|
||||
"display_name": "Kata",
|
||||
"week_start": "2026-11-30",
|
||||
"week_end": "2026-12-06",
|
||||
"unsubscribe_url": "https://sorsfonalak.test/ertesitesek?token=abc",
|
||||
"unsubscribe_post_url": "https://sorsfonalak.test/api/v1/public/weekly/unsubscribe?token=abc",
|
||||
});
|
||||
let hu = render("weekly_horoscope", "hu", &payload).unwrap();
|
||||
assert_eq!(hu.subject, "Itt a heti horoszkópod");
|
||||
assert!(hu.text.contains("a november 30. – december 6. közötti hétre"), "{}", hu.text);
|
||||
assert!(
|
||||
hu.text.contains("Leiratkozás, értesítések beállítása: https://sorsfonalak.test/ertesitesek?token=abc")
|
||||
);
|
||||
assert!(hu.html.contains(r#"href="https://sorsfonalak.test/heti-horoszkop""#));
|
||||
assert!(hu.unsubscribe_post_url.is_some());
|
||||
let mut same_month = payload.clone();
|
||||
same_month["week_start"] = json!("2026-12-07");
|
||||
same_month["week_end"] = json!("2026-12-13");
|
||||
let en = render("weekly_horoscope", "en", &same_month).unwrap();
|
||||
assert!(en.text.contains("for 7–13 December is here"), "{}", en.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waitlist_confirmation_has_the_leave_link() {
|
||||
let hu = render("waitlist_joined", "hu", &invitation_payload()).unwrap();
|
||||
|
||||
@@ -48,6 +48,11 @@ impl HoroscopeClient {
|
||||
self.post("/v1/forecast", request).await
|
||||
}
|
||||
|
||||
/// `POST /v1/week`: one week of a natal chart (the weekly horoscope's sky).
|
||||
pub async fn week(&self, request: &Value) -> Result<Value, HoroscopeError> {
|
||||
self.post("/v1/week", request).await
|
||||
}
|
||||
|
||||
/// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon).
|
||||
pub async fn sky(&self) -> Result<Value, HoroscopeError> {
|
||||
self.get("/v1/sky", &[]).await
|
||||
|
||||
Reference in New Issue
Block a user