Comparisons (synastry) of the own chart and persons
/osszevetesek compares any two of the user's charts (own and persons); the person card and the person's chart page have "Összevetés velem". The comparison page shows a double wheel (first person inside with houses, second outside, aspects between them), the aspects by character, and tabs: paid relationship analysis (synastry unit), the cross aspect grid, house overlays, composite and the full aspect list. Correcting a person within the hour now deletes the user's own comparisons with them instead of being refused; still refused after a paid analysis or when someone else's comparison uses the chart. The relationship analysis prompt is editable on /admin/promptok too, and can be tried on one of the admin's comparisons. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
-- Prompt test runs of the relationship (synastry) analysis: on one of the
|
||||
-- admin's comparisons instead of a chart.
|
||||
ALTER TABLE prompt_previews DROP CONSTRAINT prompt_previews_kind_check;
|
||||
ALTER TABLE prompt_previews ALTER COLUMN chart_id DROP NOT NULL;
|
||||
ALTER TABLE prompt_previews
|
||||
ADD COLUMN synastry_id uuid REFERENCES synastries ON DELETE CASCADE,
|
||||
ADD CONSTRAINT prompt_previews_target CHECK (
|
||||
(kind IN ('summary', 'natal') AND chart_id IS NOT NULL AND synastry_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL)
|
||||
);
|
||||
@@ -122,5 +122,5 @@ A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket
|
||||
## Korlátok
|
||||
|
||||
- **Saját születési adatok módosítása:** az első mentés után egy órán belül még háromszor javíthatók, utána naponta egyszer (`birth_data_changes` tábla). A tiltott módosítás 429-et ad `birth_data_change_limit` kóddal, a felhasználónak szóló üzenettel („A rendszer csak napi egy módosítást engedélyez. …”). A `/v1/me` `birth_change` mezője mutatja, él-e a napi korlát. Más emberek képleteit ez nem érinti.
|
||||
- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Egységet a személycsomag ad (`PERSON_PACK_SIZE` darab), a korlátlan csomag az `entitlements` tábla `unlimited_persons` sora. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`; részletes elemzés vagy szinasztria után sem. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`.
|
||||
- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Egységet a személycsomag ad (`PERSON_PACK_SIZE` darab), a korlátlan csomag az `entitlements` tábla `unlimited_persons` sora. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`. Részletes elemzés (képlet vagy összevetés) után sem (409 `person_analysed`), és akkor sem, ha valaki más összevetésében szerepel (409 `person_in_synastry`); a saját, elemzés nélküli összevetései a javításkor törlődnek. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`.
|
||||
- **Admin:** nincs módosítási korlát, korlátlan személy, a személyek adatai bármikor javíthatók, és a részletes elemzés ingyenes (nem fogy egység).
|
||||
|
||||
@@ -273,8 +273,9 @@ pub async fn update(
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
if let Some((birth, result, hash)) = &recalculated {
|
||||
// The old summary (and an admin's analyses) no longer match the chart.
|
||||
// The old summary, the comparisons (and an admin's analyses) no longer match the chart.
|
||||
sqlx::query("DELETE FROM analyses WHERE chart_id = $1").bind(id).execute(&mut *tx).await?;
|
||||
sqlx::query("DELETE FROM synastries WHERE chart1_id = $1 OR chart2_id = $1").bind(id).execute(&mut *tx).await?;
|
||||
sqlx::query("UPDATE charts SET birth_data = $1, result = $2, chart_hash = $3 WHERE id = $4")
|
||||
.bind(birth)
|
||||
.bind(result)
|
||||
@@ -322,11 +323,16 @@ async fn corrected_birth(
|
||||
return Err(ApiError::conflict("person_locked", persons::LOCKED_MESSAGE));
|
||||
}
|
||||
let admin = auth.user.has_role(db::Role::Admin);
|
||||
let (analysed, in_synastry): (bool, bool) = sqlx::query_as(
|
||||
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed'), \
|
||||
EXISTS (SELECT 1 FROM synastries WHERE chart1_id = $1 OR chart2_id = $1)",
|
||||
// The user's own comparisons with the person are deleted on correction (they
|
||||
// no longer match), unless a paid analysis was written for one of them.
|
||||
let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as(
|
||||
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed') \
|
||||
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'), \
|
||||
EXISTS (SELECT 1 FROM synastries WHERE (chart1_id = $1 OR chart2_id = $1) AND owner_id <> $2)",
|
||||
)
|
||||
.bind(chart.id)
|
||||
.bind(auth.id())
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
if analysed && !admin {
|
||||
@@ -335,10 +341,10 @@ async fn corrected_birth(
|
||||
"Ehhez a személyhez már készült részletes elemzés, ezért az adatai nem módosíthatók.",
|
||||
));
|
||||
}
|
||||
if in_synastry {
|
||||
if foreign_synastry {
|
||||
return Err(ApiError::conflict(
|
||||
"person_in_synastry",
|
||||
"A személy szerepel egy összevetésben, ezért az adatai nem módosíthatók.",
|
||||
"A személy szerepel valaki más összevetésében, ezért az adatai nem módosíthatók.",
|
||||
));
|
||||
}
|
||||
calculate(state, birth).await
|
||||
|
||||
@@ -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; 2] = [Kind::Summary, Kind::Natal];
|
||||
const EDITABLE: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry];
|
||||
const MAX_CHARS: usize = 50_000;
|
||||
const HISTORY: i64 = 20;
|
||||
/// Test runs of one admin waiting or being written at the same time.
|
||||
@@ -158,55 +158,46 @@ pub async fn save(
|
||||
pub struct StartPreview {
|
||||
/// The draft to try (it need not be saved).
|
||||
system: String,
|
||||
/// One of the admin's own charts (own or a person).
|
||||
chart_id: Uuid,
|
||||
/// One of the admin's own charts (own or a person), for a summary or natal analysis.
|
||||
chart_id: Option<Uuid>,
|
||||
/// One of the admin's own comparisons, for a synastry analysis.
|
||||
synastry_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
type PreviewRow = (
|
||||
Uuid,
|
||||
String,
|
||||
Uuid,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
Option<Value>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<i32>,
|
||||
Option<i32>,
|
||||
Option<f64>,
|
||||
OffsetDateTime,
|
||||
Option<OffsetDateTime>,
|
||||
Option<OffsetDateTime>,
|
||||
);
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct PreviewRow {
|
||||
id: Uuid,
|
||||
kind: String,
|
||||
chart_id: Option<Uuid>,
|
||||
synastry_id: Option<Uuid>,
|
||||
language: String,
|
||||
model: String,
|
||||
status: String,
|
||||
content: Option<Value>,
|
||||
error: Option<String>,
|
||||
model_used: Option<String>,
|
||||
input_tokens: Option<i32>,
|
||||
output_tokens: Option<i32>,
|
||||
cost_usd: Option<f64>,
|
||||
created_at: OffsetDateTime,
|
||||
started_at: Option<OffsetDateTime>,
|
||||
completed_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, language, model, status, content, error, model_used, \
|
||||
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, status, content, error, model_used, \
|
||||
input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
|
||||
|
||||
fn preview_view(row: PreviewRow) -> Value {
|
||||
let (
|
||||
id,
|
||||
kind,
|
||||
chart_id,
|
||||
language,
|
||||
model,
|
||||
status,
|
||||
content,
|
||||
error,
|
||||
model_used,
|
||||
input,
|
||||
output,
|
||||
cost,
|
||||
created,
|
||||
started,
|
||||
completed,
|
||||
) = row;
|
||||
let seconds = started.zip(completed).map(|(s, c)| (c - s).whole_seconds());
|
||||
json!({
|
||||
"id": id, "kind": kind, "chart_id": chart_id, "language": language, "model": model, "status": status,
|
||||
"content": content, "error": error, "model_used": model_used, "input_tokens": input, "output_tokens": output,
|
||||
"cost_usd": cost, "created_at": rfc3339(created), "completed_at": rfc3339_opt(completed), "seconds": seconds,
|
||||
})
|
||||
impl PreviewRow {
|
||||
fn view(self) -> Value {
|
||||
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,
|
||||
"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),
|
||||
"completed_at": rfc3339_opt(self.completed_at), "seconds": seconds,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start_preview(
|
||||
@@ -217,12 +208,30 @@ pub async fn start_preview(
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let kind = parse_target(&state, &kind, &language)?;
|
||||
let system = clean_system(&req.system)?;
|
||||
let own: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM charts WHERE id = $1 AND owner_id = $2")
|
||||
.bind(req.chart_id)
|
||||
.bind(admin.id())
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
own.ok_or(ApiError::NotFound("chart"))?;
|
||||
// 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"))
|
||||
}
|
||||
(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, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
|
||||
_ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
|
||||
};
|
||||
if found.is_none() {
|
||||
return Err(ApiError::NotFound(if synastry_id.is_some() { "synastry" } else { "chart" }));
|
||||
}
|
||||
let (open,): (i64,) = sqlx::query_as(
|
||||
"SELECT count(*) FROM prompt_previews WHERE created_by = $1 AND status IN ('pending', 'running')",
|
||||
)
|
||||
@@ -240,19 +249,20 @@ pub async fn start_preview(
|
||||
_ => &state.config.analysis_model,
|
||||
};
|
||||
let row: PreviewRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO prompt_previews (id, kind, chart_id, language, model, system, created_by) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING {PREVIEW_COLUMNS}"
|
||||
"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}"
|
||||
))
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(kind.as_str())
|
||||
.bind(req.chart_id)
|
||||
.bind(chart_id)
|
||||
.bind(synastry_id)
|
||||
.bind(&language)
|
||||
.bind(model)
|
||||
.bind(&system)
|
||||
.bind(admin.id())
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok((StatusCode::ACCEPTED, Json(preview_view(row))))
|
||||
Ok((StatusCode::ACCEPTED, Json(row.view())))
|
||||
}
|
||||
|
||||
pub async fn get_preview(
|
||||
@@ -266,5 +276,5 @@ pub async fn get_preview(
|
||||
.bind(admin.id())
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
Ok(Json(preview_view(row.ok_or(ApiError::NotFound("preview"))?)))
|
||||
Ok(Json(row.ok_or(ApiError::NotFound("preview"))?.view()))
|
||||
}
|
||||
|
||||
@@ -840,7 +840,7 @@ 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"]);
|
||||
assert_eq!(keys, ["summary/hu", "summary/en", "natal/hu", "natal/en", "synastry/hu", "synastry/en"]);
|
||||
let natal = &prompts[2];
|
||||
assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
|
||||
assert!(natal["user_template"].as_str().unwrap().contains("{chart data}"));
|
||||
@@ -848,7 +848,7 @@ async fn admins_edit_analysis_prompts(pool: PgPool) {
|
||||
|
||||
let put = |body: Value, uri: &'static str| app.call("PUT", uri, Some(&admin), Some(body));
|
||||
assert_eq!(put(json!({"system": " "}), "/v1/admin/prompts/natal/hu").await.status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/synastry/hu").await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/composite/hu").await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/natal/de").await.status, StatusCode::NOT_FOUND);
|
||||
// saving the built-in text keeps the built-in prompt
|
||||
let r = put(json!({"system": default}), "/v1/admin/prompts/natal/hu").await;
|
||||
@@ -945,4 +945,49 @@ async fn admins_try_prompt_drafts_on_own_charts(pool: PgPool) {
|
||||
sqlx::query("UPDATE prompt_previews SET status = 'done'").execute(&pool).await.unwrap();
|
||||
let r = app.call("POST", "/v1/admin/prompts/natal/hu/preview", Some(&admin), Some(body)).await;
|
||||
assert_eq!((r.status, r.body["model"].as_str()), (StatusCode::ACCEPTED, Some("anthropic/claude-test")));
|
||||
|
||||
// a relationship analysis is tried on one of the admin's comparisons
|
||||
let other = app.chart(&admin, "Béla", false, "1985-08-02").await;
|
||||
let syn = app.post("/v1/synastries", Some(&admin), json!({"chart1_id": own["id"], "chart2_id": other["id"]})).await;
|
||||
let uri = "/v1/admin/prompts/synastry/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 r = app.call("POST", uri, Some(&admin), Some(json!({"system": "Próba.", "synastry_id": syn.body["id"]}))).await;
|
||||
assert_eq!(
|
||||
(r.status, r.body["synastry_id"].as_str()),
|
||||
(StatusCode::ACCEPTED, syn.body["id"].as_str()),
|
||||
"{}",
|
||||
r.body
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn comparisons_with_persons(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
let bela = app.chart(&anna, "Béla", false, "1985-08-02").await;
|
||||
let compare = || app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": bela["id"]}));
|
||||
let r = compare().await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let first = r.body["id"].as_str().unwrap().to_string();
|
||||
assert_eq!((&r.body["chart1"]["is_primary"], &r.body["chart2"]["label"]), (&json!(true), &json!("Béla")));
|
||||
|
||||
// correcting the person removes the comparison that no longer matches
|
||||
let uri = format!("/v1/charts/{}", bela["id"].as_str().unwrap());
|
||||
let corrected = |date: &str| json!({"birth": {"date": date, "time": "10:00", "country": "HU", "place": "Szeged"}});
|
||||
let r = app.call("PATCH", &uri, Some(&anna), Some(corrected("1985-08-03"))).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(app.get(&format!("/v1/synastries/{first}"), Some(&anna)).await.status, StatusCode::NOT_FOUND);
|
||||
|
||||
// after a paid relationship analysis the person is fixed
|
||||
let r = compare().await;
|
||||
assert_eq!(r.status, StatusCode::CREATED);
|
||||
let id = r.body["id"].as_str().unwrap();
|
||||
grant_units(&app, &anna, "synastry", 1).await;
|
||||
let r = app.call("POST", &format!("/v1/synastries/{id}/analyses"), Some(&anna), None).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
let r = app.call("PATCH", &uri, Some(&anna), Some(corrected("1985-08-04"))).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_analysed")));
|
||||
assert_eq!(app.get("/v1/synastries", Some(&anna)).await.body["synastries"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
@@ -11,10 +11,15 @@ Next.js (App Router, TypeScript) webes felület. A compose-ban a **3001-es** por
|
||||
- **saját születési adatok**: dátum, idő (vagy „nem tudom”), ország és település helykeresővel. Mentéskor kiszámolja a képletet, és megmutatja a pozíciókat (bolygók, tengelyek, házcsúcsok).
|
||||
- A javított adatokból új képlet lesz (a backend a születési adatot nem módosítja), és az lesz a saját képlet.
|
||||
- Ha a megadott időpont az óraátállítás miatt kétszer is előfordult, a felület megkérdezi, melyikről van szó.
|
||||
- **Összevetések** (`/osszevetesek`, szinasztria): a saját és a felvett személyek képletei közül bármelyik kettő összevethető; a személykártyán és a személy képletoldalán „Összevetés velem” gomb is van. Az összevetés oldala (`/osszevetesek/{id}`):
|
||||
- kettős kör: belül az első fél bolygói és házai, kívül a második fél bolygói, középen a köztük lévő főfényszögek;
|
||||
- a fényszögek jelleg szerint (harmonikus, feszültebb, együttállás);
|
||||
- fülek: fizetős kapcsolati elemzés (`synastry` egység), a két fél közti fényszögmátrix, házátfedések, kompozit, részletes lista.
|
||||
- **Admin** (`/admin`, csak `admin` szerepkörrel; másnak 404):
|
||||
- felhasználók keresése;
|
||||
- szerepkörök be- és kikapcsolása (felhasználó, prémium, VIP, szerző, admin);
|
||||
- elemzések jóváírása típusonként (képlet, szinasztria).
|
||||
- elemzések jóváírása típusonként (képlet, szinasztria);
|
||||
- **Promptok** (`/admin/promptok`): a tömör összefoglaló, a részletes és a kapcsolati elemzés system promptja szerkeszthető, változatokkal; mentés előtt egy saját képleten vagy összevetésen kipróbálható.
|
||||
- **Jogosultság:** a belépést nem igénylő oldalakon kívül minden oldal a szerveren ellenőrzi a munkamenetet; belépés nélkül a belépőoldalra irányít, majd vissza.
|
||||
|
||||
## Felépítés
|
||||
|
||||
@@ -22,6 +22,12 @@ const KINDS: { kind: PromptKind; id: string; label: string; about: string }[] =
|
||||
label: "Részletes elemzés",
|
||||
about: "Fizetős, hat fejezet, erősségek, kihívások és útravaló. Kérésre készül.",
|
||||
},
|
||||
{
|
||||
kind: "synastry",
|
||||
id: "kapcsolati",
|
||||
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.",
|
||||
},
|
||||
];
|
||||
|
||||
const LANGUAGES: Record<string, string> = { hu: "Magyar", en: "Angol" };
|
||||
|
||||
@@ -6,7 +6,8 @@ import { AnalysisLoading } from "@/components/AnalysisLoading";
|
||||
import { AnalysisView } from "@/components/AnalysisView";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/astro";
|
||||
import type { ChartListItem, PromptKind, PromptPreview } from "@/lib/types";
|
||||
import { listName } from "@/lib/synastry";
|
||||
import type { ChartListItem, PromptKind, PromptPreview, SynastryListItem } from "@/lib/types";
|
||||
|
||||
const POLL_MS = 4000;
|
||||
const MAX_POLLS = 150; // 10 minutes
|
||||
@@ -34,7 +35,23 @@ export function PromptTrial({
|
||||
charts: ChartListItem[];
|
||||
onLoad: (system: string) => void;
|
||||
}) {
|
||||
const synastry = kind === "synastry";
|
||||
const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
|
||||
const [synastries, setSynastries] = useState<SynastryListItem[]>([]);
|
||||
const [synastryId, setSynastryId] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!synastry) return;
|
||||
api<{ synastries: SynastryListItem[] }>("/synastries")
|
||||
.then((d) => {
|
||||
const own = d.synastries.filter((s) => s.owned);
|
||||
setSynastries(own);
|
||||
setSynastryId((current) => current || own[0]?.id || "");
|
||||
})
|
||||
.catch(() => setSynastries([]));
|
||||
}, [synastry]);
|
||||
const targetId = synastry ? synastryId : chartId;
|
||||
const comparisonName = (s: SynastryListItem) => `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
|
||||
const [trials, setTrials] = useState<Trial[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -45,7 +62,7 @@ export function PromptTrial({
|
||||
setError(null);
|
||||
try {
|
||||
const preview = await api<PromptPreview>(`/admin/prompts/${kind}/${language}/preview`, {
|
||||
body: { system: draft, chart_id: chartId },
|
||||
body: synastry ? { system: draft, synastry_id: synastryId } : { system: draft, chart_id: chartId },
|
||||
});
|
||||
setTrials((all) => [{ preview, system: draft }, ...all]);
|
||||
} catch (e) {
|
||||
@@ -66,11 +83,32 @@ export function PromptTrial({
|
||||
<div className="prompt-trial-head">
|
||||
<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 képletedre. Az eredmény nem
|
||||
kerül a képlethez, csak itt látod. Valódi modellhívás, ezért költsége van.
|
||||
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"},
|
||||
csak itt látod. Valódi modellhívás, ezért költsége van.
|
||||
</p>
|
||||
</div>
|
||||
{charts.length === 0 ? (
|
||||
{synastry && synastries.length === 0 ? (
|
||||
<p className="muted">
|
||||
Kipróbáláshoz előbb készíts egy összevetést az <a href="/osszevetesek">Összevetések</a> oldalon.
|
||||
</p>
|
||||
) : synastry ? (
|
||||
<div className="prompt-trial-form">
|
||||
<div className="field">
|
||||
<label htmlFor={selectId}>Összevetés</label>
|
||||
<select id={selectId} className="inp" value={synastryId} onChange={(e) => setSynastryId(e.target.value)}>
|
||||
{synastries.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{comparisonName(s)}
|
||||
</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>
|
||||
) : charts.length === 0 ? (
|
||||
<p className="muted">Kipróbáláshoz előbb legyen legalább egy képleted.</p>
|
||||
) : (
|
||||
<div className="prompt-trial-form">
|
||||
@@ -99,7 +137,14 @@ export function PromptTrial({
|
||||
<TrialResult
|
||||
key={t.preview.id}
|
||||
trial={t}
|
||||
chartLabel={charts.find((c) => c.id === t.preview.chart_id)?.label ?? "Képlet"}
|
||||
chartLabel={
|
||||
t.preview.synastry_id
|
||||
? (() => {
|
||||
const s = synastries.find((x) => x.id === t.preview.synastry_id);
|
||||
return s ? comparisonName(s) : "Összevetés";
|
||||
})()
|
||||
: (charts.find((c) => c.id === t.preview.chart_id)?.label ?? "Képlet")
|
||||
}
|
||||
changed={t.system.trim() !== draft.trim()}
|
||||
onUpdate={update}
|
||||
onLoad={() => onLoad(t.system)}
|
||||
@@ -186,7 +231,7 @@ function TrialResult({
|
||||
<p className="summary-text">{p.content.summary}</p>
|
||||
</div>
|
||||
) : (
|
||||
<AnalysisView content={p.content} />
|
||||
<AnalysisView content={p.content} kind={p.kind === "synastry" ? "synastry" : "natal"} />
|
||||
)
|
||||
) : null}
|
||||
{meta.length > 0 && !waiting && <p className="hint">{meta.join(" · ")}</p>}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
--harmonic: #7fb0e0;
|
||||
--tense: #e38b8b;
|
||||
--square: #f0a35e;
|
||||
--p2: #c3a6f0; /* the second person of a comparison */
|
||||
--radius: 10px;
|
||||
--font-display: var(--font-cormorant), "Cormorant Garamond", Georgia, serif;
|
||||
--font-body: var(--font-inter), Inter, system-ui, sans-serif;
|
||||
@@ -459,3 +460,60 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.prompt-trial-form .field { flex-basis: 100%; }
|
||||
.prompt-trial-form .btn { width: 100%; }
|
||||
}
|
||||
|
||||
/* Comparisons (synastry) */
|
||||
.w-p2 .w-point-glyph { fill: var(--p2); }
|
||||
.w-p2 .w-point-tick { stroke: var(--p2); }
|
||||
.w-p2 .w-point:hover .w-point-glyph { fill: var(--gold); }
|
||||
.w-end-p2 { fill: var(--p2); }
|
||||
.w-p2-band { stroke-dasharray: 2 4; }
|
||||
.legend-dot, .pair-dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; flex: none; }
|
||||
.legend-p1 { background: var(--ink); }
|
||||
.legend-p2 { background: var(--p2); }
|
||||
.p2-text, .cross-grid th.p2-head { color: var(--p2); }
|
||||
.cross-grid td.cross-corner { position: relative; min-width: 76px; height: 44px; font: 500 11px var(--font-body); color: var(--muted); }
|
||||
.cross-col { position: absolute; top: 2px; right: 4px; color: var(--p2); white-space: nowrap; }
|
||||
.cross-row { position: absolute; bottom: 2px; left: 2px; white-space: nowrap; }
|
||||
|
||||
.nature { display: flex; flex-direction: column; gap: 12px; }
|
||||
.nature-bar { display: flex; gap: 3px; height: 10px; border-radius: 999px; overflow: hidden; }
|
||||
.nature-bar-sm { height: 6px; margin-top: 4px; }
|
||||
.nature-seg { flex-basis: 0; min-width: 4px; }
|
||||
.nature-harmonious { background: var(--harmonic); }
|
||||
.nature-challenging { background: var(--tense); }
|
||||
.nature-neutral { background: var(--gold); }
|
||||
.nature-list { margin: 0; display: flex; flex-direction: column; gap: 8px; }
|
||||
.nature-list > div { display: grid; grid-template-columns: 128px 1fr; gap: 8px; align-items: baseline; }
|
||||
.nature-list dt { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink-2); }
|
||||
.nature-list dd { margin: 0; }
|
||||
.nature-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
|
||||
|
||||
.pair-card { gap: 4px; }
|
||||
.pair-row {
|
||||
display: grid; grid-template-columns: auto 1fr auto; gap: 12px; align-items: center; padding: 10px 0;
|
||||
color: inherit; text-decoration: none; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.pair-row:last-child { border-bottom: 0; padding-bottom: 0; }
|
||||
a.pair-row:hover strong { color: var(--gold); }
|
||||
.pair-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.pair-text strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
|
||||
|
||||
.compare-new { gap: 16px; }
|
||||
.compare-form { display: grid; grid-template-columns: 1fr auto 1fr auto; gap: 12px; align-items: end; }
|
||||
.compare-swap { font-size: 20px; padding: 0 10px; }
|
||||
.compare-tile { gap: 6px; padding: 16px 20px; }
|
||||
.compare-tile strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
|
||||
.compare-tile .muted { font-size: 14px; }
|
||||
.compare-tile .form-actions { margin-top: 6px; }
|
||||
.back-link { font-size: 14px; text-decoration: none; align-self: flex-start; }
|
||||
@media (max-width: 640px) {
|
||||
.compare-form { grid-template-columns: 1fr auto; }
|
||||
.compare-form .field:first-child { grid-column: 1; }
|
||||
.compare-swap { grid-column: 2; grid-row: 1 / span 2; align-self: center; }
|
||||
.compare-form .field:nth-child(3) { grid-column: 1; }
|
||||
.compare-form > .btn-primary { grid-column: 1 / -1; width: 100%; }
|
||||
.nature-list > div { grid-template-columns: 1fr; gap: 2px; }
|
||||
.nav { overflow-x: auto; scrollbar-width: none; }
|
||||
.nav a { white-space: nowrap; padding: 10px 9px; }
|
||||
.cross-grid td.cross-corner { min-width: 56px; font-size: 9px; }
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ChartSummary } from "@/components/ChartSummary";
|
||||
import { ChartSwitcher } from "@/components/ChartSwitcher";
|
||||
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
|
||||
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
|
||||
import { CompareButton } from "@/components/CompareButton";
|
||||
import { Tabs } from "@/components/Tabs";
|
||||
import { ASPECTS, ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
@@ -31,6 +32,7 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
]);
|
||||
const charts = chartList?.charts ?? [];
|
||||
const persons = charts.filter((c) => c.kind === "person");
|
||||
const own = charts.find((c) => c.is_primary) ?? null;
|
||||
if (!chart) notFound();
|
||||
const list = analyses?.analyses ?? [];
|
||||
const summary = list.find((a) => a.kind === "summary" && a.status !== "failed") ?? null;
|
||||
@@ -51,7 +53,7 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
<ChartSwitcher
|
||||
title={chart.is_primary ? "Születési képletem" : chart.label}
|
||||
currentId={chart.id}
|
||||
own={charts.find((c) => c.is_primary) ?? null}
|
||||
own={own}
|
||||
persons={persons}
|
||||
canAdd={me.persons.left !== 0}
|
||||
/>
|
||||
@@ -116,6 +118,16 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!chart.is_primary && own && (
|
||||
<div className="card compare-tile">
|
||||
<span className="eyebrow">Összevetés</span>
|
||||
<strong>Te és {chart.label}</strong>
|
||||
<span className="muted">Két képlet egy körön: mi vonz, hol súrlódtok, és mit ad a kapcsolat.</span>
|
||||
<div className="form-actions">
|
||||
<CompareButton chart1={own.id} chart2={chart.id} label="Összevetés velem" className="btn" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{chart.is_primary && (
|
||||
<Link href="/szemelyek" className="card persons-tile">
|
||||
<span className="eyebrow">Személyek</span>
|
||||
@@ -144,7 +156,7 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
label: "Elemzés",
|
||||
content: (
|
||||
<DetailedAnalysis
|
||||
chartId={chart.id}
|
||||
target={{ kind: "natal", chartId: chart.id }}
|
||||
initial={detailed}
|
||||
left={me.analyses_left.natal}
|
||||
isAdmin={me.user.roles.includes("admin")}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/** Deletes a comparison (and its analysis). */
|
||||
export function ComparisonActions({ id, name }: { id: string; name: string }) {
|
||||
const router = useRouter();
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/synastries/${id}`, { method: "DELETE" });
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="person-actions">
|
||||
{confirm ? (
|
||||
<>
|
||||
<span className="hint">Törlöd a(z) {name} összevetést és az elemzését?</span>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={remove} disabled={busy}>
|
||||
{busy ? "Törlés…" : "Igen, törlöm"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setConfirm(false)} disabled={busy}>
|
||||
Mégse
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setConfirm(true)}>
|
||||
Törlés
|
||||
</button>
|
||||
)}
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
|
||||
import { CompareButton } from "@/components/CompareButton";
|
||||
import { sideName } from "@/lib/synastry";
|
||||
import type { ChartListItem } from "@/lib/types";
|
||||
|
||||
/** Picks two of the user's charts to compare. */
|
||||
export function NewComparison({ charts }: { charts: ChartListItem[] }) {
|
||||
const own = charts.find((c) => c.is_primary);
|
||||
const [first, setFirst] = useState(own?.id ?? charts[0]?.id ?? "");
|
||||
const [second, setSecond] = useState(charts.find((c) => c.id !== (own?.id ?? charts[0]?.id))?.id ?? "");
|
||||
|
||||
if (charts.length < 2) {
|
||||
return (
|
||||
<section className="card compare-new" aria-labelledby="compare-title">
|
||||
<h2 id="compare-title">Új összevetés</h2>
|
||||
<p className="muted">
|
||||
Összevetéshez legalább két képlet kell. Vedd fel társad, családtagod vagy barátod születési adatait, és nézd meg,
|
||||
hogyan hatnak egymásra a képleteitek.
|
||||
</p>
|
||||
<div className="form-actions">
|
||||
<Link href="/szemelyek/uj" className="btn btn-primary">
|
||||
Új személy felvétele
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const option = (c: ChartListItem) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{sideName(c)}
|
||||
{c.birth.time ? "" : " (idő nélkül)"}
|
||||
</option>
|
||||
);
|
||||
const swap = () => {
|
||||
setFirst(second);
|
||||
setSecond(first);
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="card compare-new" aria-labelledby="compare-title">
|
||||
<h2 id="compare-title">Új összevetés</h2>
|
||||
<div className="compare-form">
|
||||
<div className="field">
|
||||
<label htmlFor="compare-first">Első fél</label>
|
||||
<select id="compare-first" className="inp" value={first} onChange={(e) => setFirst(e.target.value)}>
|
||||
{charts.map(option)}
|
||||
</select>
|
||||
</div>
|
||||
<button type="button" className="btn btn-ghost compare-swap" onClick={swap} aria-label="A két fél felcserélése">
|
||||
⇄
|
||||
</button>
|
||||
<div className="field">
|
||||
<label htmlFor="compare-second">Második fél</label>
|
||||
<select id="compare-second" className="inp" value={second} onChange={(e) => setSecond(e.target.value)}>
|
||||
{charts.map(option)}
|
||||
</select>
|
||||
</div>
|
||||
{first && second && first !== second ? (
|
||||
<CompareButton chart1={first} chart2={second} label="Összevetés" className="btn btn-primary" />
|
||||
) : (
|
||||
<button type="button" className="btn btn-primary" disabled>
|
||||
Összevetés
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="hint">
|
||||
{first === second
|
||||
? "Két különböző képletet válassz."
|
||||
: "A körön az első fél képlete és házai vannak belül, a második fél bolygói kívül."}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { SignTrio } from "@/components/ChartCard";
|
||||
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
|
||||
import { CompositeTables, CrossGrid, HouseOverlays, InterAspectList, NatureBar } from "@/components/SynastryTables";
|
||||
import { SynastryLegend, SynastryWheel } from "@/components/SynastryWheel";
|
||||
import { Tabs } from "@/components/Tabs";
|
||||
import { ASPECTS, formatBirthDate } from "@/lib/astro";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import { sideName, sideTimeKnown } from "@/lib/synastry";
|
||||
import type { Analysis, ChartListItem, PublicConfig, Synastry, SynastrySide } from "@/lib/types";
|
||||
|
||||
export const metadata: Metadata = { title: "Összevetés" };
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const GRID_LEGEND = ["conjunction", "sextile", "square", "trine", "opposition"];
|
||||
|
||||
function Person({ side, which }: { side: SynastrySide; which: "p1" | "p2" }) {
|
||||
const time = sideTimeKnown(side);
|
||||
const birth = side.birth_data;
|
||||
const name = sideName(side);
|
||||
const body = (
|
||||
<>
|
||||
<span className={`pair-dot legend-${which}`} aria-hidden="true" />
|
||||
<span className="pair-text">
|
||||
<strong>{name}</strong>
|
||||
{birth && (
|
||||
<span className="hint">
|
||||
{formatBirthDate(birth.date)}
|
||||
{time && birth.time ? `, ${birth.time.slice(0, 5)}` : ", ismeretlen időpont"}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{side.highlights && (
|
||||
<SignTrio chart={{ highlights: { ...side.highlights, time_known: time } } as ChartListItem} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
return side.owned ? (
|
||||
<Link href={`/kepletek/${side.id}`} className="pair-row">
|
||||
{body}
|
||||
</Link>
|
||||
) : (
|
||||
<div className="pair-row">{body}</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One comparison of two charts: the double wheel, the numbers, the analysis and the tables. */
|
||||
export default async function ComparisonPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const me = await requireMe(`/osszevetesek/${id}`);
|
||||
if (!UUID.test(id)) notFound();
|
||||
const [synastry, analyses, config] = await Promise.all([
|
||||
backendGet<Synastry>(`/v1/synastries/${id}`),
|
||||
backendGet<{ analyses: Analysis[] }>(`/v1/synastries/${id}/analyses`),
|
||||
backendGet<PublicConfig>("/v1/config"),
|
||||
]);
|
||||
if (!synastry) notFound();
|
||||
const list = analyses?.analyses ?? [];
|
||||
const detailed = list.find((a) => a.status !== "failed") ?? list[0] ?? null;
|
||||
|
||||
const { chart1, chart2 } = synastry;
|
||||
const name1 = sideName(chart1);
|
||||
const name2 = sideName(chart2);
|
||||
const time1 = sideTimeKnown(chart1);
|
||||
const time2 = sideTimeKnown(chart2);
|
||||
const result = synastry.synastry;
|
||||
const unknown = [!time1 && name1, !time2 && name2].filter(Boolean);
|
||||
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 1180 }}>
|
||||
<div className="page-head">
|
||||
<Link href="/osszevetesek" className="back-link">
|
||||
← Összevetések
|
||||
</Link>
|
||||
<h1>
|
||||
{name1} és {name2}
|
||||
</h1>
|
||||
<p className="muted">Összevetés · két képlet egymásra vetítve</p>
|
||||
</div>
|
||||
|
||||
<section className="chart-layout" aria-label="Kettős képletrajz">
|
||||
<div className="card chart-wheel-card">
|
||||
<SynastryWheel
|
||||
chart1={chart1.chart}
|
||||
chart2={chart2.chart}
|
||||
time1={time1}
|
||||
time2={time2}
|
||||
aspects={result.aspects}
|
||||
name1={name1}
|
||||
name2={name2}
|
||||
/>
|
||||
<SynastryLegend name1={name1} name2={name2} time1={time1} />
|
||||
</div>
|
||||
<div className="field chart-side">
|
||||
<div className="card pair-card">
|
||||
<span className="eyebrow">A két fél</span>
|
||||
<Person side={chart1} which="p1" />
|
||||
<Person side={chart2} which="p2" />
|
||||
</div>
|
||||
<div className="card summary-card">
|
||||
<span className="eyebrow">Számokban</span>
|
||||
<h2 className="summary-title">{result.summary.aspect_count} fényszög köztetek</h2>
|
||||
<NatureBar summary={result.summary} />
|
||||
{unknown.length > 0 && (
|
||||
<p className="hint">
|
||||
{unknown.join(" és ")} születési ideje ismeretlen: az ő tengelyei és házai kimaradnak, a Hold helyzete
|
||||
közelítő.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card chart-tabs" aria-label="Elemzés és táblázatok">
|
||||
<Tabs
|
||||
label="Összevetés részletei"
|
||||
tabs={[
|
||||
{
|
||||
id: "elemzes",
|
||||
label: "Elemzés",
|
||||
content: (
|
||||
<DetailedAnalysis
|
||||
target={{ kind: "synastry", synastryId: synastry.id }}
|
||||
initial={detailed}
|
||||
left={me.analyses_left.synastry}
|
||||
isAdmin={me.user.roles.includes("admin")}
|
||||
canPay={config?.mock_payments ?? false}
|
||||
note={`Az elemzésben az első fél: ${name1}, a második fél: ${name2}.`}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "fenyszogek",
|
||||
label: "Fényszögek",
|
||||
content: (
|
||||
<div className="field" style={{ gap: 16 }}>
|
||||
<CrossGrid synastry={synastry} name1={name1} name2={name2} />
|
||||
<ul className="grid-legend" aria-label="Jelmagyarázat">
|
||||
{GRID_LEGEND.map((k) => (
|
||||
<li key={k}>
|
||||
<span className={`sym asp asp-${k}`} aria-hidden="true">
|
||||
{ASPECTS[k]?.glyph}
|
||||
</span>{" "}
|
||||
{ASPECTS[k]?.hu}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ id: "hazak", label: "Házak", content: <HouseOverlays synastry={synastry} name1={name1} name2={name2} /> },
|
||||
{ id: "kompozit", label: "Kompozit", content: <CompositeTables synastry={synastry} /> },
|
||||
{
|
||||
id: "reszletek",
|
||||
label: "Részletek",
|
||||
content: <InterAspectList synastry={synastry} name1={name1} name2={name2} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { formatDate } from "@/lib/astro";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import { listName } from "@/lib/synastry";
|
||||
import type { ChartListItem, SynastryListItem } from "@/lib/types";
|
||||
|
||||
import { ComparisonActions } from "./ComparisonActions";
|
||||
import { NewComparison } from "./NewComparison";
|
||||
|
||||
export const metadata: Metadata = { title: "Összevetések" };
|
||||
|
||||
/** The user's comparisons, and a form for a new one. */
|
||||
export default async function ComparisonsPage() {
|
||||
await requireMe("/osszevetesek");
|
||||
const [chartList, synastryList] = await Promise.all([
|
||||
backendGet<{ charts: ChartListItem[] }>("/v1/charts"),
|
||||
backendGet<{ synastries: SynastryListItem[] }>("/v1/synastries"),
|
||||
]);
|
||||
const charts = chartList?.charts ?? [];
|
||||
const synastries = synastryList?.synastries ?? [];
|
||||
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 1080 }}>
|
||||
<div className="page-head">
|
||||
<h1>Összevetések</h1>
|
||||
<p className="muted">
|
||||
Két képlet egymásra vetítve: mi vonz, hol súrlódtok, és mit ad a kapcsolat. A saját és a felvett személyek
|
||||
képletei közül bármelyik kettőt összevetheted.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<NewComparison charts={charts} />
|
||||
|
||||
{synastries.length > 0 && (
|
||||
<section className="field" aria-labelledby="list-title" style={{ gap: 12 }}>
|
||||
<h2 id="list-title">Korábbi összevetések</h2>
|
||||
<div className="chart-cards">
|
||||
{synastries.map((s) => {
|
||||
const name = `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
|
||||
const n = s.summary?.by_nature;
|
||||
const total = s.summary?.aspect_count || 1;
|
||||
return (
|
||||
<div key={s.id} className="chart-card">
|
||||
<Link href={`/osszevetesek/${s.id}`} className="chart-card-link">
|
||||
<strong className="chart-card-name">{name}</strong>
|
||||
<span className="muted">{formatDate(s.created_at)}</span>
|
||||
{n && (
|
||||
<>
|
||||
<span className="nature-bar nature-bar-sm" aria-hidden="true">
|
||||
<span className="nature-seg nature-harmonious" style={{ flexGrow: n.harmonious / total }} />
|
||||
<span className="nature-seg nature-challenging" style={{ flexGrow: n.challenging / total }} />
|
||||
<span className="nature-seg nature-neutral" style={{ flexGrow: n.neutral / total }} />
|
||||
</span>
|
||||
<span className="hint">
|
||||
{n.harmonious} harmonikus · {n.challenging} feszültebb · {n.neutral} együttállás
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Link>
|
||||
{s.owned && <ComparisonActions id={s.id} name={name} />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ export default async function PersonsPage() {
|
||||
]);
|
||||
const charts = list?.charts ?? [];
|
||||
const persons = charts.filter((c) => c.kind === "person");
|
||||
const ownId = charts.find((c) => c.is_primary)?.id ?? null;
|
||||
const isAdmin = me.user.roles.includes("admin");
|
||||
const slots = me.persons;
|
||||
const full = slots.left === 0;
|
||||
@@ -28,8 +29,8 @@ export default async function PersonsPage() {
|
||||
<div className="page-head">
|
||||
<h1>Személyek</h1>
|
||||
<p className="muted">
|
||||
Társad, családtagjaid, barátaid képlete. Mindegyikhez kérhetsz részletes elemzést, és a képletoldal címére
|
||||
kattintva válthatsz köztük.
|
||||
Társad, családtagjaid, barátaid képlete. Mindegyikhez kérhetsz részletes elemzést, összevetheted a sajátoddal,
|
||||
és a képletoldal címére kattintva válthatsz köztük.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -39,6 +40,7 @@ export default async function PersonsPage() {
|
||||
<PersonActions
|
||||
id={p.id}
|
||||
name={p.label}
|
||||
ownId={ownId}
|
||||
editable={isAdmin || (p.editable_until !== null && Date.parse(p.editable_until) > now)}
|
||||
/>
|
||||
</ChartCard>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ANGLES, ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
|
||||
import type { Aspect, Chart, Position } from "@/lib/types";
|
||||
|
||||
function Pos({ p }: { p: Position }) {
|
||||
export function Pos({ p }: { p: Position }) {
|
||||
return (
|
||||
<>
|
||||
{dms(p.degree_in_sign_dms)} <span className="sym">{SIGNS[p.sign]?.glyph}</span> {signName(p.sign)}
|
||||
@@ -47,7 +47,7 @@ export function BigThree({ chart }: { chart: Chart }) {
|
||||
}
|
||||
|
||||
// Rows and columns of the aspect grid: the points drawn on the wheel, then the angles.
|
||||
const GRID_POINTS = [
|
||||
export const GRID_POINTS = [
|
||||
"sun",
|
||||
"moon",
|
||||
"mercury",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib
|
||||
import type { ChartResult, Position } from "@/lib/types";
|
||||
|
||||
// Radii of the rings (viewBox is SIZE × SIZE, centre C).
|
||||
const SIZE = 680;
|
||||
export const SIZE = 680;
|
||||
const C = SIZE / 2;
|
||||
const R_LABEL = 322; // ASC / MC labels
|
||||
const R_OUT = 300; // outer edge of the zodiac ring
|
||||
@@ -13,7 +13,7 @@ const R_HOUSE = 172; // outer edge of the house-number ring
|
||||
const R_INNER = 146; // aspect circle
|
||||
|
||||
// Points drawn on the wheel; the asteroids and the south node are only in the tables.
|
||||
const WHEEL_POINTS = [
|
||||
export const WHEEL_POINTS = [
|
||||
"sun",
|
||||
"moon",
|
||||
"mercury",
|
||||
@@ -30,10 +30,10 @@ const WHEEL_POINTS = [
|
||||
];
|
||||
// Aspects drawn on the wheel, between these points; the rest (minor aspects,
|
||||
// nodes, Lilith, Chiron) are only in the aspect table.
|
||||
const WHEEL_ASPECTS = ["opposition", "square", "trine", "sextile"];
|
||||
const ASPECT_POINTS = ["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
|
||||
const SIGN_ORDER = Object.keys(SIGNS);
|
||||
const SIGN_ELEMENT = ["fire", "earth", "air", "water"];
|
||||
export const WHEEL_ASPECTS = ["opposition", "square", "trine", "sextile"];
|
||||
export const ASPECT_POINTS = ["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
|
||||
export const SIGN_ORDER = Object.keys(SIGNS);
|
||||
export const SIGN_ELEMENT = ["fire", "earth", "air", "water"];
|
||||
const ANGLE_LABELS: [string, string][] = [
|
||||
["ascendant", "ASC"],
|
||||
["midheaven", "MC"],
|
||||
@@ -42,15 +42,15 @@ const ANGLE_LABELS: [string, string][] = [
|
||||
];
|
||||
|
||||
/** Screen point of an ecliptic longitude: the ascendant (or 0° Aries) is on the left. */
|
||||
function xy(lon: number, r: number, start: number): [number, number] {
|
||||
export function xy(lon: number, r: number, start: number): [number, number] {
|
||||
const a = ((180 + lon - start) * Math.PI) / 180;
|
||||
return [C + r * Math.cos(a), C - r * Math.sin(a)];
|
||||
}
|
||||
|
||||
const f = (n: number) => n.toFixed(2);
|
||||
export const f = (n: number) => n.toFixed(2);
|
||||
|
||||
/** Pushes glyphs apart so that neighbours are at least `min` degrees from each other. */
|
||||
function spread(lons: number[], min: number): number[] {
|
||||
export function spread(lons: number[], min: number): number[] {
|
||||
const n = lons.length;
|
||||
const order = lons.map((_, i) => i).sort((a, b) => lons[a] - lons[b]);
|
||||
const pos = order.map((i) => lons[i]);
|
||||
@@ -73,7 +73,7 @@ function spread(lons: number[], min: number): number[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
function arcPath(r1: number, r2: number, from: number, to: number, start: number): string {
|
||||
export function arcPath(r1: number, r2: number, from: number, to: number, start: number): string {
|
||||
const [x1, y1] = xy(from, r2, start);
|
||||
const [x2, y2] = xy(to, r2, start);
|
||||
const [x3, y3] = xy(to, r1, start);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/** Compares two charts (or opens their existing comparison). */
|
||||
export function CompareButton({
|
||||
chart1,
|
||||
chart2,
|
||||
label = "Összevetés velem",
|
||||
className = "btn btn-sm btn-ghost",
|
||||
}: {
|
||||
chart1: string;
|
||||
chart2: string;
|
||||
label?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function compare() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const s = await api<{ id: string }>("/synastries", { body: { chart1_id: chart1, chart2_id: chart2 } });
|
||||
router.push(`/osszevetesek/${s.id}`);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button type="button" className={className} onClick={compare} disabled={busy}>
|
||||
{busy ? "Számolás…" : label}
|
||||
</button>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -14,30 +14,65 @@ const MAX_POLLS = 120; // 10 minutes
|
||||
|
||||
type Step = "offer" | "confirm" | "pay";
|
||||
|
||||
/** What is analysed: a natal chart, or a comparison of two charts. */
|
||||
export type AnalysisTarget = { kind: "natal"; chartId: string } | { kind: "synastry"; synastryId: string };
|
||||
|
||||
const TEXTS = {
|
||||
natal: {
|
||||
eyebrow: "Részletes elemzés",
|
||||
title: "Az egész képleted, fejezetekre bontva",
|
||||
about:
|
||||
"Kb. 1500 szó hat fejezetben: személyiség, érzelmek, gondolkodás, szerelem és kapcsolatok, hivatás, fejlődési út. " +
|
||||
"A végén erősségek, kihívások és útravaló. Csak a képleted pozíciói alapján készül.",
|
||||
loadingTitle: "Készül az elemzésed",
|
||||
loading:
|
||||
"Most íródik a hat fejezet a képleted alapján. Ez általában 1–3 perc; nyugodtan elhagyhatod az oldalt, az elemzés elkészül és itt vár.",
|
||||
item: "Részletes képletelemzés",
|
||||
unitName: "képletelemzés",
|
||||
},
|
||||
synastry: {
|
||||
eyebrow: "Kapcsolati elemzés",
|
||||
title: "Kettőtök képlete, fejezetekre bontva",
|
||||
about:
|
||||
"Kb. 1300 szó öt fejezetben: mi vonz egymáshoz, kommunikáció, érzelmi kötődés, súrlódások, hosszú távú lehetőségek " +
|
||||
"(a kompozit képlettel). A végén erősségek, kihívások és útravaló. Csak a két képlet pozíciói alapján készül.",
|
||||
loadingTitle: "Készül a kapcsolati elemzés",
|
||||
loading:
|
||||
"Most íródik az öt fejezet a két képlet alapján. Ez általában 1–3 perc; nyugodtan elhagyhatod az oldalt, az elemzés elkészül és itt vár.",
|
||||
item: "Részletes kapcsolati elemzés",
|
||||
unitName: "kapcsolati elemzés",
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The detailed analysis of a chart. A saved one is shown at once; otherwise
|
||||
* The detailed analysis of a chart or a comparison. A saved one is shown at once; otherwise
|
||||
* the offer: admins start it free, users with units confirm, others pay
|
||||
* (a stand-in payment for now). While the worker writes it, a loading wheel.
|
||||
*/
|
||||
export function DetailedAnalysis({
|
||||
chartId,
|
||||
target,
|
||||
initial,
|
||||
left,
|
||||
isAdmin,
|
||||
canPay,
|
||||
note,
|
||||
}: {
|
||||
chartId: string;
|
||||
target: AnalysisTarget;
|
||||
initial: Analysis | null;
|
||||
left: number;
|
||||
isAdmin: boolean;
|
||||
/** The stand-in payment is on (MOCK_PAYMENTS). */
|
||||
canPay: boolean;
|
||||
/** Shown above a finished analysis (e.g. who is the first and the second person). */
|
||||
note?: string;
|
||||
}) {
|
||||
const [analysis, setAnalysis] = useState<Analysis | null>(initial);
|
||||
const [step, setStep] = useState<Step>("offer");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const waiting = analysis?.status === "pending" || analysis?.status === "running";
|
||||
const t = TEXTS[target.kind];
|
||||
const path = target.kind === "natal" ? `/charts/${target.chartId}` : `/synastries/${target.synastryId}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (!waiting || !analysis) return;
|
||||
@@ -66,8 +101,8 @@ export function DetailedAnalysis({
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (pay) await api("/payments/mock", { body: { unit: "natal" } });
|
||||
setAnalysis(await api<Analysis>(`/charts/${chartId}/analyses`, { method: "POST" }));
|
||||
if (pay) await api("/payments/mock", { body: { unit: target.kind } });
|
||||
setAnalysis(await api<Analysis>(`${path}/analyses`, { method: "POST" }));
|
||||
setStep("offer");
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
@@ -78,21 +113,19 @@ export function DetailedAnalysis({
|
||||
|
||||
if (analysis?.status === "done" && analysis.content) {
|
||||
return (
|
||||
<section className="analysis-card" aria-label="Részletes elemzés">
|
||||
<span className="eyebrow">Részletes elemzés</span>
|
||||
<AnalysisView content={analysis.content} />
|
||||
<section className="analysis-card" aria-label={t.eyebrow}>
|
||||
<span className="eyebrow">{t.eyebrow}</span>
|
||||
{note && <p className="hint">{note}</p>}
|
||||
<AnalysisView content={analysis.content} kind={target.kind} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
if (waiting) {
|
||||
return (
|
||||
<section className="analysis-card" aria-label="Részletes elemzés" aria-busy="true">
|
||||
<span className="eyebrow">Részletes elemzés</span>
|
||||
<AnalysisLoading
|
||||
title="Készül az elemzésed"
|
||||
text="Most íródik a hat fejezet a képleted alapján. Ez általában 1–3 perc; nyugodtan elhagyhatod az oldalt, az elemzés elkészül és itt vár."
|
||||
/>
|
||||
<section className="analysis-card" aria-label={t.eyebrow} aria-busy="true">
|
||||
<span className="eyebrow">{t.eyebrow}</span>
|
||||
<AnalysisLoading title={t.loadingTitle} text={t.loading} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -100,13 +133,10 @@ export function DetailedAnalysis({
|
||||
return (
|
||||
<section className="analysis-card analysis-offer" aria-labelledby="detailed-title">
|
||||
<div className="offer-head">
|
||||
<span className="eyebrow">Részletes elemzés</span>
|
||||
<h2 id="detailed-title">Az egész képleted, fejezetekre bontva</h2>
|
||||
<span className="eyebrow">{t.eyebrow}</span>
|
||||
<h2 id="detailed-title">{t.title}</h2>
|
||||
</div>
|
||||
<p className="muted">
|
||||
Kb. 1500 szó hat fejezetben: személyiség, érzelmek, gondolkodás, szerelem és kapcsolatok, hivatás, fejlődési út.
|
||||
A végén erősségek, kihívások és útravaló. Csak a képleted pozíciói alapján készül.
|
||||
</p>
|
||||
<p className="muted">{t.about}</p>
|
||||
{analysis?.status === "failed" && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
Az előző kérés nem sikerült{isAdmin ? "" : ", az elemzést visszaadtuk a keretedbe"}. Próbáld újra.
|
||||
@@ -121,7 +151,7 @@ export function DetailedAnalysis({
|
||||
{isAdmin ? (
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={() => start(false)} disabled={busy}>
|
||||
{busy ? "Indítás…" : "Részletes elemzés készítése"}
|
||||
{busy ? "Indítás…" : `${t.item} készítése`}
|
||||
</button>
|
||||
<span className="hint">Adminként ingyenes.</span>
|
||||
</div>
|
||||
@@ -134,21 +164,25 @@ export function DetailedAnalysis({
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setStep("offer")} disabled={busy}>
|
||||
Mégse
|
||||
</button>
|
||||
<span className="hint">Ez felhasznál 1-et a {left} képletelemzésedből.</span>
|
||||
<span className="hint">
|
||||
Ez felhasznál 1-et a {left} {t.unitName}edből.
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={() => setStep("confirm")}>
|
||||
Részletes elemzés kérése
|
||||
</button>
|
||||
<span className="hint">Még {left} képletelemzésed van.</span>
|
||||
<span className="hint">
|
||||
Még {left} {t.unitName}ed van.
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
) : canPay ? (
|
||||
step === "pay" ? (
|
||||
<div className="pay-box">
|
||||
<div className="pay-line">
|
||||
<span>Részletes képletelemzés</span>
|
||||
<span>{t.item}</span>
|
||||
<strong>1 db</strong>
|
||||
</div>
|
||||
<div className="form-actions">
|
||||
@@ -166,16 +200,20 @@ export function DetailedAnalysis({
|
||||
<button type="button" className="btn btn-primary" onClick={() => setStep("pay")}>
|
||||
Részletes elemzés kérése
|
||||
</button>
|
||||
<Link href="/pelda" className="btn btn-ghost">
|
||||
Példa megtekintése
|
||||
</Link>
|
||||
{target.kind === "natal" && (
|
||||
<Link href="/pelda" className="btn btn-ghost">
|
||||
Példa megtekintése
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<div className="form-actions">
|
||||
<Link href="/pelda" className="btn">
|
||||
Példa megtekintése
|
||||
</Link>
|
||||
{target.kind === "natal" && (
|
||||
<Link href="/pelda" className="btn">
|
||||
Példa megtekintése
|
||||
</Link>
|
||||
)}
|
||||
<span className="hint">A részletes elemzés fizetős; a csomagok hamarosan elérhetők.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -6,8 +6,21 @@ import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/** Correct (while allowed) or delete a person. */
|
||||
export function PersonActions({ id, name, editable }: { id: string; name: string; editable: boolean }) {
|
||||
import { CompareButton } from "./CompareButton";
|
||||
|
||||
/** Compare with the own chart, correct (while allowed) or delete a person. */
|
||||
export function PersonActions({
|
||||
id,
|
||||
name,
|
||||
editable,
|
||||
ownId,
|
||||
}: {
|
||||
id: string;
|
||||
name: string;
|
||||
editable: boolean;
|
||||
/** The user's own chart, for "compare with me". */
|
||||
ownId?: string | null;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -39,6 +52,7 @@ export function PersonActions({ id, name, editable }: { id: string; name: string
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{ownId && <CompareButton chart1={ownId} chart2={id} />}
|
||||
{editable && (
|
||||
<Link href={`/kepletek/${id}/javitas`} className="btn btn-sm btn-ghost">
|
||||
Adatok javítása
|
||||
|
||||
@@ -17,6 +17,7 @@ export function SiteHeader({ me }: { me: Me }) {
|
||||
const links = [
|
||||
{ href: "/keplet", label: "Képletem" },
|
||||
{ href: "/szemelyek", label: "Személyek" },
|
||||
{ href: "/osszevetesek", label: "Összevetések" },
|
||||
{ href: "/profil", label: "Profil" },
|
||||
];
|
||||
if (me.user.roles.includes("admin")) links.push({ href: "/admin", label: "Admin" });
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
import { ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
|
||||
import type { HouseOverlay, InterAspect, Synastry, SynastryResult } from "@/lib/types";
|
||||
|
||||
import { GRID_POINTS, Pos } from "./ChartTables";
|
||||
|
||||
const NATURES: { key: keyof SynastryResult["summary"]["by_nature"]; label: string; hint: string }[] = [
|
||||
{ key: "harmonious", label: "Harmonikus", hint: "trigon, szextil: ami könnyen megy köztetek" },
|
||||
{ key: "challenging", label: "Feszültebb", hint: "kvadrát, szembenállás: súrlódás, de mozgatóerő is" },
|
||||
{ key: "neutral", label: "Együttállás", hint: "összeolvadás: erős, a bolygóktól függő hatás" },
|
||||
];
|
||||
|
||||
/** The inter-chart aspects by character, as a bar and counts. */
|
||||
export function NatureBar({ summary }: { summary: SynastryResult["summary"] }) {
|
||||
const total = summary.aspect_count || 1;
|
||||
return (
|
||||
<div className="nature">
|
||||
<div className="nature-bar" aria-hidden="true">
|
||||
{NATURES.map((n) => (
|
||||
<span
|
||||
key={n.key}
|
||||
className={`nature-seg nature-${n.key}`}
|
||||
style={{ flexGrow: summary.by_nature[n.key] / total }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<dl className="nature-list">
|
||||
{NATURES.map((n) => (
|
||||
<div key={n.key}>
|
||||
<dt>
|
||||
<span className={`nature-dot nature-${n.key}`} aria-hidden="true" /> {n.label}
|
||||
</dt>
|
||||
<dd>
|
||||
<strong>{summary.by_nature[n.key]}</strong> <span className="hint">{n.hint}</span>
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const GRID_ANGLES: [string, string][] = [
|
||||
["ascendant", "AC"],
|
||||
["midheaven", "MC"],
|
||||
];
|
||||
|
||||
function gridPoints(s: Synastry["chart1"]): [string, string][] {
|
||||
const present = new Set(s.chart.points.map((p) => p.id));
|
||||
const rows: [string, string][] = GRID_POINTS.filter((id) => present.has(id)).map((id) => [id, POINTS[id]?.glyph ?? id]);
|
||||
if (s.highlights.time_known) {
|
||||
for (const [key, label] of GRID_ANGLES) if (s.chart.angles?.[key]) rows.push([key, label]);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** The aspects between the two charts: the first person in the rows, the second in the columns. */
|
||||
export function CrossGrid({ synastry, name1, name2 }: { synastry: Synastry; name1: string; name2: string }) {
|
||||
const rows = gridPoints(synastry.chart1);
|
||||
const cols = gridPoints(synastry.chart2);
|
||||
const byPair = new Map<string, InterAspect>();
|
||||
for (const a of synastry.synastry.aspects) byPair.set(`${a.person1}|${a.person2}`, a);
|
||||
const label = ([id, text]: [string, string], who: string) => (
|
||||
<span className={text.length > 2 ? "sym" : "grid-angle"} aria-label={`${who}: ${pointName(id)}`} role="img">
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="aspect-grid-wrap">
|
||||
<table className="aspect-grid cross-grid" aria-label={`Fényszögek: sorokban ${name1}, oszlopokban ${name2}`}>
|
||||
<thead>
|
||||
<tr>
|
||||
<td className="corner cross-corner">
|
||||
<span className="cross-col">{name2} →</span>
|
||||
<span className="cross-row">↓ {name1}</span>
|
||||
</td>
|
||||
{cols.map((c) => (
|
||||
<th key={c[0]} scope="col" title={`${name2}: ${pointName(c[0])}`} className="p2-head">
|
||||
{label(c, name2)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => {
|
||||
const [id] = row;
|
||||
return (
|
||||
<tr key={id}>
|
||||
<th scope="row" title={`${name1}: ${pointName(id)}`}>
|
||||
{label(row, name1)}
|
||||
</th>
|
||||
{cols.map(([other]) => {
|
||||
const a = byPair.get(`${id}|${other}`);
|
||||
const info = a ? ASPECTS[a.aspect] : undefined;
|
||||
const text = a
|
||||
? `${name1} ${pointName(id)} ${info?.hu ?? a.aspect} ${name2} ${pointName(other)}, orbis ${orbText(a.orb)}`
|
||||
: undefined;
|
||||
return (
|
||||
<td key={other} title={text}>
|
||||
{a && (
|
||||
<span className={`sym asp asp-${a.aspect}`} aria-label={text} role="img">
|
||||
{info?.glyph ?? "?"}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OverlayTable({ title, overlays, missing }: { title: string; overlays: HouseOverlay[] | null; missing: string }) {
|
||||
return (
|
||||
<div className="table-wrap">
|
||||
<h3 style={{ marginBottom: 8 }}>{title}</h3>
|
||||
{overlays ? (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Pont</th>
|
||||
<th scope="col">Jegy</th>
|
||||
<th scope="col">Ház</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{overlays.map((o) => (
|
||||
<tr key={o.point}>
|
||||
<td>
|
||||
<span className="sym" aria-hidden="true">
|
||||
{POINTS[o.point]?.glyph}
|
||||
</span>{" "}
|
||||
{pointName(o.point)}
|
||||
</td>
|
||||
<td>
|
||||
<span className="sym" aria-hidden="true">
|
||||
{SIGNS[o.sign]?.glyph}
|
||||
</span>{" "}
|
||||
{signName(o.sign)}
|
||||
</td>
|
||||
<td className="num">{o.house}.</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<p className="muted">{missing}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Each person's points in the other's houses (needs the other's birth time). */
|
||||
export function HouseOverlays({ synastry, name1, name2 }: { synastry: Synastry; name1: string; name2: string }) {
|
||||
const o = synastry.synastry.house_overlays;
|
||||
return (
|
||||
<div className="field" style={{ gap: 16 }}>
|
||||
<p className="hint">
|
||||
Melyik életterületét érinti a másik: az egyik fél bolygói a másik házaiban. Ehhez a ház „gazdájának” pontos
|
||||
születési ideje kell.
|
||||
</p>
|
||||
<div className="grid-2" style={{ alignItems: "start" }}>
|
||||
<OverlayTable
|
||||
title={`${name2} bolygói ${name1} házaiban`}
|
||||
overlays={o.person2_in_person1}
|
||||
missing={`${name1} születési ideje ismeretlen, ezért a házai nem számolhatók.`}
|
||||
/>
|
||||
<OverlayTable
|
||||
title={`${name1} bolygói ${name2} házaiban`}
|
||||
overlays={o.person1_in_person2}
|
||||
missing={`${name2} születési ideje ismeretlen, ezért a házai nem számolhatók.`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The composite chart (midpoints of the two charts). */
|
||||
export function CompositeTables({ synastry }: { synastry: Synastry }) {
|
||||
const c = synastry.synastry.composite;
|
||||
const hasHouses = Boolean(c.houses);
|
||||
const angles = (
|
||||
[
|
||||
["ascendant", "ASC"],
|
||||
["midheaven", "MC"],
|
||||
] as const
|
||||
).filter(([key]) => c.angles?.[key]);
|
||||
const aspects = [...c.aspects].filter((a) => a.orb <= 3).sort((a, b) => a.orb - b.orb);
|
||||
return (
|
||||
<div className="field" style={{ gap: 16 }}>
|
||||
<p className="hint">
|
||||
A kompozit képlet a két képlet felezőpontjaiból áll: a kapcsolatot mint önálló harmadik „személyt” írja le.
|
||||
{!c.angles && " Tengelyek és házak nélkül, mert legalább az egyik születési idő ismeretlen."}
|
||||
</p>
|
||||
<div className="grid-2" style={{ alignItems: "start" }}>
|
||||
<div className="table-wrap">
|
||||
<h3 style={{ marginBottom: 8 }}>Pontok</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Pont</th>
|
||||
<th scope="col">Pozíció</th>
|
||||
{hasHouses && <th scope="col">Ház</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{c.points.map((p) => (
|
||||
<tr key={p.id}>
|
||||
<td>
|
||||
<span className="sym" aria-hidden="true">
|
||||
{POINTS[p.id]?.glyph}
|
||||
</span>{" "}
|
||||
{pointName(p.id)}
|
||||
</td>
|
||||
<td className="num">
|
||||
<Pos p={p} />
|
||||
</td>
|
||||
{hasHouses && <td className="num">{p.house ? `${p.house}.` : "–"}</td>}
|
||||
</tr>
|
||||
))}
|
||||
{angles.map(([key, label]) => (
|
||||
<tr key={key}>
|
||||
<td>{label}</td>
|
||||
<td className="num">
|
||||
{dms(c.angles![key].degree_in_sign_dms)} <span className="sym">{SIGNS[c.angles![key].sign]?.glyph}</span>{" "}
|
||||
{signName(c.angles![key].sign)}
|
||||
</td>
|
||||
{hasHouses && <td />}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="table-wrap">
|
||||
<h3 style={{ marginBottom: 8 }}>Szoros fényszögek</h3>
|
||||
{aspects.length === 0 ? (
|
||||
<p className="muted">Nincs 3°-nál szorosabb fényszög.</p>
|
||||
) : (
|
||||
<table>
|
||||
<tbody>
|
||||
{aspects.map((a) => (
|
||||
<tr key={`${a.point1}-${a.point2}-${a.aspect}`}>
|
||||
<td>
|
||||
{pointName(a.point1)} <AspectTag aspect={a.aspect} /> {pointName(a.point2)}
|
||||
</td>
|
||||
<td className="num">{orbText(a.orb)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AspectTag({ aspect }: { aspect: string }) {
|
||||
const info = ASPECTS[aspect];
|
||||
return (
|
||||
<span className={`aspect-tag aspect-${info?.kind ?? "neutral"}`}>
|
||||
<span className="sym" aria-hidden="true">
|
||||
{info?.glyph}
|
||||
</span>{" "}
|
||||
{info?.hu ?? aspect}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Every aspect between the two charts, closest first. */
|
||||
export function InterAspectList({ synastry, name1, name2 }: { synastry: Synastry; name1: string; name2: string }) {
|
||||
const aspects = [...synastry.synastry.aspects].sort((a, b) => a.orb - b.orb);
|
||||
if (aspects.length === 0) return <p className="muted">Nincs fényszög a két képlet között.</p>;
|
||||
return (
|
||||
<div className="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{name1}</th>
|
||||
<th scope="col">Fényszög</th>
|
||||
<th scope="col">{name2}</th>
|
||||
<th scope="col">Orbisz</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{aspects.map((a) => (
|
||||
<tr key={`${a.person1}-${a.person2}-${a.aspect}`}>
|
||||
<td>
|
||||
<span className="sym" aria-hidden="true">
|
||||
{POINTS[a.person1]?.glyph}
|
||||
</span>{" "}
|
||||
{pointName(a.person1)}
|
||||
</td>
|
||||
<td>
|
||||
<AspectTag aspect={a.aspect} />
|
||||
</td>
|
||||
<td>
|
||||
<span className="sym p2-text" aria-hidden="true">
|
||||
{POINTS[a.person2]?.glyph}
|
||||
</span>{" "}
|
||||
{pointName(a.person2)}
|
||||
</td>
|
||||
<td className="num">{orbText(a.orb)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
import { ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
|
||||
import type { ChartPoint, ChartResult, InterAspect, Position } from "@/lib/types";
|
||||
|
||||
import {
|
||||
ASPECT_POINTS,
|
||||
SIGN_ELEMENT,
|
||||
SIGN_ORDER,
|
||||
SIZE,
|
||||
WHEEL_ASPECTS,
|
||||
WHEEL_POINTS,
|
||||
arcPath,
|
||||
f,
|
||||
spread,
|
||||
xy,
|
||||
} from "./ChartWheel";
|
||||
|
||||
const C = SIZE / 2;
|
||||
const R_LABEL = 322; // ASC / MC labels of the first person
|
||||
const R_OUT = 300; // outer edge of the zodiac ring
|
||||
const R_ZOD = 262; // inner edge of the zodiac ring
|
||||
const R2_GLYPH = 238; // second person: glyphs
|
||||
const R2_DEG = 214;
|
||||
const R_MID = 198; // border of the two rings
|
||||
const R1_GLYPH = 176; // first person: glyphs
|
||||
const R1_DEG = 154;
|
||||
const R_HOUSE = 138; // house-number ring of the first person
|
||||
const R_INNER = 114; // aspect circle
|
||||
|
||||
const ANGLE_LABELS: [string, string][] = [
|
||||
["ascendant", "ASC"],
|
||||
["midheaven", "MC"],
|
||||
["descendant", "DSC"],
|
||||
["imum_coeli", "IC"],
|
||||
];
|
||||
|
||||
function angleOf(chart: ChartResult, key: string): Position | null {
|
||||
const a = chart.angles?.[key];
|
||||
return typeof a === "object" && a !== null ? a : null;
|
||||
}
|
||||
|
||||
/** One person's planets on a ring: tick on the outer edge, glyph, degree. */
|
||||
function Ring({
|
||||
points,
|
||||
placed,
|
||||
edge,
|
||||
glyphR,
|
||||
degR,
|
||||
start,
|
||||
who,
|
||||
timeKnown,
|
||||
className,
|
||||
}: {
|
||||
points: ChartPoint[];
|
||||
placed: number[];
|
||||
edge: number;
|
||||
glyphR: number;
|
||||
degR: number;
|
||||
start: number;
|
||||
who: string;
|
||||
timeKnown: boolean;
|
||||
className: string;
|
||||
}) {
|
||||
return (
|
||||
<g className={className}>
|
||||
{points.map((p, i) => {
|
||||
const [t1x, t1y] = xy(p.longitude, edge, start);
|
||||
const [t2x, t2y] = xy(p.longitude, edge - 8, start);
|
||||
const [lx, ly] = xy(placed[i], glyphR + 13, start);
|
||||
const [gx, gy] = xy(placed[i], glyphR, start);
|
||||
const [dx, dy] = xy(placed[i], degR, start);
|
||||
const deg = Number.parseInt(p.degree_in_sign_dms, 10);
|
||||
return (
|
||||
<g key={p.id} className="w-point">
|
||||
<title>
|
||||
{who}: {pointName(p.id)} {dms(p.degree_in_sign_dms)} {signName(p.sign)}
|
||||
{p.retrograde ? ", retrográd" : ""}
|
||||
{timeKnown && p.house ? `, ${p.house}. ház` : ""}
|
||||
</title>
|
||||
<line x1={f(t1x)} y1={f(t1y)} x2={f(t2x)} y2={f(t2y)} className="w-point-tick" />
|
||||
<line x1={f(t2x)} y1={f(t2y)} x2={f(lx)} y2={f(ly)} className="w-leader" />
|
||||
<text x={f(gx)} y={f(gy)} className="w-point-glyph" dominantBaseline="central" textAnchor="middle">
|
||||
{POINTS[p.id]?.glyph ?? p.id}
|
||||
</text>
|
||||
<text x={f(dx)} y={f(dy)} className="w-point-deg" dominantBaseline="central" textAnchor="middle">
|
||||
{deg}°{p.retrograde ? "℞" : ""}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Two charts on one wheel: the first person's planets and houses inside, the
|
||||
* second person's planets in the outer ring, the aspects between them in the middle.
|
||||
*/
|
||||
export function SynastryWheel({
|
||||
chart1,
|
||||
chart2,
|
||||
time1,
|
||||
time2,
|
||||
aspects,
|
||||
name1,
|
||||
name2,
|
||||
}: {
|
||||
chart1: ChartResult;
|
||||
chart2: ChartResult;
|
||||
time1: boolean;
|
||||
time2: boolean;
|
||||
aspects: InterAspect[];
|
||||
name1: string;
|
||||
name2: string;
|
||||
}) {
|
||||
const asc = time1 ? angleOf(chart1, "ascendant") : null;
|
||||
const start = asc?.longitude ?? 0;
|
||||
const cusps = time1 ? (chart1.houses?.cusps ?? []) : [];
|
||||
|
||||
const pick = (chart: ChartResult) =>
|
||||
WHEEL_POINTS.map((id) => chart.points.find((p) => p.id === id)).filter((p) => p !== undefined);
|
||||
const points1 = pick(chart1);
|
||||
const points2 = pick(chart2);
|
||||
// The inner ring is shorter, so its glyphs need a wider angle.
|
||||
const placed1 = spread(
|
||||
points1.map((p) => p.longitude),
|
||||
12,
|
||||
);
|
||||
const placed2 = spread(
|
||||
points2.map((p) => p.longitude),
|
||||
8,
|
||||
);
|
||||
|
||||
const endsOf = (points: ChartPoint[], placed: number[], chart: ChartResult, timeKnown: boolean) => {
|
||||
const ends = new Map<string, number>();
|
||||
points.forEach((p, i) => {
|
||||
if (ASPECT_POINTS.includes(p.id)) ends.set(p.id, placed[i]);
|
||||
});
|
||||
if (timeKnown) {
|
||||
for (const key of ["ascendant", "midheaven"]) {
|
||||
const a = angleOf(chart, key);
|
||||
if (a) ends.set(key, a.longitude);
|
||||
}
|
||||
}
|
||||
return ends;
|
||||
};
|
||||
const ends1 = endsOf(points1, placed1, chart1, time1);
|
||||
const ends2 = endsOf(points2, placed2, chart2, time2);
|
||||
const lines = aspects
|
||||
.filter((a) => WHEEL_ASPECTS.includes(a.aspect) && ends1.has(a.person1) && ends2.has(a.person2))
|
||||
.map((a) => ({ ...a, strength: a.max_orb > 0 ? 1 - Math.min(a.orb / a.max_orb, 1) : 0.5 }))
|
||||
.sort((x, y) => x.strength - y.strength);
|
||||
|
||||
return (
|
||||
<svg className="chart-wheel" viewBox={`0 0 ${SIZE} ${SIZE}`} role="img" aria-labelledby="biwheel-title biwheel-desc">
|
||||
<title id="biwheel-title">
|
||||
{name1} és {name2} képlete egy körön
|
||||
</title>
|
||||
<desc id="biwheel-desc">
|
||||
Belül {name1} bolygói{time1 ? " és házai" : ""}, kívül {name2} bolygói; középen a kettejük közti főfényszögek.
|
||||
</desc>
|
||||
|
||||
{/* Zodiac ring */}
|
||||
<circle cx={C} cy={C} r={R_OUT} className="w-ring" />
|
||||
{SIGN_ORDER.map((sign, i) => {
|
||||
const [gx, gy] = xy(i * 30 + 15, (R_OUT + R_ZOD) / 2, start);
|
||||
return (
|
||||
<g key={sign}>
|
||||
<path d={arcPath(R_ZOD, R_OUT, i * 30, i * 30 + 30, start)} className={`w-sign w-${SIGN_ELEMENT[i % 4]}`} />
|
||||
<text x={f(gx)} y={f(gy)} className="w-sign-glyph" dominantBaseline="central" textAnchor="middle">
|
||||
<title>{SIGNS[sign].hu}</title>
|
||||
{SIGNS[sign].glyph}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{Array.from({ length: 72 }, (_, k) => {
|
||||
const d = k * 5;
|
||||
const [x1, y1] = xy(d, R_ZOD, start);
|
||||
const [x2, y2] = xy(d, R_ZOD + (d % 10 === 0 ? 8 : 5), start);
|
||||
return <line key={d} x1={f(x1)} y1={f(y1)} x2={f(x2)} y2={f(y2)} className="w-tick" />;
|
||||
})}
|
||||
<circle cx={C} cy={C} r={R_ZOD} className="w-ring" />
|
||||
<circle cx={C} cy={C} r={R_MID} className="w-ring w-faint w-p2-band" />
|
||||
|
||||
{/* The first person's houses */}
|
||||
{cusps.length === 12 && (
|
||||
<g>
|
||||
<circle cx={C} cy={C} r={R_HOUSE} className="w-ring w-faint" />
|
||||
{cusps.map((c, i) => {
|
||||
const isAngle = i % 3 === 0;
|
||||
const [x1, y1] = xy(c.longitude, R_INNER, start);
|
||||
const [x2, y2] = xy(c.longitude, isAngle ? R_OUT : R_MID, start);
|
||||
const next = cusps[(i + 1) % 12].longitude;
|
||||
const mid = c.longitude + ((next - c.longitude + 360) % 360) / 2;
|
||||
const [nx, ny] = xy(mid, (R_HOUSE + R_INNER) / 2, start);
|
||||
return (
|
||||
<g key={c.house}>
|
||||
<line x1={f(x1)} y1={f(y1)} x2={f(x2)} y2={f(y2)} className={isAngle ? "w-axis" : "w-cusp"} />
|
||||
<text x={f(nx)} y={f(ny)} className="w-house-num" dominantBaseline="central" textAnchor="middle">
|
||||
{c.house}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{ANGLE_LABELS.map(([key, label]) => {
|
||||
const a = angleOf(chart1, key);
|
||||
if (!a) return null;
|
||||
const [x, y] = xy(a.longitude, R_LABEL, start);
|
||||
return (
|
||||
<text key={key} x={f(x)} y={f(y)} className="w-axis-label" dominantBaseline="central" textAnchor="middle">
|
||||
<title>
|
||||
{name1}: {pointName(key)} {dms(a.degree_in_sign_dms)} {signName(a.sign)}
|
||||
</title>
|
||||
{label}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
)}
|
||||
|
||||
{/* Aspects between the two */}
|
||||
<circle cx={C} cy={C} r={R_INNER} className="w-ring w-inner" />
|
||||
{lines.map((a) => {
|
||||
const [x1, y1] = xy(ends1.get(a.person1)!, R_INNER, start);
|
||||
const [x2, y2] = xy(ends2.get(a.person2)!, R_INNER, start);
|
||||
const s = a.strength;
|
||||
return (
|
||||
<line
|
||||
key={`${a.person1}-${a.person2}-${a.aspect}`}
|
||||
x1={f(x1)}
|
||||
y1={f(y1)}
|
||||
x2={f(x2)}
|
||||
y2={f(y2)}
|
||||
className={`w-aspect w-asp-${a.aspect}`}
|
||||
strokeOpacity={(0.2 + 0.8 * s * s).toFixed(2)}
|
||||
strokeWidth={(0.6 + 1.9 * s).toFixed(2)}
|
||||
>
|
||||
<title>
|
||||
{name1} {pointName(a.person1)} {ASPECTS[a.aspect]?.hu ?? a.aspect} {name2} {pointName(a.person2)} (orbis{" "}
|
||||
{orbText(a.orb)})
|
||||
</title>
|
||||
</line>
|
||||
);
|
||||
})}
|
||||
{[...ends1].map(([id, lon]) => {
|
||||
const [x, y] = xy(lon, R_INNER, start);
|
||||
return <circle key={`e1-${id}`} cx={f(x)} cy={f(y)} r={2.2} className="w-end" />;
|
||||
})}
|
||||
{[...ends2].map(([id, lon]) => {
|
||||
const [x, y] = xy(lon, R_INNER, start);
|
||||
return <circle key={`e2-${id}`} cx={f(x)} cy={f(y)} r={2.2} className="w-end w-end-p2" />;
|
||||
})}
|
||||
|
||||
<Ring
|
||||
points={points1}
|
||||
placed={placed1}
|
||||
edge={R_MID}
|
||||
glyphR={R1_GLYPH}
|
||||
degR={R1_DEG}
|
||||
start={start}
|
||||
who={name1}
|
||||
timeKnown={time1}
|
||||
className="w-p1"
|
||||
/>
|
||||
<Ring
|
||||
points={points2}
|
||||
placed={placed2}
|
||||
edge={R_ZOD}
|
||||
glyphR={R2_GLYPH}
|
||||
degR={R2_DEG}
|
||||
start={start}
|
||||
who={name2}
|
||||
timeKnown={false}
|
||||
className="w-p2"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Key to the two rings and the aspect lines. */
|
||||
export function SynastryLegend({ name1, name2, time1 }: { name1: string; name2: string; time1: boolean }) {
|
||||
return (
|
||||
<div className="hint wheel-legend">
|
||||
<p className="wheel-legend-items">
|
||||
<span className="legend-item">
|
||||
<span className="legend-dot legend-p1" aria-hidden="true" /> belül: {name1}
|
||||
{time1 ? " (bolygók és házak)" : ""}
|
||||
</span>
|
||||
<span className="legend-item">
|
||||
<span className="legend-dot legend-p2" aria-hidden="true" /> kívül: {name2}
|
||||
</span>
|
||||
</p>
|
||||
<p className="wheel-legend-items">
|
||||
{[
|
||||
["trine", "trigon"],
|
||||
["sextile", "szextil"],
|
||||
["square", "kvadrát"],
|
||||
["opposition", "szembenállás"],
|
||||
].map(([aspect, label]) => (
|
||||
<span key={aspect} className="legend-item">
|
||||
<span className={`legend-line legend-${aspect}`} aria-hidden="true" /> {label}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
<p>A vonalak a két fél bolygói közti főfényszögek; vastagabb vonal: szorosabb fényszög. Az összes a táblázatokban.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ChartListItem, Synastry, SynastrySide } from "./types";
|
||||
|
||||
/** Short name of one side of a comparison: "Én" for the own chart. */
|
||||
export function sideName(side: { label: string; is_primary?: boolean }): string {
|
||||
return side.is_primary ? "Én" : side.label;
|
||||
}
|
||||
|
||||
/** Whether a side's birth time is known (another user's chart has fewer fields). */
|
||||
export function sideTimeKnown(side: SynastrySide): boolean {
|
||||
const chart = side.chart as SynastrySide["chart"] & { time_known?: boolean };
|
||||
return side.highlights?.time_known ?? chart.time?.time_known ?? chart.time_known ?? false;
|
||||
}
|
||||
|
||||
/** Name of a chart in the comparison list, from the user's chart list. */
|
||||
export function listName(ref: { id: string; label: string }, charts: ChartListItem[]): string {
|
||||
const chart = charts.find((c) => c.id === ref.id);
|
||||
return chart ? sideName(chart) : ref.label;
|
||||
}
|
||||
|
||||
export type { Synastry };
|
||||
@@ -124,6 +124,67 @@ export interface ChartListItem {
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** An aspect between a point of the first chart and one of the second. */
|
||||
export interface InterAspect {
|
||||
person1: string;
|
||||
person2: string;
|
||||
aspect: string;
|
||||
nature: "harmonious" | "challenging" | "neutral";
|
||||
major: boolean;
|
||||
orb: number;
|
||||
max_orb: number;
|
||||
}
|
||||
|
||||
export interface HouseOverlay {
|
||||
point: string;
|
||||
sign: string;
|
||||
house: number;
|
||||
}
|
||||
|
||||
export interface SynastryResult {
|
||||
aspects: InterAspect[];
|
||||
house_overlays: {
|
||||
/** The first person's points in the second person's houses (null: second time unknown). */
|
||||
person1_in_person2: HouseOverlay[] | null;
|
||||
person2_in_person1: HouseOverlay[] | null;
|
||||
};
|
||||
summary: {
|
||||
aspect_count: number;
|
||||
by_nature: { harmonious: number; challenging: number; neutral: number };
|
||||
by_aspect: Record<string, number>;
|
||||
};
|
||||
composite: {
|
||||
method: string;
|
||||
points: ChartPoint[];
|
||||
angles: Record<string, Position> | null;
|
||||
houses: { cusps: (Position & { house: number })[] } | null;
|
||||
aspects: Aspect[];
|
||||
};
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/** One side of a comparison: the full chart when it is the viewer's own. */
|
||||
export type SynastrySide = Chart & { owned: true };
|
||||
|
||||
export interface Synastry {
|
||||
id: string;
|
||||
owned: boolean;
|
||||
chart1: SynastrySide;
|
||||
chart2: SynastrySide;
|
||||
synastry: SynastryResult;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** A comparison in the list (`GET /v1/synastries`). */
|
||||
export interface SynastryListItem {
|
||||
id: string;
|
||||
owned: boolean;
|
||||
chart1: { id: string; label: string; owned: boolean };
|
||||
chart2: { id: string; label: string; owned: boolean };
|
||||
summary: SynastryResult["summary"] | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Analysis {
|
||||
id: string;
|
||||
kind: "natal" | "synastry" | "summary";
|
||||
@@ -149,7 +210,7 @@ export interface AdminUser {
|
||||
analyses_left: UnitBalance;
|
||||
}
|
||||
|
||||
export type PromptKind = "summary" | "natal";
|
||||
export type PromptKind = "summary" | "natal" | "synastry";
|
||||
|
||||
export interface PromptRevision {
|
||||
id: number;
|
||||
@@ -179,7 +240,8 @@ export interface AdminPrompt {
|
||||
export interface PromptPreview {
|
||||
id: string;
|
||||
kind: PromptKind;
|
||||
chart_id: string;
|
||||
chart_id: string | null;
|
||||
synastry_id: string | null;
|
||||
language: string;
|
||||
model: string;
|
||||
status: "pending" | "running" | "done" | "failed";
|
||||
|
||||
@@ -45,7 +45,8 @@ pub struct Job {
|
||||
pub struct PreviewJob {
|
||||
pub id: Uuid,
|
||||
pub kind: String,
|
||||
pub chart_id: Uuid,
|
||||
pub chart_id: Option<Uuid>,
|
||||
pub synastry_id: Option<Uuid>,
|
||||
pub language: String,
|
||||
pub model: String,
|
||||
pub system: String,
|
||||
@@ -91,21 +92,9 @@ impl Analyzer {
|
||||
pub async fn prompt_for(&self, job: &Job) -> Result<Prompt, LlmError> {
|
||||
let kind = Kind::parse(&job.kind).ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
|
||||
let db_err = |e: sqlx::Error| LlmError::Transient(format!("database: {e}"));
|
||||
let gone = || LlmError::Permanent("the chart was deleted".into());
|
||||
let text = match kind {
|
||||
Kind::Natal | Kind::Summary => self.natal_text(job.chart_id).await?,
|
||||
Kind::Synastry => {
|
||||
let (result, chart1, chart2): (Value, Value, Value) = sqlx::query_as(
|
||||
"SELECT s.result, c1.result, c2.result FROM synastries s \
|
||||
JOIN charts c1 ON c1.id = s.chart1_id JOIN charts c2 ON c2.id = s.chart2_id WHERE s.id = $1",
|
||||
)
|
||||
.bind(job.synastry_id)
|
||||
.fetch_optional(&self.db)
|
||||
.await
|
||||
.map_err(db_err)?
|
||||
.ok_or_else(gone)?;
|
||||
compact::synastry(&chart1, &chart2, &result)
|
||||
}
|
||||
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
|
||||
};
|
||||
let (base, revision) = prompt::split_version(&job.prompt_version);
|
||||
if base != PROMPT_VERSION {
|
||||
@@ -135,13 +124,27 @@ impl Analyzer {
|
||||
Ok(compact::natal(&chart))
|
||||
}
|
||||
|
||||
/// The compact text of a stored synastry with its two charts.
|
||||
async fn synastry_text(&self, synastry_id: Option<Uuid>) -> Result<String, LlmError> {
|
||||
let (result, chart1, chart2): (Value, Value, Value) = sqlx::query_as(
|
||||
"SELECT s.result, c1.result, c2.result FROM synastries s \
|
||||
JOIN charts c1 ON c1.id = s.chart1_id JOIN charts c2 ON c2.id = s.chart2_id WHERE s.id = $1",
|
||||
)
|
||||
.bind(synastry_id)
|
||||
.fetch_optional(&self.db)
|
||||
.await
|
||||
.map_err(|e| LlmError::Transient(format!("database: {e}")))?
|
||||
.ok_or_else(|| LlmError::Permanent("the synastry was deleted".into()))?;
|
||||
Ok(compact::synastry(&chart1, &chart2, &result))
|
||||
}
|
||||
|
||||
/// Takes the oldest waiting prompt test run, if any.
|
||||
pub async fn claim_preview(&self) -> Result<Option<PreviewJob>, sqlx::Error> {
|
||||
let job: Option<PreviewJob> = sqlx::query_as(
|
||||
"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, language, model, system",
|
||||
RETURNING id, kind, chart_id, synastry_id, language, model, system",
|
||||
)
|
||||
.fetch_optional(&self.db)
|
||||
.await?;
|
||||
@@ -155,10 +158,12 @@ impl Analyzer {
|
||||
pub async fn handle_preview(&self, job: PreviewJob) {
|
||||
let started = Instant::now();
|
||||
let result = async {
|
||||
let kind = Kind::parse(&job.kind)
|
||||
.filter(|k| *k != Kind::Synastry)
|
||||
.ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
|
||||
let text = self.natal_text(Some(job.chart_id)).await?;
|
||||
let kind =
|
||||
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?,
|
||||
};
|
||||
let built = prompt::build(kind, &job.language, &text, Some(&job.system));
|
||||
let mut c = self.llm.complete(&job.model, &built).await?;
|
||||
prompt::polish(&job.language, &mut c.content);
|
||||
|
||||
@@ -567,11 +567,31 @@ mod analyses {
|
||||
assert!(run_once(&a).await);
|
||||
assert_eq!(row(&db, id).await.0, "done");
|
||||
|
||||
{
|
||||
let requests = fake.requests.lock().unwrap();
|
||||
let user = requests[0]["messages"][1]["content"].as_str().unwrap();
|
||||
assert!(user.starts_with("Chart data:\n\nSYNASTRY") && user.contains("- attraction: "));
|
||||
assert!(requests[0]["messages"][0]["content"].as_str().unwrap().contains("Write in English."));
|
||||
assert!(!user.contains("Szeged") && !user.contains("Pécs"));
|
||||
}
|
||||
|
||||
// a prompt test run on the comparison
|
||||
sqlx::query(
|
||||
"INSERT INTO prompt_previews (id, kind, synastry_id, language, model, system, created_by) \
|
||||
VALUES ($1, 'synastry', $2, 'hu', 'test/model', 'Kapcsolati próba.', $3)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(synastry)
|
||||
.bind(s.user)
|
||||
.execute(&db)
|
||||
.await
|
||||
.unwrap();
|
||||
a.handle_preview(a.claim_preview().await.unwrap().expect("the preview")).await;
|
||||
let (status,): (String,) = sqlx::query_as("SELECT status FROM prompt_previews").fetch_one(&db).await.unwrap();
|
||||
assert_eq!(status, "done");
|
||||
let requests = fake.requests.lock().unwrap();
|
||||
let user = requests[0]["messages"][1]["content"].as_str().unwrap();
|
||||
assert!(user.starts_with("Chart data:\n\nSYNASTRY") && user.contains("- attraction: "));
|
||||
assert!(requests[0]["messages"][0]["content"].as_str().unwrap().contains("Write in English."));
|
||||
assert!(!user.contains("Szeged") && !user.contains("Pécs"));
|
||||
assert_eq!(requests[1]["messages"][0]["content"], "Kapcsolati próba.");
|
||||
assert!(requests[1]["messages"][1]["content"].as_str().unwrap().contains("SYNASTRY"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user