Files
sorsfonalak/services/frontend/src/app/admin/AdminUsers.tsx
T

485 lines
16 KiB
TypeScript
Raw Normal View History

"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";
const UNITS: { value: UnitKind; label: string }[] = [
{ value: "natal", label: "képlet" },
{ value: "synastry", label: "szinasztria" },
{ value: "forecast", label: "előrejelzés" },
{ value: "question", label: "kérdés" },
{ 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 [page, setPage] = useState(0);
const [data, setData] = useState<{ users: AdminUser[]; total: number } | null>(null);
const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<string | null>(null);
const packages = usePackages() ?? [];
const load = useCallback(async (q: string, p: number) => {
try {
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));
}
}, []);
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 (
<section className="card" aria-label="Felhasználók listája">
<div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end" }}>
<div className="field" style={{ flex: "1 1 280px", 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);
setPage(0);
}}
placeholder="pl. anna@"
/>
</div>
{data && (
<span className="muted" style={{ fontSize: 14 }}>
{total} felhasználó
</span>
)}
</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 className="admin-users">
<thead>
<tr>
<th scope="col">Felhasználó</th>
<th scope="col">Szerepkör</th>
<th scope="col">Hátralévő elemzések</th>
<th scope="col">Képletek</th>
<th scope="col">Regisztrált</th>
<th scope="col">Utoljára belépett</th>
<th scope="col">
<span className="sr-only">Műveletek</span>
</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>
<div>{u.display_name || <span className="muted">(nincs név)</span>}</div>
<div className="muted" style={{ fontSize: 13 }}>
{u.email}
{u.id === selfId && " · te"}
</div>
</td>
<td>
<RoleBadges roles={u.roles} />
</td>
<td>
<Balances user={u} />
</td>
<td className="num">{u.charts}</td>
<td className="num">{formatDate(u.created_at)}</td>
<td className="num">{formatDate(u.last_login_at, true)}</td>
<td style={{ textAlign: "right" }}>
<button type="button" className="btn btn-sm" onClick={() => setEditing(u.id)}>
Kezelés
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{data && total > PAGE_SIZE && (
<nav className="pager" aria-label="Lapozás">
<button type="button" className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
‹ Előző
</button>
<span className="num">
{page * PAGE_SIZE + 1}–{Math.min(total, (page + 1) * PAGE_SIZE)} / {total} · {page + 1}/{pages}. oldal
</span>
<button
type="button"
className="btn btn-sm"
disabled={page + 1 >= pages}
onClick={() => setPage(page + 1)}
>
Következő ›
</button>
</nav>
)}
{selected && (
<UserDialog
user={selected}
isSelf={selected.id === selfId}
packages={packages}
onChange={update}
onClose={() => setEditing(null)}
/>
)}
</section>
);
}
function RoleBadges({ roles }: { roles: Role[] }) {
const shown = roles.filter((r) => r !== "user");
if (shown.length === 0) return <span className="muted">Felhasználó</span>;
return (
<div className="row" style={{ gap: 4 }}>
{shown.map((r) => (
<span key={r} className={r === "admin" ? "badge badge-gold" : "badge"}>
{ROLE_LABELS[r] ?? r}
</span>
))}
</div>
);
}
/** 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 <span className="muted">–</span>;
return (
<span style={{ fontSize: 13 }}>
{left.map((u, i) => (
<span key={u.value} style={{ whiteSpace: "nowrap" }}>
{i > 0 && " · "}
{u.label} <span className="num">{u.n}</span>
</span>
))}
</span>
);
}
/** 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 (
<Modal
title={user.display_name || "(nincs név)"}
subtitle={
<>
{user.email}
{isSelf && " · te"} · regisztrált {formatDate(user.created_at)}
</>
}
onClose={onClose}
canClose={canClose}
>
<RolesEditor user={user} isSelf={isSelf} onChange={onChange} />
<PackageGrant
user={user}
packages={packages}
onChange={onChange}
onUnsent={(name) => {
unsent.current.pkg = name;
}}
/>
<CreditGrant
user={user}
onChange={onChange}
onUnsent={(text) => {
unsent.current.credit = text;
}}
/>
<div className="row" style={{ justifyContent: "flex-end" }}>
<button
type="button"
className="btn"
onClick={() => {
if (canClose()) onClose();
}}
>
Bezárás
</button>
</div>
</Modal>
);
}
function RolesEditor({ user, isSelf, onChange }: { user: AdminUser; isSelf: boolean; onChange: (u: AdminUser) => void }) {
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<Status>(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 (
<div className="modal-section">
<fieldset>
<legend>Szerepkörök</legend>
<div className="row" style={{ gap: 16 }}>
{EDITABLE_ROLES.map((role) => {
const locked = isSelf && role === "admin";
return (
<label key={role} className="check">
<input
type="checkbox"
checked={user.roles.includes(role)}
disabled={busy || locked}
onChange={(e) => toggle(role, e.target.checked)}
title={locked ? "A saját admin szerepköröd nem veheted el." : undefined}
/>
{ROLE_LABELS[role]}
</label>
);
})}
</div>
<p className="muted modal-hint">A szerző híres embereket vihet fel és szerkeszthet.</p>
{status && (
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
{status.text}
</span>
)}
</fieldset>
</div>
);
}
/** 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<Status>(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 (
<form onSubmit={give} className="modal-section">
<fieldset>
<legend>Csomag kiosztása (ajándék)</legend>
<div className="row" style={{ gap: 8 }}>
<label className="sr-only" htmlFor={`pkg-${user.id}`}>
Kiosztandó csomag
</label>
<select
id={`pkg-${user.id}`}
className="inp"
style={{ flex: "1 1 220px", minHeight: 40 }}
value={id}
onChange={(e) => setId(e.target.value)}
disabled={busy || packages.length === 0}
>
<option value="">Válassz csomagot…</option>
{packages.map((p) => (
<option key={p.id} value={p.id}>
{p.name} ({huf(p.price_huf)})
</option>
))}
</select>
<button type="submit" className={id ? "btn btn-sm btn-primary" : "btn btn-sm"} disabled={busy || !id}>
{busy ? "…" : "Kiosztás"}
</button>
</div>
{status && (
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
{status.text}
</span>
)}
</fieldset>
</form>
);
}
/** 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<UnitKind>("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<Status>(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 (
<form onSubmit={grant} className="modal-section">
<fieldset>
<legend>Részletes elemzések</legend>
<dl className="balance-grid">
{UNITS.map((u) => (
<div key={u.value}>
<dt>{u.label}</dt>
<dd className="num">{user.analyses_left[u.value] ?? 0}</dd>
</div>
))}
</dl>
<div className="row" style={{ gap: 8 }}>
<label className="sr-only" htmlFor={`unit-${user.id}`}>
Elemzés fajtája
</label>
<select
id={`unit-${user.id}`}
className="inp"
style={{ flex: "1 1 150px", minHeight: 40 }}
value={unit}
onChange={(e) => setUnit(e.target.value as UnitKind)}
>
{UNITS.map((u) => (
<option key={u.value} value={u.value}>
{u.label}
</option>
))}
</select>
<label className="sr-only" htmlFor={`delta-${user.id}`}>
Darabszám (negatív: elvétel)
</label>
<input
id={`delta-${user.id}`}
className="inp"
style={{ width: 90, minHeight: 40 }}
inputMode="numeric"
placeholder="+1"
value={delta}
onChange={(e) => setDelta(e.target.value)}
/>
<button type="submit" className={delta ? "btn btn-sm btn-primary" : "btn btn-sm"} disabled={busy || !delta}>
Jóváír
</button>
</div>
<p className="muted modal-hint">Negatív számmal el is vehetsz (pl. -1).</p>
{status && (
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
{status.text}
</span>
)}
</fieldset>
</form>
);
}