Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7cc642f8b8 | ||
|
|
0358e137f1 | ||
|
|
14ed31fddc | ||
|
|
50c29e4595 |
@@ -28,6 +28,10 @@ pub enum Kind {
|
|||||||
/// A detailed analysis of a famous person's chart, about them in the third
|
/// 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`]).
|
/// person, for the public pages (the name comes with the data, see [`with_name`]).
|
||||||
Celebrity,
|
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 {
|
impl Kind {
|
||||||
@@ -44,6 +48,7 @@ impl Kind {
|
|||||||
Kind::Forecast => "forecast",
|
Kind::Forecast => "forecast",
|
||||||
Kind::Question => "question",
|
Kind::Question => "question",
|
||||||
Kind::Celebrity => "celebrity",
|
Kind::Celebrity => "celebrity",
|
||||||
|
Kind::Weekly => "weekly",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,6 +60,7 @@ impl Kind {
|
|||||||
"forecast" => Some(Kind::Forecast),
|
"forecast" => Some(Kind::Forecast),
|
||||||
"question" => Some(Kind::Question),
|
"question" => Some(Kind::Question),
|
||||||
"celebrity" => Some(Kind::Celebrity),
|
"celebrity" => Some(Kind::Celebrity),
|
||||||
|
"weekly" => Some(Kind::Weekly),
|
||||||
_ => None,
|
_ => 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::Natal | Kind::Celebrity => &NATAL_SECTIONS_HU,
|
||||||
Kind::Synastry => &SYNASTRY_SECTIONS_HU,
|
Kind::Synastry => &SYNASTRY_SECTIONS_HU,
|
||||||
Kind::Forecast => &FORECAST_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()
|
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::Natal | Kind::Celebrity => &NATAL_SECTIONS,
|
||||||
Kind::Synastry => &SYNASTRY_SECTIONS,
|
Kind::Synastry => &SYNASTRY_SECTIONS,
|
||||||
Kind::Forecast => &FORECAST_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 {
|
if kind == Kind::Summary {
|
||||||
return json!({
|
return json!({
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -269,6 +286,13 @@ fn hungarian_system(kind: Kind) -> String {
|
|||||||
előrejelzés kb. 1500–2000 szó.",
|
előrejelzés kb. 1500–2000 szó.",
|
||||||
),
|
),
|
||||||
Kind::Question => unreachable!("questions have their own prompt"),
|
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 => (
|
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ó)",
|
"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,
|
THIRD_PERSON_HU,
|
||||||
@@ -315,6 +339,9 @@ használhatsz.
|
|||||||
if kind == Kind::Celebrity {
|
if kind == Kind::Celebrity {
|
||||||
text.push_str(CELEBRITY_RULES_HU);
|
text.push_str(CELEBRITY_RULES_HU);
|
||||||
}
|
}
|
||||||
|
if kind == Kind::Weekly {
|
||||||
|
text.push_str(WEEKLY_RULES_HU);
|
||||||
|
}
|
||||||
text.push_str(HUNGARIAN_TERMS);
|
text.push_str(HUNGARIAN_TERMS);
|
||||||
if kind == Kind::Forecast {
|
if kind == Kind::Forecast {
|
||||||
text.push_str(HUNGARIAN_FORECAST_TERMS);
|
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.
|
kijelentést.
|
||||||
- Az „advice” mező nem neki szóló tanács, hanem zárógondolat: egy bekezdés, amely összefogja a portrét.";
|
- 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 = "
|
const FORECAST_RULES_HU: &str = "
|
||||||
|
|
||||||
Az előrejelzés szabályai:
|
Az előrejelzés szabályai:
|
||||||
@@ -408,6 +452,10 @@ pub fn default_system(kind: Kind, language: &str) -> String {
|
|||||||
}
|
}
|
||||||
let (role, reader) = match kind {
|
let (role, reader) = match kind {
|
||||||
Kind::Question => unreachable!("questions have their own prompt"),
|
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 => (
|
Kind::Celebrity => (
|
||||||
"a portrait of a famous person's natal chart (the reader is not that person but an interested visitor)",
|
"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 \
|
"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 {
|
length = match kind {
|
||||||
Kind::Forecast => "Length: each section 2-4 paragraphs (about 150-250 words), the timeline exactly 4 \
|
Kind::Forecast => "Length: each section 2-4 paragraphs (about 150-250 words), the timeline exactly 4 \
|
||||||
paragraphs; the whole forecast about 1500-2000 words.",
|
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 \
|
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, \
|
(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: \
|
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 {
|
if kind == Kind::Celebrity {
|
||||||
text.push_str(CELEBRITY_RULES);
|
text.push_str(CELEBRITY_RULES);
|
||||||
}
|
}
|
||||||
|
if kind == Kind::Weekly {
|
||||||
|
text.push_str(WEEKLY_RULES);
|
||||||
|
}
|
||||||
text
|
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 = "
|
const CELEBRITY_RULES: &str = "
|
||||||
|
|
||||||
Rules for a famous person's portrait:
|
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);
|
user.push_str(chart_text);
|
||||||
if kind == Kind::Summary {
|
if kind == Kind::Summary {
|
||||||
user.push_str(if hu { "\nMost írd meg a rövid összefoglalót." } else { "\nWrite the short summary now." });
|
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 {
|
} else {
|
||||||
user.push_str(if hu {
|
user.push_str(if hu {
|
||||||
"\nA megírandó fejezetek ebben a sorrendben (JSON-kulcs: tartalom):\n"
|
"\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::Summary => "chart_summary",
|
||||||
Kind::Question => "question_answer",
|
Kind::Question => "question_answer",
|
||||||
Kind::Forecast => "forecast_analysis",
|
Kind::Forecast => "forecast_analysis",
|
||||||
|
Kind::Weekly => "weekly_horoscope",
|
||||||
},
|
},
|
||||||
schema: schema(kind),
|
schema: schema(kind),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ pub fn date_of(jd_ut: f64, offset_hours: f64) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The zodiac of the natal chart, geocentric (transits are not topocentric).
|
/// 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;
|
let o = natal.settings.options;
|
||||||
Frame { sidereal: (o.zodiac == ZodiacType::Sidereal).then_some(o.ayanamsa), topocentric: None }
|
Frame { sidereal: (o.zodiac == ZodiacType::Sidereal).then_some(o.ayanamsa), topocentric: None }
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ fn natal_lon(natal: &NatalChart, id: PointId) -> Option<f64> {
|
|||||||
natal.points.iter().find(|p| p.id == id).map(|p| p.position.longitude)
|
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 houses = natal.houses.as_ref()?;
|
||||||
let mut cusps = [0.0; 12];
|
let mut cusps = [0.0; 12];
|
||||||
for (c, h) in cusps.iter_mut().zip(&houses.cusps) {
|
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
|
/// The natal points transits and progressions are measured to: the ten
|
||||||
/// planets and, with a known birth time, the Ascendant and the Midheaven.
|
/// 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).
|
/// 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 known = natal.angles.is_some();
|
||||||
let mut out: Vec<(PointId, f64)> = Body::PLANETS
|
let mut out: Vec<(PointId, f64)> = Body::PLANETS
|
||||||
.iter()
|
.iter()
|
||||||
@@ -129,15 +129,15 @@ type Window = (f64, f64);
|
|||||||
type Crossings = (Vec<Window>, Vec<(f64, bool)>);
|
type Crossings = (Vec<Window>, Vec<(f64, bool)>);
|
||||||
|
|
||||||
/// Longitude and daily motion sampled at equal steps.
|
/// Longitude and daily motion sampled at equal steps.
|
||||||
struct Samples {
|
pub(crate) struct Samples {
|
||||||
start: f64,
|
start: f64,
|
||||||
step: f64,
|
step: f64,
|
||||||
lon: Vec<f64>,
|
pub(crate) lon: Vec<f64>,
|
||||||
speed: Vec<f64>,
|
pub(crate) speed: Vec<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Samples {
|
impl Samples {
|
||||||
fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
|
pub(crate) fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
|
||||||
let n = ((to - from) / step).ceil() as usize + 1;
|
let n = ((to - from) / step).ceil() as usize + 1;
|
||||||
let mut lon = Vec::with_capacity(n);
|
let mut lon = Vec::with_capacity(n);
|
||||||
let mut speed = Vec::with_capacity(n);
|
let mut speed = Vec::with_capacity(n);
|
||||||
@@ -149,7 +149,7 @@ impl Samples {
|
|||||||
Ok(Self { start: from, step, lon, speed })
|
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
|
self.start + i as f64 * self.step
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -230,22 +230,30 @@ pub struct Contact {
|
|||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub house: Option<u8>,
|
pub house: Option<u8>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
peak_jd: f64,
|
pub(crate) peak_jd: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One year of a natal chart.
|
/// What counts as a contact: the orb, the aspects, and whether the periods
|
||||||
struct Year<'a> {
|
/// within orb are listed.
|
||||||
engine: &'a dyn Ephemeris,
|
pub(crate) struct ContactRule<'a> {
|
||||||
natal: &'a NatalChart,
|
pub(crate) orb: f64,
|
||||||
frame: Frame,
|
pub(crate) aspects: &'a [AspectKind],
|
||||||
start: f64,
|
pub(crate) with_periods: bool,
|
||||||
end: f64,
|
}
|
||||||
offset: f64,
|
|
||||||
cusps: Option<[f64; 12]>,
|
/// 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<'_> {
|
impl Year<'_> {
|
||||||
fn date(&self, jd: f64) -> String {
|
pub(crate) fn date(&self, jd: f64) -> String {
|
||||||
date_of(jd, self.offset)
|
date_of(jd, self.offset)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,17 +262,17 @@ impl Year<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Contacts of one moving planet (sampled in `s`) with the natal points.
|
/// Contacts of one moving planet (sampled in `s`) with the natal points.
|
||||||
fn contacts(
|
pub(crate) fn contacts(
|
||||||
&self,
|
&self,
|
||||||
planet: PointId,
|
planet: PointId,
|
||||||
s: &Samples,
|
s: &Samples,
|
||||||
lon_at: &dyn Fn(f64) -> Result<f64>,
|
lon_at: &dyn Fn(f64) -> Result<f64>,
|
||||||
targets: &[(PointId, f64)],
|
targets: &[(PointId, f64)],
|
||||||
with_periods: bool,
|
rule: &ContactRule,
|
||||||
) -> Result<Vec<Contact>> {
|
) -> Result<Vec<Contact>> {
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
for &(natal_point, natal) in targets {
|
for &(natal_point, natal) in targets {
|
||||||
for aspect in ASPECTS {
|
for &aspect in rule.aspects {
|
||||||
let a = aspect.angle();
|
let a = aspect.angle();
|
||||||
let mut points = vec![natal + a];
|
let mut points = vec![natal + a];
|
||||||
if a != 0.0 && a != 180.0 {
|
if a != 0.0 && a != 180.0 {
|
||||||
@@ -272,7 +280,7 @@ impl Year<'_> {
|
|||||||
}
|
}
|
||||||
let (mut windows, mut exact) = (Vec::new(), Vec::new());
|
let (mut windows, mut exact) = (Vec::new(), Vec::new());
|
||||||
for target in points {
|
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);
|
windows.extend(w);
|
||||||
exact.extend(e);
|
exact.extend(e);
|
||||||
}
|
}
|
||||||
@@ -289,7 +297,7 @@ impl Year<'_> {
|
|||||||
.map(|i| (i, separation(s.lon[i], natal)))
|
.map(|i| (i, separation(s.lon[i], natal)))
|
||||||
.map(|(i, sep)| (i, (sep - a).abs()))
|
.map(|(i, sep)| (i, (sep - a).abs()))
|
||||||
.min_by(|x, y| x.1.total_cmp(&y.1))
|
.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() {
|
let (peak_jd, min_orb) = match exact.first() {
|
||||||
Some(&(jd, _)) => (jd, 0.0),
|
Some(&(jd, _)) => (jd, 0.0),
|
||||||
None => (s.jd(closest_i), closest),
|
None => (s.jd(closest_i), closest),
|
||||||
@@ -301,7 +309,7 @@ impl Year<'_> {
|
|||||||
aspect,
|
aspect,
|
||||||
nature: aspect.nature(),
|
nature: aspect.nature(),
|
||||||
exact: exact.iter().map(|&(jd, retrograde)| Exact { date: self.date(jd), retrograde }).collect(),
|
exact: exact.iter().map(|&(jd, retrograde)| Exact { date: self.date(jd), retrograde }).collect(),
|
||||||
periods: if with_periods {
|
periods: if rule.with_periods {
|
||||||
windows
|
windows
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&(from, to)| DateRange { start: self.date(from), end: self.date(to) })
|
.map(|&(from, to)| DateRange { start: self.date(from), end: self.date(to) })
|
||||||
@@ -319,7 +327,7 @@ impl Year<'_> {
|
|||||||
Ok(out)
|
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)?;
|
let s = self.engine.position(body, jd, &self.frame)?;
|
||||||
Ok((s.longitude, s.speed_longitude))
|
Ok((s.longitude, s.speed_longitude))
|
||||||
}
|
}
|
||||||
@@ -333,7 +341,8 @@ impl Year<'_> {
|
|||||||
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
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 s = Samples::take(self.start - MARGIN_DAYS, self.end + MARGIN_DAYS, 1.0, &at)?;
|
||||||
let planet = PointId::from_planet(body);
|
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 {
|
if let Some(cusps) = self.cusps {
|
||||||
houses.push(self.house_changes(planet, &s, &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).
|
// A progressed planet meeting its own natal place only matters for the Moon (the progressed lunar return).
|
||||||
let own: Vec<(PointId, f64)> =
|
let own: Vec<(PointId, f64)> =
|
||||||
targets.iter().copied().filter(|&(id, _)| id != planet || body == Body::Moon).collect();
|
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 start = ZodiacPosition::new(s.lon[0]);
|
||||||
let mut sign_changes = Vec::new();
|
let mut sign_changes = Vec::new();
|
||||||
|
|||||||
@@ -6,8 +6,9 @@
|
|||||||
//! [`chart`] and is independent of the engine, so the engine can be replaced
|
//! [`chart`] and is independent of the engine, so the engine can be replaced
|
||||||
//! without touching the chart logic. [`synastry`] compares two charts;
|
//! without touching the chart logic. [`synastry`] compares two charts;
|
||||||
//! [`forecast`] looks at one year of a chart (solar return, transits,
|
//! [`forecast`] looks at one year of a chart (solar return, transits,
|
||||||
//! progressions, profection, eclipses); [`sky`] is the sky by date, the same
|
//! progressions, profection, eclipses); [`week`] is one week of a chart (the
|
||||||
//! for everyone (lunar phases, retrograde periods).
|
//! weekly horoscope); [`sky`] is the sky by date, the same for everyone (lunar
|
||||||
|
//! phases, retrograde periods).
|
||||||
|
|
||||||
pub mod angle;
|
pub mod angle;
|
||||||
pub mod chart;
|
pub mod chart;
|
||||||
@@ -17,6 +18,7 @@ pub mod sky;
|
|||||||
pub mod synastry;
|
pub mod synastry;
|
||||||
pub mod time;
|
pub mod time;
|
||||||
pub mod types;
|
pub mod types;
|
||||||
|
pub mod week;
|
||||||
|
|
||||||
#[cfg(feature = "swisseph")]
|
#[cfg(feature = "swisseph")]
|
||||||
pub mod swiss;
|
pub mod swiss;
|
||||||
@@ -29,3 +31,4 @@ pub use engine::{
|
|||||||
pub use forecast::{Forecast, calculate_forecast, solar_return};
|
pub use forecast::{Forecast, calculate_forecast, solar_return};
|
||||||
pub use synastry::{Synastry, calculate_synastry};
|
pub use synastry::{Synastry, calculate_synastry};
|
||||||
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
|
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
|
||||||
|
pub use week::{Week, calculate_week};
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
//! One week of a natal chart, for the weekly horoscope: the planets' aspects
|
||||||
|
//! to the natal points during the week (with the day each is exact), where
|
||||||
|
//! the planets stand at the start, the Moon's sign changes, the main lunar
|
||||||
|
//! phases, and the planets' stations and sign changes.
|
||||||
|
//!
|
||||||
|
//! The aspects use the yearly forecast's machinery ([`crate::forecast`]) on a
|
||||||
|
//! seven-day span, with the Sun to Pluto as the moving planets (the Moon
|
||||||
|
//! would touch every natal point in a week, so only its signs are given).
|
||||||
|
//! Dates are calendar days at a fixed UTC offset given by the caller.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::chart::{AspectKind, NatalChart, PointId, ZodiacPosition, house_of};
|
||||||
|
use crate::engine::{EngineError, Ephemeris};
|
||||||
|
use crate::forecast::{Contact, ContactRule, Samples, Year, cusps_of, frame_of, natal_targets};
|
||||||
|
use crate::sky::{LunationKind, RETROGRADING, lunations, moon_ingresses, stations};
|
||||||
|
use crate::types::{Body, ZodiacSign};
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, EngineError>;
|
||||||
|
|
||||||
|
/// The moving planets: everything but the Moon.
|
||||||
|
const MOVING: [Body; 9] = [
|
||||||
|
Body::Sun,
|
||||||
|
Body::Mercury,
|
||||||
|
Body::Venus,
|
||||||
|
Body::Mars,
|
||||||
|
Body::Jupiter,
|
||||||
|
Body::Saturn,
|
||||||
|
Body::Uranus,
|
||||||
|
Body::Neptune,
|
||||||
|
Body::Pluto,
|
||||||
|
];
|
||||||
|
/// The major aspects only: a week has room for the strong themes.
|
||||||
|
const ASPECTS: [AspectKind; 5] =
|
||||||
|
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
|
||||||
|
/// Orb of a contact, degrees: within it at some time during the week.
|
||||||
|
pub const WEEK_ORB: f64 = 1.0;
|
||||||
|
/// Sampling step, days (Mercury moves at most about 2° a day).
|
||||||
|
const STEP: f64 = 0.25;
|
||||||
|
/// Days sampled around the week, so a pass beginning before it is found whole.
|
||||||
|
const MARGIN_DAYS: f64 = 20.0;
|
||||||
|
|
||||||
|
/// A planet at the start of the week.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct WeekPosition {
|
||||||
|
pub planet: PointId,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub position: ZodiacPosition,
|
||||||
|
pub retrograde: bool,
|
||||||
|
/// Natal house (birth time known).
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub house: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A planet (or the Moon) entering a sign.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct WeekIngress {
|
||||||
|
pub date: String,
|
||||||
|
pub planet: PointId,
|
||||||
|
pub sign: ZodiacSign,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub house: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new moon, quarter or full moon.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct WeekLunation {
|
||||||
|
pub date: String,
|
||||||
|
pub kind: LunationKind,
|
||||||
|
/// Where the Moon is.
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub position: ZodiacPosition,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub house: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A planet standing still before turning retrograde or direct.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct WeekStation {
|
||||||
|
pub date: String,
|
||||||
|
pub planet: PointId,
|
||||||
|
pub retrograde: bool,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub position: ZodiacPosition,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One week of a natal chart.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Week {
|
||||||
|
/// First and last day (Monday and Sunday).
|
||||||
|
pub start: String,
|
||||||
|
pub end: String,
|
||||||
|
/// The planets' aspects to the natal points, by their peak inside the week.
|
||||||
|
pub contacts: Vec<Contact>,
|
||||||
|
pub positions: Vec<WeekPosition>,
|
||||||
|
/// The Moon's sign at the start, and its sign changes.
|
||||||
|
pub moon_sign: ZodiacSign,
|
||||||
|
pub moon_ingresses: Vec<WeekIngress>,
|
||||||
|
/// The other planets' sign changes.
|
||||||
|
pub ingresses: Vec<WeekIngress>,
|
||||||
|
pub lunations: Vec<WeekLunation>,
|
||||||
|
pub stations: Vec<WeekStation>,
|
||||||
|
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The week from `start_jd` (the first moment of Monday) to `end_jd` (the
|
||||||
|
/// first moment of the next Monday); dates are given at `offset_hours` from UTC.
|
||||||
|
pub fn calculate_week(
|
||||||
|
engine: &dyn Ephemeris,
|
||||||
|
natal: &NatalChart,
|
||||||
|
start_jd: f64,
|
||||||
|
end_jd: f64,
|
||||||
|
offset_hours: f64,
|
||||||
|
) -> Result<Week> {
|
||||||
|
if end_jd <= start_jd || end_jd - start_jd > 8.0 {
|
||||||
|
return Err(EngineError::Calculation("a week is at most eight days".into()));
|
||||||
|
}
|
||||||
|
let span = Year {
|
||||||
|
engine,
|
||||||
|
natal,
|
||||||
|
frame: frame_of(natal),
|
||||||
|
start: start_jd,
|
||||||
|
// The next Monday's first moment belongs to the next week.
|
||||||
|
end: end_jd - 1.0 / 86_400.0,
|
||||||
|
offset: offset_hours,
|
||||||
|
cusps: cusps_of(natal),
|
||||||
|
};
|
||||||
|
let house = |lon: f64| span.cusps.as_ref().map(|c| house_of(lon, c));
|
||||||
|
// The last day is the day before the next Monday.
|
||||||
|
let last_day = span.date(end_jd - 0.5 / 24.0);
|
||||||
|
let targets = natal_targets(natal);
|
||||||
|
let rule = ContactRule { orb: WEEK_ORB, aspects: &ASPECTS, with_periods: false };
|
||||||
|
|
||||||
|
let mut contacts = Vec::new();
|
||||||
|
let mut positions = Vec::new();
|
||||||
|
let mut ingresses = Vec::new();
|
||||||
|
for body in MOVING {
|
||||||
|
let at = |jd: f64| span.position(body, jd);
|
||||||
|
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
||||||
|
let s = Samples::take(start_jd - MARGIN_DAYS, end_jd + MARGIN_DAYS, STEP, &at)?;
|
||||||
|
let planet = PointId::from_planet(body);
|
||||||
|
contacts.extend(span.contacts(planet, &s, &lon_at, &targets, &rule)?);
|
||||||
|
|
||||||
|
let (lon, speed) = at(start_jd)?;
|
||||||
|
positions.push(WeekPosition {
|
||||||
|
planet,
|
||||||
|
position: ZodiacPosition::new(lon),
|
||||||
|
retrograde: speed < 0.0,
|
||||||
|
house: house(lon),
|
||||||
|
});
|
||||||
|
// Sign changes inside the week, to the sample (a few hours).
|
||||||
|
for i in 1..s.lon.len() {
|
||||||
|
let jd = s.jd(i);
|
||||||
|
if jd <= start_jd || jd > end_jd {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let sign = ZodiacSign::from_longitude(s.lon[i]);
|
||||||
|
if sign != ZodiacSign::from_longitude(s.lon[i - 1]) {
|
||||||
|
ingresses.push(WeekIngress { date: span.date(jd), planet, sign, house: house(s.lon[i]) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
contacts.sort_by(|a, b| a.peak_jd.total_cmp(&b.peak_jd));
|
||||||
|
|
||||||
|
let moon_start = span.position(Body::Moon, start_jd)?.0;
|
||||||
|
let moon_ingresses = moon_ingresses(engine, start_jd, end_jd)?
|
||||||
|
.into_iter()
|
||||||
|
.map(|(jd, sign)| {
|
||||||
|
let lon = span.position(Body::Moon, jd + 1.0 / 24.0).map(|(l, _)| l).unwrap_or(sign.index() as f64 * 30.0);
|
||||||
|
WeekIngress { date: span.date(jd), planet: PointId::Moon, sign, house: house(lon) }
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let lunations = lunations(engine, start_jd, end_jd)?
|
||||||
|
.into_iter()
|
||||||
|
.map(|l| WeekLunation {
|
||||||
|
date: span.date(l.jd_ut),
|
||||||
|
kind: l.kind,
|
||||||
|
position: ZodiacPosition::new(l.moon_longitude),
|
||||||
|
house: house(l.moon_longitude),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let mut week_stations = Vec::new();
|
||||||
|
for body in RETROGRADING {
|
||||||
|
for st in stations(engine, body, start_jd, end_jd)? {
|
||||||
|
week_stations.push(WeekStation {
|
||||||
|
date: span.date(st.jd_ut),
|
||||||
|
planet: PointId::from_planet(body),
|
||||||
|
retrograde: st.retrograde,
|
||||||
|
position: ZodiacPosition::new(st.longitude),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
week_stations.sort_by(|a, b| a.date.cmp(&b.date));
|
||||||
|
ingresses.sort_by(|a, b| a.date.cmp(&b.date));
|
||||||
|
|
||||||
|
let mut warnings = Vec::new();
|
||||||
|
if natal.angles.is_none() {
|
||||||
|
warnings
|
||||||
|
.push("Birth time unknown: no houses or angles, and the natal Moon is left out of the contacts.".into());
|
||||||
|
}
|
||||||
|
Ok(Week {
|
||||||
|
start: span.date(start_jd),
|
||||||
|
end: last_day,
|
||||||
|
contacts,
|
||||||
|
positions,
|
||||||
|
moon_sign: ZodiacSign::from_longitude(moon_start),
|
||||||
|
moon_ingresses,
|
||||||
|
ingresses,
|
||||||
|
lunations,
|
||||||
|
stations: week_stations,
|
||||||
|
warnings,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -217,3 +217,37 @@ fn solar_return_and_forecast() {
|
|||||||
assert!(f.eclipses.iter().any(|e| e.date == "2026-08-28"));
|
assert!(f.eclipses.iter().any(|e| e.date == "2026-08-28"));
|
||||||
serde_json::to_string(&f).unwrap();
|
serde_json::to_string(&f).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_week() {
|
||||||
|
use astro_engine::calculate_week;
|
||||||
|
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: true, options: ChartOptions::default() };
|
||||||
|
let natal = calculate_chart(engine(), &input).unwrap();
|
||||||
|
// Monday 30 November 2026, 0:00 in Budapest (UTC+1), to the next Monday.
|
||||||
|
let start = 2_461_374.5 - 1.0 / 24.0;
|
||||||
|
assert_eq!(astro_engine::forecast::date_of(start, 1.0), "2026-11-30");
|
||||||
|
let w = calculate_week(engine(), &natal, start, start + 7.0, 1.0).unwrap();
|
||||||
|
assert_eq!((w.start.as_str(), w.end.as_str()), ("2026-11-30", "2026-12-06"));
|
||||||
|
assert_eq!(w.positions.len(), 9);
|
||||||
|
assert!(w.positions.iter().all(|p| p.house.is_some()));
|
||||||
|
// Every contact is within orb during the week, with its peak and exact hits inside it.
|
||||||
|
assert!(!w.contacts.is_empty());
|
||||||
|
for c in &w.contacts {
|
||||||
|
assert!(c.min_orb <= 1.0, "{c:?}");
|
||||||
|
assert!(c.peak.as_str() >= w.start.as_str() && c.peak.as_str() <= w.end.as_str(), "{c:?}");
|
||||||
|
assert!(c.exact.iter().all(|e| e.date >= w.start && e.date <= w.end), "{c:?}");
|
||||||
|
assert_ne!(c.planet, astro_engine::chart::PointId::Moon);
|
||||||
|
}
|
||||||
|
// The Moon changes sign every two or three days, each time into the next sign.
|
||||||
|
assert!((2..=4).contains(&w.moon_ingresses.len()), "{:?}", w.moon_ingresses);
|
||||||
|
let mut sign = w.moon_sign;
|
||||||
|
for i in &w.moon_ingresses {
|
||||||
|
assert_eq!(i.sign.index(), (sign.index() + 1) % 12);
|
||||||
|
sign = i.sign;
|
||||||
|
}
|
||||||
|
// About one main lunar phase a week.
|
||||||
|
assert!((1..=2).contains(&w.lunations.len()), "{:?}", w.lunations);
|
||||||
|
let json = serde_json::to_value(&w).unwrap();
|
||||||
|
assert!(json["contacts"][0]["planet"].is_string());
|
||||||
|
assert!(json["positions"][0]["sign"].is_string());
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
-- The free weekly horoscope: the week's sky on a member's own chart (from
|
||||||
|
-- the horoscope service), its text (an analysis of kind 'weekly', written by
|
||||||
|
-- the summary's model), and the Monday e-mail that says it is there (on for
|
||||||
|
-- everyone, the members of today too; it can be turned off).
|
||||||
|
|
||||||
|
CREATE TABLE weekly_skies (
|
||||||
|
chart_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||||
|
-- The chart's data when it was calculated: new birth data, new week sky.
|
||||||
|
chart_hash text NOT NULL,
|
||||||
|
-- The Monday the week starts on (Hungarian time).
|
||||||
|
week_start date NOT NULL,
|
||||||
|
result jsonb NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (chart_id, chart_hash, week_start)
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE analyses ADD COLUMN week_start date;
|
||||||
|
|
||||||
|
ALTER TABLE analyses DROP CONSTRAINT analyses_kind_check;
|
||||||
|
ALTER TABLE analyses ADD CONSTRAINT analyses_kind_check
|
||||||
|
CHECK (kind IN ('natal', 'synastry', 'summary', 'forecast', 'tarot', 'celebrity', 'weekly'));
|
||||||
|
|
||||||
|
ALTER TABLE analyses DROP CONSTRAINT analyses_target;
|
||||||
|
ALTER TABLE analyses ADD CONSTRAINT analyses_target CHECK (
|
||||||
|
(kind IN ('natal', 'summary', 'celebrity') AND chart_id IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
|
||||||
|
OR (kind = 'tarot' AND tarot IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'weekly' AND chart_id IS NOT NULL AND week_start IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- The Monday e-mail: on unless the member turns it off. The token opens the
|
||||||
|
-- page of every e-mail setting from an e-mail's footer (no login needed).
|
||||||
|
ALTER TABLE users ADD COLUMN weekly_email boolean NOT NULL DEFAULT true;
|
||||||
|
ALTER TABLE users ADD COLUMN weekly_email_sent_on date;
|
||||||
|
ALTER TABLE users ADD COLUMN email_token uuid NOT NULL DEFAULT gen_random_uuid();
|
||||||
|
CREATE UNIQUE INDEX users_email_token ON users (email_token);
|
||||||
@@ -182,6 +182,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
|
|||||||
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
||||||
("gift", _) => gift(lang, payload, url)?,
|
("gift", _) => gift(lang, payload, url)?,
|
||||||
("gift_package", _) => gift_package(lang, payload, url)?,
|
("gift_package", _) => gift_package(lang, payload, url)?,
|
||||||
|
("weekly_horoscope", _) => weekly_horoscope(lang, payload, url)?,
|
||||||
// The forum is Hungarian only.
|
// The forum is Hungarian only.
|
||||||
("forum_reply", _) => forum_reply(payload, url)?,
|
("forum_reply", _) => forum_reply(payload, url)?,
|
||||||
("forum_digest", _) => forum_digest(payload, url)?,
|
("forum_digest", _) => forum_digest(payload, url)?,
|
||||||
@@ -602,6 +603,117 @@ fn name(payload: &Value, field: &str) -> Option<String> {
|
|||||||
(!name.is_empty()).then(|| name.to_owned())
|
(!name.is_empty()).then(|| name.to_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Monday's notice that the weekly horoscope is there: only that, the text
|
||||||
|
/// itself is read on the site after logging in.
|
||||||
|
fn weekly_horoscope(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||||
|
let start = field(payload, "week_start")?;
|
||||||
|
let end = field(payload, "week_end")?;
|
||||||
|
let range = week_range(lang, &start, &end).ok_or(TemplateError::MissingField("week_start"))?;
|
||||||
|
let greeting = match (lang, name(payload, "display_name")) {
|
||||||
|
(Lang::Hu, Some(n)) => format!("Szia {n}!"),
|
||||||
|
(Lang::Hu, None) => "Szia!".to_owned(),
|
||||||
|
(Lang::En, Some(n)) => format!("Hi {n},"),
|
||||||
|
(Lang::En, None) => "Hi,".to_owned(),
|
||||||
|
};
|
||||||
|
let unsubscribe_url = field(payload, "unsubscribe_url")?;
|
||||||
|
let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
|
||||||
|
Ok(match lang {
|
||||||
|
Lang::Hu => Content {
|
||||||
|
subject: "Itt a heti horoszkópod".into(),
|
||||||
|
preheader: Some(format!("{range}: belépés után a Heti horoszkóp oldalon olvashatod.")),
|
||||||
|
greeting,
|
||||||
|
intro: format!(
|
||||||
|
"Itt a heti horoszkópod {} {range} közötti hétre. Belépés után a Heti horoszkóp oldalon olvashatod.",
|
||||||
|
// "az április 6–12.", "a november 30."
|
||||||
|
if range.starts_with(['a', 'á', 'e', 'é', 'i', 'í', 'o', 'ó', 'ö', 'ő', 'u', 'ú', 'ü', 'ű']) {
|
||||||
|
"az"
|
||||||
|
} else {
|
||||||
|
"a"
|
||||||
|
}
|
||||||
|
),
|
||||||
|
quote: None,
|
||||||
|
points: None,
|
||||||
|
code: None,
|
||||||
|
button: "Megnézem",
|
||||||
|
url,
|
||||||
|
note: "A saját képletedből és a hét égboltjából készül.".into(),
|
||||||
|
reason: Some(
|
||||||
|
"Azért kapod ezt a levelet, mert van képleted a Sorsfonalakon. Ha nem kéred, az alábbi linken vagy a \
|
||||||
|
Profil oldalon kikapcsolhatod."
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
unsubscribe: Some(("Leiratkozás, értesítések beállítása", unsubscribe_url)),
|
||||||
|
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||||
|
},
|
||||||
|
Lang::En => Content {
|
||||||
|
subject: "Your weekly horoscope is here".into(),
|
||||||
|
preheader: Some(format!("{range}: log in to read it on the Weekly horoscope page.")),
|
||||||
|
greeting,
|
||||||
|
intro: format!(
|
||||||
|
"Your weekly horoscope for {range} is here. Log in to read it on the Weekly horoscope page."
|
||||||
|
),
|
||||||
|
quote: None,
|
||||||
|
points: None,
|
||||||
|
code: None,
|
||||||
|
button: "Read it",
|
||||||
|
url,
|
||||||
|
note: "It is written from your own chart and the week's sky.".into(),
|
||||||
|
reason: Some(
|
||||||
|
"You get this e-mail because you have a chart on Sorsfonalak. If you do not want it, turn it off with \
|
||||||
|
the link below or on your Profile page."
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
unsubscribe: Some(("Unsubscribe, e-mail settings", unsubscribe_url)),
|
||||||
|
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "november 30. – december 6." or "december 7–13." (no year).
|
||||||
|
fn week_range(lang: Lang, start: &str, end: &str) -> Option<String> {
|
||||||
|
let parse = |iso: &str| -> Option<(usize, u32)> {
|
||||||
|
let mut parts = iso.splitn(3, '-').skip(1);
|
||||||
|
let m: usize = parts.next()?.parse().ok()?;
|
||||||
|
let d: u32 = parts.next()?.get(..2)?.parse().ok()?;
|
||||||
|
Some((m.checked_sub(1).filter(|&i| i < 12)?, d))
|
||||||
|
};
|
||||||
|
let ((m1, d1), (m2, d2)) = (parse(start)?, parse(end)?);
|
||||||
|
const HU: [&str; 12] = [
|
||||||
|
"január",
|
||||||
|
"február",
|
||||||
|
"március",
|
||||||
|
"április",
|
||||||
|
"május",
|
||||||
|
"június",
|
||||||
|
"július",
|
||||||
|
"augusztus",
|
||||||
|
"szeptember",
|
||||||
|
"október",
|
||||||
|
"november",
|
||||||
|
"december",
|
||||||
|
];
|
||||||
|
const EN: [&str; 12] = [
|
||||||
|
"January",
|
||||||
|
"February",
|
||||||
|
"March",
|
||||||
|
"April",
|
||||||
|
"May",
|
||||||
|
"June",
|
||||||
|
"July",
|
||||||
|
"August",
|
||||||
|
"September",
|
||||||
|
"October",
|
||||||
|
"November",
|
||||||
|
"December",
|
||||||
|
];
|
||||||
|
Some(match (lang, m1 == m2) {
|
||||||
|
(Lang::Hu, true) => format!("{} {d1}–{d2}.", HU[m1]),
|
||||||
|
(Lang::Hu, false) => format!("{} {d1}. – {} {d2}.", HU[m1], HU[m2]),
|
||||||
|
(Lang::En, true) => format!("{d1}–{d2} {}", EN[m1]),
|
||||||
|
(Lang::En, false) => format!("{d1} {} – {d2} {}", EN[m1], EN[m2]),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// The confirmation of a purchase: what was bought, and that the buyer asked
|
/// 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
|
/// for immediate delivery and so gave up the 14-day withdrawal right (the
|
||||||
/// confirmation 45/2014. Korm. rendelet 29. § asks for).
|
/// 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]
|
#[test]
|
||||||
fn waitlist_confirmation_has_the_leave_link() {
|
fn waitlist_confirmation_has_the_leave_link() {
|
||||||
let hu = render("waitlist_joined", "hu", &invitation_payload()).unwrap();
|
let hu = render("waitlist_joined", "hu", &invitation_payload()).unwrap();
|
||||||
|
|||||||
@@ -48,6 +48,11 @@ impl HoroscopeClient {
|
|||||||
self.post("/v1/forecast", request).await
|
self.post("/v1/forecast", request).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `POST /v1/week`: one week of a natal chart (the weekly horoscope's sky).
|
||||||
|
pub async fn week(&self, request: &Value) -> Result<Value, HoroscopeError> {
|
||||||
|
self.post("/v1/week", request).await
|
||||||
|
}
|
||||||
|
|
||||||
/// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon).
|
/// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon).
|
||||||
pub async fn sky(&self) -> Result<Value, HoroscopeError> {
|
pub async fn sky(&self) -> Result<Value, HoroscopeError> {
|
||||||
self.get("/v1/sky", &[]).await
|
self.get("/v1/sky", &[]).await
|
||||||
|
|||||||
@@ -137,8 +137,9 @@ services:
|
|||||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG_WORKER:-${TAG:-latest}}
|
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG_WORKER:-${TAG:-latest}}
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
||||||
# forum: the forum's digests, daily sky thread, listener e-mails, weekly summary.
|
# forum: the forum's digests, daily sky thread, listener e-mails, weekly summary;
|
||||||
WORKER_TASKS: email,cleanup,invoices,notify,forum
|
# 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.
|
# The sky of the forum's daily thread.
|
||||||
BACKEND_URL: http://backend:8081
|
BACKEND_URL: http://backend:8081
|
||||||
# Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets.
|
# Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets.
|
||||||
|
|||||||
@@ -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=<users.email_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.
|
||||||
@@ -45,7 +45,8 @@ impl Function {
|
|||||||
|
|
||||||
pub fn of(kind: Kind) -> Function {
|
pub fn of(kind: Kind) -> Function {
|
||||||
match kind {
|
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::Question => Function::Question,
|
||||||
Kind::Natal | Kind::Synastry | Kind::Forecast | Kind::Celebrity => Function::Analysis,
|
Kind::Natal | Kind::Synastry | Kind::Forecast | Kind::Celebrity => Function::Analysis,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
|||||||
.await?;
|
.await?;
|
||||||
let replies = super::feedback::unseen_replies(&mut conn, auth.id()).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 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!({
|
Ok(Json(json!({
|
||||||
"user": UserView::from(&auth.user),
|
"user": UserView::from(&auth.user),
|
||||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||||
@@ -59,6 +63,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
|||||||
"feedback_replies_unseen": replies,
|
"feedback_replies_unseen": replies,
|
||||||
// Ask the "would you recommend us?" question now.
|
// Ask the "would you recommend us?" question now.
|
||||||
"nps_due": nps_due,
|
"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<impl IntoResp
|
|||||||
"exported_at": rfc3339(OffsetDateTime::now_utc()),
|
"exported_at": rfc3339(OffsetDateTime::now_utc()),
|
||||||
"user": UserView::from(&auth.user),
|
"user": UserView::from(&auth.user),
|
||||||
"last_login_at": rfc3339_opt(auth.user.last_login_at),
|
"last_login_at": rfc3339_opt(auth.user.last_login_at),
|
||||||
|
"weekly_horoscope_email": rows("SELECT json_build_object('on', weekly_email, 'last_sent_for_week', weekly_email_sent_on) FROM users WHERE id = $1").await?.into_iter().next(),
|
||||||
"login_methods": rows("SELECT json_build_object('provider', provider, 'email', email, 'created_at', created_at, 'last_used_at', last_used_at) FROM auth_identities WHERE user_id = $1").await?,
|
"login_methods": rows("SELECT json_build_object('provider', provider, 'email', email, 'created_at', created_at, 'last_used_at', last_used_at) FROM auth_identities WHERE user_id = $1").await?,
|
||||||
"sessions": rows("SELECT json_build_object('created_at', created_at, 'expires_at', expires_at, 'user_agent', user_agent) FROM sessions WHERE user_id = $1").await?,
|
"sessions": rows("SELECT json_build_object('created_at', created_at, 'expires_at', expires_at, 'user_agent', user_agent) FROM sessions WHERE user_id = $1").await?,
|
||||||
"charts": rows("SELECT json_build_object('id', id, 'label', label, 'is_primary', is_primary, 'birth_data', birth_data, 'result', result, 'created_at', created_at) FROM charts WHERE owner_id = $1 AND kind <> 'celebrity'").await?,
|
"charts": rows("SELECT json_build_object('id', id, 'label', label, 'is_primary', is_primary, 'birth_data', birth_data, 'result', result, 'created_at', created_at) FROM charts WHERE owner_id = $1 AND kind <> 'celebrity'").await?,
|
||||||
|
|||||||
@@ -7,7 +7,8 @@
|
|||||||
//! instead, free of charge, so the same chart is never paid for twice.
|
//! 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
|
//! 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 analysis_prompt::Kind;
|
||||||
use axum::Json;
|
use axum::Json;
|
||||||
@@ -18,7 +19,7 @@ use axum_extra::extract::WithRejection;
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use time::OffsetDateTime;
|
use time::{Date, OffsetDateTime};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::auth::validate_locale;
|
use super::auth::validate_locale;
|
||||||
@@ -53,11 +54,14 @@ pub struct AnalysisRow {
|
|||||||
pub next_attempt_at: OffsetDateTime,
|
pub next_attempt_at: OffsetDateTime,
|
||||||
/// When the current text was asked for (set again by a regeneration).
|
/// When the current text was asked for (set again by a regeneration).
|
||||||
pub requested_at: OffsetDateTime,
|
pub requested_at: OffsetDateTime,
|
||||||
|
/// The Monday of a weekly horoscope.
|
||||||
|
pub week_start: Option<Date>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
|
pub(super) const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
|
||||||
content, error, \
|
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 {
|
impl AnalysisRow {
|
||||||
pub fn view(&self) -> Value {
|
pub fn view(&self) -> Value {
|
||||||
@@ -78,6 +82,7 @@ impl AnalysisRow {
|
|||||||
"attempts": self.attempts,
|
"attempts": self.attempts,
|
||||||
"next_attempt_at": rfc3339(self.next_attempt_at),
|
"next_attempt_at": rfc3339(self.next_attempt_at),
|
||||||
"requested_at": rfc3339(self.requested_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,
|
chart_id: Uuid,
|
||||||
hash: String,
|
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(
|
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::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
|
||||||
Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)),
|
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::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 (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?;
|
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
|
||||||
@@ -225,8 +241,9 @@ pub(super) async fn queue(
|
|||||||
let insert = format!(
|
let insert = format!(
|
||||||
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
|
"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, \
|
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at, \
|
||||||
forecast_id, fallback_model) \
|
forecast_id, fallback_model, week_start) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) RETURNING {ANALYSIS_COLUMNS}"
|
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();
|
let id = Uuid::now_v7();
|
||||||
|
|
||||||
@@ -263,6 +280,7 @@ pub(super) async fn queue(
|
|||||||
.bind(OffsetDateTime::now_utc())
|
.bind(OffsetDateTime::now_utc())
|
||||||
.bind(forecast_id)
|
.bind(forecast_id)
|
||||||
.bind(fallback)
|
.bind(fallback)
|
||||||
|
.bind(week_start)
|
||||||
.fetch_one(&mut *tx)
|
.fetch_one(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
@@ -288,6 +306,7 @@ pub(super) async fn queue(
|
|||||||
.bind(None::<OffsetDateTime>)
|
.bind(None::<OffsetDateTime>)
|
||||||
.bind(forecast_id)
|
.bind(forecast_id)
|
||||||
.bind(fallback)
|
.bind(fallback)
|
||||||
|
.bind(week_start)
|
||||||
.fetch_one(&mut *tx)
|
.fetch_one(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
if let Some(unit) = unit {
|
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),
|
/// The hash of what the analysis is about (chart, comparison or forecast),
|
||||||
/// part of its cache key; `None` when that was deleted.
|
/// part of its cache key; `None` when that was deleted.
|
||||||
pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result<Option<String>, sqlx::Error> {
|
pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result<Option<String>, sqlx::Error> {
|
||||||
|
if row.kind == "weekly" {
|
||||||
|
let hash: Option<String> = 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() {
|
let (query, id) = match row.kind.as_str() {
|
||||||
"synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id),
|
"synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id),
|
||||||
"forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id),
|
"forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id),
|
||||||
|
|||||||
@@ -349,7 +349,8 @@ async fn corrected_birth(
|
|||||||
// The user's own comparisons with the person are deleted on correction (they
|
// 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.
|
// no longer match), unless a paid analysis was written for one of them.
|
||||||
let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as(
|
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 \
|
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') \
|
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 \
|
OR EXISTS (SELECT 1 FROM analyses a JOIN forecasts f ON f.id = a.forecast_id \
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ pub const TAGS: [&str; 10] = [
|
|||||||
"useful",
|
"useful",
|
||||||
];
|
];
|
||||||
/// What can be rated (analysis kinds, and answers to questions).
|
/// 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_COMMENT: usize = 1000;
|
||||||
const MAX_MESSAGE: usize = 2000;
|
const MAX_MESSAGE: usize = 2000;
|
||||||
const MAX_REPLY: usize = 4000;
|
const MAX_REPLY: usize = 4000;
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ mod invitations;
|
|||||||
mod invoices_user;
|
mod invoices_user;
|
||||||
mod jobs;
|
mod jobs;
|
||||||
mod models;
|
mod models;
|
||||||
|
mod notifications;
|
||||||
pub(crate) mod payments;
|
pub(crate) mod payments;
|
||||||
mod promo;
|
mod promo;
|
||||||
mod prompts;
|
mod prompts;
|
||||||
@@ -29,6 +30,7 @@ mod shares;
|
|||||||
pub mod sky;
|
pub mod sky;
|
||||||
mod synastries;
|
mod synastries;
|
||||||
mod tarot;
|
mod tarot;
|
||||||
|
mod weekly;
|
||||||
|
|
||||||
pub use recalculate::run as recalculate;
|
pub use recalculate::run as recalculate;
|
||||||
|
|
||||||
@@ -36,7 +38,7 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use axum::extract::{DefaultBodyLimit, Path, State};
|
use axum::extract::{DefaultBodyLimit, Path, State};
|
||||||
use axum::http::{HeaderValue, Method, header};
|
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::{Json, Router};
|
||||||
use axum_extra::extract::WithRejection;
|
use axum_extra::extract::WithRejection;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
@@ -101,6 +103,9 @@ pub fn router(state: Arc<AppState>) -> Router {
|
|||||||
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
|
.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}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart))
|
||||||
.route("/v1/charts/{id}/summary", post(analyses::summary_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/charts/{id}/forecasts", get(forecasts::list_for_chart).post(forecasts::create))
|
||||||
.route("/v1/forecasts/{id}", get(forecasts::get_one))
|
.route("/v1/forecasts/{id}", get(forecasts::get_one))
|
||||||
.route("/v1/forecasts/{id}/analyses", get(analyses::list_for_forecast).post(analyses::request_for_forecast))
|
.route("/v1/forecasts/{id}/analyses", get(analyses::list_for_forecast).post(analyses::request_for_forecast))
|
||||||
@@ -145,6 +150,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
|||||||
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
|
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
|
||||||
.route("/v1/public/invites/{token}", get(synastries::public_invite))
|
.route("/v1/public/invites/{token}", get(synastries::public_invite))
|
||||||
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
|
.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/invitations/{token}", get(invitations::public_view))
|
||||||
.route("/v1/public/waitlist", post(invitations::join_waitlist))
|
.route("/v1/public/waitlist", post(invitations::join_waitlist))
|
||||||
.route("/v1/public/chart", post(calculator::chart))
|
.route("/v1/public/chart", post(calculator::chart))
|
||||||
|
|||||||
@@ -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<Uuid, ApiError> {
|
||||||
|
let token = Uuid::parse_str(token.trim()).map_err(|_| ApiError::NotFound("token"))?;
|
||||||
|
let user: Option<Uuid> =
|
||||||
|
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<Value, ApiError> {
|
||||||
|
let weekly: bool =
|
||||||
|
sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await?;
|
||||||
|
let forum: Option<ForumRow> = 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<Query<TokenQuery>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
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<ForumSettings>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct ForumSettings {
|
||||||
|
replies: String,
|
||||||
|
followed: String,
|
||||||
|
messages: String,
|
||||||
|
mentions: String,
|
||||||
|
#[serde(default)]
|
||||||
|
listener: Option<String>,
|
||||||
|
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<Query<TokenQuery>, ApiError>,
|
||||||
|
WithRejection(Json(req), _): Body<Settings>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
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?))
|
||||||
|
}
|
||||||
@@ -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<bool, sqlx::Error> {
|
||||||
|
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<Json<Value>> {
|
||||||
|
let chart_id: Option<Uuid> = 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<Date> {
|
||||||
|
let (y, m) = key.split_once('-')?;
|
||||||
|
let month = time::Month::try_from(m.parse::<u8>().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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<Query<MonthQuery>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
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<AnalysisRow> = 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<Date>, Option<Date>) = 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<Value> = 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<EmailSwitch>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
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<Query<TokenQuery>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
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 })))
|
||||||
|
}
|
||||||
@@ -90,6 +90,23 @@ async fn fake_forecast(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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<Value>) -> (StatusCode, Json<Value>) {
|
||||||
|
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).
|
/// 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);
|
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/synastry", post(fake_synastry))
|
||||||
.route("/v1/forecast", post(fake_forecast))
|
.route("/v1/forecast", post(fake_forecast))
|
||||||
|
.route("/v1/week", post(fake_week))
|
||||||
.route(
|
.route(
|
||||||
"/v1/sky",
|
"/v1/sky",
|
||||||
get(|| async {
|
get(|| async {
|
||||||
@@ -1107,7 +1125,7 @@ async fn export_and_delete_account(pool: PgPool) {
|
|||||||
/// config and catalog, shared links, invitation pages, the waitlist and
|
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||||
/// logged-in user, so other apps cannot use them.
|
/// logged-in user, so other apps cannot use them.
|
||||||
const PUBLIC_ROUTES: [&str; 24] = [
|
const PUBLIC_ROUTES: [&str; 26] = [
|
||||||
"/healthz",
|
"/healthz",
|
||||||
// Stripe calls it; the signature proves it.
|
// Stripe calls it; the signature proves it.
|
||||||
"/v1/payments/stripe/webhook",
|
"/v1/payments/stripe/webhook",
|
||||||
@@ -1123,6 +1141,9 @@ const PUBLIC_ROUTES: [&str; 24] = [
|
|||||||
"/v1/public/shares/{slug}/visit",
|
"/v1/public/shares/{slug}/visit",
|
||||||
"/v1/public/invites/{token}",
|
"/v1/public/invites/{token}",
|
||||||
"/v1/public/invitations/unsubscribe",
|
"/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/invitations/{token}",
|
||||||
"/v1/public/waitlist",
|
"/v1/public/waitlist",
|
||||||
// The public birth chart (limited per visitor address).
|
// 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");
|
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<i32> = 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<time::Date>) =
|
||||||
|
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")]
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
||||||
let app = TestApp::new(pool.clone()).await;
|
let app = TestApp::new(pool.clone()).await;
|
||||||
|
|||||||
@@ -61,17 +61,17 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
|||||||
<section className="lp-hero">
|
<section className="lp-hero">
|
||||||
<div className="lp-wrap lp-hero-grid">
|
<div className="lp-wrap lp-hero-grid">
|
||||||
<div className="lp-hero-text">
|
<div className="lp-hero-text">
|
||||||
<span className="eyebrow lp-rise lp-r1">Születési képlet · Éves előrejelzés · Kapcsolat</span>
|
<span className="eyebrow">Születési képlet · Éves előrejelzés · Kapcsolat</span>
|
||||||
<h1 className="lp-title lp-rise lp-r2">
|
<h1 className="lp-title">
|
||||||
Ahol a csillagok
|
Ahol a csillagok
|
||||||
<br />
|
<br />
|
||||||
összekötnek.
|
összekötnek.
|
||||||
</h1>
|
</h1>
|
||||||
<p className="lp-lead lp-rise lp-r3">
|
<p className="lp-lead">
|
||||||
Add meg, mikor és hol születtél: percre pontosan kiszámoljuk a képletedet, és személyre szóló elemzést írunk
|
Add meg, mikor és hol születtél: percre pontosan kiszámoljuk a képletedet, és személyre szóló elemzést írunk
|
||||||
belőle. Megmutatjuk, mit hoz az éved, és mennyire illetek össze azzal, akit szeretsz.
|
belőle. Megmutatjuk, mit hoz az éved, és mennyire illetek össze azzal, akit szeretsz.
|
||||||
</p>
|
</p>
|
||||||
<div className="lp-personal lp-rise lp-r3">
|
<div className="lp-personal">
|
||||||
<svg aria-hidden="true" viewBox="0 0 24 24" className="lp-personal-icon">
|
<svg aria-hidden="true" viewBox="0 0 24 24" className="lp-personal-icon">
|
||||||
<path d="M12 3.5a7.5 7.5 0 0 1 7.5 7.5c0 3-.6 5.7-1.6 7.8" />
|
<path d="M12 3.5a7.5 7.5 0 0 1 7.5 7.5c0 3-.6 5.7-1.6 7.8" />
|
||||||
<path d="M4.5 11a7.5 7.5 0 0 1 3-6" />
|
<path d="M4.5 11a7.5 7.5 0 0 1 3-6" />
|
||||||
@@ -88,7 +88,7 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="lp-actions lp-rise lp-r4">
|
<div className="lp-actions">
|
||||||
<Link href={start} className="btn btn-primary lp-btn">
|
<Link href={start} className="btn btn-primary lp-btn">
|
||||||
{signIn}
|
{signIn}
|
||||||
</Link>
|
</Link>
|
||||||
@@ -97,13 +97,13 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
|||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
{!loggedIn && (
|
{!loggedIn && (
|
||||||
<p className="lp-free-line lp-rise lp-r4">
|
<p className="lp-free-line">
|
||||||
<span className="lp-free-label">Ingyenes</span>
|
<span className="lp-free-label">Ingyenes</span>
|
||||||
<Link href="/szuletesi-horoszkop">Nézd meg a születési horoszkópodat belépés nélkül →</Link>
|
<Link href="/szuletesi-horoszkop">Nézd meg a születési horoszkópodat belépés nélkül →</Link>
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{!loggedIn && (
|
{!loggedIn && (
|
||||||
<p className="hint lp-rise lp-r4">
|
<p className="hint">
|
||||||
{inviteOnly
|
{inviteOnly
|
||||||
? "Az oldal egyelőre meghívásos: meghívóval, Google-fiókkal lépsz be."
|
? "Az oldal egyelőre meghívásos: meghívóval, Google-fiókkal lépsz be."
|
||||||
: "A képlet és a rövid összefoglaló ingyenes. Google-fiókkal lépsz be."}
|
: "A képlet és a rövid összefoglaló ingyenes. Google-fiókkal lépsz be."}
|
||||||
|
|||||||
@@ -207,6 +207,25 @@ export default async function PrivacyPage() {
|
|||||||
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
|
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
|
||||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
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
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
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)
|
||||||
|
</td>
|
||||||
|
<td>Szerződés teljesítése; a levélnél jogos érdek (6. cikk (1) f)</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
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
|
||||||
|
betöltési ideje (látogatottságmérés)
|
||||||
|
</td>
|
||||||
|
<td>Hogy lássuk, mennyien nézik az egyes oldalakat, és elég gyors-e az oldal</td>
|
||||||
|
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||||
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
@@ -263,7 +282,8 @@ export default async function PrivacyPage() {
|
|||||||
<p>
|
<p>
|
||||||
<strong>Mire használjuk:</strong> a fiókod létrehozására és arra, hogy belépéskor felismerjünk; az
|
<strong>Mire használjuk:</strong> 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
|
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.
|
nevedet a megjelenítéshez; a nyelvet az oldal és az elemzések nyelvéhez.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
@@ -304,10 +324,11 @@ export default async function PrivacyPage() {
|
|||||||
<section>
|
<section>
|
||||||
<h2>4. Az elemzések és a mesterséges intelligencia</h2>
|
<h2>4. Az elemzések és a mesterséges intelligencia</h2>
|
||||||
<p>
|
<p>
|
||||||
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
|
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
|
||||||
modell (mesterséges intelligencia) írja. A modellhez a <strong>képlet csillagászati adatai</strong> jutnak
|
válaszokat nagy nyelvi modell (mesterséges intelligencia) írja. A modellhez a{" "}
|
||||||
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,
|
<strong>képlet csillagászati adatai</strong> jutnak el (a bolygók jegye, foka, háza és fényszögei), a heti
|
||||||
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
|
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
|
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.
|
önismereti célú szöveg, nem minősül egészségügyi, pénzügyi, jogi vagy más szakmai tanácsnak.
|
||||||
</p>
|
</p>
|
||||||
@@ -337,7 +358,8 @@ export default async function PrivacyPage() {
|
|||||||
<strong>Cloudflare, Inc.</strong> – a forgalom továbbítása és a támadások elleni védelem; az oldal
|
<strong>Cloudflare, Inc.</strong> – a forgalom továbbítása és a támadások elleni védelem; az oldal
|
||||||
letöltésekor kezeli az IP-címedet és a kérés adatait. Az e-mailes regisztrációnál és a jelszókérésnél a
|
letöltésekor kezeli az IP-címedet és a kérés adatait. Az e-mailes regisztrációnál és a jelszókérésnél a
|
||||||
Turnstile szolgáltatásával ellenőrzi, hogy nem gép küldi az űrlapot (ehhez a böngésző jellemzőit is
|
Turnstile szolgáltatásával ellenőrzi, hogy nem gép küldi az űrlapot (ehhez a böngésző jellemzőit is
|
||||||
vizsgálja).
|
vizsgálja). A Web Analytics szolgáltatásával méri a látogatottságot és az oldal sebességét, süti és a
|
||||||
|
böngészőben tárolt azonosító nélkül; az egyes látogatókat nem követi.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Google LLC</strong> – bejelentkezés Google-fiókkal.
|
<strong>Google LLC</strong> – bejelentkezés Google-fiókkal.
|
||||||
@@ -406,7 +428,13 @@ export default async function PrivacyPage() {
|
|||||||
<p>
|
<p>
|
||||||
A működéshez feltétlenül szükséges sütit használunk (<code>sf_session</code>), amely belépve tart. Ha a
|
A működéshez feltétlenül szükséges sütit használunk (<code>sf_session</code>), amely belépve tart. Ha a
|
||||||
fórumon világos vagy sötét témát választasz, a választásodat egy második süti (<code>sf_forum_theme</code>)
|
fórumon világos vagy sötét témát választasz, a választásodat egy második süti (<code>sf_forum_theme</code>)
|
||||||
őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket, illetve látogatottságmérőt nem használunk.
|
őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket nem használunk.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
A látogatottságot a Cloudflare Web Analytics méri, süti és a böngészőben tárolt azonosító nélkül. Az oldal
|
||||||
|
betöltésekor egy kis szkript elküldi, melyik oldalt nyitottad meg, honnan érkeztél, milyen böngészőt és
|
||||||
|
eszközt használsz, és mennyi idő alatt töltődött be az oldal. Mi ebből csak összesített számokat látunk, az
|
||||||
|
egyes látogatókat nem tudjuk követni.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
A belépés nélküli <Link href="/szuletesi-horoszkop">születési horoszkópnál</Link> a megadott születési adatokat
|
A belépés nélküli <Link href="/szuletesi-horoszkop">születési horoszkópnál</Link> a megadott születési adatokat
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ const PAGE = 50;
|
|||||||
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
|
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
|
||||||
const KINDS: Record<string, string> = {
|
const KINDS: Record<string, string> = {
|
||||||
summary: "összefoglaló",
|
summary: "összefoglaló",
|
||||||
|
weekly: "heti horoszkóp",
|
||||||
natal: "képletelemzés",
|
natal: "képletelemzés",
|
||||||
synastry: "kapcsolati",
|
synastry: "kapcsolati",
|
||||||
forecast: "előrejelzés",
|
forecast: "előrejelzés",
|
||||||
|
|||||||
@@ -9,7 +9,11 @@ import type { CatalogModel, ModelFunction } from "@/lib/types";
|
|||||||
import { RunningJobs } from "./RunningJobs";
|
import { RunningJobs } from "./RunningJobs";
|
||||||
|
|
||||||
const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = {
|
const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = {
|
||||||
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: {
|
analysis: {
|
||||||
title: "Elemzések és éves előrejelzés",
|
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.",
|
about: "Fizetős szövegek: részletes képletelemzés, kapcsolati elemzés és éves előrejelzés.",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import type { AdminJob } from "@/lib/types";
|
|||||||
|
|
||||||
const KINDS: Record<AdminJob["kind"], string> = {
|
const KINDS: Record<AdminJob["kind"], string> = {
|
||||||
summary: "Összefoglaló",
|
summary: "Összefoglaló",
|
||||||
|
weekly: "Heti horoszkóp",
|
||||||
natal: "Képletelemzés",
|
natal: "Képletelemzés",
|
||||||
synastry: "Kapcsolati elemzés",
|
synastry: "Kapcsolati elemzés",
|
||||||
forecast: "Éves előrejelzés",
|
forecast: "Éves előrejelzés",
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { copyDialog } from "@/components/Dialogs";
|
||||||
|
import { chromeIntent, type InAppBrowser } from "@/lib/inAppBrowser";
|
||||||
|
|
||||||
|
/** "a Facebook", "az Instagram": the Hungarian article, capitalised at the start of a sentence. */
|
||||||
|
function named(app: string | null): string {
|
||||||
|
if (!app) return "Egy alkalmazás";
|
||||||
|
return `${/^[aáeéiíoóöőuúüű]/i.test(app) ? "Az" : "A"} ${app}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* On the login page inside an app's built-in browser (Facebook and co.):
|
||||||
|
* why the Google button is missing, and the way out to the phone's own
|
||||||
|
* browser. On Android a link opens the page in Chrome; on an iPhone only the
|
||||||
|
* app's own menu can, so the text says where, and the link can be copied.
|
||||||
|
*/
|
||||||
|
export function InAppNotice({ browser, url, password }: { browser: InAppBrowser; url: string; password: boolean }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const where = browser.android ? "a Chrome-ban" : "a böngésződben (Safari)";
|
||||||
|
|
||||||
|
async function copy() {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(url);
|
||||||
|
setCopied(true);
|
||||||
|
} catch {
|
||||||
|
await copyDialog({
|
||||||
|
title: "A belépési oldal linkje",
|
||||||
|
text: "Másold ki, és nyisd meg a böngésződben.",
|
||||||
|
value: url,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="inapp-note" role="note">
|
||||||
|
<strong>{named(browser.app)} beépített böngészőjében vagy</strong>
|
||||||
|
<p>
|
||||||
|
Itt a Google nem engedi a Google-fiókos belépést. {password ? "Lépj be e-mail-címmel, vagy nyisd" : "Nyisd"} meg
|
||||||
|
az oldalt {where}, ott a Google-fiókoddal is beléphetsz.
|
||||||
|
{!browser.android && " Ehhez koppints a jobb felső sarokban a ⋯ gombra, és válaszd a megnyitást böngészőben."}
|
||||||
|
</p>
|
||||||
|
<div className="inapp-actions">
|
||||||
|
{browser.android && (
|
||||||
|
<a className="btn btn-primary" href={chromeIntent(url)}>
|
||||||
|
Megnyitás Chrome-ban
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
<button type="button" className="btn" onClick={() => void copy()}>
|
||||||
|
{copied ? "Kimásolva" : "Link másolása"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
|
import { headers } from "next/headers";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
@@ -6,11 +7,14 @@ import { Logo } from "@/components/SiteHeader";
|
|||||||
import { ZodiacWheel } from "@/components/ZodiacWheel";
|
import { ZodiacWheel } from "@/components/ZodiacWheel";
|
||||||
import { BACKEND_URL, getMe } from "@/lib/server";
|
import { BACKEND_URL, getMe } from "@/lib/server";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
|
import { inAppBrowser } from "@/lib/inAppBrowser";
|
||||||
import { contents } from "@/lib/packageContents";
|
import { contents } from "@/lib/packageContents";
|
||||||
|
import { siteUrl } from "@/lib/share";
|
||||||
import type { InvitationLanding, PublicConfig } from "@/lib/types";
|
import type { InvitationLanding, PublicConfig } from "@/lib/types";
|
||||||
|
|
||||||
import { AppleLogin } from "./AppleLogin";
|
import { AppleLogin } from "./AppleLogin";
|
||||||
import { GoogleLogin } from "./GoogleLogin";
|
import { GoogleLogin } from "./GoogleLogin";
|
||||||
|
import { InAppNotice } from "./InAppNotice";
|
||||||
import { PasswordLogin } from "./PasswordLogin";
|
import { PasswordLogin } from "./PasswordLogin";
|
||||||
|
|
||||||
export const metadata: Metadata = { title: "Belépés" };
|
export const metadata: Metadata = { title: "Belépés" };
|
||||||
@@ -123,6 +127,46 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
|||||||
const password = config?.password_login === true;
|
const password = config?.password_login === true;
|
||||||
const mod = Array.isArray(params.mod) ? params.mod[0] : params.mod;
|
const mod = Array.isArray(params.mod) ? params.mod[0] : params.mod;
|
||||||
const initialMode = mod === "elfelejtett" ? "forgot" : mod === "regisztracio" || rawToken ? "register" : "login";
|
const initialMode = mod === "elfelejtett" ? "forgot" : mod === "regisztracio" || rawToken ? "register" : "login";
|
||||||
|
// Facebook's and other apps' built-in browsers: Google refuses to sign in
|
||||||
|
// there, so the e-mail form comes first and the way out to the phone's own
|
||||||
|
// browser (this same page, with its invitation or referral) is offered.
|
||||||
|
const inApp = inAppBrowser((await headers()).get("user-agent") ?? "");
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
for (const [key, value] of Object.entries(params)) {
|
||||||
|
for (const v of Array.isArray(value) ? value : [value]) query.append(key, v);
|
||||||
|
}
|
||||||
|
const here = `${await siteUrl()}/belepes${query.size ? `?${query}` : ""}`;
|
||||||
|
|
||||||
|
const google =
|
||||||
|
clientId && !inApp ? (
|
||||||
|
<GoogleLogin clientId={clientId} target={target} inviteToken={pendingInvite} referral={referral} />
|
||||||
|
) : null;
|
||||||
|
const apple =
|
||||||
|
clientId && appleId ? (
|
||||||
|
<AppleLogin clientId={appleId} target={target} inviteToken={pendingInvite} referral={referral} />
|
||||||
|
) : null;
|
||||||
|
const social =
|
||||||
|
google || apple ? (
|
||||||
|
<div className="field" style={{ gap: 12 }}>
|
||||||
|
{google}
|
||||||
|
{apple}
|
||||||
|
</div>
|
||||||
|
) : null;
|
||||||
|
const passwordForm = password ? (
|
||||||
|
<PasswordLogin
|
||||||
|
target={target}
|
||||||
|
inviteToken={pendingInvite}
|
||||||
|
referral={referral}
|
||||||
|
initialMode={initialMode}
|
||||||
|
turnstileKey={config?.turnstile_site_key ?? null}
|
||||||
|
/>
|
||||||
|
) : null;
|
||||||
|
const or =
|
||||||
|
social && passwordForm ? (
|
||||||
|
<div className="auth-or" role="separator">
|
||||||
|
<span>vagy</span>
|
||||||
|
</div>
|
||||||
|
) : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="auth">
|
<div className="auth">
|
||||||
@@ -149,35 +193,25 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
|||||||
{rawToken && (
|
{rawToken && (
|
||||||
<InvitationCard invitation={inviteToken ? invitation : null} apple={appleId !== null} password={password} />
|
<InvitationCard invitation={inviteToken ? invitation : null} apple={appleId !== null} password={password} />
|
||||||
)}
|
)}
|
||||||
|
{inApp && config !== null && <InAppNotice browser={inApp} url={here} password={password} />}
|
||||||
{config === null ? (
|
{config === null ? (
|
||||||
<p className="msg msg-error" role="alert">
|
<p className="msg msg-error" role="alert">
|
||||||
A szerver most nem érhető el. Próbáld újra egy kicsit később.
|
A szerver most nem érhető el. Próbáld újra egy kicsit később.
|
||||||
</p>
|
</p>
|
||||||
) : clientId || password ? (
|
) : clientId || password ? (
|
||||||
<>
|
inApp ? (
|
||||||
{clientId && (
|
<>
|
||||||
<div className="field" style={{ gap: 12 }}>
|
{passwordForm}
|
||||||
<GoogleLogin clientId={clientId} target={target} inviteToken={pendingInvite} referral={referral} />
|
{or}
|
||||||
{appleId && (
|
{social}
|
||||||
<AppleLogin clientId={appleId} target={target} inviteToken={pendingInvite} referral={referral} />
|
</>
|
||||||
)}
|
) : (
|
||||||
</div>
|
<>
|
||||||
)}
|
{social}
|
||||||
{clientId && password && (
|
{or}
|
||||||
<div className="auth-or" role="separator">
|
{passwordForm}
|
||||||
<span>vagy</span>
|
</>
|
||||||
</div>
|
)
|
||||||
)}
|
|
||||||
{password && (
|
|
||||||
<PasswordLogin
|
|
||||||
target={target}
|
|
||||||
inviteToken={pendingInvite}
|
|
||||||
referral={referral}
|
|
||||||
initialMode={initialMode}
|
|
||||||
turnstileKey={config?.turnstile_site_key ?? null}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : (
|
) : (
|
||||||
<p className="msg msg-error" role="alert">
|
<p className="msg msg-error" role="alert">
|
||||||
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
|
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
|
||||||
|
|||||||
@@ -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<Settings | null>(null);
|
||||||
|
const [loadError, setLoadError] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [saved, setSaved] = useState<string | null>(null);
|
||||||
|
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!token) return;
|
||||||
|
api<Settings>(`/public/notifications${query}`)
|
||||||
|
.then(setSettings)
|
||||||
|
.catch((e) => setLoadError(errorText(e)));
|
||||||
|
}, [token, query]);
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
Hiányzik a link vége. Nyisd meg a teljes linket a levélből.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (loadError) {
|
||||||
|
return (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!settings) {
|
||||||
|
return <p className="muted">Betöltés…</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(next: Settings, done: string) {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setSaved(null);
|
||||||
|
try {
|
||||||
|
setSettings(await api<Settings>(`/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<ForumMail>) => {
|
||||||
|
setSaved(null);
|
||||||
|
setSettings({ ...settings, forum: forum ? { ...forum, ...patch } : null });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="card field mail-settings" style={{ gap: 18 }}>
|
||||||
|
<fieldset className="mail-set">
|
||||||
|
<legend>Heti horoszkóp</legend>
|
||||||
|
<label className="check">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={settings.weekly_horoscope}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSaved(null);
|
||||||
|
setSettings({ ...settings, weekly_horoscope: e.target.checked });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span>Hétfőnként szóljatok, ha itt az új heti horoszkópom</span>
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
{forum && (
|
||||||
|
<fieldset className="mail-set">
|
||||||
|
<legend>Fórum</legend>
|
||||||
|
<label htmlFor="mail-replies">Ha valaki válaszol nekem (a szálamban vagy a hozzászólásomra)</label>
|
||||||
|
<select
|
||||||
|
id="mail-replies"
|
||||||
|
className="inp"
|
||||||
|
value={forum.replies}
|
||||||
|
onChange={(e) => setForum({ replies: e.target.value as ForumMail["replies"] })}
|
||||||
|
>
|
||||||
|
<option value="daily">Napi összesítőben, este</option>
|
||||||
|
<option value="instant">Azonnal (szálanként óránként legfeljebb egy levél)</option>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
</select>
|
||||||
|
<label htmlFor="mail-followed">Új hozzászólás a követett szálaimban</label>
|
||||||
|
<select
|
||||||
|
id="mail-followed"
|
||||||
|
className="inp"
|
||||||
|
value={forum.followed}
|
||||||
|
onChange={(e) => setForum({ followed: e.target.value as ForumMail["followed"] })}
|
||||||
|
>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
<option value="daily">Napi összesítőben, este</option>
|
||||||
|
</select>
|
||||||
|
<label htmlFor="mail-messages">Privát üzenet vagy beszélgetési kérés</label>
|
||||||
|
<select
|
||||||
|
id="mail-messages"
|
||||||
|
className="inp"
|
||||||
|
value={forum.messages}
|
||||||
|
onChange={(e) => setForum({ messages: e.target.value as ForumMail["messages"] })}
|
||||||
|
>
|
||||||
|
<option value="instant">Azonnal</option>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
</select>
|
||||||
|
<label htmlFor="mail-mentions">Ha valaki megemlít</label>
|
||||||
|
<select
|
||||||
|
id="mail-mentions"
|
||||||
|
className="inp"
|
||||||
|
value={forum.mentions}
|
||||||
|
onChange={(e) => setForum({ mentions: e.target.value as ForumMail["mentions"] })}
|
||||||
|
>
|
||||||
|
<option value="instant">Azonnal</option>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
</select>
|
||||||
|
{forum.listener !== null && (
|
||||||
|
<>
|
||||||
|
<label htmlFor="mail-listener">
|
||||||
|
Kísérőként: ha egy meghallgatást kérő szál két órája válasz nélkül vár
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="mail-listener"
|
||||||
|
className="inp"
|
||||||
|
value={forum.listener}
|
||||||
|
onChange={(e) => setForum({ listener: e.target.value as "off" | "instant" })}
|
||||||
|
>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
<option value="instant">Azonnal (hat óránként legfeljebb egy levél)</option>
|
||||||
|
</select>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<label className="check">
|
||||||
|
<input type="checkbox" checked={forum.weekly} onChange={(e) => setForum({ weekly: e.target.checked })} />
|
||||||
|
<span>Heti összefoglaló vasárnap este: a hét legélénkebb szálai</span>
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void save(settings, "Elmentettük a beállításaidat.")}
|
||||||
|
>
|
||||||
|
{busy ? "Mentés…" : "Mentés"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void save(allOff(settings), "Leiratkoztál: ezekről nem küldünk több levelet.")}
|
||||||
|
>
|
||||||
|
Mindenről leiratkozom
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{saved && (
|
||||||
|
<p className="msg msg-ok" role="status">
|
||||||
|
{saved}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="hint" style={{ margin: 0 }}>
|
||||||
|
A jelszóval, a vásárlással és a számlával kapcsolatos leveleket ettől függetlenül megkapod.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<Record<string, string | string[]>>;
|
||||||
|
}) {
|
||||||
|
const raw = (await searchParams).token;
|
||||||
|
const token = Array.isArray(raw) ? raw[0] : raw;
|
||||||
|
return (
|
||||||
|
<main className="page" style={{ maxWidth: 640 }}>
|
||||||
|
<div className="page-head">
|
||||||
|
<h1>Értesítések</h1>
|
||||||
|
<p className="muted">Itt állíthatod be, miről kérsz levelet a Sorsfonalaktól.</p>
|
||||||
|
</div>
|
||||||
|
<MailSettings token={token ?? null} />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1034,8 +1034,6 @@ a.pair-row:hover strong { color: var(--gold); }
|
|||||||
.lp-caption { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
|
.lp-caption { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
|
||||||
.lp-caption .share-trio { justify-content: center; font-size: 15px; }
|
.lp-caption .share-trio { justify-content: center; font-size: 15px; }
|
||||||
.lp-asc { color: var(--gold); font-weight: 600; font-size: 12px; letter-spacing: 0.5px; }
|
.lp-asc { color: var(--gold); font-weight: 600; font-size: 12px; letter-spacing: 0.5px; }
|
||||||
.lp-rise { opacity: 0; transform: translateY(14px); animation: lp-rise 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) forwards; }
|
|
||||||
.lp-r1 { animation-delay: 0.1s; } .lp-r2 { animation-delay: 0.25s; } .lp-r3 { animation-delay: 0.4s; } .lp-r4 { animation-delay: 0.55s; }
|
|
||||||
|
|
||||||
.lp-band { border-top: 1px solid var(--line); padding: 96px 0; }
|
.lp-band { border-top: 1px solid var(--line); padding: 96px 0; }
|
||||||
.lp-alt { background: var(--panel-2); }
|
.lp-alt { background: var(--panel-2); }
|
||||||
@@ -1112,7 +1110,6 @@ body:has(.qdock-fab) .site-footer { padding-bottom: 88px; }
|
|||||||
@keyframes lp-fade { to { opacity: 1; } }
|
@keyframes lp-fade { to { opacity: 1; } }
|
||||||
@keyframes lp-draw { to { stroke-dashoffset: 0; } }
|
@keyframes lp-draw { to { stroke-dashoffset: 0; } }
|
||||||
@keyframes lp-spin { to { transform: rotate(360deg); } }
|
@keyframes lp-spin { to { transform: rotate(360deg); } }
|
||||||
@keyframes lp-rise { to { opacity: 1; transform: none; } }
|
|
||||||
@keyframes lp-float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }
|
@keyframes lp-float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }
|
||||||
@keyframes lp-pulse { 0%, 100% { transform: scale(1); opacity: 0.9; } 50% { transform: scale(1.6); opacity: 0.2; } }
|
@keyframes lp-pulse { 0%, 100% { transform: scale(1); opacity: 0.9; } 50% { transform: scale(1.6); opacity: 0.2; } }
|
||||||
@media (max-width: 900px) { .lp-analysis-grid { grid-template-columns: minmax(0, 1fr); } }
|
@media (max-width: 900px) { .lp-analysis-grid { grid-template-columns: minmax(0, 1fr); } }
|
||||||
@@ -1141,7 +1138,7 @@ body:has(.qdock-fab) .site-footer { padding-bottom: 88px; }
|
|||||||
}
|
}
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.lp *, .lp-orbit { animation: none !important; }
|
.lp *, .lp-orbit { animation: none !important; }
|
||||||
.lp-rise, .lp-wheel .w-point { opacity: 1; transform: none; }
|
.lp-wheel .w-point { opacity: 1; transform: none; }
|
||||||
.lp-wheel .w-aspect { stroke-dashoffset: 0; }
|
.lp-wheel .w-aspect { stroke-dashoffset: 0; }
|
||||||
.lp-wheel .w-aspect.w-asp-sextile { opacity: 1; }
|
.lp-wheel .w-aspect.w-asp-sextile { opacity: 1; }
|
||||||
}
|
}
|
||||||
@@ -1410,7 +1407,7 @@ span.tarot-fan-card { cursor: default; }
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* The ☰ menu: instead of the header's link rows where they no longer fit
|
/* 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). */
|
links and the package). */
|
||||||
.mobile-menu { display: none; margin-left: auto; }
|
.mobile-menu { display: none; margin-left: auto; }
|
||||||
.mobile-menu-button {
|
.mobile-menu-button {
|
||||||
@@ -1439,7 +1436,7 @@ span.tarot-fan-card { cursor: default; }
|
|||||||
@media (max-width: 1500px) {
|
@media (max-width: 1500px) {
|
||||||
.site-header .pkg-pill-detail { display: none; }
|
.site-header .pkg-pill-detail { display: none; }
|
||||||
}
|
}
|
||||||
@media (max-width: 1380px) {
|
@media (max-width: 1520px) {
|
||||||
.mobile-menu-app { display: block; }
|
.mobile-menu-app { display: block; }
|
||||||
.site-header .app-nav { display: none; }
|
.site-header .app-nav { display: none; }
|
||||||
.site-header .who { margin-left: auto; }
|
.site-header .who { margin-left: auto; }
|
||||||
@@ -1853,3 +1850,32 @@ span.tarot-fan-card { cursor: default; }
|
|||||||
.update-note-later { border: 0; background: none; color: var(--ink-2, #c9cfdc); font: inherit; font-size: 14px; cursor: pointer; padding: 6px; }
|
.update-note-later { border: 0; background: none; color: var(--ink-2, #c9cfdc); font: inherit; font-size: 14px; cursor: pointer; padding: 6px; }
|
||||||
.update-note-later:hover { color: var(--gold); }
|
.update-note-later:hover { color: var(--gold); }
|
||||||
@media (max-width: 479px) { .update-note { flex-wrap: wrap; justify-content: center; text-align: center; } }
|
@media (max-width: 479px) { .update-note { flex-wrap: wrap; justify-content: center; text-align: center; } }
|
||||||
|
|
||||||
|
/* Login inside Facebook's or another app's built-in browser: why, and the way out. */
|
||||||
|
.inapp-note {
|
||||||
|
display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; font-size: 14px;
|
||||||
|
border: 1px solid rgba(217, 180, 106, 0.45); background: rgba(217, 180, 106, 0.07); border-radius: 10px;
|
||||||
|
}
|
||||||
|
.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; }
|
||||||
|
|||||||
@@ -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<Month | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(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<typeof setTimeout> | undefined;
|
||||||
|
let polls = 0;
|
||||||
|
const poll = async () => {
|
||||||
|
try {
|
||||||
|
const week = await api<Week & { email: boolean }>("/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<Month>(`/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 (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!data) {
|
||||||
|
return <p className="muted">Betöltés…</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = (
|
||||||
|
<nav className="weekly-pager" aria-label="Hónapok">
|
||||||
|
{data.older ? (
|
||||||
|
<Link href={`/heti-horoszkop?honap=${data.older}`} className="btn btn-sm">
|
||||||
|
← Korábbi hónap
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
<strong>{monthName(data.month)}</strong>
|
||||||
|
{data.newer ? (
|
||||||
|
<Link
|
||||||
|
href={data.newer === data.current_month ? "/heti-horoszkop" : `/heti-horoszkop?honap=${data.newer}`}
|
||||||
|
className="btn btn-sm"
|
||||||
|
>
|
||||||
|
Újabb hónap →
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="field" style={{ gap: 18 }}>
|
||||||
|
{pager}
|
||||||
|
{data.weeks.length === 0 ? (
|
||||||
|
<p className="muted">Ebben a hónapban nem nézted meg a heti horoszkópodat.</p>
|
||||||
|
) : (
|
||||||
|
data.weeks.map((w) => (
|
||||||
|
<WeekCard
|
||||||
|
key={w.week_start}
|
||||||
|
start={w.week_start}
|
||||||
|
end={w.week_end}
|
||||||
|
analysis={w.analysis}
|
||||||
|
current={w.week_start === data.this_week}
|
||||||
|
gaveUp={w.week_start === data.this_week && gaveUp}
|
||||||
|
isAdmin={isAdmin}
|
||||||
|
onRestarted={restarted(w)}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
{(data.older || data.newer) && data.weeks.length > 1 && pager}
|
||||||
|
<div className="card">
|
||||||
|
<WeeklyEmailSwitch initial={data.email} label="Hétfőnként szóljatok e-mailben, ha itt az új heti horoszkópom" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<Record<string, string | string[]>>;
|
||||||
|
}) {
|
||||||
|
const me = await requireMe("/heti-horoszkop");
|
||||||
|
const raw = (await searchParams).honap;
|
||||||
|
const month = (Array.isArray(raw) ? raw[0] : raw) ?? null;
|
||||||
|
return (
|
||||||
|
<main className="page" style={{ maxWidth: 760 }}>
|
||||||
|
<div className="page-head">
|
||||||
|
<h1>Heti horoszkóp</h1>
|
||||||
|
<p className="muted">Hétfőnként új, a saját képletedből és a hét égboltjából.</p>
|
||||||
|
</div>
|
||||||
|
{me.primary_chart_id ? (
|
||||||
|
<WeeklyPage
|
||||||
|
key={month ?? "now"}
|
||||||
|
month={month && /^\d{4}-\d{2}$/.test(month) ? month : null}
|
||||||
|
isAdmin={me.user.roles.includes("admin")}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="card field" style={{ gap: 12 }}>
|
||||||
|
<p style={{ margin: 0 }}>A heti horoszkóphoz előbb add meg a születési adataidat.</p>
|
||||||
|
<div>
|
||||||
|
<Link href="/profil#birth" className="btn btn-primary">
|
||||||
|
Születési adatok megadása
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -87,6 +87,15 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
|||||||
referralOpen={config?.referral_rewards ?? false}
|
referralOpen={config?.referral_rewards ?? false}
|
||||||
referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
|
referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
|
||||||
/>
|
/>
|
||||||
|
{chart.id === me.primary_chart_id && (
|
||||||
|
<Link href="/heti-horoszkop" className="card weekly-teaser">
|
||||||
|
<span className="eyebrow">Heti horoszkóp</span>
|
||||||
|
<span>Hétfőnként új, a saját képletedből és a hét égboltjából.</span>
|
||||||
|
<span className="weekly-teaser-more">
|
||||||
|
Elolvasom a heti horoszkópomat<span aria-hidden="true"> →</span>
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
<BigThree chart={chart} />
|
<BigThree chart={chart} />
|
||||||
{forumEnabled() && (
|
{forumEnabled() && (
|
||||||
<div className="card ask-forum-card">
|
<div className="card ask-forum-card">
|
||||||
|
|||||||
@@ -124,6 +124,16 @@ const DATA: [string, string, string][] = [
|
|||||||
"Security, troubleshooting, preventing abuse",
|
"Security, troubleshooting, preventing abuse",
|
||||||
"Legitimate interest (Art. 6(1)(f))",
|
"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",
|
||||||
|
"Legitimate interest (Art. 6(1)(f))",
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
/** The privacy policy in English (the Hungarian one at /adatvedelem is the same in content). */
|
/** The privacy policy in English (the Hungarian one at /adatvedelem is the same in content). */
|
||||||
@@ -229,7 +239,8 @@ export default async function PrivacyPolicyPage() {
|
|||||||
<p>
|
<p>
|
||||||
<strong>How we use it:</strong> to create your account and recognise you when you sign in; your e-mail address
|
<strong>How we use it:</strong> 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
|
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;
|
display;
|
||||||
your language for the language of the site and your readings.
|
your language for the language of the site and your readings.
|
||||||
</p>
|
</p>
|
||||||
@@ -271,10 +282,11 @@ export default async function PrivacyPolicyPage() {
|
|||||||
<section>
|
<section>
|
||||||
<h2>4. Readings and artificial intelligence</h2>
|
<h2>4. Readings and artificial intelligence</h2>
|
||||||
<p>
|
<p>
|
||||||
The short summary, the detailed readings, tarot readings and the answers to your questions are written by a
|
The short summary, the weekly horoscope, the detailed readings, tarot readings and the answers to your
|
||||||
large language model (artificial intelligence). The model receives the{" "}
|
questions are written by a large language model (artificial intelligence). The model receives the{" "}
|
||||||
<strong>astronomical data of the chart</strong> (the signs, degrees, houses and aspects of the planets), for
|
<strong>astronomical data of the chart</strong> (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
|
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,
|
your questions either. The readings are for entertainment and self-reflection and are not medical,
|
||||||
financial, legal or other professional advice.
|
financial, legal or other professional advice.
|
||||||
@@ -305,6 +317,8 @@ export default async function PrivacyPolicyPage() {
|
|||||||
<strong>Cloudflare, Inc.</strong>: delivering traffic and protecting against attacks; processes your IP
|
<strong>Cloudflare, Inc.</strong>: delivering traffic and protecting against attacks; processes your IP
|
||||||
address and request data when the site loads. On the e-mail sign-up and password request forms its
|
address and request data when the site loads. On the e-mail sign-up and password request forms its
|
||||||
Turnstile service checks that a person, not a script, sends the form (looking at browser features too).
|
Turnstile service checks that a person, not a script, sends the form (looking at browser features too).
|
||||||
|
Its Web Analytics service measures visits and page speed without cookies or any identifier stored in the
|
||||||
|
browser, and does not follow individual visitors.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Google LLC</strong>: signing in with a Google account.
|
<strong>Google LLC</strong>: signing in with a Google account.
|
||||||
@@ -369,7 +383,12 @@ export default async function PrivacyPolicyPage() {
|
|||||||
<p>
|
<p>
|
||||||
We use a cookie that is strictly necessary for the service (<code>sf_session</code>), which keeps you signed
|
We use a cookie that is strictly necessary for the service (<code>sf_session</code>), which keeps you signed
|
||||||
in. If you choose the light or dark theme on the forum, a second cookie (<code>sf_forum_theme</code>) keeps
|
in. If you choose the light or dark theme on the forum, a second cookie (<code>sf_forum_theme</code>) keeps
|
||||||
your choice for a year; it stores nothing else. We use no advertising or tracking cookies and no analytics.
|
your choice for a year; it stores nothing else. We use no advertising or tracking cookies.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Visits are counted by Cloudflare Web Analytics, without cookies or any identifier stored in the browser.
|
||||||
|
When a page loads, a small script sends which page you opened, where you came from, your browser and device
|
||||||
|
type, and how long the page took to load. We only see totals and cannot follow individual visitors.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
On the public birth chart page (no account needed), the birth data you enter are sent only for the
|
On the public birth chart page (no account needed), the birth data you enter are sent only for the
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
|
||||||
import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
||||||
|
import { WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
|
||||||
import { backendGet, requireMe } from "@/lib/server";
|
import { backendGet, requireMe } from "@/lib/server";
|
||||||
import type { Chart } from "@/lib/types";
|
import type { Chart } from "@/lib/types";
|
||||||
|
|
||||||
@@ -84,6 +85,18 @@ export default async function ProfilePage() {
|
|||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section className="card" aria-labelledby="levelek-title" id="levelek">
|
||||||
|
<h2 id="levelek-title">Levelek</h2>
|
||||||
|
<WeeklyEmailSwitch
|
||||||
|
initial={me.weekly_email}
|
||||||
|
label="Heti horoszkóp: hétfőnként szólunk e-mailben, ha itt az új"
|
||||||
|
/>
|
||||||
|
<p className="hint" style={{ margin: 0 }}>
|
||||||
|
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."}
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section className="card" aria-labelledby="adataim">
|
<section className="card" aria-labelledby="adataim">
|
||||||
<h2 id="adataim">Adataim</h2>
|
<h2 id="adataim">Adataim</h2>
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
export type NavIconName =
|
export type NavIconName =
|
||||||
| "chart"
|
| "chart"
|
||||||
|
| "weekly"
|
||||||
| "persons"
|
| "persons"
|
||||||
| "compare"
|
| "compare"
|
||||||
| "tarot"
|
| "tarot"
|
||||||
@@ -45,6 +46,13 @@ export function NavIcon({ name }: { name: NavIconName }) {
|
|||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{name === "weekly" && (
|
||||||
|
<>
|
||||||
|
<rect x="4" y="5" width="16" height="15" rx="2.2" />
|
||||||
|
<path d="M4 9.5h16M8.5 3v4M15.5 3v4" />
|
||||||
|
<path d="M12 12l.9 2 2.1.9-2.1.9-.9 2-.9-2-2.1-.9 2.1-.9z" className="nav-icon-fill" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{name === "famous" && (
|
{name === "famous" && (
|
||||||
<path d="M12 3l2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6 6.6 19.5l1.2-6L3.3 9.3l6.1-.7z" />
|
<path d="M12 3l2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6 6.6 19.5l1.2-6L3.3 9.3l6.1-.7z" />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -148,11 +148,12 @@ const EXPLORE: NavItem[] = [
|
|||||||
/**
|
/**
|
||||||
* The header of the logged-in app: the menu with gold marks (the free pages
|
* 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.
|
* 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 }) {
|
export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
|
||||||
const own: NavItem[] = [
|
const own: NavItem[] = [
|
||||||
{ href: "/keplet", label: "Képletem", icon: "chart" },
|
{ href: "/keplet", label: "Képletem", icon: "chart" },
|
||||||
|
{ href: "/heti-horoszkop", label: "Heti horoszkóp", icon: "weekly" },
|
||||||
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
||||||
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
||||||
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
||||||
|
|||||||
@@ -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<string | null>(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 (
|
||||||
|
<div className="weekly-email">
|
||||||
|
<label className="check">
|
||||||
|
<input type="checkbox" checked={on} disabled={busy} onChange={(e) => void toggle(e.target.checked)} />
|
||||||
|
<span>{label}</span>
|
||||||
|
</label>
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 (
|
||||||
|
<article
|
||||||
|
className={current ? "card summary-card weekly-card weekly-current" : "card weekly-card"}
|
||||||
|
aria-labelledby={titleId}
|
||||||
|
aria-busy={!content && !gaveUp && analysis?.status !== "failed"}
|
||||||
|
>
|
||||||
|
<span className="eyebrow">
|
||||||
|
{weekRange(start, end)}
|
||||||
|
{current && " · ez a hét"}
|
||||||
|
</span>
|
||||||
|
{content ? (
|
||||||
|
<>
|
||||||
|
{isAdmin && analysis && onRestarted && (
|
||||||
|
<RegenerateButton<Analysis> url={`/admin/analyses/${analysis.id}/regenerate`} onStarted={onRestarted} />
|
||||||
|
)}
|
||||||
|
<h2 id={titleId} className="summary-title">
|
||||||
|
{content.title}
|
||||||
|
</h2>
|
||||||
|
<div className="summary-text weekly-text" lang={analysis?.language}>
|
||||||
|
<Paragraphs text={content.text ?? ""} />
|
||||||
|
</div>
|
||||||
|
{analysis && <RateContent analysisId={analysis.id} />}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<h2 id={titleId} className="sr-only">
|
||||||
|
Heti horoszkóp, {weekRange(start, end)}
|
||||||
|
</h2>
|
||||||
|
{gaveUp || analysis?.status === "failed" ? (
|
||||||
|
<p className="muted" role="status">
|
||||||
|
{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."}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<AnalysisLoading
|
||||||
|
compact
|
||||||
|
text="A heti horoszkópod készül, ez fél percig is eltarthat…"
|
||||||
|
since={analysis?.requested_at ?? analysis?.created_at}
|
||||||
|
/>
|
||||||
|
{analysis && (
|
||||||
|
<RetryNotice
|
||||||
|
status={analysis.status}
|
||||||
|
error={analysis.error}
|
||||||
|
nextAttemptAt={analysis.next_attempt_at}
|
||||||
|
isAdmin={isAdmin}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -29,6 +29,7 @@ export const TAG_LABELS: Record<string, string> = {
|
|||||||
|
|
||||||
export const KIND_LABELS: Record<string, string> = {
|
export const KIND_LABELS: Record<string, string> = {
|
||||||
summary: "Rövid összefoglaló",
|
summary: "Rövid összefoglaló",
|
||||||
|
weekly: "Heti horoszkóp",
|
||||||
natal: "Képletelemzés",
|
natal: "Képletelemzés",
|
||||||
synastry: "Kapcsolati elemzés",
|
synastry: "Kapcsolati elemzés",
|
||||||
forecast: "Éves előrejelzés",
|
forecast: "Éves előrejelzés",
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/**
|
||||||
|
* The browsers built into apps: Facebook, Messenger, Instagram, TikTok, and
|
||||||
|
* other Android apps that show pages in their own window (WebView). Google
|
||||||
|
* does not allow signing in with a Google account in them (its error page
|
||||||
|
* says "disallowed_useragent"), so the login page offers the e-mail login
|
||||||
|
* and a way out to the phone's own browser instead.
|
||||||
|
*/
|
||||||
|
export interface InAppBrowser {
|
||||||
|
/** The app's name for the text ("Facebook"); null for an unknown app. */
|
||||||
|
app: string | null;
|
||||||
|
android: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function inAppBrowser(userAgent: string): InAppBrowser | null {
|
||||||
|
const android = /Android/i.test(userAgent);
|
||||||
|
let app: string | null = null;
|
||||||
|
if (/Instagram/i.test(userAgent)) app = "Instagram";
|
||||||
|
else if (/MessengerForiOS|Orca-Android|FB_IAB\/MESSENGER/i.test(userAgent)) app = "Messenger";
|
||||||
|
else if (/FBAN|FBAV|FB_IAB|FBIOS|FB4A/.test(userAgent)) app = "Facebook";
|
||||||
|
else if (/TikTok|musical_ly|Bytedance/i.test(userAgent)) app = "TikTok";
|
||||||
|
if (app) return { app, android };
|
||||||
|
// Any other Android app's window: "; wv)" in the browser's name.
|
||||||
|
if (android && /; wv\)/.test(userAgent)) return { app: null, android };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A link that opens the page in Chrome on Android, out of the app's window.
|
||||||
|
* Without Chrome the phone falls back to the same page.
|
||||||
|
*/
|
||||||
|
export function chromeIntent(url: string): string {
|
||||||
|
const u = new URL(url);
|
||||||
|
const fallback = encodeURIComponent(url);
|
||||||
|
return `intent://${u.host}${u.pathname}${u.search}#Intent;scheme=${u.protocol.replace(":", "")};package=com.android.chrome;S.browser_fallback_url=${fallback};end`;
|
||||||
|
}
|
||||||
@@ -18,8 +18,8 @@ export const ARBITRATION_BOARD = {
|
|||||||
web: "https://panaszrendezes.hu",
|
web: "https://panaszrendezes.hu",
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PRIVACY_UPDATED = "2026. november 26.";
|
export const PRIVACY_UPDATED = "2026. november 27.";
|
||||||
export const PRIVACY_UPDATED_EN = "26 November 2026";
|
export const PRIVACY_UPDATED_EN = "27 November 2026";
|
||||||
|
|
||||||
/** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */
|
/** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */
|
||||||
export const TERMS_UPDATED = "2026. november 26.";
|
export const TERMS_UPDATED = "2026. november 26.";
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ export interface Me {
|
|||||||
nps_due: boolean;
|
nps_due: boolean;
|
||||||
/** Natal analyses earned by bringing new users through shared links. */
|
/** Natal analyses earned by bringing new users through shared links. */
|
||||||
referral_rewards: { earned: number; limit: number };
|
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`). */
|
/** A package from the catalog (`GET /v1/packages`). */
|
||||||
@@ -258,7 +260,7 @@ export interface SynastryListItem {
|
|||||||
|
|
||||||
export interface Analysis {
|
export interface Analysis {
|
||||||
id: string;
|
id: string;
|
||||||
kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity";
|
kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity" | "weekly";
|
||||||
status: "pending" | "running" | "done" | "failed";
|
status: "pending" | "running" | "done" | "failed";
|
||||||
model: string;
|
model: string;
|
||||||
language: string;
|
language: string;
|
||||||
@@ -272,6 +274,8 @@ export interface Analysis {
|
|||||||
next_attempt_at?: string;
|
next_attempt_at?: string;
|
||||||
/** When the current text was asked for: the waiting page counts from here. */
|
/** When the current text was asked for: the waiting page counts from here. */
|
||||||
requested_at?: string;
|
requested_at?: string;
|
||||||
|
/** The Monday of a weekly horoscope. */
|
||||||
|
week_start?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Admin: one failed attempt in the error log. */
|
/** Admin: one failed attempt in the error log. */
|
||||||
@@ -325,7 +329,7 @@ export interface ModelFunction {
|
|||||||
export interface AdminJob {
|
export interface AdminJob {
|
||||||
id: string;
|
id: string;
|
||||||
type: "analysis" | "question";
|
type: "analysis" | "question";
|
||||||
kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity";
|
kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity" | "weekly";
|
||||||
status: "pending" | "running";
|
status: "pending" | "running";
|
||||||
/** The model of the current attempt. */
|
/** The model of the current attempt. */
|
||||||
model: string;
|
model: string;
|
||||||
@@ -467,6 +471,8 @@ export interface AdminCelebrityRow {
|
|||||||
export interface AnalysisContent {
|
export interface AnalysisContent {
|
||||||
title?: string;
|
title?: string;
|
||||||
summary?: string;
|
summary?: string;
|
||||||
|
/** The weekly horoscope's paragraphs. */
|
||||||
|
text?: string;
|
||||||
sections?: Record<string, { title: string; body: string }>;
|
sections?: Record<string, { title: string; body: string }>;
|
||||||
strengths?: string[];
|
strengths?: string[];
|
||||||
challenges?: string[];
|
challenges?: string[];
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ mod sky;
|
|||||||
mod synastry;
|
mod synastry;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
mod week;
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ use crate::forecast::{self, ForecastRequest, ForecastResponse};
|
|||||||
use crate::natal::{self, NatalRequest, NatalResponse};
|
use crate::natal::{self, NatalRequest, NatalResponse};
|
||||||
use crate::sky::{self, EventsQuery, EventsResponse, SkyQuery, SkyResponse};
|
use crate::sky::{self, EventsQuery, EventsResponse, SkyQuery, SkyResponse};
|
||||||
use crate::synastry::{self, SynastryRequest, SynastryResponse};
|
use crate::synastry::{self, SynastryRequest, SynastryResponse};
|
||||||
|
use crate::week::{self, WeekRequest, WeekResponse};
|
||||||
|
|
||||||
type AppResult<T> = Result<Json<T>, ApiError>;
|
type AppResult<T> = Result<Json<T>, ApiError>;
|
||||||
|
|
||||||
@@ -30,6 +31,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
|||||||
.route("/v1/natal", post(natal_chart))
|
.route("/v1/natal", post(natal_chart))
|
||||||
.route("/v1/synastry", post(synastry_chart))
|
.route("/v1/synastry", post(synastry_chart))
|
||||||
.route("/v1/forecast", post(forecast_year))
|
.route("/v1/forecast", post(forecast_year))
|
||||||
|
.route("/v1/week", post(week_of_chart))
|
||||||
.route("/v1/sky", get(sky_now))
|
.route("/v1/sky", get(sky_now))
|
||||||
.route("/v1/sky/events", get(sky_events))
|
.route("/v1/sky/events", get(sky_events))
|
||||||
.layer(cors())
|
.layer(cors())
|
||||||
@@ -167,6 +169,17 @@ async fn forecast_year(
|
|||||||
Ok(Json(response))
|
Ok(Json(response))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn week_of_chart(
|
||||||
|
State(state): State<Arc<AppState>>,
|
||||||
|
body: Result<Json<WeekRequest>, JsonRejection>,
|
||||||
|
) -> AppResult<WeekResponse> {
|
||||||
|
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(
|
async fn sky_now(
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
query: Result<Query<SkyQuery>, QueryRejection>,
|
query: Result<Query<SkyQuery>, QueryRejection>,
|
||||||
|
|||||||
@@ -319,6 +319,33 @@ async fn forecast_year_with_solar_return() {
|
|||||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
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]
|
#[tokio::test]
|
||||||
async fn sky_at_a_moment() {
|
async fn sky_at_a_moment() {
|
||||||
// 2026-03-10 12:00 UTC: Mercury retrograde (26 Feb – 20 Mar), waning Moon.
|
// 2026-03-10 12:00 UTC: Mercury retrograde (26 Feb – 20 Mar), waning Moon.
|
||||||
|
|||||||
@@ -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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct WeekResponse {
|
||||||
|
pub timezone: String,
|
||||||
|
pub week: Week,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bad(msg: impl Into<String>) -> ApiError {
|
||||||
|
ApiError::BadRequest(msg.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn calculate(state: &AppState, req: WeekRequest) -> Result<WeekResponse, ApiError> {
|
||||||
|
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 })
|
||||||
|
}
|
||||||
@@ -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::<i32>);
|
||||||
|
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<String> = 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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ pub struct Job {
|
|||||||
pub attempts: i32,
|
pub attempts: i32,
|
||||||
/// A tarot reading's spread, question and cards (kind `tarot`).
|
/// A tarot reading's spread, question and cards (kind `tarot`).
|
||||||
pub tarot: Option<Value>,
|
pub tarot: Option<Value>,
|
||||||
|
/// The Monday of a weekly horoscope (kind `weekly`).
|
||||||
|
pub week_start: Option<time::Date>,
|
||||||
/// The default model, when the chosen one is another (see the module docs).
|
/// The default model, when the chosen one is another (see the module docs).
|
||||||
pub fallback_model: Option<String>,
|
pub fallback_model: Option<String>,
|
||||||
pub on_fallback: bool,
|
pub on_fallback: bool,
|
||||||
@@ -114,8 +116,8 @@ pub struct PreviewJob {
|
|||||||
/// Which analyses a claim may take.
|
/// Which analyses a claim may take.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum Lane {
|
pub enum Lane {
|
||||||
/// The short summary of a chart and the tarot readings (questions are
|
/// The short summary of a chart, the weekly horoscope and the tarot
|
||||||
/// claimed separately).
|
/// readings (questions are claimed separately).
|
||||||
Quick,
|
Quick,
|
||||||
/// The detailed analyses (famous people's too) and the yearly forecast.
|
/// The detailed analyses (famous people's too) and the yearly forecast.
|
||||||
Slow,
|
Slow,
|
||||||
@@ -124,7 +126,7 @@ pub enum Lane {
|
|||||||
impl Lane {
|
impl Lane {
|
||||||
fn kinds(self) -> &'static [&'static str] {
|
fn kinds(self) -> &'static [&'static str] {
|
||||||
match self {
|
match self {
|
||||||
Lane::Quick => &["summary", "tarot"],
|
Lane::Quick => &["summary", "weekly", "tarot"],
|
||||||
Lane::Slow => &["natal", "synastry", "forecast", "celebrity"],
|
Lane::Slow => &["natal", "synastry", "forecast", "celebrity"],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -165,7 +167,7 @@ impl Analyzer {
|
|||||||
AND kind = ANY($1) \
|
AND kind = ANY($1) \
|
||||||
ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
|
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, \
|
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())
|
.bind(lane.kinds())
|
||||||
.fetch_optional(&self.db)
|
.fetch_optional(&self.db)
|
||||||
@@ -190,6 +192,7 @@ impl Analyzer {
|
|||||||
Kind::Celebrity => self.celebrity_text(job.chart_id, &job.language).await?,
|
Kind::Celebrity => self.celebrity_text(job.chart_id, &job.language).await?,
|
||||||
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
|
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
|
||||||
Kind::Forecast => self.forecast_text(job.forecast_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())),
|
Kind::Question => return Err(LlmError::Permanent("a question is not an analysis".into())),
|
||||||
};
|
};
|
||||||
let (base, revision) = prompt::split_version(&job.prompt_version);
|
let (base, revision) = prompt::split_version(&job.prompt_version);
|
||||||
@@ -220,6 +223,21 @@ impl Analyzer {
|
|||||||
Ok(compact::natal(&chart))
|
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<Uuid>, week: Option<time::Date>) -> Result<String, LlmError> {
|
||||||
|
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.
|
/// A famous person's chart with their name in front.
|
||||||
async fn celebrity_text(&self, chart_id: Option<Uuid>, language: &str) -> Result<String, LlmError> {
|
async fn celebrity_text(&self, chart_id: Option<Uuid>, language: &str) -> Result<String, LlmError> {
|
||||||
let name: String = sqlx::query_scalar("SELECT name FROM celebrities WHERE chart_id = $1")
|
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::Forecast => self.forecast_text(job.forecast_id).await?,
|
||||||
Kind::Natal | Kind::Summary => self.natal_text(job.chart_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::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 built = prompt::build(kind, &job.language, &text, Some(&job.system));
|
||||||
let mut c = self.llm.complete(&job.model, &built).await?;
|
let mut c = self.llm.complete(&job.model, &built).await?;
|
||||||
|
|||||||
@@ -20,13 +20,22 @@ pub struct Tasks {
|
|||||||
pub notify: bool,
|
pub notify: bool,
|
||||||
/// The forum's daily e-mail digest.
|
/// The forum's daily e-mail digest.
|
||||||
pub forum: bool,
|
pub forum: bool,
|
||||||
|
/// Monday's e-mail about the weekly horoscope.
|
||||||
|
pub weekly: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Tasks {
|
impl Tasks {
|
||||||
pub const ALL: Tasks =
|
pub const ALL: Tasks =
|
||||||
Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true, forum: true };
|
Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true, forum: true, weekly: true };
|
||||||
const NONE: Tasks =
|
const NONE: Tasks = Tasks {
|
||||||
Tasks { email: false, cleanup: false, analyses: false, invoices: false, notify: false, forum: false };
|
email: false,
|
||||||
|
cleanup: false,
|
||||||
|
analyses: false,
|
||||||
|
invoices: false,
|
||||||
|
notify: false,
|
||||||
|
forum: false,
|
||||||
|
weekly: false,
|
||||||
|
};
|
||||||
|
|
||||||
pub fn parse(raw: &str) -> anyhow::Result<Self> {
|
pub fn parse(raw: &str) -> anyhow::Result<Self> {
|
||||||
let mut tasks = Self::NONE;
|
let mut tasks = Self::NONE;
|
||||||
@@ -38,9 +47,11 @@ impl Tasks {
|
|||||||
"invoices" => tasks.invoices = true,
|
"invoices" => tasks.invoices = true,
|
||||||
"notify" => tasks.notify = true,
|
"notify" => tasks.notify = true,
|
||||||
"forum" => tasks.forum = true,
|
"forum" => tasks.forum = true,
|
||||||
|
"weekly" => tasks.weekly = true,
|
||||||
other => {
|
other => {
|
||||||
anyhow::bail!(
|
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)"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
//! * hourly cleanup of expired sessions, tokens, invites and old e-mails
|
//! * hourly cleanup of expired sessions, tokens, invites and old e-mails
|
||||||
//! * writing the requested text analyses with an LLM (OpenRouter)
|
//! * writing the requested text analyses with an LLM (OpenRouter)
|
||||||
//! * issuing the invoices of the payments in Billingo
|
//! * 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
|
//! `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.
|
//! process, so they can run in separate containers; all of them by default.
|
||||||
@@ -25,6 +26,7 @@ mod invoices;
|
|||||||
mod notify;
|
mod notify;
|
||||||
mod ses;
|
mod ses;
|
||||||
mod telegram;
|
mod telegram;
|
||||||
|
mod weekly;
|
||||||
mod templates {
|
mod templates {
|
||||||
pub use email_templates::*;
|
pub use email_templates::*;
|
||||||
}
|
}
|
||||||
@@ -108,6 +110,7 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
invoices = tasks.invoices,
|
invoices = tasks.invoices,
|
||||||
notify = tasks.notify,
|
notify = tasks.notify,
|
||||||
forum = tasks.forum,
|
forum = tasks.forum,
|
||||||
|
weekly = tasks.weekly,
|
||||||
"worker tasks"
|
"worker tasks"
|
||||||
);
|
);
|
||||||
match &config.smtp_url {
|
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)"),
|
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 app = Router::new().route("/healthz", get(healthz)).with_state(pool);
|
||||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||||
tracing::info!(%addr, "worker running");
|
tracing::info!(%addr, "worker running");
|
||||||
|
|||||||
@@ -352,13 +352,30 @@ fn worker_tasks_are_chosen_by_name() {
|
|||||||
let mail = Tasks::parse("email, cleanup").unwrap();
|
let mail = Tasks::parse("email, cleanup").unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
mail,
|
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!(
|
assert_eq!(
|
||||||
Tasks::parse("analyses").unwrap(),
|
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").unwrap().forum);
|
||||||
|
assert!(Tasks::parse("email,forum,weekly").unwrap().weekly);
|
||||||
assert!(Tasks::parse("email,invoices").unwrap().invoices);
|
assert!(Tasks::parse("email,invoices").unwrap().invoices);
|
||||||
assert!(Tasks::parse("email,cleanup,invoices,notify").unwrap().notify);
|
assert!(Tasks::parse("email,cleanup,invoices,notify").unwrap().notify);
|
||||||
assert!(Tasks::parse("emails").is_err());
|
assert!(Tasks::parse("emails").is_err());
|
||||||
@@ -1196,4 +1213,141 @@ mod analyses {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!((status.as_str(), refund.as_deref()), ("failed", Some("tarot")));
|
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<Value>) =
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<bool>) {
|
||||||
|
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<u64, sqlx::Error> {
|
||||||
|
// Today in Hungary, if it is a Monday past the hour.
|
||||||
|
let monday: Option<time::Date> = 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<u64, sqlx::Error> {
|
||||||
|
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())
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user