This commit is contained in:
unknown
2025-04-14 16:47:32 +07:00
14 changed files with 441 additions and 125 deletions

View File

@ -1,7 +1,10 @@
// disbursement/history-transaction/blocks/DetailTransaction.tsx
import { KeenIcon } from '@/components';
import { useTransactionContext } from '../hooks/useTransactionContext'; import { useTransactionContext } from '../hooks/useTransactionContext';
import { useCallApi } from '@/hooks'; import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config'; import { apiConfig } from '@/config/api.config';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import moment from 'moment';
import { import {
Dialog, Dialog,
DialogBody, DialogBody,
@ -10,10 +13,11 @@ import {
DialogHeader, DialogHeader,
DialogTitle DialogTitle
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import TransactionLogViewer from './DetailTransactionLog';
const API_URL = apiConfig.service_disbursement; const API_URL = apiConfig.service_disbursement;
type StatusCode = 'W' | 'P' | 'F' | 'D' | 'Y'; type StatusCode = 'W' | 'O' | 'F' | 'D';
interface StatusInfo { interface StatusInfo {
label: string; label: string;
@ -22,11 +26,10 @@ interface StatusInfo {
} }
const statusMap: Record<StatusCode, StatusInfo> = { const statusMap: Record<StatusCode, StatusInfo> = {
W: { label: 'Waiting', bg: 'bg-yellow-100', text: 'text-yellow-600' }, W: { label: 'Waiting Schedule', bg: 'bg-yellow-100', text: 'text-yellow-600' },
P: { label: 'Pending', bg: 'bg-blue-100', text: 'text-blue-600' }, O: { label: 'On Process', bg: 'bg-blue-100', text: 'text-blue-600' },
F: { label: 'Fail', bg: 'bg-red-100', text: 'text-red-600' }, F: { label: 'Fail', bg: 'bg-red-100', text: 'text-red-600' },
D: { label: 'Done', bg: 'bg-green-100', text: 'text-green-600' }, D: { label: 'Done', bg: 'bg-green-100', text: 'text-green-600' },
Y: { label: 'Active', bg: 'bg-green-100', text: 'text-green-600' },
}; };
export const renderStatusBadge = (statusRaw: string | null | undefined) => { export const renderStatusBadge = (statusRaw: string | null | undefined) => {
@ -49,7 +52,9 @@ const DetailTransaction = () => {
const { const {
showDetailDialog, showDetailDialog,
setShowDetailDialog, setShowDetailDialog,
selectedTransactionId selectedTransactionId,
setShowDetailLogDialog,
setDetailLogData
} = useTransactionContext(); } = useTransactionContext();
const [transactionDetails, setTransactionDetails] = useState<any>(null); const [transactionDetails, setTransactionDetails] = useState<any>(null);
@ -92,27 +97,39 @@ const DetailTransaction = () => {
<thead> <thead>
<tr className="bg-gray-100"> <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">Username</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Name</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">Transfer Amount</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">Description</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">Process Date</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Response</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">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">Actions</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{transactionDetails?.log && transactionDetails?.log.length > 0 ? ( {transactionDetails?.log && transactionDetails?.log.length > 0 ? (
transactionDetails.log.map((log: { customer: any, amount: number, remark: string, reference: string, response_date: string, payment_response: string, status: string}, index: number) => ( transactionDetails.log.map((log: { id: number, customer: any, amount: number, remark: string, reference: string, request_date: string, payment_response: string, status: string}, index: number) => (
<tr key={index} className="border-t"> <tr key={index} className="border-t">
<td className="px-4 py-2 text-sm text-gray-500">{log.customer.username ?? '-'}</td> <td className="px-4 py-2 text-sm text-gray-500">{log.customer.username ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">{log.customer.fullname ?? '-'}</td> <td className="px-4 py-2 text-sm text-gray-500">{log.customer.fullname ?? '-'}</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">{log.amount ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">{log.remark ?? '-'}</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.response_date ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">{log.payment_response ?? '-'}</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">{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('YYYY-MM-DD HH:mm:ss') : '-'}</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">
<div key={`actions-${log.id}`}>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => {
setDetailLogData(log)
setShowDetailLogDialog(true);
}}
>
<KeenIcon icon="eye" />
</button>
</div>
</td>
</tr> </tr>
)) ))
) : ( ) : (

View File

@ -0,0 +1,131 @@
import React, { useState } from 'react';
import moment from 'moment';
import { useTransactionContext } from '../hooks/useTransactionContext';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogBody } from '@/components/ui/dialog';
interface LogType {
id: string;
amount: number;
remark: string;
reference: string;
response_date: string;
status: string;
customer?: {
username: string;
fullname: string;
};
payment_response?: string;
}
type StatusCode = 'W' | 'O' | 'F' | 'D';
interface StatusInfo {
label: string;
bg: string;
text: string;
}
const statusMap: Record<StatusCode, StatusInfo> = {
W: { label: 'Waiting Schedule', bg: 'bg-yellow-100', text: 'text-yellow-600' },
O: { label: 'On Process', bg: 'bg-blue-100', text: 'text-blue-600' },
F: { label: 'Fail', bg: 'bg-red-100', text: 'text-red-600' },
D: { label: 'Done', bg: 'bg-green-100', text: 'text-green-600' },
};
export const renderStatusBadge = (statusRaw: string | null | undefined) => {
const status = statusRaw as StatusCode;
const { label, bg, text } = statusMap[status] ?? {
label: 'Unknown',
bg: 'bg-gray-100',
text: 'text-gray-600',
};
return (
<span className={`px-2 py-1 text-xs font-semibold rounded-full ${bg} ${text}`}>
{label}
</span>
);
};
const TransactionLogViewer = () => {
const {
showDetailLogDialog,
setShowDetailLogDialog,
detailLogData
} = useTransactionContext();
console.log('detailLogData: ', detailLogData)
return (
<Dialog open={showDetailLogDialog} onOpenChange={setShowDetailLogDialog}>
<DialogContent className="container-fixed max-w-[1280px] w-full h-[90vh] flex flex-col p-6 overflow-hidden">
<DialogHeader>
<DialogTitle>Detail Record</DialogTitle>
</DialogHeader>
<DialogBody >
{/* Tab Content */}
{detailLogData && detailLogData != null ? (
<div className="py-4 overflow-y-auto">
<div className="space-y-4">
<div className="border rounded-lg overflow-x-auto">
<table className='min-w-full table-auto'>
<tbody>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">ID</td>
<td className="px-4 py-2 text-sm text-gray-500">{detailLogData.customer.id}</td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Username</td>
<td className="px-4 py-2 text-sm text-gray-500">{detailLogData.customer.username}</td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Name</td>
<td className="px-4 py-2 text-sm text-gray-500">{detailLogData.customer.fullname}</td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Amount</td>
<td className="px-4 py-2 text-sm text-gray-500">{detailLogData.amount}</td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Remark</td>
<td className="px-4 py-2 text-sm text-gray-500">{detailLogData.remark}</td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Payment Request</td>
<td className="px-4 py-2 text-sm text-gray-500"><pre className="whitespace-pre-wrap break-words max-w-full overflow-auto bg-gray-100 p-2 rounded text-sm">{detailLogData.payment_request}</pre></td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Payment Response</td>
<td className="px-4 py-2 text-sm text-gray-500"><pre className="whitespace-pre-wrap break-words max-w-full overflow-auto bg-gray-100 p-2 rounded text-sm">{detailLogData.payment_response}</pre></td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Status</td>
<td className="px-4 py-2 text-sm text-gray-500">{renderStatusBadge(detailLogData.status)}</td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Prosess Date</td>
<td className="px-4 py-2 text-sm text-gray-500">{detailLogData.request_date && moment(detailLogData.request_date).isValid() ? moment(detailLogData.request_date).format('YYYY-MM-DD HH:mm:ss') : '-'}</td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Response Date</td>
<td className="px-4 py-2 text-sm text-gray-500">{detailLogData.response_date && moment(detailLogData.response_date).isValid() ? moment(detailLogData.response_date).format('YYYY-MM-DD HH:mm:ss') : '-'}</td>
</tr>
<tr className='border-t'>
<td className="px-4 py-2 text-sm text-gray-500">Reference Number</td>
<td className="px-4 py-2 text-sm text-gray-500">{detailLogData.reference}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
) : (<div></div>)}
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default TransactionLogViewer;

View File

@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button';
import { useNavigate } from 'react-router'; import { useNavigate } from 'react-router';
import moment from 'moment'; import moment from 'moment';
import DetailTransaction from '../blocks/DetailTransaction'; import DetailTransaction from '../blocks/DetailTransaction';
import TransactionLogViewer from '../blocks/DetailTransactionLog';
interface TransactionProps { interface TransactionProps {
id: number; id: number;
@ -31,6 +32,11 @@ interface ContextProps {
setSelectedTransactionId: React.Dispatch<React.SetStateAction<number | null>>; setSelectedTransactionId: React.Dispatch<React.SetStateAction<number | null>>;
showUploadBatchDialog: boolean; showUploadBatchDialog: boolean;
handleUploadBatchDialog: (show: boolean) => void; handleUploadBatchDialog: (show: boolean) => void;
showDetailLogDialog: boolean;
// handleDetailLogDialog: (show: boolean) => void;
setShowDetailLogDialog: React.Dispatch<React.SetStateAction<boolean>>;
setDetailLogData: React.Dispatch<React.SetStateAction<any | null>>;
detailLogData: any | null
} }
const initialProps: ContextProps = { const initialProps: ContextProps = {
@ -41,6 +47,11 @@ const initialProps: ContextProps = {
setSelectedTransactionId: () => { }, setSelectedTransactionId: () => { },
showUploadBatchDialog: false, showUploadBatchDialog: false,
handleUploadBatchDialog: (show: boolean) => {}, handleUploadBatchDialog: (show: boolean) => {},
showDetailLogDialog: false,
// handleDetailLogDialog: (show: boolean) => {},
setShowDetailLogDialog: () => { },
setDetailLogData: () => {},
detailLogData: null,
}; };
type StatusCode = 'W' | 'P' | 'F' | 'D' | 'Y'; type StatusCode = 'W' | 'P' | 'F' | 'D' | 'Y';
@ -67,6 +78,8 @@ const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
const [showDetailDialog, setShowDetailDialog] = useState(false); const [showDetailDialog, setShowDetailDialog] = useState(false);
const [selectedTransactionId, setSelectedTransactionId] = useState<number | null>(null); const [selectedTransactionId, setSelectedTransactionId] = useState<number | null>(null);
const [showUploadBatchDialog, setShowUploadBatchDialog] = useState(false); const [showUploadBatchDialog, setShowUploadBatchDialog] = useState(false);
const [showDetailLogDialog, setShowDetailLogDialog] = useState(false);
const [detailLogData, setDetailLogData] = useState<any | null>(null);
const [transaction, setTransaction] = useState<TransactionProps[]>([]); const [transaction, setTransaction] = useState<TransactionProps[]>([]);
const { GetData } = useCallApi(); const { GetData } = useCallApi();
const navigate = useNavigate(); const navigate = useNavigate();
@ -74,6 +87,9 @@ const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
const handleUploadBatchDialog = useCallback((show: boolean) => { const handleUploadBatchDialog = useCallback((show: boolean) => {
setShowUploadBatchDialog(show); setShowUploadBatchDialog(show);
}, []); }, []);
// const handleDetailLogDialog = useCallback((show: boolean) => {
// setShowDetailLogDialog(show);
// }, []);
const columns = useMemo<ColumnDef<any>[]>( const columns = useMemo<ColumnDef<any>[]>(
() => [ () => [
@ -262,11 +278,17 @@ const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
selectedTransactionId, selectedTransactionId,
setSelectedTransactionId, setSelectedTransactionId,
handleUploadBatchDialog, handleUploadBatchDialog,
showUploadBatchDialog showUploadBatchDialog,
// handleDetailLogDialog,
showDetailLogDialog,
setShowDetailLogDialog,
setDetailLogData,
detailLogData
}} }}
> >
<Toaster expand visibleToasts={9} duration={3000} /> <Toaster expand visibleToasts={9} duration={3000} />
<DetailTransaction /> <DetailTransaction />
<TransactionLogViewer />
<DataGridProvider <DataGridProvider
columns={columns} columns={columns}

View File

@ -0,0 +1,42 @@
import { createContext, useContext, useState } from "react";
interface LogDetail {
id: number;
username: string;
name: string;
amount: number;
remark: string;
inquiry_response: string;
payment_response: string;
response_message: string;
status: string;
process_date: string;
reference_number: string;
additional_info: string;
}
interface TransactionDialogContextProps {
showLogDialog: boolean;
selectedLog: LogDetail | null;
setShowLogDialog: (val: boolean) => void;
setSelectedLog: (log: LogDetail | null) => void;
}
const TransactionDialogContext = createContext<TransactionDialogContextProps | undefined>(undefined);
export const TransactionDialogProvider = ({ children }: { children: React.ReactNode }) => {
const [showLogDialog, setShowLogDialog] = useState(false);
const [selectedLog, setSelectedLog] = useState<LogDetail | null>(null);
return (
<TransactionDialogContext.Provider value={{ showLogDialog, setShowLogDialog, selectedLog, setSelectedLog }}>
{children}
</TransactionDialogContext.Provider>
);
};
export const useTransactionDialog = () => {
const context = useContext(TransactionDialogContext);
if (!context) throw new Error("useTransactionDialog must be used within TransactionDialogProvider");
return context;
};

View File

@ -16,8 +16,10 @@ const ListToolbar = () => {
<input <input
type="text" type="text"
placeholder="Search Wallet" placeholder="Search Wallet"
value={(table.getColumn('name')?.getFilterValue() as string) ?? ''} value={(table.getColumn('wallets.name')?.getFilterValue() as string) ?? ''}
onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)} onChange={(event) =>
table.getColumn('wallets.name')?.setFilterValue(event.target.value)
}
/> />
</label> </label>
{/* <DefaultTooltip title={'Filter'} placement={'top'}> {/* <DefaultTooltip title={'Filter'} placement={'top'}>

View File

@ -74,7 +74,7 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
() => [ () => [
{ {
accessorFn: (row) => row.name, accessorFn: (row) => row.name,
id: 'name', id: 'wallets.name',
header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
enableSorting: true, enableSorting: true,
enableHiding: false, enableHiding: false,
@ -86,7 +86,7 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
accessorFn: (row) => row.description, accessorFn: (row) => row.description,
id: 'description', id: 'description',
header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />,
enableSorting: true, enableSorting: false,
enableHiding: false, enableHiding: false,
meta: { meta: {
headerClassName: 'w-[250px]' headerClassName: 'w-[250px]'
@ -94,7 +94,7 @@ const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }
}, },
{ {
accessorFn: (row) => row.status, accessorFn: (row) => row.status,
id: 'status', id: 'wallets.status',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
enableSorting: true, enableSorting: true,
enableHiding: false, enableHiding: false,

View File

@ -1,10 +1,22 @@
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components'; import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { useManageMenusContext } from '../hooks/useManageMenusContext'; import { useManageMenusContext } from '../hooks/useManageMenusContext';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import React, { useState } from 'react';
const ListToolbar = () => { const ListToolbar = () => {
const { table, reload } = useDataGrid(); const { table, reload } = useDataGrid();
const { handleAddDialog } = useManageMenusContext(); const { handleAddDialog } = useManageMenusContext();
const [searchValue, setSearchValue] = useState('');
const handleKeyDown = (event: React.KeyboardEvent) => {
if (event.key === 'Enter') {
handleSearch();
}
};
const handleSearch = () => {
table.getColumn('name')?.setFilterValue(searchValue);
};
return ( return (
<div className="card-header flex-wrap gap-2 border-b-0 px-5"> <div className="card-header flex-wrap gap-2 border-b-0 px-5">
@ -16,10 +28,16 @@ const ListToolbar = () => {
<input <input
type="text" type="text"
placeholder="Search Menu" placeholder="Search Menu"
value={(table.getColumn('name')?.getFilterValue() as string) ?? ''} value={searchValue}
onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)} onChange={(event) => setSearchValue(event.target.value)}
onKeyDown={handleKeyDown}
/> />
</label> </label>
<DefaultTooltip title={'Search'} placement={'top'}>
<Button variant="outline" className="h-7.5" onClick={handleSearch}>
<KeenIcon icon="magnifier" />
</Button>
</DefaultTooltip>
{/* <DefaultTooltip title={'Filter'} placement={'top'}> {/* <DefaultTooltip title={'Filter'} placement={'top'}>
<Button <Button
variant="outline" variant="outline"

View File

@ -109,7 +109,7 @@ const ManageMenusContextProvider = ({ children }: { children: React.ReactNode })
meta: { headerClassName: 'w-[200px]' } meta: { headerClassName: 'w-[200px]' }
}, },
{ {
accessorFn: (row) => row.parentName, accessorFn: (row) => row.parentName || row.module,
id: 'menu', id: 'menu',
header: ({ column }) => <DataGridColumnHeader title="Menu" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Menu" column={column} />,
enableSorting: false, enableSorting: false,
@ -191,11 +191,10 @@ const ManageMenusContextProvider = ({ children }: { children: React.ReactNode })
const flattenChildren = (parent: any, parentIdx: number, depth = 0, parentName = '') => { const flattenChildren = (parent: any, parentIdx: number, depth = 0, parentName = '') => {
let result: any[] = []; let result: any[] = [];
if (parent.link === '/') { if (parent.id_parent === null) {
if (!parents.find((el: any) => el.id === parent.id)) if (!parents.find((el: any) => el.id === parent.id))
setParents((el: any) => [...el, { id: parent.id, name: parent.name }]); // GET PARENTS setParents((el: any) => [...el, { id: parent.id, name: parent.name }]);
// Menambahkan parent ke dalam result meskipun tidak memiliki children
result.push({ result.push({
id: parent.id, id: parent.id,
module: parent.module, module: parent.module,
@ -208,7 +207,6 @@ const ManageMenusContextProvider = ({ children }: { children: React.ReactNode })
}); });
} }
// Jika parent tidak memiliki children, langsung return hasil yang sudah ada
if (!parent.children || parent.children.length === 0) { if (!parent.children || parent.children.length === 0) {
return result; return result;
} }
@ -230,36 +228,44 @@ const ManageMenusContextProvider = ({ children }: { children: React.ReactNode })
}; };
}); });
// Gabungkan parent dengan children yang sudah diflatten
return [...result, ...childrenFlattened]; return [...result, ...childrenFlattened];
}; };
const getMenusLists = async (page: number, limit: number, sorting: any, filter: any) => { const getMenusLists = async (page: number, limit: number, sorting: any, filter: any) => {
try { try {
sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting; sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
filter = filter.length === 0 ? {} : { any: filter[0].value?.toLowerCase() }; filter = filter.length === 0 ? {} : { name: { like: `%${filter[0].value?.toLowerCase()}%` } };
const response = await GetData(`${API_URL}/menus/list`, { const query: any = {
limit, limit,
page: page + 1, page: 1,
with_deleted: false, with_deleted: false,
order_field: sorting[0].id, order_field: sorting[0].id,
order_direction: sorting[0].desc ? 'DESC' : 'ASC', order_direction: sorting[0].desc ? 'DESC' : 'ASC'
filter: JSON.stringify(filter) };
});
if (!response?.data.list) return { data: [], totalCount: 0 }; if (filter && Object.keys(filter).length > 0) {
query.filter = JSON.stringify(filter);
query.page = page + 1;
}
const transformedData = response.data.list.flatMap((row: any, parentIdx: number) => const response = await GetData(`${API_URL}/menus/list`, query);
flattenChildren(row, parentIdx)
);
const total_count = transformedData.length; if (query.filter && query.filter.length > 0) {
const paginatedData = transformedData.slice(page * limit, (page + 1) * limit); return { data: response?.data.list, totalCount: response?.data.total_count };
} else {
const transformedData = response?.data.list.flatMap((row: any, parentIdx: number) =>
flattenChildren(row, parentIdx)
);
console.log('data', paginatedData); const total_count = transformedData.length;
// setMenus(transformedData);
return { data: paginatedData, totalCount: total_count }; // **Pagination di frontend saja (tanpa hit API ulang)**
const paginatedData = transformedData.slice(page * limit, (page + 1) * limit);
const totalPages = Math.ceil(total_count / limit);
return { data: paginatedData, totalCount: total_count };
}
} catch (error) { } catch (error) {
console.error('Error fetching Menus', error); console.error('Error fetching Menus', error);
return { data: [], totalCount: 0 }; return { data: [], totalCount: 0 };
@ -289,7 +295,7 @@ const ManageMenusContextProvider = ({ children }: { children: React.ReactNode })
pagination={{ size: 25 }} pagination={{ size: 25 }}
toolbar={<ListToolbar />} toolbar={<ListToolbar />}
layout={{ card: true }} layout={{ card: true }}
sorting={[{ id: 'id', desc: false }]} sorting={[{ id: 'created_at', desc: true }]}
serverSide={true} serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) => onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
getMenusLists(pageIndex, pageSize, sorting, columnFilters) getMenusLists(pageIndex, pageSize, sorting, columnFilters)

View File

@ -153,9 +153,9 @@ const EditDialog = () => {
email: response.data.email, email: response.data.email,
id_role: response.data.idRole, id_role: response.data.idRole,
status: response.data.status, status: response.data.status,
customerid: response.data.customerid customerid: response.data.customer.id
})); }));
// console.log('Customer ID dari user detail:', response.data.customerid); // console.log('Customer ID from API:', response?.data.customerid);
} else { } else {
setFormField((prev) => ({ setFormField((prev) => ({
...prev, ...prev,
@ -170,16 +170,6 @@ const EditDialog = () => {
// console.log('Fetched ID Role:', response?.data.id_role); // console.log('Fetched ID Role:', response?.data.id_role);
}, []); }, []);
useEffect(() => {
if (selectedUser) {
doFetchUserData(selectedUser);
}
}, [selectedUser]);
useEffect(() => {
getCustomerList([{ id: 'id', desc: false }]);
}, []);
useEffect(() => { useEffect(() => {
if (showEditDialog === false) { if (showEditDialog === false) {
resetForm(); resetForm();
@ -188,6 +178,7 @@ const EditDialog = () => {
useEffect(() => { useEffect(() => {
const fetchAllData = async () => { const fetchAllData = async () => {
await getCustomerList([{ id: 'id', desc: false }]);
await doFetchUserRole([{ id: 'name', desc: false }]); await doFetchUserRole([{ id: 'name', desc: false }]);
if (selectedUser) { if (selectedUser) {
await doFetchUserData(selectedUser); await doFetchUserData(selectedUser);

View File

@ -15,7 +15,7 @@ const ListToolBar = () => {
<KeenIcon icon="magnifier" /> <KeenIcon icon="magnifier" />
<input <input
type="text" type="text"
placeholder="Search users" placeholder="Search Users"
value={(table.getColumn('username')?.getFilterValue() as string) ?? ''} value={(table.getColumn('username')?.getFilterValue() as string) ?? ''}
onChange={(event) => onChange={(event) =>
table.getColumn('username')?.setFilterValue(event.target.value) table.getColumn('username')?.setFilterValue(event.target.value)

View File

@ -78,7 +78,7 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
const columns = useMemo<ColumnDef<any>[]>( const columns = useMemo<ColumnDef<any>[]>(
() => [ () => [
{ {
accessorFn: (row) => row.username, accessorKey: 'username',
id: 'username', id: 'username',
header: ({ column }) => <DataGridColumnHeader title="Username" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Username" column={column} />,
enableSorting: true, enableSorting: true,
@ -88,27 +88,27 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
accessorFn: (row) => row.customer?.username, accessorFn: (row) => row.customer?.username,
id: 'customer', id: 'customer',
header: ({ column }) => <DataGridColumnHeader title="Customer" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Customer" column={column} />,
enableSorting: false, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { meta: {
headerClassName: 'w-[300px]' headerClassName: 'w-[300px]'
} }
}, },
{ {
accessorFn: (row) => row.email, accessorKey: 'email',
id: 'email', id: 'email',
header: ({ column }) => <DataGridColumnHeader title="Email" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Email" column={column} />,
enableSorting: false, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { meta: {
headerClassName: 'w-[350px]' headerClassName: 'w-[350px]'
} }
}, },
{ {
accessorFn: (row) => row.name, accessorKey: 'name',
id: 'name', id: 'name',
header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
enableSorting: false, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { meta: {
headerClassName: 'w-[250px]' headerClassName: 'w-[250px]'
@ -118,7 +118,7 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
accessorFn: (row) => row.role.name, accessorFn: (row) => row.role.name,
id: 'role_name', id: 'role_name',
header: ({ column }) => <DataGridColumnHeader title="Role Name" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Role Name" column={column} />,
enableSorting: false, enableSorting: true,
enableHiding: false, enableHiding: false,
cell: (data: any) => { cell: (data: any) => {
const { role } = data.row.original; const { role } = data.row.original;
@ -132,7 +132,7 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
} }
}, },
{ {
accessorFn: (row) => row.status, accessorKey: 'status',
id: 'status', id: 'status',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
enableSorting: false, enableSorting: false,
@ -190,18 +190,31 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
); );
const doGetListData = async (page: number, limit: number, sorting: any, filter: any) => { const doGetListData = async (page: number, limit: number, sorting: any, filter: any) => {
const mappedFilter = filter.reduce((acc: any, curr: any) => {
let key = curr.id;
// mapping kolom ke nama kolom lengkap (agar tidak ambigu di backend)
if (key === 'username') key = 'Users.username';
if (key === 'customer') key = 'Customers.username';
if (key === 'role_name') key = 'Roles.name';
if (key === 'email') key = 'Users.email';
if (key === 'name') key = 'Users.name';
acc[key] = curr.value.toLowerCase();
return acc;
}, {});
sorting = sorting.length == 0 ? [{ id: 'Users.username', desc: false }] : sorting; sorting = sorting.length == 0 ? [{ id: 'Users.username', desc: false }] : sorting;
filter = filter.length == 0 ? {} : { any: filter[0].value.toLowerCase() }; filter = Object.keys(mappedFilter).length === 0 ? {} : mappedFilter;
const response = await GetData(`${API_URL}/user/list`, { const response = await GetData(`${API_URL}/user/list`, {
limit: limit, limit: limit,
page: page + 1, page: page + 1,
with_deleted: false, with_deleted: false,
order_field: sorting[0].id, order_field: sorting[0].id,
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC', order_direction: sorting[0].desc === false ? 'DESC' : 'ASC',
filter: JSON.stringify(filter) filter: JSON.stringify(filter)
}); });
// console.log('response api:', response); // console.log('response api:', response);
return { data: response?.data.list, totalCount: response?.data.total_count }; return { data: response?.data.list, totalCount: response?.data.total_count };
}; };
@ -228,9 +241,10 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
layout={{ card: true }} layout={{ card: true }}
sorting={[{ id: 'Users.username', desc: false }]} sorting={[{ id: 'Users.username', desc: false }]}
serverSide={true} serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) => onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) => {
doGetListData(pageIndex, pageSize, sorting, columnFilters) // console.log('FILTER SENT:', columnFilters);
} return doGetListData(pageIndex, pageSize, sorting, columnFilters);
}}
> >
{children} {children}
</DataGridProvider> </DataGridProvider>

View File

@ -7,7 +7,8 @@ import {
SelectTrigger, SelectTrigger,
SelectValue SelectValue
} from '@/components/ui/select'; } from '@/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { import {
Dialog, Dialog,
DialogBody, DialogBody,
@ -59,6 +60,7 @@ const EditFeeDialog = () => {
const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]); const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]);
const parsedUser = getAuth()?.user; const parsedUser = getAuth()?.user;
const [customers, setCustomers] = useState<CustomerProps[]>([]); const [customers, setCustomers] = useState<CustomerProps[]>([]);
const [open, setOpen] = useState(false);
const [alert, setAlert] = useState({ const [alert, setAlert] = useState({
show: false, show: false,
message: '' message: ''
@ -94,24 +96,22 @@ const EditFeeDialog = () => {
const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' '); const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' ');
if (showEditFeeDialog) { if (showEditFeeDialog) {
setFormField({ setFormField(prevState => ({
...formField, ...prevState,
updated_by: parsedUser?.username, updated_by: parsedUser?.username,
updated_at: formattedTime updated_at: formattedTime
}); }));
} }
}, [showEditFeeDialog]); }, [showEditFeeDialog]);
const resetForm = () => { const resetForm = () => {
if (selectedTransferFee) { if (selectedTransferFee) {
// Re-fetch the current data to reset the form to original values
fetchTransactionFee(selectedTransferFee); fetchTransactionFee(selectedTransferFee);
} else { } else {
setFormField(initialState); setFormField(initialState);
} }
}; };
/* actions */
const doUpdateTransferFee = useCallback( const doUpdateTransferFee = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => { async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
@ -257,15 +257,10 @@ const EditFeeDialog = () => {
const fetchTransactionFee = useCallback(async (id: string) => { const fetchTransactionFee = useCallback(async (id: string) => {
try { try {
const response = await GetData(`${API_URL}/transactionfees/getdata/${id}`, { id }); const response = await GetData(`${API_URL}/transactionfees/getdata/${id}`, { });
if (response?.status) { if (response?.status) {
let creditTo = '';
if (response.data.credit_destination?.id === '00000000-0000-0000-0000-000000000000') {
creditTo = 'D';
} else {
creditTo = 'I';
}
setFormField({ setFormField({
...initialState, ...initialState,
@ -282,23 +277,21 @@ const EditFeeDialog = () => {
priority: response.data.priority || '', priority: response.data.priority || '',
status: response.data.status || '', status: response.data.status || '',
status_include: response.data.status_include || '', status_include: response.data.status_include || '',
deduct_from: 'S', deduct_from: response.data.deduct_from||'',
deduct_from_account: response.data.deduct_from_account?.id || '', deduct_from_account: response.data.deduct_from_account?.id || '',
credit_to: creditTo, credit_to: response.data.credit_to || '',
credit_destination: response.data.credit_destination?.id || '00000000-0000-0000-0000-000000000000', credit_destination: response.data.credit_destination?.id || '00000000-0000-0000-0000-000000000000',
credit_destination_account: response.data.credit_destination_account?.id || '', credit_destination_account: response.data.credit_destination_account?.id || '',
updated_by: parsedUser?.username, updated_by: parsedUser?.username,
updated_at: new Date().toISOString().slice(0, 19).replace('T', ' ') updated_at: new Date().toISOString().slice(0, 19).replace('T', ' ')
}); });
} }
console.log(response)
} catch (error) { } catch (error) {
console.error('Error fetching transaction fee details', error); console.error('Error fetching transaction fee details', error);
setAlert({ show: true, message: 'Failed to fetch transaction fee details' }); setAlert({ show: true, message: 'Failed to fetch transaction fee details' });
} }
}, [GetData, parsedUser?.username]); // only use username if that's all you need }, [GetData, parsedUser?.username]);
// This flag ensures it only fetches once per open
const hasFetchedRef = useRef(false); const hasFetchedRef = useRef(false);
useEffect(() => { useEffect(() => {
@ -307,15 +300,23 @@ const EditFeeDialog = () => {
hasFetchedRef.current = true; hasFetchedRef.current = true;
} }
// Reset fetch flag if dialog is closed
if (!showEditFeeDialog) { if (!showEditFeeDialog) {
hasFetchedRef.current = false; hasFetchedRef.current = false;
} }
}, [selectedTransferFee, showEditFeeDialog, fetchTransactionFee]); }, [selectedTransferFee, showEditFeeDialog, fetchTransactionFee]);
const handleCloseDialog = () => {
setFormField(initialState);
setAlert({ show: false, message: '' });
handleEditFeeDialog(false, null);
};
return ( return (
<Dialog open={showEditFeeDialog} onOpenChange={(open) => handleEditFeeDialog(open, null)}> <Dialog open={showEditFeeDialog} onOpenChange={(open) => {
if (!open) {
handleCloseDialog();
}
}}>
<DialogContent className="container-fixed max-w-[1080px] flex flex-col p-5 overflow-hidden [&>button]:hidden"> <DialogContent className="container-fixed max-w-[1080px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogTitle></DialogTitle> <DialogTitle></DialogTitle>
<DialogDescription></DialogDescription> <DialogDescription></DialogDescription>
@ -328,7 +329,7 @@ const EditFeeDialog = () => {
</div> </div>
<div <div
className="cursor-pointer hover:opacity-100 opacity-50" className="cursor-pointer hover:opacity-100 opacity-50"
onClick={() => handleEditFeeDialog(false, null)} onClick={handleCloseDialog}
> >
<KeenIcon icon="cross" className="text-1.5xl" /> <KeenIcon icon="cross" className="text-1.5xl" />
</div> </div>
@ -654,13 +655,6 @@ const EditFeeDialog = () => {
</div> </div>
<div className="flex justify-end pt-2.5 gap-5"> <div className="flex justify-end pt-2.5 gap-5">
<Button
variant={'outline'}
type="button"
onClick={resetForm}
>
Reset
</Button>
<Button variant={'default'} type="submit" disabled={isSubmitting}> <Button variant={'default'} type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Saving...' : 'Save Changes'} {isSubmitting ? 'Saving...' : 'Save Changes'}
</Button> </Button>

View File

@ -181,7 +181,30 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
meta: { headerClassName: 'w-[250px]' } meta: { headerClassName: 'w-[250px]' }
}, },
{ {
accessorFn: (row) => row.credit_destination?.fullname, accessorFn: (row: { credit_to: string }) => {
const mapping: Record<string, string> = {
D: 'Destination Member',
S: 'Source Member',
I: 'Input Customer'
};
return mapping[row.credit_to] || 'Unknown';
},
id: 'credit_to',
header: ({ column }) => (
<DataGridColumnHeader title="Credit To" column={column} />
),
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[250px]' }
},
{
accessorFn: (row) => {
if (row.credit_to === 'S' || row.credit_to === 'D' || !row.credit_destination) {
return 'N/A';
}
return row.credit_destination?.fullname;
},
id: 'credit_destination', id: 'credit_destination',
header: ({ column }) => <DataGridColumnHeader title="Credit Destination" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Credit Destination" column={column} />,
enableSorting: true, enableSorting: true,
@ -196,37 +219,102 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
enableHiding: false, enableHiding: false,
meta: { headerClassName: 'w-[250px]' } meta: { headerClassName: 'w-[250px]' }
}, },
{
accessorFn: (row: { deduct_from: string }) => {
const mapping: Record<string, string> = {
D: 'Destination Member',
S: 'Source Member',
};
return mapping[row.deduct_from];
},
id: 'deduct_from',
header: ({ column }) => (
<DataGridColumnHeader title="Deduct From" column={column} />
),
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[250px]' }
},
{ {
accessorFn: (row) => row.deduct_from_account?.description, accessorFn: (row) => row.deduct_from_account?.description,
id: 'deduct_from_account', id: 'deduct_from_account',
header: ({ column }) => <DataGridColumnHeader title="Credit Destination Account" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Deduct From Account" column={column} />,
enableSorting: true, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { headerClassName: 'w-[250px]' } meta: { headerClassName: 'w-[250px]' }
}, },
{
accessorFn: (row) => row.priority,
id: 'priority',
header: ({ column }) => <DataGridColumnHeader title="Priority" column={column} />,
enableSorting: true,
enableHiding: false,
cell: ({ row }) => {
const isActive = row.original.priority === 'Y';
return (
<span
className={`px-2 py-1 text-xs font-semibold rounded-full ${
isActive ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'
}`}
>
{isActive ? 'Yes' : 'No'}
</span>
);
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
},
{ {
accessorFn: (row) => (row.priority === 'Y' ? 'Yes' : 'No'), accessorFn: (row) => row.status,
id: 'priority',
header: ({ column }) => <DataGridColumnHeader title="Priority" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[100px]' }
},
{
accessorFn: (row) => (row.status === 'Y' ? 'Active' : 'Inactive'),
id: 'status', id: 'status',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
enableSorting: true, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { headerClassName: 'w-[150px]' } cell: ({ row }) => {
const isActive = row.original.status === 'Y';
return (
<span
className={`px-2 py-1 text-xs font-semibold rounded-full ${
isActive ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'
}`}
>
{isActive ? 'Active' : 'Inactive'}
</span>
);
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
}, },
{ {
accessorFn: (row) => (row.status_include === 'Y' ? 'Yes' : 'No'), accessorFn: (row) => row.status_include,
id: 'status_include', id: 'status_include',
header: ({ column }) => <DataGridColumnHeader title="Status Include" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Status Include" column={column} />,
enableSorting: true, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { headerClassName: 'w-[150px]' } cell: ({ row }) => {
const isActive = row.original.status_include === 'Y';
return (
<span
className={`px-2 py-1 text-xs font-semibold rounded-full ${
isActive ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'
}`}
>
{isActive ? 'Yes' : 'No'}
</span>
);
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
}, },
{ {
id: 'actions', id: 'actions',

View File

@ -701,15 +701,6 @@ const EditDialog = () => {
</div> </div>
<div className="flex justify-end pt-2.5 gap-5"> <div className="flex justify-end pt-2.5 gap-5">
<Button
variant={'outline'}
type="reset"
onClick={() => {
resetForm();
}}
>
Reset
</Button>
<Button variant={'default'} type="submit" disabled={isSubmitting}> <Button variant={'default'} type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Saving...' : 'Save Changes'} {isSubmitting ? 'Saving...' : 'Save Changes'}
</Button> </Button>
@ -724,7 +715,7 @@ const EditDialog = () => {
</div> </div>
<AddFeeDialog /> <AddFeeDialog />
<DeleteFeeDialog /> <DeleteFeeDialog />
{/* <EditFeeDialog /> */} <EditFeeDialog />
</Container> </Container>
</ManageTransferFeeContextProvider> </ManageTransferFeeContextProvider>
</div> </div>