Files
co-lite/solvway-admin-portal/app/users/page.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

246 lines
8.9 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Pencil, Plus } from "lucide-react";
import type { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
import { DataTable } from "@/app/components/ui/data-table";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { PageHeader } from "@/app/components/ui/page-header";
import { RowActions } from "@/app/components/ui/row-actions";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { roleLabel } from "@/app/lib/roleLabel";
import { useListFilters } from "@/app/lib/hooks/useListFilters";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { listAdminUsers, sendAdminUserPasswordReset, USER_STATUS_FILTER_OPTIONS } from "@/app/lib/services/adminUsers";
import type { AdminUser } from "@/app/lib/types";
import { useTableSort } from "@/app/lib/hooks/useTableSort";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { MessageParams } from "@/app/lib/i18n/t";
const DEFAULTS = { q: "", enabled: "" };
function UsersPageContent() {
const t = useT();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
const { sorting, onSortingChange, sortBy, sortDir } = useTableSort();
const [data, setData] = useState<{ items: AdminUser[]; total: number }>({ items: [], total: 0 });
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [confirmReset, setConfirmReset] = useState<AdminUser | null>(null);
const [resetNotice, setResetNotice] = useState<{ code: string; params?: MessageParams } | null>(null);
const [resetError, setResetError] = useState<string | null>(null);
const [sending, setSending] = useState(false);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
async function confirmSendReset() {
if (!confirmReset?.id || sending) return;
setSending(true);
setResetError(null);
try {
const result = await sendAdminUserPasswordReset(confirmReset.id);
if (result.updated > 0) {
setResetNotice({ code: "UsrResetSent", params: { email: confirmReset.email } });
setConfirmReset(null);
} else {
// Upstream /user/resetAdminPassword returns 0 for a non-type-A user (or email
// mismatch). The list is scoped to type A, so a 0 here means the row is stale —
// surface it instead of claiming success.
setResetError("UsrResetNotAdmin");
}
} catch (err) {
setResetError(err instanceof Error ? err.message : "UsrResetFailed");
} finally {
setSending(false);
}
}
useEffect(() => {
if (pageSize == null) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the filter/page/reloadKey-triggered fetch below.
setLoading(true);
setError(null);
listAdminUsers({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir })
.then((result) => {
if (!cancelled) setData(result);
})
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : "UsrListLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [filters, page, reloadKey, pageSize, sortBy, sortDir]);
const statusOptions = useMemo(
() => USER_STATUS_FILTER_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
[t],
);
const columns = useMemo<ColumnDef<AdminUser, unknown>[]>(
() => [
{
accessorKey: "username",
header: t("Username"),
cell: ({ row }) => (
<Link href={`/users/${row.original.id}`} className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
{row.original.username}
</Link>
),
},
{ accessorKey: "name", header: t("Name") },
{ accessorKey: "email", header: t("Email") },
{
id: "roles",
accessorFn: () => null, // ponytail: id columns need an accessor to be sortable; server sorts
header: t("BO_ROLES"),
cell: ({ row }) => (
row.original.roles.length === 0 ? (
"—"
) : (
<div className="flex flex-wrap gap-1">
{row.original.roles.map((r) => (
<Badge key={r.id} variant="outline">
{roleLabel(r.name)}
</Badge>
))}
</div>
)
),
},
{
accessorKey: "enabled",
header: t("Status"),
cell: ({ row }) => (
<Badge variant={row.original.enabled ? "positive" : "neutral"}>
{row.original.enabled ? t("Enabled") : t("Disabled")}
</Badge>
),
},
{
id: "actions",
enableSorting: false,
header: t("CatActions"),
meta: { numeric: true },
cell: ({ row }) => (
<RowActions
label={row.original.username}
items={[{
label: t("UsrSendReset"),
onSelect: () => {
setConfirmReset(row.original);
setResetError(null);
setResetNotice(null);
},
}]}
>
<Button variant="ghost" size="sm" asChild className="h-8 px-2">
<Link href={`/users/${row.original.id}`} aria-label={t("UsrEditNamed", { username: row.original.username })}>
<Pencil aria-hidden="true" className="size-3.5" />
</Link>
</Button>
</RowActions>
),
},
],
[t],
);
return (
<>
<PageHeader
title={t("BO_USERS")}
actions={
<Button asChild>
<Link href="/users/new">
<Plus aria-hidden="true" className="size-4" />
{t("UsrAddUser")}
</Link>
</Button>
}
/>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
{resetNotice && (
<div role="alert" className="mb-4 rounded-md border border-primary/30 bg-primary/5 p-3 text-sm">
{t(resetNotice.code, resetNotice.params)}
</div>
)}
<FilterPanel activeCount={activeCount} onClear={clear}>
<FilterField label={t("UsrSearchLabel")}>
<FilterSearch className="w-full" aria-label={t("UsrSearchLabel")} placeholder={t("UsrSearchLabel")} value={filters.q} onChange={q => set({ q })} />
</FilterField>
<FilterField label={t("Status")}>
<FilterSelect className="w-full" aria-label={t("CatStatusFilter")} allLabel={t("AllStatuses")} options={statusOptions} value={filters.enabled} onChange={enabled => set({ enabled })} />
</FilterField>
</FilterPanel>
<DataTable
label={t("BO_USERS")}
columns={columns}
data={data.items}
total={data.total}
page={page}
pageSize={pageSize ?? MIN_PAGE_SIZE}
sorting={sorting}
onSortingChange={onSortingChange}
tableRef={tableRef}
onPageChange={setPage}
isLoading={loading}
rowKey={(u) => String(u.id ?? u.username)}
empty={<EmptyState title={activeCount > 0 ? t("UsrNoMatch") : t("UsrNoUsers")} />}
/>
{confirmReset && (
<Dialog open onOpenChange={(open) => !open && setConfirmReset(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("UsrSendResetTitle")}</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
{t("UsrResetConfirmBody", { email: confirmReset.email })}
</p>
{resetError && (
<div
role="alert"
className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive"
>
{t(resetError)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setConfirmReset(null)}>
{t("Cancel")}
</Button>
<Button onClick={confirmSendReset} disabled={sending}>
{t("Confirm")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
</>
);
}
export default function UsersPage() {
return (
<RequireModule pathname="/users">
<UsersPageContent />
</RequireModule>
);
}