This commit is contained in:
rgrgogu
2026-05-09 22:17:33 +08:00
parent ca6eae1d56
commit 1d94f27e61
28 changed files with 1863 additions and 220 deletions
@@ -0,0 +1,72 @@
// components/generic/Dashboard/BarBreakdown.jsx
import { BarChart, Bar, XAxis, YAxis, Tooltip, Cell, ResponsiveContainer } from "recharts";
const DEFAULT_COLORS = [
"#6366f1", "#22c55e", "#f59e0b", "#ef4444",
"#06b6d4", "#a855f7", "#ec4899", "#84cc16",
];
/**
* A horizontal bar chart card for ranked data.
*
* @param {Object} props
* @param {string} props.label Card title
* @param {Array} props.data [{ label, value }]
* @param {Function} [props.onBarClick] (entry) => void — called with the clicked bar
* @param {string[]} [props.colors]
* @param {number} [props.height] Default: 240
* @param {number} [props.yAxisWidth] Default: 130
* @param {string} [props.className]
*
* @example
* <BarBreakdown
* label="Top Groups by Members"
* data={breakdown.data}
* onBarClick={(entry) => navigate(`/admin/users/groups`)}
* />
*/
export function BarBreakdown({
label,
data = [],
onBarClick,
colors = DEFAULT_COLORS,
height = 240,
yAxisWidth = 130,
className = "",
}) {
if (!data.length) return null;
const isClickable = typeof onBarClick === "function";
return (
<div className={`bg-card border rounded-xl p-4 flex flex-col gap-2 ${className}`}>
<p className="text-sm font-medium">{label}</p>
<ResponsiveContainer width="100%" height={height}>
<BarChart
data={data}
layout="vertical"
margin={{ left: 0, right: 24, top: 4, bottom: 4 }}
onClick={isClickable ? ({ activePayload }) => {
if (activePayload?.[0]) onBarClick(activePayload[0].payload);
} : undefined}
style={isClickable ? { cursor: "pointer" } : undefined}
>
<XAxis type="number" tick={{ fontSize: 11 }} />
<YAxis
type="category"
dataKey="label"
tick={{ fontSize: 11 }}
width={yAxisWidth}
/>
<Tooltip />
<Bar dataKey="value" radius={[0, 4, 4, 0]}>
{data.map((_, i) => (
<Cell key={i} fill={colors[i % colors.length]} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
);
}
@@ -0,0 +1,74 @@
// components/generic/Dashboard/DashboardSection.jsx
import { StatGrid } from "./StatGrid";
import { PieBreakdown } from "./PieBreakdown";
import { BarBreakdown } from "./BarBreakdown";
/**
* Renders a titled section with a stat grid and breakdown charts.
*
* @param {Object} props
* @param {string} props.title
* @param {Array} props.stats [{ key, label, value, icon? }]
* @param {Array} [props.breakdowns] [{ key, label, chartType, data[] }]
* @param {Object} [props.iconMap] { [statKey]: <ReactNode> }
* @param {Object} [props.linkMap] { [statKey]: () => void } — stat card click handlers
* @param {Object} [props.chartLinkMap] { [breakdownKey]: (entry) => void } — chart segment click handlers
* @param {string} [props.className]
*
* @example
* <DashboardSection
* title="Users"
* stats={dashboard.users.stats}
* breakdowns={dashboard.users.breakdowns}
* iconMap={USER_ICON_MAP}
* linkMap={{
* total: () => navigate('/admin/users/all'),
* archived: () => navigate('/admin/users/all/archived'),
* }}
* chartLinkMap={{
* acc_type: (entry) => navigate(`/admin/users/all`),
* }}
* />
*/
export function DashboardSection({
title,
stats = [],
breakdowns = [],
iconMap = {},
linkMap = {},
chartLinkMap = {},
className = "",
}) {
return (
<section className={`flex flex-col gap-4 ${className}`}>
{title && <h2 className="text-base font-medium">{title}</h2>}
{stats.length > 0 && (
<StatGrid stats={stats} iconMap={iconMap} linkMap={linkMap} />
)}
{breakdowns.length > 0 && (
<div className={`grid gap-4 ${breakdowns.length > 1 ? "sm:grid-cols-2" : "grid-cols-1"}`}>
{breakdowns.map((b) =>
b.chartType === "bar" ? (
<BarBreakdown
key={b.key}
label={b.label}
data={b.data}
onBarClick={chartLinkMap[b.key]}
/>
) : (
<PieBreakdown
key={b.key}
label={b.label}
data={b.data}
onSliceClick={chartLinkMap[b.key]}
/>
)
)}
</div>
)}
</section>
);
}
@@ -0,0 +1,69 @@
// components/generic/Dashboard/PieBreakdown.jsx
import { PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer } from "recharts";
const DEFAULT_COLORS = [
"#6366f1", "#22c55e", "#f59e0b", "#ef4444",
"#06b6d4", "#a855f7", "#ec4899", "#84cc16",
];
/**
* A pie chart card for small-cardinality breakdowns.
*
* @param {Object} props
* @param {string} props.label Card title
* @param {Array} props.data [{ label, value }]
* @param {Function} [props.onSliceClick] (entry) => void — called with the clicked slice
* @param {string[]} [props.colors]
* @param {number} [props.height] Default: 220
* @param {string} [props.className]
*
* @example
* <PieBreakdown
* label="By Account Type"
* data={breakdown.data}
* onSliceClick={(entry) => navigate(`/admin/users/all?acc_type=${entry.label}`)}
* />
*/
export function PieBreakdown({
label,
data = [],
onSliceClick,
colors = DEFAULT_COLORS,
height = 220,
className = "",
}) {
if (!data.length) return null;
const isClickable = typeof onSliceClick === "function";
return (
<div className={`bg-card border rounded-xl p-4 flex flex-col gap-2 ${className}`}>
<p className="text-sm font-medium">{label}</p>
<ResponsiveContainer width="100%" height={height}>
<PieChart>
<Pie
data={data}
dataKey="value"
nameKey="label"
cx="50%"
cy="50%"
outerRadius={80}
label={({ label: l, percent }) =>
`${l} ${(percent * 100).toFixed(0)}%`
}
labelLine={false}
onClick={isClickable ? (entry) => onSliceClick(entry) : undefined}
cursor={isClickable ? "pointer" : undefined}
>
{data.map((_, i) => (
<Cell key={i} fill={colors[i % colors.length]} />
))}
</Pie>
<Tooltip formatter={(v, n) => [v, n]} />
<Legend />
</PieChart>
</ResponsiveContainer>
</div>
);
}
@@ -0,0 +1,49 @@
// components/generic/Dashboard/StatCard.jsx
/**
* A single metric card. Optionally clickable for navigation.
*
* @param {Object} props
* @param {string} props.label Display label
* @param {number|string} props.value Metric value
* @param {ReactNode} [props.icon] Optional icon
* @param {Function} [props.onClick] If provided, card becomes clickable
* @param {string} [props.className] Extra classes on the card
*
* @example
* <StatCard
* label="Total Users"
* value={128}
* icon={<Users className="size-5" />}
* onClick={() => navigate('/admin/users/all')}
* />
*/
export function StatCard({ label, value, icon, onClick, className = "" }) {
const isClickable = typeof onClick === "function";
return (
<div
role={isClickable ? "button" : undefined}
tabIndex={isClickable ? 0 : undefined}
onClick={isClickable ? onClick : undefined}
onKeyDown={isClickable ? (e) => e.key === "Enter" && onClick() : undefined}
className={`
bg-card border rounded-xl px-4 py-4 flex items-center gap-4
${isClickable ? "cursor-pointer hover:border-foreground/30 hover:bg-accent transition-colors" : ""}
${className}
`}
>
{icon && (
<div className="shrink-0 bg-muted rounded-lg p-2">
{icon}
</div>
)}
<div className="min-w-0">
<p className="text-[11px] uppercase tracking-wide text-muted-foreground truncate">
{label}
</p>
<p className="text-2xl font-semibold leading-tight">{value ?? 0}</p>
</div>
</div>
);
}
@@ -0,0 +1,36 @@
// components/generic/Dashboard/StatGrid.jsx
import { StatCard } from "./StatCard";
/**
* Renders a responsive grid of StatCards from a stats array.
*
* @param {Object} props
* @param {Array} props.stats [{ key, label, value, icon? }]
* @param {Object} [props.iconMap] { [key]: <ReactNode> }
* @param {Object} [props.linkMap] { [key]: () => void } — maps stat key → navigate callback
* @param {string} [props.className]
*
* @example
* const linkMap = {
* total: () => navigate('/admin/users/all'),
* active: () => navigate('/admin/users/all'),
* archived: () => navigate('/admin/users/all/archived'),
* };
* <StatGrid stats={dashboard.users.stats} iconMap={iconMap} linkMap={linkMap} />
*/
export function StatGrid({ stats = [], iconMap = {}, linkMap = {}, className = "" }) {
return (
<div className={`grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 ${className}`}>
{stats.map((s) => (
<StatCard
key={s.key}
label={s.label}
value={s.value}
icon={s.icon ?? iconMap[s.key]}
onClick={linkMap[s.key]}
/>
))}
</div>
);
}
@@ -0,0 +1,140 @@
// components/generic/Dashboard/TableDashboard.jsx
import { StatCard } from "./StatCard";
import { PieBreakdown } from "./PieBreakdown";
import { BarBreakdown } from "./BarBreakdown";
/**
* A dashboard strip rendered above a DataTable.
* Clicking any stat card or chart segment applies a filter to the table
* via tableRefsRef.current.setFilters([{ id, value }]).
*
* Clicking the same card/segment again clears that filter (toggle).
*
* @param {Object} props
* @param {Array} props.stats
* [{ key, label, value, icon?, filterId?, filterValue? }]
* - filterId: column id to filter on (e.g. "is_active")
* - filterValue: value array to apply (e.g. ["true"])
*
* @param {Array} props.breakdowns
* [{ key, label, chartType, filterId?, data: [{ label, value }] }]
* - filterId: column id for the breakdown (e.g. "acc_type")
* - Each data entry's `label` becomes the filterValue when clicked
*
* @param {Object} props.iconMap { [statKey]: <ReactNode> }
* @param {Array} props.activeFilters filtersRef.current — to highlight active items
* @param {Object} props.tableRefsRef ref with { setFilters, getFilters }
* @param {string} [props.className]
*
* @example — Users table
* <TableDashboard
* stats={dashboard.users.stats}
* breakdowns={dashboard.users.breakdowns}
* iconMap={USER_ICON_MAP}
* activeFilters={tableRefsRef.current.getFilters?.() ?? []}
* tableRefsRef={tableRefsRef}
* />
*/
export function TableDashboard({
stats = [],
breakdowns = [],
statMap = {},
tableRefsRef, // ← remove activeFilters prop entirely
className = "",
}) {
// ─── Always read live from ref ────────────────────────────────────────────
function getActiveFilters() {
return tableRefsRef?.current?.getFilters?.() ?? [];
}
function isFilterActive(filterId, filterValue) {
if (!filterId) return false;
const existing = getActiveFilters().find((f) => f.id === filterId);
if (!existing) return false;
if (!filterValue) return true;
return filterValue.every((v) => existing.value?.includes(v));
}
function toggleFilter(filterId, filterValue) {
if (!filterId || !tableRefsRef?.current?.setFilters) return;
const managedIds = new Set([
...stats.map((s) => s.filterId),
...breakdowns.map((b) => b.filterId),
].filter(Boolean));
const current = getActiveFilters();
const existing = current.find((f) => f.id === filterId);
const isActive = existing &&
(!filterValue || filterValue.every((v) => existing.value?.includes(v)));
const unrelated = current.filter((f) => !managedIds.has(f.id));
if (isActive) {
tableRefsRef.current.setFilters(unrelated);
} else {
tableRefsRef.current.setFilters([
...unrelated,
{ id: filterId, value: filterValue ?? [] },
]);
}
}
function handleStatClick(stat) {
if (!stat.filterId) return;
toggleFilter(stat.filterId, stat.filterValue);
}
function handleChartClick(breakdown, entry) {
if (!breakdown.filterId) return;
toggleFilter(breakdown.filterId, [String(entry.label)]);
}
if (!stats.length && !breakdowns.length) return null;
return (
<div className={`flex flex-col gap-4 mb-4 ${className}`}>
{stats.length > 0 && (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
{stats.map((s) => {
const active = isFilterActive(s.filterId, s.filterValue);
const mapping = statMap[s.key] ?? {};
return (
<StatCard
key={s.key}
label={mapping.label ?? s.label}
value={s.value}
icon={mapping.icon}
onClick={s.filterId ? () => handleStatClick(s) : undefined}
className={active ? "ring-2 ring-primary border-primary" : ""}
/>
);
})}
</div>
)}
{breakdowns.length > 0 && (
<div className={`grid gap-4 ${breakdowns.length > 1 ? "sm:grid-cols-2" : "grid-cols-1"}`}>
{breakdowns.map((b) =>
b.chartType === "bar" ? (
<BarBreakdown
key={b.key}
label={b.label}
data={b.data}
onBarClick={b.filterId ? (entry) => handleChartClick(b, entry) : undefined}
/>
) : (
<PieBreakdown
key={b.key}
label={b.label}
data={b.data}
onSliceClick={b.filterId ? (entry) => handleChartClick(b, entry) : undefined}
/>
)
)}
</div>
)}
</div>
);
}
+216
View File
@@ -0,0 +1,216 @@
// components/generic/Sheet/AddUsersSheet.jsx
import { useState, useEffect, useMemo } from "react";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { Spinner } from "@/components/ui/spinner";
/**
* Generic sheet for selecting and adding users to any entity
* (groups, tasks, projects, etc.)
*
* @param {Object} props
* @param {boolean} props.open
* @param {Function} props.onOpenChange
*
* @param {string} [props.title] Sheet heading. Default: "Add members"
* @param {string} [props.submitLabel] Submit button label. Default: "Add"
*
* @param {Array} props.users [{ [idKey], [labelKey] }] — list to display
* @param {boolean} props.loading
* @param {Function} props.onFetch Called on open to (re)load the list
*
* @param {string} [props.idKey] Key for the user id. Default: "user_id"
* @param {string} [props.labelKey] Key for the display name. Default: "full_name"
* @param {string} [props.subLabelKey] Optional secondary line (e.g. "email")
*
* @param {Function} props.onSubmit Called with selected ids[]
*
* @example — groups
* <AddUsersSheet
* title="Add members"
* users={usersNotIn}
* onFetch={() => fetchUsersNotInGroup(gid)}
* onSubmit={(ids) => addUsersToGroup(gid, ids)}
* ...
* />
*
* @example — tasks
* <AddUsersSheet
* title="Assign users"
* users={unassignedUsers}
* onFetch={() => fetchUnassignedUsers(taskId)}
* onSubmit={(ids) => assignUsersToTask(taskId, ids)}
* idKey="user_id"
* labelKey="full_name"
* subLabelKey="email"
* ...
* />
*/
export function AddSheet({
open,
onOpenChange,
title = "Add members",
submitLabel = "Add",
users = [],
loading = false,
onFetch,
idKey = "user_id",
labelKey = "full_name",
subLabelKey = null,
onSubmit,
}) {
const [search, setSearch] = useState("");
const [selected, setSelected] = useState([]);
useEffect(() => {
if (open) {
onFetch?.();
setSearch("");
setSelected([]);
}
}, [open]);
const filtered = useMemo(() => {
if (!search.trim()) return users;
return users.filter((u) =>
String(u[labelKey] ?? "").toLowerCase().includes(search.toLowerCase())
);
}, [search, users, labelKey]);
const toggle = (id) =>
setSelected((prev) =>
prev.includes(id) ? prev.filter((v) => v !== id) : [...prev, id]
);
const toggleAll = () => {
const allIds = filtered.map((u) => u[idKey]);
const allSelected = allIds.every((id) => selected.includes(id));
setSelected((prev) =>
allSelected
? prev.filter((id) => !allIds.includes(id))
: [...new Set([...prev, ...allIds])]
);
};
const allFilteredSelected =
filtered.length > 0 && filtered.every((u) => selected.includes(u[idKey]));
async function handleSubmit() {
if (!selected.length) return;
await onSubmit(selected);
onOpenChange(false);
}
function handleClose() {
setSearch("");
setSelected([]);
onOpenChange(false);
}
return (
<Sheet open={open} onOpenChange={handleClose}>
{/*
SheetContent is a flex column with fixed height (100dvh).
We split it into 3 rows: header (shrink-0), body (flex-1 overflow-hidden), footer (shrink-0).
The body itself is a flex column — search and select-all shrink, list overflows.
*/}
<SheetContent side="right" className="w-[400px] flex flex-col h-full p-0">
{/* Header */}
<SheetHeader className="shrink-0 border-b px-6 py-4">
<SheetTitle>{title}</SheetTitle>
</SheetHeader>
{/* Body — fills remaining space, clips overflow */}
<div className="flex-1 min-h-0 flex flex-col gap-3 px-6 py-4 relative">
{loading && (
<div className="absolute inset-0 flex items-center justify-center bg-background/60 backdrop-blur-sm z-10">
<Spinner className="size-8" />
</div>
)}
{/* Search — fixed height */}
<div className="shrink-0">
<Input
placeholder="Search..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{/* Select all — fixed height */}
{filtered.length > 0 && (
<label className="shrink-0 flex items-center gap-2 text-sm font-medium cursor-pointer select-none border-b pb-3">
<input
type="checkbox"
checked={allFilteredSelected}
onChange={toggleAll}
/>
Select all ({filtered.length})
</label>
)}
{/* Scrollable list — takes all remaining space */}
<div className="flex-1 min-h-0 overflow-y-auto">
<div className="space-y-1 pr-1">
{!loading && filtered.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-6">
{search ? `No results for "${search}".` : "No users available."}
</p>
) : (
filtered.map((user) => {
const id = user[idKey];
const label = user[labelKey];
const sub = subLabelKey ? user[subLabelKey] : null;
return (
<label
key={id}
className="flex items-center gap-3 p-1 rounded-md hover:bg-muted cursor-pointer text-sm select-none"
>
<input
type="checkbox"
checked={selected.includes(id)}
onChange={() => toggle(id)}
/>
<div className="flex flex-col min-w-0">
<span className="truncate">{label}</span>
{sub && (
<span className="text-xs text-muted-foreground truncate">
{sub}
</span>
)}
</div>
</label>
);
})
)}
</div>
</div>
</div>
{/* Footer */}
<div className="shrink-0 flex gap-2 border-t px-6 py-4">
<Button variant="outline" className="flex-1" onClick={handleClose}>
Cancel
</Button>
<Button
className="flex-1"
disabled={!selected.length || loading}
onClick={handleSubmit}
>
{selected.length > 0 ? `${submitLabel} (${selected.length})` : submitLabel}
</Button>
</div>
</SheetContent>
</Sheet>
);
}
+86 -56
View File
@@ -1,4 +1,4 @@
import { useState, useMemo, useRef, useEffect } from "react";
import { useState, useMemo, useRef, useEffect, useCallback } from "react";
import { useReactTable, getCoreRowModel, flexRender, } from "@tanstack/react-table";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table";
import { Spinner } from "@/components/ui/spinner";
@@ -35,31 +35,62 @@ export default function DataTable({
}) {
// ─── Refs — always hold latest filters and sort ───────────────────────────
const filtersRef = useRef([]);
const sortRef = useRef([]);
const sortRef = useRef([]);
// ─── State ────────────────────────────────────────────────────────────────
const [activeColumn, setActiveColumn] = useState(null);
const [sorting, setSorting] = useState([]);
const [columnFilters, setColumnFilters] = useState([]);
const [columnVisibility, setColumnVisibility] = useState({});
const [rowSelection, setRowSelection] = useState({});
const [filterState, setFilterState] = useState({
const [activeColumn, setActiveColumn] = useState(null);
const [sorting, setSorting] = useState([]);
const [columnFilters, setColumnFilters] = useState([]);
const [columnVisibility, setColumnVisibility] = useState({});
const [rowSelection, setRowSelection] = useState({});
const [filterState, setFilterState] = useState({
open: false, column: null, attr: null, data: [],
});
const activeFilters = columnFilters.filter((f) => f.value !== "");
// ─── Initial fetch on mount only ─────────────────────────────────────────
// ─── setFilters — called externally by dashboard charts ──────────────────
// Merges incoming filters with existing ones (replaces by id, appends new).
// Pass an empty array [] to clear all filters.
const setFilters = useCallback((incomingFilters) => {
setColumnFilters((prev) => {
let next;
if (!incomingFilters.length) {
next = [];
} else {
// Replace matching ids, keep the rest
const incomingIds = new Set(incomingFilters.map((f) => f.id));
const kept = prev.filter((f) => !incomingIds.has(f.id));
next = [...kept, ...incomingFilters];
}
const newFilters = next.filter((f) => f.value !== "");
filtersRef.current = newFilters;
onFetch({
page: 1,
limit: pagination.limit,
filters: newFilters,
sort: sortRef.current,
});
return next;
});
}, [onFetch, pagination.limit]);
// ─── Expose refs to parent ────────────────────────────────────────────────
useEffect(() => {
onRefsReady?.({
getFilters: () => filtersRef.current,
getSort: () => sortRef.current,
resetSelection: () => table.resetRowSelection(), // ← expose this
getFilters: () => filtersRef.current,
getSort: () => sortRef.current,
resetSelection: () => table.resetRowSelection(),
setFilters, // ← new
});
onFetch({ page: 1, limit: pagination.limit, filters: [], sort: [] });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [setFilters]);
const handleOpenFilterSheet = async (e, column, attr) => {
e.preventDefault();
@@ -79,61 +110,60 @@ export default function DataTable({
rowSelection,
pagination: {
pageIndex: pagination.page - 1,
pageSize: pagination.limit,
pageSize: pagination.limit,
},
},
enableRowSelection: true,
onRowSelectionChange: setRowSelection,
manualPagination: true,
manualSorting: true,
manualFiltering: true,
pageCount: pagination.totalPages,
enableRowSelection: true,
onRowSelectionChange: setRowSelection,
manualPagination: true,
manualSorting: true,
manualFiltering: true,
pageCount: pagination.totalPages,
// ─── Sort change ────────────────────────────────────────────────────────
// ─── Sort change ──────────────────────────────────────────────────────
onSortingChange: (updater) => {
const next = typeof updater === "function" ? updater(sorting) : updater;
const next = typeof updater === "function" ? updater(sorting) : updater;
const newSort = next.length ? [{ id: next[0].id, desc: next[0].desc }] : [];
setSorting(next);
sortRef.current = newSort;
onFetch({
page: 1,
limit: pagination.limit,
page: 1,
limit: pagination.limit,
filters: filtersRef.current,
sort: newSort,
sort: newSort,
});
},
// ─── Filter change ──────────────────────────────────────────────────────
// ─── Filter change ────────────────────────────────────────────────────
onColumnFiltersChange: (updater) => {
const next = typeof updater === "function" ? updater(columnFilters) : updater;
const next = typeof updater === "function" ? updater(columnFilters) : updater;
const newFilters = next.filter((f) => f.value !== "");
setColumnFilters(next);
filtersRef.current = newFilters;
onFetch({
page: 1,
limit: pagination.limit,
page: 1,
limit: pagination.limit,
filters: newFilters,
sort: sortRef.current,
sort: sortRef.current,
});
},
onColumnVisibilityChange: setColumnVisibility,
getCoreRowModel: getCoreRowModel(),
getCoreRowModel: getCoreRowModel(),
});
// ─── Single handler for all page changes ──────────────────────────────────────
// ─── Page change ──────────────────────────────────────────────────────────
const handlePageChange = (page) => {
setPagination((p) => ({ ...p, page }));
onFetch({
page,
limit: pagination.limit,
limit: pagination.limit,
filters: filtersRef.current,
sort: sortRef.current,
sort: sortRef.current,
});
};
@@ -169,7 +199,7 @@ export default function DataTable({
onFetch({ page: 1, limit: pagination.limit, filters: [], sort: sortRef.current });
}}
onRemove={(id) => {
const next = columnFilters.filter((c) => c.id !== id);
const next = columnFilters.filter((c) => c.id !== id);
const newFilters = next.filter((f) => f.value !== "");
setColumnFilters(next);
filtersRef.current = newFilters;
@@ -187,7 +217,7 @@ export default function DataTable({
filters={activeFilters}
attributes={attributes}
onRemove={(id) => {
const next = columnFilters.filter((c) => c.id !== id);
const next = columnFilters.filter((c) => c.id !== id);
const newFilters = next.filter((f) => f.value !== "");
setColumnFilters(next);
filtersRef.current = newFilters;
@@ -204,8 +234,8 @@ export default function DataTable({
<TableRow key={hg.id} className="bg-muted/40 hover:bg-muted/40">
{hg.headers.map((header) => {
const isPinned = header.column.getIsPinned();
const attr = header.column.columnDef.meta?.attr;
const isPlain = header.column.id === "select" || header.column.id === "actions";
const attr = header.column.columnDef.meta?.attr;
const isPlain = header.column.id === "select" || header.column.id === "actions";
return (
<TableHead
@@ -213,10 +243,10 @@ export default function DataTable({
className={cn("align-middle whitespace-nowrap", isPinned ? "bg-muted" : "")}
style={{
position: isPinned ? "sticky" : "relative",
right: isPinned === "right" ? header.column.getStart("right") : undefined,
left: isPinned === "left" ? header.column.getStart("left") : undefined,
zIndex: isPinned ? 2 : 0,
width: header.column.columnDef.size,
right: isPinned === "right" ? header.column.getStart("right") : undefined,
left: isPinned === "left" ? header.column.getStart("left") : undefined,
zIndex: isPinned ? 2 : 0,
width: header.column.columnDef.size,
}}
>
{isPlain ? (
@@ -238,11 +268,11 @@ export default function DataTable({
</TableHeader>
{renderFilterSheet?.({
open: filterState.open,
open: filterState.open,
onOpenChange: (v) => setFilterState((p) => ({ ...p, open: v })),
column: filterState.column,
attr: filterState.attr,
data: filterState.data,
column: filterState.column,
attr: filterState.attr,
data: filterState.data,
loading,
})}
@@ -271,9 +301,9 @@ export default function DataTable({
className={cn("m-0", isPinned && "bg-card")}
style={{
position: isPinned ? "sticky" : "relative",
right: isPinned === "right" ? 0 : undefined,
left: isPinned === "left" ? cell.column.getStart("left") : undefined,
zIndex: isPinned ? 1 : 0,
right: isPinned === "right" ? 0 : undefined,
left: isPinned === "left" ? cell.column.getStart("left") : undefined,
zIndex: isPinned ? 1 : 0,
}}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
@@ -298,16 +328,16 @@ export default function DataTable({
<TablePagination
table={table}
pagination={pagination}
onPageChange={handlePageChange} // ← replaces setPagination
onPageChange={handlePageChange}
totalRecords={pagination.totalRecords}
rowCount={data.length}
onPageSizeChange={(size) => {
setPagination((p) => ({ ...p, limit: size, page: 1 })); // ← updates your state
setPagination((p) => ({ ...p, limit: size, page: 1 }));
onFetch({
page: 1,
limit: size,
page: 1,
limit: size,
filters: filtersRef.current,
sort: sortRef.current,
sort: sortRef.current,
});
}}
pageSizeOptions={pageSizeOptions}
+64
View File
@@ -0,0 +1,64 @@
import { createContext, useCallback, useContext, useState } from "react";
import api from "@/utils/api.util";
import { toast } from "sonner";
const AdminDashboardContext = createContext(null);
export function useDashboard() {
const ctx = useContext(AdminDashboardContext);
if (!ctx) throw new Error("useDashboard must be used within a DashboardProvider");
return ctx;
}
export function AdminDashboardProvider({ children }) {
const [usersDashboard, setUsersDashboard] = useState(null);
const [groupsDashboard, setGroupsDashboard] = useState(null);
const [loading, setLoading] = useState(false);
const request = useCallback(async (fn) => {
setLoading(true);
try {
return await fn();
} catch (err) {
const message = err?.response?.data?.message ?? "Something went wrong.";
toast.error(message);
return null;
} finally {
setLoading(false);
}
}, []);
// ─── GET /api/admin/dashboard/users ───────────────────────────────────────
const fetchUsersDashboard = useCallback(
() =>
request(async () => {
const res = await api.get("/admin/dashboard/users");
setUsersDashboard(res.data?.data ?? null);
return res.data;
}),
[request]
);
// ─── GET /api/admin/dashboard/groups ──────────────────────────────────────
const fetchGroupsDashboard = useCallback(
() =>
request(async () => {
const res = await api.get("/admin/dashboard/groups");
setGroupsDashboard(res.data?.data ?? null);
return res.data;
}),
[request]
);
return (
<AdminDashboardContext.Provider value={{
usersDashboard,
groupsDashboard,
loading,
fetchUsersDashboard,
fetchGroupsDashboard,
}}>
{children}
</AdminDashboardContext.Provider>
);
}
+8 -5
View File
@@ -1,13 +1,16 @@
// ─── AdminProvider.jsx ─────────────────────────────────────────────────────────
import { AdminDashboardProvider } from "../AdminDashboardContext"
import { UserProvider } from "../AdminUserContext";
import { UserGroupProvider } from "../AdminUserGroupContext";
export const AdminProvider = ({ children }) => {
return (
<UserProvider>
<UserGroupProvider>
{children}
</UserGroupProvider>
</UserProvider>
<AdminDashboardProvider>
<UserProvider>
<UserGroupProvider>
{children}
</UserGroupProvider>
</UserProvider>
</AdminDashboardProvider>
);
};
+30
View File
@@ -0,0 +1,30 @@
// modules/admin/data/dashboard.data.jsx
//
// Centralizes all icon maps, link maps, and chart link maps for the
// admin dashboard. To add a new section (e.g. Tasks), just add a new
// export block here and import it in UsersDashboard.jsx.
import {
Users, UserCheck, UserMinus, ShieldCheck,
Archive, FolderOpen, Layers,
} from "lucide-react";
// ─── Users ───────────────────────────────────────────────────────────────────
export const USER_STAT_MAP = {
total: { label: "Total Users", icon: <Users className="size-5 text-muted-foreground" /> },
active: { label: "Active", icon: <UserCheck className="size-5 text-green-500" /> },
inactive: { label: "Inactive", icon: <UserMinus className="size-5 text-red-400" /> },
verified: { label: "Verified", icon: <ShieldCheck className="size-5 text-blue-500" /> },
archived: { label: "Archived", icon: <Archive className="size-5 text-muted-foreground" /> },
};
// ─── User Groups ──────────────────────────────────────────────────────────────
export const GROUP_STAT_MAP = {
total: { label: "Total Groups", icon: <Layers className="size-5 text-muted-foreground" /> },
active: { label: "Active", icon: <UserCheck className="size-5 text-green-500" /> },
inactive: { label: "Inactive", icon: <UserMinus className="size-5 text-red-400" /> },
archived: { label: "Archived", icon: <Archive className="size-5 text-muted-foreground" /> },
empty: { label: "Empty Groups", icon: <FolderOpen className="size-5 text-amber-500" /> },
};
@@ -0,0 +1,110 @@
// modules/admin/components/user_groups/AddGroupDialog.jsx
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
const schema = z.object({
name: z.string().min(1, "Name is required."),
description: z.string().min(1, "Description is required."),
});
/**
* Dialog for creating a new group.
* Matches context: createGroup({ name, description })
*
* @param {Object} props
* @param {boolean} props.open
* @param {Function} props.onOpenChange
* @param {Function} props.onSubmit Called with { name, description }
* @param {boolean} [props.loading]
*/
export function AddGroupDialog({ open, onOpenChange, onSubmit, loading }) {
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
defaultValues: { name: "", description: "" },
});
async function onValid(values) {
await onSubmit(values);
reset();
}
function handleClose() {
reset();
onOpenChange(false);
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[440px]">
<DialogHeader>
<DialogTitle>Add group</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onValid)} className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="name">
Name <span className="text-destructive">*</span>
</Label>
<Input
id="name"
placeholder="Group name"
{...register("name")}
/>
{errors.name && (
<p className="text-sm text-destructive">{errors.name.message}</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="description">
Description <span className="text-destructive">*</span>
</Label>
<Textarea
id="description"
placeholder="Brief description of this group"
className="resize-none"
rows={3}
{...register("description")}
/>
{errors.description && (
<p className="text-sm text-destructive">{errors.description.message}</p>
)}
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={handleClose}
disabled={loading}
>
Cancel
</Button>
<Button type="submit" disabled={loading}>
{loading ? "Creating..." : "Add group"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,114 @@
// modules/admin/components/user_groups/EditGroupDialog.jsx
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
const schema = z.object({
name: z.string().min(1, "Name is required."),
description: z.string().min(1, "Description is required."),
});
/**
* Dialog for editing a group's name and description.
* Matches context: updateGroup(gid, { name, description })
*
* `group` is the full row object from the table — pre-fills name + description.
* `values` re-syncs whenever `group` prop changes.
*
* @param {Object} props
* @param {boolean} props.open
* @param {Function} props.onOpenChange
* @param {Object} props.group Row object: { group_id, name, description, ... }
* @param {Function} props.onSubmit Called with { name, description }
* @param {boolean} [props.loading]
*/
export function EditGroupDialog({ open, onOpenChange, group, onSubmit, loading }) {
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
values: {
name: group?.name ?? "",
description: group?.description ?? "",
},
});
async function onValid(values) {
await onSubmit(values);
}
function handleClose() {
reset();
onOpenChange(false);
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[440px]">
<DialogHeader>
<DialogTitle>Edit group</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onValid)} className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="edit-name">
Name <span className="text-destructive">*</span>
</Label>
<Input
id="edit-name"
{...register("name")}
/>
{errors.name && (
<p className="text-sm text-destructive">{errors.name.message}</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="edit-description">
Description <span className="text-destructive">*</span>
</Label>
<Textarea
id="edit-description"
className="resize-none"
rows={3}
{...register("description")}
/>
{errors.description && (
<p className="text-sm text-destructive">{errors.description.message}</p>
)}
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={handleClose}
disabled={loading}
>
Cancel
</Button>
<Button type="submit" disabled={loading}>
{loading ? "Saving..." : "Save changes"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -1,121 +1,202 @@
import { useMemo, useRef, useState } from "react";
// modules/admin/components/user_groups/GroupTable.jsx
import { useMemo, useRef, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useUserGroups } from "@/contexts/AdminUserGroupContext";
import { useDashboard } from "@/contexts/AdminDashboardContext";
import DataTable from "@/components/generic/Table/DataTable";
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
import { TableDashboard } from "@/components/generic/Dashboard/TableDashboard";
import { AddGroupDialog } from "./AddGroupDialog";
import { EditGroupDialog } from "./EditGroupDialog";
import { buildDataColumns, columnPinning } from "../../config/user_groups/columns.config";
import { buildToolbarActions } from "../../config/user_groups/toolbar.config";
import { buildSelectionActions } from "../../config/user_groups/selection.config";
import { buildRowActions } from "../../config/user_groups/rowActions.config";
import { GROUP_STAT_MAP } from "@/data/adminDashboard.data";
import { getTimestamp } from "@/utils/timestamp.util";
export default function GroupTable() {
const [archiveTarget, setArchiveTarget] = useState(null); // single: row object
const [archiveIds, setArchiveIds] = useState(null); // bulk: array of ids
const tableRefsRef = useRef({ getFilters: () => [], getSort: () => [], resetSelection: () => {} });
const navigate = useNavigate();
const [createOpen, setCreateOpen] = useState(false);
const [editTarget, setEditTarget] = useState(null);
const [archiveTarget, setArchiveTarget] = useState(null);
const [archiveIds, setArchiveIds] = useState(null);
const {
groups,
attributes,
pagination,
setPagination,
loading,
fetchGroups,
fetchGroupFieldValues,
deactivateGroup,
deactivateGroups,
} = useUserGroups();
const tableRefsRef = useRef({
getFilters: () => [],
getSort: () => [],
resetSelection: () => { },
setFilters: () => { },
});
const exportConfig = {
allData: groups,
attributes,
filename: `${getTimestamp()}_UserGroups`,
sheetName: "UserGroups",
};
const navigate = useNavigate();
const rowActions = buildRowActions({
navigate,
onArchive: (row) => setArchiveTarget(row),
});
const {
groups, attributes, pagination, setPagination, loading,
fetchGroups, fetchGroupFieldValues,
createGroup, updateGroup, deactivateGroup, deactivateGroups,
} = useUserGroups();
const toolbarActions = buildToolbarActions({
fetchGroups, pagination, exportConfig, navigate,
getFilters: () => tableRefsRef.current.getFilters(),
getSort: () => tableRefsRef.current.getSort(),
});
const { groupsDashboard, fetchGroupsDashboard } = useDashboard();
const selectionActions = buildSelectionActions({
exportConfig,
archiveGroup: (row) => setArchiveTarget(row), // single
archiveGroups: (ids) => setArchiveIds(ids), // bulk
});
useEffect(() => {
fetchGroupsDashboard();
}, []);
const columns = useMemo(() => buildDataColumns(attributes, rowActions), [attributes]);
// ─── Keep activeFilters in sync for highlight ─────────────────────────────
const handleRefsReady = (refs) => {
tableRefsRef.current = refs; // ← no override needed
};
const handleArchiveSuccess = () => {
setArchiveTarget(null);
setArchiveIds(null);
tableRefsRef.current.resetSelection?.();
fetchGroups({ page: 1, limit: pagination.limit });
};
const exportConfig = {
allData: groups,
attributes,
filename: `${getTimestamp()}_UserGroups`,
sheetName: "UserGroups",
};
return (
<>
<DataTable
title="User Groups"
data={groups}
columns={columns}
attributes={attributes}
pagination={pagination}
setPagination={setPagination}
loading={loading}
onFetch={fetchGroups}
onFetchFilterData={fetchGroupFieldValues}
onRefsReady={(refs) => tableRefsRef.current = refs}
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
<FilterSheet
open={open}
onOpenChange={onOpenChange}
column={column}
attr={attr}
data={data}
loading={loading}
/>
)}
columnPinning={columnPinning}
toolbarActions={toolbarActions}
selectionActions={selectionActions}
recordLabel="group"
emptyMessage="No user groups match the current filters."
/>
const rowActions = buildRowActions({
navigate,
onEdit: (row) => setEditTarget(row),
onArchive: (row) => setArchiveTarget(row),
});
{/* Single archive */}
<ArchiveDialog
open={!!archiveTarget}
onOpenChange={(v) => !v && setArchiveTarget(null)}
entity={archiveTarget}
entityLabel="Group"
getName={(g) => g?.name}
onArchive={(g) => deactivateGroup(g?.group_id)}
loading={loading}
onSuccess={handleArchiveSuccess}
/>
const toolbarActions = buildToolbarActions({
fetchGroups, pagination, exportConfig, navigate,
onAddGroup: () => setCreateOpen(true),
getFilters: () => tableRefsRef.current.getFilters(),
getSort: () => tableRefsRef.current.getSort(),
});
{/* Bulk archive */}
<ArchiveDialog
open={!!archiveIds}
onOpenChange={(v) => !v && setArchiveIds(null)}
ids={archiveIds ?? []}
entityLabel="Group"
onArchive={deactivateGroups}
loading={loading}
onSuccess={handleArchiveSuccess}
/>
</>
);
const selectionActions = buildSelectionActions({
exportConfig,
archiveGroup: (row) => setArchiveTarget(row),
archiveGroups: (ids) => setArchiveIds(ids),
});
const columns = useMemo(
() => buildDataColumns(attributes, rowActions),
[attributes],
);
const handleArchiveSuccess = () => {
setArchiveTarget(null);
setArchiveIds(null);
tableRefsRef.current.resetSelection?.();
fetchGroups({ page: 1, limit: pagination.limit });
fetchGroupsDashboard();
};
// ─── Attach filterId + filterValue to each stat ───────────────────────────
// "archived" and "empty" have no direct column to filter on in this table
const dashboardStats = (groupsDashboard?.stats ?? []).map((s) => ({
...s,
filterId: s.key === "archived" || s.key === "empty" || s.key === "total" ? null : "is_active",
filterValue: s.key === "active" ? ["true"]
: s.key === "inactive" ? ["false"]
: null,
}));
// ─── top_groups bar has no filterable column in this table ────────────────
const dashboardBreakdowns = (groupsDashboard?.breakdowns ?? []).map((b) => ({
...b,
filterId: null,
}));
return (
<>
{/* ── Dashboard strip ── */}
{groupsDashboard && ( // ← was dashboard?.groups
<TableDashboard
stats={dashboardStats}
breakdowns={dashboardBreakdowns}
statMap={GROUP_STAT_MAP}
tableRefsRef={tableRefsRef}
/>
)}
{/* ── Data table ── */}
<DataTable
title="User Groups"
data={groups}
columns={columns}
attributes={attributes}
pagination={pagination}
setPagination={setPagination}
loading={loading}
onFetch={fetchGroups}
onFetchFilterData={fetchGroupFieldValues}
onRefsReady={handleRefsReady}
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
<FilterSheet
open={open}
onOpenChange={onOpenChange}
column={column}
attr={attr}
data={data}
loading={loading}
/>
)}
columnPinning={columnPinning}
toolbarActions={toolbarActions}
selectionActions={selectionActions}
recordLabel="group"
emptyMessage="No user groups match the current filters."
/>
{/* Add group */}
<AddGroupDialog
open={createOpen}
onOpenChange={setCreateOpen}
loading={loading}
onSubmit={async (values) => {
await createGroup(values);
setCreateOpen(false);
fetchGroups({ page: 1, limit: pagination.limit });
fetchGroupsDashboard();
}}
/>
{/* Edit group */}
<EditGroupDialog
open={!!editTarget}
onOpenChange={(v) => !v && setEditTarget(null)}
group={editTarget}
loading={loading}
onSubmit={async (values) => {
await updateGroup(editTarget?.group_id, values);
setEditTarget(null);
fetchGroups({ page: 1, limit: pagination.limit });
}}
/>
{/* Single archive */}
<ArchiveDialog
open={!!archiveTarget}
onOpenChange={(v) => !v && setArchiveTarget(null)}
entity={archiveTarget}
entityLabel="Group"
getName={(g) => g?.name}
onArchive={(g) => deactivateGroup(g?.group_id)}
loading={loading}
onSuccess={handleArchiveSuccess}
/>
{/* Bulk archive */}
<ArchiveDialog
open={!!archiveIds}
onOpenChange={(v) => !v && setArchiveIds(null)}
ids={archiveIds ?? []}
entityLabel="Group"
onArchive={deactivateGroups}
loading={loading}
onSuccess={handleArchiveSuccess}
/>
</>
);
}
@@ -1,37 +1,53 @@
import { useMemo, useRef, useState } from "react";
// modules/admin/components/users/UsersTable.jsx
import { useMemo, useRef, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useUsers } from "@/contexts/AdminUserContext";
import { useDashboard } from "@/contexts/AdminDashboardContext";
import DataTable from "@/components/generic/Table/DataTable";
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
import { TableDashboard } from "@/components/generic/Dashboard/TableDashboard";
import { buildDataColumns, columnPinning } from "../../config/users/columns.config";
import { buildToolbarActions } from "../../config/users/toolbar.config";
import { buildSelectionActions } from "../../config/users/selection.config";
import { buildRowActions } from "../../config/users/rowActions.config";
import { USER_STAT_MAP } from "@/data/adminDashboard.data";
import { getTimestamp } from "@/utils/timestamp.util";
export default function UsersTable() {
const [archiveTarget, setArchiveTarget] = useState(null); // single: row object
const [archiveIds, setArchiveIds] = useState(null); // bulk: array of ids
const tableRefsRef = useRef({ getFilters: () => [], getSort: () => [], resetSelection: () => { } });
const [archiveTarget, setArchiveTarget] = useState(null);
const [archiveIds, setArchiveIds] = useState(null);
const tableRefsRef = useRef({
getFilters: () => [],
getSort: () => [],
resetSelection: () => { },
setFilters: () => { },
});
const navigate = useNavigate();
const {
users,
attributes,
pagination,
setPagination,
loading,
fetchUsers,
fetchUserFieldValues,
deactivateUser,
deactivateUsers,
users, attributes, pagination, setPagination, loading,
fetchUsers, fetchUserFieldValues, deactivateUser, deactivateUsers,
} = useUsers();
// Shared export config — passed into toolbar + selection configs
const { usersDashboard, fetchUsersDashboard } = useDashboard();
useEffect(() => {
fetchUsersDashboard();
}, []);
// ─── Keep activeFilters in sync so TableDashboard can highlight active ────
const handleRefsReady = (refs) => {
tableRefsRef.current = refs; // ← just store directly, no override needed
};
const exportConfig = {
allData: users,
attributes,
@@ -47,20 +63,58 @@ export default function UsersTable() {
});
const selectionActions = buildSelectionActions({
exportConfig,
archiveUser: (row) => setArchiveTarget(row), // single
archiveUsers: (ids) => setArchiveIds(ids), // bulk
archiveUser: (row) => setArchiveTarget(row),
archiveUsers: (ids) => setArchiveIds(ids),
});
const columns = useMemo(() => buildDataColumns(attributes, rowActions), [attributes]);
const handleArchiveSuccess = () => {
setArchiveTarget(null);
setArchiveIds(null);
tableRefsRef.current.resetSelection?.(); // ← clear selection
tableRefsRef.current.resetSelection?.();
fetchUsers({ page: 1, limit: pagination.limit });
fetchUsersDashboard();
};
// ─── Attach filterId + filterValue to each stat so TableDashboard
// knows which column/value to apply when clicked ──────────────────────
const dashboardStats = (usersDashboard?.stats ?? []).map((s) => ({ // ← was dashboard?.users?.stats
...s,
filterId: s.key === "archived" || s.key === "total" ? null : "is_active",
filterValue: s.key === "active" ? ["true"]
: s.key === "inactive" ? ["false"]
: null,
}));
// Override verified → correct column
const statsWithFilter = dashboardStats.map((s) =>
s.key === "verified"
? { ...s, filterId: "is_verified", filterValue: ["true"] }
: s
);
// ─── Attach filterId to each breakdown so clicking a slice filters ────────
const dashboardBreakdowns = (usersDashboard?.breakdowns ?? []).map((b) => ({
...b,
filterId: b.key === "acc_type" ? "acc_type"
: b.key === "reg_type" ? "reg_type"
: null,
}));
return (
<>
{/* ── Dashboard strip ── */}
{usersDashboard && (
<TableDashboard
stats={statsWithFilter}
breakdowns={dashboardBreakdowns}
statMap={USER_STAT_MAP}
tableRefsRef={tableRefsRef}
/>
)}
{/* ── Data table ── */}
<DataTable
title="Users"
data={users}
@@ -71,7 +125,7 @@ export default function UsersTable() {
loading={loading}
onFetch={fetchUsers}
onFetchFilterData={fetchUserFieldValues}
onRefsReady={(refs) => tableRefsRef.current = refs}
onRefsReady={handleRefsReady}
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
<FilterSheet
open={open}
@@ -88,7 +142,8 @@ export default function UsersTable() {
recordLabel="user"
emptyMessage="No users match the current filters."
/>
{/* Single restore */}
{/* Single archive */}
<ArchiveDialog
open={!!archiveTarget}
onOpenChange={(v) => !v && setArchiveTarget(null)}
@@ -99,8 +154,8 @@ export default function UsersTable() {
loading={loading}
onSuccess={handleArchiveSuccess}
/>
{/* Bulk restore */}
{/* Bulk archive */}
<ArchiveDialog
open={!!archiveIds}
onOpenChange={(v) => !v && setArchiveIds(null)}
@@ -11,28 +11,27 @@ import { Eye, Pencil, Archive } from "lucide-react";
* @param {Function} deps.archiveUser Archive handler from useManagement
* @returns {Array} rowActions
*/
export function buildRowActions({ navigate, onArchive }) {
export function buildRowActions({ navigate, onEdit, onArchive }) {
return [
{
key: "view",
label: "View details",
icon: <Eye className="h-3.5 w-3.5" />,
onClick: (row) => navigate(`view/${row.user_id}`),
key: "view",
label: "View details",
icon: <Eye className="h-3.5 w-3.5" />,
onClick: (row) => navigate(`view/${row.group_id}`),
},
{
key: "edit",
label: "Edit",
icon: <Pencil className="h-3.5 w-3.5" />,
onClick: (row) => navigate(`edit/${row.user_id}`),
disabled: (row) => row.role === "super_admin",
key: "edit",
label: "Edit details",
icon: <Pencil className="h-3.5 w-3.5" />,
onClick: (row) => onEdit(row),
},
{
key: "archive",
label: "Archive",
key: "archive",
label: "Archive",
className: "text-destructive focus:text-destructive",
icon: <Archive className="h-3.5 w-3.5" />,
onClick: (row) => onArchive(row), // ← opens dialog, not deactivateUser
hidden: (row) => !row.is_active, // ← hide if already inactive
icon: <Archive className="h-3.5 w-3.5" />,
onClick: (row) => onArchive(row),
hidden: (row) => !row.is_active,
separator: true,
},
];
@@ -1,5 +1,5 @@
// ─── config/toolbar.config.jsx ────────────────────────────────────────────────
import { RefreshCw, Download, UserPlus, Archive } from "lucide-react";
import { RefreshCw, Download, FolderPlus, Archive } from "lucide-react";
import { exportTableToExcel } from "@/utils/excel.util";
/**
@@ -9,7 +9,7 @@ import { exportTableToExcel } from "@/utils/excel.util";
* @param {Object} deps.exportConfig { allData, attributes, filename, sheetName }
* @param {Function} deps.navigate React Router navigate
*/
export function buildToolbarActions({ fetchGroups, pagination, exportConfig, navigate, getFilters, getSort }) {
export function buildToolbarActions({ fetchGroups, pagination, exportConfig, onAddGroup, navigate, getFilters, getSort }) {
return [
{
key: "refresh",
@@ -28,11 +28,11 @@ export function buildToolbarActions({ fetchGroups, pagination, exportConfig, nav
{
key: "add-group",
type: "button",
icon: <UserPlus className="h-3.5 w-3.5" />,
icon: <FolderPlus className="h-3.5 w-3.5" />,
label: "Add Group",
variant: "default",
className: "text-primary-foreground",
onClick: () => navigate("add/staff"),
onClick: () => onAddGroup(),
},
{
key: "archived-groups",
@@ -0,0 +1,45 @@
// config/columns.config.jsx
// Column definitions and pinning config for the Users table.
import { buildColumns } from "@/utils/table.util";
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
import { Badge } from "@/components/ui/badge";
import { Users } from "lucide-react";
export const columnPinning = {
right: ["actions"],
left: [],
};
// ─── Custom cell overrides ────────────────────────────────────────────────────
const cellOverrides = {
// memberCount: (info) => {
// const count = parseInt(info.getValue() ?? 0, 10);
// return (
// <div className="flex items-center gap-1.5">
// <Users className="h-3.5 w-3.5 text-muted-foreground" />
// <Badge variant="secondary" className="text-xs font-medium tabular-nums">
// {count} {count === 1 ? "member" : "members"}
// </Badge>
// </div>
// );
// },
};
/**
* Builds the full column array for the Users table.
*
* @param {Array} attributes Field definitions from the server (drives data columns)
* @param {Array} rowActions Row-level kebab action definitions
* @returns {Array} TanStack column definitions
*/
export function buildDataColumns(attributes, rowActions) {
const visibleAttributes = attributes.filter((a) => !a.hidden);
return [
buildSelectionColumn(),
...buildColumns(visibleAttributes, { cellOverrides }),
buildRowActionsColumn(rowActions, { dropdownLabel: "Group Actions" }),
];
}
@@ -0,0 +1,20 @@
// modules/admin/config/user_groups/view/rowActions.config.jsx
import { UserMinus } from "lucide-react";
/**
* @param {Object} deps
* @param {Function} deps.onRemove Opens remove-member confirm dialog
* @returns {Array} rowActions
*/
export function buildRowActions({ onRemove }) {
return [
{
key: "remove",
label: "Remove from group",
className: "text-destructive focus:text-destructive",
icon: <UserMinus className="h-3.5 w-3.5" />,
onClick: (row) => onRemove(row),
},
];
}
@@ -0,0 +1,34 @@
// modules/admin/config/user_groups/view/selection.config.jsx
import { Download, UserMinus } from "lucide-react";
import { exportTableToExcel } from "@/utils/excel.util";
/**
* @param {Object} deps
* @param {Object} deps.exportConfig { allData, attributes, filename, sheetName }
* @param {Function} deps.onRemoveMember Opens single remove dialog (row)
* @param {Function} deps.onRemoveMembers Opens bulk remove dialog (ids[])
*/
export function buildSelectionActions({ exportConfig, onRemoveMember, onRemoveMembers }) {
return [
{
key: "export-selected",
label: "Export",
icon: <Download className="h-3.5 w-3.5" />,
onClick: (rows, table) =>
exportTableToExcel({ ...exportConfig, selectedRows: rows, tableInstance: table }),
},
{
key: "remove-selected",
label: "Remove",
icon: <UserMinus className="h-3.5 w-3.5" />,
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
onClick: (rows) => {
const ids = rows.map((r) => r.user_id);
ids.length === 1
? onRemoveMember(rows[0]) // single confirm dialog
: onRemoveMembers(ids); // bulk confirm dialog
},
},
];
}
@@ -0,0 +1,56 @@
// modules/admin/config/user_groups/view/toolbar.config.jsx
import { RefreshCw, Download, UserPlus } from "lucide-react";
import { exportTableToExcel } from "@/utils/excel.util";
/**
* @param {Object} deps
* @param {Function} deps.fetchGroup Context fetchGroup(gid, params)
* @param {string} deps.gid Current group id from useParams
* @param {Object} deps.pagination Current pagination state
* @param {Object} deps.exportConfig { allData, attributes, filename, sheetName }
* @param {Function} deps.onAddMember Opens AddMemberSheet
* @param {Function} deps.getFilters Returns active filters from tableRefsRef
* @param {Function} deps.getSort Returns active sort from tableRefsRef
*/
export function buildToolbarActions({
fetchGroup,
gid,
pagination,
exportConfig,
onAddMember,
getFilters,
getSort,
}) {
return [
{
key: "refresh",
type: "button",
icon: <RefreshCw className="h-3.5 w-3.5" />,
label: "Refresh",
onClick: () =>
fetchGroup(gid, {
page: 1,
limit: pagination.limit,
filters: getFilters(),
sort: getSort(),
}),
},
{
key: "export",
type: "button",
icon: <Download className="h-3.5 w-3.5" />,
label: "Export",
onClick: (table) => exportTableToExcel({ ...exportConfig, tableInstance: table }),
},
{
key: "add-member",
type: "button",
icon: <UserPlus className="h-3.5 w-3.5" />,
label: "Add Member",
variant: "default",
className: "text-primary-foreground",
onClick: () => onAddMember(),
},
];
}
@@ -21,7 +21,7 @@ export function buildRowActions({ navigate, onArchive }) {
},
{
key: "edit",
label: "Edit",
label: "Edit details",
icon: <Pencil className="h-3.5 w-3.5" />,
onClick: (row) => navigate(`edit/${row.user_id}`),
disabled: (row) => row.role === "super_admin",
+1 -2
View File
@@ -12,6 +12,7 @@
***********************************************************************************************************************************************************************/
import { Outlet, useNavigate } from "react-router-dom"
import { useAuth } from "@/contexts/AuthContext"
import { AdminProvider } from "@/contexts/provider/AdminProvider" // ← add
import { TooltipProvider } from "@/components/ui/tooltip"
import { Badge } from "@/components/ui/badge"
@@ -22,8 +23,6 @@ import AdminSideTabs from "../components/AdminSideTabs"
import UserMenu from "@/components/generic/UserMenu"
import { ROLE_CONFIG } from "@/data/profile.data"
import { AdminProvider } from "@/contexts/provider/AdminProvider" // ← add
const AdminLayout = () => {
const { user, logout } = useAuth();
const navigate = useNavigate();
-11
View File
@@ -1,11 +0,0 @@
import React from 'react'
const Admin = () => {
return (
<div>
Admin Page
</div>
)
}
export default Admin
@@ -0,0 +1,9 @@
// modules/admin/pages/UsersDashboard.jsx
export default function AdminDashboard() {
return (
<div>
AdminDashboard
</div>
);
}
@@ -0,0 +1,110 @@
// modules/admin/components/user_groups/AddGroupDialog.jsx
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
const schema = z.object({
name: z.string().min(1, "Name is required."),
description: z.string().min(1, "Description is required."),
});
/**
* Dialog for creating a new group.
* Matches context: createGroup({ name, description })
*
* @param {Object} props
* @param {boolean} props.open
* @param {Function} props.onOpenChange
* @param {Function} props.onSubmit Called with { name, description }
* @param {boolean} [props.loading]
*/
export function AddGroupDialog({ open, onOpenChange, onSubmit, loading }) {
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
defaultValues: { name: "", description: "" },
});
async function onValid(values) {
await onSubmit(values);
reset();
}
function handleClose() {
reset();
onOpenChange(false);
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[440px]">
<DialogHeader>
<DialogTitle>Add group</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onValid)} className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="name">
Name <span className="text-destructive">*</span>
</Label>
<Input
id="name"
placeholder="Group name"
{...register("name")}
/>
{errors.name && (
<p className="text-sm text-destructive">{errors.name.message}</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="description">
Description <span className="text-destructive">*</span>
</Label>
<Textarea
id="description"
placeholder="Brief description of this group"
className="resize-none"
rows={3}
{...register("description")}
/>
{errors.description && (
<p className="text-sm text-destructive">{errors.description.message}</p>
)}
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={handleClose}
disabled={loading}
>
Cancel
</Button>
<Button type="submit" disabled={loading}>
{loading ? "Creating..." : "Add group"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -1,11 +1,250 @@
import React from 'react'
// modules/admin/pages/user_groups/ViewGroup.jsx
import { useRef, useMemo, useState, useEffect, useCallback } from "react";
import { useParams } from "react-router-dom";
import { House, Users } from "lucide-react";
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import DataTable from "@/components/generic/Table/DataTable";
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
import { AddSheet } from "@/components/generic/Sheet/AddSheet";
import { useUserGroups } from "@/contexts/AdminUserGroupContext";
import { buildDataColumns, columnPinning } from "../../config/user_groups/view/columns.config";
import { buildToolbarActions } from "../../config/user_groups/view/toolbar.config";
import { buildSelectionActions } from "../../config/user_groups/view/selection.config";
import { buildRowActions } from "../../config/user_groups/view/rowActions.config";
import { getTimestamp } from "@/utils/timestamp.util";
export default function ViewGroup() {
const { groupId } = useParams();
const tableRefsRef = useRef({
getFilters: () => [],
getSort: () => [],
resetSelection: () => { },
setFilters: () => { },
});
const [addMemberOpen, setAddMemberOpen] = useState(false);
const [archiveTarget, setArchiveTarget] = useState(null);
const [archiveIds, setArchiveIds] = useState(null);
const [memberAttrs, setMemberAttrs] = useState([]);
const {
group,
members,
usersNotIn,
pagination,
setPagination,
loading,
fetchGroup,
fetchGroupFieldValues,
fetchUsersNotInGroup,
addUsersToGroup,
removeUsersFromGroup,
} = useUserGroups();
useEffect(() => {
if (!groupId) return;
fetchGroup(groupId).then((res) => {
const attrs = res?.data?.members?.attributes ?? [];
setMemberAttrs(attrs);
});
}, []);
const handleRefsReady = (refs) => {
tableRefsRef.current = refs; // ← just store refs directly, nothing else needed
};
const exportConfig = {
allData: members,
attributes: memberAttrs,
filename: `${getTimestamp()}_Group_${groupId}_Members`,
sheetName: "Members",
};
const rowActions = buildRowActions({
onRemove: (row) => setArchiveTarget(row),
});
const toolbarActions = buildToolbarActions({
fetchGroup,
groupId,
pagination,
exportConfig,
onAddMember: () => setAddMemberOpen(true),
getFilters: () => tableRefsRef.current.getFilters(),
getSort: () => tableRefsRef.current.getSort(),
});
const selectionActions = buildSelectionActions({
exportConfig,
onRemoveMember: (row) => setArchiveTarget(row),
onRemoveMembers: (ids) => setArchiveIds(ids),
});
const columns = useMemo(
() => buildDataColumns(memberAttrs, rowActions),
[memberAttrs],
);
const handleRemoveSuccess = () => {
setArchiveTarget(null);
setArchiveIds(null);
tableRefsRef.current.resetSelection?.();
fetchGroup(groupId, { page: 1, limit: pagination.limit });
};
const breadcrumbItems = [
{ label: "Home", icon: <House className="size-4" />, to: "/admin/users" },
{ label: "User Groups", to: "/admin/users/groups" },
{ label: group?.name ?? "View Group" },
];
const formattedCreated = group?.createdAt
? new Date(group.createdAt).toLocaleDateString("en-PH", {
year: "numeric", month: "long", day: "numeric",
})
: "—";
const formattedUpdated = group?.updatedAt
? new Date(group.updatedAt).toLocaleDateString("en-PH", {
year: "numeric", month: "long", day: "numeric",
})
: "—";
const handleFetch = useCallback(
(params) => fetchGroup(groupId, params),
[groupId] // fetchGroup should be useCallback'd in context
);
const ViewGroup = () => {
return (
<div>
ViewGroup
</div>
)
}
<section className="bg-muted/60 min-h-full">
<div className="lg:container lg:mx-auto lg:px-0 flex flex-col items-start px-4">
export default ViewGroup
<div className="flex flex-col gap-2 my-6">
<AppBreadcrumb items={breadcrumbItems} />
</div>
<div className="w-full flex flex-col gap-4 pb-8">
{/* ── Group detail card ─────────────────────────────────────────── */}
<div className="bg-card border rounded-xl p-5 flex flex-col gap-4">
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<h1 className="text-lg font-medium leading-none">
{group?.name ?? "—"}
</h1>
<span
className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${group?.is_active
? "bg-green-100 text-green-700"
: "bg-red-100 text-red-600"
}`}
>
{group?.is_active ? "Active" : "Inactive"}
</span>
</div>
<p className="text-sm text-muted-foreground">
{group?.description ?? "—"}
</p>
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
{[
{ label: "Group ID", value: group?.group_id ? `#${group.group_id}` : "—" },
{ label: "Members", value: pagination?.totalRecords ?? 0, icon: <Users className="size-3.5 text-muted-foreground" /> },
{ label: "Created", value: formattedCreated },
{ label: "Last Updated", value: formattedUpdated },
].map(({ label, value, icon }) => (
<div key={label} className="bg-muted rounded-lg px-3 py-2">
<span className="block text-[11px] uppercase tracking-wide text-muted-foreground mb-1">
{label}
</span>
<span className="text-sm font-medium flex items-center gap-1.5">
{icon}{value}
</span>
</div>
))}
</div>
</div>
{/* ── Members table ─────────────────────────────────────────────── */}
<div className="w-full">
<DataTable
title="Members"
data={members}
columns={columns}
attributes={memberAttrs}
pagination={pagination}
setPagination={setPagination}
loading={loading}
onFetch={handleFetch}
onFetchFilterData={fetchGroupFieldValues}
onRefsReady={handleRefsReady}
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
<FilterSheet
open={open}
onOpenChange={onOpenChange}
column={column}
attr={attr}
data={data}
loading={loading}
/>
)}
columnPinning={columnPinning}
toolbarActions={toolbarActions}
selectionActions={selectionActions}
recordLabel="member"
emptyMessage="No members in this group yet."
/>
</div>
</div>
</div>
{/* ── Add member — generic sheet ───────────────────────────────────── */}
<AddSheet
open={addMemberOpen}
onOpenChange={setAddMemberOpen}
title="Add members"
submitLabel="Add"
users={usersNotIn}
loading={loading}
onFetch={() => fetchUsersNotInGroup(groupId)}
idKey="user_id"
labelKey="full_name"
onSubmit={async (user_ids) => {
await addUsersToGroup(groupId, user_ids);
fetchGroup(groupId, { page: 1, limit: pagination.limit });
}}
/>
{/* ── Single remove ────────────────────────────────────────────────── */}
<ArchiveDialog
open={!!archiveTarget}
onOpenChange={(v) => !v && setArchiveTarget(null)}
entity={archiveTarget}
entityLabel="Member"
getName={(m) => m?.personal_info?.name?.full_name ?? m?.email}
onArchive={(m) => removeUsersFromGroup(groupId, [m?.user_id])} // ← stays the same
loading={loading}
onSuccess={handleRemoveSuccess}
/>
{/* ── Bulk remove ──────────────────────────────────────────────────── */}
<ArchiveDialog
open={!!archiveIds}
onOpenChange={(v) => !v && setArchiveIds(null)}
ids={archiveIds ?? []}
entityLabel="Member"
onArchive={({ ids }) => removeUsersFromGroup(groupId, ids)} // ← destructure { ids }
loading={loading}
onSuccess={handleRemoveSuccess}
/>
</section>
);
}
+2 -2
View File
@@ -6,7 +6,7 @@ import AdminLayout from '../layouts/AdminLayout'
import UserManagementLayout from '../layouts/UserManagementLayout'
// Global Pages
import Admin from '../pages/Admin'
import AdminDashboard from '../pages/AdminDashboard'
import ProfilePage from '@/components/generic/Profile'
// Specific Pages
@@ -31,7 +31,7 @@ export const AdminRoutes = {
element: <AdminLayout />, // ← shared sidebar/header for all admin pages
children: [
// Admin Management
{ index: true, element: <Admin /> }, // /admin
{ index: true, element: <AdminDashboard /> }, // /admin
{ path: 'my-profile', element: <ProfilePage /> },
// Users Management