This commit is contained in:
unknown
2025-05-22 12:59:31 +07:00
15 changed files with 1021 additions and 956 deletions

View File

@ -3,8 +3,9 @@ import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTitle
} from '@/components/ui/dialog';
import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config';
@ -19,24 +20,6 @@ import {
} from '@/components/ui/select';
import { DefaultTooltip, KeenIcon } from '@/components';
interface WalletTransaction {
ID: string;
transaction_code: string;
transaction_type: {
id: string;
name: string;
};
type: string;
amount: number;
pre_amount: number;
post_amount: number;
category: string;
notes: string;
date: string;
msisdn_reff?: string;
purpose?: string;
}
interface ShowDetailWalletDialogProps {
open: boolean;
onClose: () => void;
@ -58,107 +41,23 @@ const getDefaultDateRange = () => {
};
};
const columns = [
{
accessorKey: 'transaction_code',
header: ({ column }: any) => <DataGridColumnHeader title="Transaction Code" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[120px]' },
},
{
accessorKey: 'msisdn_reff',
header: ({ column }: any) => <DataGridColumnHeader title="MSISDN Reffer" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[120px]' },
},
{
accessorKey: 'transaction_type.name',
header: ({ column }: any) => <DataGridColumnHeader title="Transaction Type" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[180px]' },
},
{
accessorKey: 'type',
header: ({ column }: any) => <DataGridColumnHeader title="Type" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[80px]' },
},
{
accessorKey: 'amount',
header: ({ column }: any) => <DataGridColumnHeader title="Amount" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue()?.toFixed(2),
meta: { headerClassName: 'min-w-[100px]' },
},
{
accessorKey: 'pre_amount',
header: ({ column }: any) => <DataGridColumnHeader title="Pre Amount" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue()?.toFixed(2),
meta: { headerClassName: 'min-w-[100px]' },
},
{
accessorKey: 'post_amount',
header: ({ column }: any) => <DataGridColumnHeader title="Post Amount" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue()?.toFixed(2),
meta: { headerClassName: 'min-w-[100px]' },
},
{
accessorKey: 'category',
header: ({ column }: any) => <DataGridColumnHeader title="Category" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[80px]' },
},
{
accessorKey: 'date',
header: ({ column }: any) => <DataGridColumnHeader title="Date" column={column} />,
enableSorting: false,
cell: (info: any) => {
const val = info.getValue();
if (!val) return '-';
return new Date(val).toLocaleString('id-ID', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
},
meta: { headerClassName: 'min-w-[150px]' },
},
{
accessorKey: 'purpose',
header: ({ column }: any) => <DataGridColumnHeader title="Purpose" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue() || '-',
meta: { headerClassName: 'min-w-[200px]' },
},
{
accessorKey: 'notes',
header: ({ column }: any) => <DataGridColumnHeader title="Notes" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue() || '-',
meta: { headerClassName: 'min-w-[200px]' },
},
];
const ShowDetailWalletDialog: React.FC<ShowDetailWalletDialogProps> = ({
open,
onClose,
idbalance,
}) => {
const { GetData } = useCallApi();
const [data, setData] = useState<WalletTransaction[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [dateRange, setDateRange] = useState(getDefaultDateRange());
const [selectedTransferType, setSelectedTransferType] = useState<string | null>(null);
const [transferType, setTransferType] = useState<TransferType[]>([]);
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
const [searchValue, setSearchValue] = useState('');
const [transferType, setTransferType] = useState<TransferType[]>([]);
const [category, setCategory] = useState<string[]>([]);
const [transaction, setTransaction] = useState<any[]>([]);
const [filters, setFilters] = useState<any>({});
const fetchTransferType = async () => {
const fetchTransferType = useCallback(async () => {
try {
const response = await GetData(`${apiConfig.service_transaction}/transactiontype/list`, {
limit: 100,
@ -171,71 +70,18 @@ const ShowDetailWalletDialog: React.FC<ShowDetailWalletDialogProps> = ({
} catch (error) {
console.error('Error fetching transfer types', error);
}
};
}, [GetData]);
const getDetailList = useCallback(
async (
limit: number,
page: number,
with_deleted: boolean,
order_field: string,
order_direction: string,
filter: any
): Promise<WalletTransaction[]> => {
if (!idbalance) return [];
try {
const response = await GetData(
`${apiConfig.service_wallet}/dashboard/balance/list-balance-detail/${idbalance}`,
{
limit,
page,
with_deleted,
order_field,
order_direction,
filter: JSON.stringify(filter),
}
);
return response?.data?.list || [];
} catch (error) {
console.error('Error fetching wallet detail:', error);
return [];
}
},
[GetData, idbalance]
);
useEffect(() => {
fetchTransferType();
}, [fetchTransferType]);
const fetchData = useCallback(
async (params: {
pageIndex: number;
pageSize: number;
sorting: Array<{ id: string; desc: boolean }>;
columnFilters: any[];
}): Promise<{ data: WalletTransaction[] }> => {
// setIsLoading(true);
const order_field = params.sorting.length ? params.sorting[0].id : 'date';
const order_direction = params.sorting.length && params.sorting[0].desc ? 'DESC' : 'ASC';
const result = await getDetailList(
params.pageSize,
params.pageIndex + 1,
false,
order_field,
order_direction,
params.columnFilters
);
setData(result);
setIsLoading(false);
return { data: result };
},
[getDetailList]
);
// Ambil unique category dari data transaksi setelah data di-fetch
useEffect(() => {
const uniqueCategories = Array.from(
new Set(data.map((tx) => tx.category).filter((cat) => !!cat))
new Set(transaction.map((tx) => tx.category).filter((cat) => !!cat))
);
setCategory(uniqueCategories);
}, [data]);
}, [transaction]);
const handleTransferTypeChange = (value: string) => {
setSelectedTransferType(value === 'all' ? null : value);
@ -250,30 +96,151 @@ const ShowDetailWalletDialog: React.FC<ShowDetailWalletDialogProps> = ({
setSelectedTransferType(null);
setSelectedCategory(null);
setSearchValue('');
setFilters({});
};
useEffect(() => {
fetchTransferType();
}, []);
const handleApplyFilters = () => {
const appliedFilters: any = {};
useEffect(() => {
if (!open) return;
if (dateRange.from && dateRange.to) {
const fromDate = new Date(`${dateRange.from}T00:00:00Z`);
const toDate = new Date(`${dateRange.to}T23:59:59Z`);
appliedFilters.date = {
from: fromDate.toISOString(),
to: toDate.toISOString(),
};
}
const filters = [];
if (selectedTransferType) {
appliedFilters.transaction_type_id = selectedTransferType;
}
if (dateRange.from) filters.push({ id: 'date', value: { gte: dateRange.from } });
if (dateRange.to) filters.push({ id: 'date', value: { lte: dateRange.to } });
if (selectedTransferType) filters.push({ id: 'transaction_type.id', value: selectedTransferType });
if (selectedCategory) filters.push({ id: 'category', value: selectedCategory });
if (searchValue) filters.push({ id: 'transaction_code', value: searchValue });
if (selectedCategory) {
appliedFilters.category = selectedCategory;
}
fetchData({
pageIndex: 0,
pageSize: 10,
sorting: [{ id: 'date', desc: true }],
columnFilters: filters,
});
}, [dateRange, selectedTransferType, selectedCategory, searchValue, open]);
if (searchValue) {
appliedFilters.transaction_code = searchValue;
}
setFilters(appliedFilters);
};
const columns = [
{
accessorKey: 'transaction_code',
header: ({ column }: any) => <DataGridColumnHeader title="Transaction Code" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[120px]' },
},
{
accessorKey: 'msisdn_reff',
header: ({ column }: any) => <DataGridColumnHeader title="MSISDN Reffer" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[120px]' },
},
{
accessorKey: 'transaction_type.name',
header: ({ column }: any) => <DataGridColumnHeader title="Transaction Type" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[180px]' },
},
{
accessorKey: 'type',
header: ({ column }: any) => <DataGridColumnHeader title="Type" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[80px]' },
},
{
accessorKey: 'amount',
header: ({ column }: any) => <DataGridColumnHeader title="Amount" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue()?.toFixed(2),
meta: { headerClassName: 'min-w-[100px]' },
},
{
accessorKey: 'pre_amount',
header: ({ column }: any) => <DataGridColumnHeader title="Pre Amount" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue()?.toFixed(2),
meta: { headerClassName: 'min-w-[100px]' },
},
{
accessorKey: 'post_amount',
header: ({ column }: any) => <DataGridColumnHeader title="Post Amount" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue()?.toFixed(2),
meta: { headerClassName: 'min-w-[100px]' },
},
{
accessorKey: 'category',
header: ({ column }: any) => <DataGridColumnHeader title="Category" column={column} />,
enableSorting: false,
meta: { headerClassName: 'min-w-[80px]' },
},
{
accessorKey: 'date',
header: ({ column }: any) => <DataGridColumnHeader title="Date" column={column} />,
enableSorting: false,
cell: (info: any) => {
const val = info.getValue();
if (!val) return '-';
return new Date(val).toLocaleString('id-ID', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
},
meta: { headerClassName: 'min-w-[150px]' },
},
{
accessorKey: 'purpose',
header: ({ column }: any) => <DataGridColumnHeader title="Purpose" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue() || '-',
meta: { headerClassName: 'min-w-[200px]' },
},
{
accessorKey: 'notes',
header: ({ column }: any) => <DataGridColumnHeader title="Notes" column={column} />,
enableSorting: false,
cell: (info: any) => info.getValue() || '-',
meta: { headerClassName: 'min-w-[200px]' },
},
];
const getTransactionLists = useCallback(
async (page: number, limit: number, sorting: any, _columnFilters: any) => {
// console.log(idbalance);
try {
const response = await GetData(`${apiConfig.service_wallet}/dashboard/balance/list-balance-detail/${idbalance}`, {
limit,
page: page + 1,
with_deleted: false,
order_field: "created_at",
order_direction: 'DESC',
filter: JSON.stringify(filters)
});
// console.log(filters);
if (!response || !response.data) {
console.warn('No data received:', response);
return { data: [], totalCount: 0 };
}
setTransaction(response.data.list);
return { data: response.data.list, totalCount: response.data.total_count };
} catch (error) {
console.error('Error fetching transaction', error);
return { data: [], totalCount: 0 };
}
},
[GetData, idbalance, filters]
);
return (
<Dialog open={open} onOpenChange={onClose}>
@ -281,98 +248,98 @@ const ShowDetailWalletDialog: React.FC<ShowDetailWalletDialogProps> = ({
<DialogHeader>
<DialogTitle>Details Wallet Statement</DialogTitle>
</DialogHeader>
<DialogDescription />
<DialogBody>
<div className="py-4 max-h-[70vh] overflow-y-auto">
{/* <div className="flex flex-wrap gap-2 lg:gap-5 w-full mb-4">
<div className="flex flex-wrap gap-3 w-full">
<label className="input input-sm w-full sm:w-[160px]">
From
<input
type="date"
value={dateRange.from}
onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
/>
</label>
<div className="flex flex-wrap gap-2 lg:gap-5 w-full mb-4">
<div className="flex flex-wrap gap-3 w-full">
<label className="input input-sm w-full 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-full 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-full sm:w-[160px]">
To
<input
type="date"
value={dateRange.to}
onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
/>
</label>
<div className="w-full sm:w-[160px]">
<Select value={selectedTransferType || 'all'} onValueChange={handleTransferTypeChange}>
<SelectTrigger className="h-[32px]">
<SelectValue placeholder="Transaction Type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Select Transaction</SelectItem>
{transferType.map((transfer) => (
<SelectItem key={transfer.id} value={transfer.id}>
{transfer.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="w-full sm:w-[160px]">
<Select value={selectedCategory ?? ''} onValueChange={handleCategoryChange}>
<SelectTrigger className="h-[32px]">
<SelectValue placeholder="Select Category" />
</SelectTrigger>
<SelectContent>
{category.length === 0 ? (
<div className="text-gray-500 px-4 py-2">No data</div>
) : (
category.map((cat) => (
<SelectItem key={cat} value={cat}>
{cat}
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
<label className="input input-sm w-full sm:w-[160px]">
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder="Transaction Code"
className="overflow-hidden text-ellipsis w-full"
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
</label>
<DefaultTooltip title="Reset Filter" placement="top">
<Button variant="outline" className="h-8" onClick={handleClearAllFilters}>
<KeenIcon icon="arrow-circle-left" />
</Button>
</DefaultTooltip>
<div className="w-full sm:w-[160px]">
<Select value={selectedTransferType || 'all'} onValueChange={handleTransferTypeChange}>
<SelectTrigger className="h-[32px]">
<SelectValue placeholder="Transaction Type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Select Transaction</SelectItem>
{transferType.map((transfer) => (
<SelectItem key={transfer.id} value={transfer.id}>
{transfer.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div> */}
<div className="w-full sm:w-[160px]">
<Select value={selectedCategory ?? ''} onValueChange={handleCategoryChange}>
<SelectTrigger className="h-[32px]">
<SelectValue placeholder="Select Category" />
</SelectTrigger>
<SelectContent>
{category.length === 0 ? (
<div className="text-gray-500 px-4 py-2">No data</div>
) : (
category.map((cat) => (
<SelectItem key={cat} value={cat}>
{cat}
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
<label className="input input-sm w-full sm:w-[160px]">
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder="Transaction Code"
className="overflow-hidden text-ellipsis w-full"
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
</label>
<DefaultTooltip title="Reset Filter" placement="top">
<Button variant="outline" className="h-8" onClick={handleClearAllFilters}>
<KeenIcon icon="arrow-circle-left" />
</Button>
</DefaultTooltip>
<Button variant="outline" className="h-8" onClick={handleApplyFilters}>
Filter Data
</Button>
</div>
</div>
<div className="py-4 max-h-[70vh] overflow-y-auto">
<DataGridProvider
key={JSON.stringify(filters)}
columns={columns}
data={data}
pagination={{ size: 10 }}
toolbar={null}
layout={{ card: true }}
sorting={[{ id: 'date', desc: true }]}
serverSide={false}
onFetchData={async (params) => {
return await fetchData({
pageIndex: params.pageIndex,
pageSize: params.pageSize,
sorting: params.sorting ?? [],
columnFilters: params.columnFilters ?? [],
});
}}
sorting={[{ id: 'id', desc: false }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
getTransactionLists(pageIndex, pageSize, sorting, columnFilters)
}
/>
</div>
</DialogBody>
@ -381,4 +348,4 @@ const ShowDetailWalletDialog: React.FC<ShowDetailWalletDialogProps> = ({
);
};
export default ShowDetailWalletDialog;
export default ShowDetailWalletDialog;

View File

@ -23,7 +23,7 @@ const HistoryTransactionDisbursement = () => {
</Link>
<Link underline="none" color="inherit">
<span className="text-sm">History Disbursement</span>
<span className="text-sm">Disbursement</span>
</Link>
</Breadcrumbs>
<div className="grid gap-5 lg:gap-7.5">

View File

@ -94,66 +94,65 @@ const DetailTransaction = () => {
}
}, [showDetailDialog]);
const handleExport = async () => {
if (!selectedTransactionId || !transactionDetails) return;
const handleExport = async () => {
if (!selectedTransactionId || !transactionDetails) return;
setIsExporting(true);
try {
const response = await fetch(
`${API_URL}/transaction/export?id_disbursment=${selectedTransactionId}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${getAuth()?.access_token}`
setIsExporting(true);
try {
const response = await fetch(
`${API_URL}/transaction/export?id_disbursment=${selectedTransactionId}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${getAuth()?.access_token}`
}
}
);
if (!response.ok) {
throw new Error('Failed to fetch file');
}
const blob = await response.blob();
const contentDisposition = response.headers.get('content-disposition');
const executionDate = transactionDetails.execution_date;
const formattedDate = executionDate
? moment(executionDate).format('YYYYMMDD_HHmm')
: moment().format('YYYYMMDD_HHmm');
let filename = `transaction_${formattedDate}.xlsx`;
if (contentDisposition) {
const filenameMatch = contentDisposition.match(/filename\*?=(?:UTF-8'')?"?([^;"\n]*)"?/);
if (filenameMatch && filenameMatch[1]) {
filename = decodeURIComponent(filenameMatch[1]);
}
}
);
if (!response.ok) {
throw new Error('Failed to fetch file');
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
toast.success('Export successful');
} catch (error) {
console.error('Error exporting transaction:', error);
toast.error('Failed to export transaction');
} finally {
setIsExporting(false);
}
const blob = await response.blob();
const contentDisposition = response.headers.get('content-disposition');
const executionDate = transactionDetails.execution_date;
const formattedDate = executionDate
? moment(executionDate).format('YYYYMMDD_HHmm')
: moment().format('YYYYMMDD_HHmm');
let filename = `transaction_${formattedDate}.xlsx`;
if (contentDisposition) {
const filenameMatch = contentDisposition.match(/filename\*?=(?:UTF-8'')?"?([^;"\n]*)"?/);
if (filenameMatch && filenameMatch[1]) {
filename = decodeURIComponent(filenameMatch[1]);
}
}
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
toast.success('Export successful');
} catch (error) {
console.error('Error exporting transaction:', error);
toast.error('Failed to export transaction');
} finally {
setIsExporting(false);
}
};
};
return (
<Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
<DialogContent className="container-fixed max-w-[1280px] w-full h-[90vh] flex flex-col p-6 overflow-hidden">
<DialogHeader>
<DialogHeader>
<DialogTitle className="text-2xl font-bold">Transaction Details</DialogTitle>
</DialogHeader>
<DialogBody>
<DialogBody className="flex flex-col overflow-hidden h-full">
<div className="py-4 overflow-y-auto max-h-[600px] space-y-6">
{/* Summary Info */}
{transactionDetails && (
@ -213,7 +212,6 @@ const handleExport = async () => {
</div>
)}
{/* Log Table */}
<div className="border rounded-lg overflow-x-auto">
{isLoading ? (
<div className="flex flex-col items-center justify-center p-8">
@ -229,96 +227,113 @@ const handleExport = async () => {
<p className="mt-4 text-gray-500">Loading Logs Details...</p>
</div>
) : (
<table className="min-w-full table-auto">
<thead>
<tr className="bg-gray-100">
<th className="px-4 py-2 text-left text-sm text-gray-500">Username</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Fullname</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Amount</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Status</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Process Date</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Invoice Number</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Remark 1</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Remark 2</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Remark 3</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Actions</th>
</tr>
</thead>
<tbody>
{transactionDetails?.log && transactionDetails.log.length > 0 ? (
transactionDetails.log.map((log: any, index: number) => (
<tr key={index} className="border-t">
<td className="px-4 py-2 text-sm text-gray-500">
{log.customer?.username ?? 'Not Found'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.customer?.fullname ?? 'Not Found'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">{log.amount ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">
{renderStatusBadge(log.status) ?? '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.request_date && moment(log.request_date).isValid()
? moment(log.request_date).format('DD/MM/YYYY HH:mm')
: '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.reference ?? '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">{log.remark_1 ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">{log.remark_2 ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">{log.remark_3 ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => {
setDetailLogData(log);
setShowDetailLogDialog(true);
}}
>
<KeenIcon icon="eye" />
</button>
</td>
<>
<div className="flex justify-end m-5">
<button
className={`px-5 py-2 bg-green-600 text-white font-semibold rounded-lg hover:bg-green-700 transition-colors flex items-center ${isExporting ? 'opacity-50 pointer-events-none' : ''}`}
onClick={() => {
if (!isExporting) {
handleExport();
}
}}
>
{isExporting ? (
<>
<span className="animate-spin ">
<KeenIcon icon="spinner" />
</span>
Exporting...
</>
) : (
<>
<KeenIcon icon="download" />
Export
</>
)}
</button>
</div>
<div className="max-h-[900px] overflow-y-auto border rounded-lg">
<table className="min-w-full table-auto">
<thead>
<tr className="bg-gray-100">
<th className="px-4 py-2 text-left text-sm text-gray-500">Username</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Fullname</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Amount</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Status</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">
Process Date
</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">
Invoice Number
</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Remark 1</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Remark 2</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Remark 3</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Actions</th>
</tr>
))
) : (
<tr>
<td colSpan={10} className="px-4 py-2 text-center text-sm text-gray-500">
No logs available
</td>
</tr>
)}
</tbody>
</table>
</thead>
<tbody>
{transactionDetails?.log && transactionDetails.log.length > 0 ? (
transactionDetails.log.map((log: any, index: number) => (
<tr key={index} className="border-t">
<td className="px-4 py-2 text-sm text-gray-500">
{log.customer?.username ?? 'Not Found'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.customer?.fullname ?? 'Not Found'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.amount ?? '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{renderStatusBadge(log.status) ?? '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.request_date && moment(log.request_date).isValid()
? moment(log.request_date).format('DD/MM/YYYY HH:mm')
: '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.reference ?? '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.remark_1 ?? '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.remark_2 ?? '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{log.remark_3 ?? '-'}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => {
setDetailLogData(log);
setShowDetailLogDialog(true);
}}
>
<KeenIcon icon="eye" />
</button>
</td>
</tr>
))
) : (
<tr>
<td
colSpan={10}
className="px-4 py-2 text-center text-sm text-gray-500"
>
No logs available
</td>
</tr>
)}
</tbody>
</table>
</div>
</>
)}
</div>
{/* Export Button - Moved to bottom right after table */}
<div className="flex justify-end">
<button
className={`px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center ${isExporting ? 'opacity-50 pointer-events-none' : ''}`}
onClick={() => {
if (!isExporting) {
handleExport();
}
}}
>
{isExporting ? (
<>
<span className="animate-spin mr-2">
<KeenIcon icon="spinner" />
</span>
Exporting...
</>
) : (
<>
<KeenIcon icon="download" className="mr-2" />
Export
</>
)}
</button>
</div>
</div>
</DialogBody>
</DialogContent>
@ -326,4 +341,4 @@ const handleExport = async () => {
);
};
export default DetailTransaction;
export default DetailTransaction;

View File

@ -285,7 +285,7 @@ const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
pagination={{ size: 10 }}
toolbar={<ListToolbar />}
layout={{ card: true }}
sorting={[{ id: 'execution_date', desc: false }]}
sorting={[{ id: 'execution_date', desc: true }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
getTransactionLists(pageIndex, pageSize, sorting, columnFilters)

View File

@ -14,76 +14,61 @@ import {
const ListToolbar = () => {
const { table, reload } = useDataGrid();
// Set the initial state for trxDate
// State untuk filter
const [trxDate, settrxDate] = useState({ from: '', to: '' });
const [statusApproval, setStatusApproval] = useState<string>(
(table.getColumn('status_approve')?.getFilterValue() as string) ?? ''
);
const [statusApproval, setStatusApproval] = useState<string>('');
const [searchValue, setSearchValue] = useState<string>('');
const [typeSearchValue, setSearchTypeValue] = useState<string>('');
useEffect(() => {
const timer = setTimeout(() => {
table.getColumn('status_approve')?.setFilterValue(statusApproval);
table.setPageIndex(0);
}, 200);
return () => clearTimeout(timer);
}, [statusApproval, table]);
// Function to format date to YYYY-MM-DD
const formatDate = (date: Date): string => {
return date.toISOString().split('T')[0];
};
const [searchValue, setSearchValue] = useState<string>();
const [typeSearchValue, setSearchTypeValue] = useState<string>();
// useEffect to set the default date values
// Set tanggal default saat pertama mount
useEffect(() => {
const today = new Date();
// const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const formatDate = (date: Date) => date.toISOString().split('T')[0];
settrxDate({
from: formatDate(today),
to: formatDate(today),
});
}, []);
// Fungsi untuk apply semua filter sekaligus saat tombol Filter ditekan
const handleFilterData = useCallback(() => {
try {
if (!trxDate.from || !trxDate.to) {
toast.error('Please select From and To dates');
return;
}
// Set filter tanggal
table.getColumn('transaction_date')?.setFilterValue(trxDate);
// Set filter status approval
table.getColumn('status_approve')?.setFilterValue(statusApproval || '');
// Set filter search type sebagai column filter id 'searchtype'
table.setColumnFilters((prevFilters) => {
// Hapus dulu filter dengan id 'searchtype' dan 'code' agar gak duplikat
const filtered = prevFilters.filter(
(f) => f.id !== 'searchtype' && f.id !== 'code'
);
// Tambahkan filter baru jika ada
if (typeSearchValue) {
filtered.push({ id: 'searchtype', value: typeSearchValue });
}
if (searchValue) {
filtered.push({ id: 'code', value: searchValue });
}
return filtered;
});
// Reset ke halaman pertama
table.setPageIndex(0);
} catch (error) {
toast.error('Error applying filter');
console.error('Error applying filter:', error);
console.error(error);
}
}, [trxDate, table]);
useEffect(() => {
const timer = setTimeout(() => {
// Add search type filter to column filters
table.setColumnFilters((prev) => [
...prev.filter((f) => f.id !== 'searchtype'),
{ id: 'searchtype', value: typeSearchValue },
]);
table.setPageIndex(0);
}, 200);
return () => clearTimeout(timer);
}, [typeSearchValue, table]);
useEffect(() => {
const timer = setTimeout(() => {
table.getColumn('code')?.setFilterValue(searchValue);
table.setPageIndex(0);
}, 200);
return () => clearTimeout(timer);
}, [searchValue, table]);
useEffect(() => {
if (trxDate.from && trxDate.to) {
handleFilterData();
}
}, [trxDate]);
}, [trxDate, statusApproval, searchValue, typeSearchValue, table]);
return (
<div className="card-header flex-wrap gap-2 border-b-0 px-5">
@ -93,11 +78,8 @@ const ListToolbar = () => {
From
<input
type="date"
placeholder="From"
value={trxDate.from}
onChange={(event) =>
settrxDate({ ...trxDate, from: event.target.value })
}
onChange={(e) => settrxDate({ ...trxDate, from: e.target.value })}
name="from"
/>
</label>
@ -106,20 +88,15 @@ const ListToolbar = () => {
To
<input
type="date"
placeholder="To"
value={trxDate.to}
onChange={(event) =>
settrxDate({ ...trxDate, to: event.target.value })
}
onChange={(e) => settrxDate({ ...trxDate, to: e.target.value })}
name="to"
/>
</label>
<Select
value={statusApproval}
onValueChange={(value) => {
setStatusApproval(value);
}}
onValueChange={setStatusApproval}
>
<SelectTrigger className="input input-sm w-[160px] h-[31px]">
<SelectValue placeholder="Select Status" />
@ -133,9 +110,7 @@ const ListToolbar = () => {
<Select
value={typeSearchValue}
onValueChange={(value) => {
setSearchTypeValue(value);
}}
onValueChange={setSearchTypeValue}
>
<SelectTrigger className="input input-sm w-[250px] h-[31px]">
<SelectValue placeholder="Select Search Type" />
@ -151,12 +126,16 @@ const ListToolbar = () => {
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder={`Search ${typeSearchValue || ''}`} // Use typeSearchValue if it's set, else fallback to an empty string
placeholder={`Search ${typeSearchValue || ''}`}
value={searchValue}
onChange={(event) => setSearchValue(event.target.value)}
onChange={(e) => setSearchValue(e.target.value)}
/>
</label>
{/* Tombol Filter */}
<Button onClick={handleFilterData}>
Filter
</Button>
</div>
<div className="ml-auto">
@ -166,23 +145,22 @@ const ListToolbar = () => {
className="h-7.5"
onClick={() => {
const today = new Date();
// const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const formatDate = (date: Date) => date.toISOString().split('T')[0];
// Resetting all filters
// Reset semua filter dan tanggal ke hari ini
setSearchValue('');
setStatusApproval('');
settrxDate({
from: formatDate(today),
to: formatDate(today),
});
settrxDate({ from: formatDate(today), to: formatDate(today) });
setSearchTypeValue('');
// Reset filter di tabel
table.getColumn('code')?.setFilterValue('');
table.getColumn('status_approve')?.setFilterValue('');
table.getColumn('transaction_date')?.setFilterValue('');
table.setColumnFilters([]);
table.setPageIndex(0);
reload(); // Reload table data
reload();
}}
>
<KeenIcon icon="arrows-circle" />

View File

@ -1,7 +1,7 @@
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { useTransactionContext } from '../hooks/useTransactionContext';
import { Button } from '@/components/ui/button';
import { useCallback, useState, useEffect } from 'react';
import { useCallback, useState, useEffect, useRef } from 'react';
import { toast } from 'sonner';
import {
Select,
@ -17,8 +17,8 @@ import { getAuth } from '@/auth';
const ListToolbar = () => {
const { table, reload } = useDataGrid();
const [trxDate, settrxDate] = useState({ from: '', to: '' });
const [searchValue, setSearchValue] = useState<string>(''); // default: empty string
const [typeSearchValue, setSearchTypeValue] = useState<string>(''); // default: empty string
const [searchValue, setSearchValue] = useState<string>('');
const [typeSearchValue, setSearchTypeValue] = useState<string>('');
const [typeValue, setTypeValue] = useState<string>(
(table.getState().columnFilters.find(f => f.id === 'kind')?.value as string) ?? ''
);
@ -26,62 +26,44 @@ const ListToolbar = () => {
const { GetData } = useCallApi();
const API_URL = apiConfig.transaction;
const formatDate = (date: Date): string => {
return date.toISOString().split('T')[0];
};
const formatDate = (date: Date): string => date.toISOString().split('T')[0];
// Set tanggal default hari ini saat mount
useEffect(() => {
const today = new Date();
settrxDate({
from: formatDate(today),
to: formatDate(today),
});
const formatted = formatDate(today);
settrxDate({ from: formatted, to: formatted });
}, []);
useEffect(() => {
const timer = setTimeout(() => {
table.setColumnFilters((prev) => [
...prev.filter((f) => f.id !== 'kind'),
{ id: 'kind', value: typeValue },
]);
table.setPageIndex(0);
}, 200);
return () => clearTimeout(timer);
}, [typeValue, table]);
useEffect(() => {
const timer = setTimeout(() => {
table.setColumnFilters((prev) => [
...prev.filter((f) => f.id !== 'searchtype'),
{ id: 'searchtype', value: typeSearchValue },
]);
table.setPageIndex(0);
}, 200);
return () => clearTimeout(timer);
}, [typeSearchValue, table]);
useEffect(() => {
const timer = setTimeout(() => {
table.getColumn('code')?.setFilterValue(searchValue);
table.setPageIndex(0);
}, 200);
return () => clearTimeout(timer);
}, [searchValue, table]);
// **Hilangkan semua useEffect yang auto apply filter saat input berubah**
// Karena kamu mau filter apply hanya lewat tombol Filter
// Fungsi untuk apply SEMUA filter sekaligus saat tombol Filter diklik
const handleFilterData = useCallback(() => {
try {
table.getColumn('transaction_date')?.setFilterValue(trxDate);
} catch (error) {
toast.error('Error applying filter');
console.error('Error applying filter:', error);
if (!trxDate.from || !trxDate.to) {
toast.error('Please select both From and To dates');
return;
}
}, [trxDate, table]);
useEffect(() => {
if (trxDate.from && trxDate.to) {
handleFilterData();
}
}, [trxDate]);
// Terapkan filter tanggal
table.getColumn('transaction_date')?.setFilterValue(trxDate);
// Terapkan filter jenis transaksi (kind)
table.setColumnFilters((prev) => {
// Hapus filter 'kind' dan 'searchtype' agar bisa set ulang
const others = prev.filter(f => f.id !== 'kind' && f.id !== 'searchtype' && f.id !== 'code');
// Bangun array baru dengan filter yang diinginkan
const filters: any[] = [...others];
if (typeValue) filters.push({ id: 'kind', value: typeValue });
if (typeSearchValue) filters.push({ id: 'searchtype', value: typeSearchValue });
if (searchValue) filters.push({ id: 'code', value: searchValue });
return filters;
});
table.setPageIndex(0);
}, [trxDate, typeValue, typeSearchValue, searchValue, table]);
const exporDataToExcel = async (
typeSearchValue: string,
@ -93,8 +75,8 @@ const ListToolbar = () => {
const formattedFilter: any = {
"Transactions.transaction_date": {
from: `${trxDate.from} 00:00:00`,
to: `${trxDate.to} 23:59:59`
}
to: `${trxDate.to} 23:59:59`,
},
};
if (typeSearchValue === 'msisdn') {
@ -106,17 +88,20 @@ const ListToolbar = () => {
}
if (typeValue) {
formattedFilter["Transactions.kind"] = typeValue;
formattedFilter['Transactions.kind'] = typeValue;
}
const filterParam = encodeURIComponent(JSON.stringify(formattedFilter));
const response = await fetch(`${API_URL}/transaction/export?filter=${filterParam}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${getAuth()?.access_token}`, // ganti dengan token kamu
const response = await fetch(
`${API_URL}/transaction/export?filter=${filterParam}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${getAuth()?.access_token}`,
},
}
});
);
if (!response.ok) {
throw new Error('Failed to fetch file');
@ -161,16 +146,11 @@ const ListToolbar = () => {
name="to"
/>
</label>
<Select
value={typeValue}
onValueChange={(value) => setTypeValue(value)}
>
<Select value={typeValue} onValueChange={(value) => setTypeValue(value)}>
<SelectTrigger className="input input-sm w-[250px] h-[31px]">
<SelectValue placeholder="Select Transaction Type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="T">TRANSFER</SelectItem>
<SelectItem value="P">PURCHASE</SelectItem>
<SelectItem value="W">WITHDRAW</SelectItem>
@ -193,10 +173,7 @@ const ListToolbar = () => {
</SelectContent>
</Select>
<Select
value={typeSearchValue}
onValueChange={(value) => setSearchTypeValue(value)}
>
<Select value={typeSearchValue} onValueChange={(value) => setSearchTypeValue(value)}>
<SelectTrigger className="input input-sm w-[250px] h-[31px]">
<SelectValue placeholder="Select Search Type" />
</SelectTrigger>
@ -216,6 +193,11 @@ const ListToolbar = () => {
onChange={(event) => setSearchValue(event.target.value)}
/>
</label>
<Button className="h-7.5" onClick={handleFilterData}>
Filter
</Button>
</div>
<div className="ml-auto flex gap-2">
@ -245,28 +227,17 @@ const ListToolbar = () => {
Export Data
</Button>
<DefaultTooltip title={'Refresh'} placement={'top'}>
<Button
variant="outline"
className="h-7.5"
onClick={() => {
const today = new Date();
setSearchValue('');
setSearchTypeValue('');
setTypeValue('');
settrxDate({
from: formatDate(today),
to: formatDate(today),
});
table.setColumnFilters([
{ id: 'code', value: '' },
{ id: 'kind', value: '' },
]);
settrxDate({ from: formatDate(today), to: formatDate(today) });
table.setColumnFilters([]);
table.setPageIndex(0);
reload();
}}

View File

@ -1,363 +0,0 @@
import { useEffect, useState } from 'react';
import {
Dialog,
DialogBody,
DialogContent,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { useManageWalletContext } from '../hooks/useManageWalletHistoryContext';
import { DefaultTooltip, KeenIcon } from '@/components';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config';
const formatDate = (date: Date) => date.toLocaleDateString('sv-SE');
const API_URL_WALLET = apiConfig.service_wallet;
const API_URL = apiConfig.service_transaction;
interface TransferType {
id: string;
name: string;
}
interface WalletTransaction {
ID: string;
id_balance: string;
transaction_code: string;
transaction_type: {
id: string;
name: string;
};
type: string;
amount: number;
pre_amount: number;
post_amount: number;
category: string;
notes: string;
date: string;
}
const ShowDialog = () => {
const { showDetailDialog, setShowDetailDialog, selectedWallet } = useManageWalletContext();
const [isLoading, setIsLoading] = useState(false);
const { GetData } = useCallApi();
const [transferType, setTransferType] = useState<TransferType[]>([]);
const [transactions, setTransactions] = useState<WalletTransaction[]>([]);
const [filteredTransactions, setFilteredTransactions] = useState<WalletTransaction[]>([]);
const [category, setCategory] = useState<string[]>([]);
const getDefaultDateRange = () => {
const today = new Date();
const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
return {
from: formatDate(sevenDaysAgo),
to: formatDate(today)
};
};
useEffect(() => {
const uniqueCategories = Array.from(
new Set(transactions.map((transaction) => transaction.category))
);
setCategory(uniqueCategories);
}, [transactions]);
const [dateRange, setDateRange] = useState(getDefaultDateRange());
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
const [selectedTransferType, setSelectedTransferType] = useState<string | null>(null);
const [searchValue, setSearchValue] = useState('');
const fetchTransferType = async () => {
try {
const response = await GetData(`${API_URL}/transactiontype/list`, {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'created_at',
order_direction: 'ASC'
});
setTransferType(response?.data?.list || []);
} catch (error) {
console.error('Error fetching transfer type', error);
}
};
useEffect(() => {
fetchTransferType();
}, []);
useEffect(() => {
const fetchWalletTransactions = async () => {
if (!selectedWallet?.ID || !showDetailDialog) return;
setIsLoading(true);
try {
const response = await GetData(
`${API_URL_WALLET}/dashboard/balance/list-balance-detail/${selectedWallet.ID}`,
{
limit: 100,
page: 1,
order_field: 'created_at',
order_direction: 'DESC'
}
);
const transactionData =
response?.data?.list || (Array.isArray(response?.data) ? response.data : []);
// console.log('Loaded Transactions:', transactionData);
setTransactions(transactionData);
setFilteredTransactions(transactionData);
} catch (error) {
console.error('Error fetching balance:', error);
} finally {
setIsLoading(false);
}
};
fetchWalletTransactions();
}, [showDetailDialog, selectedWallet, GetData]);
useEffect(() => {
if (transactions.length === 0) return;
setIsLoading(true);
const timer = setTimeout(() => {
// console.log('Debugging Filter - Selected Transfer Type:', selectedTransferType);
const filtered = transactions.filter((transaction) => {
// console.log('Transaction Type:', {
// id: transaction.transaction_type?.id,
// expected: selectedTransferType,
// match: transaction.transaction_type?.id === selectedTransferType
// });
const transactionDate = new Date(transaction.date);
const fromDate = new Date(dateRange.from);
const toDate = new Date(dateRange.to);
fromDate.setHours(0, 0, 0, 0);
toDate.setHours(23, 59, 59, 999);
const dateMatch = transactionDate >= fromDate && transactionDate <= toDate;
const typeMatch = selectedTransferType
? transaction.transaction_type?.id === selectedTransferType
: true;
const codeMatch = searchValue
? transaction.transaction_code.toLowerCase().includes(searchValue.toLowerCase())
: true;
const categoryMatch = selectedCategory ? transaction.category === selectedCategory : true;
return dateMatch && typeMatch && codeMatch && categoryMatch;
});
// console.log('Filtered Results Count:', filtered.length);
setFilteredTransactions(filtered);
setIsLoading(false);
}, 300);
return () => clearTimeout(timer);
}, [dateRange, transactions, selectedTransferType, searchValue, selectedCategory]);
const handleCategoryChange = (value: string) => {
setSelectedCategory(value);
};
const handleTransferTypeChange = (value: string) => {
// console.log('Transfer Type Changed:', value);
setSelectedTransferType(value === 'all' ? null : value);
};
const handleClearAllFilters = () => {
setDateRange(getDefaultDateRange());
setSelectedTransferType(null);
setSearchValue('');
setSelectedCategory(null);
};
useEffect(() => {
if (!showDetailDialog) return;
const checkNewDay = () => {
const now = new Date();
const currentDate = formatDate(now);
const fromDate = new Date(dateRange.from);
if (
currentDate !== formatDate(new Date(dateRange.to)) &&
now.getTime() - fromDate.getTime() > 7 * 24 * 60 * 60 * 1000
) {
setDateRange(getDefaultDateRange());
toast.info('Date range has been updated to the current period');
}
};
checkNewDay();
const interval = setInterval(checkNewDay, 60 * 60 * 1000);
return () => clearInterval(interval);
}, [showDetailDialog, dateRange]);
return (
<Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
<DialogContent className="max-w-[95vw] sm:max-w-[1200px] p-4 overflow-hidden">
<DialogHeader>
<DialogTitle>Details Wallet Statement</DialogTitle>
</DialogHeader>
<DialogBody>
<div className="flex flex-wrap gap-2 lg:gap-5 w-full mb-4">
<div className="flex flex-wrap gap-3 w-full">
<label className="input input-sm w-full sm:w-[160px]">
From
<input
type="date"
placeholder="From"
value={dateRange.from}
onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
/>
</label>
<label className="input input-sm w-full sm:w-[160px]">
To
<input
type="date"
placeholder="To"
value={dateRange.to}
onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
/>
</label>
<div className="w-full sm:w-[160px]">
<Select
value={selectedTransferType || 'all'}
onValueChange={handleTransferTypeChange}
>
<SelectTrigger className="h-[32px]">
<SelectValue placeholder="Transaction Type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Select Transaction</SelectItem>
{transferType.map((transfer) => (
<SelectItem
key={transfer.id}
value={transfer.id} // Pastikan tidak ada .toString() di sini
>
{transfer.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="w-full sm:w-[160px]">
<Select value={selectedCategory ?? ''} onValueChange={handleCategoryChange}>
<SelectTrigger className="h-[32px]">
<SelectValue placeholder="Select Category" />
</SelectTrigger>
<SelectContent>
{category.length === 0 ? (
<div className="text-gray-500 px-4 py-2">No data</div>
) : (
category.map((cat) => (
<SelectItem key={cat} value={cat}>
{cat}
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
<label className="input input-sm w-full sm:w-[160px]">
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder="Transaction Code"
className="overflow-hidden text-ellipsis w-full"
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
</label>
<DefaultTooltip title={'Reset Filter'} placement={'top'}>
<Button
variant="outline"
className="h-8 disabled:bg-gray-400"
onClick={handleClearAllFilters}
>
<KeenIcon icon="arrow-circle-left" />
</Button>
</DefaultTooltip>
</div>
</div>
<div className="py-4 max-h-[70vh] overflow-y-auto">
{isLoading ? (
<div className="text-center text-gray-500">Loading details...</div>
) : filteredTransactions.length > 0 ? (
<div className="w-full">
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="bg-gray-100 text-left">
<th className="p-3 text-sm min-w-[120px]">Transaction Code</th>
<th className="p-3 text-sm min-w-[180px]">Transaction Type</th>
<th className="p-3 text-sm min-w-[80px]">Type</th>
<th className="p-3 text-sm min-w-[100px]">Amount</th>
<th className="p-3 text-sm min-w-[100px]">Pre Amount</th>
<th className="p-3 text-sm min-w-[100px]">Post Amount</th>
<th className="p-3 text-sm min-w-[80px]">Category</th>
<th className="p-3 text-sm min-w-[150px]">Date</th>
<th className="p-3 text-sm min-w-[200px]">Notes</th>
</tr>
</thead>
<tbody>
{filteredTransactions.map((transaction) => (
<tr key={transaction.ID}>
<td className="p-3 text-sm">{transaction.transaction_code}</td>
<td className="p-3 text-sm">
{transaction.transaction_type?.name || 'N/A'}
</td>
<td className="p-3 text-sm">{transaction.type}</td>
<td className="p-3 text-sm">{transaction.amount.toFixed(2)}</td>
<td className="p-3 text-sm">{transaction.pre_amount.toFixed(2)}</td>
<td className="p-3 text-sm">{transaction.post_amount.toFixed(2)}</td>
<td className="p-3 text-sm">{transaction.category}</td>
<td className="p-3 text-sm">
{new Date(transaction.date).toLocaleString('id-ID', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</td>
<td className="p-3 text-sm">{transaction.notes || '-'}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
) : (
<div className="text-center text-gray-500 py-10">No transaction data available</div>
)}
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default ShowDialog;

View File

@ -1,12 +0,0 @@
import { useContext } from 'react';
import { ManageWalletContext } from './ManageWalletHistoryContext';
const useManageWalletContext = () => {
const context = useContext(ManageWalletContext);
if (!context) {
throw new Error('useManageWalletContext must be used within a ManageWalletContextProvider');
}
return context;
};
export { useManageWalletContext };

View File

@ -1,9 +1,9 @@
import { Container, DataGridInner } from '@/components';
import { ManageWalletContextProvider } from './hooks/ManageWalletHistoryContext';
import { Breadcrumbs, Link } from '@mui/material';
import { Helmet } from 'react-helmet';
import { ManageWalletContextProvider } from './hooks/ManageWalletStatementContext';
const WalletHistory = () => {
const WalletStatement = () => {
return (
<>
<Helmet>
@ -35,4 +35,4 @@ const WalletHistory = () => {
);
};
export default WalletHistory;
export default WalletStatement;

View File

@ -0,0 +1,503 @@
import { useEffect, useState } from 'react';
import {
Dialog,
DialogBody,
DialogContent,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { useManageStatementContext } from '../hooks/useManageWalletStatementContext';
import { DefaultTooltip, KeenIcon } from '@/components';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config';
const API_URL_WALLET = apiConfig.service_wallet;
const API_URL = apiConfig.service_transaction;
interface TransactionType {
id: string;
name: string;
}
interface WalletTransaction {
ID: string;
id_balance: string;
transaction_code: string;
transaction_type: {
id: string;
name: string;
};
type: string;
amount: number;
pre_amount: number;
post_amount: number;
category: string;
notes: string;
date: string;
msisdn_reff: string;
purpose: string;
}
const ShowDialog = () => {
const { showDetailDialog, setShowDetailDialog, selectedWallet } = useManageStatementContext();
const [isLoading, setIsLoading] = useState(false);
const { GetData } = useCallApi();
const [transactionType, setTransactionType] = useState<TransactionType[]>([]);
const [filteredTransactions, setFilteredTransactions] = useState<WalletTransaction[]>([]);
const [currentPage, setCurrentPage] = useState(1);
const [totalItems, setTotalItems] = useState(0);
const [totalPages, setTotalPages] = useState(1);
const itemsPerPage = 10;
const getDefaultDateRange = () => {
const today = new Date();
today.setHours(23, 59, 59, 999);
const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
sevenDaysAgo.setHours(0, 0, 0, 0);
return {
from: formatDate(sevenDaysAgo, true),
to: formatDate(today, true)
};
};
const formatDate = (date: Date, includeTime = false) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
if (includeTime) {
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
}
return `${year}-${month}-${day}`;
};
const [dateRange, setDateRange] = useState(getDefaultDateRange());
const [category, setCategory] = useState<TransactionKindValue | null>(null);
const [selectedCategory, setSelectedCategory] = useState<string>('');
const [selectedTransactionType, setSelectedTransactionType] = useState<string>('');
const [searchValue, setSearchValue] = useState('');
const TransactionKind = {
return: 'R',
transfer: 'T',
purchase: 'P',
purchase_loja: 'L',
withdraw: 'W',
topup: 'U',
topup_p24: 'B',
topup_partner: 'N',
reward: 'E',
transfer_agent: 'A',
withdraw_agent: 'M',
topup_agent: 'O',
transfer_p24: 'S',
withdraw_merchant: 'I',
donation: 'D',
fee: 'F',
raversal: 'V',
cashback_cash: 'C',
cashback_point: 'H',
withdraw_admin: 'J'
};
type TransactionKindValue = (typeof TransactionKind)[keyof typeof TransactionKind];
const fetchTransactionType = async () => {
try {
setIsLoading(true);
const response = await GetData(`${API_URL}/transactiontype/list`, {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'created_at',
order_direction: 'ASC'
});
setTransactionType(
(response?.data?.list || []).sort((a: any, b: any) => a.name.localeCompare(b.name))
);
} catch (error) {
console.error('Error fetching Transaction type', error);
toast.error('Failed to load transaction types');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchTransactionType();
}, []);
const fetchFilteredTransactions = async () => {
if (!selectedWallet?.ID) return;
setIsLoading(true);
try {
let fromDateTime = dateRange.from;
if (!fromDateTime.includes('T')) {
const fromDate = new Date(fromDateTime);
fromDateTime = formatDate(fromDate, true);
}
let toDateTime = dateRange.to;
if (!toDateTime.includes('T')) {
const toDate = new Date(toDateTime);
toDate.setHours(23, 59, 59, 999);
toDateTime = formatDate(toDate, true);
}
const response = await GetData(
`${API_URL_WALLET}/dashboard/balance/list-balance-detail/${selectedWallet.ID}`,
{
limit: itemsPerPage,
page: currentPage,
order_field: 'created_at',
order_direction: 'DESC',
start_date: fromDateTime,
end_date: toDateTime,
transaction_type: selectedTransactionType || undefined,
category: selectedCategory || undefined,
search: searchValue || undefined
}
);
console.log(response);
setFilteredTransactions(response?.data?.list || []);
setTotalItems(response?.data?.total || 0);
setTotalPages(Math.ceil((response?.data?.total || 0) / itemsPerPage));
} catch (error) {
console.error('Error fetching filtered transactions:', error);
toast.error('Failed to load filtered transactions');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
if (!showDetailDialog || !selectedWallet?.ID) return;
const timer = setTimeout(() => {
fetchFilteredTransactions();
}, 300);
return () => clearTimeout(timer);
}, [
showDetailDialog,
dateRange.from,
dateRange.to,
selectedTransactionType,
selectedCategory,
searchValue,
selectedWallet?.ID,
currentPage
]);
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setSearchValue(value);
};
const handleDateChange = (type: 'from' | 'to', value: string) => {
const date = new Date(value);
if (type === 'from') {
date.setHours(0, 0, 0, 0);
} else {
date.setHours(23, 59, 59, 999);
}
const formattedDate = formatDate(date, true);
console.log(`Setting ${type} date to:`, formattedDate);
setDateRange((prev) => ({ ...prev, [type]: formattedDate }));
};
const handleClearAllFilters = () => {
const defaultDates = getDefaultDateRange();
console.log('Resetting filters to default:', defaultDates);
setDateRange(defaultDates);
setSelectedTransactionType('');
setSearchValue('');
setSelectedCategory('');
setCurrentPage(1);
};
const handlePageChange = (page: number) => {
setCurrentPage(page);
};
useEffect(() => {
if (!showDetailDialog) return;
const checkNewDay = () => {
const now = new Date();
const currentDate = formatDate(now);
const fromDate = new Date(dateRange.from);
if (
currentDate !== formatDate(new Date(dateRange.to)) &&
now.getTime() - fromDate.getTime() > 7 * 24 * 60 * 60 * 1000
) {
setDateRange(getDefaultDateRange());
toast.info('Date range has been updated to the current period');
}
};
checkNewDay();
const interval = setInterval(checkNewDay, 60 * 60 * 1000);
return () => clearInterval(interval);
}, [showDetailDialog, dateRange]);
const getDisplayDate = (dateTimeString: string) => {
if (!dateTimeString) return '';
return dateTimeString.split('T')[0];
};
return (
<Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
<DialogContent className="max-w-[95vw] sm:max-w-[1200px] p-4 overflow-hidden">
<DialogHeader>
<DialogTitle>Details Wallet Statement</DialogTitle>
</DialogHeader>
<DialogBody>
<div className="py-4 max-h-[90vh] overflow-y-auto overflow-x auto flex flex-wrap gap-2 lg:gap-5 w-full">
<div className="flex flex-wrap gap-3 w-full">
<label className="input input-sm w-full sm:w-[160px]">
From
<input
type="date"
placeholder="From"
value={getDisplayDate(dateRange.from)}
onChange={(e) => handleDateChange('from', e.target.value)}
/>
</label>
<label className="input input-sm w-full sm:w-[160px]">
To
<input
type="date"
placeholder="To"
value={getDisplayDate(dateRange.to)}
onChange={(e) => handleDateChange('to', e.target.value)}
/>
</label>
<div className="w-full sm:w-[200px]">
<Select
value={selectedTransactionType}
onValueChange={(value) => setSelectedTransactionType(value)}
>
<SelectTrigger className="h-[32px]">
<SelectValue placeholder="Transaction Type" />
</SelectTrigger>
<SelectContent>
{transactionType.map((transaction) => (
<SelectItem key={transaction.id} value={transaction.id}>
{transaction.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="w-full sm:w-[160px]">
<Select
value={selectedCategory}
onValueChange={(value) => setSelectedCategory(value)}
>
<SelectTrigger className="h-[32px]">
<SelectValue placeholder="Status Kind" />
</SelectTrigger>
<SelectContent>
{Object.entries(TransactionKind).map(([label, value]) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<label className="input input-sm w-full sm:w-[160px]">
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder="Transaction Code"
className="overflow-hidden text-ellipsis w-full"
value={searchValue}
onChange={handleSearchChange}
/>
</label>
<DefaultTooltip title={'Reset Filter'} placement={'top'}>
<Button
variant="outline"
className="h-8 disabled:bg-gray-400"
onClick={handleClearAllFilters}
>
<KeenIcon icon="arrow-circle-left" />
</Button>
</DefaultTooltip>
</div>
{isLoading ? (
<div className="w-full text-center text-gray-500">Loading details...</div>
) : filteredTransactions.length > 0 ? (
<div className="w-[80%] border overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full border-collapse table-auto">
<thead>
<tr className="bg-gray-100 text-left">
<th className="p-3 text-sm min-w-[120px] border border-gray-300">
Transaction Code
</th>
<th className="p-3 text-sm min-w-[120px] border border-gray-300">
MSISDN Reffer
</th>
<th className="p-3 text-sm min-w-[180px] border border-gray-300">
Transaction Type
</th>
<th className="p-3 text-sm min-w-[80px] border border-gray-300">Type</th>
<th className="p-3 text-sm min-w-[100px] border border-gray-300">Amount</th>
<th className="p-3 text-sm min-w-[100px] border border-gray-300">
Pre Amount
</th>
<th className="p-3 text-sm min-w-[100px] border border-gray-300">
Post Amount
</th>
<th className="p-3 text-sm min-w-[80px] border border-gray-300">
Status Kind
</th>
<th className="p-3 text-sm min-w-[150px] border border-gray-300">
Date Time
</th>
<th className="p-3 text-sm min-w-[180px] border border-gray-300">Notes</th>
<th className="p-3 text-sm min-w-[180px] border border-gray-300">
Purpose
</th>
</tr>
</thead>
<tbody>
{filteredTransactions.map((transaction) => (
<tr key={transaction.ID} className="hover:bg-gray-50">
<td className="p-3 text-sm border border-gray-300">
{transaction.transaction_code}
</td>
<td className="p-3 text-sm border border-gray-300">
{transaction.msisdn_reff}
</td>
<td className="p-3 text-sm border border-gray-300">
{transaction.transaction_type?.name || 'N/A'}
</td>
<td className="p-3 text-sm border border-gray-300">{transaction.type}</td>
<td className="p-3 text-sm border border-gray-300">
{transaction.amount.toFixed(2)}
</td>
<td className="p-3 text-sm border border-gray-300">
{transaction.pre_amount.toFixed(2)}
</td>
<td className="p-3 text-sm border border-gray-300">
{transaction.post_amount.toFixed(2)}
</td>
<td className="p-3 text-sm border border-gray-300">
{transaction.category}
</td>
<td className="p-3 text-sm border border-gray-300">
{new Date(transaction.date).toLocaleString('id-ID', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</td>
<td className="p-3 text-sm border border-gray-300">
{transaction.notes || '-'}
</td>
<td className="p-3 text-sm border border-gray-300">
{transaction.purpose || '-'}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
) : (
<div className="text-center text-gray-500 py-10">No transaction data available</div>
)}
<div className="flex justify-between items-center mt-4 flex-wrap gap-2">
<div className="text-sm text-gray-600">
Showing {(currentPage - 1) * itemsPerPage + 1} to{' '}
{Math.min(currentPage * itemsPerPage, totalItems)} of {totalItems} entries
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
disabled={currentPage === 1}
>
Prev
</Button>
<div className="flex items-center gap-1">
{Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
let pageToShow;
if (totalPages <= 5) {
pageToShow = i + 1;
} else if (currentPage <= 3) {
pageToShow = i + 1;
} else if (currentPage >= totalPages - 2) {
pageToShow = totalPages - 4 + i;
} else {
pageToShow = currentPage - 2 + i;
}
return (
<Button
key={pageToShow}
variant={currentPage === pageToShow ? 'default' : 'outline'}
size="sm"
onClick={() => handlePageChange(pageToShow)}
className="w-8 h-8 p-0"
>
{pageToShow}
</Button>
);
})}
</div>
<Button
variant="outline"
size="sm"
onClick={() => handlePageChange(Math.min(totalPages, currentPage + 1))}
disabled={currentPage === totalPages}
>
Next
</Button>
</div>
</div>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default ShowDialog;

View File

@ -250,14 +250,7 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
if (Array.isArray(filter)) {
filter.forEach((f: any) => {
if (f.id === 'msisdn' && f.value) {
filterParams.msisdn = { like: `%${f.value.toLowerCase()}%` };
}
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`
};
filterParams.msisdn = f.value;
}
if (f.id === 'id_wallet' && f.value) {

View File

@ -0,0 +1,13 @@
import { useContext } from 'react';
import { ManageWalletContext } from './ManageWalletStatementContext';
const useManageStatementContext = () => {
const context = useContext(ManageWalletContext);
if (!context) {
throw new Error('useManageStatementContext must be used within a ManageStatementContextProvider');
}
return context;
};
export { useManageStatementContext };

View File

@ -41,7 +41,7 @@ import ProviderMaster from '@/pages/master/provider/ProviderMaster';
import ConversionMaster from '@/pages/master/conversion/ConversionMaster';
import RewardMaster from '@/pages/master/reward/RewardMaster';
import WalletRuleMaster from '@/pages/master/walletRule/WalletRuleMaster';
import WalletHistory from '@/pages/wallet/wallet-history/WalletHistory';
import WalletStatement from '@/pages/wallet/wallet-statement/WalletStatement';
import WalletMaster from '@/pages/master/wallet/WalletMaster';
import CurrencyMaster from '@/pages/master/currency/CurrencyMaster';
import FeedbackMemberMaster from '@/pages/members/feedback-member/FeedbackMember';
@ -101,7 +101,7 @@ const AppRoutingSetup = (): ReactElement => {
<Route path="/transfer-type/transfer-type-management" element={<TransferType />} />
<Route path="/wallet/wallet-history" element={<WalletHistory />} />
<Route path="/wallet/wallet-statement" element={<WalletStatement />} />
<Route path="/notification/notification-management" element={<ManageNotification />} />