From 0358e137f11535d93b521719193003ec8c18eff1 Mon Sep 17 00:00:00 2001 From: feco Date: Fri, 27 Nov 2026 09:40:09 +0000 Subject: [PATCH] Weekly horoscope: its own page, a Monday e-mail, and one page for every e-mail setting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- crates/analysis-prompt/src/lib.rs | 74 +++++- crates/astro-engine/src/forecast.rs | 66 ++--- crates/astro-engine/src/lib.rs | 7 +- crates/astro-engine/src/week.rs | 214 +++++++++++++++++ crates/astro-engine/tests/swiss_reference.rs | 34 +++ .../db/migrations/0047_weekly_horoscope.sql | 37 +++ crates/email-templates/src/lib.rs | 137 +++++++++++ crates/horoscope-client/src/lib.rs | 5 + deploy/docker-compose.yml | 5 +- docs/heti-horoszkop.md | 49 ++++ services/backend/src/models.rs | 3 +- services/backend/src/routes/account.rs | 7 + services/backend/src/routes/analyses.rs | 37 ++- services/backend/src/routes/charts.rs | 3 +- services/backend/src/routes/feedback.rs | 2 +- services/backend/src/routes/mod.rs | 9 +- services/backend/src/routes/notifications.rs | 131 ++++++++++ services/backend/src/routes/weekly.rs | 227 ++++++++++++++++++ services/backend/src/tests.rs | 149 +++++++++++- .../frontend/src/app/adatvedelem/page.tsx | 23 +- .../frontend/src/app/admin/hibak/ErrorLog.tsx | 1 + .../src/app/admin/modellek/AdminModels.tsx | 6 +- .../src/app/admin/modellek/RunningJobs.tsx | 1 + .../src/app/ertesitesek/MailSettings.tsx | 214 +++++++++++++++++ .../frontend/src/app/ertesitesek/page.tsx | 24 ++ services/frontend/src/app/globals.css | 25 +- .../src/app/heti-horoszkop/WeeklyPage.tsx | 151 ++++++++++++ .../frontend/src/app/heti-horoszkop/page.tsx | 46 ++++ .../frontend/src/app/kepletek/[id]/page.tsx | 9 + services/frontend/src/app/privacy/page.tsx | 15 +- services/frontend/src/app/profil/page.tsx | 13 + services/frontend/src/components/NavIcon.tsx | 8 + .../frontend/src/components/SiteHeader.tsx | 3 +- .../src/components/WeeklyHoroscope.tsx | 155 ++++++++++++ services/frontend/src/lib/feedback.ts | 1 + services/frontend/src/lib/types.ts | 10 +- services/horoscope-api/src/main.rs | 1 + services/horoscope-api/src/routes.rs | 13 + services/horoscope-api/src/tests.rs | 27 +++ services/horoscope-api/src/week.rs | 63 +++++ services/worker/src/analysis/compact.rs | 143 +++++++++++ services/worker/src/analysis/mod.rs | 30 ++- services/worker/src/config.rs | 19 +- services/worker/src/main.rs | 12 + services/worker/src/tests.rs | 158 +++++++++++- services/worker/src/weekly.rs | 71 ++++++ 46 files changed, 2368 insertions(+), 70 deletions(-) create mode 100644 crates/astro-engine/src/week.rs create mode 100644 crates/db/migrations/0047_weekly_horoscope.sql create mode 100644 docs/heti-horoszkop.md create mode 100644 services/backend/src/routes/notifications.rs create mode 100644 services/backend/src/routes/weekly.rs create mode 100644 services/frontend/src/app/ertesitesek/MailSettings.tsx create mode 100644 services/frontend/src/app/ertesitesek/page.tsx create mode 100644 services/frontend/src/app/heti-horoszkop/WeeklyPage.tsx create mode 100644 services/frontend/src/app/heti-horoszkop/page.tsx create mode 100644 services/frontend/src/components/WeeklyHoroscope.tsx create mode 100644 services/horoscope-api/src/week.rs create mode 100644 services/worker/src/weekly.rs diff --git a/crates/analysis-prompt/src/lib.rs b/crates/analysis-prompt/src/lib.rs index fdc4437..09d0b6b 100644 --- a/crates/analysis-prompt/src/lib.rs +++ b/crates/analysis-prompt/src/lib.rs @@ -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), } diff --git a/crates/astro-engine/src/forecast.rs b/crates/astro-engine/src/forecast.rs index dd7f3d7..5e2da69 100644 --- a/crates/astro-engine/src/forecast.rs +++ b/crates/astro-engine/src/forecast.rs @@ -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 { 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, Vec<(f64, bool)>); /// Longitude and daily motion sampled at equal steps. -struct Samples { +pub(crate) struct Samples { start: f64, step: f64, - lon: Vec, - speed: Vec, + pub(crate) lon: Vec, + pub(crate) speed: Vec, } impl Samples { - fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result { + pub(crate) fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result { 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, #[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, targets: &[(PointId, f64)], - with_periods: bool, + rule: &ContactRule, ) -> Result> { 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(); diff --git a/crates/astro-engine/src/lib.rs b/crates/astro-engine/src/lib.rs index d87df2e..7c87fd0 100644 --- a/crates/astro-engine/src/lib.rs +++ b/crates/astro-engine/src/lib.rs @@ -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}; diff --git a/crates/astro-engine/src/week.rs b/crates/astro-engine/src/week.rs new file mode 100644 index 0000000..cd68534 --- /dev/null +++ b/crates/astro-engine/src/week.rs @@ -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 = std::result::Result; + +/// 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, +} + +/// 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, +} + +/// 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, +} + +/// 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, + pub positions: Vec, + /// The Moon's sign at the start, and its sign changes. + pub moon_sign: ZodiacSign, + pub moon_ingresses: Vec, + /// The other planets' sign changes. + pub ingresses: Vec, + pub lunations: Vec, + pub stations: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, +} + +/// 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 { + 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, + }) +} diff --git a/crates/astro-engine/tests/swiss_reference.rs b/crates/astro-engine/tests/swiss_reference.rs index 6fb876b..7942a37 100644 --- a/crates/astro-engine/tests/swiss_reference.rs +++ b/crates/astro-engine/tests/swiss_reference.rs @@ -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()); +} diff --git a/crates/db/migrations/0047_weekly_horoscope.sql b/crates/db/migrations/0047_weekly_horoscope.sql new file mode 100644 index 0000000..f9e626d --- /dev/null +++ b/crates/db/migrations/0047_weekly_horoscope.sql @@ -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); diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index 63268d5..b19717c 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -182,6 +182,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result 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 { (!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 { + 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 { + 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(); diff --git a/crates/horoscope-client/src/lib.rs b/crates/horoscope-client/src/lib.rs index 7a06085..a75b81c 100644 --- a/crates/horoscope-client/src/lib.rs +++ b/crates/horoscope-client/src/lib.rs @@ -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 { + self.post("/v1/week", request).await + } + /// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon). pub async fn sky(&self) -> Result { self.get("/v1/sky", &[]).await diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 4c8ecd0..d78b3fd 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -137,8 +137,9 @@ services: image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG_WORKER:-${TAG:-latest}} environment: DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak - # forum: the forum's digests, daily sky thread, listener e-mails, weekly summary. - WORKER_TASKS: email,cleanup,invoices,notify,forum + # forum: the forum's digests, daily sky thread, listener e-mails, weekly summary; + # weekly: Monday's e-mail about the weekly horoscope. + WORKER_TASKS: email,cleanup,invoices,notify,forum,weekly # The sky of the forum's daily thread. BACKEND_URL: http://backend:8081 # Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets. diff --git a/docs/heti-horoszkop.md b/docs/heti-horoszkop.md new file mode 100644 index 0000000..1b57920 --- /dev/null +++ b/docs/heti-horoszkop.md @@ -0,0 +1,49 @@ +# Heti horoszkóp + +Ingyenes, személyes heti szöveg a tag saját képletéből és a hét égboltjából. Hétfőtől vasárnapig tart, magyar idő szerint. + +## Az oldal + +- **Saját oldala van:** `/heti-horoszkop`, a menüben a „Képletem” után. A saját képlet oldalán, az összefoglaló alatt egy kis kártya visz ide. +- **Egy hónap egyszerre:** a hetek a hétfőjük hónapjához tartoznak, legelöl a legújabb. A „Korábbi hónap” és „Újabb hónap” gomb lapoz (`?honap=2026-10`); csak olyan hónapra visz, amelyben van szöveg, és előre csak az aktuális hónapig. +- **Készül:** az aktuális hónapban az oldal először a heti szöveget kéri (`POST /v1/weekly`). Amíg a worker írja (kb. 20 másodperc), a hét kártyáján a várakozó animáció látszik, a hónap többi hete alatta. +- **Csak a megnézett hetek:** régebbi hétnek csak akkor van szövege, ha a tag azon a héten megnyitotta az oldalt. Visszamenőleg nem készül. +- API: `GET /v1/weekly/history?month=2026-11` → `{month, current_month, this_week, weeks: [{week_start, week_end, analysis}], older, newer, email}`. Minden saját képlet hetei számítanak, mert a születési adat közben változhatott. + +## Hogyan készül + +- **A hét égboltja:** a horoscope-api `POST /v1/week` végpontja (`astro_engine::week`). Tartalma: + - a bolygók (a Naptól a Plútóig) fényszögei a születési pontokhoz, 1°-os hatásfokkal, a pontos nappal; + - hol állnak a bolygók a hét elején (jegy, születési ház, retrográd); + - a Hold jegyváltásai, a fő holdfázisok, a bolygók irányváltásai és jegyváltásai. + + A Hold fényszögei nincsenek benne, mert egy hét alatt minden pontot érint. A backend képletenként, születési adatonként és hetenként egyszer kéri le, és a `weekly_skies` táblába menti. +- **A szöveg:** egy `weekly` típusú elemzés (`analyses.week_start` a hétfő). Az összefoglaló olcsó modellje írja (az admin modellbeállításainál a „Tömör összefoglaló és heti horoszkóp”). Formája: cím, és 3 rövid bekezdés (150–220 szó): a hét fő témája, a kulcsnapok a hét napjainak nevével, és egy javaslat. Az admin promptszerkesztőben nem szerkeszthető. +- **Csak aki megnézi:** a szöveg akkor készül el, amikor a tag a héten először megnyitja a Heti horoszkóp oldalt (`POST /v1/weekly`). Így az AI-költség csak azokra jut, akik olvassák (egy szöveg kb. 1–1,5 Ft). +- **Értékelés:** a szöveg alatt ugyanaz a csillagos értékelés van, mint az elemzéseknél. Admin újraírathatja. + +## Hétfői levél + +- **Kinek:** minden tagnak, akinek van saját képlete, és nem kapcsolta ki (`users.weekly_email`, alapból bekapcsolva, a meglévő tagoknál is). +- **Mikor:** hétfőn 7 órától, hetente egyszer (`users.weekly_email_sent_on`). A worker `weekly` feladata 10 percenként nézi. Ha a worker egész hétfőn állt, az a hét kimarad. +- **Mi van benne:** csak annyi, hogy itt a heti horoszkóp, és egy gomb a Heti horoszkóp oldalra. A szöveget csak belépés után lehet elolvasni. +- **Kikapcsolás:** + - a Heti horoszkóp oldal alján lévő kapcsolóval; + - a Profil oldal „Levelek” részében; + - a levél alján lévő linkkel (`/ertesitesek?token=`, belépés nélkül); + - a levelező saját „Leiratkozás” gombjával (RFC 8058, `POST /v1/public/weekly/unsubscribe`), ez csak ezt a levelet kapcsolja ki. + + Az oldalon bekapcsolva az első levél a következő hétfőn jön, mert a heti szöveget a tag már látja. + +## Értesítések oldal + +Az `/ertesitesek?token=…` oldalon belépés nélkül beállítható minden olyan levél, amely nem egy lépéshez tartozik: + +- a heti horoszkóp hétfői levele; +- fórumtagoknál a fórum levelei, ugyanazok a beállítások, mint a fórumprofilnál (válaszok, követett szálak, privát üzenetek, említések, kísérő értesítések, heti összefoglaló). + +API: `GET` és `PUT /v1/public/notifications?token=`. A jelszóval, a vásárlással és a számlával kapcsolatos levelek mindig mennek. A „Mindenről leiratkozom” gomb mindent kikapcsol. + +## Később + +Ha a tagok rászoknak, előfizetéses lesz (havi és éves). Ehhez a `POST /v1/weekly` kap egy jogosultság-ellenőrzést; az oldal, a régi hetek és a hétfői levél maradhat. diff --git a/services/backend/src/models.rs b/services/backend/src/models.rs index 318735b..8ad0f57 100644 --- a/services/backend/src/models.rs +++ b/services/backend/src/models.rs @@ -45,7 +45,8 @@ impl Function { pub fn of(kind: Kind) -> Function { match kind { - Kind::Summary => Function::Summary, + // The weekly horoscope is written by the summary's (cheaper) model. + Kind::Summary | Kind::Weekly => Function::Summary, Kind::Question => Function::Question, Kind::Natal | Kind::Synastry | Kind::Forecast | Kind::Celebrity => Function::Analysis, } diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs index cc67e2d..80c295c 100644 --- a/services/backend/src/routes/account.rs +++ b/services/backend/src/routes/account.rs @@ -41,6 +41,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> { .await?; let replies = super::feedback::unseen_replies(&mut conn, auth.id()).await?; let nps_due = super::feedback::nps_due(&mut conn, auth.id()).await?; + let weekly_email: bool = sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1") + .bind(auth.id()) + .fetch_one(&mut *conn) + .await?; Ok(Json(json!({ "user": UserView::from(&auth.user), "providers": providers.into_iter().map(|(p,)| p).collect::>(), @@ -59,6 +63,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> { "feedback_replies_unseen": replies, // Ask the "would you recommend us?" question now. "nps_due": nps_due, + // Monday's e-mail about the weekly horoscope is on. + "weekly_email": weekly_email, }))) } @@ -169,6 +175,7 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult 'celebrity'").await?, diff --git a/services/backend/src/routes/analyses.rs b/services/backend/src/routes/analyses.rs index bf3cff7..5f1a0e6 100644 --- a/services/backend/src/routes/analyses.rs +++ b/services/backend/src/routes/analyses.rs @@ -7,7 +7,8 @@ //! instead, free of charge, so the same chart is never paid for twice. //! //! Every saved chart also gets a free short summary (`summary` kind, written -//! by `SUMMARY_MODEL`); the detailed analyses are paid. +//! by `SUMMARY_MODEL`); the detailed analyses are paid. The own chart's free +//! weekly horoscope (`weekly` kind, see [`super::weekly`]) uses the summary's model. use analysis_prompt::Kind; use axum::Json; @@ -18,7 +19,7 @@ use axum_extra::extract::WithRejection; use serde::Deserialize; use serde_json::{Value, json}; use sqlx::PgPool; -use time::OffsetDateTime; +use time::{Date, OffsetDateTime}; use uuid::Uuid; use super::auth::validate_locale; @@ -53,11 +54,14 @@ pub struct AnalysisRow { pub next_attempt_at: OffsetDateTime, /// When the current text was asked for (set again by a regeneration). pub requested_at: OffsetDateTime, + /// The Monday of a weekly horoscope. + pub week_start: Option, } pub(super) const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \ content, error, \ - credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at"; + credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at, \ + week_start"; impl AnalysisRow { pub fn view(&self) -> Value { @@ -78,6 +82,7 @@ impl AnalysisRow { "attempts": self.attempts, "next_attempt_at": rfc3339(self.next_attempt_at), "requested_at": rfc3339(self.requested_at), + "week_start": self.week_start.map(|d| d.to_string()), }) } } @@ -143,6 +148,12 @@ pub(super) enum Target { chart_id: Uuid, hash: String, }, + /// The own chart's weekly horoscope (free); `hash` covers the chart and the week. + Weekly { + chart_id: Uuid, + hash: String, + week_start: Date, + }, } async fn request( @@ -197,6 +208,11 @@ pub(super) async fn queue( Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None), Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)), Target::Celebrity { chart_id, hash } => ("celebrity", hash, Some(*chart_id), None, None), + Target::Weekly { chart_id, hash, .. } => ("weekly", hash, Some(*chart_id), None, None), + }; + let week_start = match target { + Target::Weekly { week_start, .. } => Some(*week_start), + _ => None, }; let (model, fallback) = &crate::models::models_for(state, Kind::parse(kind).expect("known kind")).await?; let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?; @@ -225,8 +241,9 @@ pub(super) async fn queue( let insert = format!( "INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \ cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at, \ - forecast_id, fallback_model) \ - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) RETURNING {ANALYSIS_COLUMNS}" + forecast_id, fallback_model, week_start) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) \ + RETURNING {ANALYSIS_COLUMNS}" ); let id = Uuid::now_v7(); @@ -263,6 +280,7 @@ pub(super) async fn queue( .bind(OffsetDateTime::now_utc()) .bind(forecast_id) .bind(fallback) + .bind(week_start) .fetch_one(&mut *tx) .await?; tx.commit().await?; @@ -288,6 +306,7 @@ pub(super) async fn queue( .bind(None::) .bind(forecast_id) .bind(fallback) + .bind(week_start) .fetch_one(&mut *tx) .await?; if let Some(unit) = unit { @@ -395,6 +414,14 @@ pub async fn request_for_forecast( /// The hash of what the analysis is about (chart, comparison or forecast), /// part of its cache key; `None` when that was deleted. pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result, sqlx::Error> { + if row.kind == "weekly" { + let hash: Option = sqlx::query_scalar("SELECT chart_hash FROM charts WHERE id = $1") + .bind(row.chart_id) + .fetch_optional(db) + .await?; + let week = row.week_start.map(|d| d.to_string()).unwrap_or_default(); + return Ok(hash.map(|h| super::weekly::target_hash(&h, &week))); + } let (query, id) = match row.kind.as_str() { "synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id), "forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id), diff --git a/services/backend/src/routes/charts.rs b/services/backend/src/routes/charts.rs index aebdf6c..aa2844e 100644 --- a/services/backend/src/routes/charts.rs +++ b/services/backend/src/routes/charts.rs @@ -349,7 +349,8 @@ async fn corrected_birth( // The user's own comparisons with the person are deleted on correction (they // no longer match), unless a paid analysis was written for one of them. let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as( - "SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed') \ + "SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind NOT IN ('summary', 'weekly') \ + AND status <> 'failed') \ OR EXISTS (SELECT 1 FROM analyses a JOIN synastries s ON s.id = a.synastry_id \ WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed') \ OR EXISTS (SELECT 1 FROM analyses a JOIN forecasts f ON f.id = a.forecast_id \ diff --git a/services/backend/src/routes/feedback.rs b/services/backend/src/routes/feedback.rs index 23b8d08..390f59c 100644 --- a/services/backend/src/routes/feedback.rs +++ b/services/backend/src/routes/feedback.rs @@ -43,7 +43,7 @@ pub const TAGS: [&str; 10] = [ "useful", ]; /// What can be rated (analysis kinds, and answers to questions). -const RATED_KINDS: [&str; 5] = ["summary", "natal", "synastry", "forecast", "tarot"]; +const RATED_KINDS: [&str; 6] = ["summary", "natal", "synastry", "forecast", "tarot", "weekly"]; const MAX_COMMENT: usize = 1000; const MAX_MESSAGE: usize = 2000; const MAX_REPLY: usize = 4000; diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 4435698..b1d8da7 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -20,6 +20,7 @@ mod invitations; mod invoices_user; mod jobs; mod models; +mod notifications; pub(crate) mod payments; mod promo; mod prompts; @@ -29,6 +30,7 @@ mod shares; pub mod sky; mod synastries; mod tarot; +mod weekly; pub use recalculate::run as recalculate; @@ -36,7 +38,7 @@ use std::sync::Arc; use axum::extract::{DefaultBodyLimit, Path, State}; use axum::http::{HeaderValue, Method, header}; -use axum::routing::{delete, get, patch, post}; +use axum::routing::{delete, get, patch, post, put}; use axum::{Json, Router}; use axum_extra::extract::WithRejection; use serde_json::{Value, json}; @@ -101,6 +103,9 @@ pub fn router(state: Arc) -> Router { .route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove)) .route("/v1/charts/{id}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart)) .route("/v1/charts/{id}/summary", post(analyses::summary_for_chart)) + .route("/v1/weekly", post(weekly::current)) + .route("/v1/weekly/email", put(weekly::set_email)) + .route("/v1/weekly/history", get(weekly::history)) .route("/v1/charts/{id}/forecasts", get(forecasts::list_for_chart).post(forecasts::create)) .route("/v1/forecasts/{id}", get(forecasts::get_one)) .route("/v1/forecasts/{id}/analyses", get(analyses::list_for_forecast).post(analyses::request_for_forecast)) @@ -145,6 +150,8 @@ pub fn router(state: Arc) -> Router { .route("/v1/public/shares/{slug}/visit", post(shares::visit)) .route("/v1/public/invites/{token}", get(synastries::public_invite)) .route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe)) + .route("/v1/public/weekly/unsubscribe", post(weekly::unsubscribe)) + .route("/v1/public/notifications", get(notifications::get_settings).put(notifications::put_settings)) .route("/v1/public/invitations/{token}", get(invitations::public_view)) .route("/v1/public/waitlist", post(invitations::join_waitlist)) .route("/v1/public/chart", post(calculator::chart)) diff --git a/services/backend/src/routes/notifications.rs b/services/backend/src/routes/notifications.rs new file mode 100644 index 0000000..e82f8d8 --- /dev/null +++ b/services/backend/src/routes/notifications.rs @@ -0,0 +1,131 @@ +//! The page of every e-mail setting, opened from an e-mail's footer with the +//! user's `email_token` (no login needed): Monday's weekly horoscope e-mail +//! and, for forum members, the forum's e-mails (the same settings as on the +//! forum profile). The e-mails that belong to something the user does +//! (password, purchase, invoice) always go, so they are not listed. + +use axum::Json; +use axum::extract::{Query, State}; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; +use uuid::Uuid; + +use super::{Body, St}; +use crate::AppState; +use crate::error::{ApiError, ApiResult}; + +#[derive(Deserialize)] +pub struct TokenQuery { + token: String, +} + +async fn user_of(state: &AppState, token: &str) -> Result { + let token = Uuid::parse_str(token.trim()).map_err(|_| ApiError::NotFound("token"))?; + let user: Option = + sqlx::query_scalar("SELECT id FROM users WHERE email_token = $1").bind(token).fetch_optional(&state.db).await?; + user.ok_or(ApiError::NotFound("token")) +} + +type ForumRow = (String, String, String, String, String, bool, bool); + +async fn settings(state: &AppState, user: Uuid) -> Result { + let weekly: bool = + sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await?; + let forum: Option = sqlx::query_as( + "SELECT email_replies, email_followed, email_messages, email_mentions, email_listener, email_weekly, listener \ + FROM forum.members WHERE user_id = $1", + ) + .bind(user) + .fetch_optional(&state.db) + .await?; + Ok(json!({ + "weekly_horoscope": weekly, + "forum": forum.map(|(replies, followed, messages, mentions, listener_mail, weekly, listener)| json!({ + "replies": replies, + "followed": followed, + "messages": messages, + "mentions": mentions, + // Only volunteer listeners get these. + "listener": listener.then_some(listener_mail), + "weekly": weekly, + })), + })) +} + +pub async fn get_settings( + State(state): St, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let user = user_of(&state, &q.token).await?; + Ok(Json(settings(&state, user).await?)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Settings { + weekly_horoscope: bool, + #[serde(default)] + forum: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ForumSettings { + replies: String, + followed: String, + messages: String, + mentions: String, + #[serde(default)] + listener: Option, + weekly: bool, +} + +fn one_of(value: &str, allowed: &[&str], what: &str) -> Result<(), ApiError> { + if allowed.contains(&value) { + Ok(()) + } else { + Err(ApiError::BadRequest(format!("{what} must be one of {}", allowed.join(", ")))) + } +} + +pub async fn put_settings( + State(state): St, + WithRejection(Query(q), _): WithRejection, ApiError>, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + let user = user_of(&state, &q.token).await?; + if let Some(f) = &req.forum { + one_of(&f.replies, &["off", "daily", "instant"], "replies")?; + one_of(&f.followed, &["off", "daily"], "followed")?; + one_of(&f.messages, &["off", "instant"], "messages")?; + one_of(&f.mentions, &["off", "instant"], "mentions")?; + if let Some(l) = &f.listener { + one_of(l, &["off", "instant"], "listener")?; + } + } + let mut tx = state.db.begin().await?; + sqlx::query("UPDATE users SET weekly_email = $2, updated_at = now() WHERE id = $1") + .bind(user) + .bind(req.weekly_horoscope) + .execute(&mut *tx) + .await?; + if let Some(f) = &req.forum { + sqlx::query( + "UPDATE forum.members SET email_replies = $2, email_followed = $3, email_messages = $4, \ + email_mentions = $5, email_listener = coalesce($6, email_listener), email_weekly = $7 \ + WHERE user_id = $1", + ) + .bind(user) + .bind(&f.replies) + .bind(&f.followed) + .bind(&f.messages) + .bind(&f.mentions) + .bind(&f.listener) + .bind(f.weekly) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(Json(settings(&state, user).await?)) +} diff --git a/services/backend/src/routes/weekly.rs b/services/backend/src/routes/weekly.rs new file mode 100644 index 0000000..77607b8 --- /dev/null +++ b/services/backend/src/routes/weekly.rs @@ -0,0 +1,227 @@ +//! The free weekly horoscope of the member's own chart: the week's sky (from +//! the horoscope service, stored per chart and week in `weekly_skies`) and its +//! text (an analysis of kind `weekly`, written by the summary's model). It is +//! asked for when the weekly horoscope page opens, so it is only written for +//! those who look; Monday's e-mail (worker; on unless turned off) says no +//! more than that it is there. The page shows one month at a time, the +//! newest week first ([`history`]). +//! +//! Weeks run from Monday to Sunday, Hungarian time. + +use axum::Json; +use axum::extract::{Query, State}; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; +use time::Date; +use uuid::Uuid; + +use super::analyses::{ANALYSIS_COLUMNS, AnalysisRow, Target, queue}; +use super::charts::{ChartRow, owned_chart}; +use super::{Body, St}; +use crate::AppState; +use crate::auth::AuthUser; +use crate::error::{ApiError, ApiResult}; + +/// The Monday of the current week in Hungary. +const THIS_MONDAY: &str = "SELECT date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date"; + +/// What a weekly text is about, for its cache key: the chart and the week. +pub fn target_hash(chart_hash: &str, week_start: &str) -> String { + format!("{chart_hash}|week|{week_start}") +} + +/// The week's sky on the chart, calculated once per chart, birth data and week. +async fn ensure_sky(state: &AppState, chart: &ChartRow, week: Date) -> Result<(), ApiError> { + let (exists,): (bool,) = sqlx::query_as( + "SELECT EXISTS (SELECT 1 FROM weekly_skies WHERE chart_id = $1 AND chart_hash = $2 AND week_start = $3)", + ) + .bind(chart.id) + .bind(&chart.chart_hash) + .bind(week) + .fetch_one(&state.db) + .await?; + if exists { + return Ok(()); + } + let mut result = state.horoscope.week(&json!({ "birth": chart.birth_data, "start": week.to_string() })).await?; + if let Some(obj) = result.as_object_mut() { + obj.remove("meta"); + } + sqlx::query( + "INSERT INTO weekly_skies (chart_id, chart_hash, week_start, result) VALUES ($1, $2, $3, $4) \ + ON CONFLICT DO NOTHING", + ) + .bind(chart.id) + .bind(&chart.chart_hash) + .bind(week) + .bind(&result) + .execute(&state.db) + .await?; + Ok(()) +} + +async fn weekly_email(state: &AppState, user: Uuid) -> Result { + sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await +} + +/// This week's horoscope of the own chart: queued if it does not exist yet +/// (or the last attempt failed); the page polls this until it is written. +pub async fn current(State(state): St, auth: AuthUser) -> ApiResult> { + let chart_id: Option = sqlx::query_scalar("SELECT id FROM charts WHERE owner_id = $1 AND is_primary") + .bind(auth.id()) + .fetch_optional(&state.db) + .await?; + let chart = owned_chart(&state.db, chart_id.ok_or(ApiError::NotFound("chart"))?, auth.id()).await?; + let week: Date = sqlx::query_scalar(THIS_MONDAY).fetch_one(&state.db).await?; + ensure_sky(&state, &chart, week).await?; + let target = Target::Weekly { + chart_id: chart.id, + hash: target_hash(&chart.chart_hash, &week.to_string()), + week_start: week, + }; + let (_, row) = queue(&state, auth.id(), &target, &auth.user.locale, None).await?; + let end = week.saturating_add(time::Duration::days(6)); + Ok(Json(json!({ + "week_start": week.to_string(), + "week_end": end.to_string(), + "analysis": row.view(), + "email": weekly_email(&state, auth.id()).await?, + }))) +} + +/// "2026-11". +fn month_key(date: Date) -> String { + format!("{:04}-{:02}", date.year(), u8::from(date.month())) +} + +/// The first day of a "2026-11" month. +fn month_start(key: &str) -> Option { + let (y, m) = key.split_once('-')?; + let month = time::Month::try_from(m.parse::().ok()?).ok()?; + Date::from_calendar_date(y.parse().ok()?, month, 1).ok() +} + +fn next_month(first: Date) -> Date { + let (y, m) = (first.year(), first.month()); + let y = if m == time::Month::December { y + 1 } else { y }; + Date::from_calendar_date(y, m.next(), 1).expect("the first of a month") +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MonthQuery { + /// "2026-11"; this month by default. + month: Option, +} + +/// One month of the member's weekly horoscopes (weeks counted by their +/// Monday), the newest first, and the months before and after that have any. +/// Only weeks the member opened have a text. +pub async fn history( + State(state): St, + auth: AuthUser, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let this_week: Date = sqlx::query_scalar(THIS_MONDAY).fetch_one(&state.db).await?; + let current = month_start(&month_key(this_week)).expect("a valid month"); + let first = match q.month.as_deref() { + Some(m) => month_start(m).ok_or_else(|| ApiError::BadRequest("month must look like 2026-11".into()))?, + None => current, + } + .min(current); + let next = next_month(first); + // Every own chart counts: the birth data may have changed meanwhile. + const MINE: &str = "kind = 'weekly' AND chart_id IN (SELECT id FROM charts WHERE owner_id = $1 AND kind = 'own')"; + let rows: Vec = sqlx::query_as(&format!( + "SELECT DISTINCT ON (week_start) {ANALYSIS_COLUMNS} FROM analyses \ + WHERE {MINE} AND week_start >= $2 AND week_start < $3 \ + ORDER BY week_start DESC, (status = 'done') DESC, created_at DESC" + )) + .bind(auth.id()) + .bind(first) + .bind(next) + .fetch_all(&state.db) + .await?; + let (older, newer): (Option, Option) = sqlx::query_as(&format!( + "SELECT (SELECT max(week_start) FROM analyses WHERE {MINE} AND week_start < $2), \ + (SELECT min(week_start) FROM analyses WHERE {MINE} AND week_start >= $3)" + )) + .bind(auth.id()) + .bind(first) + .bind(next) + .fetch_one(&state.db) + .await?; + // This month always has a page (its week is written when it opens). + let newer = newer.map(month_key).or_else(|| (first < current).then(|| month_key(current))); + let weeks: Vec = rows + .iter() + .filter_map(|r| { + let start = r.week_start?; + Some(json!({ + "week_start": start.to_string(), + "week_end": start.saturating_add(time::Duration::days(6)).to_string(), + "analysis": r.view(), + })) + }) + .collect(); + Ok(Json(json!({ + "month": month_key(first), + "current_month": month_key(current), + "this_week": this_week.to_string(), + "weeks": weeks, + "older": older.map(month_key), + "newer": newer, + "email": weekly_email(&state, auth.id()).await?, + }))) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EmailSwitch { + on: bool, +} + +/// Turns Monday's e-mail on or off. Turned on, the first one comes next +/// Monday (this week's horoscope is already in front of the member). +pub async fn set_email( + State(state): St, + auth: AuthUser, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + sqlx::query(&format!( + "UPDATE users SET weekly_email = $2, \ + weekly_email_sent_on = CASE WHEN $2 THEN greatest(weekly_email_sent_on, ({THIS_MONDAY})) \ + ELSE weekly_email_sent_on END, \ + updated_at = now() \ + WHERE id = $1" + )) + .bind(auth.id()) + .bind(req.on) + .execute(&state.db) + .await?; + Ok(Json(json!({ "email": req.on }))) +} + +#[derive(Deserialize)] +pub struct TokenQuery { + token: String, +} + +/// "No more weekly horoscope e-mails", straight from the mail client's +/// unsubscribe button (RFC 8058 one-click POST); the footer link opens the +/// page of every e-mail setting ([`super::notifications`]). No login needed. +pub async fn unsubscribe( + State(state): St, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let token = Uuid::parse_str(q.token.trim()).map_err(|_| ApiError::NotFound("token"))?; + let done = sqlx::query("UPDATE users SET weekly_email = false, updated_at = now() WHERE email_token = $1") + .bind(token) + .execute(&state.db) + .await?; + if done.rows_affected() == 0 { + return Err(ApiError::NotFound("token")); + } + Ok(Json(json!({ "unsubscribed": true }))) +} diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 3b9c77c..2e72442 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -90,6 +90,23 @@ async fn fake_forecast(Json(body): Json) -> (StatusCode, Json) { ) } +/// Calls of the fake week endpoint (only `weekly_horoscope_of_the_own_chart` uses it). +static WEEK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +async fn fake_week(Json(body): Json) -> (StatusCode, Json) { + WEEK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let start = body["start"].as_str().unwrap_or("2026-11-30").to_string(); + ( + StatusCode::OK, + Json(json!({ + "timezone": "Europe/Budapest", + "week": {"start": start, "end": "?", "contacts": [], "positions": [], "moon_sign": "leo", + "moon_ingresses": [], "ingresses": [], "lunations": [], "stations": []}, + "meta": {} + })), + ) +} + /// 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); @@ -254,6 +271,7 @@ async fn fake_services_with(s3: FakeS3) -> String { ) .route("/v1/synastry", post(fake_synastry)) .route("/v1/forecast", post(fake_forecast)) + .route("/v1/week", post(fake_week)) .route( "/v1/sky", get(|| async { @@ -1107,7 +1125,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; 24] = [ +const PUBLIC_ROUTES: [&str; 26] = [ "/healthz", // Stripe calls it; the signature proves it. "/v1/payments/stripe/webhook", @@ -1123,6 +1141,9 @@ const PUBLIC_ROUTES: [&str; 24] = [ "/v1/public/shares/{slug}/visit", "/v1/public/invites/{token}", "/v1/public/invitations/unsubscribe", + // The e-mail settings behind an e-mail's footer link: the token stands for the login. + "/v1/public/weekly/unsubscribe", + "/v1/public/notifications", "/v1/public/invitations/{token}", "/v1/public/waitlist", // The public birth chart (limited per visitor address). @@ -1957,6 +1978,132 @@ async fn invitation_only_signup(pool: PgPool) { assert_eq!(app.outbox_url("admin@example.com", "invitation").await, "https://sorsfonalak.test/meghivo/minta"); } +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn weekly_horoscope_of_the_own_chart(pool: PgPool) { + let app = TestApp::new(pool.clone()).await; + let anna = app.register("anna@example.com", "Anna").await; + let bob = app.register("bob@example.com", "Bob").await; + // No own chart yet: nothing to write it from. + assert_eq!(app.call("POST", "/v1/weekly", Some(&bob), None).await.status, StatusCode::NOT_FOUND); + let chart = app.chart(&anna, "Saját", true, "1990-03-15").await; + + let calls = WEEK_CALLS.load(std::sync::atomic::Ordering::Relaxed); + let r = app.call("POST", "/v1/weekly", Some(&anna), None).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let parts: Vec = r.body["week_start"].as_str().unwrap().split('-').map(|p| p.parse().unwrap()).collect(); + let month = time::Month::try_from(parts[1] as u8).unwrap(); + let start = time::Date::from_calendar_date(parts[0], month, parts[2] as u8).unwrap(); + assert_eq!(start.weekday(), time::Weekday::Monday); + assert_eq!(r.body["week_end"], start.saturating_add(time::Duration::days(6)).to_string()); + let a = &r.body["analysis"]; + assert_eq!((a["kind"].as_str(), a["status"].as_str()), (Some("weekly"), Some("pending"))); + assert_eq!((a["chart_id"].as_str(), a["credits_charged"].as_i64()), (chart["id"].as_str(), Some(0))); + assert_eq!(a["week_start"], r.body["week_start"]); + // On by default. + assert_eq!(r.body["email"], true); + // Asked again: the same text, the sky calculated once. + let again = app.call("POST", "/v1/weekly", Some(&anna), None).await.body; + assert_eq!(again["analysis"]["id"], a["id"]); + assert_eq!(WEEK_CALLS.load(std::sync::atomic::Ordering::Relaxed), calls + 1); + // Written by the summary's model; not among the chart's analyses on its page, but listed. + let (weekly_model, summary_model): (String, String) = sqlx::query_as( + "SELECT w.model, s.model FROM analyses w JOIN analyses s ON s.chart_id = w.chart_id AND s.kind = 'summary' \ + WHERE w.kind = 'weekly'", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(weekly_model, summary_model); + + // The page: one month at a time, the newest week first; older months page back. + let month = app.get("/v1/weekly/history", Some(&anna)).await.body; + assert_eq!(month["month"], month["current_month"]); + assert_eq!(month["this_week"], r.body["week_start"]); + assert_eq!(month["weeks"].as_array().unwrap().len(), 1); + assert_eq!(month["weeks"][0]["analysis"]["id"], a["id"]); + assert_eq!((month["older"].is_null(), month["newer"].is_null()), (true, true)); + let old_week = start.saturating_sub(time::Duration::days(35)); + sqlx::query( + "INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, status, \ + content, credits_charged, week_start) \ + SELECT $1, 'weekly', c.id, c.owner_id, 'hu', 'm', 'v3', 'old', 'done', '{\"title\": \"Régi hét\"}', 0, $2 \ + FROM charts c WHERE c.id = $3", + ) + .bind(uuid::Uuid::now_v7()) + .bind(old_week) + .bind(uuid::Uuid::parse_str(chart["id"].as_str().unwrap()).unwrap()) + .execute(&pool) + .await + .unwrap(); + let older_key = format!("{:04}-{:02}", old_week.year(), u8::from(old_week.month())); + let month = app.get("/v1/weekly/history", Some(&anna)).await.body; + assert_eq!(month["older"], older_key); + let back = app.get(&format!("/v1/weekly/history?month={older_key}"), Some(&anna)).await.body; + assert_eq!(back["weeks"][0]["analysis"]["content"]["title"], "Régi hét"); + assert_eq!(back["weeks"][0]["week_start"], old_week.to_string()); + assert_eq!(back["newer"], month["current_month"]); + // Not into the future; a bad month is refused; others see nothing of it. + assert_eq!(app.get("/v1/weekly/history?month=2999-01", Some(&anna)).await.body["month"], month["current_month"]); + assert_eq!(app.get("/v1/weekly/history?month=nope", Some(&anna)).await.status, StatusCode::BAD_REQUEST); + assert_eq!(app.get("/v1/weekly/history", Some(&bob)).await.body["weeks"], json!([])); + + // Monday's e-mail: off and on again from the site. + let r = app.call("PUT", "/v1/weekly/email", Some(&anna), Some(json!({"on": false}))).await; + assert_eq!((r.status, &r.body["email"]), (StatusCode::OK, &json!(false))); + assert_eq!(app.get("/v1/me", Some(&anna)).await.body["weekly_email"], false); + app.call("PUT", "/v1/weekly/email", Some(&anna), Some(json!({"on": true}))).await; + let (on, sent_on): (bool, Option) = + sqlx::query_as("SELECT weekly_email, weekly_email_sent_on FROM users WHERE email = 'anna@example.com'") + .fetch_one(&pool) + .await + .unwrap(); + // Turned on again, the first one comes next Monday. + assert_eq!((on, sent_on), (true, Some(start))); + + // The page of every e-mail setting, from the footer link (no login). + let (token,): (uuid::Uuid,) = sqlx::query_as("SELECT email_token FROM users WHERE email = 'anna@example.com'") + .fetch_one(&pool) + .await + .unwrap(); + let page = format!("/v1/public/notifications?token={token}"); + let r = app.get(&page, None).await; + assert_eq!((r.status, &r.body), (StatusCode::OK, &json!({"weekly_horoscope": true, "forum": null}))); + assert_eq!(app.get("/v1/public/notifications?token=nope", None).await.status, StatusCode::NOT_FOUND); + assert_eq!( + app.get(&format!("/v1/public/notifications?token={}", uuid::Uuid::now_v7()), None).await.status, + StatusCode::NOT_FOUND + ); + // A forum member sees the forum's e-mails too. + sqlx::query( + "INSERT INTO forum.members (user_id, nickname, nickname_key, avatar) \ + SELECT id, 'Csillag', 'csillag', 'moon-gold' FROM users WHERE email = 'anna@example.com'", + ) + .execute(&pool) + .await + .unwrap(); + let r = app.get(&page, None).await.body; + assert_eq!( + r["forum"], + json!({"replies": "daily", "followed": "off", "messages": "instant", "mentions": "instant", "listener": null, "weekly": false}) + ); + let mut forum = r["forum"].clone(); + forum["replies"] = json!("loud"); + let bad = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true, "forum": forum}))).await; + assert_eq!(bad.status, StatusCode::BAD_REQUEST); + let off = json!({"replies": "off", "followed": "off", "messages": "off", "mentions": "off", "listener": null, "weekly": false}); + let r = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": false, "forum": off}))).await; + assert_eq!((r.status, &r.body["weekly_horoscope"], &r.body["forum"]), (StatusCode::OK, &json!(false), &off)); + // The mail client's one-click unsubscribe turns off the weekly e-mail only. + app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true}))).await; + let r = app.call("POST", &format!("/v1/public/weekly/unsubscribe?token={token}"), None, None).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(app.get(&page, None).await.body["weekly_horoscope"], false); + assert_eq!( + app.call("POST", "/v1/public/weekly/unsubscribe?token=nope", None, None).await.status, + StatusCode::NOT_FOUND + ); +} + #[sqlx::test(migrator = "db::MIGRATOR")] async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) { let app = TestApp::new(pool.clone()).await; diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index 529aa71..f887d03 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -207,6 +207,17 @@ export default async function PrivacyPage() { Biztonság, hibakeresés, visszaélések kiszűrése Jogos érdek (6. cikk (1) f) + + + Heti horoszkóp: a hét égboltja a saját képleteden, a belőle írt szöveg, és hogy kéred-e a hétfői + értesítő levelet + + + Az ingyenes heti horoszkóp; hétfőnként egy rövid levél, hogy itt az új (alapból küldjük, a levél + alján, a Heti horoszkóp oldalon vagy a Profil oldalon bármikor kikapcsolhatod) + + Szerződés teljesítése; a levélnél jogos érdek (6. cikk (1) f) + Melyik oldalt nyitottad meg, honnan érkeztél, a böngésződ és az eszközöd típusa, az országod és az oldal @@ -271,7 +282,8 @@ export default async function PrivacyPage() {

Mire használjuk: a fiókod létrehozására és arra, hogy belépéskor felismerjünk; az e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed, elfogadták a meghívódat, vagy - válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted); a + válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted) és a + heti horoszkóp hétfői értesítőjéhez (ha nem kapcsoltad ki); a nevedet a megjelenítéshez; a nyelvet az oldal és az elemzések nyelvéhez.

@@ -312,10 +324,11 @@ export default async function PrivacyPage() {

4. Az elemzések és a mesterséges intelligencia

- A rövid összefoglalót, a részletes elemzéseket, a kártyajóslást és a kérdésekre adott válaszokat nagy nyelvi - modell (mesterséges intelligencia) írja. A modellhez a képlet csillagászati adatai jutnak - el (a bolygók jegye, foka, háza és fényszögei), kártyajóslásnál a kihúzott lapok, és ha kérdést teszel fel, - a kérdésed szövege. Nevet, e-mail-címet, születési dátumot, időpontot vagy helyet nem küldünk el. Kérjük, a + A rövid összefoglalót, a heti horoszkópot, a részletes elemzéseket, a kártyajóslást és a kérdésekre adott + válaszokat nagy nyelvi modell (mesterséges intelligencia) írja. A modellhez a{" "} + képlet csillagászati adatai jutnak el (a bolygók jegye, foka, háza és fényszögei), a heti + horoszkópnál a hét égboltja is (hol járnak a bolygók, és milyen fényszöget alkotnak a képleteddel), + kártyajóslásnál a kihúzott lapok, és ha kérdést teszel fel, a kérdésed szövege. Nevet, e-mail-címet, születési dátumot, időpontot vagy helyet nem küldünk el. Kérjük, a kérdéseidbe se írj neveket vagy érzékeny adatot (például egészségügyi adatot). Az elemzés szórakoztató és önismereti célú szöveg, nem minősül egészségügyi, pénzügyi, jogi vagy más szakmai tanácsnak.

diff --git a/services/frontend/src/app/admin/hibak/ErrorLog.tsx b/services/frontend/src/app/admin/hibak/ErrorLog.tsx index 38c208b..3bf75ad 100644 --- a/services/frontend/src/app/admin/hibak/ErrorLog.tsx +++ b/services/frontend/src/app/admin/hibak/ErrorLog.tsx @@ -12,6 +12,7 @@ const PAGE = 50; const SOURCES: Record = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" }; const KINDS: Record = { summary: "összefoglaló", + weekly: "heti horoszkóp", natal: "képletelemzés", synastry: "kapcsolati", forecast: "előrejelzés", diff --git a/services/frontend/src/app/admin/modellek/AdminModels.tsx b/services/frontend/src/app/admin/modellek/AdminModels.tsx index f3e8973..2513c03 100644 --- a/services/frontend/src/app/admin/modellek/AdminModels.tsx +++ b/services/frontend/src/app/admin/modellek/AdminModels.tsx @@ -9,7 +9,11 @@ import type { CatalogModel, ModelFunction } from "@/lib/types"; import { RunningJobs } from "./RunningJobs"; const LABELS: Record = { - summary: { title: "Tömör összefoglaló", about: "Ingyenes, minden új képlethez magától elkészül. Olcsó, gyors modell elég." }, + summary: { + title: "Tömör összefoglaló és heti horoszkóp", + about: + "Ingyenes: az összefoglaló minden új képlethez magától elkészül, a heti horoszkóp akkor, amikor a tag a héten megnyitja a képletét. Olcsó, gyors modell elég.", + }, analysis: { title: "Elemzések és éves előrejelzés", about: "Fizetős szövegek: részletes képletelemzés, kapcsolati elemzés és éves előrejelzés.", diff --git a/services/frontend/src/app/admin/modellek/RunningJobs.tsx b/services/frontend/src/app/admin/modellek/RunningJobs.tsx index 6413af6..bbd7d70 100644 --- a/services/frontend/src/app/admin/modellek/RunningJobs.tsx +++ b/services/frontend/src/app/admin/modellek/RunningJobs.tsx @@ -7,6 +7,7 @@ import type { AdminJob } from "@/lib/types"; const KINDS: Record = { summary: "Összefoglaló", + weekly: "Heti horoszkóp", natal: "Képletelemzés", synastry: "Kapcsolati elemzés", forecast: "Éves előrejelzés", diff --git a/services/frontend/src/app/ertesitesek/MailSettings.tsx b/services/frontend/src/app/ertesitesek/MailSettings.tsx new file mode 100644 index 0000000..7deb5d7 --- /dev/null +++ b/services/frontend/src/app/ertesitesek/MailSettings.tsx @@ -0,0 +1,214 @@ +"use client"; + +import { useEffect, useState } from "react"; + +import { api, errorText } from "@/lib/api"; + +interface ForumMail { + replies: "off" | "daily" | "instant"; + followed: "off" | "daily"; + messages: "off" | "instant"; + mentions: "off" | "instant"; + /** Only for volunteer listeners. */ + listener: "off" | "instant" | null; + weekly: boolean; +} + +interface Settings { + weekly_horoscope: boolean; + forum: ForumMail | null; +} + +/** Everything off: the weekly horoscope and every forum e-mail. */ +function allOff(s: Settings): Settings { + return { + weekly_horoscope: false, + forum: s.forum + ? { + replies: "off", + followed: "off", + messages: "off", + mentions: "off", + listener: s.forum.listener === null ? null : "off", + weekly: false, + } + : null, + }; +} + +/** + * The e-mail settings behind an e-mail's footer link: the token in the link + * stands for the login. Nothing changes until a button is pressed (mail + * providers' link scanners open every link). + */ +export function MailSettings({ token }: { token: string | null }) { + const [settings, setSettings] = useState(null); + const [loadError, setLoadError] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(null); + const query = token ? `?token=${encodeURIComponent(token)}` : ""; + + useEffect(() => { + if (!token) return; + api(`/public/notifications${query}`) + .then(setSettings) + .catch((e) => setLoadError(errorText(e))); + }, [token, query]); + + if (!token) { + return ( +

+ Hiányzik a link vége. Nyisd meg a teljes linket a levélből. +

+ ); + } + if (loadError) { + return ( +

+ Ez a link nem érvényes. Nyisd meg a teljes linket a levélből, vagy lépj be, és a Profil oldalon állítsd be. +

+ ); + } + if (!settings) { + return

Betöltés…

; + } + + async function save(next: Settings, done: string) { + setBusy(true); + setError(null); + setSaved(null); + try { + setSettings(await api(`/public/notifications${query}`, { method: "PUT", body: next })); + setSaved(done); + } catch (e) { + setError(errorText(e)); + } finally { + setBusy(false); + } + } + + const forum = settings.forum; + const setForum = (patch: Partial) => { + setSaved(null); + setSettings({ ...settings, forum: forum ? { ...forum, ...patch } : null }); + }; + + return ( +
+
+ Heti horoszkóp + +
+ + {forum && ( +
+ Fórum + + + + + + + + + {forum.listener !== null && ( + <> + + + + )} + +
+ )} + +
+ + +
+ {saved && ( +

+ {saved} +

+ )} + {error && ( +

+ {error} +

+ )} +

+ A jelszóval, a vásárlással és a számlával kapcsolatos leveleket ettől függetlenül megkapod. +

+
+ ); +} diff --git a/services/frontend/src/app/ertesitesek/page.tsx b/services/frontend/src/app/ertesitesek/page.tsx new file mode 100644 index 0000000..78d52f0 --- /dev/null +++ b/services/frontend/src/app/ertesitesek/page.tsx @@ -0,0 +1,24 @@ +import type { Metadata } from "next"; + +import { MailSettings } from "./MailSettings"; + +export const metadata: Metadata = { title: "Értesítések", robots: { index: false } }; + +/** Every e-mail setting, from the link in an e-mail's footer (no login needed). */ +export default async function MailSettingsPage({ + searchParams, +}: { + searchParams: Promise>; +}) { + const raw = (await searchParams).token; + const token = Array.isArray(raw) ? raw[0] : raw; + return ( +
+
+

Értesítések

+

Itt állíthatod be, miről kérsz levelet a Sorsfonalaktól.

+
+ +
+ ); +} diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 013a8ef..00ae6fb 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -1407,7 +1407,7 @@ span.tarot-fan-card { cursor: default; } } /* The ☰ menu: instead of the header's link rows where they no longer fit - on one line (logged out below 1240px; logged in below 1380px, with more + on one line (logged out below 1240px; logged in below 1520px, with more links and the package). */ .mobile-menu { display: none; margin-left: auto; } .mobile-menu-button { @@ -1436,7 +1436,7 @@ span.tarot-fan-card { cursor: default; } @media (max-width: 1500px) { .site-header .pkg-pill-detail { display: none; } } -@media (max-width: 1380px) { +@media (max-width: 1520px) { .mobile-menu-app { display: block; } .site-header .app-nav { display: none; } .site-header .who { margin-left: auto; } @@ -1858,3 +1858,24 @@ span.tarot-fan-card { cursor: default; } } .inapp-note p { margin: 0; color: var(--ink-2); } .inapp-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; } + +/* The weekly horoscope page (one month at a time) and its link on the chart page. */ +.weekly-card { gap: 10px; } +.weekly-text p { margin: 0 0 10px; } +.weekly-text p:last-child { margin-bottom: 0; } +.weekly-pager { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 10px; } +.weekly-pager > :first-child { justify-self: start; } +.weekly-pager > :last-child { justify-self: end; } +.weekly-pager strong { font-family: var(--font-display); font-size: 22px; font-weight: 600; text-align: center; } +.weekly-teaser { display: flex; flex-direction: column; gap: 6px; text-decoration: none; color: var(--ink-2); border-color: rgba(217, 180, 106, 0.35); } +.weekly-teaser:hover { border-color: var(--gold); } +.weekly-teaser-more { color: var(--gold); font-weight: 500; } +@media (max-width: 480px) { + .weekly-pager { grid-template-columns: 1fr 1fr; } + .weekly-pager strong { grid-column: 1 / -1; grid-row: 1; } +} + +/* The e-mail settings behind an e-mail's footer link. */ +.mail-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; min-width: 0; } +.mail-set legend { font-family: var(--font-display); font-size: 20px; font-weight: 600; margin-bottom: 4px; } +.mail-set label:not(.check) { font-size: 14px; color: var(--ink-2); margin-top: 6px; } diff --git a/services/frontend/src/app/heti-horoszkop/WeeklyPage.tsx b/services/frontend/src/app/heti-horoszkop/WeeklyPage.tsx new file mode 100644 index 0000000..1c8e182 --- /dev/null +++ b/services/frontend/src/app/heti-horoszkop/WeeklyPage.tsx @@ -0,0 +1,151 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useState } from "react"; + +import { MONTHS, WeekCard, WeeklyEmailSwitch } from "@/components/WeeklyHoroscope"; +import { api, errorText } from "@/lib/api"; +import type { Analysis } from "@/lib/types"; + +const POLL_MS = 3000; +const MAX_POLLS = 60; + +interface Week { + week_start: string; + week_end: string; + analysis: Analysis; +} + +interface Month { + month: string; + current_month: string; + this_week: string; + weeks: Week[]; + older: string | null; + newer: string | null; + email: boolean; +} + +/** "2026. november". */ +function monthName(key: string): string { + const [y, m] = key.split("-").map(Number); + return `${y}. ${MONTHS[m - 1]}`; +} + +/** + * One month of weekly horoscopes, the newest week first. In this month the + * week's horoscope is asked for first (queued if new), and polled until the + * worker has written it; meanwhile its card shows the waiting animation. + */ +export function WeeklyPage({ month, isAdmin }: { month: string | null; isAdmin: boolean }) { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [gaveUp, setGaveUp] = useState(false); + // Bumped when an admin has this week's text written again: polls anew. + const [round, setRound] = useState(0); + const query = month ? `?month=${month}` : ""; + + /** This week's horoscope into the list (it may not be there yet). */ + const putWeek = (week: Week) => + setData((d) => (d ? { ...d, weeks: [week, ...d.weeks.filter((w) => w.week_start !== week.week_start)] } : d)); + + useEffect(() => { + let stopped = false; + let timer: ReturnType | undefined; + let polls = 0; + const poll = async () => { + try { + const week = await api("/weekly", { method: "POST" }); + if (stopped) return; + putWeek({ week_start: week.week_start, week_end: week.week_end, analysis: week.analysis }); + if (week.analysis.status === "done") return; + } catch { + // try again on the next tick + } + if (++polls >= MAX_POLLS) return setGaveUp(true); + timer = setTimeout(poll, POLL_MS); + }; + (async () => { + try { + const page = await api(`/weekly/history${query}`); + if (stopped) return; + setData(page); + if (page.month === page.current_month) await poll(); + } catch (e) { + if (!stopped) setError(errorText(e)); + } + })(); + return () => { + stopped = true; + clearTimeout(timer); + }; + }, [query, round]); + + if (error) { + return ( +

+ {error} +

+ ); + } + if (!data) { + return

Betöltés…

; + } + + const restarted = (week: Week) => (a: Analysis) => { + setGaveUp(false); + setData((d) => + d ? { ...d, weeks: d.weeks.map((w) => (w.week_start === week.week_start ? { ...w, analysis: a } : w)) } : d, + ); + if (week.week_start === data.this_week) setRound((r) => r + 1); + }; + + const pager = ( + + ); + + return ( +
+ {pager} + {data.weeks.length === 0 ? ( +

Ebben a hónapban nem nézted meg a heti horoszkópodat.

+ ) : ( + data.weeks.map((w) => ( + + )) + )} + {(data.older || data.newer) && data.weeks.length > 1 && pager} +
+ +
+
+ ); +} diff --git a/services/frontend/src/app/heti-horoszkop/page.tsx b/services/frontend/src/app/heti-horoszkop/page.tsx new file mode 100644 index 0000000..bcfaf0d --- /dev/null +++ b/services/frontend/src/app/heti-horoszkop/page.tsx @@ -0,0 +1,46 @@ +import type { Metadata } from "next"; +import Link from "next/link"; + +import { requireMe } from "@/lib/server"; + +import { WeeklyPage } from "./WeeklyPage"; + +export const metadata: Metadata = { title: "Heti horoszkóp" }; + +/** + * The member's weekly horoscopes, one month at a time, the newest first + * (`?honap=2026-11` pages back). This week's is written when the page opens. + */ +export default async function WeeklyHoroscopePage({ + searchParams, +}: { + searchParams: Promise>; +}) { + const me = await requireMe("/heti-horoszkop"); + const raw = (await searchParams).honap; + const month = (Array.isArray(raw) ? raw[0] : raw) ?? null; + return ( +
+
+

Heti horoszkóp

+

Hétfőnként új, a saját képletedből és a hét égboltjából.

+
+ {me.primary_chart_id ? ( + + ) : ( +
+

A heti horoszkóphoz előbb add meg a születési adataidat.

+
+ + Születési adatok megadása + +
+
+ )} +
+ ); +} diff --git a/services/frontend/src/app/kepletek/[id]/page.tsx b/services/frontend/src/app/kepletek/[id]/page.tsx index 09cef86..04b4c16 100644 --- a/services/frontend/src/app/kepletek/[id]/page.tsx +++ b/services/frontend/src/app/kepletek/[id]/page.tsx @@ -87,6 +87,15 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri referralOpen={config?.referral_rewards ?? false} referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned} /> + {chart.id === me.primary_chart_id && ( + + Heti horoszkóp + Hétfőnként új, a saját képletedből és a hét égboltjából. + + Elolvasom a heti horoszkópomat + + + )} {forumEnabled() && (
diff --git a/services/frontend/src/app/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index 687c552..f22aed3 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -124,6 +124,11 @@ const DATA: [string, string, string][] = [ "Security, troubleshooting, preventing abuse", "Legitimate interest (Art. 6(1)(f))", ], + [ + "Weekly horoscope: the week's sky on your own chart, the text written from it, and whether you want the Monday notice e-mail", + "The free weekly horoscope; a short e-mail on Mondays that the new one is there (sent by default; turn it off at any time in the e-mail's footer, on the Weekly horoscope page or on your Profile page)", + "Performance of the contract; for the e-mail, legitimate interest (Art. 6(1)(f))", + ], [ "Which page you opened, where you came from, your browser and device type, your country and how long the page took to load (visitor statistics)", "Seeing how many people view each page and whether the site is fast enough", @@ -234,7 +239,8 @@ export default async function PrivacyPolicyPage() {

How we use it: to create your account and recognise you when you sign in; your e-mail address for service e-mails (for example when a reading is ready, an invitation was accepted, or someone replied on the - forum, when someone mentions you there, or the forum's weekly summary, if you asked for these); your name for + forum, when someone mentions you there, or the forum's weekly summary, if you asked for these) and for the + weekly horoscope's Monday notice (unless you turned it off); your name for display; your language for the language of the site and your readings.

@@ -276,10 +282,11 @@ export default async function PrivacyPolicyPage() {

4. Readings and artificial intelligence

- The short summary, the detailed readings, tarot readings and the answers to your questions are written by a - large language model (artificial intelligence). The model receives the{" "} + The short summary, the weekly horoscope, the detailed readings, tarot readings and the answers to your + questions are written by a large language model (artificial intelligence). The model receives the{" "} astronomical data of the chart (the signs, degrees, houses and aspects of the planets), for - a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail + the weekly horoscope also the week's sky (where the planets are and the aspects they make to your chart), + for a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail address, birth date, time or place. Please do not write names or sensitive data (such as health data) into your questions either. The readings are for entertainment and self-reflection and are not medical, financial, legal or other professional advice. diff --git a/services/frontend/src/app/profil/page.tsx b/services/frontend/src/app/profil/page.tsx index 98d5a56..7bdb25c 100644 --- a/services/frontend/src/app/profil/page.tsx +++ b/services/frontend/src/app/profil/page.tsx @@ -2,6 +2,7 @@ import type { Metadata } from "next"; import Link from "next/link"; import { ROLE_LABELS, formatDate } from "@/lib/astro"; +import { WeeklyEmailSwitch } from "@/components/WeeklyHoroscope"; import { backendGet, requireMe } from "@/lib/server"; import type { Chart } from "@/lib/types"; @@ -84,6 +85,18 @@ export default async function ProfilePage() { />

+
+

Levelek

+ +

+ A levélben csak annyi áll, hogy elkészült; a horoszkópot belépés után a Heti horoszkóp oldalon olvashatod. + {!chart && " Ehhez előbb add meg a születési adataidat."} +

+
+

Adataim

diff --git a/services/frontend/src/components/NavIcon.tsx b/services/frontend/src/components/NavIcon.tsx index cde4060..44cd18c 100644 --- a/services/frontend/src/components/NavIcon.tsx +++ b/services/frontend/src/components/NavIcon.tsx @@ -3,6 +3,7 @@ export type NavIconName = | "chart" + | "weekly" | "persons" | "compare" | "tarot" @@ -45,6 +46,13 @@ export function NavIcon({ name }: { name: NavIconName }) { /> )} + {name === "weekly" && ( + <> + + + + + )} {name === "famous" && ( )} diff --git a/services/frontend/src/components/SiteHeader.tsx b/services/frontend/src/components/SiteHeader.tsx index fbbdb7f..30b2050 100644 --- a/services/frontend/src/components/SiteHeader.tsx +++ b/services/frontend/src/components/SiteHeader.tsx @@ -148,11 +148,12 @@ const EXPLORE: NavItem[] = [ /** * The header of the logged-in app: the menu with gold marks (the free pages * in one "Felfedezés" dropdown), the Moon today, the package and the account. - * Below 1380px the menu moves behind ☰, grouped. + * Below 1520px the menu moves behind ☰, grouped. */ export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) { const own: NavItem[] = [ { href: "/keplet", label: "Képletem", icon: "chart" }, + { href: "/heti-horoszkop", label: "Heti horoszkóp", icon: "weekly" }, { href: "/szemelyek", label: "Személyek", icon: "persons" }, { href: "/osszevetesek", label: "Összevetések", icon: "compare" }, { href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" }, diff --git a/services/frontend/src/components/WeeklyHoroscope.tsx b/services/frontend/src/components/WeeklyHoroscope.tsx new file mode 100644 index 0000000..ff2f703 --- /dev/null +++ b/services/frontend/src/components/WeeklyHoroscope.tsx @@ -0,0 +1,155 @@ +"use client"; + +import { useEffect, useState } from "react"; + +import { api, errorText } from "@/lib/api"; +import type { Analysis } from "@/lib/types"; + +import { AnalysisLoading } from "./AnalysisLoading"; +import { RateContent } from "./RateContent"; +import { RegenerateButton } from "./RegenerateButton"; +import { RetryNotice } from "./RetryNotice"; +import { Paragraphs } from "./Rich"; + +export const MONTHS = [ + "január", + "február", + "március", + "április", + "május", + "június", + "július", + "augusztus", + "szeptember", + "október", + "november", + "december", +]; + +/** "november 30. – december 6." or "december 7–13.". */ +export function weekRange(start: string, end: string): string { + const [, m1, d1] = start.split("-").map(Number); + const [, m2, d2] = end.split("-").map(Number); + return m1 === m2 ? `${MONTHS[m1 - 1]} ${d1}–${d2}.` : `${MONTHS[m1 - 1]} ${d1}. – ${MONTHS[m2 - 1]} ${d2}.`; +} + +/** + * Monday's e-mail about the weekly horoscope, on or off. Turned on, the first + * one comes next Monday. + */ +export function WeeklyEmailSwitch({ initial, label }: { initial: boolean; label: string }) { + const [on, setOn] = useState(initial); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + useEffect(() => setOn(initial), [initial]); + + async function toggle(next: boolean) { + setBusy(true); + setError(null); + setOn(next); + try { + await api("/weekly/email", { method: "PUT", body: { on: next } }); + } catch (e) { + setOn(!next); + setError(errorText(e)); + } finally { + setBusy(false); + } + } + + return ( +

+ + {error && ( +

+ {error} +

+ )} +
+ ); +} + +/** + * One week's horoscope: the text, or while the worker writes it the waiting + * animation (this week's, the page polls it), or a note when it failed. + */ +export function WeekCard({ + start, + end, + analysis, + current = false, + gaveUp = false, + isAdmin = false, + onRestarted, +}: { + start: string; + end: string; + analysis: Analysis | null; + /** This week: marked, and it may still be written. */ + current?: boolean; + /** The page stopped waiting for it. */ + gaveUp?: boolean; + isAdmin?: boolean; + onRestarted?: (a: Analysis) => void; +}) { + const content = analysis?.status === "done" ? analysis.content : null; + const titleId = `week-${start}`; + return ( +
+ + {weekRange(start, end)} + {current && " · ez a hét"} + + {content ? ( + <> + {isAdmin && analysis && onRestarted && ( + url={`/admin/analyses/${analysis.id}/regenerate`} onStarted={onRestarted} /> + )} +

+ {content.title} +

+
+ +
+ {analysis && } + + ) : ( + <> +

+ Heti horoszkóp, {weekRange(start, end)} +

+ {gaveUp || analysis?.status === "failed" ? ( +

+ {current + ? "A heti horoszkóp most nem készült el. Töltsd újra az oldalt egy kicsit később." + : "Ez a heti horoszkóp nem készült el."} +

+ ) : ( + <> + + {analysis && ( + + )} + + )} + + )} +
+ ); +} diff --git a/services/frontend/src/lib/feedback.ts b/services/frontend/src/lib/feedback.ts index e386492..b4ff337 100644 --- a/services/frontend/src/lib/feedback.ts +++ b/services/frontend/src/lib/feedback.ts @@ -29,6 +29,7 @@ export const TAG_LABELS: Record = { export const KIND_LABELS: Record = { summary: "Rövid összefoglaló", + weekly: "Heti horoszkóp", natal: "Képletelemzés", synastry: "Kapcsolati elemzés", forecast: "Éves előrejelzés", diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index 6e1929e..4d7d37c 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -31,6 +31,8 @@ export interface Me { nps_due: boolean; /** Natal analyses earned by bringing new users through shared links. */ referral_rewards: { earned: number; limit: number }; + /** Monday's e-mail about the weekly horoscope is on. */ + weekly_email: boolean; } /** A package from the catalog (`GET /v1/packages`). */ @@ -258,7 +260,7 @@ export interface SynastryListItem { export interface Analysis { id: string; - kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity"; + kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity" | "weekly"; status: "pending" | "running" | "done" | "failed"; model: string; language: string; @@ -272,6 +274,8 @@ export interface Analysis { next_attempt_at?: string; /** When the current text was asked for: the waiting page counts from here. */ requested_at?: string; + /** The Monday of a weekly horoscope. */ + week_start?: string | null; } /** Admin: one failed attempt in the error log. */ @@ -325,7 +329,7 @@ export interface ModelFunction { export interface AdminJob { id: string; type: "analysis" | "question"; - kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity"; + kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity" | "weekly"; status: "pending" | "running"; /** The model of the current attempt. */ model: string; @@ -467,6 +471,8 @@ export interface AdminCelebrityRow { export interface AnalysisContent { title?: string; summary?: string; + /** The weekly horoscope's paragraphs. */ + text?: string; sections?: Record; strengths?: string[]; challenges?: string[]; diff --git a/services/horoscope-api/src/main.rs b/services/horoscope-api/src/main.rs index 8bdff47..c38c4fb 100644 --- a/services/horoscope-api/src/main.rs +++ b/services/horoscope-api/src/main.rs @@ -16,6 +16,7 @@ mod sky; mod synastry; #[cfg(test)] mod tests; +mod week; use std::path::PathBuf; use std::sync::Arc; diff --git a/services/horoscope-api/src/routes.rs b/services/horoscope-api/src/routes.rs index 1a186c1..45e1d4c 100644 --- a/services/horoscope-api/src/routes.rs +++ b/services/horoscope-api/src/routes.rs @@ -17,6 +17,7 @@ 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}; +use crate::week::{self, WeekRequest, WeekResponse}; type AppResult = Result, ApiError>; @@ -30,6 +31,7 @@ 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/week", post(week_of_chart)) .route("/v1/sky", get(sky_now)) .route("/v1/sky/events", get(sky_events)) .layer(cors()) @@ -167,6 +169,17 @@ async fn forecast_year( Ok(Json(response)) } +async fn week_of_chart( + State(state): State>, + body: Result, JsonRejection>, +) -> AppResult { + let Json(request) = body?; + let response = tokio::task::spawn_blocking(move || week::calculate(&state, request)) + .await + .map_err(|e| ApiError::Internal(e.to_string()))??; + Ok(Json(response)) +} + async fn sky_now( State(state): State>, query: Result, QueryRejection>, diff --git a/services/horoscope-api/src/tests.rs b/services/horoscope-api/src/tests.rs index a304f88..4f0f6ea 100644 --- a/services/horoscope-api/src/tests.rs +++ b/services/horoscope-api/src/tests.rs @@ -319,6 +319,33 @@ async fn forecast_year_with_solar_return() { assert_eq!(status, StatusCode::BAD_REQUEST); } +#[tokio::test] +async fn one_week_of_a_chart() { + let birth = json!({"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"}); + let (status, d) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-11-30"}))).await; + assert_eq!(status, StatusCode::OK, "{d}"); + assert_eq!(d["timezone"], "Europe/Budapest"); + let w = &d["week"]; + assert_eq!((w["start"].as_str(), w["end"].as_str()), (Some("2026-11-30"), Some("2026-12-06"))); + assert_eq!(w["positions"].as_array().unwrap().len(), 9); + assert!(w["positions"][0]["house"].as_u64().is_some()); + assert!(!w["moon_ingresses"].as_array().unwrap().is_empty()); + + // Unknown birth time: no houses. + let (status, u) = call( + "POST", + "/v1/week", + Some(json!({"birth": {"date": "1985-07-14", "country": "HU", "place": "Budapest"}, "start": "2026-11-30"})), + ) + .await; + assert_eq!(status, StatusCode::OK, "{u}"); + assert!(u["week"]["positions"][0]["house"].is_null()); + + // Not a Monday. + let (status, _) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-12-01"}))).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. diff --git a/services/horoscope-api/src/week.rs b/services/horoscope-api/src/week.rs new file mode 100644 index 0000000..b48c4ce --- /dev/null +++ b/services/horoscope-api/src/week.rs @@ -0,0 +1,63 @@ +//! `POST /v1/week`: one week of a natal chart, for the weekly horoscope: the +//! planets' aspects to the natal points (with the day each is exact), where +//! the planets stand, the Moon's sign changes, the lunar phases, and the +//! planets' stations and sign changes. The week runs from Monday 0:00 to the +//! next Monday on the clock of `tz` (default Europe/Budapest); the dates are +//! local days there. + +use astro_engine::{Week, calculate_week}; +use jiff::civil::Date; +use serde::{Deserialize, Serialize}; + +use crate::AppState; +use crate::error::ApiError; +use crate::natal::{self, NatalRequest}; +use crate::sky::DEFAULT_TZ; + +const UNIX_EPOCH_JD: f64 = 2_440_587.5; + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WeekRequest { + /// Birth data as for `POST /v1/natal`. + pub birth: NatalRequest, + /// The Monday the week starts on, `YYYY-MM-DD`. + pub start: String, + #[serde(default)] + pub tz: Option, +} + +#[derive(Debug, Serialize)] +pub struct WeekResponse { + pub timezone: String, + pub week: Week, +} + +fn bad(msg: impl Into) -> ApiError { + ApiError::BadRequest(msg.into()) +} + +pub fn calculate(state: &AppState, req: WeekRequest) -> Result { + let start: Date = req.start.parse().map_err(|_| bad("start must be a date (YYYY-MM-DD)"))?; + if start.weekday() != jiff::civil::Weekday::Monday { + return Err(bad("start must be a Monday")); + } + if !(1900..=2100).contains(&start.year()) { + return Err(bad("start must be between 1900 and 2100")); + } + let zone_name = req.tz.unwrap_or_else(|| DEFAULT_TZ.to_string()); + let tz = state.atlas.zones.get(&zone_name)?; + let natal = natal::calculate(state, req.birth).map_err(|e| e.for_person("birth"))?; + + let jd_at = |date: Date| -> Result<(f64, f64), ApiError> { + let zoned = date.to_zoned(tz.clone()).map_err(|e| ApiError::Internal(e.to_string()))?; + let jd = zoned.timestamp().as_second() as f64 / 86_400.0 + UNIX_EPOCH_JD; + Ok((jd, f64::from(zoned.offset().seconds()) / 3600.0)) + }; + let (start_jd, offset) = jd_at(start)?; + let next = start.checked_add(jiff::Span::new().days(7)).map_err(|e| ApiError::Internal(e.to_string()))?; + let (end_jd, _) = jd_at(next)?; + let week = calculate_week(state.engine.as_ref(), &natal.chart, start_jd, end_jd, offset) + .map_err(|e| ApiError::Calculation(e.to_string()))?; + Ok(WeekResponse { timezone: zone_name, week }) +} diff --git a/services/worker/src/analysis/compact.rs b/services/worker/src/analysis/compact.rs index c612775..6551e61 100644 --- a/services/worker/src/analysis/compact.rs +++ b/services/worker/src/analysis/compact.rs @@ -583,6 +583,149 @@ fn aspect_lines(out: &mut String, aspects: &Value, heading: &str, limit: usize) } } +/// "Wednesday 2026-12-02": a local day with its weekday (the text names days by weekday). +fn day(date: &str) -> String { + let mut parts = date.splitn(3, '-').map(str::parse::); + let weekday = match (parts.next(), parts.next(), parts.next()) { + (Some(Ok(y)), Some(Ok(m)), Some(Ok(d))) => u8::try_from(m) + .ok() + .and_then(|m| time::Month::try_from(m).ok()) + .and_then(|m| time::Date::from_calendar_date(y, m, u8::try_from(d).ok()?).ok()) + .map(|d| d.weekday().to_string()), + _ => None, + }; + weekday.map_or_else(|| date.to_string(), |w| format!("{w} {date}")) +} + +/// ", natal house 5" when the house is known. +fn house_suffix(v: &Value) -> String { + v["house"].as_i64().map(|h| format!(", natal house {h}")).unwrap_or_default() +} + +/// One week of a chart: the natal chart, then the stored week sky of the +/// horoscope service (`POST /v1/week`): where the planets stand, their +/// aspects to the natal points, the Moon's signs, lunar phases, stations and +/// sign changes. +pub fn weekly(chart: &Value, result: &Value) -> String { + let w = &result["week"]; + let mut out = format!( + "WEEK: {} to {} (local days, Hungarian time).\n\n", + day(w["start"].as_str().unwrap_or("?")), + day(w["end"].as_str().unwrap_or("?")) + ); + out.push_str(&natal(chart)); + + out.push_str("\nTHE WEEK'S SKY ON THIS CHART\n\nPlanets at the start of the week:\n"); + for p in w["positions"].as_array().into_iter().flatten() { + let retro = if p["retrograde"].as_bool() == Some(true) { ", retrograde" } else { "" }; + let _ = writeln!( + out, + "- {}: {}{retro}{}", + point_name(p["planet"].as_str().unwrap_or("?")), + position(p), + house_suffix(p) + ); + } + + out.push_str("\nTransits to the natal chart this week (orb 1°; in order of their peak):\n"); + let contacts = w["contacts"].as_array().map(Vec::as_slice).unwrap_or_default(); + if contacts.is_empty() { + out.push_str("- none\n"); + } + for c in contacts { + let planet = c["planet"].as_str().unwrap_or("?"); + let slow = ["jupiter", "saturn", "uranus", "neptune", "pluto"].contains(&planet); + let mut line = format!( + "- {} {} natal {} ({}{})", + point_name(planet), + words(c["aspect"].as_str().unwrap_or("?")), + point_name(c["natal_point"].as_str().unwrap_or("?")), + c["nature"].as_str().unwrap_or("neutral"), + if slow { ", slow planet: background of the week" } else { "" } + ); + let exact: Vec = c["exact"] + .as_array() + .into_iter() + .flatten() + .map(|e| { + let d = day(e["date"].as_str().unwrap_or("?")); + if e["retrograde"].as_bool() == Some(true) { format!("{d} (retrograde)") } else { d } + }) + .collect(); + if exact.is_empty() { + let _ = write!( + line, + ": not exact this week, closest {:.1}° around {}", + c["min_orb"].as_f64().unwrap_or(0.0), + day(c["peak"].as_str().unwrap_or("?")) + ); + } else { + let _ = write!(line, ": exact on {}", exact.join(", ")); + } + if let Some(h) = c["house"].as_i64() { + let _ = write!(line, "; {} in natal house {h}", point_name(planet)); + } + let _ = writeln!(out, "{line}"); + } + + let mut moon = + format!("\nThe Moon: in {} at the start of the week", capitalize(w["moon_sign"].as_str().unwrap_or("?"))); + for i in w["moon_ingresses"].as_array().into_iter().flatten() { + let _ = write!( + moon, + "; enters {} on {}{}", + capitalize(i["sign"].as_str().unwrap_or("?")), + day(i["date"].as_str().unwrap_or("?")), + house_suffix(i) + ); + } + let _ = writeln!(out, "{moon}."); + + let lunations = w["lunations"].as_array().map(Vec::as_slice).unwrap_or_default(); + if !lunations.is_empty() { + out.push_str("Lunar phases:\n"); + for l in lunations { + let _ = writeln!( + out, + "- {} on {} at {}{}", + capitalize(&words(l["kind"].as_str().unwrap_or("?"))), + day(l["date"].as_str().unwrap_or("?")), + position(l), + house_suffix(l) + ); + } + } + let stations = w["stations"].as_array().map(Vec::as_slice).unwrap_or_default(); + if !stations.is_empty() { + out.push_str("Stations:\n"); + for st in stations { + let turn = if st["retrograde"].as_bool() == Some(true) { "turns retrograde" } else { "turns direct" }; + let _ = writeln!( + out, + "- {} {turn} on {} at {}", + point_name(st["planet"].as_str().unwrap_or("?")), + day(st["date"].as_str().unwrap_or("?")), + position(st) + ); + } + } + let ingresses = w["ingresses"].as_array().map(Vec::as_slice).unwrap_or_default(); + if !ingresses.is_empty() { + out.push_str("Sign changes:\n"); + for i in ingresses { + let _ = writeln!( + out, + "- {} enters {} on {}{}", + point_name(i["planet"].as_str().unwrap_or("?")), + capitalize(i["sign"].as_str().unwrap_or("?")), + day(i["date"].as_str().unwrap_or("?")), + house_suffix(i) + ); + } + } + out +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/worker/src/analysis/mod.rs b/services/worker/src/analysis/mod.rs index 3118eea..fae311b 100644 --- a/services/worker/src/analysis/mod.rs +++ b/services/worker/src/analysis/mod.rs @@ -54,6 +54,8 @@ pub struct Job { pub attempts: i32, /// A tarot reading's spread, question and cards (kind `tarot`). pub tarot: Option, + /// The Monday of a weekly horoscope (kind `weekly`). + pub week_start: Option, /// The default model, when the chosen one is another (see the module docs). pub fallback_model: Option, pub on_fallback: bool, @@ -114,8 +116,8 @@ pub struct PreviewJob { /// Which analyses a claim may take. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Lane { - /// The short summary of a chart and the tarot readings (questions are - /// claimed separately). + /// The short summary of a chart, the weekly horoscope and the tarot + /// readings (questions are claimed separately). Quick, /// The detailed analyses (famous people's too) and the yearly forecast. Slow, @@ -124,7 +126,7 @@ pub enum Lane { impl Lane { fn kinds(self) -> &'static [&'static str] { match self { - Lane::Quick => &["summary", "tarot"], + Lane::Quick => &["summary", "weekly", "tarot"], Lane::Slow => &["natal", "synastry", "forecast", "celebrity"], } } @@ -165,7 +167,7 @@ impl Analyzer { AND kind = ANY($1) \ ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \ RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, prompt_version, attempts, \ - tarot, fallback_model, on_fallback, started_at", + tarot, week_start, fallback_model, on_fallback, started_at", ) .bind(lane.kinds()) .fetch_optional(&self.db) @@ -190,6 +192,7 @@ impl Analyzer { Kind::Celebrity => self.celebrity_text(job.chart_id, &job.language).await?, Kind::Synastry => self.synastry_text(job.synastry_id).await?, Kind::Forecast => self.forecast_text(job.forecast_id).await?, + Kind::Weekly => self.weekly_text(job.chart_id, job.week_start).await?, Kind::Question => return Err(LlmError::Permanent("a question is not an analysis".into())), }; let (base, revision) = prompt::split_version(&job.prompt_version); @@ -220,6 +223,21 @@ impl Analyzer { Ok(compact::natal(&chart)) } + /// A chart with the sky of one week on it (stored by the backend). + async fn weekly_text(&self, chart_id: Option, week: Option) -> Result { + let row: Option<(Value, Value)> = sqlx::query_as( + "SELECT w.result, c.result FROM weekly_skies w JOIN charts c ON c.id = w.chart_id \ + WHERE w.chart_id = $1 AND w.week_start = $2 AND w.chart_hash = c.chart_hash", + ) + .bind(chart_id) + .bind(week) + .fetch_optional(&self.db) + .await + .map_err(|e| LlmError::Transient(format!("database: {e}")))?; + let (sky, chart) = row.ok_or_else(|| LlmError::Permanent("the week's sky is missing".into()))?; + Ok(compact::weekly(&chart, &sky)) + } + /// A famous person's chart with their name in front. async fn celebrity_text(&self, chart_id: Option, language: &str) -> Result { let name: String = sqlx::query_scalar("SELECT name FROM celebrities WHERE chart_id = $1") @@ -285,7 +303,9 @@ impl Analyzer { Kind::Forecast => self.forecast_text(job.forecast_id).await?, Kind::Natal | Kind::Summary => self.natal_text(job.chart_id).await?, Kind::Celebrity => self.celebrity_text(job.chart_id, &job.language).await?, - Kind::Question => return Err(LlmError::Permanent("a question has no test run".into())), + Kind::Question | Kind::Weekly => { + return Err(LlmError::Permanent(format!("a {} text has no test run", job.kind))); + } }; let built = prompt::build(kind, &job.language, &text, Some(&job.system)); let mut c = self.llm.complete(&job.model, &built).await?; diff --git a/services/worker/src/config.rs b/services/worker/src/config.rs index 8c8866b..802cd67 100644 --- a/services/worker/src/config.rs +++ b/services/worker/src/config.rs @@ -20,13 +20,22 @@ pub struct Tasks { pub notify: bool, /// The forum's daily e-mail digest. pub forum: bool, + /// Monday's e-mail about the weekly horoscope. + pub weekly: bool, } impl Tasks { pub const ALL: Tasks = - Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true, forum: true }; - const NONE: Tasks = - Tasks { email: false, cleanup: false, analyses: false, invoices: false, notify: false, forum: false }; + Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true, forum: true, weekly: true }; + const NONE: Tasks = Tasks { + email: false, + cleanup: false, + analyses: false, + invoices: false, + notify: false, + forum: false, + weekly: false, + }; pub fn parse(raw: &str) -> anyhow::Result { let mut tasks = Self::NONE; @@ -38,9 +47,11 @@ impl Tasks { "invoices" => tasks.invoices = true, "notify" => tasks.notify = true, "forum" => tasks.forum = true, + "weekly" => tasks.weekly = true, other => { anyhow::bail!( - "unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify, forum)" + "unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify, forum, \ + weekly)" ) } } diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index cdabd74..5228b67 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -5,6 +5,7 @@ //! * hourly cleanup of expired sessions, tokens, invites and old e-mails //! * writing the requested text analyses with an LLM (OpenRouter) //! * issuing the invoices of the payments in Billingo +//! * Monday's e-mail about the weekly horoscope //! //! `WORKER_TASKS` (e.g. `email,cleanup` or `analyses`) picks the jobs of one //! process, so they can run in separate containers; all of them by default. @@ -25,6 +26,7 @@ mod invoices; mod notify; mod ses; mod telegram; +mod weekly; mod templates { pub use email_templates::*; } @@ -108,6 +110,7 @@ async fn main() -> anyhow::Result<()> { invoices = tasks.invoices, notify = tasks.notify, forum = tasks.forum, + weekly = tasks.weekly, "worker tasks" ); match &config.smtp_url { @@ -179,6 +182,15 @@ async fn main() -> anyhow::Result<()> { None => tracing::warn!("PUBLIC_BASE_URL is not set: no forum task (its e-mail links need it)"), } + match &config.public_base_url { + _ if !tasks.weekly => {} + Some(base) => { + tracing::info!("weekly horoscope e-mails enabled (Mondays)"); + jobs.spawn(weekly::run(pool.clone(), base.clone(), stop.clone())); + } + None => tracing::warn!("PUBLIC_BASE_URL is not set: no weekly horoscope e-mails (their links need it)"), + } + let app = Router::new().route("/healthz", get(healthz)).with_state(pool); let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?; tracing::info!(%addr, "worker running"); diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs index 8ffc1e1..cdf4109 100644 --- a/services/worker/src/tests.rs +++ b/services/worker/src/tests.rs @@ -352,13 +352,30 @@ fn worker_tasks_are_chosen_by_name() { let mail = Tasks::parse("email, cleanup").unwrap(); assert_eq!( mail, - Tasks { email: true, cleanup: true, analyses: false, invoices: false, notify: false, forum: false } + Tasks { + email: true, + cleanup: true, + analyses: false, + invoices: false, + notify: false, + forum: false, + weekly: false + } ); assert_eq!( Tasks::parse("analyses").unwrap(), - Tasks { email: false, cleanup: false, analyses: true, invoices: false, notify: false, forum: false } + Tasks { + email: false, + cleanup: false, + analyses: true, + invoices: false, + notify: false, + forum: false, + weekly: false + } ); assert!(Tasks::parse("email,forum").unwrap().forum); + assert!(Tasks::parse("email,forum,weekly").unwrap().weekly); assert!(Tasks::parse("email,invoices").unwrap().invoices); assert!(Tasks::parse("email,cleanup,invoices,notify").unwrap().notify); assert!(Tasks::parse("emails").is_err()); @@ -1196,4 +1213,141 @@ mod analyses { .unwrap(); assert_eq!((status.as_str(), refund.as_deref()), ("failed", Some("tarot"))); } + + /// A week sky as the horoscope service returns it (shortened). + fn week_sky() -> Value { + json!({ + "timezone": "Europe/Budapest", + "week": { + "start": "2026-11-30", "end": "2026-12-06", + "contacts": [ + {"planet": "mars", "natal_point": "sun", "aspect": "square", "nature": "tense", + "exact": [{"date": "2026-12-02", "retrograde": false}], "peak": "2026-12-02", "min_orb": 0.0, "house": 10}, + {"planet": "saturn", "natal_point": "moon", "aspect": "trine", "nature": "harmonious", + "exact": [], "peak": "2026-11-30", "min_orb": 0.4, "house": 2} + ], + "positions": [ + {"planet": "sun", "longitude": 247.8, "sign": "sagittarius", "degree_in_sign": 7.8, "retrograde": false, "house": 5} + ], + "moon_sign": "leo", + "moon_ingresses": [{"date": "2026-12-01", "planet": "moon", "sign": "virgo", "house": 11}], + "ingresses": [], + "lunations": [{"date": "2026-12-01", "kind": "last_quarter", "longitude": 159.0, "sign": "virgo", "degree_in_sign": 9.0, "house": 11}], + "stations": [] + } + }) + } + + #[sqlx::test(migrator = "db::MIGRATOR")] + async fn writes_the_weekly_horoscope(db: PgPool) { + let s = setup(&db).await; + sqlx::query("INSERT INTO weekly_skies (chart_id, chart_hash, week_start, result) VALUES ($1, 'hash1', '2026-11-30', $2)") + .bind(s.chart) + .bind(week_sky()) + .execute(&db) + .await + .unwrap(); + let id = Uuid::now_v7(); + sqlx::query( + "INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, \ + credits_charged, week_start) \ + VALUES ($1, 'weekly', $2, $3, 'hu', 'test/cheap', 'v3', 'key', 0, '2026-11-30')", + ) + .bind(id) + .bind(s.chart) + .bind(s.user) + .execute(&db) + .await + .unwrap(); + let text = json!({"title": "Lendület és türelem", "text": "Első bekezdés.\n\nMásodik.\n\nHarmadik."}); + let (fake, url) = fake_openrouter(vec![reply(&text)]).await; + let a = analyzer(&db, &url); + // A quick text: the quick lane takes it. + let job = a.claim(Lane::Quick).await.unwrap().expect("the weekly horoscope is due"); + a.handle(job).await; + let (status, content): (String, Option) = + sqlx::query_as("SELECT status, content FROM analyses WHERE id = $1").bind(id).fetch_one(&db).await.unwrap(); + assert_eq!((status.as_str(), content.unwrap()["title"].as_str()), ("done", Some("Lendület és türelem"))); + + let requests = fake.requests.lock().unwrap(); + let body = &requests[0]; + assert_eq!(body["model"], "test/cheap"); + assert_eq!(body["response_format"]["json_schema"]["name"], "weekly_horoscope"); + let system = body["messages"][0]["content"].as_str().unwrap(); + let user = body["messages"][1]["content"].as_str().unwrap(); + assert!(system.contains("heti horoszkópot") && system.contains("a hét napjainak nevével"), "{system}"); + for line in [ + "WEEK: Monday 2026-11-30 to Sunday 2026-12-06", + "- Sun: Pisces 24°42', house 8", + "- Sun: Sagittarius 7°48', natal house 5", + "- Mars square natal Sun (tense): exact on Wednesday 2026-12-02; Mars in natal house 10", + "- Saturn trine natal Moon (harmonious, slow planet: background of the week): not exact this week, closest 0.4° around Monday 2026-11-30", + "The Moon: in Leo at the start of the week; enters Virgo on Tuesday 2026-12-01, natal house 11.", + "- Last quarter on Tuesday 2026-12-01 at Virgo 9°00', natal house 11", + "Most írd meg a heti horoszkópot.", + ] { + assert!(user.contains(line), "missing {line:?} in\n{user}"); + } + for secret in ["1990", "14:30", "Szeged", "Hungary"] { + assert!(!user.contains(secret), "{secret} leaked"); + } + } +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn monday_weekly_horoscope_emails_go_once_a_week(db: PgPool) { + let monday = time::Date::from_calendar_date(2026, time::Month::November, 30).unwrap(); + let mut ids = Vec::new(); + for (email, chart, on) in + [("anna@example.com", true, true), ("bela@example.com", false, true), ("cili@example.com", true, false)] + { + let id = Uuid::now_v7(); + sqlx::query("INSERT INTO users (id, email, display_name, weekly_email) VALUES ($1, $2, 'Anna', $3)") + .bind(id) + .bind(email) + .bind(on) + .execute(&db) + .await + .unwrap(); + if chart { + sqlx::query( + "INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \ + VALUES ($1, $2, 'Saját', true, 'own', '{}', '{}', 'h')", + ) + .bind(Uuid::now_v7()) + .bind(id) + .execute(&db) + .await + .unwrap(); + } + ids.push(id); + } + // On by default: a member of today gets it too. + let (default_on,): (bool,) = + sqlx::query_as("SELECT weekly_email FROM users WHERE email = 'anna@example.com'").fetch_one(&db).await.unwrap(); + assert!(default_on); + + // Only who has a chart and did not turn it off; once a week. + assert_eq!(crate::weekly::queue_week(&db, "https://sorsfonalak.test/", monday).await.unwrap(), 1); + assert_eq!(crate::weekly::queue_week(&db, "https://sorsfonalak.test", monday).await.unwrap(), 0); + let (to, template, payload, token): (String, String, serde_json::Value, Uuid) = sqlx::query_as( + "SELECT o.to_email, o.template, o.payload, u.email_token FROM email_outbox o JOIN users u ON u.id = o.user_id", + ) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!((to.as_str(), template.as_str()), ("anna@example.com", "weekly_horoscope")); + assert_eq!(payload["url"], "https://sorsfonalak.test/heti-horoszkop"); + assert_eq!( + (payload["week_start"].as_str(), payload["week_end"].as_str()), + (Some("2026-11-30"), Some("2026-12-06")) + ); + assert_eq!(payload["unsubscribe_url"], format!("https://sorsfonalak.test/ertesitesek?token={token}")); + let mail = render(&template, "hu", &payload).unwrap(); + assert_eq!(mail.subject, "Itt a heti horoszkópod"); + assert!(mail.unsubscribe_post_url.unwrap().ends_with(&format!("/api/v1/public/weekly/unsubscribe?token={token}"))); + + // The next Monday again. + let next = monday.saturating_add(time::Duration::days(7)); + assert_eq!(crate::weekly::queue_week(&db, "https://sorsfonalak.test", next).await.unwrap(), 1); } diff --git a/services/worker/src/weekly.rs b/services/worker/src/weekly.rs new file mode 100644 index 0000000..1f9bd02 --- /dev/null +++ b/services/worker/src/weekly.rs @@ -0,0 +1,71 @@ +//! Monday's e-mail about the weekly horoscope: from 7:00 Hungarian time on +//! Mondays, every member with their own chart who has not turned it off +//! (`users.weekly_email`, on by default) gets one short notice with a link to +//! the weekly horoscope page. Its footer leads to the page of every e-mail setting. The text +//! itself is written when they open that page (the backend queues it), so the +//! e-mail says only that it is there. Once a week each (`weekly_email_sent_on`); +//! a Monday missed (the worker was down all day) is not made up later. + +use std::time::Duration; + +use sqlx::PgPool; +use tokio::sync::watch; + +/// From this hour (Hungarian time) on Mondays. +const FROM_HOUR: i32 = 7; +/// How often the job looks. +const EVERY: Duration = Duration::from_secs(600); + +pub async fn run(db: PgPool, base: String, stop: watch::Receiver) { + loop { + match send_due(&db, &base).await { + Ok(0) => {} + Ok(n) => tracing::info!(queued = n, "weekly horoscope e-mails queued"), + Err(e) => tracing::error!(error = %e, "queueing the weekly horoscope e-mails"), + } + tokio::select! { + () = tokio::time::sleep(EVERY) => {} + () = crate::stopped(stop.clone()) => break, + } + } +} + +/// Queues this Monday's e-mails that are due; how many. +pub async fn send_due(db: &PgPool, base: &str) -> Result { + // Today in Hungary, if it is a Monday past the hour. + let monday: Option = sqlx::query_scalar( + "SELECT CASE WHEN extract(isodow FROM l) = 1 AND extract(hour FROM l) >= $1 THEN l::date END \ + FROM (SELECT now() AT TIME ZONE 'Europe/Budapest' AS l) t", + ) + .bind(FROM_HOUR) + .fetch_one(db) + .await?; + let Some(monday) = monday else { return Ok(0) }; + queue_week(db, base, monday).await +} + +/// Queues the e-mail of the week starting on `monday` for everyone who gets +/// it and has not had it yet (one statement: marking and queueing go together). +pub async fn queue_week(db: &PgPool, base: &str, monday: time::Date) -> Result { + let done = sqlx::query( + "WITH due AS ( \ + UPDATE users u SET weekly_email_sent_on = $1 \ + WHERE u.weekly_email AND (u.weekly_email_sent_on IS NULL OR u.weekly_email_sent_on < $1) \ + AND EXISTS (SELECT 1 FROM charts c WHERE c.owner_id = u.id AND c.is_primary) \ + RETURNING u.id, u.email, u.locale, u.display_name, u.email_token) \ + INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) \ + SELECT gen_random_uuid(), id, email, 'weekly_horoscope', locale, jsonb_build_object( \ + 'url', $2 || '/heti-horoszkop', \ + 'display_name', display_name, \ + 'week_start', $1::text, \ + 'week_end', ($1 + 6)::text, \ + 'unsubscribe_url', $2 || '/ertesitesek?token=' || email_token, \ + 'unsubscribe_post_url', $2 || '/api/v1/public/weekly/unsubscribe?token=' || email_token) \ + FROM due", + ) + .bind(monday) + .bind(base.trim_end_matches('/')) + .execute(db) + .await?; + Ok(done.rows_affected()) +}