integrate users

This commit is contained in:
rgrgogu
2026-05-06 14:14:54 +08:00
parent 569442bf33
commit f165e8b3bb
35 changed files with 2516 additions and 24 deletions
+134
View File
@@ -0,0 +1,134 @@
// ─── utils/exportToExcel.js ───────────────────────────────────────────────────
import * as XLSX from "xlsx";
const SKIP_IDS = new Set(["select", "actions"]);
// ─── Resolve dot-notation or direct key from a row ────────────────────────────
function resolveValue(row, key) {
if (!key) return "";
// ─── Try direct key first e.g. "email", "acc_type" ────────────────────────
if (key in row) return row[key] ?? "";
// ─── Dot-notation fallback e.g. "personal_info.name.full_name" ────────────
return key.split(".").reduce((acc, part) => acc?.[part] ?? "", row) ?? "";
}
// ─── Flatten a nested row based on attributes ─────────────────────────────────
function flattenRow(row, attributes) {
const result = {};
for (const attr of attributes) {
const { field } = attr;
result[field] = resolveValue(row, field);
}
return result;
}
/**
* Resolves which columns to export based on the TanStack table instance
* (reads visible columns) or falls back to the raw attributes array.
*
* @param {TableInstance|null} tableInstance
* @param {Array} attributes
* @returns {Array} [{ key, label, width }]
*/
function resolveColumns(tableInstance, attributes) {
if (tableInstance) {
return tableInstance
.getVisibleLeafColumns()
.filter((col) => !SKIP_IDS.has(col.id))
.map((col) => ({
key: col.id,
label:
col.columnDef.meta?.label ??
(typeof col.columnDef.header === "string" ? col.columnDef.header : col.id),
width: col.columnDef.meta?.exportWidth ?? 20,
}));
}
return (attributes ?? [])
.filter((attr) => attr.hidden !== true && !SKIP_IDS.has(attr.field))
.map((attr) => ({
key: attr.field,
label: attr.name ?? attr.field,
width: attr.exportWidth ?? 20,
}));
}
/**
* Dynamic export handler — designed to be called directly from toolbar
* and selection action configs across any table.
*
* Resolves columns from the live TanStack table instance (respects column
* visibility toggles) and resolves rows from the selection or full dataset.
*
* @param {Object} options
* @param {Array} options.allData Full dataset for this table
* @param {Array} options.attributes Field definitions (fallback if no tableInstance)
* @param {Array} [options.selectedRows] Checked rows — exports these if non-empty
* @param {TableInstance|null}[options.tableInstance] TanStack table — reads visible columns
* @param {string} [options.filename] Without extension. Default: "export"
* @param {string} [options.sheetName] Sheet tab name. Default: "Sheet1"
*
* @example
* // Toolbar export (all rows, visible columns)
* onClick: (table) => exportTableToExcel({ allData: users, attributes, tableInstance: table })
*
* @example
* // Selection export (checked rows only, visible columns)
* onClick: (rows, table) => exportTableToExcel({ allData: users, attributes, selectedRows: rows, tableInstance: table })
*/
export function exportTableToExcel({
allData = [],
attributes = [],
selectedRows = [],
tableInstance = null,
filename = "export",
sheetName = "Sheet1",
} = {}) {
const columns = resolveColumns(tableInstance, attributes);
const rawData = Array.isArray(selectedRows) && selectedRows.length > 0
? selectedRows
: allData;
// ─── Flatten rows so dot-notation keys resolve correctly ──────────────────
const data = rawData.map((row) => flattenRow(row, attributes));
exportToExcel({ data, columns, filename, sheetName });
}
/**
* Core export — writes a plain array of objects to an .xlsx file.
* Use exportTableToExcel above for table-aware dynamic exports.
*
* @param {Object} options
* @param {Array} options.data Rows to export
* @param {Array} options.columns [{ key, label, width }]
* @param {string} [options.filename] Without extension. Default: "export"
* @param {string} [options.sheetName] Sheet tab name. Default: "Sheet1"
*/
export function exportToExcel({
data = [],
columns = [],
filename = "export",
sheetName = "Sheet1",
} = {}) {
if (!data.length || !columns.length) {
console.warn("exportToExcel: no data or columns to export.");
return;
}
const headers = columns.map((c) => c.label ?? c.key);
const rows = data.map((row) =>
columns.map((c) => resolveValue(row, c.key))
);
const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
ws["!cols"] = columns.map((c) => ({ wch: c.width ?? 20 }));
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, sheetName);
XLSX.writeFile(wb, `${filename}.xlsx`);
}
+250
View File
@@ -0,0 +1,250 @@
import { useState, useEffect } from "react";
import { createColumnHelper } from "@tanstack/react-table";
import { format } from "date-fns";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
import { Search } from "lucide-react";
export const pageSizes = [10, 25, 50, 75, 100, 250, 500, 750, 1000]
// ── Badge style map for enum values ───────────────────────────────────────────
const BADGE_STYLES = {
"Active": "bg-emerald-100 text-emerald-800 border-emerald-200",
"Not Active": "bg-rose-100 text-rose-700 border-rose-200",
"Verified": "bg-blue-100 text-blue-800 border-blue-200",
"Not Verified": "bg-amber-100 text-amber-700 border-amber-200",
"system": "bg-violet-50 text-violet-700 border-violet-200",
"google": "bg-orange-50 text-orange-700 border-orange-200",
"admin": "bg-red-100 text-red-700 border-red-200",
"user": "bg-blue-100 text-blue-700 border-blue-200",
"staff": "bg-green-100 text-green-700 border-green-200",
};
function EnumBadge({ value }) {
return (
<Badge
variant="outline"
className={`text-[11px] font-medium px-2 py-0.5 ${BADGE_STYLES[value] ?? ""}`}
>
{value}
</Badge>
);
}
export function formatDate(value) {
if (!value) return null;
try { return format(new Date(value), "MMM d, yyyy"); }
catch { return value; }
}
function renderCell(attr, value) {
if (value === null || value === undefined || value === "") {
return <span className="text-muted-foreground/40">-</span>;
}
switch (attr.type) {
case "enum":
if (attr.field === "is_active")
return <EnumBadge value={value ? "Active" : "Not Active"} />;
else if (attr.field === "is_verified")
return <EnumBadge value={value ? "Verified" : "Not Verified"} />;
else
return <EnumBadge value={value} />;
case "date": return <span className="text-xs text-muted-foreground">{formatDate(value)}</span>;
case "number": return <span className="font-mono text-xs font-semibold text-muted-foreground">{value}</span>;
default: return <span className="text-sm">{value}</span>;
}
}
export function ColumnFilter({ column, attr }) {
const columnValue = column.getFilterValue() ?? "";
const [inputValue, setInputValue] = useState(columnValue);
// keep in sync when external reset happens
useEffect(() => {
setInputValue(columnValue);
}, [columnValue]);
// ─────────────────────────────────────────────
// ENUM (AUTO APPLY)
// ─────────────────────────────────────────────
if (attr.type === "enum") {
return (
<Select
value={inputValue || "__all__"}
onValueChange={(v) => {
const value = v === "__all__" ? "" : v;
setInputValue(value);
column.setFilterValue(value); // ✅ auto apply
}}
>
<SelectTrigger className="h-7 text-xs w-full">
<SelectValue placeholder="All" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__all__">All</SelectItem>
{attr.options?.choices?.map((c) => (
<SelectItem key={c} value={c}>
{c}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
// ─────────────────────────────────────────────
// DATE (SINGLE)
// ─────────────────────────────────────────────
if (attr.type === "date") {
const value =
inputValue &&
typeof inputValue === "object" &&
("from" in inputValue || "to" in inputValue)
? inputValue
: null;
const isRange = !!value;
return (
<div className="flex flex-col gap-1">
{/* MODE TOGGLE */}
<div className="flex items-center gap-2 text-xs">
<label className="flex items-center gap-1">
<input
type="radio"
checked={!isRange}
onChange={() => {
setInputValue("");
column.setFilterValue("");
}}
/>
Single
</label>
<label className="flex items-center gap-1">
<input
type="radio"
checked={isRange}
onChange={() => {
setInputValue({ from: "", to: "" });
column.setFilterValue({ from: "", to: "" });
}}
/>
Range
</label>
</div>
{/* SINGLE DATE */}
{!isRange && (
<Input
type="date"
value={inputValue || ""}
onChange={(e) => {
const val = e.target.value;
setInputValue(val);
column.setFilterValue(val);
}}
className="h-7 text-xs"
/>
)}
{/* RANGE */}
{isRange && (
<div className="flex gap-1">
<Input
type="date"
value={value.from}
onChange={(e) => {
const next = {
from: e.target.value,
to: value.to || "",
};
setInputValue(next);
column.setFilterValue(next);
}}
className="h-7 text-xs"
/>
<Input
type="date"
value={value.to}
onChange={(e) => {
const next = {
from: value.from || "",
to: e.target.value,
};
setInputValue(next);
column.setFilterValue(next);
}}
className="h-7 text-xs"
/>
</div>
)}
</div>
);
}
// ─────────────────────────────────────────────
// TEXT FILTER (manual apply)
// ─────────────────────────────────────────────
return (
<div className="flex gap-1">
<Input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
column.setFilterValue(inputValue);
}
}}
placeholder="Filter..."
className="h-7 text-xs w-full"
/>
<Button
size="icon"
variant="outline"
className="h-7 w-7"
onClick={() => column.setFilterValue(inputValue)}
>
<Search className="size-3.5" />
</Button>
</div>
);
}
// ── Sort icon ──────────────────────────────────────────────────────────────────
export function SortIcon({ column }) {
const s = column.getIsSorted();
if (s === "asc") return <ArrowUp className="ml-1 h-3 w-3 text-primary shrink-0" />;
if (s === "desc") return <ArrowDown className="ml-1 h-3 w-3 text-primary shrink-0" />;
return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground/40 shrink-0" />;
}
// ── Build columns dynamically from attributes ──────────────────────────────────
const columnHelper = createColumnHelper();
export function buildColumns(attrs) {
return attrs.map((attr) =>
columnHelper.accessor(attr.field, {
id: attr.field,
header: attr.name,
enableSorting: true,
enableColumnFilter: true,
filterFn: (row, colId, filterValue) => {
if (!filterValue) return true;
const val = String(row.getValue(colId) ?? "").toLowerCase();
return val.includes(String(filterValue).toLowerCase());
},
cell: (info) => renderCell(attr, info.getValue()),
meta: { attr },
})
);
}
+13
View File
@@ -0,0 +1,13 @@
export function getTimestamp() {
const now = new Date();
const YYYY = now.getFullYear();
const MM = String(now.getMonth() + 1).padStart(2, "0");
const DD = String(now.getDate()).padStart(2, "0");
const HH = String(now.getHours()).padStart(2, "0");
const mm = String(now.getMinutes()).padStart(2, "0");
const SS = String(now.getSeconds()).padStart(2, "0");
return `${YYYY}${MM}${DD}_${HH}${mm}${SS}`;
}