adding 3 filters on wallet history
This commit is contained in:
@ -1,40 +1,189 @@
|
||||
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
|
||||
import { useManageWalletContext } from '../hooks/useManageWalletHistoryContext';
|
||||
import { useCallApi } from '@/hooks';
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
const API_URL_WALLET = apiConfig.service_wallet;
|
||||
|
||||
interface WalletProps {
|
||||
ID: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const ListToolbar = () => {
|
||||
const { table, reload } = useDataGrid();
|
||||
const { handleAddDialog } = useManageWalletContext();
|
||||
const { GetData } = useCallApi();
|
||||
|
||||
const [searchValue, setSearchValue] = useState<string>(
|
||||
(table.getColumn('msisdn')?.getFilterValue() as string) ?? ''
|
||||
);
|
||||
const [dateRange, setDateRange] = useState({ from: '', to: '' });
|
||||
const [walletId, setWalletId] = useState<string>(
|
||||
(table.getColumn('id_wallet')?.getFilterValue() as string) ?? ''
|
||||
);
|
||||
const [wallets, setWallets] = useState<WalletProps[]>([]);
|
||||
|
||||
const formatDate = (date: Date): string => date.toISOString().split('T')[0];
|
||||
|
||||
useEffect(() => {
|
||||
const today = new Date();
|
||||
const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
|
||||
setDateRange({ from: formatDate(firstDayOfMonth), to: formatDate(today) });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
table.getColumn('msisdn')?.setFilterValue(searchValue);
|
||||
table.setPageIndex(0);
|
||||
}, 200);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchValue, table]);
|
||||
|
||||
const handleFilterByDate = useCallback(() => {
|
||||
try {
|
||||
table.getColumn('CreatedAt')?.setFilterValue(dateRange);
|
||||
} catch (error) {
|
||||
toast.error('Error applying date filter');
|
||||
console.error('Error applying date filter:', error);
|
||||
}
|
||||
}, [dateRange, table]);
|
||||
|
||||
useEffect(() => {
|
||||
table.getColumn('id_wallet')?.setFilterValue(walletId);
|
||||
table.setPageIndex(0);
|
||||
}, [walletId, table]);
|
||||
|
||||
useEffect(() => {
|
||||
if (dateRange.from && dateRange.to) {
|
||||
handleFilterByDate();
|
||||
}
|
||||
}, [dateRange, handleFilterByDate]);
|
||||
|
||||
const fetchWallets = async () => {
|
||||
try {
|
||||
const response = await GetData(`${API_URL_WALLET}/dashboard/wallet/`, {
|
||||
limit: 100,
|
||||
page: 1,
|
||||
with_deleted: false,
|
||||
order_field: 'created_at',
|
||||
order_direction: 'ASC'
|
||||
});
|
||||
setWallets(response?.data.list || []);
|
||||
} catch (error) {
|
||||
console.error('Error fetching wallets', error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchWallets();
|
||||
}, []);
|
||||
|
||||
const handleClearAllFilters = () => {
|
||||
setSearchValue('');
|
||||
setWalletId('');
|
||||
|
||||
const today = new Date();
|
||||
const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
|
||||
setDateRange({
|
||||
from: formatDate(firstDayOfMonth),
|
||||
to: formatDate(today)
|
||||
});
|
||||
|
||||
table.getAllColumns().forEach((column) => {
|
||||
if (column.id !== 'CreatedAt') {
|
||||
column.setFilterValue(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
table.setPageIndex(0);
|
||||
|
||||
table.getColumn('CreatedAt')?.setFilterValue({
|
||||
from: formatDate(firstDayOfMonth),
|
||||
to: formatDate(today)
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card-header flex-wrap gap-2 border-b-0 px-5">
|
||||
<div className="flex flex-wrap gap-2 lg:gap-5 w-full">
|
||||
<div className="flex justify-between w-full items-center">
|
||||
<div className="flex w-[50%] gap-3 items-center">
|
||||
{/* <label className="input input-sm w-1/3">
|
||||
<div className="flex gap-3 items-center flex-wrap">
|
||||
<label className="input input-sm w-[160px]">
|
||||
From
|
||||
<input
|
||||
type="date"
|
||||
value={dateRange.from}
|
||||
onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="input input-sm w-[160px]">
|
||||
To
|
||||
<input
|
||||
type="date"
|
||||
value={dateRange.to}
|
||||
onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="input input-sm w-1/3">
|
||||
<KeenIcon icon="magnifier" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search Wallet"
|
||||
value={(table.getColumn('msisdn')?.getFilterValue() as string) ?? ''}
|
||||
onChange={(event) => table.getColumn('msisdn')?.setFilterValue(event.target.value)}
|
||||
placeholder="Search MSISDN"
|
||||
value={searchValue}
|
||||
onChange={(e) => setSearchValue(e.target.value)}
|
||||
/>
|
||||
</label> */}
|
||||
{/* <DefaultTooltip title={'Filter'} placement={'top'}>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-7.5 disabled:bg-gray-400"
|
||||
// disabled={isLoading}
|
||||
// onClick={handleFilterData}
|
||||
</label>
|
||||
|
||||
<div className="w-[220px]">
|
||||
<Select
|
||||
value={walletId}
|
||||
onValueChange={(value) => {
|
||||
setWalletId(value);
|
||||
}}
|
||||
>
|
||||
{loadingButton === 'filter' ? <ContentLoader /> : <KeenIcon icon="filter" />}
|
||||
<KeenIcon icon="filter" />
|
||||
</Button>
|
||||
</DefaultTooltip> */}
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select Wallet" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{wallets.map((wallet) => (
|
||||
<SelectItem key={wallet.ID} value={wallet.ID}>
|
||||
{wallet.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button variant="outline" size="sm" onClick={handleClearAllFilters}>
|
||||
Clear Filter
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 items-center">
|
||||
<DefaultTooltip title={'Refresh'} placement={'top'}>
|
||||
<Button variant="outline" className="h-7.5" onClick={() => reload()}>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-7.5"
|
||||
onClick={() => {
|
||||
setSearchValue('');
|
||||
setWalletId('');
|
||||
table.setColumnFilters((prev) => prev.filter((f) => f.id === 'CreatedAt'));
|
||||
table.setPageIndex(0);
|
||||
reload();
|
||||
}}
|
||||
>
|
||||
<KeenIcon icon="arrows-circle" />
|
||||
</Button>
|
||||
</DefaultTooltip>
|
||||
|
||||
@ -6,6 +6,16 @@ import { ColumnDef } from '@tanstack/react-table';
|
||||
import React, { createContext, useCallback, useMemo, useState } from 'react';
|
||||
import ListToolbar from '../blocks/ListToolbar';
|
||||
|
||||
// Helper function for number formatting with currency format
|
||||
const formatNumber = (num: number, currencyCode: string = 'USD'): string => {
|
||||
return num.toLocaleString('en-US', {
|
||||
style: 'currency',
|
||||
currency: currencyCode,
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2
|
||||
});
|
||||
};
|
||||
|
||||
interface WalletProps {
|
||||
id: string;
|
||||
name: string;
|
||||
@ -23,11 +33,10 @@ interface ContextProps {
|
||||
handleDeleteDialog: (show: boolean, selected_wallet: WalletProps | null) => void;
|
||||
selectedWallet: WalletProps | null;
|
||||
getWalletLists: (
|
||||
limit: number,
|
||||
page: number,
|
||||
with_deleted: boolean,
|
||||
order_field: any,
|
||||
order_direction: any
|
||||
limit: number,
|
||||
sorting: any,
|
||||
filter: any
|
||||
) => Promise<{ data: WalletProps[]; totalCount: number } | undefined>;
|
||||
}
|
||||
|
||||
@ -81,8 +90,22 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'amount' ,
|
||||
accessorKey: 'id_wallet',
|
||||
header: ({ column }) => <DataGridColumnHeader title="Wallet ID" column={column} />,
|
||||
enableSorting: false,
|
||||
enableHiding: true, // Hide this column from view but use it for filtering
|
||||
meta: {
|
||||
headerClassName: 'w-[200px]'
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'amount',
|
||||
header: ({ column }) => <DataGridColumnHeader title="Amount" column={column} />,
|
||||
cell: ({ row }) => {
|
||||
// Get currency code from the nested data structure if available
|
||||
const currencyCode = row.original.balance_type?.currency?.code || 'USD';
|
||||
return formatNumber(row.original.amount, currencyCode);
|
||||
},
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
meta: {
|
||||
@ -90,8 +113,10 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'trx_count_today' ,
|
||||
header: ({ column }) => <DataGridColumnHeader title="Transaction Count Today" column={column} />,
|
||||
accessorKey: 'trx_count_today',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Transaction Count Today" column={column} />
|
||||
),
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
meta: {
|
||||
@ -99,8 +124,13 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'amount_this_month' ,
|
||||
header: ({ column }) => <DataGridColumnHeader title="Ammount This Month" column={column} />,
|
||||
accessorKey: 'amount_this_month',
|
||||
header: ({ column }) => <DataGridColumnHeader title="Amount This Month" column={column} />,
|
||||
cell: ({ row }) => {
|
||||
// Get currency code from the nested data structure if available
|
||||
const currencyCode = row.original.balance_type?.currency?.code || 'USD';
|
||||
return formatNumber(row.original.amount_this_month, currencyCode);
|
||||
},
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
meta: {
|
||||
@ -109,16 +139,14 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
|
||||
},
|
||||
{
|
||||
accessorKey: 'CreatedAt',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Created At" column={column} />
|
||||
),
|
||||
cell: ({ row }) =>
|
||||
header: ({ column }) => <DataGridColumnHeader title="Created At" column={column} />,
|
||||
cell: ({ row }) =>
|
||||
new Date(row.original.CreatedAt).toLocaleString('id-ID', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
minute: '2-digit'
|
||||
}),
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
@ -182,22 +210,54 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
|
||||
|
||||
const getWalletLists = async (page: number, limit: number, sorting: any, filter: any) => {
|
||||
try {
|
||||
const sortField = 'CreatedAt';
|
||||
const sortDirection = 'ASC';
|
||||
|
||||
filter = filter.length == 0 ? {} : { name: filter[0].value?.toLowerCase() };
|
||||
const sortField = sorting.length > 0 ? sorting[0].id : 'created_at';
|
||||
const sortDirection = sorting.length > 0 ? (sorting[0].desc ? 'DESC' : 'ASC') : 'ASC';
|
||||
|
||||
// Initialize filter object
|
||||
let filterParams: any = {};
|
||||
|
||||
// Process filter array
|
||||
if (Array.isArray(filter)) {
|
||||
filter.forEach((f: any) => {
|
||||
// Handle MSISDN search
|
||||
if (f.id === 'msisdn' && f.value) {
|
||||
filterParams.msisdn = { like: `%${f.value.toLowerCase()}%` };
|
||||
}
|
||||
|
||||
// Handle date range filter
|
||||
if (f.id === 'CreatedAt' && f.value?.from && f.value?.to) {
|
||||
filterParams.created_at = {
|
||||
from: `${f.value.from} 00:00:00`,
|
||||
to: `${f.value.to} 23:59:59`
|
||||
};
|
||||
}
|
||||
|
||||
// Handle wallet ID filter
|
||||
if (f.id === 'id_wallet' && f.value) {
|
||||
filterParams.id_wallet = f.value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const response = await GetData(`${API_URL_WALLET}/dashboard/balance/`, {
|
||||
limit,
|
||||
page: page + 1,
|
||||
with_deleted: false,
|
||||
order_field: sortField,
|
||||
order_direction: sortDirection,
|
||||
// filter: JSON.stringify(filter)
|
||||
filter: JSON.stringify(filterParams)
|
||||
});
|
||||
|
||||
if (!response || !response.data) {
|
||||
console.warn('No data received:', response);
|
||||
return { data: [], totalCount: 0 };
|
||||
}
|
||||
|
||||
setWallets(response?.data.list);
|
||||
return { data: response?.data.list, totalCount: response?.data.total_count };
|
||||
} catch (error) {
|
||||
console.error('Error fetching Wallet', error);
|
||||
return { data: [], totalCount: 0 };
|
||||
}
|
||||
};
|
||||
|
||||
@ -221,7 +281,6 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
|
||||
pagination={{ size: 10 }}
|
||||
toolbar={<ListToolbar />}
|
||||
layout={{ card: true }}
|
||||
// sorting={[{ id: 'created_at', desc: true }]}
|
||||
serverSide={true}
|
||||
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
|
||||
getWalletLists(pageIndex, pageSize, sorting, columnFilters)
|
||||
|
||||
Reference in New Issue
Block a user