From 8d9c50cb029655b60de735d5ff085fc8870821d0 Mon Sep 17 00:00:00 2001 From: feco Date: Mon, 23 Nov 2026 09:04:51 +0000 Subject: [PATCH 1/4] Admin: paged user list with a dialog; creators manage famous people - The user list pages (25 per page, with the total from the backend); roles, packages and single units are set in a dialog instead of in the row. - Creators may add, edit and publish famous people and rewrite their portraits (own regenerate route); they delete only their own. The rest of the admin stays closed to them; the header links them to their page. - No free-horoscope offer on the star sign and famous people lists. - .table-wrap is a containing block, so .sr-only text inside it no longer widens the page on phones. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- services/backend/src/auth.rs | 22 + services/backend/src/routes/admin.rs | 10 +- services/backend/src/routes/analyses.rs | 7 +- services/backend/src/routes/celebrities.rs | 43 +- services/backend/src/routes/mod.rs | 1 + services/backend/src/tests.rs | 62 +++ .../frontend/src/app/admin/AdminUsers.tsx | 445 ++++++++++++------ .../hires-emberek/[id]/CelebrityEditor.tsx | 22 +- .../src/app/admin/hires-emberek/[id]/page.tsx | 8 +- .../src/app/admin/hires-emberek/page.tsx | 6 +- .../src/app/csillagjegyek/[jegy]/page.tsx | 3 - .../frontend/src/app/csillagjegyek/page.tsx | 11 - services/frontend/src/app/globals.css | 33 +- .../frontend/src/app/hires-emberek/page.tsx | 11 - services/frontend/src/components/AdminNav.tsx | 16 +- services/frontend/src/components/Modal.tsx | 55 +++ .../frontend/src/components/SiteHeader.tsx | 1 + services/frontend/src/lib/types.ts | 2 + 18 files changed, 541 insertions(+), 217 deletions(-) create mode 100644 services/frontend/src/components/Modal.tsx diff --git a/services/backend/src/auth.rs b/services/backend/src/auth.rs index 7b68c2f..e9e6d0b 100644 --- a/services/backend/src/auth.rs +++ b/services/backend/src/auth.rs @@ -85,6 +85,28 @@ impl FromRequestParts> for AdminUser { } } +/// Guard: may manage the famous people (the admin or the creator role). +pub struct CelebrityEditor(pub AuthUser); + +impl CelebrityEditor { + pub fn is_admin(&self) -> bool { + self.0.user.has_role(Role::Admin) + } +} + +impl FromRequestParts> for CelebrityEditor { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, state: &Arc) -> Result { + let user = AuthUser::from_request_parts(parts, state).await?; + if user.user.has_role(Role::Creator) { + return Ok(CelebrityEditor(user)); + } + user.require(Role::Admin)?; + Ok(CelebrityEditor(user)) + } +} + pub fn user_agent(parts_headers: &axum::http::HeaderMap) -> Option { parts_headers.get(USER_AGENT).and_then(|v| v.to_str().ok()).map(|s| s.chars().take(300).collect()) } diff --git a/services/backend/src/routes/admin.rs b/services/backend/src/routes/admin.rs index 47660e6..950439f 100644 --- a/services/backend/src/routes/admin.rs +++ b/services/backend/src/routes/admin.rs @@ -60,11 +60,17 @@ pub async fn list_users( WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1 \ ORDER BY u.created_at DESC LIMIT $2 OFFSET $3", ) - .bind(pattern) + .bind(&pattern) .bind(limit) .bind(offset) .fetch_all(&state.db) .await?; + let total: i64 = sqlx::query_scalar( + "SELECT count(*) FROM users u WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1", + ) + .bind(&pattern) + .fetch_one(&state.db) + .await?; let users: Vec = rows .into_iter() .map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, forecast, question, tarot)| { @@ -78,7 +84,7 @@ pub async fn list_users( }) }) .collect(); - Ok(Json(json!({ "users": users, "limit": limit, "offset": offset }))) + Ok(Json(json!({ "users": users, "total": total, "limit": limit, "offset": offset }))) } #[derive(Deserialize)] diff --git a/services/backend/src/routes/analyses.rs b/services/backend/src/routes/analyses.rs index bbb7001..bf3cff7 100644 --- a/services/backend/src/routes/analyses.rs +++ b/services/backend/src/routes/analyses.rs @@ -410,6 +410,11 @@ pub async fn regenerate( _admin: crate::auth::AdminUser, WithRejection(Path(id), _): IdPath, ) -> ApiResult> { + Ok(Json(regenerate_in_place(&state, id).await?)) +} + +/// See [`regenerate`]; also used for the famous people's analyses. +pub(super) async fn regenerate_in_place(state: &AppState, id: Uuid) -> Result { let row = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?; if row.status == "pending" || row.status == "running" { return Err(ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül.")); @@ -446,5 +451,5 @@ pub async fn regenerate( sqlx::query("SELECT pg_notify('analyses', '')").execute(&mut *tx).await?; tx.commit().await?; tracing::info!(%id, kind, "analysis regenerated"); - Ok(Json(row.view())) + Ok(row.view()) } diff --git a/services/backend/src/routes/celebrities.rs b/services/backend/src/routes/celebrities.rs index 34c8960..082cc7e 100644 --- a/services/backend/src/routes/celebrities.rs +++ b/services/backend/src/routes/celebrities.rs @@ -23,7 +23,7 @@ use super::analyses::{ANALYSIS_COLUMNS, AnalysisRow, Target, queue}; use super::charts::{CHART_COLUMNS, ChartRow, calculate, find_chart}; use super::{Body, IdPath, St, double_option}; use crate::AppState; -use crate::auth::{AdminUser, AuthUser}; +use crate::auth::{AuthUser, CelebrityEditor}; use crate::error::{ApiError, ApiResult}; use crate::views::{chart_highlights, public_chart, rfc3339, rfc3339_opt}; @@ -43,12 +43,13 @@ struct CelebrityRow { focus_x: f32, focus_y: f32, published_at: Option, + created_by: Option, created_at: OffsetDateTime, updated_at: OffsetDateTime, } const COLUMNS: &str = "id, chart_id, name, subtitle, slug, photo_key, photo_width, photo_height, focus_x, focus_y, \ - published_at, created_at, updated_at"; + published_at, created_by, created_at, updated_at"; impl CelebrityRow { fn photo(&self) -> Value { @@ -161,6 +162,7 @@ async fn admin_view(db: &PgPool, row: &CelebrityRow) -> Result let chart = find_chart(db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?; let analysis = latest_analysis(db, row.chart_id).await?; let mut view = row.base(); + view["created_by"] = json!(row.created_by); view["birth_data"] = chart.birth_data.clone(); view["birth"] = public_chart(&chart.result, true)["birth"].clone(); view["highlights"] = chart_highlights(&chart.result); @@ -174,7 +176,7 @@ async fn admin_view(db: &PgPool, row: &CelebrityRow) -> Result type ListRow = (Uuid, Uuid, String, Option, String, Option, Option, Value, Option); -pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> { +pub async fn list(State(state): St, _editor: CelebrityEditor) -> ApiResult> { let rows: Vec = sqlx::query_as( "SELECT c.id, c.chart_id, c.name, c.subtitle, c.slug, c.published_at, c.photo_key, ch.result, \ (SELECT a.status FROM analyses a WHERE a.chart_id = c.chart_id AND a.kind = 'celebrity' \ @@ -210,7 +212,7 @@ pub struct CreateCelebrity { /// Adds a famous person: calculates the chart and queues the analysis. pub async fn create( State(state): St, - AdminUser(admin): AdminUser, + CelebrityEditor(admin): CelebrityEditor, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { let name = clean_name(&req.name)?; @@ -249,7 +251,7 @@ pub async fn create( pub async fn get_one( State(state): St, - _admin: AdminUser, + _editor: CelebrityEditor, WithRejection(Path(id), _): IdPath, ) -> ApiResult> { let row = find(&state.db, id).await?; @@ -273,7 +275,7 @@ pub struct UpdateCelebrity { pub async fn update( State(state): St, - AdminUser(admin): AdminUser, + CelebrityEditor(admin): CelebrityEditor, WithRejection(Path(id), _): IdPath, WithRejection(Json(req), _): Body, ) -> ApiResult> { @@ -353,10 +355,10 @@ pub async fn update( } /// Queues the analysis again when there is none or the last one failed -/// (rewriting a finished one: `POST /v1/admin/analyses/{id}/regenerate`). +/// (rewriting a finished one: [`regenerate_analysis`]). pub async fn request_analysis( State(state): St, - AdminUser(admin): AdminUser, + CelebrityEditor(admin): CelebrityEditor, WithRejection(Path(id), _): IdPath, ) -> ApiResult> { let row = find(&state.db, id).await?; @@ -365,6 +367,17 @@ pub async fn request_analysis( Ok(Json(admin_view(&state.db, &row).await?)) } +/// Writes the finished (or failed) analysis again with the current prompt. +pub async fn regenerate_analysis( + State(state): St, + _editor: CelebrityEditor, + WithRejection(Path(id), _): IdPath, +) -> ApiResult> { + let row = find(&state.db, id).await?; + let analysis = latest_analysis(&state.db, row.chart_id).await?.ok_or(ApiError::NotFound("analysis"))?; + Ok(Json(super::analyses::regenerate_in_place(&state, analysis.id).await?)) +} + fn storage(state: &AppState) -> Result<&crate::storage::Storage, ApiError> { state .storage @@ -385,7 +398,7 @@ async fn delete_photo(state: &AppState, key: &str) { /// WebP); it replaces the previous one. The face point is reset. pub async fn upload_photo( State(state): St, - AdminUser(admin): AdminUser, + CelebrityEditor(admin): CelebrityEditor, WithRejection(Path(id), _): IdPath, body: Bytes, ) -> ApiResult> { @@ -422,7 +435,7 @@ pub async fn upload_photo( pub async fn remove_photo( State(state): St, - _admin: AdminUser, + _editor: CelebrityEditor, WithRejection(Path(id), _): IdPath, ) -> ApiResult> { let row = find(&state.db, id).await?; @@ -442,10 +455,14 @@ pub async fn remove_photo( /// Deletes the famous person with their chart, analysis and photo. pub async fn remove( State(state): St, - AdminUser(admin): AdminUser, + editor: CelebrityEditor, WithRejection(Path(id), _): IdPath, ) -> ApiResult { let row = find(&state.db, id).await?; + if !editor.is_admin() && row.created_by != Some(editor.0.id()) { + return Err(ApiError::Forbidden("only an admin may delete someone else's famous person".into())); + } + let admin = editor.0; sqlx::query("DELETE FROM charts WHERE id = $1").bind(row.chart_id).execute(&state.db).await?; if let Some(key) = &row.photo_key { delete_photo(&state, key).await; @@ -474,7 +491,7 @@ pub async fn public_list(State(state): St) -> ApiResult> { Ok(Json(json!({ "celebrities": items }))) } -/// Public: one famous person's page (a draft only for admins). +/// Public: one famous person's page (a draft only for admins and creators). pub async fn public_view( State(state): St, auth: Result, @@ -485,7 +502,7 @@ pub async fn public_view( .fetch_optional(&state.db) .await? .ok_or(ApiError::NotFound("celebrity"))?; - let admin = auth.is_ok_and(|a| a.user.has_role(db::Role::Admin)); + let admin = auth.is_ok_and(|a| a.user.has_role(db::Role::Admin) || a.user.has_role(db::Role::Creator)); if row.published_at.is_none() && !admin { return Err(ApiError::NotFound("celebrity")); } diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 0e43b4c..8ee82fb 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -160,6 +160,7 @@ pub fn router(state: Arc) -> Router { get(celebrities::get_one).patch(celebrities::update).delete(celebrities::remove), ) .route("/v1/admin/celebrities/{id}/analysis", post(celebrities::request_analysis)) + .route("/v1/admin/celebrities/{id}/analysis/regenerate", post(celebrities::regenerate_analysis)) .route( "/v1/admin/celebrities/{id}/photo", axum::routing::put(celebrities::upload_photo) diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 5d822fe..375ba4a 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -3099,3 +3099,65 @@ async fn admins_publish_famous_people_with_a_photo(pool: PgPool) { assert_eq!(left["celebrities"].as_array().unwrap().len(), 1); assert_eq!(left["celebrities"][0]["id"].as_str(), Some(second.as_str())); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn creators_add_famous_people_but_nothing_else_of_the_admin(pool: PgPool) { + let app = TestApp::new(pool.clone()).await; + let admin = app.register("admin@example.com", "Admin").await; + let writer = app.register("szerzo@example.com", "Szerző").await; + sqlx::query("UPDATE users SET roles = '{user,creator}' WHERE email = 'szerzo@example.com'") + .execute(&pool) + .await + .unwrap(); + let birth = json!({"date": "1926-06-01", "time": "09:30", "country": "HU", "place": "Szeged"}); + + // the famous people: add, edit, see the draft, rewrite the analysis, delete their own + let r = app.post("/v1/admin/celebrities", Some(&writer), json!({"name": "Teszt Elek", "birth": birth})).await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + let id = r.body["id"].as_str().unwrap().to_string(); + let analysis_id = r.body["analysis"]["id"].as_str().unwrap().to_string(); + assert!(r.body["created_by"].is_string()); + let r = app.call("PATCH", &format!("/v1/admin/celebrities/{id}"), Some(&writer), Some(json!({"subtitle": "író"}))).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(app.get("/v1/public/celebrities/teszt-elek", Some(&writer)).await.status, StatusCode::OK); + let regenerate = format!("/v1/admin/celebrities/{id}/analysis/regenerate"); + let r = app.post(®enerate, Some(&writer), json!({})).await; + assert_eq!(r.status, StatusCode::CONFLICT, "still pending: {}", r.body); + sqlx::query("UPDATE analyses SET status = 'done', content = '{}', completed_at = now() WHERE id = $1::uuid") + .bind(&analysis_id) + .execute(&pool) + .await + .unwrap(); + let r = app.post(®enerate, Some(&writer), json!({})).await; + assert_eq!((r.status, r.body["status"].as_str()), (StatusCode::OK, Some("pending")), "{}", r.body); + assert_eq!(r.body["id"].as_str(), Some(analysis_id.as_str())); + + // someone else's famous person: edited, but only an admin deletes it + let r = app.post("/v1/admin/celebrities", Some(&admin), json!({"name": "Admin Ádám", "birth": birth})).await; + let others = r.body["id"].as_str().unwrap().to_string(); + let r = app.call("DELETE", &format!("/v1/admin/celebrities/{others}"), Some(&writer), None).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); + let r = app.call("DELETE", &format!("/v1/admin/celebrities/{id}"), Some(&writer), None).await; + assert_eq!(r.status, StatusCode::NO_CONTENT); + + // the rest of the admin stays closed + for uri in ["/v1/admin/users", "/v1/admin/prompts", "/v1/admin/errors"] { + assert_eq!(app.get(uri, Some(&writer)).await.status, StatusCode::FORBIDDEN, "{uri}"); + } + let r = app.post(&format!("/v1/admin/analyses/{analysis_id}/regenerate"), Some(&writer), json!({})).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn the_user_list_pages_with_a_total(pool: PgPool) { + let app = TestApp::new(pool.clone()).await; + let admin = app.register("admin@example.com", "Admin").await; + for i in 0..4 { + app.register(&format!("lap{i}@example.com"), "Lapozó").await; + } + let r = app.get("/v1/admin/users?limit=2&offset=2", Some(&admin)).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!((r.body["total"].as_i64(), r.body["users"].as_array().unwrap().len()), (Some(5), 2)); + let r = app.get("/v1/admin/users?q=lap&limit=3&offset=3", Some(&admin)).await; + assert_eq!((r.body["total"].as_i64(), r.body["users"].as_array().unwrap().len()), (Some(4), 1)); +} diff --git a/services/frontend/src/app/admin/AdminUsers.tsx b/services/frontend/src/app/admin/AdminUsers.tsx index 3ab6d8b..787a6b3 100644 --- a/services/frontend/src/app/admin/AdminUsers.tsx +++ b/services/frontend/src/app/admin/AdminUsers.tsx @@ -2,11 +2,13 @@ import { useCallback, useEffect, useState } from "react"; +import { Modal } from "@/components/Modal"; import { huf, usePackages } from "@/components/PackageCards"; import { api, errorText } from "@/lib/api"; import { ROLE_LABELS, formatDate } from "@/lib/astro"; import type { AdminUser, Package, Role } from "@/lib/types"; +const PAGE_SIZE = 25; const EDITABLE_ROLES: Role[] = ["user", "creator", "admin"]; type UnitKind = "natal" | "synastry" | "forecast" | "question" | "tarot"; @@ -18,16 +20,22 @@ const UNITS: { value: UnitKind; label: string }[] = [ { value: "tarot", label: "kártyajóslás" }, ]; +type Status = { ok: boolean; text: string } | null; + export function AdminUsers({ selfId }: { selfId: string }) { const [query, setQuery] = useState(""); - const [users, setUsers] = useState(null); + const [page, setPage] = useState(0); + const [data, setData] = useState<{ users: AdminUser[]; total: number } | null>(null); const [error, setError] = useState(null); + const [editing, setEditing] = useState(null); const packages = usePackages() ?? []; - const load = useCallback(async (q: string) => { + const load = useCallback(async (q: string, p: number) => { try { - const data = await api<{ users: AdminUser[] }>(`/admin/users?q=${encodeURIComponent(q)}`); - setUsers(data.users); + const res = await api<{ users: AdminUser[]; total: number }>( + `/admin/users?q=${encodeURIComponent(q)}&limit=${PAGE_SIZE}&offset=${p * PAGE_SIZE}`, + ); + setData(res); setError(null); } catch (e) { setError(errorText(e)); @@ -35,22 +43,39 @@ export function AdminUsers({ selfId }: { selfId: string }) { }, []); useEffect(() => { - const t = setTimeout(() => load(query.trim()), 250); + const t = setTimeout(() => load(query.trim(), page), 250); return () => clearTimeout(t); - }, [query, load]); + }, [query, page, load]); + + const users = data?.users ?? null; + const total = data?.total ?? 0; + const pages = Math.max(1, Math.ceil(total / PAGE_SIZE)); + const selected = users?.find((u) => u.id === editing) ?? null; + const update = (next: AdminUser) => + setData((d) => d && { ...d, users: d.users.map((x) => (x.id === next.id ? next : x)) }); return (
-
- - setQuery(e.target.value)} - placeholder="pl. anna@" - /> +
+
+ + { + setQuery(e.target.value); + setPage(0); + }} + placeholder="pl. anna@" + /> +
+ {data && ( + + {total} felhasználó + + )}
{error && (

@@ -63,53 +88,153 @@ export function AdminUsers({ selfId }: { selfId: string }) {

Nincs találat.

) : (
- +
- - - + + + {users.map((u) => ( - setUsers((list) => list?.map((x) => (x.id === next.id ? next : x)) ?? null)} - /> + + + + + + + + + ))}
FelhasználóSzerepkörökRészletes elemzésekCsomagSzerepkörHátralévő elemzések Képletek Regisztrált Utoljára belépett + Műveletek +
+
{u.display_name || (nincs név)}
+
+ {u.email} + {u.id === selfId && " · te"} +
+
+ + + + {u.charts}{formatDate(u.created_at)}{formatDate(u.last_login_at, true)} + +
)} + {data && total > PAGE_SIZE && ( + + )} + {selected && ( + setEditing(null)} + /> + )}
); } -function UserRow({ +function RoleBadges({ roles }: { roles: Role[] }) { + const shown = roles.filter((r) => r !== "user"); + if (shown.length === 0) return Felhasználó; + return ( +
+ {shown.map((r) => ( + + {ROLE_LABELS[r] ?? r} + + ))} +
+ ); +} + +/** The remaining units in one line, only the ones the user has. */ +function Balances({ user }: { user: AdminUser }) { + const left = UNITS.map((u) => ({ ...u, n: user.analyses_left[u.value] ?? 0 })).filter((u) => u.n !== 0); + if (left.length === 0) return –; + return ( + + {left.map((u, i) => ( + + {i > 0 && " · "} + {u.label} {u.n} + + ))} + + ); +} + +/** Roles, a package and single units for one user. */ +function UserDialog({ user, isSelf, packages, onChange, + onClose, }: { user: AdminUser; isSelf: boolean; packages: Package[]; onChange: (u: AdminUser) => void; + onClose: () => void; }) { - const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null); - const [busy, setBusy] = useState(false); - const [delta, setDelta] = useState(""); - const [unit, setUnit] = useState("natal"); + return ( + + {user.email} + {isSelf && " · te"} · regisztrált {formatDate(user.created_at)} + + } + onClose={onClose} + > + + + +
+ +
+
+ ); +} - async function toggleRole(role: Role, on: boolean) { +function RolesEditor({ user, isSelf, onChange }: { user: AdminUser; isSelf: boolean; onChange: (u: AdminUser) => void }) { + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState(null); + + async function toggle(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); @@ -117,27 +242,7 @@ function UserRow({ 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 { - const res = await api<{ analyses_left: AdminUser["analyses_left"] }>(`/admin/users/${user.id}/credits`, { - body: { unit, delta: n, note: "admin" }, - }); - onChange({ ...user, analyses_left: res.analyses_left }); - setDelta(""); - const label = UNITS.find((u) => u.value === unit)?.label; - setStatus({ ok: true, text: `${n > 0 ? "+" : ""}${n} ${label}` }); + setStatus({ ok: true, text: "Mentve." }); } catch (e) { setStatus({ ok: false, text: errorText(e) }); } finally { @@ -146,26 +251,19 @@ function UserRow({ } return ( - - -
{user.display_name || (nincs név)}
-
- {user.email} - {isSelf && " · te"} -
- - -
+
+
+ Szerepkörök +
{EDITABLE_ROLES.map((role) => { - const on = user.roles.includes(role); const locked = isSelf && role === "admin"; return ( -
- - -
- - képlet {user.analyses_left.natal} -
- szinasztria {user.analyses_left.synastry} -
- előrejelzés {user.analyses_left.forecast ?? 0} -
- kérdés {user.analyses_left.question ?? 0} -
- jóslás {user.analyses_left.tarot ?? 0} -
- - - - setDelta(e.target.value)} - /> - -
+

A szerző híres embereket vihet fel és szerkeszthet.

{status && ( {status.text} )} - - - - - {user.charts} - {formatDate(user.created_at)} - {formatDate(user.last_login_at, true)} - +
+
); } @@ -247,7 +294,7 @@ function PackageGrant({ }) { const [id, setId] = useState(""); const [busy, setBusy] = useState(false); - const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null); + const [status, setStatus] = useState(null); async function give(e: React.FormEvent) { e.preventDefault(); @@ -256,12 +303,11 @@ function PackageGrant({ setBusy(true); setStatus(null); try { - const res = await api<{ analyses_left: AdminUser["analyses_left"] }>( - `/admin/users/${user.id}/packages`, - { body: { package: pkg.id, note: "admin ajándék" } }, - ); + const res = await api<{ analyses_left: AdminUser["analyses_left"] }>(`/admin/users/${user.id}/packages`, { + body: { package: pkg.id, note: "admin ajándék" }, + }); onChange({ ...user, analyses_left: res.analyses_left }); - setStatus({ ok: true, text: `${pkg.name} kiosztva` }); + setStatus({ ok: true, text: `${pkg.name} kiosztva.` }); setId(""); } catch (err) { setStatus({ ok: false, text: errorText(err) }); @@ -271,35 +317,122 @@ function PackageGrant({ } return ( -
-
- - setId(e.target.value)} + disabled={busy || packages.length === 0} + > + + {packages.map((p) => ( + + ))} + + +
+ {status && ( + + {status.text} + + )} + +
+ ); +} + +/** Adds (or takes away) single analyses of one kind. */ +function CreditGrant({ user, onChange }: { user: AdminUser; onChange: (u: AdminUser) => void }) { + const [delta, setDelta] = useState(""); + const [unit, setUnit] = useState("natal"); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState(null); + + 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 { + const res = await api<{ analyses_left: AdminUser["analyses_left"] }>(`/admin/users/${user.id}/credits`, { + body: { unit, delta: n, note: "admin" }, + }); + onChange({ ...user, analyses_left: res.analyses_left }); + setDelta(""); + const label = UNITS.find((u) => u.value === unit)?.label; + setStatus({ ok: true, text: `${n > 0 ? "+" : ""}${n} ${label}.` }); + } catch (err) { + setStatus({ ok: false, text: errorText(err) }); + } finally { + setBusy(false); + } + } + + return ( +
+
+ Részletes elemzések +
+ {UNITS.map((u) => ( +
+
{u.label}
+
{user.analyses_left[u.value] ?? 0}
+
))} - - -
- {status && ( - - {status.text} - - )} + +
+ + + + setDelta(e.target.value)} + /> + +
+

Negatív számmal el is vehetsz (pl. -1).

+ {status && ( + + {status.text} + + )} + ); } diff --git a/services/frontend/src/app/admin/hires-emberek/[id]/CelebrityEditor.tsx b/services/frontend/src/app/admin/hires-emberek/[id]/CelebrityEditor.tsx index cc9f237..ace4e5c 100644 --- a/services/frontend/src/app/admin/hires-emberek/[id]/CelebrityEditor.tsx +++ b/services/frontend/src/app/admin/hires-emberek/[id]/CelebrityEditor.tsx @@ -17,7 +17,7 @@ import { ANALYSIS_STATUS, SubtitleField } from "../AdminCelebrities"; const POLL_MS = 10_000; /** Everything about one famous person: photo and face point, texts, publishing, portrait, birth data. */ -export function CelebrityEditor({ id }: { id: string }) { +export function CelebrityEditor({ id, selfId, isAdmin }: { id: string; selfId: string; isAdmin: boolean }) { const router = useRouter(); const [c, setC] = useState(null); const [error, setError] = useState(null); @@ -130,12 +130,18 @@ export function CelebrityEditor({ id }: { id: string }) {

Törlés

-

A képlet, a portré és a fotó is törlődik; a nyilvános oldal megszűnik.

-
- -
+ {isAdmin || c.created_by === selfId ? ( + <> +

A képlet, a portré és a fotó is törlődik; a nyilvános oldal megszűnik.

+
+ +
+ + ) : ( +

Akit más vitt fel, azt csak admin törölheti.

+ )}
); @@ -382,7 +388,7 @@ function AnalysisSection({ - url={`/admin/analyses/${a.id}/regenerate`} onStarted={onAnalysis} /> + url={`${url}/analysis/regenerate`} onStarted={onAnalysis} /> )} diff --git a/services/frontend/src/app/admin/hires-emberek/[id]/page.tsx b/services/frontend/src/app/admin/hires-emberek/[id]/page.tsx index 8bb8204..ec54969 100644 --- a/services/frontend/src/app/admin/hires-emberek/[id]/page.tsx +++ b/services/frontend/src/app/admin/hires-emberek/[id]/page.tsx @@ -1,7 +1,7 @@ import type { Metadata } from "next"; import { notFound } from "next/navigation"; -import { AdminNav } from "@/components/AdminNav"; +import { AdminNav, canEditCelebrities } from "@/components/AdminNav"; import { requireMe } from "@/lib/server"; import { CelebrityEditor } from "./CelebrityEditor"; @@ -13,11 +13,11 @@ type Props = { params: Promise<{ id: string }> }; export default async function AdminCelebrityPage({ params }: Props) { const { id } = await params; const me = await requireMe(`/admin/hires-emberek/${id}`); - if (!me.user.roles.includes("admin")) notFound(); + if (!canEditCelebrities(me.user.roles)) notFound(); return (
- - + +
); } diff --git a/services/frontend/src/app/admin/hires-emberek/page.tsx b/services/frontend/src/app/admin/hires-emberek/page.tsx index 6e2c1d5..176fa1e 100644 --- a/services/frontend/src/app/admin/hires-emberek/page.tsx +++ b/services/frontend/src/app/admin/hires-emberek/page.tsx @@ -1,7 +1,7 @@ import type { Metadata } from "next"; import { notFound } from "next/navigation"; -import { AdminNav } from "@/components/AdminNav"; +import { AdminNav, canEditCelebrities } from "@/components/AdminNav"; import { requireMe } from "@/lib/server"; import { AdminCelebrities } from "./AdminCelebrities"; @@ -10,10 +10,10 @@ export const metadata: Metadata = { title: "Híres emberek" }; export default async function AdminCelebritiesPage() { const me = await requireMe("/admin/hires-emberek"); - if (!me.user.roles.includes("admin")) notFound(); + if (!canEditCelebrities(me.user.roles)) notFound(); return (
- +

Híres emberek

diff --git a/services/frontend/src/app/csillagjegyek/[jegy]/page.tsx b/services/frontend/src/app/csillagjegyek/[jegy]/page.tsx index 9de7e2a..0cea4aa 100644 --- a/services/frontend/src/app/csillagjegyek/[jegy]/page.tsx +++ b/services/frontend/src/app/csillagjegyek/[jegy]/page.tsx @@ -118,9 +118,6 @@ export default async function SignPage({ params }: { params: Promise<{ jegy: str

diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 82d6e85..1d9fe15 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -180,7 +180,8 @@ textarea.inp { padding: 12px 14px; line-height: 1.55; min-height: 96px; resize: .combo-list small { color: var(--muted); } /* Tables */ -.table-wrap { overflow-x: auto; } +/* relative: absolutely placed children (e.g. .sr-only) stay clipped inside. */ +.table-wrap { overflow-x: auto; position: relative; } 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; } @@ -482,6 +483,36 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } } .admin-nav a:hover { color: var(--ink); } .admin-nav a[aria-current="page"] { color: var(--gold); border-bottom-color: var(--gold); } + +/* Admin: the user list's pager and the user dialog. */ +.pager { display: flex; align-items: center; justify-content: center; gap: 14px; flex-wrap: wrap; font-size: 14px; color: var(--ink-2); } +.admin-users td { vertical-align: middle; } +dialog.modal { + width: min(560px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); padding: 0; margin: auto; + background: var(--panel); color: var(--ink); border: 1px solid var(--line-2); border-radius: 14px; + box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5); +} +dialog.modal::backdrop { background: rgba(5, 8, 16, 0.72); backdrop-filter: blur(2px); } +.modal-inner { display: flex; flex-direction: column; gap: 18px; padding: 22px 24px 24px; } +.modal-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; } +.modal-head h2 { font-size: 26px; line-height: 1.15; overflow-wrap: anywhere; } +.modal-sub { font-size: 13px; margin-top: 4px; overflow-wrap: anywhere; } +.modal-close { + flex: none; width: 36px; height: 36px; display: grid; place-items: center; border-radius: 8px; + background: none; border: 1px solid var(--line-2); color: var(--ink-2); cursor: pointer; +} +.modal-close:hover { color: var(--gold); border-color: var(--gold); } +.modal-close svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; } +.modal-section, .modal-section fieldset { border: 0; margin: 0; padding: 0; min-width: 0; } +.modal-section { border-top: 1px solid var(--line); padding-top: 16px; display: flex; flex-direction: column; gap: 10px; } +.modal-section fieldset { display: flex; flex-direction: column; gap: 10px; } +.modal-section legend { font-size: 14px; font-weight: 600; color: var(--ink); padding: 0; margin-bottom: 10px; } +.modal-hint { font-size: 13px; margin: 0; } +.balance-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 8px; margin: 0; } +.balance-grid div { background: var(--panel-2); border: 1px solid var(--line); border-radius: 8px; padding: 6px 10px; } +.balance-grid dt { font-size: 12px; color: var(--muted); } +.balance-grid dd { margin: 0; font-size: 18px; color: var(--ink); } +@media (max-width: 480px) { .modal-inner { padding: 18px 16px 20px; } } .prompt-kind { display: flex; flex-direction: column; gap: 20px; } .prompt-kind-head { display: flex; gap: 16px 24px; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; } .prompt-kind-head > p { flex: 1 1 360px; margin: 0; } diff --git a/services/frontend/src/app/hires-emberek/page.tsx b/services/frontend/src/app/hires-emberek/page.tsx index 2ed00bf..1d48fee 100644 --- a/services/frontend/src/app/hires-emberek/page.tsx +++ b/services/frontend/src/app/hires-emberek/page.tsx @@ -68,17 +68,6 @@ export default async function CelebritiesPage() { ))} )} -
-

- Kíváncsi vagy a saját képletedre? Az ingyenes születési horoszkóp a születési adataidból kiszámolja, belépés - nélkül. -

-
- - Ingyenes születési horoszkóp - -
-
diff --git a/services/frontend/src/components/AdminNav.tsx b/services/frontend/src/components/AdminNav.tsx index 3f21911..a766c08 100644 --- a/services/frontend/src/components/AdminNav.tsx +++ b/services/frontend/src/components/AdminNav.tsx @@ -1,20 +1,28 @@ import Link from "next/link"; +import type { Role } from "@/lib/types"; + const PAGES = [ { href: "/admin", label: "Felhasználók" }, { href: "/admin/meghivok", label: "Meghívók" }, { href: "/admin/promokodok", label: "Promókódok" }, - { href: "/admin/hires-emberek", label: "Híres emberek" }, + { href: "/admin/hires-emberek", label: "Híres emberek", creator: true }, { href: "/admin/promptok", label: "Promptok" }, { href: "/admin/modellek", label: "Modellek" }, { href: "/admin/hibak", label: "Hibanapló" }, ]; -/** Switches between the admin pages. */ -export function AdminNav({ current }: { current: string }) { +/** May manage the famous people (an admin or a creator). */ +export function canEditCelebrities(roles: Role[]): boolean { + return roles.includes("admin") || roles.includes("creator"); +} + +/** Switches between the admin pages (a creator who is no admin: only theirs). */ +export function AdminNav({ current, roles }: { current: string; roles?: Role[] }) { + const admin = !roles || roles.includes("admin"); return ( © {new Date().getFullYear()} Sorsfonalak diff --git a/services/frontend/src/app/belepes/page.tsx b/services/frontend/src/app/belepes/page.tsx index 41b8291..720b922 100644 --- a/services/frontend/src/app/belepes/page.tsx +++ b/services/frontend/src/app/belepes/page.tsx @@ -22,7 +22,8 @@ export const metadata: Metadata = { title: "Belépés" }; */ function safeTarget(value: string | string[] | undefined): string { const v = Array.isArray(value) ? value[0] : value; - return v && /^\/(?![/\\])[^\\\u0000-\u001f]*$/.test(v) ? v : "/"; + // By default to the user's chart (or to the profile for their birth data). + return v && /^\/(?![/\\])[^\\\u0000-\u001f]*$/.test(v) ? v : "/keplet"; } async function loadConfig(): Promise { diff --git a/services/frontend/src/app/jelszo/SetPasswordForm.tsx b/services/frontend/src/app/jelszo/SetPasswordForm.tsx index 7679492..3aa7c81 100644 --- a/services/frontend/src/app/jelszo/SetPasswordForm.tsx +++ b/services/frontend/src/app/jelszo/SetPasswordForm.tsx @@ -29,7 +29,7 @@ export function SetPasswordForm({ token, minLength }: { token: string; minLength setBusy(true); try { await api("/auth/set-password", { body: { token, password } }); - router.replace("/"); + router.replace("/keplet"); router.refresh(); } catch (err) { if (err instanceof ApiError && err.code === "invalid_token") setExpired(true); diff --git a/services/frontend/src/app/page.tsx b/services/frontend/src/app/page.tsx index 62c77b3..b279097 100644 --- a/services/frontend/src/app/page.tsx +++ b/services/frontend/src/app/page.tsx @@ -1,5 +1,4 @@ import type { Metadata } from "next"; -import { redirect } from "next/navigation"; import { JsonLd } from "@/components/PublicFooter"; import { OPERATOR } from "@/lib/legal"; @@ -42,14 +41,13 @@ async function signupMode(): Promise { } } -/** Visitors get the home page; logged-in users go to their chart (or to the profile for their birth data). */ +/** The home page, for visitors and logged-in users alike (they get the app's header and a link to their chart). */ export default async function Home() { const me = await getMe(); - if (me) redirect(me.primary_chart_id ? "/keplet" : "/profil"); const base = await siteUrl(); return ( <> - +