feat: add credit transactions table
- Introduced a new CreditTransactionsPageClient component to display credit transactions. - Implemented getCreditTransactions action for fetching transaction data. - Added CreditTransactionsTable component for rendering transaction details with pagination and sorting. - Updated English and Chinese translation files to include credit transaction messages. - Integrated the credit transactions page into the existing credits settings layout.
This commit is contained in:
parent
1740c826c7
commit
40af0f6922
@ -494,6 +494,42 @@
|
||||
"error": "Failed to unban user"
|
||||
},
|
||||
"close": "Close"
|
||||
},
|
||||
"creditTransactions": {
|
||||
"title": "Credit Transactions",
|
||||
"error": "Failed to get credit transactions",
|
||||
"search": "Search credit transactions...",
|
||||
"columns": {
|
||||
"columns": "Columns",
|
||||
"id": "ID",
|
||||
"type": "Type",
|
||||
"description": "Description",
|
||||
"amount": "Amount",
|
||||
"remainingAmount": "Remaining Amount",
|
||||
"paymentId": "Payment ID",
|
||||
"expirationDate": "Expiration Date",
|
||||
"expirationDateProcessedAt": "Expiration Date Processed At",
|
||||
"createdAt": "Created At",
|
||||
"updatedAt": "Updated At"
|
||||
},
|
||||
"noResults": "No results",
|
||||
"firstPage": "First Page",
|
||||
"lastPage": "Last Page",
|
||||
"nextPage": "Next Page",
|
||||
"previousPage": "Previous Page",
|
||||
"rowsPerPage": "Rows per page",
|
||||
"page": "Page",
|
||||
"loading": "Loading...",
|
||||
"paymentIdCopied": "Payment ID copied to clipboard",
|
||||
"types": {
|
||||
"MONTHLY_REFRESH": "Monthly Refresh",
|
||||
"REGISTER_GIFT": "Register Gift",
|
||||
"PURCHASE": "Purchase",
|
||||
"USAGE": "Usage",
|
||||
"EXPIRE": "Expire"
|
||||
},
|
||||
"expired": "Expired",
|
||||
"never": "Never"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
|
@ -495,6 +495,42 @@
|
||||
"error": "解除封禁失败"
|
||||
},
|
||||
"close": "关闭"
|
||||
},
|
||||
"creditTransactions": {
|
||||
"title": "积分交易记录",
|
||||
"error": "获取积分交易记录失败",
|
||||
"search": "搜索积分交易记录...",
|
||||
"columns": {
|
||||
"columns": "列",
|
||||
"id": "ID",
|
||||
"type": "类型",
|
||||
"description": "描述",
|
||||
"amount": "金额",
|
||||
"remainingAmount": "剩余金额",
|
||||
"paymentId": "支付ID",
|
||||
"expirationDate": "过期时间",
|
||||
"expirationDateProcessedAt": "过期时间处理时间",
|
||||
"createdAt": "创建时间",
|
||||
"updatedAt": "更新时间"
|
||||
},
|
||||
"noResults": "无结果",
|
||||
"firstPage": "首页",
|
||||
"lastPage": "末页",
|
||||
"nextPage": "下一页",
|
||||
"previousPage": "上一页",
|
||||
"rowsPerPage": "每页行数",
|
||||
"page": "页",
|
||||
"loading": "加载中...",
|
||||
"paymentIdCopied": "支付ID已复制到剪贴板",
|
||||
"types": {
|
||||
"MONTHLY_REFRESH": "月度刷新",
|
||||
"REGISTER_GIFT": "注册礼品",
|
||||
"PURCHASE": "购买",
|
||||
"USAGE": "使用",
|
||||
"EXPIRE": "过期"
|
||||
},
|
||||
"expired": "已过期",
|
||||
"never": "永不"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
|
@ -82,10 +82,18 @@ export const createCreditPaymentIntent = actionClient
|
||||
return { success: false, error: 'Invalid credit package' };
|
||||
}
|
||||
|
||||
const customMetadata: Record<string, string> = {
|
||||
packageId,
|
||||
price: creditPackage.price.toString(),
|
||||
credits: creditPackage.credits.toString(),
|
||||
userId: session.user.id,
|
||||
userName: session.user.name,
|
||||
};
|
||||
|
||||
try {
|
||||
// Create payment intent
|
||||
const paymentIntent = await createPaymentIntent({
|
||||
amount: creditPackage.price * 100, // Convert to cents
|
||||
amount: creditPackage.price,
|
||||
currency: 'usd',
|
||||
metadata: {
|
||||
packageId,
|
||||
|
114
src/actions/get-credit-transactions.ts
Normal file
114
src/actions/get-credit-transactions.ts
Normal file
@ -0,0 +1,114 @@
|
||||
'use server';
|
||||
|
||||
import { getDb } from '@/db';
|
||||
import { creditTransaction, user } from '@/db/schema';
|
||||
import { asc, desc, eq, ilike, or, sql } from 'drizzle-orm';
|
||||
import { createSafeActionClient } from 'next-safe-action';
|
||||
import { z } from 'zod';
|
||||
|
||||
// Create a safe action client
|
||||
const actionClient = createSafeActionClient();
|
||||
|
||||
// Define the schema for getCreditTransactions parameters
|
||||
const getCreditTransactionsSchema = z.object({
|
||||
pageIndex: z.number().min(0).default(0),
|
||||
pageSize: z.number().min(1).max(100).default(10),
|
||||
search: z.string().optional().default(''),
|
||||
sorting: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
desc: z.boolean(),
|
||||
})
|
||||
)
|
||||
.optional()
|
||||
.default([]),
|
||||
});
|
||||
|
||||
// Define sort field mapping
|
||||
const sortFieldMap = {
|
||||
type: creditTransaction.type,
|
||||
amount: creditTransaction.amount,
|
||||
remainingAmount: creditTransaction.remainingAmount,
|
||||
description: creditTransaction.description,
|
||||
createdAt: creditTransaction.createdAt,
|
||||
updatedAt: creditTransaction.updatedAt,
|
||||
expirationDate: creditTransaction.expirationDate,
|
||||
expirationDateProcessedAt: creditTransaction.expirationDateProcessedAt,
|
||||
paymentId: creditTransaction.paymentId,
|
||||
} as const;
|
||||
|
||||
// Create a safe action for getting credit transactions
|
||||
export const getCreditTransactionsAction = actionClient
|
||||
.schema(getCreditTransactionsSchema)
|
||||
.action(async ({ parsedInput }) => {
|
||||
try {
|
||||
const { pageIndex, pageSize, search, sorting } = parsedInput;
|
||||
|
||||
const where = search
|
||||
? or(
|
||||
ilike(creditTransaction.description, `%${search}%`),
|
||||
ilike(creditTransaction.type, `%${search}%`),
|
||||
ilike(creditTransaction.paymentId, `%${search}%`)
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const offset = pageIndex * pageSize;
|
||||
|
||||
// Get the sort configuration
|
||||
const sortConfig = sorting[0];
|
||||
const sortField = sortConfig?.id
|
||||
? sortFieldMap[sortConfig.id as keyof typeof sortFieldMap]
|
||||
: creditTransaction.createdAt;
|
||||
const sortDirection = sortConfig?.desc ? desc : asc;
|
||||
|
||||
const db = await getDb();
|
||||
let [items, [{ count }]] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: creditTransaction.id,
|
||||
userId: creditTransaction.userId,
|
||||
type: creditTransaction.type,
|
||||
description: creditTransaction.description,
|
||||
amount: creditTransaction.amount,
|
||||
remainingAmount: creditTransaction.remainingAmount,
|
||||
paymentId: creditTransaction.paymentId,
|
||||
expirationDate: creditTransaction.expirationDate,
|
||||
expirationDateProcessedAt: creditTransaction.expirationDateProcessedAt,
|
||||
createdAt: creditTransaction.createdAt,
|
||||
updatedAt: creditTransaction.updatedAt,
|
||||
})
|
||||
.from(creditTransaction)
|
||||
.where(where)
|
||||
.orderBy(sortDirection(sortField))
|
||||
.limit(pageSize)
|
||||
.offset(offset),
|
||||
db
|
||||
.select({ count: sql`count(*)` })
|
||||
.from(creditTransaction)
|
||||
.where(where),
|
||||
]);
|
||||
|
||||
// hide user data in demo website
|
||||
if (process.env.NEXT_PUBLIC_DEMO_WEBSITE === 'true') {
|
||||
items = items.map((item) => ({
|
||||
...item,
|
||||
paymentId: item.paymentId ? 'pi_demo123456' : null,
|
||||
}));
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
items,
|
||||
total: Number(count),
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('get credit transactions error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch credit transactions',
|
||||
};
|
||||
}
|
||||
});
|
@ -1,9 +1,12 @@
|
||||
import { CreditPackages } from '@/components/settings/credits/credit-packages';
|
||||
import { CreditTransactionsPageClient } from '@/components/settings/credits/credit-transactions-page';
|
||||
|
||||
export default function CreditsPage() {
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<CreditPackages />
|
||||
|
||||
<CreditTransactionsPageClient />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
74
src/components/settings/credits/credit-transactions-page.tsx
Normal file
74
src/components/settings/credits/credit-transactions-page.tsx
Normal file
@ -0,0 +1,74 @@
|
||||
'use client';
|
||||
|
||||
import { getCreditTransactionsAction } from '@/actions/get-credit-transactions';
|
||||
import type { CreditTransaction } from '@/components/settings/credits/credit-transactions-table';
|
||||
import { CreditTransactionsTable } from '@/components/settings/credits/credit-transactions-table';
|
||||
import { useTransactionStore } from '@/stores/transaction-store';
|
||||
import type { SortingState } from '@tanstack/react-table';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export function CreditTransactionsPageClient() {
|
||||
const t = useTranslations('Dashboard.admin.creditTransactions');
|
||||
const [pageIndex, setPageIndex] = useState(0);
|
||||
const [pageSize, setPageSize] = useState(3);
|
||||
const [search, setSearch] = useState('');
|
||||
const [data, setData] = useState<CreditTransaction[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { refreshTrigger } = useTransactionStore();
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await getCreditTransactionsAction({
|
||||
pageIndex,
|
||||
pageSize,
|
||||
search,
|
||||
sorting,
|
||||
});
|
||||
|
||||
if (result?.data?.success) {
|
||||
setData(result.data.data?.items || []);
|
||||
setTotal(result.data.data?.total || 0);
|
||||
} else {
|
||||
const errorMessage = result?.data?.error || t('error');
|
||||
toast.error(errorMessage);
|
||||
setData([]);
|
||||
setTotal(0);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('CreditTransactions, fetch credit transactions error:', error);
|
||||
toast.error(t('error'));
|
||||
setData([]);
|
||||
setTotal(0);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [pageIndex, pageSize, search, sorting, refreshTrigger]);
|
||||
|
||||
return (
|
||||
<div className="w-full space-y-4">
|
||||
<h1 className="text-lg font-semibold">{t('title')}</h1>
|
||||
|
||||
<CreditTransactionsTable
|
||||
data={data}
|
||||
total={total}
|
||||
pageIndex={pageIndex}
|
||||
pageSize={pageSize}
|
||||
search={search}
|
||||
loading={loading}
|
||||
onSearch={setSearch}
|
||||
onPageChange={setPageIndex}
|
||||
onPageSizeChange={setPageSize}
|
||||
onSortingChange={setSorting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
576
src/components/settings/credits/credit-transactions-table.tsx
Normal file
576
src/components/settings/credits/credit-transactions-table.tsx
Normal file
@ -0,0 +1,576 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { formatDate } from '@/lib/formatter';
|
||||
import {
|
||||
type ColumnDef,
|
||||
type ColumnFiltersState,
|
||||
type SortingState,
|
||||
type VisibilityState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFilteredRowModel,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel,
|
||||
useReactTable,
|
||||
} from '@tanstack/react-table';
|
||||
import {
|
||||
ArrowUpDownIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsLeftIcon,
|
||||
ChevronsRightIcon,
|
||||
RefreshCwIcon,
|
||||
GiftIcon,
|
||||
ShoppingCartIcon,
|
||||
MinusCircleIcon,
|
||||
ClockIcon,
|
||||
} from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { Badge } from '../../ui/badge';
|
||||
import { Label } from '../../ui/label';
|
||||
import { CREDIT_TRANSACTION_TYPE } from '@/lib/constants';
|
||||
|
||||
// Define the credit transaction interface
|
||||
interface CreditTransaction {
|
||||
id: string;
|
||||
userId: string;
|
||||
type: string;
|
||||
description: string | null;
|
||||
amount: number;
|
||||
remainingAmount: number | null;
|
||||
paymentId: string | null;
|
||||
expirationDate: Date | null;
|
||||
expirationDateProcessedAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
interface DataTableColumnHeaderProps<TData, TValue>
|
||||
extends React.HTMLAttributes<HTMLDivElement> {
|
||||
column: any;
|
||||
title: string;
|
||||
}
|
||||
|
||||
function DataTableColumnHeader<TData, TValue>({
|
||||
column,
|
||||
title,
|
||||
className,
|
||||
}: DataTableColumnHeaderProps<TData, TValue>) {
|
||||
return (
|
||||
<div className={className}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
||||
className="h-8 data-[state=open]:bg-accent"
|
||||
>
|
||||
<span>{title}</span>
|
||||
<ArrowUpDownIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface CreditTransactionsTableProps {
|
||||
data: CreditTransaction[];
|
||||
total: number;
|
||||
pageIndex: number;
|
||||
pageSize: number;
|
||||
search: string;
|
||||
loading?: boolean;
|
||||
onSearch: (search: string) => void;
|
||||
onPageChange: (page: number) => void;
|
||||
onPageSizeChange: (size: number) => void;
|
||||
onSortingChange?: (sorting: SortingState) => void;
|
||||
}
|
||||
|
||||
export { type CreditTransaction };
|
||||
|
||||
export function CreditTransactionsTable({
|
||||
data,
|
||||
total,
|
||||
pageIndex,
|
||||
pageSize,
|
||||
search,
|
||||
loading,
|
||||
onSearch,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
onSortingChange,
|
||||
}: CreditTransactionsTableProps) {
|
||||
const t = useTranslations('Dashboard.admin.creditTransactions');
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
|
||||
// show fake data in demo website
|
||||
const isDemo = process.env.NEXT_PUBLIC_DEMO_WEBSITE === 'true';
|
||||
|
||||
// Map column IDs to translation keys
|
||||
const columnIdToTranslationKey = {
|
||||
type: 'columns.type' as const,
|
||||
amount: 'columns.amount' as const,
|
||||
remainingAmount: 'columns.remainingAmount' as const,
|
||||
description: 'columns.description' as const,
|
||||
paymentId: 'columns.paymentId' as const,
|
||||
expirationDate: 'columns.expirationDate' as const,
|
||||
expirationDateProcessedAt: 'columns.expirationDateProcessedAt' as const,
|
||||
createdAt: 'columns.createdAt' as const,
|
||||
updatedAt: 'columns.updatedAt' as const,
|
||||
} as const;
|
||||
|
||||
// Get transaction type icon and color
|
||||
const getTransactionTypeIcon = (type: string) => {
|
||||
switch (type) {
|
||||
case CREDIT_TRANSACTION_TYPE.MONTHLY_REFRESH:
|
||||
return <RefreshCwIcon className="h-4 w-4 text-blue-500" />;
|
||||
case CREDIT_TRANSACTION_TYPE.REGISTER_GIFT:
|
||||
return <GiftIcon className="h-4 w-4 text-green-500" />;
|
||||
case CREDIT_TRANSACTION_TYPE.PURCHASE:
|
||||
return <ShoppingCartIcon className="h-4 w-4 text-purple-500" />;
|
||||
case CREDIT_TRANSACTION_TYPE.USAGE:
|
||||
return <MinusCircleIcon className="h-4 w-4 text-red-500" />;
|
||||
case CREDIT_TRANSACTION_TYPE.EXPIRE:
|
||||
return <ClockIcon className="h-4 w-4 text-gray-500" />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Get transaction type color
|
||||
const getTransactionTypeColor = (type: string) => {
|
||||
switch (type) {
|
||||
case CREDIT_TRANSACTION_TYPE.MONTHLY_REFRESH:
|
||||
return 'bg-blue-100 text-blue-800 border-blue-200';
|
||||
case CREDIT_TRANSACTION_TYPE.REGISTER_GIFT:
|
||||
return 'bg-green-100 text-green-800 border-green-200';
|
||||
case CREDIT_TRANSACTION_TYPE.PURCHASE:
|
||||
return 'bg-purple-100 text-purple-800 border-purple-200';
|
||||
case CREDIT_TRANSACTION_TYPE.USAGE:
|
||||
return 'bg-red-100 text-red-800 border-red-200';
|
||||
case CREDIT_TRANSACTION_TYPE.EXPIRE:
|
||||
return 'bg-gray-100 text-gray-800 border-gray-200';
|
||||
default:
|
||||
return 'bg-gray-100 text-gray-800 border-gray-200';
|
||||
}
|
||||
};
|
||||
|
||||
// Table columns definition
|
||||
const columns: ColumnDef<CreditTransaction>[] = [
|
||||
{
|
||||
accessorKey: 'type',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.type')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`px-2 py-1 flex items-center gap-1 ${getTransactionTypeColor(transaction.type)}`}
|
||||
>
|
||||
{getTransactionTypeIcon(transaction.type)}
|
||||
{transaction.type}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'amount',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.amount')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
<span
|
||||
className={`font-medium ${
|
||||
transaction.amount > 0 ? 'text-green-600' : 'text-red-600'
|
||||
}`}
|
||||
>
|
||||
{transaction.amount > 0 ? '+' : ''}
|
||||
{transaction.amount.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'remainingAmount',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.remainingAmount')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
{transaction.remainingAmount !== null ? (
|
||||
<span className="font-medium text-gray-600">
|
||||
{transaction.remainingAmount.toLocaleString()}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-400">-</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'description',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.description')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
<span className="max-w-[200px] truncate" title={transaction.description || undefined}>
|
||||
{transaction.description || '-'}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'paymentId',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.paymentId')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
{transaction.paymentId ? (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-sm px-1.5 cursor-pointer hover:bg-accent max-w-[150px]"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(transaction.paymentId!);
|
||||
toast.success(t('paymentIdCopied'));
|
||||
}}
|
||||
>
|
||||
<span className="truncate">{transaction.paymentId}</span>
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-gray-400">-</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'expirationDate',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.expirationDate')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
{transaction.expirationDate ? (
|
||||
<span className="text-sm">
|
||||
{formatDate(transaction.expirationDate)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-400">-</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'expirationDateProcessedAt',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.expirationDateProcessedAt')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
{transaction.expirationDateProcessedAt ? (
|
||||
<span className="text-sm">
|
||||
{formatDate(transaction.expirationDateProcessedAt)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-400">-</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'createdAt',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.createdAt')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
<span className="text-sm">
|
||||
{formatDate(transaction.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'updatedAt',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('columns.updatedAt')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const transaction = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2 pl-3">
|
||||
<span className="text-sm">
|
||||
{formatDate(transaction.updatedAt)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: Math.ceil(total / pageSize),
|
||||
state: {
|
||||
sorting,
|
||||
columnFilters,
|
||||
columnVisibility,
|
||||
pagination: { pageIndex, pageSize },
|
||||
},
|
||||
onSortingChange: (updater) => {
|
||||
const next = typeof updater === 'function' ? updater(sorting) : updater;
|
||||
setSorting(next);
|
||||
onSortingChange?.(next);
|
||||
},
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => {
|
||||
const next =
|
||||
typeof updater === 'function'
|
||||
? updater({ pageIndex, pageSize })
|
||||
: updater;
|
||||
if (next.pageIndex !== pageIndex) onPageChange(next.pageIndex);
|
||||
if (next.pageSize !== pageSize) onPageSizeChange(next.pageSize);
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
manualPagination: true,
|
||||
manualSorting: true,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="w-full flex-col justify-start gap-6 space-y-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex flex-1 items-center gap-4">
|
||||
<Input
|
||||
placeholder={t('search')}
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
onSearch(event.target.value);
|
||||
onPageChange(0);
|
||||
}}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="cursor-pointer">
|
||||
<span className="inline">{t('columns.columns')}</span>
|
||||
<ChevronDownIcon />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table
|
||||
.getAllColumns()
|
||||
.filter((column) => column.getCanHide())
|
||||
.map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem
|
||||
key={column.id}
|
||||
className="capitalize cursor-pointer"
|
||||
checked={column.getIsVisible()}
|
||||
onCheckedChange={(value) =>
|
||||
column.toggleVisibility(!!value)
|
||||
}
|
||||
>
|
||||
{t(
|
||||
columnIdToTranslationKey[
|
||||
column.id as keyof typeof columnIdToTranslationKey
|
||||
] || 'columns.columns'
|
||||
)}
|
||||
</DropdownMenuCheckboxItem>
|
||||
);
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && 'selected'}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext()
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length}
|
||||
className="h-24 text-center"
|
||||
>
|
||||
{loading ? t('loading') : t('noResults')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{total > 0 && (
|
||||
<span>
|
||||
{t('totalRecords', { count: total })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">
|
||||
{t('rowsPerPage')}
|
||||
</Label>
|
||||
<Select
|
||||
value={`${pageSize}`}
|
||||
onValueChange={(value) => {
|
||||
onPageSizeChange(Number(value));
|
||||
onPageChange(0);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
size="sm"
|
||||
className="w-20 cursor-pointer"
|
||||
id="rows-per-page"
|
||||
>
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30, 40, 50].map((pageSize) => (
|
||||
<SelectItem key={pageSize} value={`${pageSize}`}>
|
||||
{pageSize}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
{t('page')} {pageIndex + 1} {' / '}
|
||||
{Math.max(1, Math.ceil(total / pageSize))}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="hidden h-8 w-8 p-0 lg:flex"
|
||||
onClick={() => onPageChange(0)}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
>
|
||||
<span className="sr-only">{t('goToFirstPage')}</span>
|
||||
<ChevronsLeftIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={() => onPageChange(pageIndex - 1)}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
>
|
||||
<span className="sr-only">{t('goToPreviousPage')}</span>
|
||||
<ChevronLeftIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={() => onPageChange(pageIndex + 1)}
|
||||
disabled={!table.getCanNextPage()}
|
||||
>
|
||||
<span className="sr-only">{t('goToNextPage')}</span>
|
||||
<ChevronRightIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="hidden h-8 w-8 p-0 lg:flex"
|
||||
onClick={() => onPageChange(Math.ceil(total / pageSize) - 1)}
|
||||
disabled={!table.getCanNextPage()}
|
||||
>
|
||||
<span className="sr-only">{t('goToLastPage')}</span>
|
||||
<ChevronsRightIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
Loading…
Reference in New Issue
Block a user