Start the Next.js frontend: Google login, profile, birth data, admin

services/frontend (Next.js 16, App Router) runs on port 3001 in compose. The
browser only talks to the frontend: /api/v1/* is proxied to the backend, so
the session cookie lives on the frontend's host, and /api/geo/* exposes the
country list and place search of the horoscope-api.

- /belepes: Google Identity Services button, client id from /v1/config
- /profil: account facts, display name and language, own birth data with
  place search, DST ambiguity prompt and the chart's positions
- /admin: user search, role toggles, credit grants (admins only, 404 otherwise)

Services now tolerate migrations newer than their binary, so they can be
rebuilt one at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-15 21:00:50 +00:00
co-authored by Claude Opus 5.5
parent 4aabb7343c
commit 1f177f859e
38 changed files with 2996 additions and 5 deletions
@@ -0,0 +1,83 @@
"use client";
import { useState } from "react";
import { countryName, formatBirthDate } from "@/lib/astro";
import type { BirthData } from "@/lib/types";
import { BirthForm } from "./BirthForm";
export interface SavedBirth {
birth: BirthData;
placeName: string | null;
region: string | null;
countryCode: string | null;
zone: string;
utcOffset: string;
dst: boolean;
}
/** Shows the saved birth data (and the chart tables), or the form to enter or correct it. */
export function BirthEditor({ chart, children }: { chart: SavedBirth | null; children: React.ReactNode }) {
const [editing, setEditing] = useState(chart === null);
if (editing || !chart) {
return (
<div className="field" style={{ gap: 16 }}>
{chart ? (
<p className="muted">
A javított adatokból új képlet készül, és az lesz a saját képleted. A régit a meglévő összevetések miatt
megtartjuk.
</p>
) : (
<p className="muted">
Add meg a születésed adatait. Ebből számoljuk a képletedet; a helyi időt és az akkori időzónát (nyári
időszámítást) a születési hely alapján magunk határozzuk meg.
</p>
)}
<BirthForm
initial={chart ? { ...chart.birth, placeName: chart.placeName, region: chart.region } : null}
onCancel={chart ? () => setEditing(false) : undefined}
onSaved={() => setEditing(false)}
/>
</div>
);
}
const { birth } = chart;
const country = chart.countryCode ?? birth.country;
return (
<div className="field" style={{ gap: 24 }}>
<div className="card-head" style={{ alignItems: "flex-start" }}>
<dl className="facts">
<dt>Dátum</dt>
<dd>{formatBirthDate(birth.date)}</dd>
<dt>Időpont</dt>
<dd>
{birth.time ? (
<>
{birth.time.slice(0, 5)}{" "}
<span className="muted">
({chart.zone}, UTC{chart.utcOffset}
{chart.dst ? ", nyári idő" : ""})
</span>
</>
) : (
<span className="muted">ismeretlen</span>
)}
</dd>
<dt>Hely</dt>
<dd>
{chart.placeName ?? birth.place ?? "–"}
{chart.region && <span className="muted">, {chart.region}</span>}
{country && <span className="muted">, {countryName(country)}</span>}
</dd>
</dl>
<button type="button" className="btn" onClick={() => setEditing(true)}>
Adatok javítása
</button>
</div>
{children}
</div>
);
}
@@ -0,0 +1,326 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { ApiError, api, errorText } from "@/lib/api";
import { countryName } from "@/lib/astro";
import type { BirthData, Country, Place } from "@/lib/types";
type Initial = (BirthData & { placeName: string | null; region: string | null }) | null;
type Ambiguity = "earlier" | "later";
const ERRORS: Record<string, string> = {
place_not_found: "Nem találjuk ezt a települést. Válassz a listából.",
nonexistent_local_time:
"Ez az időpont az óraátállítás miatt nem létezett ezen a napon (az órát előreállították). Ellenőrizd a születési időt.",
invalid_date: "Érvénytelen dátum.",
};
export function BirthForm({
initial,
onCancel,
onSaved,
}: {
initial: Initial;
onCancel?: () => void;
onSaved: () => void;
}) {
const router = useRouter();
const [date, setDate] = useState(initial?.date ?? "");
const [time, setTime] = useState(initial?.time?.slice(0, 5) ?? "");
const [timeUnknown, setTimeUnknown] = useState(initial ? !initial.time : false);
const [country, setCountry] = useState(initial?.country ?? "HU");
const [place, setPlace] = useState<Place | null>(
initial?.geonames_id && initial.placeName
? {
geonames_id: initial.geonames_id,
name: initial.placeName,
region: initial.region,
population: null,
country_code: initial.country ?? "HU",
}
: null,
);
const [ambiguous, setAmbiguous] = useState(false);
const [ambiguity, setAmbiguity] = useState<Ambiguity>("earlier");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const today = useMemo(() => new Date().toISOString().slice(0, 10), []);
async function submit(e: React.FormEvent) {
e.preventDefault();
setError(null);
if (!date) return setError("Add meg a születési dátumot.");
if (!timeUnknown && !time) return setError("Add meg a születési időt, vagy jelöld, hogy nem tudod.");
if (!place) return setError("Válaszd ki a születési helyet a listából.");
setBusy(true);
try {
await api("/charts", {
body: {
label: "Saját képlet",
is_primary: true,
birth: {
date,
...(timeUnknown ? {} : { time }),
country,
geonames_id: place.geonames_id,
...(ambiguous ? { ambiguous_time: ambiguity } : {}),
},
},
});
onSaved();
router.refresh();
} catch (err) {
if (err instanceof ApiError && err.code === "ambiguous_local_time") {
setAmbiguous(true);
setError(
"Ez az időpont az óraátállítás miatt kétszer is előfordult ezen a napon. Válaszd ki, melyikben születtél, és mentsd újra.",
);
} else {
setError(err instanceof ApiError ? (ERRORS[err.code] ?? errorText(err)) : errorText(err));
}
} finally {
setBusy(false);
}
}
return (
<form onSubmit={submit} className="field" style={{ gap: 18 }} noValidate>
<div className="grid-2">
<div className="field">
<label htmlFor="birth-date">Születési dátum</label>
<input
id="birth-date"
type="date"
className="inp"
min="1000-01-01"
max={today}
value={date}
onChange={(e) => setDate(e.target.value)}
required
/>
</div>
<div className="field">
<label htmlFor="birth-time">Születési idő (helyi idő)</label>
<input
id="birth-time"
type="time"
className="inp"
value={timeUnknown ? "" : time}
disabled={timeUnknown}
onChange={(e) => {
setTime(e.target.value);
setAmbiguous(false);
}}
/>
<label className="check">
<input type="checkbox" checked={timeUnknown} onChange={(e) => setTimeUnknown(e.target.checked)} />
Nem tudom a születési időt
</label>
</div>
</div>
<div className="grid-2">
<CountrySelect
value={country}
onChange={(c) => {
setCountry(c);
setPlace(null);
}}
/>
<PlaceSearch country={country} value={place} onChange={setPlace} />
</div>
{ambiguous && (
<fieldset className="field" style={{ border: 0, padding: 0, margin: 0 }}>
<legend className="label" style={{ marginBottom: 8 }}>
Melyik időpontban születtél?
</legend>
<label className="check">
<input type="radio" name="ambiguity" checked={ambiguity === "earlier"} onChange={() => setAmbiguity("earlier")} />
Az elsőben, még nyári időszámítás szerint
</label>
<label className="check">
<input type="radio" name="ambiguity" checked={ambiguity === "later"} onChange={() => setAmbiguity("later")} />
A másodikban, már téli időszámítás szerint
</label>
</fieldset>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={busy}>
{busy ? "Számolás…" : "Mentés és képlet számítása"}
</button>
{onCancel && (
<button type="button" className="btn btn-ghost" onClick={onCancel} disabled={busy}>
Mégse
</button>
)}
</div>
</form>
);
}
function CountrySelect({ value, onChange }: { value: string; onChange: (iso2: string) => void }) {
const [countries, setCountries] = useState<Country[]>([]);
useEffect(() => {
fetch("/api/geo/countries")
.then((r) => (r.ok ? r.json() : { countries: [] }))
.then((d: { countries: Country[] }) => {
const named = d.countries.map((c) => ({ iso2: c.iso2, name: countryName(c.iso2, c.name) }));
named.sort((a, b) => a.name.localeCompare(b.name, "hu"));
setCountries(named);
})
.catch(() => setCountries([]));
}, []);
return (
<div className="field">
<label htmlFor="birth-country">Ország</label>
<select id="birth-country" className="inp" value={value} onChange={(e) => onChange(e.target.value)}>
{countries.length === 0 && <option value={value}>{countryName(value)}</option>}
{countries.map((c) => (
<option key={c.iso2} value={c.iso2}>
{c.name}
</option>
))}
</select>
</div>
);
}
function PlaceSearch({
country,
value,
onChange,
}: {
country: string;
value: Place | null;
onChange: (p: Place | null) => void;
}) {
const listId = useId();
const [query, setQuery] = useState(value?.name ?? "");
const [results, setResults] = useState<Place[]>([]);
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
const [loading, setLoading] = useState(false);
const seq = useRef(0);
// A new country starts a new search.
const firstCountry = useRef(country);
useEffect(() => {
if (country === firstCountry.current) return;
firstCountry.current = country;
setQuery("");
setResults([]);
}, [country]);
useEffect(() => {
const q = query.trim();
if (q.length < 2 || (value && value.name === query)) {
setResults([]);
return;
}
const id = ++seq.current;
setLoading(true);
const timer = setTimeout(async () => {
try {
const res = await fetch(`/api/geo/places?country=${country}&q=${encodeURIComponent(q)}&limit=8`);
const data = res.ok ? ((await res.json()) as { places: Place[] }) : { places: [] };
if (id === seq.current) {
setResults(data.places);
setActive(0);
setOpen(true);
}
} catch {
if (id === seq.current) setResults([]);
} finally {
if (id === seq.current) setLoading(false);
}
}, 250);
return () => clearTimeout(timer);
}, [query, country, value]);
function choose(p: Place) {
onChange(p);
setQuery(p.name);
setOpen(false);
}
function onKey(e: React.KeyboardEvent) {
if (!open || results.length === 0) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((a) => (a + 1) % results.length);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((a) => (a - 1 + results.length) % results.length);
} else if (e.key === "Enter") {
e.preventDefault();
choose(results[active]);
} else if (e.key === "Escape") {
setOpen(false);
}
}
const showList = open && results.length > 0;
return (
<div className="field">
<label htmlFor="birth-place">Település</label>
<div className="combo">
<input
id="birth-place"
className="inp"
role="combobox"
aria-expanded={showList}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={showList ? `${listId}-${active}` : undefined}
autoComplete="off"
placeholder="Kezdd el gépelni, pl. Szeged"
value={query}
onChange={(e) => {
setQuery(e.target.value);
if (value) onChange(null);
}}
onKeyDown={onKey}
onFocus={() => results.length > 0 && setOpen(true)}
onBlur={() => setTimeout(() => setOpen(false), 150)}
/>
{showList && (
<ul className="combo-list" id={listId} role="listbox">
{results.map((p, i) => (
<li key={p.geonames_id} role="presentation">
<button
type="button"
id={`${listId}-${i}`}
role="option"
aria-selected={i === active}
tabIndex={-1}
onMouseDown={(e) => e.preventDefault()}
onClick={() => choose(p)}
>
{p.name} {p.region && <small>· {p.region}</small>}
</button>
</li>
))}
</ul>
)}
</div>
<span className="hint" aria-live="polite">
{value
? `Kiválasztva: ${value.name}${value.region ? `, ${value.region}` : ""}`
: loading
? "Keresés…"
: query.trim().length >= 2 && results.length === 0
? "Nincs találat ebben az országban."
: "Válassz a listából."}
</span>
</div>
);
}
@@ -0,0 +1,62 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
export function ProfileForm({ displayName, locale }: { displayName: string; locale: string }) {
const router = useRouter();
const [name, setName] = useState(displayName);
const [lang, setLang] = useState(locale);
const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
const [busy, setBusy] = useState(false);
async function save(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setStatus(null);
try {
await api("/me", { method: "PATCH", body: { display_name: name.trim(), locale: lang } });
setStatus({ ok: true, text: "Elmentve." });
router.refresh();
} catch (err) {
setStatus({ ok: false, text: errorText(err) });
} finally {
setBusy(false);
}
}
return (
<form onSubmit={save} className="field" style={{ gap: 16 }}>
<div className="field">
<label htmlFor="display-name">Megjelenített név</label>
<input
id="display-name"
className="inp"
value={name}
maxLength={80}
autoComplete="name"
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="field">
<label htmlFor="locale">Az elemzések nyelve</label>
<select id="locale" className="inp" value={lang} onChange={(e) => setLang(e.target.value)}>
<option value="hu">Magyar</option>
<option value="en">English</option>
</select>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={busy}>
Mentés
</button>
{status && (
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
{status.text}
</span>
)}
</div>
</form>
);
}
+80
View File
@@ -0,0 +1,80 @@
import type { Metadata } from "next";
import { ChartTables } from "@/components/ChartTables";
import { ROLE_LABELS, formatDate } from "@/lib/astro";
import { backendGet, requireMe } from "@/lib/server";
import type { Chart } from "@/lib/types";
import { BirthEditor } from "./BirthEditor";
import { ProfileForm } from "./ProfileForm";
export const metadata: Metadata = { title: "Profil" };
const PROVIDERS: Record<string, string> = { google: "Google", password: "E-mail és jelszó" };
export default async function ProfilePage() {
const me = await requireMe("/profil");
const chart = me.primary_chart_id ? await backendGet<Chart>(`/v1/charts/${me.primary_chart_id}`) : null;
const { user } = me;
return (
<main className="page">
<div className="page-head">
<h1>Profil</h1>
<p className="muted">A fiókod adatai és a saját születési képleted.</p>
</div>
<section className="card" aria-labelledby="account">
<div className="card-head">
<h2 id="account">Fiók</h2>
<div className="row" style={{ gap: 6 }}>
{user.roles.map((r) => (
<span key={r} className={r === "user" ? "badge" : "badge badge-gold"}>
{ROLE_LABELS[r] ?? r}
</span>
))}
</div>
</div>
<div className="grid-2">
<dl className="facts">
<dt>E-mail</dt>
<dd>
{user.email} {user.email_verified && <span className="badge">megerősítve</span>}
</dd>
<dt>Belépés</dt>
<dd>{me.providers.map((p) => PROVIDERS[p] ?? p).join(", ") || "–"}</dd>
<dt>Kreditek</dt>
<dd>{me.credits}</dd>
<dt>Tag óta</dt>
<dd>{formatDate(user.created_at)}</dd>
</dl>
<ProfileForm displayName={user.display_name ?? ""} locale={user.locale} />
</div>
</section>
<section className="card" aria-labelledby="birth">
<div className="card-head">
<h2 id="birth">Születési adataim</h2>
{chart && !chart.highlights.time_known && <span className="badge">ismeretlen születési idő</span>}
</div>
<BirthEditor
chart={
chart
? {
birth: chart.birth_data,
placeName: chart.chart.location.place?.name ?? null,
region: chart.chart.location.place?.region ?? null,
countryCode: chart.chart.location.place?.country_code ?? chart.birth_data.country ?? null,
zone: chart.chart.time.zone,
utcOffset: chart.chart.time.utc_offset,
dst: chart.chart.time.dst,
}
: null
}
>
{chart && <ChartTables chart={chart} />}
</BirthEditor>
</section>
</main>
);
}