From b53cadcd8c0ae5e902898276bec7487968509dc6 Mon Sep 17 00:00:00 2001 From: feco Date: Tue, 17 Nov 2026 16:59:18 +0000 Subject: [PATCH] Renaming a person keeps the chart and its analyses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The person edit form sent the birth data with every save, so a new name alone recalculated the chart, deleted its analyses and comparisons and queued a new summary. Now the backend ignores birth data equal to the stored one (and keeps everything when a recalculation gives the same chart), and the form sends it only when it changed. The name can be changed after the correction window too ("Átnevezés" on the person card). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- services/backend/README.md | 2 +- services/backend/src/routes/charts.rs | 20 +++++-- services/backend/src/tests.rs | 46 ++++++++++++++- .../kepletek/[id]/javitas/RenamePerson.tsx | 59 +++++++++++++++++++ .../src/app/kepletek/[id]/javitas/page.tsx | 14 ++--- .../frontend/src/app/profil/BirthForm.tsx | 11 +++- .../frontend/src/components/PersonActions.tsx | 8 +-- 7 files changed, 140 insertions(+), 20 deletions(-) create mode 100644 services/frontend/src/app/kepletek/[id]/javitas/RenamePerson.tsx diff --git a/services/backend/README.md b/services/backend/README.md index 5970d43..935426e 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -124,5 +124,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. Helyet a csomagok adnak; korlátlan az `unlimited_persons` jogosultsággal és futó Korlátlan csomaggal. 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`. +- **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. Helyet a csomagok adnak; korlátlan az `unlimited_persons` jogosultsággal és futó Korlátlan csomaggal. 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`. A név (`label`) bármikor változhat; ha a `birth` ugyanaz, mint a tárolt (vagy ugyanazt a képletet adja), nincs újraszámolás, és az elemzések, összevetések maradnak. 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). diff --git a/services/backend/src/routes/charts.rs b/services/backend/src/routes/charts.rs index 649f076..67fefb4 100644 --- a/services/backend/src/routes/charts.rs +++ b/services/backend/src/routes/charts.rs @@ -267,15 +267,25 @@ pub async fn update( None => chart.label.clone(), }; let is_primary = req.is_primary.unwrap_or(chart.is_primary); - let recalculated = match req.birth { + // The same birth data again (e.g. only the name changed): no recalculation, + // and the analyses and comparisons stay. A new calculation that gives the + // same chart keeps them too. + let birth = req.birth.map(clean_birth).transpose()?.filter(|b| *b != chart.birth_data); + let recalculated = match birth { Some(birth) => Some(corrected_birth(&state, &auth, &chart, birth).await?), None => None, }; + let chart_changed = recalculated.as_ref().is_some_and(|(_, _, hash)| *hash != chart.chart_hash); let mut tx = state.db.begin().await?; if let Some((birth, result, hash)) = &recalculated { - // 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?; + if chart_changed { + // 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) @@ -303,7 +313,7 @@ pub async fn update( birth_changes::record(&mut tx, &auth, id).await?; } tx.commit().await?; - if recalculated.is_some() { + if chart_changed { queue_summary(&state, &auth, &row).await; } Ok(Json(row.owner_view())) diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index a6b6bf4..38c8bc2 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -802,7 +802,8 @@ async fn persons_use_package_slots(pool: PgPool) { .execute(&app.pool) .await .unwrap(); - let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(corrected.clone())).await; + let again = json!({"birth": {"date": "1986-01-03", "time": "10:00", "country": "HU", "place": "Szeged"}}); + let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(again)).await; assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_locked"))); let r = app.call("PATCH", &format!("/v1/charts/{}", own["id"].as_str().unwrap()), Some(&anna), Some(corrected)).await; @@ -1068,3 +1069,46 @@ async fn packages_grant_units_and_unlimited(pool: PgPool) { assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED); assert_eq!(app.get("/v1/me", Some(&bela)).await.body["unlimited_until"], Value::Null); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn renaming_a_person_keeps_chart_and_analyses(pool: PgPool) { + let app = TestApp::new(pool.clone()).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 id = bela["id"].as_str().unwrap(); + let syn = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": id})).await; + assert_eq!(syn.status, StatusCode::CREATED); + let summaries = || async { + let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM analyses WHERE chart_id = $1::uuid") + .bind(id) + .fetch_one(&pool) + .await + .unwrap(); + n + }; + assert_eq!(summaries().await, 1); + + // the edit form sends the unchanged birth data with the new name + let same = json!({"label": "Béla bácsi", + "birth": {"date": "1985-08-02", "time": "14:30", "country": "HU", "place": "Szeged"}}); + let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same.clone())).await; + assert_eq!( + (r.status, &r.body["label"], &r.body["chart_hash"]), + (StatusCode::OK, &json!("Béla bácsi"), &bela["chart_hash"]) + ); + assert_eq!(summaries().await, 1); + let r = app.get(&format!("/v1/synastries/{}", syn.body["id"].as_str().unwrap()), Some(&anna)).await; + assert_eq!(r.status, StatusCode::OK); + + // after the correction window the name can still change + sqlx::query("UPDATE charts SET created_at = now() - interval '2 hours' WHERE id = $1::uuid") + .bind(id) + .execute(&pool) + .await + .unwrap(); + let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(json!({"label": "Béla"}))).await; + assert_eq!((r.status, &r.body["label"]), (StatusCode::OK, &json!("Béla"))); + let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same)).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); +} diff --git a/services/frontend/src/app/kepletek/[id]/javitas/RenamePerson.tsx b/services/frontend/src/app/kepletek/[id]/javitas/RenamePerson.tsx new file mode 100644 index 0000000..343db8d --- /dev/null +++ b/services/frontend/src/app/kepletek/[id]/javitas/RenamePerson.tsx @@ -0,0 +1,59 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +import { api, errorText } from "@/lib/api"; + +/** Changes only a person's name (any time; the chart and analyses stay). */ +export function RenamePerson({ id, name }: { id: string; name: string }) { + const router = useRouter(); + const [value, setValue] = useState(name); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function save(e: React.FormEvent) { + e.preventDefault(); + if (!value.trim()) return setError("Add meg a nevét."); + setBusy(true); + setError(null); + try { + await api(`/charts/${id}`, { method: "PATCH", body: { label: value.trim() } }); + router.push(`/kepletek/${id}`); + router.refresh(); + } catch (err) { + setError(errorText(err)); + setBusy(false); + } + } + + return ( +
+
+ + setValue(e.target.value)} + required + /> +
+ {error && ( +

+ {error} +

+ )} +
+ + +
+
+ ); +} diff --git a/services/frontend/src/app/kepletek/[id]/javitas/page.tsx b/services/frontend/src/app/kepletek/[id]/javitas/page.tsx index 19b43ff..ff60fc7 100644 --- a/services/frontend/src/app/kepletek/[id]/javitas/page.tsx +++ b/services/frontend/src/app/kepletek/[id]/javitas/page.tsx @@ -1,17 +1,17 @@ import type { Metadata } from "next"; -import Link from "next/link"; import { notFound } from "next/navigation"; import { backendGet, requireMe } from "@/lib/server"; import type { Chart } from "@/lib/types"; import { EditPerson } from "./EditPerson"; +import { RenamePerson } from "./RenamePerson"; export const metadata: Metadata = { title: "Adatok javítása" }; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -/** Correcting a person's birth data (within an hour of adding them; admins any time). */ +/** Correcting a person: name any time, birth data within an hour of adding them (admins any time). */ export default async function EditPersonPage({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; const me = await requireMe(`/kepletek/${id}/javitas`); @@ -26,7 +26,9 @@ export default async function EditPersonPage({ params }: { params: Promise<{ id:

{chart.label} adatai

- A javítás után újraszámoljuk a képletet és a rövid összefoglalót. + {editable + ? "Ha a születési adatokon változtatsz, újraszámoljuk a képletet és a rövid összefoglalót. A név módosítása a képletet és az elemzéseket nem érinti." + : "A név bármikor módosítható; a képlet és az elemzések maradnak."}

@@ -42,10 +44,8 @@ export default async function EditPersonPage({ params }: { params: Promise<{ id: /> ) : ( <> -

A személy születési adatai csak a felvételt követő egy órán belül javíthatók.

- - Vissza a képlethez - + +

A születési adatok csak a felvételt követő egy órán belül javíthatók.

)}
diff --git a/services/frontend/src/app/profil/BirthForm.tsx b/services/frontend/src/app/profil/BirthForm.tsx index fe1647d..f59644d 100644 --- a/services/frontend/src/app/profil/BirthForm.tsx +++ b/services/frontend/src/app/profil/BirthForm.tsx @@ -69,10 +69,19 @@ export function BirthForm({ geonames_id: place.geonames_id, ...(ambiguous ? { ambiguous_time: ambiguity } : {}), }; + // Correcting a person: the birth data only when it changed, so a new + // name alone does not recalculate the chart or drop its analyses. + const birthChanged = + !initial || + ambiguous || + date !== initial.date || + (timeUnknown ? null : time) !== (initial.time?.slice(0, 5) ?? null) || + country !== (initial.country ?? "HU") || + place.geonames_id !== initial.geonames_id; const saved = person?.chartId ? await api<{ id: string }>(`/charts/${person.chartId}`, { method: "PATCH", - body: { label: name.trim(), birth }, + body: birthChanged ? { label: name.trim(), birth } : { label: name.trim() }, }) : await api<{ id: string }>("/charts", { body: person diff --git a/services/frontend/src/components/PersonActions.tsx b/services/frontend/src/components/PersonActions.tsx index 3163515..60f23c1 100644 --- a/services/frontend/src/components/PersonActions.tsx +++ b/services/frontend/src/components/PersonActions.tsx @@ -53,11 +53,9 @@ export function PersonActions({ ) : ( <> {ownId && } - {editable && ( - - Adatok javítása - - )} + + {editable ? "Adatok javítása" : "Átnevezés"} +