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,182 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { ROLE_LABELS, formatDate } from "@/lib/astro";
import type { AdminUser, Role } from "@/lib/types";
const EDITABLE_ROLES: Role[] = ["user", "premium", "vip", "creator", "admin"];
export function AdminUsers({ selfId }: { selfId: string }) {
const [query, setQuery] = useState("");
const [users, setUsers] = useState<AdminUser[] | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async (q: string) => {
try {
const data = await api<{ users: AdminUser[] }>(`/admin/users?q=${encodeURIComponent(q)}`);
setUsers(data.users);
setError(null);
} catch (e) {
setError(errorText(e));
}
}, []);
useEffect(() => {
const t = setTimeout(() => load(query.trim()), 250);
return () => clearTimeout(t);
}, [query, load]);
return (
<section className="card" aria-label="Felhasználók listája">
<div className="field" style={{ maxWidth: 420 }}>
<label htmlFor="user-search">Keresés név vagy e-mail alapján</label>
<input
id="user-search"
className="inp"
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="pl. anna@"
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{users === null ? (
<p className="muted">Betöltés…</p>
) : users.length === 0 ? (
<p className="muted">Nincs találat.</p>
) : (
<div className="table-wrap">
<table>
<thead>
<tr>
<th scope="col">Felhasználó</th>
<th scope="col">Szerepkörök</th>
<th scope="col">Kredit</th>
<th scope="col">Képletek</th>
<th scope="col">Regisztrált</th>
<th scope="col">Utoljára belépett</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<UserRow
key={u.id}
user={u}
isSelf={u.id === selfId}
onChange={(next) => setUsers((list) => list?.map((x) => (x.id === next.id ? next : x)) ?? null)}
/>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
function UserRow({ user, isSelf, onChange }: { user: AdminUser; isSelf: boolean; onChange: (u: AdminUser) => void }) {
const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
const [busy, setBusy] = useState(false);
const [delta, setDelta] = useState("");
async function toggleRole(role: Role, on: boolean) {
const roles = on ? [...user.roles, role] : user.roles.filter((r) => r !== role);
if (roles.length === 0) return setStatus({ ok: false, text: "Legalább egy szerepkör kell." });
setBusy(true);
setStatus(null);
try {
const res = await api<{ roles: Role[] }>(`/admin/users/${user.id}`, { method: "PATCH", body: { roles } });
onChange({ ...user, roles: res.roles });
} catch (e) {
setStatus({ ok: false, text: errorText(e) });
} finally {
setBusy(false);
}
}
async function grant(e: React.FormEvent) {
e.preventDefault();
const n = Number.parseInt(delta, 10);
if (!Number.isFinite(n) || n === 0) return setStatus({ ok: false, text: "Adj meg egy nem nulla egész számot." });
setBusy(true);
setStatus(null);
try {
await api(`/admin/users/${user.id}/credits`, { body: { delta: n, note: "admin" } });
onChange({ ...user, credits: user.credits + n });
setDelta("");
setStatus({ ok: true, text: n > 0 ? `+${n} kredit` : `${n} kredit` });
} catch (e) {
setStatus({ ok: false, text: errorText(e) });
} finally {
setBusy(false);
}
}
return (
<tr>
<td>
<div>{user.display_name || <span className="muted">(nincs név)</span>}</div>
<div className="muted" style={{ fontSize: 13 }}>
{user.email}
{isSelf && " · te"}
</div>
</td>
<td>
<div className="row" style={{ gap: 4 }}>
{EDITABLE_ROLES.map((role) => {
const on = user.roles.includes(role);
const locked = isSelf && role === "admin";
return (
<label key={role} className="check" style={{ minHeight: 28, fontSize: 13, marginRight: 8 }}>
<input
type="checkbox"
checked={on}
disabled={busy || locked}
onChange={(e) => toggleRole(role, e.target.checked)}
title={locked ? "A saját admin szerepköröd nem veheted el." : undefined}
/>
{ROLE_LABELS[role]}
</label>
);
})}
</div>
</td>
<td>
<form onSubmit={grant} className="row" style={{ gap: 6, flexWrap: "nowrap" }}>
<span className="num" style={{ minWidth: 28 }}>
{user.credits}
</span>
<label className="sr-only" htmlFor={`delta-${user.id}`}>
Kredit jóváírása
</label>
<input
id={`delta-${user.id}`}
className="inp"
style={{ width: 76, minHeight: 36 }}
inputMode="numeric"
placeholder="+10"
value={delta}
onChange={(e) => setDelta(e.target.value)}
/>
<button type="submit" className="btn btn-sm" disabled={busy || !delta}>
Jóváír
</button>
</form>
{status && (
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
{status.text}
</span>
)}
</td>
<td className="num">{user.charts}</td>
<td className="num">{formatDate(user.created_at)}</td>
<td className="num">{formatDate(user.last_login_at, true)}</td>
</tr>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { requireMe } from "@/lib/server";
import { AdminUsers } from "./AdminUsers";
export const metadata: Metadata = { title: "Admin" };
export default async function AdminPage() {
const me = await requireMe("/admin");
// Non-admins see the same 404 as for a missing page.
if (!me.user.roles.includes("admin")) notFound();
return (
<main className="page" style={{ maxWidth: 1180 }}>
<div className="page-head">
<h1>Felhasználók</h1>
<p className="muted">Szerepkörök és kreditek kezelése. A prémium és a VIP szerepkör nyitja meg a drágább elemző modelleket.</p>
</div>
<AdminUsers selfId={me.user.id} />
</main>
);
}
@@ -0,0 +1,23 @@
// Country list and place search for the birth data form (public data from
// the horoscope-api; only these two endpoints are passed through).
import type { NextRequest } from "next/server";
const HOROSCOPE_API_URL = (process.env.HOROSCOPE_API_URL ?? "http://localhost:8080").replace(/\/$/, "");
const ALLOWED = new Set(["countries", "places"]);
export async function GET(req: NextRequest, ctx: { params: Promise<{ kind: string }> }) {
const { kind } = await ctx.params;
if (!ALLOWED.has(kind)) return Response.json({ error: { code: "not_found", message: "not found" } }, { status: 404 });
try {
const res = await fetch(`${HOROSCOPE_API_URL}/v1/${kind}${req.nextUrl.search}`, {
// The country list rarely changes.
...(kind === "countries" ? { next: { revalidate: 86400 } } : { cache: "no-store" as const }),
});
return new Response(res.body, {
status: res.status,
headers: { "content-type": res.headers.get("content-type") ?? "application/json" },
});
} catch {
return Response.json({ error: { code: "unavailable", message: "A helykereső most nem érhető el." } }, { status: 502 });
}
}
@@ -0,0 +1,48 @@
// Forwards /api/v1/* to the backend, so the browser talks to one origin and
// the session cookie belongs to the frontend's host (no CORS needed).
import type { NextRequest } from "next/server";
import { BACKEND_URL } from "@/lib/server";
const REQUEST_HEADERS = ["accept", "accept-language", "authorization", "content-type", "cookie", "user-agent"];
// Hop-by-hop or re-computed by the runtime.
const SKIP_RESPONSE_HEADERS = new Set(["connection", "content-encoding", "content-length", "set-cookie", "transfer-encoding"]);
async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
const { path } = await ctx.params;
const target = `${BACKEND_URL}/v1/${path.map(encodeURIComponent).join("/")}${req.nextUrl.search}`;
const headers = new Headers();
for (const name of REQUEST_HEADERS) {
const value = req.headers.get(name);
if (value) headers.set(name, value);
}
const forwardedFor = req.headers.get("x-forwarded-for");
if (forwardedFor) headers.set("x-forwarded-for", forwardedFor);
let res: Response;
try {
res = await fetch(target, {
method: req.method,
headers,
body: req.method === "GET" || req.method === "HEAD" ? undefined : await req.arrayBuffer(),
redirect: "manual",
cache: "no-store",
});
} catch {
return Response.json({ error: { code: "backend_unavailable", message: "A szerver most nem érhető el." } }, { status: 502 });
}
const out = new Headers();
res.headers.forEach((value, name) => {
if (!SKIP_RESPONSE_HEADERS.has(name)) out.set(name, value);
});
for (const cookie of res.headers.getSetCookie()) out.append("set-cookie", cookie);
return new Response(res.body, { status: res.status, headers: out });
}
export const GET = forward;
export const POST = forward;
export const PATCH = forward;
export const PUT = forward;
export const DELETE = forward;
@@ -0,0 +1,63 @@
"use client";
import Script from "next/script";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { api, errorText } from "@/lib/api";
export function GoogleLogin({ clientId, target }: { clientId: string; target: string }) {
const router = useRouter();
const slot = useRef<HTMLDivElement>(null);
const [ready, setReady] = useState(false);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const onCredential = useCallback(
async (response: GoogleCredentialResponse) => {
setBusy(true);
setError(null);
try {
await api("/auth/google", { body: { id_token: response.credential } });
router.replace(target);
router.refresh();
} catch (e) {
setError(errorText(e));
setBusy(false);
}
},
[router, target],
);
useEffect(() => {
const google = window.google;
if (!ready || !google || !slot.current) return;
google.accounts.id.initialize({ client_id: clientId, callback: onCredential, ux_mode: "popup", itp_support: true });
google.accounts.id.renderButton(slot.current, {
theme: "filled_black",
size: "large",
text: "continue_with",
shape: "rectangular",
locale: "hu",
width: Math.min(400, slot.current.clientWidth || 400),
});
}, [ready, clientId, onCredential]);
return (
<div className="field">
<Script
src="https://accounts.google.com/gsi/client"
strategy="afterInteractive"
onReady={() => setReady(true)}
onError={() => setError("Nem sikerült betölteni a Google-belépést. Ellenőrizd a hálózatot vagy a reklámblokkolót.")}
/>
<div ref={slot} className="gsi-slot" aria-busy={busy} />
{busy && <p className="msg muted">Belépés…</p>}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</div>
);
}
@@ -0,0 +1,71 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { Logo } from "@/components/SiteHeader";
import { ZodiacWheel } from "@/components/ZodiacWheel";
import { BACKEND_URL, getMe } from "@/lib/server";
import type { PublicConfig } from "@/lib/types";
import { GoogleLogin } from "./GoogleLogin";
export const metadata: Metadata = { title: "Belépés" };
/** Only local paths, so the login cannot redirect to another site. */
function safeTarget(value: string | string[] | undefined): string {
const v = Array.isArray(value) ? value[0] : value;
return v && v.startsWith("/") && !v.startsWith("//") ? v : "/profil";
}
async function loadConfig(): Promise<PublicConfig | null> {
try {
const res = await fetch(`${BACKEND_URL}/v1/config`, { cache: "no-store" });
return res.ok ? ((await res.json()) as PublicConfig) : null;
} catch {
return null;
}
}
export default async function LoginPage({ searchParams }: { searchParams: Promise<Record<string, string | string[]>> }) {
const target = safeTarget((await searchParams).vissza);
if (await getMe()) redirect(target);
const config = await loadConfig();
const clientId = config?.google_login.enabled ? config.google_login.client_id : null;
return (
<div className="auth">
<aside className="auth-aside">
<Logo />
<ZodiacWheel className="wheel" />
<div className="row" style={{ flexDirection: "column", alignItems: "flex-start", gap: 10, maxWidth: 460 }}>
<p className="tagline">Ahol a csillagok összekötnek.</p>
<p className="muted" style={{ fontSize: 16 }}>
Születési képlet, szinasztria és közösség – egy helyen.
</p>
</div>
</aside>
<main className="auth-main">
<div className="auth-box">
<div className="page-head">
<h1 style={{ fontSize: 44 }}>Belépés</h1>
<p className="muted">Lépj be a Google-fiókoddal. Ha még nincs fiókod, az első belépéskor létrejön.</p>
</div>
{config === null ? (
<p className="msg msg-error" role="alert">
A szerver most nem érhető el. Próbáld újra egy kicsit később.
</p>
) : clientId ? (
<GoogleLogin clientId={clientId} target={target} />
) : (
<p className="msg msg-error" role="alert">
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
</p>
)}
<p className="hint">
A belépéssel elfogadod, hogy a születési adataidat a képleted kiszámításához tároljuk. Bármikor törölheted
őket a profilodban.
</p>
</div>
</main>
</div>
);
}
+158
View File
@@ -0,0 +1,158 @@
/* Sorsfonalak – night sky with gold accents (from the design canvas). */
:root {
--bg: #0d1220;
--panel: #111729;
--panel-2: #0f1426;
--line: #1f2740;
--line-2: #2c3654;
--ink: #ece6d8;
--ink-2: #c9cfdc;
--muted: #a3abc0;
--gold: #d9b46a;
--gold-hover: #e6c482;
--gold-ink: #141a2c;
--danger: #f2a0a0;
--ok: #9fd8b0;
--radius: 10px;
--font-display: var(--font-cormorant), "Cormorant Garamond", Georgia, serif;
--font-body: var(--font-inter), Inter, system-ui, sans-serif;
--font-symbols: "Noto Sans Symbols", "Segoe UI Symbol", "DejaVu Sans", sans-serif;
color-scheme: dark;
}
* { box-sizing: border-box; }
html, body { margin: 0; }
body {
min-height: 100vh;
background: var(--bg);
color: var(--ink);
font: 400 15px/1.55 var(--font-body);
}
a { color: var(--gold); }
a:hover { color: var(--gold-hover); }
:focus-visible { outline: 2px solid var(--gold); outline-offset: 2px; }
h1, h2, h3 { font-family: var(--font-display); font-weight: 600; line-height: 1.1; margin: 0; }
h1 { font-size: 40px; }
h2 { font-size: 28px; }
h3 { font-size: 20px; }
p { margin: 0; }
.muted { color: var(--muted); }
.sym { font-family: var(--font-symbols); }
/* Header */
.site-header {
position: sticky; top: 0; z-index: 10;
display: flex; align-items: center; gap: 24px; flex-wrap: wrap;
padding: 12px 24px; background: rgba(13, 18, 32, 0.94);
border-bottom: 1px solid var(--line); backdrop-filter: blur(6px);
}
.logo { font-family: var(--font-display); font-size: 28px; font-weight: 600; color: var(--ink); text-decoration: none; letter-spacing: 0.3px; }
.logo span { color: var(--gold); }
.logo:hover { color: var(--ink); }
.nav { display: flex; gap: 4px; flex: 1; }
.nav a { color: var(--ink-2); text-decoration: none; padding: 10px 12px; border-radius: 8px; min-height: 44px; display: inline-flex; align-items: center; }
.nav a:hover, .nav a[aria-current="page"] { color: var(--gold); background: rgba(217, 180, 106, 0.08); }
.who { display: flex; align-items: center; gap: 12px; color: var(--muted); font-size: 14px; }
/* Layout */
.page { max-width: 960px; margin: 0 auto; padding: 32px 16px 64px; display: flex; flex-direction: column; gap: 24px; }
.page-head { display: flex; flex-direction: column; gap: 6px; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 24px; display: flex; flex-direction: column; gap: 18px; }
.card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; }
.facts { display: grid; grid-template-columns: max-content 1fr; gap: 8px 20px; margin: 0; }
.facts dt { color: var(--muted); }
.facts dd { margin: 0; }
/* Forms */
.field { display: flex; flex-direction: column; gap: 8px; }
.field label, .label { font-size: 14px; font-weight: 500; }
.hint { font-size: 13px; color: var(--muted); }
.inp {
width: 100%; min-height: 48px; padding: 0 14px; border-radius: var(--radius);
border: 1px solid var(--line-2); background: var(--panel-2); color: var(--ink);
font: 400 15px var(--font-body);
}
select.inp { padding-right: 32px; }
.inp::placeholder { color: #8a93ab; }
.inp:focus { outline: none; border-color: var(--gold); box-shadow: 0 0 0 3px rgba(217, 180, 106, 0.25); }
.inp:disabled { opacity: 0.55; }
.check { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--ink-2); min-height: 32px; cursor: pointer; }
.check input { width: 18px; height: 18px; accent-color: var(--gold); margin: 0; }
.row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
.form-actions { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
.btn {
min-height: 44px; padding: 0 18px; border-radius: var(--radius); border: 1px solid var(--line-2);
background: transparent; color: var(--ink); font: 500 15px var(--font-body); cursor: pointer;
display: inline-flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none;
}
.btn:hover { border-color: #5a6790; background: rgba(255, 255, 255, 0.03); color: var(--ink); }
.btn:disabled { opacity: 0.55; cursor: default; }
.btn-primary { background: var(--gold); border-color: var(--gold); color: var(--gold-ink); font-weight: 600; }
.btn-primary:hover { background: var(--gold-hover); border-color: var(--gold-hover); color: var(--gold-ink); }
.btn-ghost { border-color: transparent; color: var(--muted); padding: 0 12px; }
.btn-ghost:hover { color: var(--ink); border-color: transparent; }
.btn-sm { min-height: 36px; padding: 0 12px; font-size: 14px; }
.msg { font-size: 14px; }
.msg-error { color: var(--danger); }
.msg-ok { color: var(--ok); }
.badge {
display: inline-flex; align-items: center; min-height: 24px; padding: 0 10px; border-radius: 999px;
border: 1px solid var(--line-2); font-size: 12px; color: var(--ink-2); white-space: nowrap;
}
.badge-gold { border-color: rgba(217, 180, 106, 0.5); color: var(--gold); }
/* Place search */
.combo { position: relative; }
.combo-list {
position: absolute; z-index: 5; left: 0; right: 0; top: calc(100% + 4px); margin: 0; padding: 4px;
list-style: none; background: var(--panel-2); border: 1px solid var(--line-2); border-radius: var(--radius);
max-height: 280px; overflow-y: auto;
}
.combo-list button {
width: 100%; text-align: left; background: transparent; border: 0; color: var(--ink); cursor: pointer;
padding: 10px 12px; border-radius: 8px; font: inherit; min-height: 44px;
}
.combo-list button:hover, .combo-list button[aria-selected="true"] { background: rgba(217, 180, 106, 0.1); }
.combo-list small { color: var(--muted); }
/* Tables */
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid var(--line); vertical-align: middle; }
th { color: var(--muted); font-weight: 500; font-size: 13px; }
td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.retro { color: var(--gold); font-size: 12px; margin-left: 4px; }
/* Big three */
.big3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
.big3 > div { background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; display: flex; flex-direction: column; gap: 4px; }
.big3 .glyph { font-size: 26px; color: var(--gold); line-height: 1; }
.big3 strong { font-family: var(--font-display); font-size: 24px; font-weight: 600; }
/* Login */
.auth { min-height: 100vh; display: flex; flex-wrap: wrap; }
.auth-aside {
flex: 1 1 480px; min-height: 320px; background: var(--panel); border-right: 1px solid var(--line);
padding: 40px 48px; display: flex; flex-direction: column; justify-content: space-between; gap: 32px;
}
.auth-main { flex: 1 1 480px; display: flex; align-items: center; justify-content: center; padding: 48px 24px; }
.auth-box { width: 100%; max-width: 420px; display: flex; flex-direction: column; gap: 28px; }
.wheel { width: min(380px, 80%); aspect-ratio: 1; margin: 0 auto; }
.tagline { font-family: var(--font-display); font-size: 36px; font-weight: 600; line-height: 1.1; }
.gsi-slot { min-height: 44px; display: flex; justify-content: center; }
@media (max-width: 640px) {
h1 { font-size: 32px; }
.site-header { padding: 10px 16px; gap: 12px; }
.nav { order: 3; flex-basis: 100%; }
.card { padding: 18px; }
.auth-aside { padding: 28px 20px; min-height: 0; }
.wheel { width: 60%; }
.big3 { grid-template-columns: 1fr; }
}
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
@@ -0,0 +1,4 @@
// Container health check.
export function GET() {
return Response.json({ status: "ok" });
}
+31
View File
@@ -0,0 +1,31 @@
import type { Metadata } from "next";
import { Cormorant_Garamond, Inter } from "next/font/google";
import { SiteHeader } from "@/components/SiteHeader";
import { getMe } from "@/lib/server";
import "./globals.css";
const cormorant = Cormorant_Garamond({
subsets: ["latin", "latin-ext"],
weight: ["500", "600"],
variable: "--font-cormorant",
});
const inter = Inter({ subsets: ["latin", "latin-ext"], variable: "--font-inter" });
export const metadata: Metadata = {
title: { default: "Sorsfonalak", template: "%s · Sorsfonalak" },
description: "Születési képlet, szinasztria és közösség – egy helyen.",
};
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const me = await getMe();
return (
<html lang="hu" className={`${cormorant.variable} ${inter.variable}`}>
<body>
{me && <SiteHeader me={me} />}
{children}
</body>
</html>
);
}
+13
View File
@@ -0,0 +1,13 @@
import Link from "next/link";
export default function NotFound() {
return (
<main className="page" style={{ alignItems: "flex-start" }}>
<h1>Nincs ilyen oldal</h1>
<p className="muted">A keresett oldal nem létezik, vagy nincs hozzá jogosultságod.</p>
<Link href="/" className="btn">
Vissza a kezdőlapra
</Link>
</main>
);
}
+8
View File
@@ -0,0 +1,8 @@
import { redirect } from "next/navigation";
import { getMe } from "@/lib/server";
// No home page yet: logged-in users go to their profile, others to login.
export default async function Home() {
redirect((await getMe()) ? "/profil" : "/belepes");
}
@@ -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>
);
}