Renaming a person keeps the chart and its analyses
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -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).
|
||||
|
||||
@@ -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 {
|
||||
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("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()))
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<string | null>(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 (
|
||||
<form onSubmit={save} className="field" style={{ gap: 16 }} noValidate>
|
||||
<div className="field" style={{ maxWidth: 420 }}>
|
||||
<label htmlFor="rename">Név</label>
|
||||
<input
|
||||
id="rename"
|
||||
className="inp"
|
||||
value={value}
|
||||
maxLength={100}
|
||||
autoComplete="off"
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || value.trim() === name}>
|
||||
{busy ? "Mentés…" : "Név mentése"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => router.push(`/kepletek/${id}`)} disabled={busy}>
|
||||
Mégse
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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:
|
||||
<div className="page-head">
|
||||
<h1>{chart.label} adatai</h1>
|
||||
<p className="muted">
|
||||
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."}
|
||||
</p>
|
||||
</div>
|
||||
<section className="card" aria-label="Születési adatok">
|
||||
@@ -42,10 +44,8 @@ export default async function EditPersonPage({ params }: { params: Promise<{ id:
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<p className="muted">A személy születési adatai csak a felvételt követő egy órán belül javíthatók.</p>
|
||||
<Link href={`/kepletek/${id}`} className="btn" style={{ alignSelf: "flex-start" }}>
|
||||
Vissza a képlethez
|
||||
</Link>
|
||||
<RenamePerson id={id} name={chart.label} />
|
||||
<p className="hint">A születési adatok csak a felvételt követő egy órán belül javíthatók.</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -53,11 +53,9 @@ export function PersonActions({
|
||||
) : (
|
||||
<>
|
||||
{ownId && <CompareButton chart1={ownId} chart2={id} />}
|
||||
{editable && (
|
||||
<Link href={`/kepletek/${id}/javitas`} className="btn btn-sm btn-ghost">
|
||||
Adatok javítása
|
||||
{editable ? "Adatok javítása" : "Átnevezés"}
|
||||
</Link>
|
||||
)}
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setConfirm(true)}>
|
||||
Törlés
|
||||
</button>
|
||||
|
||||
Reference in New Issue
Block a user