This commit is contained in:
Raja Oktafrianto
2025-04-14 17:40:25 +07:00
20 changed files with 1083 additions and 652 deletions

View File

@ -36,6 +36,7 @@ import {
interface DataTableProps<TData, TValue> { interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]; columns: ColumnDef<TData, TValue>[];
data: TData[]; data: TData[];
createData: any;
onUpdate: any; onUpdate: any;
onDelete: any; onDelete: any;
} }
@ -46,7 +47,7 @@ export function DataTable<TData, TValue>({
createData, createData,
onUpdate, onUpdate,
onDelete onDelete
}: DataTableProps<TData, TValue> & { createData?: () => void }) { }: DataTableProps<TData, TValue>) {
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]); const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const [sorting, setSorting] = useState<SortingState>([]); const [sorting, setSorting] = useState<SortingState>([]);
@ -74,7 +75,7 @@ export function DataTable<TData, TValue>({
onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)} onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)}
className="max-w-sm" className="max-w-sm"
/> />
{/* <Button onClick={createData} variant="outline" className="h-7.5 text-[0.8rem]">Add Data</Button> */} {createData?(<Button onClick={createData} variant="outline" className="h-7.5 text-[0.8rem]">Add Data</Button>) : ""}
</div> </div>
<div className="rounded-md border"> <div className="rounded-md border">
<Table className=''> <Table className=''>

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

@ -157,7 +157,8 @@ const Kyc = () => {
} }
if (dialogType === 'update') { if (dialogType === 'update') {
await axios.put(`${BASE_URL}/customer/update/${customerId}`, form); await axios.put(`${BASE_URL}/customer/update/${customerId}`, form);
if (updateData.isneedapproval == 1) await axios.post(`${BASE_URL}/customer/approve`, { customerid: customerId, description: description}); if (updateData.isneedapproval == 1&&destinationGroup === "Premium") await axios.post(`${BASE_URL}/customer/approve`, { customerid: customerId, description: updateData.approval_description_premium});
if (updateData.isneedapproval == 1&&destinationGroup === "Agent") await axios.post(`${BASE_URL}/customer/approve`, { customerid: customerId, description: updateData.approval_description_agent});
} }
await fetchCustomers(); await fetchCustomers();
setDialogOpen(false); setDialogOpen(false);
@ -233,6 +234,7 @@ const Kyc = () => {
<div className="w-full overflow-x-auto px-4"> <div className="w-full overflow-x-auto px-4">
<div className="min-w-[800px]"> <div className="min-w-[800px]">
<DataTable <DataTable
createData={null}
data={members} data={members}
columns={columns} columns={columns}
onUpdate={handleUpdate} onUpdate={handleUpdate}

View File

@ -48,6 +48,10 @@ const ManageMembers = () => {
let temp = 1; let temp = 1;
let resMembers = customers.data.data.list.map((el: any) => { let resMembers = customers.data.data.list.map((el: any) => {
el.no = temp++; el.no = temp++;
if (el.date_birth) {
const d = new Date(el.date_birth);
el.date_birth = d.toLocaleString("sv-SE");
}
el.name = el.fullname; el.name = el.fullname;
return el; return el;
}); });
@ -77,6 +81,7 @@ const ManageMembers = () => {
function createMember() { function createMember() {
setDialogType('create'); setDialogType('create');
setSelectedMember('')
setMember(initialMember); setMember(initialMember);
setIsDialogOpen(true); setIsDialogOpen(true);
} }
@ -132,13 +137,35 @@ const ManageMembers = () => {
if (updateData[property]) form.append(property, updateData[property]); if (updateData[property]) form.append(property, updateData[property]);
} }
if (dialogType === 'update') await axios.put(`${BASE_URL}/customer/update/${selectedMember}`, form, { if (dialogType === 'update') {
await axios.put(`${BASE_URL}/customer/update/${selectedMember}`, form, {
headers: { headers: {
'Content-Type': 'multipart/form-data' 'Content-Type': 'multipart/form-data'
} }
}); });
// if (dialogType === 'create') await axios.post(`${BASE_URL}/customers/create`, member) toast.success('Success Edit Member');
toast.success('Success Update Member'); }
if (dialogType === 'create') {
const createMember:any = member
createMember.pin = "admin"
delete createMember.password;
delete createMember.try_pin;
delete createMember.license_number;
delete createMember.isneedapproval;
delete createMember.isapproved;
delete createMember.approveddate;
delete createMember.approvedby;
delete createMember.updated_by;
delete createMember.deleted_by;
delete createMember.deleted_at;
delete createMember.group;
delete createMember.point_tier;
delete createMember.approval_description_premium;
delete createMember.approval_description_agent;
delete createMember.language;
await axios.post(`${BASE_URL}/customers/create`, member)
toast.success('Success Create Member. PIN sent to email');
}
} catch (error: any) { } catch (error: any) {
toast.error(error.message); toast.error(error.message);
} finally { } finally {
@ -170,7 +197,7 @@ const ManageMembers = () => {
onYes={handleYes} onYes={handleYes}
onNo={() => setDialogOpen(false)} onNo={() => setDialogOpen(false)}
/> />
{ member.id !== '' ? ( { (member.id!=='' || dialogType==='create') ? (
<DetailMember <DetailMember
showAddDialog={isDialogOpen} showAddDialog={isDialogOpen}
setShowAddDialog={setShowAddDialog} setShowAddDialog={setShowAddDialog}
@ -179,6 +206,7 @@ const ManageMembers = () => {
initialData={member} initialData={member}
fetchCustomers={fetchCustomers} fetchCustomers={fetchCustomers}
profession={profession} profession={profession}
dialogType={dialogType}
/> />
): ""} ): ""}
<h1 className="text-xl font-medium leading-none text-gray-900 mb-3 grid gap-5 lg:gap-7.5 mx-8 w-auto">Manage Members</h1> <h1 className="text-xl font-medium leading-none text-gray-900 mb-3 grid gap-5 lg:gap-7.5 mx-8 w-auto">Manage Members</h1>

View File

@ -21,14 +21,7 @@ import ConfirmDialog from '@/components/confirm';
const BASE_URL_CUSTOMER = apiConfig.service_customer; const BASE_URL_CUSTOMER = apiConfig.service_customer;
// ACCESS ADM // ACCESS ADM
export default function AdmAccess( export default function AdmAccess({page,formData,handleClose,fetchCustomers,viewOnly,setViewOnly}: any) {
page: string,
data: any,
handleClose: any,
fetchCustomers: any,
viewOnly: any,
setViewOnly: any
) {
const [dialogOpen, setDialogOpen] = useState(false); const [dialogOpen, setDialogOpen] = useState(false);
const [dialogType, setDialogType] = useState(''); const [dialogType, setDialogType] = useState('');
const [changeGroup, setChangeGroup] = useState(''); const [changeGroup, setChangeGroup] = useState('');
@ -59,10 +52,10 @@ export default function AdmAccess(
const handleYes = async () => { const handleYes = async () => {
try { try {
if (dialogType === 'update status') { if (dialogType === 'update status') {
let statusNext = getPinStatus(data.status).res; let statusNext = getPinStatus(formData.status).res;
if (statusNext) if (statusNext)
await axios.put(`${BASE_URL_CUSTOMER}/customer/statuspin`, { await axios.put(`${BASE_URL_CUSTOMER}/customer/statuspin`, {
customerid: data.id, customerid: formData.id,
status: statusNext status: statusNext
}); });
else toast.error('Handle Active/Suspend only'); else toast.error('Handle Active/Suspend only');
@ -70,8 +63,8 @@ export default function AdmAccess(
toast.success('Success Update Status'); toast.success('Success Update Status');
} }
if (dialogType === 'reset pin') { if (dialogType === 'reset pin') {
if (data.id) if (formData.id)
await axios.post(`${BASE_URL_CUSTOMER}/customer/resetpin`, { customerid: data.id }); await axios.post(`${BASE_URL_CUSTOMER}/customer/resetpin`, { customerid: formData.id });
else throw { message: 'data.id not found' }; else throw { message: 'data.id not found' };
await fetchCustomers(); await fetchCustomers();
toast.success('Pin will send to customer MSISDN'); toast.success('Pin will send to customer MSISDN');
@ -99,10 +92,10 @@ export default function AdmAccess(
async function buttonChangeGroup() { async function buttonChangeGroup() {
try { try {
let dataObj = { let dataObj = {
customerid: data.id, customerid: formData.id,
destination_group: changeGroup destination_group: changeGroup
}; };
if (data.group_id === changeGroup) if (formData.group_id === changeGroup)
throw { message: `You update same group as the exist customer group` }; throw { message: `You update same group as the exist customer group` };
if (dataObj.customerid && dataObj.destination_group) { if (dataObj.customerid && dataObj.destination_group) {
await axios.post(`${BASE_URL_CUSTOMER}/customer/change-group`, dataObj); await axios.post(`${BASE_URL_CUSTOMER}/customer/change-group`, dataObj);
@ -119,14 +112,14 @@ export default function AdmAccess(
function openChangeGroupDialog(e: any) { function openChangeGroupDialog(e: any) {
e.preventDefault(); e.preventDefault();
setChangeGroup(data.group_id); setChangeGroup(formData.group_id);
setChangeGroupD(true); setChangeGroupD(true);
} }
function btnConfirmDialog(status: boolean) { function btnConfirmDialog(status: boolean) {
setDialogOpen(status); setDialogOpen(status);
} }
if (!formData.id) return '';
if (page !== 'kyc') { if (page !== 'kyc') {
return ( return (
<div className="bg-white p-6 rounded-md shadow-md space-y-6"> <div className="bg-white p-6 rounded-md shadow-md space-y-6">
@ -136,9 +129,9 @@ export default function AdmAccess(
{/* Left Side */} {/* Left Side */}
<div className="space-y-4"> <div className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<p className="text-sm">Pin Status: {getPinStatus(data.status).msg}</p> <p className="text-sm">Pin Status: {getPinStatus(formData.status).msg}</p>
<Button variant="default" onClick={(e) => buttonStatus(e)}> <Button variant="default" onClick={(e) => buttonStatus(e)}>
{getPinStatus(data.status).btn} {getPinStatus(formData.status).btn}
</Button> </Button>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">

View File

@ -6,7 +6,7 @@ import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner'; import { toast } from 'sonner';
const BASE_URL_CUSTOMER = apiConfig.service_customer; const BASE_URL_CUSTOMER = apiConfig.service_customer;
export default function CustomerWallet(customerid: any) { export default function CustomerWallet({customerid}: any) {
const [customerWallet, setCustomerWallet] = useState([]); const [customerWallet, setCustomerWallet] = useState([]);
if (!customerid) return ''; if (!customerid) return '';
@ -21,7 +21,7 @@ export default function CustomerWallet(customerid: any) {
}); });
setCustomerWallet(getCustWallet.data.data.data); setCustomerWallet(getCustWallet.data.data.data);
} catch (error: any) { } catch (error: any) {
// toast.error(error.message); setCustomerWallet([])
toast.error(`Wallet Not Found`); toast.error(`Wallet Not Found`);
} }
} }
@ -30,7 +30,7 @@ export default function CustomerWallet(customerid: any) {
<div className="bg-white p-6 rounded-md shadow-md space-y-4"> <div className="bg-white p-6 rounded-md shadow-md space-y-4">
<h2 className="text-lg font-semibold">Wallet Member</h2> <h2 className="text-lg font-semibold">Wallet Member</h2>
<Card className="p-4"> <Card className="p-4">
{customerWallet.length ? ( {customerWallet ? (
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="min-w-full text-sm text-left"> <table className="min-w-full text-sm text-left">
<thead className="text-xs text-gray-500 border-b"> <thead className="text-xs text-gray-500 border-b">

View File

@ -29,7 +29,7 @@ import AdmAccess from './AdmAccess';
import CustomerWallet from './CustomerWallet'; import CustomerWallet from './CustomerWallet';
const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialData, handleReject, page, fetchCustomers, const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialData, handleReject, page, fetchCustomers,
handleClose, profession handleClose, profession, dialogType
}: any) => { }: any) => {
const [formData, setFormData] = useState(initialData || initialMember); const [formData, setFormData] = useState(initialData || initialMember);
const [viewOnly, setViewOnly] = useState(false); const [viewOnly, setViewOnly] = useState(false);
@ -168,11 +168,18 @@ const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialDa
function buttonOnSubmit(e:any) { function buttonOnSubmit(e:any) {
e.preventDefault(); e.preventDefault();
if (dialogType === 'update') {
if (page === 'kyc' && formData.destinationGroup === "Premium" && !formData.approval_description_premium) return toast.warning(`Approval Premium Description needed!`) if (page === 'kyc' && formData.destinationGroup === "Premium" && !formData.approval_description_premium) return toast.warning(`Approval Premium Description needed!`)
if (page === 'kyc' && formData.destinationGroup === "Agent" && !formData.approval_description_premium) return toast.warning(`Approval Agent Description needed!`) if (page === 'kyc' && formData.destinationGroup === "Agent" && !formData.approval_description_premium) return toast.warning(`Approval Agent Description needed!`)
if (!formData.msisdn||!formData.email||!formData.fullname||!formData.username||!formData.mother_fullname||!formData.address||!formData.nationality||!formData.date_birth||!formData.gender) { if (!formData.msisdn||!formData.email||!formData.fullname||!formData.username||!formData.mother_fullname||!formData.address||!formData.nationality||!formData.date_birth||!formData.gender) {
return toast.warning(`Required fields cannot be empty: msisdn, email, fullname, username, mother Full Name, Address, Nationality, Date Of Birth, Gender.!`) return toast.warning(`Required fields cannot be empty: msisdn, email, fullname, username, mother Full Name, Address, Nationality, Date Of Birth, Gender.!`)
} }
}
if (dialogType === 'create') {
if (!formData.msisdn||!formData.email||!formData.fullname||!formData.username||!formData.mother_fullname||!formData.address||!formData.nationality||!formData.date_birth||!formData.gender) {
return toast.warning(`Required fields cannot be empty: msisdn, email, fullname, username, mother Full Name, Address, Nationality, Date Of Birth, Gender.!`)
}
}
// if (page === 'kyc' && !formData.description) return toast.warning(`Description for approval needed!`) // if (page === 'kyc' && !formData.description) return toast.warning(`Description for approval needed!`)
handleSubmit(formData); handleSubmit(formData);
} }
@ -204,25 +211,23 @@ const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialDa
</Alert> </Alert>
)} )}
{/* <form> */}
{/* onSubmit={(e) => buttonOnSubmit(e, formData)} */}
<div className="card-body grid gap-5"> <div className="card-body grid gap-5">
{formData.id ? generateInput(formData, handleChange, 'Group', 'group_name', 'text', true, true): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Group', 'group_name', 'text', true, true): ''}
{formData.id ? generateInput(formData, handleChange, 'Username', 'username', 'text', true, true): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Username', 'username', 'text', true, dialogType==='create'?false:true): ''}
{formData.id ? generateInput(formData, handleChange, 'Full Name', 'fullname', 'text', true, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Full Name', 'fullname', 'text', true, viewOnly): ''}
{formData.id ? generateImage(formData, handleChange, 'Photo', 'photouser'): ''} {(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'Photo', 'photouser'): ''}
{formData.id ? generateList(formData, handleChange, genders, 'gender', 'Gender', null, true): ''} {(formData.id || dialogType === "create") ? generateList(formData, handleChange, genders, 'gender', 'Gender', null, true): ''}
{formData.id ? generateInput(formData, handleChange, 'Date of Birth', 'date_birth', 'date', true, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Date of Birth', 'date_birth', 'date', true, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'Phone Number', 'msisdn', 'text', true, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Phone Number', 'msisdn', 'text', true, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'Email', 'email', 'text', true, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Email', 'email', 'text', true, viewOnly): ''}
{/* {generateList(formData, handleChange, status, 'status', 'Status', null, true)} */} {/* {generateList(formData, handleChange, status, 'status', 'Status', null, true)} */}
{formData.id ? generateList(formData, handleChange, profession, 'profession', 'Profession', null, false): ''} {(formData.id || dialogType === "create") ? generateList(formData, handleChange, profession, 'profession', 'Profession', null, false): ''}
{formData.id ? generateList(formData, handleChange, municipios, 'municipio', 'Municipio', null, false): ''} {(formData.id || dialogType === "create") ? generateList(formData, handleChange, municipios, 'municipio', 'Municipio', null, false): ''}
{formData.id ? generateList(formData, handleChange, postoAdm, 'posto_adms', 'Posto', 'posto_adms_id', false): ''} {(formData.id || dialogType === "create") ? generateList(formData, handleChange, postoAdm, 'posto_adms', 'Posto', 'posto_adms_id', false): ''}
{formData.id ? generateList(formData, handleChange, sucos, 'suco', 'Suco', 'sucos_id', false): ''} {(formData.id || dialogType === "create") ? generateList(formData, handleChange, sucos, 'suco', 'Suco', 'sucos_id', false): ''}
{formData.id ? generateList(formData, handleChange, aldeias, 'aldeia', 'Aldeia', null, false): ''} {(formData.id || dialogType === "create") ? generateList(formData, handleChange, aldeias, 'aldeia', 'Aldeia', null, false): ''}
{formData.id ? generateInput(formData, handleChange, 'Nationality', 'nationality', 'text', true, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Nationality', 'nationality', 'text', true, viewOnly): ''}
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5"> <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56"></label> <label className="form-label flex items-center gap-1 max-w-56"></label>
<ul className=""> <ul className="">
@ -238,29 +243,33 @@ const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialDa
)} )}
</ul> </ul>
</div> </div>
{formData.id ? generateInput(formData, handleChange, 'Address', 'address', 'text', true, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Address', 'address', 'text', true, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'Mother Fullname', 'mother_fullname', 'text', true, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Mother Fullname', 'mother_fullname', 'text', true, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'Identity Number', 'identity_number', 'text', false, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Identity Number', 'identity_number', 'text', false, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'License Number', 'license_number', 'text', false, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'License Number', 'license_number', 'text', false, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'Merchant Name', 'agent_name', 'text', false, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Merchant Name', 'agent_name', 'text', false, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'Merchant Address', 'merchantaddress', 'text', false, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Merchant Address', 'merchantaddress', 'text', false, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'Longitude Merchant', 'longitudemerchant', 'text', false, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Longitude Merchant', 'longitudemerchant', 'text', false, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'Latitude Merchant', 'latitudemerchant', 'text', false, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Latitude Merchant', 'latitudemerchant', 'text', false, viewOnly): ''}
{formData.id ? generateImage(formData, handleChange, 'File Selfie', 'file_selfie'): ''} {(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'File Selfie', 'file_selfie'): ''}
{formData.id ? generateImage(formData, handleChange, 'File Document', 'file_document_id'): ''} {(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'File Document', 'file_document_id'): ''}
{formData.id ? generateImage(formData, handleChange, 'File Document & Selfie', 'file_document_id_selfie'): ''} {(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'File Document & Selfie', 'file_document_id_selfie'): ''}
{formData.id ? generateImage(formData, handleChange, 'File Commercial License', 'file_commercial_license'): ''} {(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'File Commercial License', 'file_commercial_license'): ''}
{formData.id ? generateList(formData, handleChange, banks, 'bank_name', 'Bank Name', null, false): ''} {(formData.id || dialogType === "create") ? generateList(formData, handleChange, banks, 'bank_name', 'Bank Name', null, false): ''}
{formData.id ? generateInput(formData, handleChange, 'Bank Account', 'bank_account', 'text', false, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Bank Account', 'bank_account', 'text', false, viewOnly): ''}
{formData.id ? generateInput(formData, handleChange, 'iBank Number', 'ibank_number', 'text', false, viewOnly): ''} {(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'iBank Number', 'ibank_number', 'text', false, viewOnly): ''}
{(formData.id&&(!page||formData.destinationGroup === "Premium")) ? generateInput(formData, handleChange, 'Approval Premium Description', 'approval_description_premium', 'text', false, viewOnly): ''} {(formData.id&&(!page||formData.destinationGroup === "Premium")) ? generateInput(formData, handleChange, 'Approval Premium Description', 'approval_description_premium', 'text', false, viewOnly): ''}
{(formData.id&&(!page||formData.destinationGroup === "Agent")) ? generateInput(formData, handleChange, 'Approval Agent Description', 'approval_description_agent', 'text', false, viewOnly): ''} {(formData.id&&(!page||formData.destinationGroup === "Agent")) ? generateInput(formData, handleChange, 'Approval Agent Description', 'approval_description_agent', 'text', false, viewOnly): ''}
{(formData.id && page!=='kyc') ? AdmAccess(page, formData, handleClose,fetchCustomers, viewOnly, setViewOnly): ""} {(formData.id && page!=='kyc') ? (
{(formData.id && page!=='kyc') ? CustomerWallet(formData.id) : ""} <AdmAccess page={page}formData={formData}fetchCustomers={fetchCustomers}handleClose={handleClose}viewOnly={viewOnly}setViewOnly={setViewOnly}/>
): ""}
{(formData.id && page!=='kyc') ? (
<CustomerWallet customerid={formData.id}/>
) : ""}
<div className="flex justify-end gap-5"> <div className="flex justify-end gap-5">
<Button onClick={(e:any) => btnPrevDef(e)} color="secondary">{ viewOnly ? (`Open Edit`) : (`Close Edit`) }</Button> <Button onClick={(e:any) => btnPrevDef(e)} color="secondary">{ viewOnly ? (`Open Edit`) : (`Close Edit`) }</Button>
@ -276,7 +285,7 @@ const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialDa
</Button> </Button>
</div> </div>
</div> </div>
{/* </form> */}
</div> </div>
</DialogBody> </DialogBody>
</DialogContent> </DialogContent>
@ -289,8 +298,7 @@ export default DetailMember;
function generateInput(formData:any, handleChange:any, label:string, name:string, type: string, required: boolean, disabled: boolean) { function generateInput(formData:any, handleChange:any, label:string, name:string, type: string, required: boolean, disabled: boolean) {
function generateDate(isoString: string) { function generateDate(isoString: string) {
const date = new Date(isoString); return isoString.slice(0, 10); // "2000-01-18"
return date.toISOString().slice(0, 10); // "2000-01-18"
} }
return ( return (
<> <>

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,7 +191,7 @@ 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 }]); setParents((el: any) => [...el, { id: parent.id, name: parent.name }]);
@ -234,20 +234,27 @@ const ManageMenusContextProvider = ({ children }: { children: React.ReactNode })
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: 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);
if (query.filter && query.filter.length > 0) {
return { data: response?.data.list, totalCount: response?.data.total_count };
} else {
const transformedData = response?.data.list.flatMap((row: any, parentIdx: number) =>
flattenChildren(row, parentIdx) flattenChildren(row, parentIdx)
); );
@ -258,6 +265,7 @@ const ManageMenusContextProvider = ({ children }: { children: React.ReactNode })
const totalPages = Math.ceil(total_count / limit); const totalPages = Math.ceil(total_count / limit);
return { data: paginatedData, totalCount: total_count }; 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 };
@ -287,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

@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { useManageTransferFeeContext } from '../hooks/useManageTransferFeeContext'; import { useManageTransferFeeContext } from '../hooks/useManageTransferFeeContext';
import { NumericFormat } from 'react-number-format'; import { NumericFormat } from 'react-number-format';
import { import {
@ -40,11 +40,7 @@ import {
TableHeader, TableHeader,
TableRow TableRow
} from '@/components/ui/table'; } from '@/components/ui/table';
import { ManageTransferFeeContext } from '../hooks/ManageTransferFeeContext';
import { ColumnDef } from '@tanstack/react-table';
import { ManageTransferFeeContextProvider } from '../../transferfee/hooks/ManageTransferFeeContext';
import { apiConfig } from '@/config/api.config'; import { apiConfig } from '@/config/api.config';
import { get } from 'http';
interface TransactionTypeProps { interface TransactionTypeProps {
id: string; id: string;
@ -62,12 +58,19 @@ interface CustomerProps {
const API_URL = apiConfig.service_transaction; const API_URL = apiConfig.service_transaction;
const API_URL_MASTER_DATA = apiConfig.service_master_data; const API_URL_MASTER_DATA = apiConfig.service_master_data;
const API_URL_CUSTOMER = apiConfig.service_customer; const API_URL_CUSTOMER = apiConfig.service_customer;
const AddFeeDialog = () => { const AddFeeDialog = () => {
const parentRef = useRef<any | null>(null); const parentRef = useRef<any | null>(null);
const { reload } = useDataGrid(); const { reload } = useDataGrid();
const { PostData, PutData, GetData } = useCallApi(); const { PostData, PutData, GetData } = useCallApi();
const { showAddFeeDialog, handleAddFeeDialog, handleEditFeeDialog, selectedTransferFee } = const {
useManageTransferFeeContext(); showAddFeeDialog,
handleAddFeeDialog,
handleEditFeeDialog,
selectedTransferFee,
transactionTypeId
} = useManageTransferFeeContext();
const [alert, setAlert] = useState({ const [alert, setAlert] = useState({
show: false, show: false,
message: '' message: ''
@ -76,7 +79,15 @@ const AddFeeDialog = () => {
const [wallets, setWallets] = useState<WalletProps[]>([]); const [wallets, setWallets] = useState<WalletProps[]>([]);
const [customers, setCustomers] = useState<CustomerProps[]>([]); const [customers, setCustomers] = useState<CustomerProps[]>([]);
const [defaultCustomer, setDefaultCustomer] = useState(''); const [defaultCustomer, setDefaultCustomer] = useState('');
const [transactionTypeName, setTransactionTypeName] = useState('');
const [isLoadingTransactionType, setIsLoadingTransactionType] = useState(false);
const [isLoadingWallets, setIsLoadingWallets] = useState(false);
const [isLoadingCustomers, setIsLoadingCustomers] = useState(false);
const customersWithNames = customers.map((customer) => ({
id: customer.id,
name: customer.username,
}));
const initialState = { const initialState = {
name: '', name: '',
description: '', description: '',
@ -104,54 +115,57 @@ const AddFeeDialog = () => {
const resetForm = () => { const resetForm = () => {
setFormField(initialState); setFormField(initialState);
setTransactionTypeName('');
}; };
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [showTransactionFeeDialog, setShowTransactionFeeDialog] = useState(false); const [showTransactionFeeDialog, setShowTransactionFeeDialog] = useState(false);
const parsedUser = getAuth()?.user; const parsedUser = getAuth()?.user;
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { useEffect(() => {
e.preventDefault(); if (showAddFeeDialog && transactionTypeId) {
// setIsSubmitting(true); setIsLoadingTransactionType(true);
const payload = {
name: formField.name, setFormField(prev => ({
description: formField.description, ...prev,
period_start: formField.period_start, transaction_type: transactionTypeId
period_end: formField.period_end, }));
minimum_amount: formField.minimum_amount,
maximum_amount: formField.maximum_amount, const getTransactionTypeDetails = async () => {
deduct_amount: formField.deduct_amount, try {
deduct_percentage: formField.deduct_percentage, const response = await GetData(`${API_URL}/transactiontype/getdata/${transactionTypeId}`, {});
fee_amount: formField.fee_amount, if (response?.status && response?.data) {
transaction_type: formField.transaction_type, setTransactionTypeName(response.data.name);
status: formField.status, }
status_include: formField.status_include, } catch (error) {
priority: formField.priority, console.error('Error fetching transaction type details', error);
deduct_from: formField.deduct_from, } finally {
deduct_from_account: formField.deduct_from_account, setIsLoadingTransactionType(false);
credit_to: formField.credit_to, }
credit_destination: formField.credit_destination,
credit_destination_account: formField.credit_destination_account
};
}; };
getTransactionTypeDetails();
}
}, [showAddFeeDialog, transactionTypeId, GetData]);
useEffect(() => { useEffect(() => {
const created_time = new Date(); const created_time = new Date();
const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' '); const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
if (showAddFeeDialog) { if (showAddFeeDialog) {
setFormField({ setFormField(prev => ({
...formField, ...prev,
created_by: parsedUser?.username, created_by: parsedUser?.username,
created_at: formattedTime created_at: formattedTime
}); }));
} }
}, [showAddFeeDialog]); }, [showAddFeeDialog, parsedUser?.username]);
useEffect(() => { useEffect(() => {
if (!showAddFeeDialog) return; if (!showAddFeeDialog) return;
const getTransactionTypeList = async (sorting: any) => { const getTransactionTypeList = async (sorting: any) => {
setIsLoadingTransactionType(true);
try { try {
sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting; sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
const response = await GetData(`${API_URL}/transactiontype/list`, { const response = await GetData(`${API_URL}/transactiontype/list`, {
@ -164,13 +178,16 @@ const AddFeeDialog = () => {
setTransactionTypes(response?.data.list || []); setTransactionTypes(response?.data.list || []);
} catch (error) { } catch (error) {
console.error('Error fetching transaction types', error); console.error('Error fetching transaction types', error);
} finally {
setIsLoadingTransactionType(false);
} }
}; };
getTransactionTypeList([{ id: 'id', desc: false }]); getTransactionTypeList([{ id: 'id', desc: false }]);
}, [showAddFeeDialog]); }, [showAddFeeDialog, GetData]);
const fetchWallets = useCallback(async () => { const fetchWallets = useCallback(async () => {
setIsLoadingWallets(true);
const params = { const params = {
limit: 100, limit: 100,
page: 1, page: 1,
@ -188,6 +205,8 @@ const AddFeeDialog = () => {
} catch (error) { } catch (error) {
console.error('Error fetching wallets', error); console.error('Error fetching wallets', error);
setWallets([]); setWallets([]);
} finally {
setIsLoadingWallets(false);
} }
}, [GetData]); }, [GetData]);
@ -199,6 +218,7 @@ const AddFeeDialog = () => {
useEffect(() => { useEffect(() => {
if (!showAddFeeDialog) return; if (!showAddFeeDialog) return;
const getCustomerList = async (sorting: any) => { const getCustomerList = async (sorting: any) => {
setIsLoadingCustomers(true);
try { try {
sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting; sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
@ -218,6 +238,8 @@ const AddFeeDialog = () => {
} catch (error) { } catch (error) {
console.error('Error fetching customers', error); console.error('Error fetching customers', error);
setCustomers([]); setCustomers([]);
} finally {
setIsLoadingCustomers(false);
} }
}; };
@ -280,6 +302,13 @@ const AddFeeDialog = () => {
reload(); reload();
resetForm(); resetForm();
handleAddFeeDialog(false); handleAddFeeDialog(false);
const createActivity = {
module: 'Manage Transfer Fee',
description: `Create Transfer Fee => ${formField.name}`,
action: 'C'
};
doSaveLogActivity(createActivity);
} else { } else {
setAlert({ show: true, message: response?.message || 'Failed to create transfer fee' }); setAlert({ show: true, message: response?.message || 'Failed to create transfer fee' });
} }
@ -293,6 +322,40 @@ const AddFeeDialog = () => {
[formField, PostData, reload, handleAddFeeDialog] [formField, PostData, reload, handleAddFeeDialog]
); );
const renderSelectWithLoading = (
value: string,
onChangeHandler: (value: string) => void,
options: {id: string, name: string}[] | null,
placeholder: string,
isLoading: boolean
) => {
return (
<Select
value={value}
onValueChange={onChangeHandler}
disabled={isLoading}
>
<SelectTrigger>
{isLoading ? (
<div className="flex items-center">
<div className="animate-pulse bg-gray-200 h-4 w-24 rounded"></div>
<span className="ml-2">Loading...</span>
</div>
) : (
<SelectValue placeholder={placeholder} />
)}
</SelectTrigger>
<SelectContent>
{options && options.map((option) => (
<SelectItem value={option.id} key={option.id}>
{option.name}
</SelectItem>
))}
</SelectContent>
</Select>
);
};
return ( return (
<Dialog open={showAddFeeDialog} onOpenChange={(open) => handleAddFeeDialog(open)}> <Dialog open={showAddFeeDialog} onOpenChange={(open) => handleAddFeeDialog(open)}>
<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">
@ -325,6 +388,35 @@ const AddFeeDialog = () => {
<form action="" onSubmit={doCreateTransferType}> <form action="" onSubmit={doCreateTransferType}>
<div className="card flex flex-col gap-5"> <div className="card flex flex-col gap-5">
<div className="card-body grid gap-5 p-0"> <div className="card-body grid gap-5 p-0">
<div className="w-full">
<label className="form-label">Transaction Type ID <span className="text-red-500">*</span></label>
{transactionTypeId ? (
<div className="relative">
<Input
className="input bg-gray-100"
type="text"
value={isLoadingTransactionType ? '' : transactionTypeName}
readOnly
/>
{isLoadingTransactionType && (
<div className="absolute inset-0 flex items-center justify-start bg-gray-100 px-3">
<div className="flex items-center">
<div className="animate-pulse bg-gray-200 h-4 w-24 rounded"></div>
<span className="ml-2 text-gray-500">Loading transaction type...</span>
</div>
</div>
)}
</div>
) : (
renderSelectWithLoading(
formField.transaction_type,
(transaction_type) => setFormField((prev) => ({ ...prev, transaction_type })),
transactionTypes,
"Select Transaction Type",
isLoadingTransactionType
)
)}
</div>
<div className="w-full"> <div className="w-full">
<label className="form-label">Transfer Free Name <span className="text-red-500">*</span></label> <label className="form-label">Transfer Free Name <span className="text-red-500">*</span></label>
<Input <Input
@ -475,21 +567,13 @@ const AddFeeDialog = () => {
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label">Deduct From Destination <span className="text-red-500">*</span></label> <label className="form-label">Deduct From Destination <span className="text-red-500">*</span></label>
<Select {renderSelectWithLoading(
value={formField.deduct_from_account} formField.deduct_from_account,
onValueChange={(value) => setFormField({ ...formField, deduct_from_account: value })} (value) => setFormField({ ...formField, deduct_from_account: value }),
> wallets,
<SelectTrigger> "Select Wallet",
<SelectValue placeholder="Select Wallet" /> isLoadingWallets
</SelectTrigger> )}
<SelectContent>
{wallets.map((wallet) => (
<SelectItem value={wallet.id} key={wallet.id}>
{wallet.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label">Credit To <span className="text-red-500">*</span></label> <label className="form-label">Credit To <span className="text-red-500">*</span></label>
@ -514,60 +598,24 @@ const AddFeeDialog = () => {
{formField.credit_to === 'I' && ( {formField.credit_to === 'I' && (
<div className="w-full"> <div className="w-full">
<label className="form-label">Credit Destination <span className="text-red-500">*</span></label> <label className="form-label">Credit Destination <span className="text-red-500">*</span></label>
<Select {renderSelectWithLoading(
value={formField.credit_destination} formField.credit_destination,
onValueChange={(value) => setFormField({ ...formField, credit_destination: value })} (value) => setFormField({ ...formField, credit_destination: value }),
> customersWithNames,
<SelectTrigger> "Select Customer",
<SelectValue placeholder="Select Customer" /> isLoadingCustomers
</SelectTrigger> )}
<SelectContent>
{customers.map((customer) => (
<SelectItem value={customer.id} key={customer.id}>
{customer.username} - {customer.msisdn}
</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
)} )}
<div className="w-full"> <div className="w-full">
<label className="form-label">Credit Destination Account <span className="text-red-500">*</span></label> <label className="form-label">Credit Destination Account <span className="text-red-500">*</span></label>
<Select {renderSelectWithLoading(
value={formField.credit_destination_account} formField.credit_destination_account,
onValueChange={(value) => setFormField({ ...formField, credit_destination_account: value })} (value) => setFormField({ ...formField, credit_destination_account: value }),
> wallets,
<SelectTrigger> "Select Wallet",
<SelectValue placeholder="Select Wallet" /> isLoadingWallets
</SelectTrigger> )}
<SelectContent>
{wallets.map((wallet) => (
<SelectItem value={wallet.id} key={wallet.id}>
{wallet.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="w-full">
<label className="form-label">Transaction Type ID <span className="text-red-500">*</span></label>
<Select
value={formField.transaction_type}
onValueChange={(transaction_type) =>
setFormField((prev) => ({ ...prev, transaction_type }))
}
>
<SelectTrigger>
<SelectValue placeholder="Select Transaction Type" />
</SelectTrigger>
<SelectContent>
{transactionTypes.map((transactiontype) => (
<SelectItem value={transactiontype.id} key={transactiontype.id}>
{transactiontype.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label">Status <span className="text-red-500">*</span></label> <label className="form-label">Status <span className="text-red-500">*</span></label>
@ -624,7 +672,11 @@ const AddFeeDialog = () => {
> >
Reset Reset
</Button> </Button>
<Button variant={'default'} type="submit" disabled={isSubmitting}> <Button
variant={'default'}
type="submit"
disabled={isSubmitting || isLoadingTransactionType || isLoadingWallets || isLoadingCustomers}
>
{isSubmitting ? 'Saving...' : 'Save Changes'} {isSubmitting ? 'Saving...' : 'Save Changes'}
</Button> </Button>
</div> </div>

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();
@ -167,6 +167,11 @@ const EditFeeDialog = () => {
toast.success('Successfully updated transfer fee'); toast.success('Successfully updated transfer fee');
reload(); reload();
handleEditFeeDialog(false, null); handleEditFeeDialog(false, null);
const createActivity = {
module: 'Manage Transfer Type',
description: `Edit Transfer Type => ${selectedTransferFee}`,
action: 'U'
};
} else { } else {
setAlert({ show: true, message: response?.message || 'Failed to update transfer fee' }); setAlert({ show: true, message: response?.message || 'Failed to update transfer fee' });
} }
@ -257,15 +262,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 +282,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 +305,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 +334,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 +660,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

@ -1,15 +1,15 @@
import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components'; import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner'; import { Toaster } from '@/components/ui/sonner';
import { apiConfig } from '@/config/api.config'; import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks'; import { useCallApi } from '@/hooks';
import { ColumnDef } from '@tanstack/react-table'; import { ColumnDef } from '@tanstack/react-table';
import { createContext, useCallback, useEffect, useMemo, useState } from 'react'; import { createContext, useCallback, useEffect, useMemo, useState } from 'react';
import ListToolbar from '../blocks/ListToolBar'; import ListToolbar from '../blocks/ListToolBar';
import DeleteDialog from '../blocks/DeleteDialog'; import DeleteDialog from '../blocks/DeleteDialog';
import { EditFeeDialog } from '../blocks/EditDialog'; import { EditFeeDialog } from '../blocks/EditDialog';
import { useManageTransferTypeContext } from '../../transfertype/hooks/useManageTransferTypeContext'; import { useManageTransferTypeContext } from '../../transfertype/hooks/useManageTransferTypeContext';
interface ContextProps { interface ContextProps {
showEditFeeDialog: boolean; showEditFeeDialog: boolean;
handleEditFeeDialog: (show: boolean, selected_TransferFee: string | null) => void; handleEditFeeDialog: (show: boolean, selected_TransferFee: string | null) => void;
showAddFeeDialog: boolean; showAddFeeDialog: boolean;
@ -17,19 +17,23 @@ interface ContextProps {
handleDeleteFeeDialog: (show: boolean, selected_TransferFee: string | null) => void; handleDeleteFeeDialog: (show: boolean, selected_TransferFee: string | null) => void;
showDeleteFeeDialog: boolean; showDeleteFeeDialog: boolean;
selectedTransferFee: string | null; selectedTransferFee: string | null;
} transactionTypeId: string | null;
const initialProps: ContextProps = { }
const initialProps: ContextProps = {
showEditFeeDialog: false, showEditFeeDialog: false,
handleEditFeeDialog: () => {}, handleEditFeeDialog: () => {},
showAddFeeDialog: false, showAddFeeDialog: false,
handleAddFeeDialog: () => {}, handleAddFeeDialog: () => {},
showDeleteFeeDialog: false, showDeleteFeeDialog: false,
handleDeleteFeeDialog: () => {}, handleDeleteFeeDialog: () => {},
selectedTransferFee: null selectedTransferFee: null,
}; transactionTypeId: null,
interface TransferFeeProps { };
interface TransferFeeProps {
name: string; name: string;
description: string; description: string;
minimum_amount: number; minimum_amount: number;
@ -42,20 +46,18 @@ interface TransferFeeProps {
status: string; status: string;
status_include: string; status_include: string;
fee: number; fee: number;
} }
const ManageTransferFeeContext = createContext<ContextProps>(initialProps); const ManageTransferFeeContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_transaction; const API_URL = apiConfig.service_transaction;
const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactNode }) => { const ManageTransferFeeContextProvider = ({ children, transactionTypeId = null }: { children: React.ReactNode; transactionTypeId?: string | null }) => {
const [showEditFeeDialog, setShowEditFeeDialog] = useState(false); const [showEditFeeDialog, setShowEditFeeDialog] = useState(false);
const [showAddFeeDialog, setShowAddFeeDialog] = useState(false); const [showAddFeeDialog, setShowAddFeeDialog] = useState(false);
const [showDeleteFeeDialog, setShowDeleteFeeDialog] = useState(false); const [showDeleteFeeDialog, setShowDeleteFeeDialog] = useState(false);
const { showAddDialog, handleAddDialog, selectedTransferType } = useManageTransferTypeContext(); const { showAddDialog, handleAddDialog, selectedTransferType } = useManageTransferTypeContext();
const [selectedTransferFee, setSelectedTransferFee] = useState<string | null>(null); const [selectedTransferFee, setSelectedTransferFee] = useState<string | null>(null);
const { GetData } = useCallApi(); const { GetData } = useCallApi();
const handleEditFeeDialog = useCallback((show: boolean, selected_TransferFee: string | null) => { const handleEditFeeDialog = useCallback((show: boolean, selected_TransferFee: string | null) => {
setSelectedTransferFee(show ? selected_TransferFee : null); setSelectedTransferFee(show ? selected_TransferFee : null);
setShowEditFeeDialog(show); setShowEditFeeDialog(show);
@ -85,7 +87,7 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
try { try {
const response = await GetData(`${API_URL}/transactionfees/getdatabytransactiontype/${selectedTransferType}`, {}); const response = await GetData(`${API_URL}/transactionfees/getdatabytransactiontype/${selectedTransferType}`, {});
console.log('API Response:', response?.data); // console.log('API Response:', response?.data);
return { return {
data: response?.data , data: response?.data ,
@ -181,7 +183,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,
@ -197,36 +222,101 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
meta: { headerClassName: 'w-[250px]' } meta: { headerClassName: 'w-[250px]' }
}, },
{ {
accessorFn: (row) => row.deduct_from_account?.description, accessorFn: (row: { deduct_from: string }) => {
id: 'deduct_from_account', const mapping: Record<string, string> = {
header: ({ column }) => <DataGridColumnHeader title="Credit Destination Account" column={column} />, D: 'Destination Member',
S: 'Source Member',
};
return mapping[row.deduct_from];
},
id: 'deduct_from',
header: ({ column }) => (
<DataGridColumnHeader title="Deduct From" column={column} />
),
enableSorting: true, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { headerClassName: 'w-[250px]' } meta: { headerClassName: 'w-[250px]' }
}, },
{ {
accessorFn: (row) => (row.priority === 'Y' ? 'Yes' : 'No'), accessorFn: (row) => row.deduct_from_account?.description,
id: 'deduct_from_account',
header: ({ column }) => <DataGridColumnHeader title="Deduct From Account" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[250px]' }
},
{
accessorFn: (row) => row.priority,
id: 'priority', id: 'priority',
header: ({ column }) => <DataGridColumnHeader title="Priority" column={column} />, header: ({ column }) => <DataGridColumnHeader title="Priority" column={column} />,
enableSorting: true, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { headerClassName: 'w-[100px]' } 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.status === 'Y' ? 'Active' : 'Inactive'), accessorFn: (row) => row.status,
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',
@ -265,7 +355,7 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
<div className="container mx-auto py-5"> <div className="container mx-auto py-5">
<div className="flex justify-between items-center mt-6"> <div className="flex justify-between items-center mt-6">
<h1 className="text-xl font-semibold text-gray-900">Manage Transaction Fee</h1> <h1 className="text-xl font-semibold text-gray-900">Manage Transaction Fee</h1>
</div> </div>
<ManageTransferFeeContext.Provider <ManageTransferFeeContext.Provider
value={{ value={{
showEditFeeDialog, showEditFeeDialog,
@ -274,7 +364,8 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
handleAddFeeDialog, handleAddFeeDialog,
selectedTransferFee, selectedTransferFee,
showDeleteFeeDialog, showDeleteFeeDialog,
handleDeleteFeeDialog handleDeleteFeeDialog,
transactionTypeId
}} }}
> >
<Toaster expand visibleToasts={9} duration={3000} /> <Toaster expand visibleToasts={9} duration={3000} />
@ -295,6 +386,6 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
</ManageTransferFeeContext.Provider> </ManageTransferFeeContext.Provider>
</div> </div>
); );
}; };
export { ManageTransferFeeContext, ManageTransferFeeContextProvider }; export { ManageTransferFeeContext, ManageTransferFeeContextProvider };

View File

@ -39,6 +39,7 @@ import {
CommandItem, CommandItem,
CommandList CommandList
} from '@/components/ui/command'; } from '@/components/ui/command';
import { doSaveLogActivity } from '@/actions/GlobalActions';
interface WalletProps { interface WalletProps {
id: string; id: string;
@ -95,7 +96,6 @@ const AddDialog = () => {
const parsedUser = getAuth()?.user; const parsedUser = getAuth()?.user;
// Updated validation function to make only certain fields required
const validateForm = () => { const validateForm = () => {
const requiredFields = [ const requiredFields = [
'name', 'name',
@ -141,6 +141,13 @@ const AddDialog = () => {
toast.success('Success Create Transfer Type'); toast.success('Success Create Transfer Type');
reload(); reload();
resetForm(); resetForm();
const createActivity = {
module: 'Manage Transfer Type',
description: `Create Transfer Type => ${formField.name}`,
action: 'C'
};
doSaveLogActivity(createActivity);
} }
}) })
.finally(() => { .finally(() => {
@ -218,7 +225,7 @@ const AddDialog = () => {
order_direction: 'ASC', order_direction: 'ASC',
}; };
const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, params); const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, params);
console.log(response) // console.log(response)
if (response?.status && response?.data) { if (response?.status && response?.data) {
setWallets(response.data.list); setWallets(response.data.list);
} else { } else {
@ -230,7 +237,7 @@ const AddDialog = () => {
if (!showAddDialog) return; if (!showAddDialog) return;
fetchWallets(); fetchWallets();
}, [showAddDialog]); }, [showAddDialog]);
console.log(formField) // console.log(formField)
return ( return (
<Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}> <Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
<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">
@ -436,7 +443,7 @@ const AddDialog = () => {
<div className="w-full"> <div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5"> <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56"> <label className="form-label flex items-center gap-1 max-w-56">
TransactionType Status Status Transaction Type
<span className="text-red-500"> *</span> <span className="text-red-500"> *</span>
</label> </label>
@ -453,12 +460,15 @@ const AddDialog = () => {
<SelectContent> <SelectContent>
<SelectItem value="D">Disbursement </SelectItem> <SelectItem value="D">Disbursement </SelectItem>
<SelectItem value="O">Other </SelectItem> <SelectItem value="O">Other </SelectItem>
<SelectItem value="CA">Change Customer to Agent </SelectItem> <SelectItem value="CA">Change Group Emoney Customer to Agent </SelectItem>
<SelectItem value="AC">Change Agent to Customer </SelectItem> <SelectItem value="AC">Change Group Emoney Agent to Customer </SelectItem>
<SelectItem value="PA">Change Group Point Agent to Customer </SelectItem>
<SelectItem value="PC">Change Group Point Customer to Agent</SelectItem>
<SelectItem value="CE">Return Customer Emoney </SelectItem> <SelectItem value="CE">Return Customer Emoney </SelectItem>
<SelectItem value="AD">Return Agent Deposit </SelectItem> <SelectItem value="AD">Return Agent Deposit </SelectItem>
<SelectItem value="AM">Return Agent Merchant </SelectItem> <SelectItem value="AM">Return Agent Merchant </SelectItem>
<SelectItem value="AE">Return Agent Emoney </SelectItem> <SelectItem value="AE">Return Agent Emoney </SelectItem>
<SelectItem value="R">Reward Point </SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>

View File

@ -7,6 +7,7 @@ import { toast } from 'sonner';
import { useCallApi } from '@/hooks'; import { useCallApi } from '@/hooks';
import { useManageTransferTypeContext } from '../hooks/useManageTransferTypeContext'; import { useManageTransferTypeContext } from '../hooks/useManageTransferTypeContext';
import { DialogDescription } from '@radix-ui/react-dialog'; import { DialogDescription } from '@radix-ui/react-dialog';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_transaction; const API_URL = apiConfig.service_transaction;
@ -33,6 +34,12 @@ const DeleteDialog = () => {
setAlert({ show: false, message: '' }); setAlert({ show: false, message: '' });
handleDeleteDialog(false, null); handleDeleteDialog(false, null);
reload(); reload();
const createActivity = {
module: 'Manage Transfer Type',
description: `Delete Transfer Type => ${selectedTransferType}`,
action: 'D'
};
doSaveLogActivity(createActivity);
// setTimeout(() => toast.success('Success Delete Transaction Type'), 0); // setTimeout(() => toast.success('Success Delete Transaction Type'), 0);
} else { } else {
setAlert({ show: true, message: response?.message }); setAlert({ show: true, message: response?.message });

View File

@ -54,8 +54,7 @@ interface PermissionObject {
const EditDialog = () => { const EditDialog = () => {
const parentRef = useRef<any | null>(null); const parentRef = useRef<any | null>(null);
const { showEditDialog, handleEditDialog, selectedTransferType } = const { showEditDialog, handleEditDialog, selectedTransferType } = useManageTransferTypeContext();
useManageTransferTypeContext();
const { reload } = useDataGrid(); const { reload } = useDataGrid();
const [wallets, setWallets] = useState<WalletProps[]>([]); const [wallets, setWallets] = useState<WalletProps[]>([]);
const [groups, setGroups] = useState<PermissionObject[]>([]); const [groups, setGroups] = useState<PermissionObject[]>([]);
@ -112,13 +111,11 @@ const EditDialog = () => {
const isSelected = prevState.permission.includes(groupId); const isSelected = prevState.permission.includes(groupId);
if (isSelected) { if (isSelected) {
// Remove the permission if already selected
return { return {
...prevState, ...prevState,
permission: prevState.permission.filter((id) => id !== groupId) permission: prevState.permission.filter((id) => id !== groupId)
}; };
} else { } else {
// Add the permission if not selected
return { return {
...prevState, ...prevState,
permission: [...prevState.permission, groupId] permission: [...prevState.permission, groupId]
@ -138,13 +135,13 @@ const EditDialog = () => {
'type' 'type'
]; ];
const missingFields = requiredFields.filter( const missingFields = requiredFields.filter((field) => {
(field) => { return (
return formField[field as keyof typeof formField] === '' || formField[field as keyof typeof formField] === '' ||
formField[field as keyof typeof formField] === null || formField[field as keyof typeof formField] === null ||
formField[field as keyof typeof formField] === undefined; formField[field as keyof typeof formField] === undefined
}
); );
});
if (missingFields.length > 0) { if (missingFields.length > 0) {
setAlert({ setAlert({
@ -154,7 +151,6 @@ const EditDialog = () => {
return false; return false;
} }
// Validate that at least one permission is selected
if (formField.permission.length === 0) { if (formField.permission.length === 0) {
setAlert({ setAlert({
show: true, show: true,
@ -217,13 +213,15 @@ const EditDialog = () => {
const doUpdateTransferType = useCallback(async () => { const doUpdateTransferType = useCallback(async () => {
try { try {
// Create a clean copy of the form data with properly formatted permissions
const formDataToSend = { const formDataToSend = {
...formField, ...formField,
permission: formField.permission.filter(id => typeof id === 'string') permission: formField.permission.filter((id) => typeof id === 'string')
}; };
const response = await PutData(`${API_URL}/transactiontype/update/${selectedTransferType}`, formDataToSend); const response = await PutData(
`${API_URL}/transactiontype/update/${selectedTransferType}`,
formDataToSend
);
if (response?.status) { if (response?.status) {
setAlert({ show: false, message: '' }); setAlert({ show: false, message: '' });
@ -236,15 +234,12 @@ const EditDialog = () => {
setAlert({ setAlert({
show: true, show: true,
message: message:
error instanceof Error error instanceof Error ? error.message : 'An error occurred while updating transfer type'
? error.message
: 'An error occurred while updating transfer type'
}); });
return false; return false;
} }
}, [formField, selectedTransferType, PutData]); }, [formField, selectedTransferType, PutData]);
// Fetch customers
useEffect(() => { useEffect(() => {
if (!showEditDialog) return; if (!showEditDialog) return;
@ -270,7 +265,6 @@ const EditDialog = () => {
getCustomerList(); getCustomerList();
}, [showEditDialog, GetData]); }, [showEditDialog, GetData]);
// Fetch groups
useEffect(() => { useEffect(() => {
if (!showEditDialog) return; if (!showEditDialog) return;
@ -295,7 +289,6 @@ const EditDialog = () => {
getGroupList(); getGroupList();
}, [showEditDialog, GetData]); }, [showEditDialog, GetData]);
// Fetch wallets
useEffect(() => { useEffect(() => {
if (!showEditDialog) return; if (!showEditDialog) return;
@ -306,7 +299,7 @@ const EditDialog = () => {
page: 1, page: 1,
with_deleted: false, with_deleted: false,
order_field: 'Wallets.name', order_field: 'Wallets.name',
order_direction: 'ASC', order_direction: 'ASC'
}); });
if (response?.status && response?.data) { if (response?.status && response?.data) {
@ -320,21 +313,21 @@ const EditDialog = () => {
getWalletList(); getWalletList();
}, [showEditDialog, GetData]); }, [showEditDialog, GetData]);
// Fetch transaction type data
useEffect(() => { useEffect(() => {
if (!showEditDialog || !selectedTransferType) return; if (!showEditDialog || !selectedTransferType) return;
const fetchTransactionType = async () => { const fetchTransactionType = async () => {
try { try {
const response = await GetData(`${API_URL}/transactiontype/getdata/${selectedTransferType}`, {}); const response = await GetData(
console.log(response); `${API_URL}/transactiontype/getdata/${selectedTransferType}`,
{}
);
// console.log(response);
if (response?.status) { if (response?.status) {
// Process permissions to ensure they're always string IDs
let permissionIds: string[] = []; let permissionIds: string[] = [];
if (Array.isArray(response.data.permission)) { if (Array.isArray(response.data.permission)) {
permissionIds = response.data.permission.map((perm: any) => { permissionIds = response.data.permission.map((perm: any) => {
// Check if permission is an object or string
if (typeof perm === 'object' && perm !== null) { if (typeof perm === 'object' && perm !== null) {
return perm.id; return perm.id;
} }
@ -582,7 +575,7 @@ const EditDialog = () => {
<div className="w-full"> <div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5"> <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56"> <label className="form-label flex items-center gap-1 max-w-56">
Type Status Transaction Type
<span className="text-red-500"> *</span> <span className="text-red-500"> *</span>
</label> </label>
<div className="grow"> <div className="grow">
@ -598,12 +591,15 @@ const EditDialog = () => {
<SelectContent> <SelectContent>
<SelectItem value="D">Disbursement </SelectItem> <SelectItem value="D">Disbursement </SelectItem>
<SelectItem value="O">Other </SelectItem> <SelectItem value="O">Other </SelectItem>
<SelectItem value="CA">Change Customer to Agent </SelectItem> <SelectItem value="CA">Change Group Emoney Customer to Agent </SelectItem>
<SelectItem value="AC">Change Agent to Customer </SelectItem> <SelectItem value="AC">Change Group Emoney Agent to Customer </SelectItem>
<SelectItem value="PA">Change Group Point Agent to Customer </SelectItem>
<SelectItem value="PC">Change Group Point Customer to Agent</SelectItem>
<SelectItem value="CE">Return Customer Emoney </SelectItem> <SelectItem value="CE">Return Customer Emoney </SelectItem>
<SelectItem value="AD">Return Agent Deposit </SelectItem> <SelectItem value="AD">Return Agent Deposit </SelectItem>
<SelectItem value="AM">Return Agent Merchant </SelectItem> <SelectItem value="AM">Return Agent Merchant </SelectItem>
<SelectItem value="AE">Return Agent Emoney </SelectItem> <SelectItem value="AE">Return Agent Emoney </SelectItem>
<SelectItem value="R">Reward Point </SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
@ -660,7 +656,6 @@ const EditDialog = () => {
</div> </div>
</div> </div>
{/* Group Permission Section - Read Only Display */}
<div className="w-full"> <div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5"> <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56"> <label className="form-label flex items-center gap-1 max-w-56">
@ -671,12 +666,11 @@ const EditDialog = () => {
<Input <Input
type="text" type="text"
placeholder="No groups selected" placeholder="No groups selected"
value={selectedPermissionNames || ""} value={selectedPermissionNames || ''}
readOnly readOnly
className="bg-gray-100 mb-2" className="bg-gray-100 mb-2"
/> />
{/* Groups Selection Area */}
<div className="border rounded-md p-3 max-h-48 overflow-y-auto"> <div className="border rounded-md p-3 max-h-48 overflow-y-auto">
<div className="grid grid-cols-1 md:grid-cols-2 gap-2"> <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
{groups.map((group) => ( {groups.map((group) => (
@ -701,30 +695,20 @@ 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>
</div> </div>
</div> </div>
</form> </form>
{/* Transaction Fee Section */} <ManageTransferFeeContextProvider transactionTypeId={selectedTransferType}>
<ManageTransferFeeContextProvider>
<Container> <Container>
<div className="grid gap-5 lg:gap-7.5 mt-5"> <div className="grid gap-5 lg:gap-7.5 mt-5">
<DataGridInner /> <DataGridInner />
</div> </div>
<AddFeeDialog /> <AddFeeDialog />
<DeleteFeeDialog /> <DeleteFeeDialog />
{/* <EditFeeDialog /> */} <EditFeeDialog />
</Container> </Container>
</ManageTransferFeeContextProvider> </ManageTransferFeeContextProvider>
</div> </div>

View File

@ -147,12 +147,28 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
meta: { headerClassName: 'w-[250px]' } meta: { headerClassName: 'w-[250px]' }
}, },
{ {
accessorFn: (row) => row.type, accessorFn: (row: {type: string }) => {
const mapping: Record<string, string> = {
D: 'Disbursement',
O: 'Other',
CA: 'Change Group Emoney Customer to Agent',
AC:'Change Group Emoney Agent to Customer',
PC: 'Change Group Point Agent to Customer',
PA: 'Change Group Point Customer to Agent',
CE:'Return Customer Emoney',
AD:'Return Agent Deposit',
AM: 'Return Agent Merchant',
AE: 'Return Agent Emoney',
R: 'Reward Point',
};
return mapping[row.type] || 'Unknown';
},
id: 'type', id: 'type',
header: ({ column }) => ( header: ({ column }) => (
<DataGridColumnHeader title="TransactionType Status" column={column} /> <DataGridColumnHeader title="Status Transaction Type" column={column} />
), ),
enableSorting: false, enableSorting: true,
enableHiding: false, enableHiding: false,
meta: { headerClassName: 'w-[250px]' } meta: { headerClassName: 'w-[250px]' }
}, },
@ -223,7 +239,7 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
order_direction: orderDirection, order_direction: orderDirection,
filter: JSON.stringify(filter) filter: JSON.stringify(filter)
}); });
console.log(response?.data.list); // console.log(response?.data.list);
return { data: response?.data.list, totalCount: response?.data.total_count }; return { data: response?.data.list, totalCount: response?.data.total_count };
}; };
@ -250,7 +266,7 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
pagination={{ size: 10 }} pagination={{ size: 10 }}
layout={{ card: true }} layout={{ card: true }}
toolbar={<ListToolbar />} toolbar={<ListToolbar />}
sorting={[{ id: 'created_at', desc: true }]} // Default sorting sorting={[{ id: 'created_at', desc: true }]}
serverSide={true} serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) => onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
doGetTransferTypeListData(pageIndex, pageSize, sorting, columnFilters) doGetTransferTypeListData(pageIndex, pageSize, sorting, columnFilters)