Main #12

Merged
sagifer merged 3 commits from main into prod 2026-11-18 12:41:14 +01:00
13 changed files with 266 additions and 52 deletions
+1 -1
View File
@@ -9,7 +9,7 @@
use serde_json::{Value, json};
/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key).
pub const PROMPT_VERSION: &str = "v2";
pub const PROMPT_VERSION: &str = "v3";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
@@ -0,0 +1,14 @@
-- The yearly forecast prompt is editable on the admin page too, and can be
-- tried on one of the admin's own forecasts.
ALTER TABLE prompt_revisions DROP CONSTRAINT prompt_revisions_kind_check;
ALTER TABLE prompt_revisions ADD CONSTRAINT prompt_revisions_kind_check
CHECK (kind IN ('summary', 'natal', 'synastry', 'forecast'));
ALTER TABLE prompt_previews DROP CONSTRAINT prompt_previews_target;
ALTER TABLE prompt_previews
ADD COLUMN forecast_id uuid REFERENCES forecasts ON DELETE CASCADE,
ADD CONSTRAINT prompt_previews_target CHECK (
(kind IN ('summary', 'natal') 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)
);
+2 -1
View File
@@ -31,8 +31,9 @@ A modellhez nem megy születési dátum, hely vagy pontos életkor (csak évtize
Trendekről, lehetőségekről és időzítésről szól, nem biztos eseményekről. Betegségről, halálról, balesetről, terhességről, perekről és pénzügyi nyereségről vagy veszteségről nem jósol (`FORECAST_RULES` a promptban).
A rendszerprompt az admin felületen (Promptok → Éves előrejelzés) szerkeszthető, és mentés előtt kipróbálható az admin egyik saját, már kiszámolt évén. A változás csak az ezután kért elemzésekre hat. A modell kapta adatsor (`compact::forecast`) és a kimeneti séma a kódban van.
## Később
- Havi előrejelzés: holdvisszatérés és a hónap gyorsabb tranzitjai (Mars, Vénusz, Nap).
- Tranzitok a kompozit képletre: „mi vár rátok idén”.
- Az admin promptszerkesztőben az előrejelzés promptja is szerkeszthető legyen.
+1 -1
View File
@@ -22,7 +22,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | ez írja a fizetős részletes elemzéseket |
| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
| `ANALYSIS_PROMPT_VERSION` | `v2` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
| `ANALYSIS_PROMPT_VERSION` | `v3` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
| `MAX_CHARTS_PER_USER` | `1000` | biztonsági felső korlát a képletek számára |
| `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8081`, `text`, `info` | |
+2 -2
View File
@@ -61,7 +61,7 @@ pub struct Config {
/// `SUMMARY_MODEL`: writes the free short summary of every saved chart
/// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each).
pub summary_model: String,
/// `ANALYSIS_PROMPT_VERSION` (default `v2`); part of the analysis cache key.
/// `ANALYSIS_PROMPT_VERSION` (default `v3`); part of the analysis cache key.
pub prompt_version: String,
/// `MAX_CHARTS_PER_USER` (default 1000): a safety cap.
pub max_charts_per_user: i64,
@@ -121,7 +121,7 @@ impl Config {
supported_locales,
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()),
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()),
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v3".into()),
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
signup_mode: match var("SIGNUP_MODE").as_deref() {
+24 -21
View File
@@ -27,7 +27,7 @@ use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, rfc3339_opt};
/// The kinds whose prompt the admin page edits.
const EDITABLE: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry];
const EDITABLE: [Kind; 4] = [Kind::Summary, Kind::Natal, Kind::Synastry, Kind::Forecast];
const MAX_CHARS: usize = 50_000;
const HISTORY: i64 = 20;
/// Test runs of one admin waiting or being written at the same time.
@@ -162,6 +162,8 @@ pub struct StartPreview {
chart_id: Option<Uuid>,
/// One of the admin's own comparisons, for a synastry analysis.
synastry_id: Option<Uuid>,
/// A yearly forecast of one of the admin's own charts, for a forecast analysis.
forecast_id: Option<Uuid>,
}
#[derive(sqlx::FromRow)]
@@ -170,6 +172,7 @@ struct PreviewRow {
kind: String,
chart_id: Option<Uuid>,
synastry_id: Option<Uuid>,
forecast_id: Option<Uuid>,
language: String,
model: String,
status: String,
@@ -184,7 +187,7 @@ struct PreviewRow {
completed_at: Option<OffsetDateTime>,
}
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, status, content, error, model_used, \
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, model, status, content, error, model_used, \
input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
impl PreviewRow {
@@ -192,6 +195,7 @@ impl PreviewRow {
let seconds = self.started_at.zip(self.completed_at).map(|(s, c)| (c - s).whole_seconds());
json!({
"id": self.id, "kind": self.kind, "chart_id": self.chart_id, "synastry_id": self.synastry_id,
"forecast_id": self.forecast_id,
"language": self.language, "model": self.model, "status": self.status, "content": self.content,
"error": self.error, "model_used": self.model_used, "input_tokens": self.input_tokens,
"output_tokens": self.output_tokens, "cost_usd": self.cost_usd, "created_at": rfc3339(self.created_at),
@@ -208,29 +212,27 @@ pub async fn start_preview(
) -> ApiResult<(StatusCode, Json<Value>)> {
let kind = parse_target(&state, &kind, &language)?;
let system = clean_system(&req.system)?;
// The target must be the admin's own: a chart, or for a synastry analysis a comparison.
let (chart_id, synastry_id, found) = match (kind, req.chart_id, req.synastry_id) {
(Kind::Synastry, None, Some(id)) => {
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM synastries WHERE id = $1 AND owner_id = $2")
.bind(id)
.bind(admin.id())
.fetch_optional(&state.db)
.await?;
(None, Some(id), row.map(|_| "synastry"))
// The target must be the admin's own: a chart, a comparison or a forecast.
let (chart_id, synastry_id, forecast_id) = (req.chart_id, req.synastry_id, req.forecast_id);
let (query, id, what) = match (kind, chart_id, synastry_id, forecast_id) {
(Kind::Summary | Kind::Natal, Some(id), None, None) => {
("SELECT id FROM charts WHERE id = $1 AND owner_id = $2", id, "chart")
}
(Kind::Summary | Kind::Natal, Some(id), None) => {
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM charts WHERE id = $1 AND owner_id = $2")
.bind(id)
.bind(admin.id())
.fetch_optional(&state.db)
.await?;
(Some(id), None, row.map(|_| "chart"))
(Kind::Synastry, None, Some(id), None) => {
("SELECT id FROM synastries WHERE id = $1 AND owner_id = $2", id, "synastry")
}
(Kind::Forecast, None, None, Some(id)) => (
"SELECT f.id FROM forecasts f JOIN charts c ON c.id = f.chart_id WHERE f.id = $1 AND c.owner_id = $2",
id,
"forecast",
),
(Kind::Synastry, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
(Kind::Forecast, ..) => return Err(ApiError::BadRequest("a forecast analysis needs forecast_id".into())),
_ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
};
let found: Option<(Uuid,)> = sqlx::query_as(query).bind(id).bind(admin.id()).fetch_optional(&state.db).await?;
if found.is_none() {
return Err(ApiError::NotFound(if synastry_id.is_some() { "synastry" } else { "chart" }));
return Err(ApiError::NotFound(what));
}
let (open,): (i64,) = sqlx::query_as(
"SELECT count(*) FROM prompt_previews WHERE created_by = $1 AND status IN ('pending', 'running')",
@@ -249,13 +251,14 @@ pub async fn start_preview(
_ => &state.config.analysis_model,
};
let row: PreviewRow = sqlx::query_as(&format!(
"INSERT INTO prompt_previews (id, kind, chart_id, synastry_id, language, model, system, created_by) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING {PREVIEW_COLUMNS}"
"INSERT INTO prompt_previews (id, kind, chart_id, synastry_id, forecast_id, language, model, system, created_by) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {PREVIEW_COLUMNS}"
))
.bind(Uuid::now_v7())
.bind(kind.as_str())
.bind(chart_id)
.bind(synastry_id)
.bind(forecast_id)
.bind(&language)
.bind(model)
.bind(&system)
+28 -1
View File
@@ -929,7 +929,8 @@ async fn admins_edit_analysis_prompts(pool: PgPool) {
let prompts = r.body["prompts"].as_array().unwrap();
let keys: Vec<String> =
prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect();
assert_eq!(keys, ["summary/hu", "summary/en", "natal/hu", "natal/en", "synastry/hu", "synastry/en"]);
let expected = ["summary", "natal", "synastry", "forecast"].map(|k| [format!("{k}/hu"), format!("{k}/en")]);
assert_eq!(keys, expected.concat());
let natal = &prompts[2];
assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
assert!(natal["user_template"].as_str().unwrap().contains("{chart data}"));
@@ -1048,6 +1049,32 @@ async fn admins_try_prompt_drafts_on_own_charts(pool: PgPool) {
"{}",
r.body
);
// a yearly forecast is tried on a forecast of one of the admin's charts
sqlx::query("UPDATE prompt_previews SET status = 'done'").execute(&pool).await.unwrap();
let own_id = own["id"].as_str().unwrap();
let forecast = app.post(&format!("/v1/charts/{own_id}/forecasts"), Some(&admin), json!({})).await;
assert_eq!(forecast.status, StatusCode::CREATED, "{}", forecast.body);
let annas_id = annas["id"].as_str().unwrap();
let annas_forecast = app.post(&format!("/v1/charts/{annas_id}/forecasts"), Some(&anna), json!({})).await;
let uri = "/v1/admin/prompts/forecast/hu/preview";
let r = app.call("POST", uri, Some(&admin), Some(json!({"system": "Próba.", "chart_id": own["id"]}))).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
let body = json!({"system": "Próba.", "forecast_id": annas_forecast.body["id"]});
assert_eq!(app.call("POST", uri, Some(&admin), Some(body)).await.status, StatusCode::NOT_FOUND);
let body = json!({"system": "Próba.", "forecast_id": forecast.body["id"]});
let r = app.call("POST", uri, Some(&admin), Some(body)).await;
assert_eq!(
(r.status, r.body["forecast_id"].as_str()),
(StatusCode::ACCEPTED, forecast.body["id"].as_str()),
"{}",
r.body
);
// and its prompt is listed and can be saved like the others
let prompts = app.get("/v1/admin/prompts", Some(&admin)).await.body;
assert!(prompts["prompts"].as_array().unwrap().iter().any(|p| p["kind"] == "forecast"));
let r = app.call("PUT", "/v1/admin/prompts/forecast/hu", Some(&admin), Some(json!({"system": "Saját."}))).await;
assert_eq!((r.status, &r.body["custom"]), (StatusCode::OK, &json!(true)), "{}", r.body);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -28,6 +28,13 @@ const KINDS: { kind: PromptKind; id: string; label: string; about: string }[] =
label: "Kapcsolati elemzés",
about: "Fizetős összevetés-elemzés két képletről: öt fejezet, erősségek, kihívások és útravaló. Kérésre készül.",
},
{
kind: "forecast",
id: "elorejelzes",
label: "Éves előrejelzés",
about:
"Fizetős elemzés egy születésnaptól a következőig: szolár, lassú tranzitok, progresszió, profekció, fogyatkozások. Öt fejezet, lehetőségek, kihívások és útravaló. Kérésre készül.",
},
];
const LANGUAGES: Record<string, string> = { hu: "Magyar", en: "Angol" };
@@ -7,7 +7,7 @@ import { AnalysisView } from "@/components/AnalysisView";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import { listName } from "@/lib/synastry";
import type { ChartListItem, PromptKind, PromptPreview, SynastryListItem } from "@/lib/types";
import type { ChartListItem, ForecastList, ForecastSummary, PromptKind, PromptPreview, SynastryListItem } from "@/lib/types";
const POLL_MS = 4000;
const MAX_POLLS = 150; // 10 minutes
@@ -36,6 +36,7 @@ export function PromptTrial({
onLoad: (system: string) => void;
}) {
const synastry = kind === "synastry";
const forecastKind = kind === "forecast";
const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
const [synastries, setSynastries] = useState<SynastryListItem[]>([]);
const [synastryId, setSynastryId] = useState("");
@@ -50,7 +51,23 @@ export function PromptTrial({
})
.catch(() => setSynastries([]));
}, [synastry]);
const targetId = synastry ? synastryId : chartId;
// A forecast is tried on one of the chosen chart's calculated years.
const [forecasts, setForecasts] = useState<ForecastSummary[] | null>(null);
const [forecastId, setForecastId] = useState("");
const [allForecasts, setAllForecasts] = useState<ForecastSummary[]>([]);
useEffect(() => {
if (!forecastKind || !chartId) return;
setForecasts(null);
api<ForecastList>(`/charts/${chartId}/forecasts`)
.then((d) => {
setForecasts(d.forecasts);
setForecastId(d.forecasts[0]?.id ?? "");
setAllForecasts((all) => [...all.filter((f) => f.chart_id !== chartId), ...d.forecasts]);
})
.catch(() => setForecasts([]));
}, [forecastKind, chartId]);
const targetId = synastry ? synastryId : forecastKind ? forecastId : chartId;
const forecastName = (f: ForecastSummary) => `${f.year}–${f.year + 1} · ${f.place ?? "születési hely"}`;
const comparisonName = (s: SynastryListItem) => `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
const [trials, setTrials] = useState<Trial[]>([]);
const [busy, setBusy] = useState(false);
@@ -62,7 +79,11 @@ export function PromptTrial({
setError(null);
try {
const preview = await api<PromptPreview>(`/admin/prompts/${kind}/${language}/preview`, {
body: synastry ? { system: draft, synastry_id: synastryId } : { system: draft, chart_id: chartId },
body: synastry
? { system: draft, synastry_id: synastryId }
: forecastKind
? { system: draft, forecast_id: forecastId }
: { system: draft, chart_id: chartId },
});
setTrials((all) => [{ preview, system: draft }, ...all]);
} catch (e) {
@@ -84,7 +105,8 @@ export function PromptTrial({
<h2 id={`${selectId}-title`}>Kipróbálás</h2>
<p className="hint">
A szerkesztőben lévő szöveggel (mentés nélkül is) megírja az elemzést egy saját{" "}
{synastry ? "összevetésedre" : "képletedre"}. Az eredmény nem kerül {synastry ? "az összevetéshez" : "a képlethez"},
{synastry ? "összevetésedre" : forecastKind ? "előrejelzésedre" : "képletedre"}. Az eredmény nem kerül{" "}
{synastry ? "az összevetéshez" : forecastKind ? "az előrejelzéshez" : "a képlethez"},
csak itt látod. Valódi modellhívás, ezért költsége van.
</p>
</div>
@@ -110,6 +132,54 @@ export function PromptTrial({
</div>
) : charts.length === 0 ? (
<p className="muted">Kipróbáláshoz előbb legyen legalább egy képleted.</p>
) : forecastKind ? (
<div className="prompt-trial-form">
<div className="field">
<label htmlFor={selectId}>Képlet</label>
<select id={selectId} className="inp" value={chartId} onChange={(e) => setChartId(e.target.value)}>
{charts.map((c) => (
<option key={c.id} value={c.id}>
{c.is_primary ? `Én (${c.label})` : c.label}
{c.birth.time ? "" : " – idő nélkül"}
</option>
))}
</select>
</div>
{forecasts === null ? (
<p className="hint">Betöltés…</p>
) : forecasts.length === 0 ? (
<p className="muted">
Ehhez a képlethez még nincs kiszámolt év. Előbb kérj egyet az{" "}
<a href={`/kepletek/${chartId}/elorejelzes`}>előrejelzés oldalán</a> (a számítás ingyenes).
</p>
) : (
<>
<div className="field">
<label htmlFor={`${selectId}-year`}>Év</label>
<select
id={`${selectId}-year`}
className="inp"
value={forecastId}
onChange={(e) => setForecastId(e.target.value)}
>
{forecasts.map((f) => (
<option key={f.id} value={f.id}>
{forecastName(f)}
</option>
))}
</select>
</div>
<button
type="button"
className="btn btn-primary"
onClick={start}
disabled={busy || !targetId || !draft.trim()}
>
{busy ? "Indítás…" : "Kipróbálás"}
</button>
</>
)}
</div>
) : (
<div className="prompt-trial-form">
<div className="field">
@@ -138,7 +208,13 @@ export function PromptTrial({
key={t.preview.id}
trial={t}
chartLabel={
t.preview.synastry_id
t.preview.forecast_id
? (() => {
const f = allForecasts.find((x) => x.id === t.preview.forecast_id);
const c = f && charts.find((x) => x.id === f.chart_id);
return f ? `${c?.label ?? "Képlet"}, ${forecastName(f)}` : "Előrejelzés";
})()
: t.preview.synastry_id
? (() => {
const s = synastries.find((x) => x.id === t.preview.synastry_id);
return s ? comparisonName(s) : "Összevetés";
@@ -218,7 +294,13 @@ function TrialResult({
{waiting ? (
<AnalysisLoading
compact
text={p.kind === "summary" ? "Készül az összefoglaló, kb. 10–30 másodperc." : "Készül az elemzés, kb. 1–3 perc."}
text={
p.kind === "summary"
? "Készül az összefoglaló, kb. 10–30 másodperc."
: p.kind === "forecast"
? "Készül az előrejelzés, kb. 2–4 perc."
: "Készül az elemzés, kb. 1–3 perc."
}
/>
) : p.status === "failed" ? (
<p className="msg msg-error" role="alert">
@@ -231,7 +313,7 @@ function TrialResult({
<p className="summary-text">{p.content.summary}</p>
</div>
) : (
<AnalysisView content={p.content} kind={p.kind === "synastry" ? "synastry" : "natal"} />
<AnalysisView content={p.content} kind={p.kind} />
)
) : null}
{meta.length > 0 && !waiting && <p className="hint">{meta.join(" · ")}</p>}
+2 -1
View File
@@ -229,7 +229,7 @@ export interface AdminUser {
analyses_left: UnitBalance;
}
export type PromptKind = "summary" | "natal" | "synastry";
export type PromptKind = "summary" | "natal" | "synastry" | "forecast";
export interface PromptRevision {
id: number;
@@ -261,6 +261,7 @@ export interface PromptPreview {
kind: PromptKind;
chart_id: string | null;
synastry_id: string | null;
forecast_id: string | null;
language: string;
model: string;
status: "pending" | "running" | "done" | "failed";
+2 -1
View File
@@ -22,7 +22,8 @@ Háttérmunkák a közös PostgreSQL-adatbázis fölött: e-mail-küldés, szöv
**Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`)
- A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül.
- A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC.
- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v2`; ha a sor `prompt_version`-je `v2-r<id>`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön):
- **5 fokos szabály:** ha egy pont legfeljebb 5°-kal (`CUSP_ORB`) a következő ház csúcsa előtt áll, a szöveg már abban a házban adja meg, és odaírja, hogy formálisan az előzőben van („house 11 (on the cusp: 2°00' before it, formally house 10)”). Így olvassák az asztrológusok. A számított ház, a képlet rajza és a táblázatok nem változnak. Ugyanez érvényes az összevetés házátfedéseire, a szolár Aszcendensre, az év urára és a fogyatkozásokra.
- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v3`; ha a sor `prompt_version`-je `v3-r<id>`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön):
- `title`, `summary`;
- `sections`, radixnál: `personality`, `emotions`, `mind`, `love`, `work`, `growth`; szinasztriánál: `attraction`, `communication`, `emotional_bond`, `friction`, `long_term`;
- `strengths`, `challenges`, `advice`;
+90 -14
View File
@@ -75,12 +75,49 @@ fn names(list: &Value) -> String {
list.as_array().into_iter().flatten().filter_map(Value::as_str).map(point_name).collect::<Vec<_>>().join(", ")
}
/// A point at most this far before the next house cusp is read in that house,
/// as astrologers do (the "5° rule"). The calculation keeps the exact house.
const CUSP_ORB: f64 = 5.0;
/// "2°05'"
fn degrees(x: f64) -> String {
let minutes = (x * 60.0).round() as i64;
format!("{}°{:02}'", minutes / 60, minutes % 60)
}
fn point_longitude(chart: &Value, id: &str) -> Option<f64> {
points(chart).find(|p| p["id"] == id)?["longitude"].as_f64()
}
/// The house a point is read in: its own, or the next one when that cusp is
/// at most [`CUSP_ORB`] ahead, with how far ahead it is.
fn read_house(longitude: Option<f64>, house: i64, cusps: &Value) -> (i64, Option<f64>) {
let next = house % 12 + 1;
let cusp = cusps.as_array().into_iter().flatten().find(|c| c["house"].as_i64() == Some(next));
match (longitude, cusp.and_then(|c| c["longitude"].as_f64())) {
(Some(lon), Some(cusp)) if (cusp - lon).rem_euclid(360.0) <= CUSP_ORB => {
(next, Some((cusp - lon).rem_euclid(360.0)))
}
_ => (house, None),
}
}
/// "house 11 (on the cusp: 2°05' before it, formally house 10)" or "house 10".
fn house_text(longitude: Option<f64>, house: i64, cusps: &Value) -> String {
match read_house(longitude, house, cusps) {
(read, Some(before)) => {
format!("house {read} (on the cusp: {} before it, formally house {house})", degrees(before))
}
(read, None) => format!("house {read}"),
}
}
/// One line per point: "Sun: Cancer 0°24', house 3, retrograde, domicile".
fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) {
for p in points(chart).filter(|p| MAIN_POINTS.contains(&p["id"].as_str().unwrap_or(""))) {
let mut line = format!("{prefix}- {}: {}", point_name(p["id"].as_str().unwrap_or("?")), position(p));
if houses && let Some(h) = p["house"].as_i64() {
let _ = write!(line, ", house {h}");
let _ = write!(line, ", {}", house_text(p["longitude"].as_f64(), h, &chart["houses"]["cusps"]));
}
if p["retrograde"].as_bool() == Some(true) {
line.push_str(", retrograde");
@@ -97,7 +134,10 @@ fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) {
.filter(|p| ASTEROIDS.contains(&p["id"].as_str().unwrap_or("")))
.map(|p| {
let house = if houses {
p["house"].as_i64().map(|h| format!(" (house {h})")).unwrap_or_default()
p["house"]
.as_i64()
.map(|h| format!(" ({})", house_text(p["longitude"].as_f64(), h, &chart["houses"]["cusps"])))
.unwrap_or_default()
} else {
String::new()
};
@@ -155,12 +195,15 @@ pub fn natal(chart: &Value) -> String {
if kind == "modern" && ruler["traditional"]["planet"] == r["planet"] {
continue;
}
let house = r["house"].as_i64().map_or_else(
|| "house ?".to_string(),
|h| house_text(point_longitude(chart, planet), h, &chart["houses"]["cusps"]),
);
let _ = writeln!(
out,
"- Chart ruler ({kind}): {} in {}, house {}",
"- Chart ruler ({kind}): {} in {}, {house}",
point_name(planet),
capitalize(r["sign"].as_str().unwrap_or("?")),
r["house"]
);
}
}
@@ -199,7 +242,10 @@ pub fn natal(chart: &Value) -> String {
}
if known && let Some(fortune) = chart["lots"]["fortune"].as_object() {
let fortune = Value::Object(fortune.clone());
let _ = writeln!(out, "- Part of Fortune: {}, house {}", position(&fortune), fortune["house"]);
if let Some(h) = fortune["house"].as_i64() {
let house = house_text(fortune["longitude"].as_f64(), h, &chart["houses"]["cusps"]);
let _ = writeln!(out, "- Part of Fortune: {}, {house}", position(&fortune));
}
}
out
}
@@ -251,16 +297,23 @@ pub fn synastry(chart1: &Value, chart2: &Value, result: &Value) -> String {
}
let overlays = &result["house_overlays"];
for (key, label) in [
("person1_in_person2", "Person 1's planets in Person 2's houses"),
("person2_in_person1", "Person 2's planets in Person 1's houses"),
for (key, label, own, other) in [
("person1_in_person2", "Person 1's planets in Person 2's houses", chart1, chart2),
("person2_in_person1", "Person 2's planets in Person 1's houses", chart2, chart1),
] {
let list: Vec<String> = overlays[key]
.as_array()
.into_iter()
.flatten()
.filter(|o| MAIN_POINTS.contains(&o["point"].as_str().unwrap_or("")))
.filter_map(|o| Some(format!("{} {}", point_name(o["point"].as_str()?), o["house"].as_i64()?)))
.filter_map(|o| {
let point = o["point"].as_str()?;
let house = o["house"].as_i64()?;
Some(match read_house(point_longitude(own, point), house, &other["houses"]["cusps"]) {
(read, Some(_)) => format!("{} {read} (on the cusp, formally {house})", point_name(point)),
(read, None) => format!("{} {read}", point_name(point)),
})
})
.collect();
if !list.is_empty() {
let _ = writeln!(out, "\n{label}: {}", list.join(", "));
@@ -357,7 +410,12 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
out.push_str("\nSOLAR RETURN CHART (cast for the moment of the solar return at the place of the birthday):\n");
angle_lines(&mut out, sr, "");
if let Some(h) = sr["natal_house_of_ascendant"].as_i64() {
let _ = writeln!(out, "- The solar return Ascendant falls in natal house {h}.");
let asc = sr["angles"]["ascendant"]["longitude"].as_f64();
let _ = writeln!(
out,
"- The solar return Ascendant falls in natal {}.",
house_text(asc, h, &chart["houses"]["cusps"])
);
}
point_lines(&mut out, sr, "", true);
aspect_lines(&mut out, &sr["aspects"], "Solar return aspects (tightest first):", 15);
@@ -370,13 +428,16 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
let planets = names(&p["planets_in_sign"]);
let _ = writeln!(
out,
"\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, house {}).{}",
"\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, {}).{}",
p["house"],
capitalize(p["sign"].as_str().unwrap_or("?")),
point_name(p["lord"].as_str().unwrap_or("?")),
point_name(p["lord"].as_str().unwrap_or("?")),
capitalize(p["lord_sign"].as_str().unwrap_or("?")),
p["lord_house"],
p["lord_house"].as_i64().map_or_else(
|| "house ?".to_string(),
|h| house_text(point_longitude(chart, p["lord"].as_str().unwrap_or("")), h, &chart["houses"]["cusps"])
),
if planets.is_empty() { String::new() } else { format!(" Natal planets in that sign: {planets}.") }
);
}
@@ -466,7 +527,7 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
position(e)
);
if let Some(h) = e["house"].as_i64() {
let _ = write!(line, ", natal house {h}");
let _ = write!(line, ", natal {}", house_text(e["longitude"].as_f64(), h, &chart["houses"]["cusps"]));
}
let hits: Vec<String> = e["contacts"]
.as_array()
@@ -525,6 +586,7 @@ fn aspect_lines(out: &mut String, aspects: &Value, heading: &str, limit: usize)
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn fixture(name: &str) -> Value {
let path = format!("{}/testdata/{name}", env!("CARGO_MANIFEST_DIR"));
@@ -539,6 +601,19 @@ mod tests {
}
}
#[test]
fn points_just_before_a_cusp_are_read_in_the_next_house() {
let cusps = json!([{"house": 10, "longitude": 300.0}, {"house": 11, "longitude": 319.0}]);
// Moon at 17° with the 11th cusp at 19°: an astrologer reads it in the 11th.
assert_eq!(read_house(Some(317.0), 10, &cusps), (11, Some(2.0)));
assert_eq!(house_text(Some(317.0), 10, &cusps), "house 11 (on the cusp: 2°00' before it, formally house 10)");
assert_eq!(read_house(Some(313.0), 10, &cusps), (10, None));
assert_eq!(read_house(None, 10, &cusps), (10, None));
// across 0° Aries, and from the 12th to the 1st
let cusps = json!([{"house": 1, "longitude": 2.0}]);
assert_eq!(read_house(Some(358.5), 12, &cusps), (1, Some(3.5)));
}
#[test]
fn natal_with_birth_time() {
let text = natal(&fixture("natal-1990-03-15.json"));
@@ -553,7 +628,8 @@ mod tests {
"House cusps: 1 Leo 19°23' | 2 Virgo 9°35'",
"- Moon trine Chiron (orb 0.1°, applying)",
"- Elements: air 2 (Venus, Mars); earth 3 (Saturn, Uranus, Neptune); fire 0;",
"- Part of Fortune: Aries 5°10', house 8",
// 4' before the 9th cusp: read in the 9th
"- Part of Fortune: Aries 5°10', house 9 (on the cusp: 0°04' before it, formally house 8)",
] {
assert!(text.contains(expected), "missing '{expected}' in:\n{text}");
}
+4 -2
View File
@@ -48,6 +48,7 @@ pub struct PreviewJob {
pub kind: String,
pub chart_id: Option<Uuid>,
pub synastry_id: Option<Uuid>,
pub forecast_id: Option<Uuid>,
pub language: String,
pub model: String,
pub system: String,
@@ -159,7 +160,7 @@ impl Analyzer {
"UPDATE prompt_previews SET status = 'running', started_at = now() \
WHERE id = (SELECT id FROM prompt_previews WHERE status = 'pending' \
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
RETURNING id, kind, chart_id, synastry_id, language, model, system",
RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, system",
)
.fetch_optional(&self.db)
.await?;
@@ -177,7 +178,8 @@ impl Analyzer {
Kind::parse(&job.kind).ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
let text = match kind {
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
_ => self.natal_text(job.chart_id).await?,
Kind::Forecast => self.forecast_text(job.forecast_id).await?,
Kind::Natal | Kind::Summary => self.natal_text(job.chart_id).await?,
};
let built = prompt::build(kind, &job.language, &text, Some(&job.system));
let mut c = self.llm.complete(&job.model, &built).await?;