436 lines
14 KiB
TypeScript
436 lines
14 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useState } from "react";
|
|
import { Mail } from "lucide-react";
|
|
import { toast } from "sonner";
|
|
import {
|
|
api,
|
|
AdminError,
|
|
type AdminUser,
|
|
type UserLimitsInput,
|
|
} from "@/lib/api";
|
|
import { GoogleIcon, FacebookIcon } from "@/components/ui/provider-icons";
|
|
import { usePagedList } from "@/lib/use-paged-list";
|
|
import { ListShell, EmptyRow } from "@/components/list-shell";
|
|
import { Table, THead, TR, TH, TD } from "@/components/ui/table";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Modal } from "@/components/ui/modal";
|
|
import { RowMenu, type MenuItem } from "@/components/ui/menu";
|
|
import { Avatar } from "@/components/ui/avatar";
|
|
import { useConfirm } from "@/components/confirm";
|
|
import { Input } from "@/components/ui/input";
|
|
import { RichTextarea } from "@/components/ui/rich-textarea";
|
|
import { fmtDate } from "@/lib/utils";
|
|
import { DiscipleLinkModal } from "./disciple-link-modal";
|
|
import { useStaff } from "@/components/staff-context";
|
|
import { Clamp } from "@/components/ui/clamp";
|
|
|
|
export default function UsersPage() {
|
|
const { can } = useStaff();
|
|
const [q, setQ] = useState("");
|
|
const fetcher = useCallback(
|
|
(limit: number, offset: number) => api.users(q, limit, offset),
|
|
[q],
|
|
);
|
|
const list = usePagedList<AdminUser>(fetcher, [q]);
|
|
const confirm = useConfirm();
|
|
const [notify, setNotify] = useState<AdminUser | null>(null);
|
|
const [limitsUser, setLimitsUser] = useState<AdminUser | null>(null);
|
|
const [discipleUser, setDiscipleUser] = useState<AdminUser | null>(null);
|
|
|
|
async function toggleBan(u: AdminUser) {
|
|
const banning = !u.banned_at;
|
|
if (
|
|
banning &&
|
|
!(await confirm({
|
|
title: `Suspend @${u.handle}?`,
|
|
message: "They'll be signed out and unable to log in until you unban them.",
|
|
confirmLabel: "Suspend account",
|
|
destructive: true,
|
|
}))
|
|
) {
|
|
return;
|
|
}
|
|
try {
|
|
await (banning ? api.banUser(u.id) : api.unbanUser(u.id));
|
|
toast.success(banning ? "Account suspended." : "Account restored.");
|
|
list.refresh();
|
|
} catch (err) {
|
|
toast.error(err instanceof AdminError ? err.message : "Action failed.");
|
|
}
|
|
}
|
|
|
|
async function removeDiscipleLink(u: AdminUser) {
|
|
if (
|
|
!(await confirm({
|
|
title: `Remove disciple link from @${u.handle}?`,
|
|
message:
|
|
"Their profile badge and the highlight in the disciples directory will be removed. You can re-link them at any time.",
|
|
confirmLabel: "Remove link",
|
|
destructive: true,
|
|
}))
|
|
) {
|
|
return;
|
|
}
|
|
try {
|
|
await api.unlinkDisciple(u.id);
|
|
toast.success("Disciple link removed.");
|
|
list.refresh();
|
|
} catch (err) {
|
|
toast.error(err instanceof AdminError ? err.message : "Action failed.");
|
|
}
|
|
}
|
|
|
|
function menuItems(u: AdminUser): MenuItem[] {
|
|
// Only what this role may do. The BFF refuses the rest regardless.
|
|
const items: MenuItem[] = [];
|
|
if (can("users:notify")) {
|
|
items.push({ label: "Send notification", onClick: () => setNotify(u) });
|
|
}
|
|
if (can("users:limits")) {
|
|
items.push({ label: "Edit limits", onClick: () => setLimitsUser(u) });
|
|
}
|
|
if (can("disciples:manage")) {
|
|
items.push({
|
|
label: u.disciple_id ? "Change disciple link" : "Link direct disciple",
|
|
onClick: () => setDiscipleUser(u),
|
|
});
|
|
if (u.disciple_id) {
|
|
items.push({
|
|
label: "Remove disciple link",
|
|
onClick: () => removeDiscipleLink(u),
|
|
});
|
|
}
|
|
}
|
|
// No ban option for staff: removing a staff member is a superadmin job,
|
|
// done from the Staff page — and the BFF refuses it from here anyway.
|
|
if (can("users:ban") && !u.admin_role) {
|
|
items.push({
|
|
label: u.banned_at ? "Unban account" : "Ban account",
|
|
onClick: () => toggleBan(u),
|
|
destructive: !u.banned_at,
|
|
});
|
|
}
|
|
return items;
|
|
}
|
|
|
|
return (
|
|
<ListShell
|
|
title="Users"
|
|
total={list.total}
|
|
searchPlaceholder="Search name, handle, or email…"
|
|
onQueryChange={setQ}
|
|
list={list}
|
|
>
|
|
<Table>
|
|
<THead>
|
|
<TR>
|
|
<TH>User</TH>
|
|
<TH>Email</TH>
|
|
<TH>Posts</TH>
|
|
<TH>Joined</TH>
|
|
<TH className="text-right">Actions</TH>
|
|
</TR>
|
|
</THead>
|
|
<tbody>
|
|
{list.items.length === 0 && !list.loading ? (
|
|
<EmptyRow cols={5} label="No users found." />
|
|
) : (
|
|
list.items.map((u) => (
|
|
<TR key={u.id}>
|
|
<TD>
|
|
<div className="flex min-w-0 items-center gap-3">
|
|
<Avatar src={u.avatar_url} name={u.name} />
|
|
<div className="min-w-0">
|
|
<div className="flex min-w-0 items-center gap-2">
|
|
<Clamp className="font-medium">{u.name}</Clamp>
|
|
{u.banned_at ? (
|
|
<span className="shrink-0 rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-destructive whitespace-nowrap">
|
|
Suspended
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
<Clamp className="text-xs text-muted-foreground">
|
|
{`@${u.handle}`}
|
|
</Clamp>
|
|
{u.disciple_id ? (
|
|
<div
|
|
className="mt-1 inline-flex max-w-full items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary"
|
|
title={
|
|
u.disciple_name
|
|
? `Linked to ${u.disciple_name}`
|
|
: "Linked to an unknown disciple record"
|
|
}
|
|
>
|
|
<Clamp>{u.disciple_name ?? "Direct disciple"}</Clamp>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
</TD>
|
|
<TD>
|
|
<div className="space-y-1.5">
|
|
{u.email ? (
|
|
<Clamp>{u.email}</Clamp>
|
|
) : (
|
|
<span className="text-muted-foreground">—</span>
|
|
)}
|
|
<AuthIcons user={u} />
|
|
</div>
|
|
</TD>
|
|
<TD>{u.post_count}</TD>
|
|
<TD className="whitespace-nowrap">{fmtDate(u.created_at)}</TD>
|
|
<TD className="text-right">
|
|
<RowMenu items={menuItems(u)} />
|
|
</TD>
|
|
</TR>
|
|
))
|
|
)}
|
|
</tbody>
|
|
</Table>
|
|
|
|
<NotifyModal user={notify} onClose={() => setNotify(null)} />
|
|
<LimitsModal
|
|
user={limitsUser}
|
|
onClose={() => setLimitsUser(null)}
|
|
onSaved={list.refresh}
|
|
/>
|
|
<DiscipleLinkModal
|
|
user={discipleUser}
|
|
onClose={() => setDiscipleUser(null)}
|
|
onSaved={list.refresh}
|
|
/>
|
|
</ListShell>
|
|
);
|
|
}
|
|
|
|
function AuthIcons({ user }: { user: AdminUser }) {
|
|
const hasGoogle = user.providers.includes("google");
|
|
const hasFacebook = user.providers.includes("facebook");
|
|
if (!user.has_password && !hasGoogle && !hasFacebook) {
|
|
return <span className="text-muted-foreground">—</span>;
|
|
}
|
|
return (
|
|
<div className="flex items-center gap-2">
|
|
{user.has_password ? (
|
|
// Tooltip shows the email on hover; clicking copies it to the clipboard.
|
|
<button
|
|
type="button"
|
|
title={user.email ? `Click to copy ${user.email}` : "Email & password"}
|
|
onClick={() => {
|
|
if (!user.email) return;
|
|
// No await before the write — keeps the click's user activation.
|
|
navigator.clipboard.writeText(user.email).then(
|
|
() => toast.success("Email copied"),
|
|
() => toast.error("Could not copy"),
|
|
);
|
|
}}
|
|
className="inline-flex text-muted-foreground outline-none hover:text-foreground focus-visible:text-foreground"
|
|
>
|
|
<Mail className="size-4" />
|
|
</button>
|
|
) : null}
|
|
{hasGoogle ? <GoogleIcon className="size-4" /> : null}
|
|
{hasFacebook ? <FacebookIcon className="size-4" /> : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// An effective limit of -1 means "unlimited" (premium default) — shown as an
|
|
// empty field. Saving an empty field sends null, which resets that limit to
|
|
// the plan default on the server.
|
|
function limitToField(v: number | undefined): string {
|
|
return v === undefined || v < 0 ? "" : String(v);
|
|
}
|
|
|
|
function LimitsModal({
|
|
user,
|
|
onClose,
|
|
onSaved,
|
|
}: {
|
|
user: AdminUser | null;
|
|
onClose: () => void;
|
|
onSaved: () => void;
|
|
}) {
|
|
const [bookmark, setBookmark] = useState("");
|
|
const [pub, setPub] = useState("");
|
|
const [priv, setPriv] = useState("");
|
|
const [busy, setBusy] = useState(false);
|
|
// Re-seed the fields whenever a different user's modal opens.
|
|
const [seededFor, setSeededFor] = useState<string | null>(null);
|
|
if (user && seededFor !== user.id) {
|
|
setSeededFor(user.id);
|
|
setBookmark(limitToField(user.bookmark_limit));
|
|
setPub(limitToField(user.public_collection_limit));
|
|
setPriv(limitToField(user.private_collection_limit));
|
|
}
|
|
if (!user && seededFor !== null) setSeededFor(null);
|
|
|
|
// "" → null (reset to plan default); a non-negative integer → that cap.
|
|
function parseField(raw: string): number | null | undefined {
|
|
const t = raw.trim();
|
|
if (t === "") return null;
|
|
const n = Number(t);
|
|
if (!Number.isInteger(n) || n < 0) return undefined; // invalid
|
|
return n;
|
|
}
|
|
|
|
async function save() {
|
|
if (!user) return;
|
|
const b = parseField(bookmark);
|
|
const p = parseField(pub);
|
|
const v = parseField(priv);
|
|
if (b === undefined || p === undefined || v === undefined) {
|
|
toast.error("Limits must be whole numbers (0 or more).");
|
|
return;
|
|
}
|
|
const limits: UserLimitsInput = {
|
|
bookmark_limit: b,
|
|
public_collection_limit: p,
|
|
private_collection_limit: v,
|
|
};
|
|
setBusy(true);
|
|
try {
|
|
await api.setUserLimits(user.id, limits);
|
|
toast.success(`Limits updated for @${user.handle}`);
|
|
onSaved();
|
|
onClose();
|
|
} catch (err) {
|
|
toast.error(err instanceof AdminError ? err.message : "Could not update.");
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Modal
|
|
open={!!user}
|
|
onClose={onClose}
|
|
title={user ? `Edit limits — @${user.handle}` : "Edit limits"}
|
|
>
|
|
<div className="space-y-4">
|
|
<p className="text-sm text-muted-foreground">
|
|
How many of each this user can save. Leave a field blank to use their
|
|
plan default.
|
|
</p>
|
|
<LimitField
|
|
label="Bookmarks"
|
|
value={bookmark}
|
|
onChange={setBookmark}
|
|
/>
|
|
<LimitField
|
|
label="Public collections"
|
|
value={pub}
|
|
onChange={setPub}
|
|
/>
|
|
<LimitField
|
|
label="Private collections"
|
|
value={priv}
|
|
onChange={setPriv}
|
|
/>
|
|
<div className="flex justify-end gap-2">
|
|
<Button variant="ghost" onClick={onClose}>
|
|
Cancel
|
|
</Button>
|
|
<Button onClick={save} disabled={busy}>
|
|
{busy ? "Saving…" : "Save limits"}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</Modal>
|
|
);
|
|
}
|
|
|
|
function LimitField({
|
|
label,
|
|
value,
|
|
onChange,
|
|
}: {
|
|
label: string;
|
|
value: string;
|
|
onChange: (v: string) => void;
|
|
}) {
|
|
return (
|
|
<label className="block space-y-1.5">
|
|
<span className="text-sm font-medium">{label}</span>
|
|
<Input
|
|
type="number"
|
|
min={0}
|
|
inputMode="numeric"
|
|
value={value}
|
|
onChange={(e) => onChange(e.target.value)}
|
|
placeholder="Plan default"
|
|
/>
|
|
</label>
|
|
);
|
|
}
|
|
|
|
function NotifyModal({
|
|
user,
|
|
onClose,
|
|
}: {
|
|
user: AdminUser | null;
|
|
onClose: () => void;
|
|
}) {
|
|
const [title, setTitle] = useState("");
|
|
const [body, setBody] = useState("");
|
|
const [busy, setBusy] = useState(false);
|
|
|
|
async function send() {
|
|
if (!user || body.trim() === "") return;
|
|
setBusy(true);
|
|
try {
|
|
await api.notifyUser(user.id, title.trim(), body.trim());
|
|
toast.success(`Notification sent to @${user.handle}`);
|
|
setTitle("");
|
|
setBody("");
|
|
onClose();
|
|
} catch (err) {
|
|
toast.error(err instanceof AdminError ? err.message : "Could not send.");
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Modal
|
|
open={!!user}
|
|
onClose={onClose}
|
|
title={user ? `Notify @${user.handle}` : "Notify"}
|
|
>
|
|
<div className="space-y-4">
|
|
<p className="text-sm text-muted-foreground">
|
|
Sends an in-app notification, plus web push and email where available.
|
|
</p>
|
|
<label className="block space-y-1.5">
|
|
<span className="text-sm font-medium">Title (optional)</span>
|
|
<Input
|
|
value={title}
|
|
onChange={(e) => setTitle(e.target.value)}
|
|
maxLength={120}
|
|
placeholder="A note from the team"
|
|
/>
|
|
</label>
|
|
<label className="block space-y-1.5">
|
|
<span className="text-sm font-medium">Message</span>
|
|
<RichTextarea
|
|
value={body}
|
|
onValueChange={setBody}
|
|
rows={5}
|
|
maxLength={4000}
|
|
placeholder="Write your message…"
|
|
/>
|
|
</label>
|
|
<div className="flex justify-end gap-2">
|
|
<Button variant="ghost" onClick={onClose}>
|
|
Cancel
|
|
</Button>
|
|
<Button onClick={send} disabled={busy || body.trim() === ""}>
|
|
{busy ? "Sending…" : "Send notification"}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</Modal>
|
|
);
|
|
}
|