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:
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user