Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
319 lines
10 KiB
TypeScript
319 lines
10 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
import type { ColumnDef } from "@tanstack/react-table";
|
|
import { Badge } from "@/app/components/ui/badge";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { DataTable } from "@/app/components/ui/data-table";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/app/components/ui/dialog";
|
|
import { FilterSearch } from "@/app/components/ui/filter-panel";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import { PageHeader } from "@/app/components/ui/page-header";
|
|
import { Segmented } from "@/app/components/ui/segmented";
|
|
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
|
import { Textarea } from "@/app/components/ui/textarea";
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import { formatDateTime } from "@/app/lib/format";
|
|
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import { RequireModule } from "@/app/lib/RequireModule";
|
|
import {
|
|
listOnlineUsers,
|
|
signOutOnlineUser,
|
|
type OnlineKind,
|
|
type OnlineUser,
|
|
type OnlineWindow,
|
|
} from "@/app/lib/services/onlineUsers";
|
|
|
|
// add-online-users: who is active in admin-portal and on the customer portal, and the forced sign-out.
|
|
// "Online" means a request within the window — sessions are stateless, so there is no exact signed-in state.
|
|
|
|
const REFRESH_MS = 30_000;
|
|
const MAX_REASON = 500;
|
|
|
|
const fromEpoch = (ms: number | null | undefined) => (ms == null ? null : new Date(ms).toISOString());
|
|
|
|
function SignOutDialog({
|
|
kind,
|
|
person,
|
|
onClose,
|
|
onDone,
|
|
}: {
|
|
kind: OnlineKind;
|
|
person: OnlineUser;
|
|
onClose: () => void;
|
|
onDone: (person: OnlineUser) => void;
|
|
}) {
|
|
const t = useT();
|
|
const [reason, setReason] = useState("");
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const display = person.name || person.id;
|
|
const trimmed = reason.trim();
|
|
|
|
async function confirm() {
|
|
setBusy(true);
|
|
setError(null);
|
|
try {
|
|
await signOutOnlineUser({ kind, id: person.id, reason: trimmed });
|
|
onDone(person);
|
|
} catch (err) {
|
|
const code = err instanceof ApiError ? (err.data as { code?: unknown } | undefined)?.code : undefined;
|
|
setError(
|
|
code === "OnlineUserCannotSignOutSelf"
|
|
? "OnlineUsersSignOutSelf"
|
|
: code === "OnlineUserCannotSignOutSuperAdmin"
|
|
? "OnlineUsersSignOutSuperAdmin"
|
|
: "OnlineUsersSignOutFailed",
|
|
);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Dialog open onOpenChange={(open) => !open && !busy && onClose()}>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>{t("OnlineUsersSignOutTitle", { name: display })}</DialogTitle>
|
|
<DialogDescription>{t("OnlineUsersSignOutBody", { name: display })}</DialogDescription>
|
|
</DialogHeader>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="online-users-reason">{t("OnlineUsersReason")}</Label>
|
|
<Textarea
|
|
id="online-users-reason"
|
|
value={reason}
|
|
maxLength={MAX_REASON}
|
|
onChange={(e) => setReason(e.target.value)}
|
|
/>
|
|
{error && (
|
|
<p role="alert" className="text-sm text-destructive">
|
|
{t(error)}
|
|
</p>
|
|
)}
|
|
</div>
|
|
<DialogFooter>
|
|
<Button variant="outline" onClick={onClose} disabled={busy}>
|
|
{t("Cancel")}
|
|
</Button>
|
|
<Button variant="destructive" onClick={confirm} disabled={busy || !trimmed}>
|
|
{t("OnlineUsersSignOut")}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
function OnlineUsersContent() {
|
|
const t = useT();
|
|
const { tableRef, pageSize } = useFitPageSize();
|
|
const [kind, setKind] = useState<OnlineKind>("ADMIN");
|
|
const [windowMinutes, setWindowMinutes] = useState<OnlineWindow>(15);
|
|
const [q, setQ] = useState("");
|
|
const [page, setPage] = useState(1);
|
|
const [rows, setRows] = useState<OnlineUser[]>([]);
|
|
const [total, setTotal] = useState(0);
|
|
const [counts, setCounts] = useState({ admins: 0, members: 0 });
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState(false);
|
|
const [reloadKey, setReloadKey] = useState(0);
|
|
// The kind is captured with the row, so a sign-out always targets the tab the row was listed on.
|
|
const [target, setTarget] = useState<{ kind: OnlineKind; person: OnlineUser } | null>(null);
|
|
const [notice, setNotice] = useState<string | null>(null);
|
|
|
|
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
|
|
|
useEffect(() => {
|
|
// A hidden tab does not poll, so an admin who leaves this page open is not kept "online" by it.
|
|
const timer = setInterval(() => {
|
|
if (document.visibilityState === "visible") refetch();
|
|
}, REFRESH_MS);
|
|
return () => clearInterval(timer);
|
|
}, [refetch]);
|
|
|
|
useEffect(() => {
|
|
if (pageSize == null) return;
|
|
let cancelled = false;
|
|
// eslint-disable-next-line react-hooks/set-state-in-effect -- marks the fetch below as in flight.
|
|
setLoading(true);
|
|
listOnlineUsers({ kind, windowMinutes, q, page, pageSize })
|
|
.then((result) => {
|
|
if (cancelled) return;
|
|
setRows(result.rows);
|
|
setTotal(result.total);
|
|
setCounts({ admins: result.adminCount, members: result.memberCount });
|
|
setError(false);
|
|
})
|
|
.catch(() => {
|
|
if (!cancelled) setError(true);
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [kind, windowMinutes, q, page, reloadKey, pageSize]);
|
|
|
|
const columns = useMemo<ColumnDef<OnlineUser, unknown>[]>(() => {
|
|
const cols: ColumnDef<OnlineUser, unknown>[] = [
|
|
{
|
|
accessorKey: "id",
|
|
header: t(kind === "ADMIN" ? "OnlineUsersColUsername" : "OnlineUsersColMemberCode"),
|
|
cell: ({ row }) => (
|
|
<span className="flex items-center gap-2">
|
|
<span className="block max-w-[14rem] truncate">{row.original.id}</span>
|
|
{row.original.self && <Badge variant="outline">{t("OnlineUsersYou")}</Badge>}
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
accessorKey: "name",
|
|
header: t("OnlineUsersColName"),
|
|
cell: ({ row }) => <span className="block max-w-[14rem] truncate">{row.original.name ?? "—"}</span>,
|
|
},
|
|
];
|
|
if (kind === "ADMIN") {
|
|
cols.push({
|
|
accessorKey: "roles",
|
|
header: t("OnlineUsersColRoles"),
|
|
cell: ({ row }) => (
|
|
<span className="block max-w-[14rem] truncate">{(row.original.roles ?? []).join(", ") || "—"}</span>
|
|
),
|
|
});
|
|
}
|
|
cols.push(
|
|
{
|
|
accessorKey: "lastSeenAt",
|
|
header: t("OnlineUsersColLastActivity"),
|
|
cell: ({ row }) => <span className="tabular">{formatDateTime(fromEpoch(row.original.lastSeenAt))}</span>,
|
|
},
|
|
{
|
|
accessorKey: "clientIp",
|
|
header: t("OnlineUsersColIp"),
|
|
cell: ({ row }) => row.original.clientIp ?? "—",
|
|
},
|
|
{
|
|
accessorKey: "activeSince",
|
|
header: t("OnlineUsersColActiveSince"),
|
|
cell: ({ row }) => <span className="tabular">{formatDateTime(fromEpoch(row.original.activeSince))}</span>,
|
|
},
|
|
{
|
|
id: "actions",
|
|
header: "",
|
|
cell: ({ row }) =>
|
|
row.original.self ? null : (
|
|
<Button variant="outline" size="sm" onClick={() => setTarget({ kind, person: row.original })}>
|
|
{t("OnlineUsersSignOut")}
|
|
</Button>
|
|
),
|
|
},
|
|
);
|
|
return cols;
|
|
}, [kind, t]);
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<p className="text-sm text-muted-foreground">{t("OnlineUsersHint")}</p>
|
|
<div className="flex flex-wrap items-center gap-3">
|
|
<Segmented<OnlineKind>
|
|
label={t("OnlineUsers")}
|
|
value={kind}
|
|
onChange={(k) => {
|
|
if (k !== kind) setRows([]);
|
|
setKind(k);
|
|
setQ("");
|
|
setPage(1);
|
|
}}
|
|
options={[
|
|
{ value: "ADMIN", label: t("OnlineUsersTabAdmins", { count: counts.admins }) },
|
|
{ value: "MEMBER", label: t("OnlineUsersTabMembers", { count: counts.members }) },
|
|
]}
|
|
/>
|
|
<Segmented<"15" | "60">
|
|
label={t("OnlineUsersWindow")}
|
|
value={String(windowMinutes) as "15" | "60"}
|
|
onChange={(w) => {
|
|
setWindowMinutes(Number(w) as OnlineWindow);
|
|
setPage(1);
|
|
}}
|
|
options={[
|
|
{ value: "15", label: t("OnlineUsersWindow15") },
|
|
{ value: "60", label: t("OnlineUsersWindow60") },
|
|
]}
|
|
/>
|
|
<FilterSearch
|
|
key={kind}
|
|
aria-label={t(kind === "ADMIN" ? "OnlineUsersSearchAdmins" : "OnlineUsersSearchMembers")}
|
|
placeholder={t(kind === "ADMIN" ? "OnlineUsersSearchAdmins" : "OnlineUsersSearchMembers")}
|
|
value={q}
|
|
onChange={(value) => {
|
|
setQ(value);
|
|
setPage(1);
|
|
}}
|
|
/>
|
|
</div>
|
|
|
|
{notice && (
|
|
<p role="status" className="text-sm text-muted-foreground">
|
|
{notice}
|
|
</p>
|
|
)}
|
|
{error && <ErrorState message={t("OnlineUsersLoadFailed")} onRetry={refetch} />}
|
|
|
|
<DataTable
|
|
label={t("OnlineUsers")}
|
|
columns={columns}
|
|
data={rows}
|
|
total={total}
|
|
page={page}
|
|
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
|
tableRef={tableRef}
|
|
onPageChange={setPage}
|
|
isLoading={loading && rows.length === 0}
|
|
rowKey={(r) => r.id}
|
|
empty={<EmptyState title={t(kind === "ADMIN" ? "OnlineUsersEmptyAdmins" : "OnlineUsersEmptyMembers")} />}
|
|
/>
|
|
|
|
{target && (
|
|
<SignOutDialog
|
|
kind={target.kind}
|
|
person={target.person}
|
|
onClose={() => setTarget(null)}
|
|
onDone={(person) => {
|
|
setTarget(null);
|
|
setNotice(t("OnlineUsersSignOutDone", { name: person.name || person.id }));
|
|
refetch();
|
|
}}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function OnlineUsersPageContent() {
|
|
const t = useT();
|
|
return (
|
|
<>
|
|
<PageHeader title={t("OnlineUsers")} />
|
|
<OnlineUsersContent />
|
|
</>
|
|
);
|
|
}
|
|
|
|
export default function OnlineUsersPage() {
|
|
return (
|
|
<RequireModule pathname="/online-users">
|
|
<OnlineUsersPageContent />
|
|
</RequireModule>
|
|
);
|
|
}
|