Files
sorsfonalak/services/frontend/src/app/admin/AdminUsers.tsx
T
fecoandClaude Opus 5.5 b0fc547b73
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 5m52s
CI / deploy (push) Skipped
Tarot readings: AI-written, drawn on the server, sold as units
A new Kártyajóslás page: choose a spread (1, 3 or 5 cards), ask a
question, pick the cards from the fanned deck and watch them turn over;
the reading is written by the detailed-analysis model from the cards,
their positions and base meanings, the question and the reader's Sun,
Moon and Ascendant. The server shuffles and draws, so nobody can draw
again for free. A reading is a 'tarot' analysis (worker, retries,
fallback, refunds and admin regeneration as for analyses), uses one
'tarot' unit, and survives recalculations; deleting the account
deletes it.

Packages carry 2/5/10 readings, the new +5 kártyajóslás addon costs
1 000 Ft. The card artwork comes from the tarot design studio
(celestial astrolabe style); the deck JSON is shared by the frontend
and the prompt. A public example is at /kartyajoslas/pelda.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 14:35:50 +00:00

306 lines
9.8 KiB
TypeScript

"use client";
import { useCallback, useEffect, useState } from "react";
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 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" },
];
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 packages = usePackages() ?? [];
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">Részletes elemzések</th>
<th scope="col">Csomag</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}
packages={packages}
onChange={(next) => setUsers((list) => list?.map((x) => (x.id === next.id ? next : x)) ?? null)}
/>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
function UserRow({
user,
isSelf,
packages,
onChange,
}: {
user: AdminUser;
isSelf: boolean;
packages: Package[];
onChange: (u: AdminUser) => void;
}) {
const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
const [busy, setBusy] = useState(false);
const [delta, setDelta] = useState("");
const [unit, setUnit] = useState<UnitKind>("natal");
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 {
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 (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: 92, fontSize: 13 }}>
képlet {user.analyses_left.natal}
<br />
szinasztria {user.analyses_left.synastry}
<br />
előrejelzés {user.analyses_left.forecast ?? 0}
<br />
kérdés {user.analyses_left.question ?? 0}
<br />
jóslás {user.analyses_left.tarot ?? 0}
</span>
<label className="sr-only" htmlFor={`unit-${user.id}`}>
Elemzés fajtája
</label>
<select
id={`unit-${user.id}`}
className="inp"
style={{ width: 118, minHeight: 36 }}
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}`}>
Jóváírt darabszám
</label>
<input
id={`delta-${user.id}`}
className="inp"
style={{ width: 76, minHeight: 36 }}
inputMode="numeric"
placeholder="+1"
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>
<PackageGrant user={user} packages={packages} onChange={onChange} />
</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>
);
}
/** Gives the user a package from the catalog (a gift: nothing is paid). */
function PackageGrant({
user,
packages,
onChange,
}: {
user: AdminUser;
packages: Package[];
onChange: (u: AdminUser) => void;
}) {
const [id, setId] = useState("");
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(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="field" style={{ gap: 6 }}>
<div className="row" style={{ gap: 6, flexWrap: "nowrap" }}>
<label className="sr-only" htmlFor={`pkg-${user.id}`}>
Kiosztandó csomag
</label>
<select
id={`pkg-${user.id}`}
className="inp"
style={{ width: 190, minHeight: 36 }}
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="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>
)}
</form>
);
}