"use client"; import { useCallback, useEffect, useRef, 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"; /** `short`: the mark in the list, where the names do not fit (explained under it). */ const UNITS: { value: UnitKind; label: string; short: string }[] = [ { value: "natal", label: "képlet", short: "K" }, { value: "synastry", label: "szinasztria", short: "Sz" }, { value: "forecast", label: "előrejelzés", short: "E" }, { value: "question", label: "kérdés", short: "?" }, { value: "tarot", label: "kártyajóslás", short: "T" }, ]; type Stats = { users: number; buyers: number; test_buyers: number }; type UserPage = { users: AdminUser[]; total: number; stats: Stats }; type Status = { ok: boolean; text: string } | null; export function AdminUsers({ selfId }: { selfId: string }) { const [query, setQuery] = useState(""); const [page, setPage] = useState(0); const [data, setData] = useState(null); const [error, setError] = useState(null); const [editing, setEditing] = useState(null); const packages = usePackages() ?? []; const load = useCallback(async (q: string, p: number) => { try { const res = await api( `/admin/users?q=${encodeURIComponent(q)}&limit=${PAGE_SIZE}&offset=${p * PAGE_SIZE}`, ); setData(res); setError(null); } catch (e) { setError(errorText(e)); } }, []); useEffect(() => { const t = setTimeout(() => load(query.trim(), page), 250); return () => clearTimeout(t); }, [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 (
{data && }
{ setQuery(e.target.value); setPage(0); }} placeholder="pl. anna@" />
{data && query.trim() && ( {total} találat )}
{error && (

{error}

)} {users === null ? (

Betöltés…

) : users.length === 0 ? (

Nincs találat.

) : (
{users.map((u) => ( ))}
Felhasználó Szerepkör Hátralévő 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)}

Hátralévő:{" "} {UNITS.map((u, i) => ( {i > 0 && " · "} {u.short} {u.label} ))}

)} {data && total > PAGE_SIZE && ( )} {selected && ( setEditing(null)} /> )}
); } 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} ))}
); } /** Everyone on the site and who has paid (not affected by the search). */ function SiteStats({ stats }: { stats: Stats }) { const share = stats.users > 0 ? (stats.buyers / stats.users) * 100 : 0; return (
Felhasználó
{stats.users.toLocaleString("hu-HU")}
Vásárló
{stats.buyers.toLocaleString("hu-HU")}
{stats.users > 0 && `a felhasználók ${share.toLocaleString("hu-HU", { maximumFractionDigits: 1 })}%-a`} {stats.test_buyers > 0 && ( <> {stats.users > 0 &&
}+{stats.test_buyers} csak tesztmódban )}
); } /** The remaining units as short marks (K 2 · ? 3), 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) => ( {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; }) { // What was chosen or typed but not sent yet (a package, a number of units). const unsent = useRef<{ pkg: string | null; credit: string | null }>({ pkg: null, credit: null }); const canClose = () => { const { pkg, credit } = unsent.current; const what = [pkg && `a(z) ${pkg} csomag`, credit && `${credit} jóváírás`].filter(Boolean).join(" és "); return !what || window.confirm(`Még nem küldted el: ${what}. Bezárod nélküle?`); }; return ( {user.email} {isSelf && " · te"} · regisztrált {formatDate(user.created_at)} } onClose={onClose} canClose={canClose} > { unsent.current.pkg = name; }} /> { unsent.current.credit = text; }} />
); } 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); setStatus(null); try { const res = await api<{ roles: Role[] }>(`/admin/users/${user.id}`, { method: "PATCH", body: { roles } }); onChange({ ...user, roles: res.roles }); setStatus({ ok: true, text: "Mentve." }); } catch (e) { setStatus({ ok: false, text: errorText(e) }); } finally { setBusy(false); } } return (
Szerepkörök
{EDITABLE_ROLES.map((role) => { const locked = isSelf && role === "admin"; return ( ); })}

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

{status && ( {status.text} )}
); } /** Gives the user a package from the catalog (a gift: nothing is paid). */ function PackageGrant({ user, packages, onChange, onUnsent, }: { user: AdminUser; packages: Package[]; onChange: (u: AdminUser) => void; /** The chosen package's name while it is not given yet (null: nothing pending). */ onUnsent: (name: string | null) => void; }) { const [id, setId] = useState(""); useEffect(() => { onUnsent(packages.find((p) => p.id === id)?.name ?? null); }, [id, packages, onUnsent]); const [busy, setBusy] = useState(false); const [status, setStatus] = useState(null); async function give(e: React.FormEvent) { e.preventDefault(); const pkg = packages.find((p) => p.id === id); if (!pkg) return; 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" }, }); onChange({ ...user, analyses_left: res.analyses_left }); setStatus({ ok: true, text: `${pkg.name} kiosztva.` }); setId(""); } catch (err) { setStatus({ ok: false, text: errorText(err) }); } finally { setBusy(false); } } return (
Csomag kiosztása (ajándék)
{status && ( {status.text} )}
); } /** Adds (or takes away) single analyses of one kind. */ function CreditGrant({ user, onChange, onUnsent, }: { user: AdminUser; onChange: (u: AdminUser) => void; /** The typed amount while it is not sent yet (null: nothing pending). */ onUnsent: (text: string | null) => void; }) { const [delta, setDelta] = useState(""); const [unit, setUnit] = useState("natal"); useEffect(() => { const label = UNITS.find((u) => u.value === unit)?.label; onUnsent(delta.trim() ? `${delta.trim()} ${label}` : null); }, [delta, unit, onUnsent]); 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}
))}
setDelta(e.target.value)} />

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

{status && ( {status.text} )}
); }