This commit is contained in:
wayanrivan
2025-04-15 10:55:08 +07:00
55 changed files with 4375 additions and 732 deletions

View File

@ -93,6 +93,7 @@ const ManageAccount = () => {
<DataTable
columns={columns}
data={dataAccount}
createData={null}
onUpdate={() => console.log('Callback update')}
onDelete={() => console.log('Callback delete')}
/>

View File

@ -0,0 +1,39 @@
import { Container, DataGridInner } from '@/components';
import { TransactionProvider } from './hooks/TransactionContext';
import { Breadcrumbs, Link } from '@mui/material';
import { Helmet } from 'react-helmet';
import { UploadBatchDialog } from './blocks/UploadBatchDialog';
const HistoryTransactionDisbursement = () => {
return (
<>
<Helmet>
<title>TPAY | History Disbursement</title>
</Helmet>
<TransactionProvider>
<Container className="mb-7">
<h1 className="text-xl font-medium leading-none text-gray-900 mb-5">DISBURSEMENT</h1>
<Breadcrumbs sx={{ mb: 2 }}>
<Link underline="none" color="inherit" href="/">
<span className="text-sm hover:underline">Dashboard</span>
</Link>
<Link underline="none" color="inherit">
<span className="text-sm">Disbursement</span>
</Link>
<Link underline="none" color="inherit">
<span className="text-sm">History Disbursement</span>
</Link>
</Breadcrumbs>
<div className="grid gap-5 lg:gap-7.5">
<DataGridInner />
</div>
<UploadBatchDialog />
</Container>
</TransactionProvider>
</>
);
};
export default HistoryTransactionDisbursement;

View File

@ -0,0 +1,153 @@
// disbursement/history-transaction/blocks/DetailTransaction.tsx
import { KeenIcon } from '@/components';
import { useTransactionContext } from '../hooks/useTransactionContext';
import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config';
import { useEffect, useState } from 'react';
import moment from 'moment';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import TransactionLogViewer from './DetailTransactionLog';
const API_URL = apiConfig.service_disbursement;
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 DetailTransaction = () => {
const { GetData } = useCallApi();
const {
showDetailDialog,
setShowDetailDialog,
selectedTransactionId,
setShowDetailLogDialog,
setDetailLogData
} = useTransactionContext();
const [transactionDetails, setTransactionDetails] = useState<any>(null);
useEffect(() => {
const fetchTransactionDetails = async () => {
if (selectedTransactionId) {
try {
const response = await GetData(`${API_URL}/transaction/history/${selectedTransactionId}`, {
id: selectedTransactionId
});
// console.log(response?.data);
setTransactionDetails(response?.data);
} catch (error) {
console.error('Error fetching transaction', error);
}
}
};
if (showDetailDialog && selectedTransactionId) {
fetchTransactionDetails();
}
}, [showDetailDialog, selectedTransactionId, GetData]);
const [activeTab, setActiveTab] = useState('detail'); // 'detail', 'log', 'approve'
return (
<Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
<DialogContent className="container-fixed max-w-[1024px] flex flex-col p-5 overflow-hidden">
<DialogHeader>
<DialogTitle>Transaction Details</DialogTitle>
</DialogHeader>
<DialogBody>
{/* Tab Content */}
<div className="py-4 overflow-y-auto max-h-[400px]">
<div className="space-y-4">
<div className="border rounded-lg overflow-x-auto">
<table className="min-w-full table-auto">
<thead>
<tr className="bg-gray-100">
<th className="px-4 py-2 text-left text-sm text-gray-500">Username</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Fullname</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Amount</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Status</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Process Date</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Invoice Number</th>
<th className="px-4 py-2 text-left text-sm text-gray-500">Actions</th>
</tr>
</thead>
<tbody>
{transactionDetails?.log && transactionDetails?.log.length > 0 ? (
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">
<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.amount ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">{renderStatusBadge(log.status) ?? '-'}</td>
<td className="px-4 py-2 text-sm text-gray-500">{log.request_date && moment(log.request_date).isValid() ? moment(log.request_date).format('DD/MM/YYYY HH:mm: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>
<td colSpan={8} className="px-4 py-2 text-center text-sm text-gray-500">
No logs available
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default DetailTransaction;

View File

@ -0,0 +1,127 @@
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();
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('DD/MM/YYYY 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('DD/MM/YYYY 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

@ -0,0 +1,70 @@
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { useTransactionContext } from '../hooks/useTransactionContext';
import { Button } from '@/components/ui/button';
import { useCallback, useState, useEffect } from 'react';
import { toast } from 'sonner';
const ListToolbar = () => {
const { table, reload } = useDataGrid();
const { handleUploadBatchDialog } = useTransactionContext();
// Set the initial state for trxDate
const [trxDate, settrxDate] = useState({ from: '', to: '' });
// Function to format date to YYYY-MM-DD
const formatDate = (date: Date): string => {
return date.toISOString().split('T')[0];
};
// useEffect to set the default date values
useEffect(() => {
const today = new Date();
const nextWeek = new Date(today);
nextWeek.setDate(today.getDate() + 7);
settrxDate({
from: formatDate(today), // Set 'from' to today
to: formatDate(nextWeek), // Set 'to' to 7 days later
});
}, []);
const handleFilterData = useCallback(() => {
try {
table.getColumn('transaction_date')?.setFilterValue(trxDate);
} catch (error) {
toast.error('Error applying filter');
console.error('Error applying filter:', error);
}
}, [trxDate, table]);
useEffect(() => {
if (trxDate.from && trxDate.to) {
handleFilterData();
}
}, [trxDate]);
return (
<div className="card-header flex-wrap gap-2 border-b-0 px-5">
<div className="flex flex-wrap gap-2 lg:gap-5 w-full">
<div className="flex justify-between w-full items-center">
<div className="flex gap-3 items-center ml-auto">
<Button
variant="outline"
className="h-7.5 text-[0.8rem]"
onClick={() => handleUploadBatchDialog(true)}
>
Upload Batch
</Button>
<DefaultTooltip title={'Refresh'} placement={'top'}>
<Button variant="outline" className="h-7.5" onClick={() => reload()}>
<KeenIcon icon="arrows-circle" />
</Button>
</DefaultTooltip>
</div>
</div>
</div>
</div>
);
};
export default ListToolbar;

View File

@ -0,0 +1,194 @@
import { MouseEvent, useCallback, useEffect, useRef, useState } from 'react';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { useTransactionContext } from '../hooks';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import clsx from 'clsx';
const API_URL = apiConfig.service_disbursement;
const UploadBatchDialog = () => {
const parentRef = useRef<any | null>(null);
const { showUploadBatchDialog, handleUploadBatchDialog } = useTransactionContext();
const { reload } = useDataGrid();
const { PostData, PostDataFile, GetData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState: {
execution_date: string,
file: File | null;
} = {
execution_date: '',
file: null
}
const [formField, setFormField] = useState(initialState);
const resetForm = () => {
setFormField(initialState);
setAlert({ show: false, message: '' });
};
/* actions */
const doUploadBatch = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData();
formData.append('execution_date', formField.execution_date);
if (formField.file) {
formData.append('file', formField.file);
}
try {
const response = await PostDataFile(`${API_URL}/upload-excel`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
if (response?.status) {
handleUploadBatchDialog(false);
resetForm();
reload();
const createActivity = {
module: 'Disbursement',
description: `Create New Disbursement => ${formField.file?.name}`,
action: 'C'
};
doSaveLogActivity(createActivity);
toast.success('Success Create Disbursement');
} else {
toast.error('Failed to create disbursement');
setAlert({ show: true, message: response?.message ?? 'Failed to create disbursement.' });
}
} catch (error) {
toast.error('Error uploading batch');
setAlert({ show: true, message: 'Something went wrong. Please try again.' });
}
},
[formField]
);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log('Form data before submit:', formField);
if (
formField.execution_date.trim() === '' ||
formField.file === null
) {
setAlert({ show: true, message: 'Please fill in all required fields.' });
return;
}
doUploadBatch(e);
// console.log(formField);
setAlert({ show: false, message: '' });
};
useEffect(() => {
if (showUploadBatchDialog === false) {
resetForm();
}
}, [showUploadBatchDialog]);
return (
<Dialog open={showUploadBatchDialog} onOpenChange={(open) => handleUploadBatchDialog(open)}>
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
<div className="flex items-center justify-between flex-wrap grow">
<div className="flex flex-col justify-center">
<h1 className="text-xl font-semibold leading-none text-gray-900">Upload Batch</h1>
<div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
</div>
<div
className="cursor-pointer hover:opacity-100 opacity-50"
onClick={() => {
handleUploadBatchDialog(false);
resetForm();
}}
>
<KeenIcon icon="cross" className="text-1.5xl" />
</div>
</div>
</DialogHeader>
<DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
<div className="flex flex-col px-0">
{alert.show && (
<Alert variant="danger" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
)}
<form action="" onSubmit={handleSubmit}>
<div className="card-body grid gap-5 p-0">
<div className="w-full">
<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">Execution Date</label>
<Input
className="input"
type="datetime-local"
autoComplete="off"
value={formField.execution_date}
required
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, execution_date: target.value }))
}
/>
</div>
</div>
<div className="w-full">
<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">File</label>
<Input
className="input"
type="file"
autoComplete="off"
required
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, file: target.files?.[0] ?? null }))
}
/>
</div>
</div>
<div className="flex justify-end pt-2.5">
<Button className="btn btn-primary" type="submit">
Save Changes
</Button>
</div>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export { UploadBatchDialog };

View File

@ -0,0 +1,302 @@
import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
import { apiConfig } from '@/config/api.config';
import { ColumnDef } from '@tanstack/react-table';
import axios from 'axios';
import React, { createContext, useCallback, useEffect, useMemo, useState } from 'react';
import { useCallApi } from '@/hooks';
import ListToolbar from '../blocks/ListToolbar';
import { Button } from '@/components/ui/button';
import { useNavigate } from 'react-router';
import moment from 'moment';
import DetailTransaction from '../blocks/DetailTransaction';
import TransactionLogViewer from '../blocks/DetailTransactionLog';
interface TransactionProps {
id: number;
name: string;
}
interface ContextProps {
getTransactionLists: (
limit: number,
page: number,
with_deleted: boolean,
order_field: any,
order_direction: any,
filter: any
) => Promise<{ data: TransactionProps[]; totalCount: number } | undefined>;
showDetailDialog: boolean;
setShowDetailDialog: React.Dispatch<React.SetStateAction<boolean>>;
selectedTransactionId: number | null;
setSelectedTransactionId: React.Dispatch<React.SetStateAction<number | null>>;
showUploadBatchDialog: boolean;
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 = {
getTransactionLists: async () => ({ data: [], totalCount: 0 }),
showDetailDialog: false,
setShowDetailDialog: () => { },
selectedTransactionId: null,
setSelectedTransactionId: () => { },
showUploadBatchDialog: false,
handleUploadBatchDialog: (show: boolean) => {},
showDetailLogDialog: false,
// handleDetailLogDialog: (show: boolean) => {},
setShowDetailLogDialog: () => { },
setDetailLogData: () => {},
detailLogData: null,
};
type StatusCode = 'W' | 'P' | 'F' | 'D' | 'Y';
interface StatusInfo {
label: string;
bg: string;
text: string;
}
const statusMap: Record<StatusCode, StatusInfo> = {
W: { label: 'Waiting', bg: 'bg-yellow-100', text: 'text-yellow-600' },
P: { label: 'Pending', 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' },
Y: { label: 'Active', bg: 'bg-green-100', text: 'text-green-600' },
};
const ManageTransactionContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_disbursement;
const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
const [showDetailDialog, setShowDetailDialog] = useState(false);
const [selectedTransactionId, setSelectedTransactionId] = useState<number | null>(null);
const [showUploadBatchDialog, setShowUploadBatchDialog] = useState(false);
const [showDetailLogDialog, setShowDetailLogDialog] = useState(false);
const [detailLogData, setDetailLogData] = useState<any | null>(null);
const [transaction, setTransaction] = useState<TransactionProps[]>([]);
const { GetData } = useCallApi();
const navigate = useNavigate();
const handleUploadBatchDialog = useCallback((show: boolean) => {
setShowUploadBatchDialog(show);
}, []);
// const handleDetailLogDialog = useCallback((show: boolean) => {
// setShowDetailLogDialog(show);
// }, []);
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorKey: 'file_name',
header: ({ column }) => <DataGridColumnHeader title="File Name" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
},
},
{
accessorFn: (row) => {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(row.amount);
},
id: 'amount',
header: ({ column }) => <DataGridColumnHeader title="Amount" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]',
},
},
{
accessorKey: 'total_record',
header: ({ column }) => <DataGridColumnHeader title="Total Record" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
},
},
{
accessorKey: 'total_success',
header: ({ column }) => <DataGridColumnHeader title="Success Record" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
},
},
{
accessorKey: 'total_fail',
header: ({ column }) => <DataGridColumnHeader title="Fail Record" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
},
},
{
accessorKey: 'total_pending',
header: ({ column }) => <DataGridColumnHeader title="Pending Record" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
},
},
{
accessorFn: (row) => row.status,
id: 'status',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => {
const status = row.original.status 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>
);
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center',
},
},
{
accessorFn: (row) => row.execution_date,
id: 'execution_date',
header: ({ column }) => <DataGridColumnHeader title="Execution Date" column={column} />,
enableSorting: true,
enableHiding: false,
cell: ({ row }) => moment(row.original.execution_date).format('DD/MM/YYYY HH:mm:ss')
},
{
accessorFn: (row) => row.done_date,
id: 'done_date',
header: ({ column }) => <DataGridColumnHeader title="Done Date" column={column} />,
enableSorting: true,
enableHiding: false,
cell: ({ row }) => row.original.done_date ? moment(row.original.done_date).format('DD/MM/YYYY HH:mm:ss') : ''
},
{
id: 'actions',
header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
enableSorting: false,
enableHiding: false,
cell: (data) => {
const row = data.row.original;
return (
<div key={`actions-${row.id}`}>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => {
setSelectedTransactionId(row.id);
setShowDetailDialog(true);
}}
>
<KeenIcon icon="eye" />
</button>
</div>
);
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
}
],
[]);
const getTransactionLists = async (page: number, limit: number, sorting: any, filter: any) => {
try {
let startdate;
let enddate;
let formattedFilter;
if (filter == undefined || filter.length == 0) {
const today = new Date();
const nextWeek = new Date();
nextWeek.setDate(today.getDate() + 7);
startdate = today.toISOString().split('T')[0];
enddate = nextWeek.toISOString().split('T')[0];
} else if (filter != undefined || filter.length != 0) {
startdate = filter[0].value.from;
enddate = filter[0].value.to;
}
formattedFilter = {
};
const response = await GetData(`${API_URL}/transaction/history`, {
limit,
page: page + 1,
with_deleted: false,
order_field: "id",
order_direction: 'DESC',
filter: JSON.stringify(formattedFilter)
});
setTransaction(response?.data.list);
return { data: response?.data.list, totalCount: response?.data.total_count };
} catch (error) {
console.error('Error fetching transaction', error);
}
};
return (
<ManageTransactionContext.Provider
value={{
getTransactionLists,
showDetailDialog,
setShowDetailDialog,
selectedTransactionId,
setSelectedTransactionId,
handleUploadBatchDialog,
showUploadBatchDialog,
// handleDetailLogDialog,
showDetailLogDialog,
setShowDetailLogDialog,
setDetailLogData,
detailLogData
}}
>
<Toaster expand visibleToasts={9} duration={3000} />
<DetailTransaction />
<TransactionLogViewer />
<DataGridProvider
columns={columns}
pagination={{ size: 10 }}
toolbar={<ListToolbar />}
layout={{ card: true }}
sorting={[{ id: 'id', desc: false }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
getTransactionLists(pageIndex, pageSize, sorting, columnFilters)
}
>
{children}
</DataGridProvider>
</ManageTransactionContext.Provider>
);
};
export { TransactionProvider, ManageTransactionContext };
export type { TransactionProps };

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

@ -0,0 +1,2 @@
export * from './TransactionContext';
export * from './useTransactionContext';

View File

@ -0,0 +1,12 @@
import { useContext } from 'react';
import { ManageTransactionContext } from './TransactionContext';
const useTransactionContext = () => {
const context = useContext(ManageTransactionContext);
if (!context) throw new Error('useTransactionContext must be used within AuthProvider');
return context;
};
export { useTransactionContext };

View File

@ -89,6 +89,10 @@ const ManageGroups = () => {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.groupName) return toast.warning(`Group name can not be empty!`)
if (!formData.status) return toast.warning(`Status can not be empty!`)
if (!formData.description) return toast.warning(`Description can not be empty!`)
setIsDialogOpen(false);
setDialogOpen(true);
};
@ -198,7 +202,7 @@ const ManageGroups = () => {
<Dialog open={isDialogOpen} onClose={closeDialog}>
<DialogContent className="w-full">
<div className="flex justify-between">
<DialogTitle>Create New Group</DialogTitle>
<DialogTitle>{dialogType==='create'?"Create New Group":"Update Group"}</DialogTitle>
<Box display="flex" justifyContent="flex-end">
<Button
variant="outlined"

View File

@ -23,6 +23,7 @@ import {
SelectValue
} from '@/components/ui/select';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { NumericFormat } from 'react-number-format';
interface ProviderProps {
provider_id: string;
@ -41,15 +42,29 @@ const EditDialog = () => {
show: false,
message: ''
});
const initialState = {
const initialState: {
name: string;
code: string;
type: string;
description: string;
price_point: string | number | null;
price_cash: string | number | null;
cashback_point: string | number | null;
cashback_cash: string | number | null;
status: string;
provider: string;
process_on_third_party: string;
updated_by: string;
updated_at: string;
} = {
name: '',
code: '',
type: '',
description: '',
price_point: 0,
price_cash: 0,
cashback_point: 0,
cashback_cash: 0,
price_point: null,
price_cash: null,
cashback_point: null,
cashback_cash: null,
status: '',
provider: '',
process_on_third_party: '',
@ -139,11 +154,13 @@ const EditDialog = () => {
formField.type.trim() === '' ||
formField.code.trim() === '' ||
formField.description.trim() === '' ||
formField.price_point === 0 ||
formField.price_cash === 0 ||
formField.cashback_point === 0 ||
formField.cashback_cash === 0 ||
formField.status === '' ||
formField.price_point === null ||
formField.price_cash === null ||
formField.cashback_point === null ||
formField.cashback_cash === null ||
formField.status.trim() === '' ||
formField.provider.trim() === '' ||
formField.process_on_third_party.trim() === '' ||
formField.updated_by.trim() === '' ||
formField.updated_at.trim() === ''
) {
@ -152,7 +169,7 @@ const EditDialog = () => {
}
doUpdateProduct(e);
console.log(formField);
// console.log(formField);
setAlert({ show: false, message: '' });
};
@ -260,16 +277,19 @@ const EditDialog = () => {
<label className="form-label flex items-center gap-1 max-w-56">
Price Point<span className="text-red-500">*</span>
</label>
<Input
<NumericFormat
className="input"
type="number"
min={0}
step={0.01}
value={formField.price_point}
onChange={(e) => {
const value = parseFloat(e.target.value);
setFormField({ ...formField, price_point: isNaN(value) ? 0 : value });
value={formField.price_point ?? ''}
thousandSeparator="."
decimalSeparator=","
allowNegative={false}
onValueChange={(values) => {
setFormField((prev) => ({
...prev,
price_point: values.floatValue !== undefined ? values.floatValue : ''
}));
}}
placeholder="Enter Price Point"
/>
</div>
</div>
@ -279,16 +299,19 @@ const EditDialog = () => {
<label className="form-label flex items-center gap-1 max-w-56">
Price Cash<span className="text-red-500">*</span>
</label>
<Input
<NumericFormat
className="input"
type="number"
min={0}
step={0.01}
value={formField.price_cash}
onChange={(e) => {
const value = parseFloat(e.target.value);
setFormField({ ...formField, price_cash: isNaN(value) ? 0 : value });
value={formField.price_cash ?? ''}
thousandSeparator="."
decimalSeparator=","
allowNegative={false}
onValueChange={(values) => {
setFormField((prev) => ({
...prev,
price_cash: values.floatValue !== undefined ? values.floatValue : ''
}));
}}
placeholder="Enter Price Cash"
/>
</div>
</div>
@ -298,16 +321,19 @@ const EditDialog = () => {
<label className="form-label flex items-center gap-1 max-w-56">
Cashback Point<span className="text-red-500">*</span>
</label>
<Input
<NumericFormat
className="input"
type="number"
min={0}
step={0.01}
value={formField.cashback_point}
onChange={(e) => {
const value = parseFloat(e.target.value);
setFormField({ ...formField, cashback_point: isNaN(value) ? 0 : value });
value={formField.cashback_point ?? ''}
thousandSeparator="."
decimalSeparator=","
allowNegative={false}
onValueChange={(values) => {
setFormField((prev) => ({
...prev,
cashback_point: values.floatValue !== undefined ? values.floatValue : ''
}));
}}
placeholder="Enter Cashback Point"
/>
</div>
</div>
@ -317,16 +343,19 @@ const EditDialog = () => {
<label className="form-label flex items-center gap-1 max-w-56">
Cashback Cash<span className="text-red-500">*</span>
</label>
<Input
<NumericFormat
className="input"
type="number"
min={0}
step={0.01}
value={formField.cashback_cash}
onChange={(e) => {
const value = parseFloat(e.target.value);
setFormField({ ...formField, cashback_cash: isNaN(value) ? 0 : value });
value={formField.cashback_cash ?? ''}
thousandSeparator="."
decimalSeparator=","
allowNegative={false}
onValueChange={(values) => {
setFormField((prev) => ({
...prev,
cashback_cash: values.floatValue !== undefined ? values.floatValue : ''
}));
}}
placeholder="Enter Cashback Cash"
/>
</div>
</div>

View File

@ -72,6 +72,19 @@ const ManageProductsContextProvider = ({ children }: { children: React.ReactNode
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.code,
id: 'code',
header: ({ column }) => <DataGridColumnHeader title="Code" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[100px]'
},
filterFn: (row, id, value) => {
return row.original.products_name.toLowerCase().includes(value.toLowerCase());
}
},
{
accessorFn: (row) => row.name,
id: 'name',
@ -89,12 +102,32 @@ const ManageProductsContextProvider = ({ children }: { children: React.ReactNode
accessorFn: (row) => row.description,
id: 'description',
header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />,
enableSorting: true,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
}
},
{
accessorFn: (row) => row.provider?.name,
id: 'provider_name',
header: ({ column }) => <DataGridColumnHeader title="Provider Name" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
}
},
{
accessorFn: (row) => row.type,
id: 'type',
header: ({ column }) => <DataGridColumnHeader title="Type" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[150px]'
}
},
{
accessorFn: (row) => row.price_point,
id: 'price_point',
@ -115,6 +148,64 @@ const ManageProductsContextProvider = ({ children }: { children: React.ReactNode
headerClassName: 'w-[100px]'
}
},
{
accessorFn: (row) => row.cashback_point,
id: 'cashback_point',
header: ({ column }) => <DataGridColumnHeader title="Cashback Point" column={column} />,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[100px]'
}
},
{
accessorFn: (row) => row.cashback_cash,
id: 'cashback_cash',
header: ({ column }) => <DataGridColumnHeader title="Cashback Cash" column={column} />,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[100px]'
}
},
{
accessorFn: (row) => row.process_on_third_party,
id: 'process_on_third_party',
header: ({ column }) => <DataGridColumnHeader title="Third Party" column={column} />,
cell: ({ row }) => {
const isActive = row.original.process_on_third_party === 'Y';
return <span>{isActive ? 'Yes' : 'No'}</span>;
},
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[100px]'
}
},
{
accessorFn: (row) => row.status,
id: 'status',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
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>
);
},
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[100px]'
}
},
{
id: 'actions',
header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
@ -160,7 +251,7 @@ const ManageProductsContextProvider = ({ children }: { children: React.ReactNode
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
filter: JSON.stringify(filter)
});
// console.log(response?.data);
console.log(response?.data);
setProducts(response?.data.list);
return { data: response?.data.list, totalCount: response?.data.total_count };
} catch (error) {
@ -189,7 +280,7 @@ const ManageProductsContextProvider = ({ children }: { children: React.ReactNode
pagination={{ size: 10 }}
toolbar={<ListToolbar />}
layout={{ card: true }}
sorting={[{ id: 'Product.id', desc: false }]}
sorting={[{ id: 'Product.created_at', desc: true }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
getProductsLists(pageIndex, pageSize, sorting, columnFilters)

View File

@ -23,6 +23,7 @@ import {
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_master_data;
@ -75,6 +76,13 @@ const AddDialog = () => {
resetForm();
reload();
toast.success('Reward Create successfully!');
const createActivity = {
module: 'Manage Reward',
description: `Create New Reward => ${formField.name}`,
action: 'C'
};
doSaveLogActivity(createActivity);
} else {
toast.error('Failed to create reward.');
setAlert({ show: true, message: 'Failed to create reward. Please try again.' });

View File

@ -13,6 +13,7 @@ import {
import { Button } from '@/components/ui/button';
import { DialogDescription } from '@radix-ui/react-dialog';
import { useManageRewardContext } from '../hooks/useManageRewardContext';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_master_data;
@ -33,17 +34,25 @@ const DeleteDialog = () => {
return;
}
// console.log('Ini datanya:', selectedReward);
const response = await DeleteData(`${API_URL}/reward/delete/${selectedReward?.id}/true`, {
id: selectedReward.id
const response = await DeleteData(`${API_URL}/reward/delete/${selectedReward}/true`, {
id: selectedReward
});
// console.log('Response Delete:', response);
if (response?.status) {
setAlert({ show: false, message: '' });
setAlert((prev) => ({ ...prev, show: false, message: '' }));
handleDeleteDialog(false, null);
toast.success('Success Delete Reward');
reload();
const createActivity = {
module: 'Manage Reward',
description: `Delete Reward => ${selectedReward}`,
action: 'D'
};
doSaveLogActivity(createActivity);
} else {
setAlert({ show: true, message: response?.message });
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
toast.error('Failed Delete Reward');
}
}, [selectedReward, DeleteData, handleDeleteDialog, reload]);

View File

@ -23,6 +23,7 @@ import {
SelectValue
} from '@/components/ui/select';
import { useManageRewardContext } from '../hooks/useManageRewardContext';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_master_data;
@ -57,7 +58,9 @@ const EditDialog = () => {
const RewardType = {
'Daily Check in': 'D',
Referal: 'R'
Referal: 'R',
'Level Pro': 'P',
'Level Prioritas': 'L'
} as const;
type RewardTypeValue = (typeof RewardType)[keyof typeof RewardType];
@ -67,13 +70,20 @@ const EditDialog = () => {
e.preventDefault();
// console.log('Ini datanya:', selectedReward);
const response = await PutData(`${API_URL}/reward/update/${selectedReward?.id}`, formField);
const response = await PutData(`${API_URL}/reward/update/${selectedReward}`, formField);
if (response?.status) {
resetForm();
handleEditDialog(false, null);
toast.success('Success Update Reward');
reload();
const editActivity = {
module: 'Manage Reward',
description: `Edit Reward => ${formField.name}`,
action: 'U'
};
doSaveLogActivity(editActivity);
} else {
toast.error('Error Update Reward');
setAlert({ show: true, message: 'Failed to Update Reward. Please try again.' });
@ -118,7 +128,7 @@ const EditDialog = () => {
useEffect(() => {
if (selectedReward) {
doFetchData(selectedReward.id.toString());
doFetchData(selectedReward);
}
}, [selectedReward]);

View File

@ -6,7 +6,7 @@ import React, { createContext, useCallback, useMemo, useState } from 'react';
import { Toaster } from 'sonner';
import ListToolbar from '../blocks/ListToolbar';
interface Reward {
interface SelectedReward {
id: number;
name: string;
type: string;
@ -14,23 +14,14 @@ interface Reward {
status: string;
}
const initialState = {
id: '',
name: '',
type: '',
amount: '',
status: ''
};
interface ContextProps {
showAddDialog: boolean;
handleAddDialog: (show: boolean) => void;
showEditDialog: boolean;
handleEditDialog: (show: boolean, selected_reward: Reward | null) => void;
handleEditDialog: (show: boolean, selected_reward: string | null) => void;
showDeleteDialog: boolean;
handleDeleteDialog: (show: boolean, selected_rewad: Reward | null) => void;
selectedReward: Reward | null;
reward: string | null;
handleDeleteDialog: (show: boolean, selected_reward: string | null) => void;
selectedReward: string | null;
}
const initialProps: ContextProps = {
@ -40,31 +31,29 @@ const initialProps: ContextProps = {
handleEditDialog: () => {},
showDeleteDialog: false,
handleDeleteDialog: () => {},
selectedReward: null,
reward: null
selectedReward: null
};
const ManageRewardContext = createContext<ContextProps>(initialProps);
const API_URL_MASTER_DATA = apiConfig.service_master_data;
const ManageRewardContextProvider = ({ children }: { children: React.ReactNode }) => {
const [reward, setRewards] = useState<string | null>(null);
const [showAddDialog, setShowAddDialog] = useState(false);
const [showEditDialog, setShowEditDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [selectedReward, setSelectedReward] = useState<Reward | null>(null);
const [selectedReward, setSelectedReward] = useState<string | null>(null);
const { GetData } = useCallApi();
const handleAddDialog = useCallback((show: boolean) => {
setShowAddDialog(show);
}, []);
const handleEditDialog = useCallback((show: boolean, selected_reward: Reward | null) => {
const handleEditDialog = useCallback((show: boolean, selected_reward: string | null) => {
setShowEditDialog(show);
setSelectedReward(show ? selected_reward : null);
}, []);
const handleDeleteDialog = useCallback((show: boolean, selected_reward: Reward | null) => {
const handleDeleteDialog = useCallback((show: boolean, selected_reward: string | null) => {
setShowDeleteDialog(show);
setSelectedReward(show ? selected_reward : null);
}, []);
@ -135,13 +124,13 @@ const ManageRewardContextProvider = ({ children }: { children: React.ReactNode }
<>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleEditDialog(true, row)}
onClick={() => handleEditDialog(true, row.id)}
>
<KeenIcon icon="notepad-edit" />
</button>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleDeleteDialog(true, row)}
onClick={() => handleDeleteDialog(true, row.id)}
>
<KeenIcon icon="trash" />
</button>
@ -154,7 +143,7 @@ const ManageRewardContextProvider = ({ children }: { children: React.ReactNode }
}
}
],
[]
[handleEditDialog, handleDeleteDialog]
);
const getRewardList = async (page: number, limit: number, sorting: any, filter: any) => {
@ -162,7 +151,7 @@ const ManageRewardContextProvider = ({ children }: { children: React.ReactNode }
sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
const response = await GetData(`${API_URL_MASTER_DATA}/reward/list`, {
limit,
limit: limit,
page: page + 1,
with_deleted: false,
order_field: sorting[0].id,
@ -171,7 +160,6 @@ const ManageRewardContextProvider = ({ children }: { children: React.ReactNode }
});
// console.log('API Response:', response?.data.list);
// console.log('reward list :', response);
setRewards(response?.data.list);
return { data: response?.data.list, totalCount: response?.data.total_count };
} catch (error) {
console.error('Error fethcing reward', error);
@ -181,7 +169,6 @@ const ManageRewardContextProvider = ({ children }: { children: React.ReactNode }
return (
<ManageRewardContext.Provider
value={{
reward,
showAddDialog,
handleAddDialog,
showEditDialog,
@ -210,4 +197,4 @@ const ManageRewardContextProvider = ({ children }: { children: React.ReactNode }
};
export { ManageRewardContext, ManageRewardContextProvider };
export type { Reward };
export type { SelectedReward };

View File

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

View File

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

View File

@ -0,0 +1,37 @@
import { Container, DataGridInner } from '@/components';
import { ManageKycDeletionContextProvider } from './hooks/ManageKycDeletionContext';
import { Breadcrumbs, Link } from '@mui/material';
import { Helmet } from 'react-helmet';
const ManageKycDeletion = () => {
return (
<>
<Helmet>
<title>TPAY | List Deletion</title>
</Helmet>
<ManageKycDeletionContextProvider>
<Container className="mb-7">
<h1 className="text-xl font-medium leading-none text-gray-900 mb-5">MANAGE KYC DELETION</h1>
<Breadcrumbs sx={{ mb: 2 }}>
<Link underline="none" color="inherit" href="/">
<span className="text-sm hover:underline">Dashboard</span>
</Link>
<Link underline="none" color="inherit">
<span className="text-sm">Member</span>
</Link>
<Link underline="none" color="inherit">
<span className="text-sm">History Disbursement</span>
</Link>
</Breadcrumbs>
<div className="grid gap-5 lg:gap-7.5">
<DataGridInner />
</div>
</Container>
</ManageKycDeletionContextProvider>
</>
);
};
export default ManageKycDeletion;

View File

@ -0,0 +1,98 @@
import {
Dialog,
DialogBody,
DialogContent,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useManageKycDeletionContext } from '../hooks';
import { apiConfig } from '@/config/api.config';
import axios from 'axios';
const API_URL = apiConfig.service_customer;
const DetailDialog = () => {
const { showDetailDialog, setShowDetailDialog, detailKyc, handleApproveReject } = useManageKycDeletionContext();
return (
<Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
<DialogContent className="container-fixed max-w-[1024px] flex flex-col p-5 overflow-hidden">
<DialogHeader>
<DialogTitle>Customer Deletion Details </DialogTitle>
</DialogHeader>
<DialogBody>
{/* Tab Content */}
{detailKyc && detailKyc != null ? (
<div className="flex flex-col">
{generateInput(detailKyc, null, 'Group', 'group_name', 'text', false, true)}
{generateInput(detailKyc, null, 'Username', 'username', 'text', false, true)}
{generateInput(detailKyc, null, 'Full Name', 'fullname', 'text', false, true)}
{generateInput(detailKyc, null, 'Gender', 'customers_gender', 'text', false, true)}
{generateInput(detailKyc, null, 'Date of Birth', 'birthdate', 'date', false, true)}
{generateInput(detailKyc, null, 'Mother Name', 'registered_mother_fullname', 'text', false, true)}
{generateInput(detailKyc, null, 'MSISDN', 'registered_msisdn', 'text', false, true)}
{generateInput(detailKyc, null, 'Reason Deletion', 'reason_deletion', 'text', false, true)}
{generateInput(detailKyc, null, 'Reason Note', 'reason_note', 'text', false, true)}
{generateInput(detailKyc, null, 'Status Approval', 'status_approve', 'text', false, true)}
<div className="flex justify-end gap-2 mt-3">
<Button type="button" variant="outline" onClick={() => setShowDetailDialog(false)}>Cancel</Button>
<Button onClick={()=>handleApproveReject(detailKyc.id, 'N')} variant="destructive" color="warning">Reject</Button>
<Button onClick={()=>handleApproveReject(detailKyc.id, 'Y')} variant="default" color="primary">Approve</Button>
</div>
</div>
) : (<div></div>)}
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default DetailDialog;
function generateInput(formData:any, handleChange:any, label:string, name:string, type: string, required: boolean, disabled: boolean) {
function generateDate(isoString: string) {
return isoString.slice(0, 10); // "2000-01-18"
}
type Code = 'W' | 'Y' | 'N' | 'T' | 'P' | 'D' | 'L';
interface Reason {
label: string;
}
const statusMap: Record<Code, Reason> = {
W: {label: 'Waiting Approval'},
Y: {label: 'Approve'},
N: {label: 'Reject'},
T: {label: 'Tidak lagi menggunakan layanan'},
P: {label: 'Privasi dan keamanan'},
D: {label: 'Akun ganda'},
L: {label: 'Lainnya'}
};
if (name == 'reason_deletion' || name == 'status_approve') {
const status = formData[name] as Code
const fixStatus = statusMap[status] ?? {label: formData[name]}
formData[name] = fixStatus.label
}
return (
<>
<div className="w-full mt-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}<span className="text-red-500">{required?"*":""}</span>
</label>
<Input
className="input"
readOnly={disabled}
required={required}
type={type}
name={name}
value={formData[name]?(type === 'date' ? generateDate(formData[name]) : formData[name]):""}
onChange={handleChange}
/>
</div>
</div>
</>
)
}

View File

@ -0,0 +1,61 @@
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { Button } from '@/components/ui/button';
import { useCallback, useState, useEffect } from 'react';
import { toast } from 'sonner';
const ListToolbar = () => {
const { table, reload } = useDataGrid();
// Set the initial state for trxDate
const [trxDate, settrxDate] = useState({ from: '', to: '' });
// Function to format date to YYYY-MM-DD
const formatDate = (date: Date): string => {
return date.toISOString().split('T')[0];
};
// useEffect to set the default date values
useEffect(() => {
const today = new Date();
const nextWeek = new Date(today);
nextWeek.setDate(today.getDate() + 7);
settrxDate({
from: formatDate(today), // Set 'from' to today
to: formatDate(nextWeek), // Set 'to' to 7 days later
});
}, []);
const handleFilterData = useCallback(() => {
try {
table.getColumn('transaction_date')?.setFilterValue(trxDate);
} catch (error) {
toast.error('Error applying filter');
console.error('Error applying filter:', error);
}
}, [trxDate, table]);
useEffect(() => {
if (trxDate.from && trxDate.to) {
handleFilterData();
}
}, [trxDate]);
return (
<div className="card-header flex-wrap gap-2 border-b-0 px-5">
<div className="flex flex-wrap gap-2 lg:gap-5 w-full">
<div className="flex justify-between w-full items-center">
<div className="flex gap-3 items-center ml-auto">
<DefaultTooltip title={'Refresh'} placement={'top'}>
<Button variant="outline" className="h-7.5" onClick={() => reload()}>
<KeenIcon icon="arrows-circle" />
</Button>
</DefaultTooltip>
</div>
</div>
</div>
</div>
);
};
export default ListToolbar;

View File

@ -0,0 +1,294 @@
import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
import { toast } from 'sonner';
import { apiConfig } from '@/config/api.config';
import { ColumnDef } from '@tanstack/react-table';
import { createContext, useCallback, useMemo, useState } from 'react';
import ListToolbar from '../blocks/ListToolbar';
import { useCallApi } from '@/hooks';
import moment from 'moment';
import DetailDialog from '../blocks/DetailDialog';
interface ManageKycDeletionProps {
id: string;
customers_id: string;
group_id: string;
username: string;
fullname: string;
email: string;
status: string;
created_at: Date;
}
interface ContextProps {
getKycDeletionList: (
limit: number,
page: number,
with_deleted: boolean,
order_field: any,
order_direction: any,
filter: any
) => Promise<{ data: ManageKycDeletionProps[]; totalCount: number } | undefined>;
showDetailDialog: boolean;
setShowDetailDialog: React.Dispatch<React.SetStateAction<boolean>>;
handleDetailDialog: (show: boolean, selected_user: string | null) => void;
showAddDialog: boolean;
handleAddDialog: (show: boolean) => void;
selectedIdCustomer: string | null;
detailKyc: any | null;
setDetailKyc: React.Dispatch<React.SetStateAction<any>>;
handleApproveReject: (customerDeletionId: string, status_approve: string) => {};
}
const initialProps: ContextProps = {
getKycDeletionList: async () => ({ data: [], totalCount: 0 }),
showDetailDialog: false,
handleDetailDialog: () => {},
showAddDialog: false,
handleAddDialog: () => {},
selectedIdCustomer: null,
setShowDetailDialog: () => { },
detailKyc: async () => {},
setDetailKyc: () => { },
handleApproveReject: () => ({customerDeletionId: '0', status_approve: 'Y'}),
};
const ManageKycDeletionContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_customer;
type StatusCode = 'W' | 'Y' | 'N' | 'T';
interface StatusInfo {
label: string;
bg: string;
text: string;
}
const statusMap: Record<StatusCode, StatusInfo> = {
W: { label: 'Waiting Approval', bg: 'bg-yellow-100', text: 'text-yellow-600' },
T: { label: 'No Need', bg: 'bg-blue-100', text: 'text-blue-600' },
N: { label: 'Reject', bg: 'bg-red-100', text: 'text-red-600' },
Y: { label: 'Approve', 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 { reload } = useDataGrid();
const ManageKycDeletionContextProvider = ({ children }: { children: React.ReactNode }) => {
const [showDetailDialog, setShowDetailDialog] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
const [selectedIdCustomer, setSelectedIdCustomer] = useState<string | null>(null);
const [detailKyc, setDetailKyc] = useState<any>();
const [manageKyc, setManageKyc] = useState<ManageKycDeletionProps[]>([]);
const { GetData, PostData } = useCallApi();
const getKycDeletionList = async (page: number, limit: number, sorting: any, filter: any) => {
try {
let startdate;
let enddate;
let formattedFilter;
if (filter == undefined || filter.length == 0) {
const today = new Date();
const nextWeek = new Date();
nextWeek.setDate(today.getDate() + 7);
startdate = today.toISOString().split('T')[0];
enddate = nextWeek.toISOString().split('T')[0];
} else if (filter != undefined || filter.length != 0) {
startdate = filter[0].value.from;
enddate = filter[0].value.to;
}
formattedFilter = {
};
const response = await GetData(`${API_URL}/customer_deletion/list`, {
limit,
page: page + 1,
with_deleted: false,
order_field: "id",
order_direction: 'DESC',
filter: JSON.stringify(formattedFilter)
});
setManageKyc(response?.data.list);
return { data: response?.data.list, totalCount: response?.data.total_count };
} catch (error) {
console.error('Error fetching transaction', error);
}
};
const handleDetailDialog = useCallback(async (show: boolean, selected_id_customer: string | null) => {
if (show == true) {
setSelectedIdCustomer(show ? selected_id_customer : null);
let detailCustomer = await GetData(`${API_URL}/customer_deletion/detail/${selected_id_customer}`, {})
setDetailKyc(detailCustomer?.data)
}
setShowDetailDialog(show);
}, []);
const handleAddDialog = useCallback((show: boolean) => {
setShowAddDialog(show);
}, []);
const handleApproveReject = useCallback(async (customerDeletionId: string, status_approve: string) => {
console.log(customerDeletionId, status_approve)
try {
let approveReject = await PostData(`${API_URL}/customer_deletion/update_status/${customerDeletionId}`, {
status_approve
})
if (approveReject?.status == true) {
toast.success('Success update status approval')
handleDetailDialog(false, null)
} else {
toast.warning(`${approveReject?.message}`)
handleDetailDialog(false, null)
}
} catch (error) {
toast.warning('Failed to approve/reject')
handleDetailDialog(false, null)
}
}, [])
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.id,
id: 'id',
header: ({ column }) => <DataGridColumnHeader title="ID" column={column} />,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[100px]'
},
},
{
accessorFn: (row) => row.created_at,
id: 'created_at',
header: ({ column }) => <DataGridColumnHeader title="Created Date" column={column} />,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
},
cell: ({ row }) => moment(row.original.created_at).format('DD/MM/YYYY HH:mm:ss')
},
{
accessorFn: (row) => row.username,
id: 'username',
header: ({ column }) => <DataGridColumnHeader title="Username" column={column} />,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.fullname,
id: 'fullname',
header: ({ column }) => <DataGridColumnHeader title="Fullname" column={column} />,
enableSorting: true,
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.registered_email,
id: 'email',
header: ({ column }) => <DataGridColumnHeader title="Email" column={column} />,
enableSorting: true,
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.status_approve,
id: 'status_approve',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
enableSorting: true,
meta: {
headerClassName: 'w-[350px]'
},
cell: ({row}) => renderStatusBadge(row.original.status_approve)
},
{
id: 'actions',
enableSorting: false,
header: ({ column }) => <DataGridColumnHeader title="Action" column={column} />,
cell: (data: any) => {
const row = data.row.original;
return (
<>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleDetailDialog(true, row.id)}
>
<KeenIcon icon="notepad-edit" />
</button>
</>
);
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
}
],
[handleDetailDialog]
);
return (
<ManageKycDeletionContext.Provider
value={{
getKycDeletionList,
showDetailDialog,
handleDetailDialog,
showAddDialog,
handleAddDialog,
selectedIdCustomer,
setShowDetailDialog,
setDetailKyc,
detailKyc,
handleApproveReject,
}}
>
<Toaster expand visibleToasts={9} duration={3000} />
<DetailDialog />
<DataGridProvider
columns={columns}
pagination={{ size: 10 }}
toolbar={<ListToolbar />}
layout={{ card: true }}
sorting={[{ id: 'name', desc: false }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
getKycDeletionList(pageIndex, pageSize, sorting, columnFilters)
}
>
{children}
</DataGridProvider>
</ManageKycDeletionContext.Provider>
);
};
export { ManageKycDeletionContextProvider, ManageKycDeletionContext };
export type { ManageKycDeletionProps };

View File

@ -0,0 +1,2 @@
export * from './ManageKycDeletionContext';
export * from './useManageKycDeletionContext';

View File

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

View File

@ -5,12 +5,15 @@ import React, { createContext, useContext, useState, useEffect } from 'react';
import { ManageKycContextProvider } from './hooks';
import { columns, initialMember } from './Columns';
import { useAuthContext } from '@/auth';
import { LoaderTransparant } from '@/components';
import { apiConfig } from '@/config/api.config';
import ConfirmDialog from '@/components/confirm';
import axios from 'axios';
import { toast } from 'sonner';
const BASE_URL = apiConfig.service_customer;
import CustomerDialog from '../manage-members/CustomerDetailModal';
const BASE_URL_MASTER_DATA = apiConfig.service_master_data;
// import CustomerDialog from '../manage-members/CustomerDetailModal';
import DetailMember from '../manage-members/blocks/DetailMember';
import { Breadcrumbs, Link } from '@mui/material';
import { Helmet } from 'react-helmet';
@ -37,6 +40,7 @@ const Kyc = () => {
const [loading, setLoading] = useState(false);
const [members, setMembers] = useState([]);
const [member, setMember] = useState(initialMember);
const [profession, setProfession] = useState([]);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [dialogType, setDialogType] = useState('');
@ -44,12 +48,12 @@ const Kyc = () => {
const { getUser } = useAuthContext();
useEffect(() => {
fetchGroups();
fetchCustomers();
}, []);
async function fetchGroups() {
async function fetchCustomers() {
try {
let groups = await axios.get(`${BASE_URL}/customer/list`, {
let customers = await axios.get(`${BASE_URL}/customer/list`, {
params: {
limit: 10,
page: 1,
@ -60,12 +64,22 @@ const Kyc = () => {
}
});
let temp = 1;
let resMembers = groups.data.data.list.map((el: any) => {
let resMembers = customers.data.data.list.map((el: any) => {
el.no = temp++;
el.name = el.fullname;
return el;
});
setMembers(resMembers);
let getProfession: any = await axios.get(`${BASE_URL_MASTER_DATA}/profession/list`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setProfession(getProfession.data.data.list)
} catch (error: any) {
toast.error(error.message);
console.log(error);
@ -90,13 +104,19 @@ const Kyc = () => {
}
const handleYes = async () => {
setLoading(true)
const userLogin: any = await getUser();
const updateData: any = member;
const customerId = member.id;
const description = member.description;
const destinationGroup = updateData.destinationGroup;
updateData.updated_by = userLogin.data ? userLogin.data.id : '';
let today = new Date();
updateData.updated_at = today.toString();
updateData.municipio = updateData.municipio_id;
updateData.posto_adms = updateData.posto_adms_id;
updateData.suco = updateData.suco_id;
updateData.aldeia = updateData.aldeia_id;
delete updateData.id;
delete updateData.pin;
delete updateData.name;
@ -107,6 +127,14 @@ const Kyc = () => {
delete updateData.destinationGroup;
delete updateData.statusApproval;
delete updateData.description;
delete updateData.municipio_id;
delete updateData.municipio_name;
delete updateData.posto_adms_id;
delete updateData.posto_adms_name;
delete updateData.suco_id;
delete updateData.suco_name;
delete updateData.aldeia_id;
delete updateData.aldeia_name;
delete updateData.group_id;
delete updateData.group_name;
delete updateData.group_description;
@ -124,27 +152,34 @@ const Kyc = () => {
if (updateData[property]) form.append(property, updateData[property]);
}
if (dialogType === 'reject') {
await axios.post(`${BASE_URL}/customer/reject`, { customerid: customerId });
if (destinationGroup === "Premium") await axios.post(`${BASE_URL}/customer/reject`, { customerid: customerId, description: updateData.approval_description_premium });
if (destinationGroup === "Agent") await axios.post(`${BASE_URL}/customer/reject`, { customerid: customerId, description: updateData.approval_description_agent });
}
if (dialogType === 'update') {
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 fetchGroups();
setDialogOpen(false);
setIsDialogOpen(false);
toast.success('Success Update Kyc Member');
toast.success(`Success Update & ${dialogType} Kyc Member`);
} catch (error: any) {
if (error?.response?.data?.error) error.message = error?.response?.data?.error
setDialogOpen(false);
setIsDialogOpen(false);
toast.error(error.message);
} finally {
await fetchCustomers();
setLoading(false)
}
};
function setShowAddDialog(el: any) {
setIsDialogOpen(el)
}
if (loading) return <LoaderTransparant />;
return (
<>
<Helmet>
@ -161,12 +196,23 @@ const Kyc = () => {
onNo={() => setDialogOpen(false)}
/>
{ member.id ? (
<CustomerDialog
open={isDialogOpen}
// <CustomerDialog
// open={isDialogOpen}
// handleClose={closeDialog}
// handleSubmit={handleSubmit}
// initialData={member}
// viewStats={true}
// page={'kyc'}
// />
<DetailMember
showAddDialog={isDialogOpen}
setShowAddDialog={setShowAddDialog}
handleClose={closeDialog}
handleReject={handleReject}
handleSubmit={handleSubmit}
initialData={member}
viewStats={true}
fetchCustomers={fetchCustomers}
profession={profession}
page={'kyc'}
/>
): ""}
@ -189,6 +235,7 @@ const Kyc = () => {
<div className="w-full overflow-x-auto px-4">
<div className="min-w-[800px]">
<DataTable
createData={null}
data={members}
columns={columns}
onUpdate={handleUpdate}

View File

@ -178,5 +178,7 @@ export const initialMember = {
posto_adms: '',
suco: '',
aldeia: '',
profession: ''
profession: '',
approval_description_premium: '',
approval_description_agent: ''
};

View File

@ -295,8 +295,7 @@ const CustomerDialog = ({ open, handleClose, handleSubmit, initialData, viewStat
<TextField disabled={viewOnly} fullWidth margin="dense" label="iBank Number" name="ibank_number" value={formData.ibank_number} onChange={handleChange} />
<Divider className="pt-7"/>
{/* {getAdmAccess(page, formData, handleClose, fetchCustomers)} */}
{
page === 'kyc' ? (
{ page === 'kyc' ? (
<>
<Typography sx={{color:'grey'}}>Approval</Typography>
<TextField fullWidth required={page === 'kyc'?true:false} margin="dense" label="Approval Description" name="description" value={formData.description} onChange={handleChange} />
@ -589,23 +588,21 @@ function showCustomerWallet(customerid: any) {
}}
>
<Box>
<Typography variant="subtitle2" color="text.secondary">
Name
</Typography>
<Typography variant="subtitle2" color="text.secondary">Name</Typography>
<Typography variant="body1" fontWeight={500}>
{item.wallet.name}
</Typography>
</Box>
<Box>
<Typography variant="subtitle2" color="text.secondary">
Description
</Typography>
<Typography variant="subtitle2" color="text.secondary">Description</Typography>
<Typography variant="body1">{item.wallet.description}</Typography>
</Box>
<Box>
<Typography variant="subtitle2" color="text.secondary">
Transaction Today
</Typography>
<Typography variant="subtitle2" color="text.secondary">Balance</Typography>
<Typography variant="body1">{item.amount}</Typography>
</Box>
<Box>
<Typography variant="subtitle2" color="text.secondary">Transaction Today</Typography>
<Typography variant="body1">{item.transaction_number_today}</Typography>
</Box>
</ListItem>

View File

@ -3,20 +3,22 @@ import { apiConfig } from '@/config/api.config';
import { columns, Members, initialMember } from './Columns';
import { useState, useEffect } from 'react';
import axios from 'axios';
import CustomerDialog from './CustomerDetailModal';
// import CustomerDialog from './CustomerDetailModal';
import DetailMember from './blocks/DetailMember';
import ConfirmDialog from '@/components/confirm';
import { useAuthContext } from '@/auth';
import { ScreenLoader } from '@/components';
import { LoaderTransparant } from '@/components';
import { toast } from 'sonner';
import { Breadcrumbs, Link } from '@mui/material';
const BASE_URL_MASTER_DATA = apiConfig.service_master_data;
const BASE_URL = apiConfig.service_customer;
import { Helmet } from 'react-helmet';
const ManageMembers = () => {
const [loading, setLoading] = useState(false);
const [members, setMembers] = useState([]);
const [selectedMember, setSelectedMember] = useState('');
const [member, setMember] = useState(initialMember);
const [profession, setProfession] = useState([]);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [dialogType, setDialogType] = useState('');
@ -34,7 +36,7 @@ const ManageMembers = () => {
async function fetchCustomers() {
try {
let groups = await axios.get(`${BASE_URL}/customer/list`, {
let customers = await axios.get(`${BASE_URL}/customer/list`, {
params: {
limit: 20,
page: 1,
@ -44,12 +46,26 @@ const ManageMembers = () => {
}
});
let temp = 1;
let resMembers = groups.data.data.list.map((el: any) => {
let resMembers = customers.data.data.list.map((el: any) => {
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;
return el;
});
setMembers(resMembers);
let getProfession: any = await axios.get(`${BASE_URL_MASTER_DATA}/profession/list`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setProfession(getProfession.data.data.list)
} catch (error: any) {
toast.error(error.message);
console.log(error);
@ -65,6 +81,7 @@ const ManageMembers = () => {
function createMember() {
setDialogType('create');
setSelectedMember('')
setMember(initialMember);
setIsDialogOpen(true);
}
@ -75,11 +92,16 @@ const ManageMembers = () => {
}
const handleYes = async () => {
setLoading(true)
const userLogin: any = await getUser();
const updateData: any = member;
updateData.updated_by = userLogin.data ? userLogin.data.id : '';
let today = new Date();
updateData.updated_at = today.toString();
updateData.municipio = updateData.municipio_id;
updateData.posto_adms = updateData.posto_adms_id;
updateData.suco = updateData.suco_id;
updateData.aldeia = updateData.aldeia_id;
delete updateData.id;
delete updateData.pin;
delete updateData.name;
@ -90,6 +112,14 @@ const ManageMembers = () => {
delete updateData.destinationGroup;
delete updateData.statusApproval;
delete updateData.description;
delete updateData.municipio_id;
delete updateData.municipio_name;
delete updateData.posto_adms_id;
delete updateData.posto_adms_name;
delete updateData.suco_id;
delete updateData.suco_name;
delete updateData.aldeia_id;
delete updateData.aldeia_name;
delete updateData.group_id;
delete updateData.group_name;
delete updateData.group_description;
@ -107,24 +137,50 @@ const ManageMembers = () => {
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: {
'Content-Type': 'multipart/form-data'
}
});
// if (dialogType === 'create') await axios.post(`${BASE_URL}/customers/create`, member)
await fetchCustomers();
setDialogOpen(false);
setIsDialogOpen(false);
toast.success('Success Update Member');
toast.success('Success Edit 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) {
setDialogOpen(false);
setIsDialogOpen(false);
toast.error(error.message);
} finally {
setDialogOpen(false);
closeDialog();
await fetchCustomers();
setLoading(false)
}
};
if (loading) return <ScreenLoader />;
function setShowAddDialog(el: any) {
setIsDialogOpen(el)
}
if (loading) return <LoaderTransparant />;
return (
<>
@ -141,14 +197,17 @@ const ManageMembers = () => {
onYes={handleYes}
onNo={() => setDialogOpen(false)}
/>
{ member.id ? (
<CustomerDialog
open={isDialogOpen}
handleClose={closeDialog}
handleSubmit={handleSubmit}
initialData={member}
fetchCustomers={fetchCustomers}
/>
{ (member.id!=='' || dialogType==='create') ? (
<DetailMember
showAddDialog={isDialogOpen}
setShowAddDialog={setShowAddDialog}
handleClose={closeDialog}
handleSubmit={handleSubmit}
initialData={member}
fetchCustomers={fetchCustomers}
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>
<div className='grid gap-5 lg:gap-7.5 mx-8 w-auto'>

View File

@ -0,0 +1,241 @@
import { useState, useEffect } from 'react';
import axios from 'axios';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import {
Select,
SelectTrigger,
SelectContent,
SelectItem,
SelectValue
} from '@/components/ui/select';
import { apiConfig } from '@/config/api.config';
import ConfirmDialog from '@/components/confirm';
const BASE_URL_CUSTOMER = apiConfig.service_customer;
// ACCESS ADM
export default function AdmAccess({page,formData,handleClose,fetchCustomers,viewOnly,setViewOnly}: any) {
const [dialogOpen, setDialogOpen] = useState(false);
const [dialogType, setDialogType] = useState('');
const [changeGroup, setChangeGroup] = useState('');
const [changeGroupD, setChangeGroupD] = useState(false);
const [groups, setGroups] = useState([]);
useEffect(() => {
fetchGroups();
}, []);
const fetchGroups = async () => {
try {
let getGroups = await axios.get(`${BASE_URL_CUSTOMER}/groups/list`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC'
}
});
setGroups(getGroups.data.data.list);
} catch (error: any) {
toast.error(error.message);
}
};
const handleYes = async () => {
try {
if (dialogType === 'update status') {
let statusNext = getPinStatus(formData.status).res;
if (statusNext)
await axios.put(`${BASE_URL_CUSTOMER}/customer/statuspin`, {
customerid: formData.id,
status: statusNext
});
else toast.error('Handle Active/Suspend only');
await fetchCustomers();
toast.success('Success Update Status');
}
if (dialogType === 'reset pin') {
if (formData.id)
await axios.post(`${BASE_URL_CUSTOMER}/customer/resetpin`, { customerid: formData.id });
else throw { message: 'data.id not found' };
await fetchCustomers();
toast.success('Pin will send to customer MSISDN');
}
} catch (error: any) {
toast.error(error.message);
} finally {
setDialogOpen(false);
handleClose();
}
};
function buttonStatus(e: any) {
e.preventDefault();
setDialogType('update status');
setDialogOpen(true);
}
function buttonResetPin(e: any) {
e.preventDefault();
setDialogType('reset pin');
setDialogOpen(true);
}
async function buttonChangeGroup() {
try {
let dataObj = {
customerid: formData.id,
destination_group: changeGroup
};
if (formData.group_id === changeGroup)
throw { message: `You update same group as the exist customer group` };
if (dataObj.customerid && dataObj.destination_group) {
await axios.post(`${BASE_URL_CUSTOMER}/customer/change-group`, dataObj);
}
toast.success('Success Change group');
await fetchCustomers();
setChangeGroupD(false);
handleClose();
} catch (error: any) {
console.log(error);
toast.error(error.message);
}
}
function openChangeGroupDialog(e: any) {
e.preventDefault();
setChangeGroup(formData.group_id);
setChangeGroupD(true);
}
function btnConfirmDialog(status: boolean) {
setDialogOpen(status);
}
if (!formData.id) return '';
if (page !== 'kyc') {
return (
<div className="bg-white p-6 rounded-md shadow-md space-y-6">
<h2 className="text-lg font-semibold">Access Administration</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Left Side */}
<div className="space-y-4">
<div className="space-y-2">
<p className="text-sm">Pin Status: {getPinStatus(formData.status).msg}</p>
<Button variant="default" onClick={(e) => buttonStatus(e)}>
{getPinStatus(formData.status).btn}
</Button>
</div>
<div className="space-y-2">
<p className="text-sm">Reset PIN</p>
<Button variant="default" onClick={(e) => buttonResetPin(e)}>
Reset PIN
</Button>
</div>
</div>
{/* Right Side */}
<div className="space-y-4">
<div className="space-y-2">
<p className="text-sm">Change Group</p>
<Button variant="default" onClick={(e) => openChangeGroupDialog(e)}>
Change Group
</Button>
</div>
<div className="space-y-2">
<p className="text-sm">Edit Member</p>
<Button variant="default" onClick={() => setViewOnly(!viewOnly)}>
{viewOnly ? 'Open Edit' : 'Close Edit'}
</Button>
</div>
</div>
</div>
{/* Change Group Dialog */}
<Dialog open={changeGroupD} onOpenChange={setChangeGroupD}>
<DialogContent>
<DialogHeader>
<DialogTitle className="text-orange-500">
Are you sure to change customer Group?
</DialogTitle>
</DialogHeader>
<div className="space-y-3 p-5">
<p className="text-sm font-medium">Destination Group</p>
<Select value={changeGroup} onValueChange={setChangeGroup}>
<SelectTrigger>
<SelectValue placeholder="Select group" />
</SelectTrigger>
<SelectContent>
{groups?.map((el: any) => (
<SelectItem key={el.id} value={el.id}>
{el.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setChangeGroupD(false)}>
No
</Button>
<Button onClick={buttonChangeGroup}>Yes</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<ConfirmDialog
open={dialogOpen}
// onClose={() => btnConfirmDialog(false)}
onOpenChange={() => setDialogOpen(false)}
title="Confirm Action"
content={`Are you sure you want to ${dialogType}?`}
onYes={handleYes}
onNo={() => btnConfirmDialog(false)}
/>
</div>
);
} else {
return '';
}
}
function getPinStatus(status: string) {
if (status === 'Y')
return {
msg: 'Active',
btn: 'Block PIN',
res: 'Block'
};
if (status === 'N')
return {
msg: 'Not Active',
btn: 'Activate PIN',
res: null
};
if (status === 'P')
return {
msg: 'Suspend PIN',
btn: 'Unblock PIN',
res: 'UnBlock'
};
if (status === 'O')
return {
msg: 'Suspend OTP',
btn: 'Unblock OTP',
res: null
};
return {
msg: 'None',
btn: 'No status found',
res: null
};
}

View File

@ -0,0 +1,69 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Card } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';
const BASE_URL_CUSTOMER = apiConfig.service_customer;
export default function CustomerWallet({customerid}: any) {
const [customerWallet, setCustomerWallet] = useState([]);
if (!customerid) return '';
useEffect(() => {
fetchCustomerWallet();
}, []);
async function fetchCustomerWallet() {
try {
let getCustWallet = await axios.get(`${BASE_URL_CUSTOMER}/customer/wallet`, {
params: { customerid: customerid }
});
setCustomerWallet(getCustWallet.data.data.data);
} catch (error: any) {
setCustomerWallet([])
toast.error(`Wallet Not Found`);
}
}
return (
<div className="bg-white p-6 rounded-md shadow-md space-y-4">
<h2 className="text-lg font-semibold">Wallet Member</h2>
<Card className="p-4">
{customerWallet ? (
<div className="overflow-x-auto">
<table className="min-w-full text-sm text-left">
<thead className="text-xs text-gray-500 border-b">
<tr>
<th className="p-2">No</th>
<th className="p-2">Name</th>
<th className="p-2">Balance</th>
<th className="p-2">Month Limit</th>
<th className="p-2">Credit Limit</th>
</tr>
</thead>
<tbody>
{customerWallet.map((item:any, index) => (
<tr
key={item.id}
className={`${
index % 2 === 0 ? "bg-gray-50" : "bg-white"
} hover:bg-gray-100`}
>
<td className="p-2 font-medium">{index+1}</td>
<td className="p-2">{item.wallet}</td>
<td className="p-2">{item.amount}</td>
<td className="p-2">{item.monthly_limit}</td>
<td className="p-2">{item.credit_limit}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p className="text-sm text-muted-foreground">No wallet</p>
)}
</Card>
</div>
);
}

View File

@ -0,0 +1,380 @@
import { apiConfig } from '@/config/api.config';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
import axios from 'axios';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
const BASE_URL_MASTER_DATA = apiConfig.service_master_data;
const URL_NATIONALITY = apiConfig.nationality;
import { initialMember } from "../Columns";
import AdmAccess from './AdmAccess';
import CustomerWallet from './CustomerWallet';
const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialData, handleReject, page, fetchCustomers,
handleClose, profession, dialogType
}: any) => {
const [formData, setFormData] = useState(initialData || initialMember);
const [viewOnly, setViewOnly] = useState(false);
const [nationality, setNationality] = useState([]);
const [municipios, setMunicipios] = useState([]);
const [aldeias, setAldeias] = useState([]);
const [postoAdm, setPostoAdm] = useState([]);
const [sucos, setSucos] = useState<any>([]);
const [genders] = useState([ { name: 'Male',id: 'M' }, { name: 'Female',id: 'F' }])
const [status] = useState([
{ name: 'Active',id: 'Y' }, { name: 'Inactive',id: 'N' }, { name: 'Suspend PIN',id: 'P' }, { name: 'Suspend OTP',id: 'O' }
])
const [banks] = useState([
{ name: 'BNCTL',id: 'BNCTL' }, { name: 'BRI',id: 'BRI' }, { name: 'BNU',id: 'BNU' }, { name: 'Mandiri',id: 'Mandiri' }
])
const parentRef = useRef<any | null>(null);
const [alert, setAlert] = useState({
show: false,
message: ''
});
useEffect(() => {
setFormData(initialData || {});
// fetchMasterData()
}, [initialData]);
const handleChange = async (e: any) => {
const { name, value } = e.target;
if (name === "file_selfie" || name === "photouser" || name === 'file_document_id' || name === "file_document_id_selfie" ||
name === "file_commercial_license") { // FOR FILE ONLY
setFormData({ ...formData, [name]: e.target.files[0] });
} else if(name === "nationality") {
let getNationality = await axios.get(`${URL_NATIONALITY}/${value}`);
setNationality(getNationality.data.data)
setFormData({ ...formData, [name]: value });
} else {
setFormData({ ...formData, [name]: value });
if (name === 'municipio' || name === 'posto_adms' || name === 'suco') await getMasterAfter(name, value);
}
};
async function getMasterAfter(name: string, id: any) {
if (name === 'municipio') {
let getMunicipiosPosto = await axios.get(`${BASE_URL_MASTER_DATA}/municipios/postoadms/${id}`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setPostoAdm(getMunicipiosPosto.data.data)
}
if (name === 'posto_adms') {
let getPostoSuco = await axios.get(`${BASE_URL_MASTER_DATA}/postoadms/sucos/${id}`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setSucos(getPostoSuco.data.data)
}
if (name === 'suco') {
let getSucoAldeias = await axios.get(`${BASE_URL_MASTER_DATA}/sucos/aldeias/${id}`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setAldeias(getSucoAldeias.data.data)
}
}
const handleAddDialog = (show:boolean) => {
if (show) {
setShowAddDialog(show)
} else {
handleClose()
setShowAddDialog(show)
}
}
async function fetchMasterData() {
try {
let getMunicipios = await axios.get(`${BASE_URL_MASTER_DATA}/municipios/list`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setMunicipios(getMunicipios.data.data.list)
let getPostoAdms = await axios.get(`${BASE_URL_MASTER_DATA}/postoadms/list`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setPostoAdm(getPostoAdms.data.data.list)
let getSucos = await axios.get(`${BASE_URL_MASTER_DATA}/sucos/list`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setSucos(getSucos.data.data.list)
let getAldeias = await axios.get(`${BASE_URL_MASTER_DATA}/aldeias/list`, {
params: {
limit: 50,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
}
});
setAldeias(getAldeias.data.data.list)
} catch (error) {
console.log(error);
}
}
function buttonOnSubmit(e:any) {
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 === "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) {
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!`)
handleSubmit(formData);
}
function btnPrevDef(e:any) {
e.preventDefault();
viewOnly ? setViewOnly(false) : setViewOnly(true)
}
const onReject = () => {
if (formData.destinationGroup === "Premium" && !formData.approval_description_premium) return toast.warning(`Approval Premium Description needed!`)
if (formData.destinationGroup === "Agent" && !formData.approval_description_premium) return toast.warning(`Approval Agent Description needed!`)
handleReject(formData);
handleClose();
}
return (
<Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5">
<DialogHeader>
<DialogTitle>Member - {dialogType ==='create' ? "Create" : "View/Edit"}</DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<DialogBody ref={parentRef}>
<div className="flex flex-col">
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
<div className="card-body grid gap-5">
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Group', 'group_name', 'text', true, true): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Username', 'username', 'text', true, dialogType==='create'?false:true): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Full Name', 'fullname', 'text', true, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'Photo', 'photouser'): ''}
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, genders, 'gender', 'Gender', null, true): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Date of Birth', 'date_birth', 'date', true, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Phone Number', 'msisdn', 'text', true, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Email', 'email', 'text', true, viewOnly): ''}
{/* {generateList(formData, handleChange, status, 'status', 'Status', null, true)} */}
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, profession, 'profession', 'Profession', null, false): ''}
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, municipios, 'municipio', 'Municipio', null, false): ''}
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, postoAdm, 'posto_adms', 'Posto', 'posto_adms_id', false): ''}
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, sucos, 'suco', 'Suco', 'sucos_id', false): ''}
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, aldeias, 'aldeia', 'Aldeia', null, false): ''}
{(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">
<label className="form-label flex items-center gap-1 max-w-56"></label>
<ul className="">
{nationality.map((item: any, index) => (
<li key={index} value={item.name}
onClick={() => handleChange({target:{name: 'nationality', value: item.name }})}
className="bg-gray-100 px-4 py-2 rounded hover:bg-gray-200 cursor-default transition">
{item.name}
</li>
))}
{formData.nationality && nationality.length === 0 && (
<li className="text-gray-500">No results found.</li>
)}
</ul>
</div>
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Address', 'address', 'text', true, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Mother Fullname', 'mother_fullname', 'text', true, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Identity Number', 'identity_number', 'text', false, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'License Number', 'license_number', 'text', false, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Merchant Name', 'agent_name', 'text', false, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Merchant Address', 'merchantaddress', 'text', false, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Longitude Merchant', 'longitudemerchant', 'text', false, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Latitude Merchant', 'latitudemerchant', 'text', false, viewOnly): ''}
{(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'File Selfie', 'file_selfie'): ''}
{(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'File Document', 'file_document_id'): ''}
{(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'File Document & Selfie', 'file_document_id_selfie'): ''}
{(formData.id || dialogType === "create") ? generateImage(formData, handleChange, 'File Commercial License', 'file_commercial_license'): ''}
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, banks, 'bank_name', 'Bank Name', null, false): ''}
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Bank Account', 'bank_account', '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 === "Agent")) ? generateInput(formData, handleChange, 'Approval Agent Description', 'approval_description_agent', 'text', false, viewOnly): ''}
{(formData.id && page!=='kyc') ? (
<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">
<Button onClick={(e:any) => btnPrevDef(e)} color="secondary">{ viewOnly ? (`Open Edit`) : (`Close Edit`) }</Button>
<Button type="button" variant="outline" onClick={() => handleAddDialog(false)}>Cancel</Button>
{/* <Button onClick={(e) => buttonOnSubmit(e, formData)} variant="default">Save Changes</Button> */}
{
formData.isneedapproval == 1 && page === 'kyc' ? (
<Button onClick={onReject} variant="destructive" color="warning">Reject</Button>
) : ('')
}
<Button onClick={(e) => buttonOnSubmit(e)} color="primary" variant="default">
{ formData.id ? (formData.isneedapproval == 1 && page === 'kyc' ? (`Edit & Approve`) : (`Edit`)) : ("Create") }
</Button>
</div>
</div>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default DetailMember;
{/* <span className="text-red-500 text-[10px] lowercase align-middle ml-1">(agent)</span> */}
function generateInput(formData:any, handleChange:any, label:string, name:string, type: string, required: boolean, disabled: boolean) {
function generateDate(isoString: string) {
return isoString.slice(0, 10); // "2000-01-18"
}
return (
<>
<div className="w-full">
<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}<span className="text-red-500">{required?"*":""}</span>
</label>
<Input
className="input"
readOnly={disabled}
required={required}
type={type}
name={name}
value={formData[name]?(type === 'date' ? generateDate(formData[name]) : formData[name]):""}
onChange={handleChange}
/>
</div>
</div>
</>
)
}
// ON DEV (DI SELECT MASI HILANG)
function generateList(formData:any, handleChange: any, list:any, name:string, label: string, difId: any, required: boolean) {
return (
<>
<div className="w-full">
<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}
<span className="text-red-600">{required?"*":""}</span></label>
<Select required={required} value={formData[name]} onValueChange={(e) => (handleChange({ target : { name, value: e }}))}>
<SelectTrigger>
<SelectValue placeholder={`Select ${label}`} />
</SelectTrigger>
<SelectContent>
{list.map((el: any, idx: any) => (
<SelectItem key={idx} value={el.id}>{el.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</>
)
}
// ON DEV (UPDATENYA)
function generateImage(formData:any, handleChange:any, label:string, name:string) {
const imagePreview = (file:any) => {
if (file && file.type && file.type.startsWith('image/')) {
const previewURL = URL.createObjectURL(file);
return previewURL
}
return file
};
return (
<>
<div className="flex items-center justify-between w-full max-w-xl">
<label className="form-label flex items-center gap-1 max-w-56">
{label}<span className="text-red-500"></span>
</label>
<div className="flex items-center space-x-4 w-3/4 justify-end">
{ formData[name] ? (
<div className="border-2 border-dashed border-red-300 rounded-md p-2">
<img width={300} height={250} srcSet={imagePreview(formData[name])} src={imagePreview(formData[name])} alt={name} style={{borderRadius: 10}}/>
{/* <img width={300} height={250} srcSet={formData[name]} src={formData[name]} alt={name} style={{borderRadius: 10}}/> */}
</div>
) : (<span>No Data</span>)}
<label className="bg-red-600 text-white px-2 py-1 rounded-full flex items-center cursor-pointer hover:bg-red-800">
<span style={{fontSize: 13}}>Upload</span>
<input type="file" className="hidden" name={name} onChange={handleChange} accept="image/*" />
</label>
</div>
</div>
</>
)
}

View File

@ -1,10 +1,22 @@
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { useManageMenusContext } from '../hooks/useManageMenusContext';
import { Button } from '@/components/ui/button';
import React, { useState } from 'react';
const ListToolbar = () => {
const { table, reload } = useDataGrid();
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 (
<div className="card-header flex-wrap gap-2 border-b-0 px-5">
@ -16,10 +28,16 @@ const ListToolbar = () => {
<input
type="text"
placeholder="Search Menu"
value={(table.getColumn('name')?.getFilterValue() as string) ?? ''}
onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)}
value={searchValue}
onChange={(event) => setSearchValue(event.target.value)}
onKeyDown={handleKeyDown}
/>
</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'}>
<Button
variant="outline"

View File

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

View File

@ -15,6 +15,16 @@ import {
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList
} from '@/components/ui/command';
import { ChevronDown } from 'lucide-react';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useUserContext } from '../hooks';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
@ -25,6 +35,14 @@ import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import clsx from 'clsx';
export interface CustomerProps {
id: string;
msisdn: string;
email: string;
fullname: string;
username: string;
}
interface RoleListProps {
id: string;
name: string;
@ -42,7 +60,9 @@ interface CreateUserParams {
status: string;
}
const API_URL_CUSTOMER = apiConfig.service_customer;
const API_URL = apiConfig.service_dashboard;
type PasswordType = 'password' | 'retype_password';
const AddDialog = () => {
@ -62,7 +82,8 @@ const AddDialog = () => {
retype_password: '',
name: '',
id_role: '',
status: ''
status: '',
customerid: ''
};
const [formField, setFormField] = useState(initialState);
const [showPassword, setShowPassword] = useState({
@ -71,6 +92,8 @@ const AddDialog = () => {
});
const [messagePassword, setMessagePassword] = useState(true);
const [open, setOpen] = useState(false);
const [customers, setCustomers] = useState<CustomerProps[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [passwordErrors, setPasswordErrors] = useState<string[]>([]);
@ -155,6 +178,23 @@ const AddDialog = () => {
// console.log('ini data user_role:', response?.data);
}, []);
const getCustomerList = async (sorting: any) => {
try {
sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
limit: 100,
page: 1,
with_deleted: false,
order_field: sorting[0].id,
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
});
setCustomers(response?.data.list);
} catch (error) {
console.error('Error fetching customer', error);
}
};
useEffect(() => {
fetchRoles();
}, [fetchRoles]);
@ -162,7 +202,7 @@ const AddDialog = () => {
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log('Form data before submit:', formField);
// console.log('Form data before submit:', formField);
if (
formField.email.trim() === '' ||
@ -171,7 +211,8 @@ const AddDialog = () => {
formField.retype_password.trim() === '' ||
formField.name.trim() === '' ||
formField.id_role.trim() === '' ||
formField.status.trim() === ''
formField.status.trim() === '' ||
formField.customerid.trim() === ''
) {
setAlert({ show: true, message: 'Please fill name field.' });
return;
@ -196,6 +237,10 @@ const AddDialog = () => {
}
}, [showAddDialog]);
useEffect(() => {
getCustomerList([{ id: 'id', desc: false }]);
}, []);
const togglePassword = useCallback((event: MouseEvent<HTMLButtonElement>, key: string) => {
event.preventDefault();
setShowPassword((prev) => ({ ...prev, [key]: !prev[key as PasswordType] }));
@ -262,6 +307,58 @@ const AddDialog = () => {
</div>
</div>
<div className="w-full">
<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">Customer</label>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
className="input col-span-5 text-left flex justify-between"
style={{ color: 'inherit' }}
>
<span>
{customers.find((customer) => customer.id === formField.customerid)
?.username || 'Select Customer'}
</span>
<ChevronDown className="w-4 h-4 opacity-70" />
</button>
</PopoverTrigger>
<PopoverContent className="w-[400px] p-0">
<Command>
<CommandInput placeholder="Search Customer..." />
<CommandList
className="max-h-[300px] overflow-y-auto"
style={{ touchAction: 'pan-y' }}
onWheel={(e) => {
e.currentTarget.scrollTop += e.deltaY;
}}
>
<CommandEmpty>No Customer found.</CommandEmpty>
<CommandGroup>
{customers.map((customer) => (
<CommandItem
key={customer.id}
value={customer.username}
onSelect={() => {
setFormField({
...formField,
customerid: customer.id
});
setOpen(false);
}}
>
{customer.username}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
</div>
<div className="w-full">
<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">Email</label>

View File

@ -34,6 +34,7 @@ const DeleteDialog = () => {
const response = await DeleteData(`${API_URL}/user/delete/${selectedUser}/${enforce}`, {
id: selectedUser
});
// console.log('Delete Response User:', response);
if (response?.status) {
setAlert((prev) => ({ ...prev, show: false, message: '' }));
handleDeleteDialog(false, null);

View File

@ -6,7 +6,15 @@ import {
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
Dialog,
DialogBody,
@ -15,7 +23,9 @@ import {
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { CustomerProps } from './AddDialog';
import { useUserContext } from '../hooks';
import { ChevronDown } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
@ -30,6 +40,7 @@ interface RoleListProps {
status: string;
}
const API_URL_CUSTOMER = apiConfig.service_customer;
const API_URL = apiConfig.service_dashboard;
const initialState = {
@ -37,7 +48,8 @@ const initialState = {
username: '',
email: '',
id_role: '',
status: ''
status: '',
customerid: ''
};
const EditDialog = () => {
@ -45,7 +57,9 @@ const EditDialog = () => {
const { showEditDialog, selectedUser, handleEditDialog } = useUserContext();
const { reload } = useDataGrid();
const { GetData, PutData } = useCallApi();
const [open, setOpen] = useState(false);
const [roles, setRoles] = useState<RoleListProps[]>([]);
const [customers, setCustomers] = useState<CustomerProps[]>([]);
const [alert, setAlert] = useState({
show: false,
message: ''
@ -109,9 +123,27 @@ const EditDialog = () => {
}
}, []);
const getCustomerList = async (sorting: any) => {
try {
sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
limit: 100,
page: 1,
with_deleted: false,
order_field: sorting[0].id,
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
});
// console.log('CUSTOMER: ', response?.data);
setCustomers(response?.data.list);
} catch (error) {
console.error('Error fetching customer', error);
}
};
const doFetchUserData = useCallback(async (id: string) => {
const response = await GetData(`${API_URL}/user/detail/${id}`, { id });
// console.log('User detail response:', response);
// console.log('User detail response:', response?.data);
if (response?.status) {
setFormField((prev) => ({
@ -120,8 +152,10 @@ const EditDialog = () => {
username: response.data.username,
email: response.data.email,
id_role: response.data.idRole,
status: response.data.status
status: response.data.status,
customerid: response.data.customer.id
}));
// console.log('Customer ID from API:', response?.data.customerid);
} else {
setFormField((prev) => ({
...prev,
@ -129,18 +163,13 @@ const EditDialog = () => {
username: '',
email: '',
id_role: '0',
status: ''
status: '',
customerid: ''
}));
}
// console.log('Fetched ID Role:', response?.data.id_role);
}, []);
useEffect(() => {
if (selectedUser) {
doFetchUserData(selectedUser);
}
}, [selectedUser]);
useEffect(() => {
if (showEditDialog === false) {
resetForm();
@ -149,6 +178,7 @@ const EditDialog = () => {
useEffect(() => {
const fetchAllData = async () => {
await getCustomerList([{ id: 'id', desc: false }]);
await doFetchUserRole([{ id: 'name', desc: false }]);
if (selectedUser) {
await doFetchUserData(selectedUser);
@ -220,6 +250,58 @@ const EditDialog = () => {
</div>
</div>
<div className="w-full">
<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">Customer</label>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
className="input col-span-5 text-left flex justify-between"
style={{ color: 'inherit' }}
>
<span>
{customers.find((customer) => customer.id === formField.customerid)
?.username || 'Select Customer'}
</span>
<ChevronDown className="w-4 h-4 opacity-70" />
</button>
</PopoverTrigger>
<PopoverContent className="w-[400px] p-0">
<Command>
<CommandInput placeholder="Search Customer..." />
<CommandList
className="max-h-[300px] overflow-y-auto"
style={{ touchAction: 'pan-y' }}
onWheel={(e) => {
e.currentTarget.scrollTop += e.deltaY;
}}
>
<CommandEmpty>No Customer found.</CommandEmpty>
<CommandGroup>
{customers.map((customer) => (
<CommandItem
key={customer.id}
value={customer.username}
onSelect={() => {
setFormField({
...formField,
customerid: customer.id
});
setOpen(false);
}}
>
{customer.username}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
</div>
<div className="w-full">
<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">Email</label>

View File

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

View File

@ -27,6 +27,7 @@ interface SelectedUser {
role: string;
new_password: string;
check_new_password: string;
customer: string;
}
const initialProps: ContextProps = {
@ -77,17 +78,27 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.username,
accessorKey: 'username',
id: 'username',
header: ({ column }) => <DataGridColumnHeader title="Username" column={column} />,
enableSorting: true,
enableHiding: false
},
{
accessorFn: (row) => row.customer?.username,
id: 'customer',
header: ({ column }) => <DataGridColumnHeader title="Customer" column={column} />,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[300px]'
}
},
{
accessorFn: (row) => row.email,
id: 'email',
header: ({ column }) => <DataGridColumnHeader title="Email" column={column} />,
enableSorting: false,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[350px]'
@ -97,17 +108,17 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
accessorFn: (row) => row.name,
id: 'name',
header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
enableSorting: false,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[350px]'
headerClassName: 'w-[250px]'
}
},
{
accessorFn: (row) => row.role.name,
id: 'role_name',
header: ({ column }) => <DataGridColumnHeader title="Role Name" column={column} />,
enableSorting: false,
enableSorting: true,
enableHiding: false,
cell: (data: any) => {
const { role } = data.row.original;
@ -179,17 +190,30 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
);
const doGetListData = async (page: number, limit: number, sorting: any, filter: any) => {
sorting = sorting.length == 0 ? [{ id: 'username', desc: false }] : sorting;
filter = filter.length == 0 ? {} : { any: filter[0].value.toLowerCase() };
const USER_TABLE_COLUMNS = ['username', 'email', 'name', 'status'];
// Tambahkan prefix ke field dari tabel Users
const mappedSorting = sorting.map((sort: any) => ({
...sort,
id: USER_TABLE_COLUMNS.includes(sort.id) ? `Users.${sort.id}` : sort.id
}));
const orderField = mappedSorting[0]?.id ?? 'Users.username';
const orderDirection = mappedSorting[0]?.desc === false ? 'DESC' : 'ASC';
filter =
filter.length == 0
? {}
: { 'Users.username': { like: `%${filter[0].value?.toLowerCase()}%` } };
const response = await GetData(`${API_URL}/user/list`, {
limit: limit,
page: page + 1,
with_deleted: false,
order_field: sorting[0].id,
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
order_field: orderField,
order_direction: orderDirection,
filter: JSON.stringify(filter)
});
console.log('response api:', response);
// console.log('response api:', response);
return { data: response?.data.list, totalCount: response?.data.total_count };
};
@ -215,7 +239,7 @@ const ManageUserContextProvider = ({ children }: { children: React.ReactNode })
pagination={{ size: 10 }}
toolbar={<ListToolBar />}
layout={{ card: true }}
sorting={[{ id: 'username', desc: false }]}
sorting={[{ id: 'Users.username', desc: false }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
doGetListData(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 { NumericFormat } from 'react-number-format';
import {
@ -40,31 +40,56 @@ import {
TableHeader,
TableRow
} 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 { get } from 'http';
interface TransactionTypeProps {
id: string;
name: string;
}
interface WalletProps {
id: string;
name: string;
}
interface CustomerProps {
id: string;
username: string;
msisdn: string;
}
const API_URL = apiConfig.service_transaction;
const API_URL_MASTER_DATA = apiConfig.service_master_data;
const API_URL_CUSTOMER = apiConfig.service_customer;
const AddFeeDialog = () => {
const parentRef = useRef<any | null>(null);
const { reload } = useDataGrid();
const { PostData, PutData, GetData } = useCallApi();
const { showAddFeeDialog, handleAddFeeDialog, handleEditFeeDialog, selectedTransferFee } =
useManageTransferFeeContext();
const {
showAddFeeDialog,
handleAddFeeDialog,
handleEditFeeDialog,
selectedTransferFee,
transactionTypeId
} = useManageTransferFeeContext();
const [customerSearchTerm, setCustomerSearchTerm] = useState('');
const [open, setOpen] = useState(false);
const [alert, setAlert] = useState({
show: false,
message: ''
});
const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]);
const [wallets, setWallets] = useState<WalletProps[]>([]);
const [customers, setCustomers] = useState<CustomerProps[]>([]);
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 = {
name: '',
description: '',
@ -75,58 +100,85 @@ const AddFeeDialog = () => {
period_end: '',
deduct_amount: 0,
deduct_percentage: 0,
fee_amount: 0,
priority: '',
status: '',
status_include: '',
created_by: '',
created_at: ''
created_at: '',
deduct_from: '',
deduct_from_account: '',
credit_to: '',
credit_destination: '00000000-0000-0000-0000-000000000000',
credit_destination_account: ''
};
const [formField, setFormField] = useState(initialState);
const resetForm = () => {
setFormField(initialState);
setTransactionTypeName('');
};
const [isSubmitting, setIsSubmitting] = useState(false);
const [showTransactionFeeDialog, setShowTransactionFeeDialog] = useState(false);
const parsedUser = getAuth()?.user;
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
// setIsSubmitting(true);
const payload = {
name: formField.name,
description: formField.description,
period_start: formField.period_start,
period_end: formField.period_end,
minimum_amount: formField.minimum_amount,
maximum_amount: formField.maximum_amount,
deduct_amount: formField.deduct_amount,
deduct_percentage: formField.deduct_percentage,
transaction_type: formField.transaction_type,
status: formField.status,
status_include: formField.status_include,
priority: formField.priority
};
};
useEffect(() => {
if (showAddFeeDialog && transactionTypeId) {
setIsLoadingTransactionType(true);
setFormField((prev) => ({
...prev,
transaction_type: transactionTypeId
}));
const getTransactionTypeDetails = async () => {
try {
const response = await GetData(
`${API_URL}/transactiontype/getdata/${transactionTypeId}`,
{}
);
if (response?.status && response?.data) {
setTransactionTypeName(response.data.name);
}
} catch (error) {
console.error('Error fetching transaction type details', error);
} finally {
setIsLoadingTransactionType(false);
}
};
getTransactionTypeDetails();
}
}, [showAddFeeDialog, transactionTypeId, GetData]);
useEffect(() => {
if (!showAddFeeDialog) {
setCustomerSearchTerm('');
setOpen(false);
}
}, [showAddFeeDialog]);
useEffect(() => {
const created_time = new Date();
const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
if (showAddFeeDialog) {
setFormField({
...formField,
setFormField((prev) => ({
...prev,
created_by: parsedUser?.username,
created_at: formattedTime
});
}));
}
}, [showAddFeeDialog]);
}, [showAddFeeDialog, parsedUser?.username]);
useEffect(() => {
if (!showAddFeeDialog) return;
const getTransactionTypeList = async (sorting: any) => {
setIsLoadingTransactionType(true);
try {
sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
const response = await GetData(`${API_URL}/transactiontype/list`, {
@ -138,40 +190,182 @@ const AddFeeDialog = () => {
});
setTransactionTypes(response?.data.list || []);
} catch (error) {
console.error('Error fetching customer', error);
console.error('Error fetching transaction types', error);
} finally {
setIsLoadingTransactionType(false);
}
};
getTransactionTypeList([{ id: 'id', desc: false }]);
}, [showAddFeeDialog]);
}, [showAddFeeDialog, GetData]);
const fetchWallets = useCallback(async () => {
setIsLoadingWallets(true);
const params = {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'Wallets.name',
order_direction: 'ASC'
};
try {
const response = await GetData(`${API_URL_MASTER_DATA}/wallet/list`, params);
if (response?.status && response?.data) {
setWallets(response.data.list);
} else {
setWallets([]);
}
} catch (error) {
console.error('Error fetching wallets', error);
setWallets([]);
} finally {
setIsLoadingWallets(false);
}
}, [GetData]);
useEffect(() => {
if (!showAddFeeDialog) return;
fetchWallets();
}, [showAddFeeDialog, fetchWallets]);
useEffect(() => {
if (!showAddFeeDialog) return;
const getCustomerList = async (sorting: any) => {
setIsLoadingCustomers(true);
try {
sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
limit: 100,
page: 1,
with_deleted: false,
order_field: sorting[0].id,
order_direction: sorting[0].desc ? 'DESC' : 'ASC'
});
const customerList = response?.data.list || [];
setCustomers(customerList);
if (customerList.length > 0) {
setDefaultCustomer(customerList[0].id);
}
} catch (error) {
console.error('Error fetching customers', error);
setCustomers([]);
} finally {
setIsLoadingCustomers(false);
}
};
getCustomerList([{ id: 'id', desc: false }]);
}, [showAddFeeDialog, GetData]);
const doCreateTransferType = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
for (const key in formField) {
if (
formField[key as keyof typeof formField] === '' ) {
setAlert({ show: true, message: 'All fields must be filled out' });
setIsSubmitting(true);
const requiredFields = [
'name',
'description',
'period_start',
'period_end',
'transaction_type',
'status',
'status_include',
'priority',
'deduct_from',
'deduct_from_account',
'credit_to',
'credit_destination_account'
];
for (const field of requiredFields) {
if (formField[field as keyof typeof formField] === '') {
setAlert({
show: true,
message: `All required fields must be filled out. Missing: ${field.replace(/_/g, ' ')}`
});
setIsSubmitting(false);
return;
}
}
if (formField.credit_to === 'I' && !formField.credit_destination) {
setAlert({
show: true,
message: 'Credit destination is required when Input Customer is selected'
});
setIsSubmitting(false);
return;
}
setAlert({ show: false, message: '' });
const response = await PostData(`${API_URL}/transactionfees/create`, {
...formField
});
if (response?.status) {
// toast.success('Success Create Transfer Fee');
reload();
resetForm();
handleAddFeeDialog(false);
} else {
setAlert({ show: true, message: response?.message || 'Failed to create transfer fee' });
const payload = { ...formField };
if (formField.credit_to !== 'I') {
payload.credit_destination = '00000000-0000-0000-0000-000000000000';
}
try {
const response = await PostData(`${API_URL}/transactionfees/create`, payload);
if (response?.status) {
toast.success('Successfully created transfer fee');
reload();
resetForm();
handleAddFeeDialog(false);
const createActivity = {
module: 'Manage Transfer Fee',
description: `Create Transfer Fee => ${formField.name}`,
action: 'C'
};
doSaveLogActivity(createActivity);
} else {
setAlert({ show: true, message: response?.message || 'Failed to create transfer fee' });
}
} catch (error) {
console.error('Error creating transfer fee', error);
setAlert({ show: true, message: 'An error occurred while creating the transfer fee' });
} finally {
setIsSubmitting(false);
}
},
[formField]
[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 (
<Dialog open={showAddFeeDialog} onOpenChange={(open) => handleAddFeeDialog(open)}>
<DialogContent className="container-fixed max-w-[1080px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
@ -194,12 +388,51 @@ const AddFeeDialog = () => {
</div>
</DialogHeader>
<DialogBody className="max-h-[1080px] overflow-y-auto">
{alert.show && <Alert variant="danger">{alert.message}</Alert>}
{alert.show && (
<div className="sticky top-0 z-10 bg-white p-3">
<Alert variant="danger" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
</div>
)}
<form action="" onSubmit={doCreateTransferType}>
<div className="card flex flex-col gap-5">
<div className="card-body grid gap-5 p-0">
<div className="w-full">
<label className="form-label">Transfer Free Name <span className="text-red-500">*</span></label>
<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">
<label className="form-label">
Transfer Free Name <span className="text-red-500">*</span>
</label>
<Input
className="input"
type="text"
@ -211,7 +444,9 @@ const AddFeeDialog = () => {
/>
</div>
<div className="w-full">
<label className="form-label">Description <span className="text-red-500">*</span></label>
<label className="form-label">
Description <span className="text-red-500">*</span>
</label>
<Input
className="input"
type="text"
@ -236,7 +471,7 @@ const AddFeeDialog = () => {
minimum_amount: values.floatValue || 0
}));
}}
placeholder="Enter Max Transaction Per Day"
placeholder="Enter Minimum Amount"
/>
</div>
<div className="w-full">
@ -253,11 +488,13 @@ const AddFeeDialog = () => {
maximum_amount: values.floatValue || 0
}));
}}
placeholder="Enter Max Transaction Per Day"
placeholder="Enter Maximum Amount"
/>
</div>
<div className="w-full">
<label className="form-label">Period Start <span className="text-red-500">*</span></label>
<label className="form-label">
Period Start <span className="text-red-500">*</span>
</label>
<Input
className="input"
type="date"
@ -269,7 +506,9 @@ const AddFeeDialog = () => {
/>
</div>
<div className="w-full">
<label className="form-label">Period End <span className="text-red-500">*</span></label>
<label className="form-label">
Period End <span className="text-red-500">*</span>
</label>
<Input
className="input"
type="date"
@ -294,7 +533,7 @@ const AddFeeDialog = () => {
deduct_amount: values.floatValue || 0
}));
}}
placeholder="Enter Max Transaction Per Day"
placeholder="Enter Deduct Amount"
/>
</div>
<div className="w-full">
@ -311,31 +550,169 @@ const AddFeeDialog = () => {
deduct_percentage: values.floatValue || 0
}));
}}
placeholder="Enter Max Transaction Per Day"
placeholder="Enter Deduct Percentage"
/>
</div>
<div className="w-full">
<label className="form-label">Transacsion Type ID <span className="text-red-500">*</span></label>
<label className="form-label">Fee Amount</label>
<NumericFormat
className="input"
value={formField.fee_amount}
thousandSeparator="."
decimalSeparator=","
allowNegative={false}
onValueChange={(values) => {
setFormField((prev) => ({
...prev,
fee_amount: values.floatValue || 0
}));
}}
placeholder="Enter Fee Amount"
/>
</div>
<div className="w-full">
<label className="form-label">
Deduct From <span className="text-red-500">*</span>
</label>
<Select
value={formField.transaction_type}
onValueChange={(transaction_type) =>
setFormField((prev) => ({ ...prev, transaction_type }))
}
value={formField.deduct_from}
onValueChange={(value) => setFormField({ ...formField, deduct_from: value })}
>
<SelectTrigger>
<SelectValue placeholder="Select Wallet" />
<SelectValue placeholder="Select Deduct From" />
</SelectTrigger>
<SelectContent>
{transactionTypes.map((transactiontype, idx) => (
<SelectItem value={transactiontype.id} key={transactiontype.id}>
{transactiontype.name}
</SelectItem>
))}
<SelectItem value="D">Destination Member</SelectItem>
<SelectItem value="S">Source Member</SelectItem>
</SelectContent>
</Select>
</div>
<div className="w-full">
<label className="form-label">Status <span className="text-red-500">*</span></label>
<label className="form-label">
Deduct From Destination <span className="text-red-500">*</span>
</label>
{renderSelectWithLoading(
formField.deduct_from_account,
(value) => setFormField({ ...formField, deduct_from_account: value }),
wallets,
'Select Wallet',
isLoadingWallets
)}
</div>
<div className="w-full">
<label className="form-label">
Credit To <span className="text-red-500">*</span>
</label>
<Select
value={formField.credit_to}
onValueChange={(value) =>
setFormField({
...formField,
credit_to: value,
credit_destination:
value === 'I' ? '' : '00000000-0000-0000-0000-000000000000'
})
}
>
<SelectTrigger>
<SelectValue placeholder="Select Credit To" />
</SelectTrigger>
<SelectContent>
<SelectItem value="D">Destination Member</SelectItem>
<SelectItem value="S">Source Member</SelectItem>
<SelectItem value="I">Input Customer</SelectItem>
</SelectContent>
</Select>
</div>
{formField.credit_to === 'I' && (
<div className="w-full">
<label className="form-label">
Credit Destination <span className="text-red-500">*</span>
</label>
<div className="relative">
<div
className="flex w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 cursor-pointer"
onClick={() => setOpen(!open)}
>
<span className="truncate">
{customers.find(
(customer) => customer.id === formField.credit_destination
)?.username || 'Search customer...'}
</span>
<path d="m6 9 6 6 6-6"></path>
</div>
{open && (
<div className="absolute left-0 right-0 top-full z-50 mt-1 max-h-52 overflow-auto rounded-md border border-gray-200 bg-white shadow-lg">
<div className="sticky top-0 bg-white p-2 border-b">
<Input
className="h-8 text-sm"
type="text"
placeholder="Search customer..."
value={customerSearchTerm}
onChange={(e) => setCustomerSearchTerm(e.target.value)}
autoComplete="off"
onClick={(e) => e.stopPropagation()}
autoFocus
/>
</div>
<div>
{customers
.filter(
(customer) =>
customer.username
.toLowerCase()
.includes(customerSearchTerm.toLowerCase()) ||
customer.msisdn.includes(customerSearchTerm)
)
.map((customer) => (
<div
key={customer.id}
className="cursor-pointer px-3 py-1.5 text-sm hover:bg-gray-100"
onClick={() => {
setFormField({
...formField,
credit_destination: customer.id
});
setOpen(false);
}}
>
{customer.username}
</div>
))}
{customers.filter(
(customer) =>
customer.username
.toLowerCase()
.includes(customerSearchTerm.toLowerCase()) ||
customer.msisdn.includes(customerSearchTerm)
).length === 0 && (
<div className="px-3 py-2 text-sm text-gray-500">
No customer found
</div>
)}
</div>
</div>
)}
</div>
</div>
)}
<div className="w-full">
<label className="form-label">
Credit Destination Account <span className="text-red-500">*</span>
</label>
{renderSelectWithLoading(
formField.credit_destination_account,
(value) => setFormField({ ...formField, credit_destination_account: value }),
wallets,
'Select Wallet',
isLoadingWallets
)}
</div>
<div className="w-full">
<label className="form-label">
Status <span className="text-red-500">*</span>
</label>
<Select
value={formField.status}
onValueChange={(value) => setFormField({ ...formField, status: value })}
@ -350,7 +727,9 @@ const AddFeeDialog = () => {
</Select>
</div>
<div className="w-full">
<label className="form-label">Status Include <span className="text-red-500">*</span></label>
<label className="form-label">
Status Include <span className="text-red-500">*</span>
</label>
<Select
value={formField.status_include}
onValueChange={(value) => setFormField({ ...formField, status_include: value })}
@ -365,7 +744,9 @@ const AddFeeDialog = () => {
</Select>
</div>
<div className="w-full">
<label className="form-label">Priority <span className="text-red-500">*</span></label>
<label className="form-label">
Priority <span className="text-red-500">*</span>
</label>
<Select
value={formField.priority}
onValueChange={(value) => setFormField({ ...formField, priority: value })}
@ -389,7 +770,16 @@ const AddFeeDialog = () => {
>
Reset
</Button>
<Button variant={'default'} type="submit" disabled={isSubmitting}>
<Button
variant={'default'}
type="submit"
disabled={
isSubmitting ||
isLoadingTransactionType ||
isLoadingWallets ||
isLoadingCustomers
}
>
{isSubmitting ? 'Saving...' : 'Save Changes'}
</Button>
</div>

View File

@ -1,4 +1,11 @@
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle , DialogDescription} from '@/components/ui/dialog';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogDescription
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Alert, useDataGrid } from '@/components';
import { useCallback, useState } from 'react';
@ -9,8 +16,9 @@ import { useManageTransferFeeContext } from '../hooks/useManageTransferFeeContex
const API_URL = apiConfig.service_transaction;
const DeleteDialog = () => {
const { showDeleteFeeDialog, handleDeleteFeeDialog, selectedTransferFee } = useManageTransferFeeContext();
const DeleteFeeDialog = () => {
const { showDeleteFeeDialog, handleDeleteFeeDialog, selectedTransferFee } =
useManageTransferFeeContext();
const { reload } = useDataGrid();
const { DeleteData } = useCallApi();
const [alert, setAlert] = useState({
@ -19,9 +27,12 @@ const DeleteDialog = () => {
});
const doDeleteTransferFee = useCallback(async () => {
const response = await DeleteData(`${API_URL}/transactionfees/delete/${selectedTransferFee}/false`, {
id: selectedTransferFee
});
const response = await DeleteData(
`${API_URL}/transactionfees/delete/${selectedTransferFee}/false`,
{
id: selectedTransferFee
}
);
if (response?.status) {
setAlert({ show: false, message: '' });
@ -39,7 +50,9 @@ const DeleteDialog = () => {
<DialogContent className="container-fixed max-w-md flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0 block">
<DialogTitle className="text-lg">Delete Transfer Type</DialogTitle>
<DialogDescription className="text-sm">Are you sure you want to delete this data?</DialogDescription>
<DialogDescription className="text-sm">
Are you sure you want to delete this data?
</DialogDescription>
<Alert variant="warning">
<h3 className="text-lg">Are you sure?</h3>
<span className="text-sm">You will delete this data!</span>
@ -63,5 +76,4 @@ const DeleteDialog = () => {
);
};
export default DeleteDialog;
export { DeleteDialog };
export default DeleteFeeDialog;

View File

@ -7,7 +7,6 @@ import {
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import {
Dialog,
DialogBody,
@ -25,16 +24,16 @@ import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { getAuth } from '@/auth';
import { ManageTransferFeeContextProvider } from '../../transferfee/hooks/ManageTransferFeeContext';
import AddFeeDialog from '../../transferfee/blocks/AddDialog';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
const API_URL = apiConfig.service_transaction;
const API_URL_MASTERDATA = apiConfig.service_master_data;
const API_URL_MASTER_DATA = apiConfig.service_master_data;
const API_URL_CUSTOMER = apiConfig.service_customer;
interface WalletProps {
Wallet_id: string;
Wallet_name: string;
id: string;
name: string;
}
interface CustomerProps {
@ -53,88 +52,188 @@ const EditFeeDialog = () => {
const { showEditFeeDialog, handleEditFeeDialog, selectedTransferFee } =
useManageTransferFeeContext();
const { reload } = useDataGrid();
const [wallets, setWallets] = useState<WalletProps[]>([]);
const { GetData, PutData } = useCallApi();
const [isSubmitting, setIsSubmitting] = useState(false);
const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]);
const parsedUser = getAuth()?.user;
const [wallets, setWallets] = useState<WalletProps[]>([]);
const [customers, setCustomers] = useState<CustomerProps[]>([]);
const [transactionTypes, setTransactionTypes] = useState<TransactionTypeProps[]>([]);
const [transactionTypeName, setTransactionTypeName] = useState('');
const customersWithNames = customers.map((customer) => ({
id: customer.id,
name: customer.username
}));
const [customerSearchTerm, setCustomerSearchTerm] = useState('');
const [showCustomerSearch, setShowCustomerSearch] = useState(false);
const [open, setOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [alert, setAlert] = useState({
show: false,
message: ''
});
const [formField, setFormField] = useState({
const [isLoadingTransferFee, setIsLoadingTransferFee] = useState(false);
const [isLoadingTransactionType, setIsLoadingTransactionType] = useState(false);
const [isLoadingWallets, setIsLoadingWallets] = useState(false);
const [isLoadingCustomers, setIsLoadingCustomers] = useState(false);
const initialState = {
name: '',
description: '',
transaction_type: '',
minimum_amount: 0,
maximum_amount: 0,
period_start: '',
period_end: '',
deduct_amount: 0,
deduct_percentage: 0,
fee_amount: 0,
priority: '',
status: '',
status_include: '',
transaction_type: '',
updated_by: '',
updated_at: ''
});
updated_at: '',
deduct_from: '',
deduct_from_account: '',
credit_to: '',
credit_destination: '00000000-0000-0000-0000-000000000000',
credit_destination_account: ''
};
const [formField, setFormField] = useState(initialState);
useEffect(() => {
const updated_time = new Date();
const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' ');
if (showEditFeeDialog) {
setFormField({
...formField,
setFormField((prevState) => ({
...prevState,
updated_by: parsedUser?.username,
updated_at: formattedTime
});
}));
}
}, [showEditFeeDialog]);
/* actions */
}, [showEditFeeDialog, parsedUser?.username]);
const resetForm = () => {
if (selectedTransferFee) {
fetchTransactionFee(selectedTransferFee);
} else {
setFormField(initialState);
}
};
const doUpdateTransferFee = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await PutData(`${API_URL}/transactionfees/update/${selectedTransferFee}`, {
...formField
});
if (response?.status) {
handleEditFeeDialog(false, null);
// toast.success('Success Update Transaction Fee');
reload();
} else {
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
setIsSubmitting(true);
const requiredFields = [
'name',
'description',
'period_start',
'period_end',
'transaction_type',
'status',
'status_include',
'priority',
'deduct_from',
'deduct_from_account',
'credit_to',
'credit_destination_account'
];
for (const field of requiredFields) {
if (formField[field as keyof typeof formField] === '') {
setAlert({
show: true,
message: `All required fields must be filled out. Missing: ${field.replace(/_/g, ' ')}`
});
setIsSubmitting(false);
return;
}
}
if (formField.credit_to === 'I' && !formField.credit_destination) {
setAlert({
show: true,
message: 'Credit destination is required when Input Customer is selected'
});
setIsSubmitting(false);
return;
}
setAlert({ show: false, message: '' });
const payload = { ...formField };
if (formField.credit_to !== 'I') {
payload.credit_destination = '00000000-0000-0000-0000-000000000000';
}
try {
const response = await PutData(
`${API_URL}/transactionfees/update/${selectedTransferFee}`,
payload
);
if (response?.status) {
toast.success('Successfully updated transfer fee');
reload();
handleEditFeeDialog(false, null);
const createActivity = {
module: 'Manage Transfer Fee',
description: `Edit Transfer Fee => ${formField.name}`,
action: 'U'
};
doSaveLogActivity(createActivity);
} else {
setAlert({ show: true, message: response?.message || 'Failed to update transfer fee' });
}
} catch (error) {
console.error('Error updating transfer fee', error);
setAlert({ show: true, message: 'An error occurred while updating the transfer fee' });
} finally {
setIsSubmitting(false);
}
},
[formField, selectedTransferFee]
[formField, selectedTransferFee, PutData, reload, handleEditFeeDialog]
);
const fetchWallets = useCallback(async () => {
setIsLoadingWallets(true);
const params = {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
filter: JSON.stringify({
status: 'Y'
})
order_field: 'Wallets.name',
order_direction: 'ASC'
};
const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, params);
if (response?.status && response?.data) {
setWallets(response.data.list);
} else {
try {
const response = await GetData(`${API_URL_MASTER_DATA}/wallet/list`, params);
if (response?.status && response?.data) {
setWallets(response.data.list);
} else {
setWallets([]);
}
} catch (error) {
console.error('Error fetching wallets', error);
setWallets([]);
} finally {
setIsLoadingWallets(false);
}
}, []);
}, [GetData]);
useEffect(() => {
if (!showEditFeeDialog) return;
fetchWallets();
}, [fetchWallets]);
}, [showEditFeeDialog, fetchWallets]);
useEffect(() => {
if (!showEditFeeDialog) return;
const getCustomerList = async (sorting: any) => {
setIsLoadingCustomers(true);
try {
sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
@ -146,16 +245,20 @@ const EditFeeDialog = () => {
});
setCustomers(response?.data.list || []);
} catch (error) {
console.error('Error fetching customer', error);
console.error('Error fetching customers', error);
} finally {
setIsLoadingCustomers(false);
}
};
getCustomerList([{ id: 'msisdn', desc: false }]);
}, []);
getCustomerList([{ id: 'id', desc: false }]);
}, [showEditFeeDialog, GetData]);
useEffect(() => {
if (!showEditFeeDialog) return;
const getTransactionTypeList = async (sorting: any) => {
setIsLoadingTransactionType(true);
try {
sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
const response = await GetData(`${API_URL}/transactiontype/list`, {
@ -165,96 +268,207 @@ const EditFeeDialog = () => {
order_field: sorting[0].id,
order_direction: sorting[0].desc ? 'DESC' : 'ASC'
});
// console.log('Transaction Type: ', response?.data.list);
setTransactionTypes(response?.data.list);
setTransactionTypes(response?.data.list || []);
} catch (error) {
console.error('Error fetching Transaction Type', error);
console.error('Error fetching transaction types', error);
} finally {
setIsLoadingTransactionType(false);
}
};
getTransactionTypeList([{ id: 'id', desc: false }]);
}, [showEditFeeDialog]);
}, [showEditFeeDialog, GetData]);
const fetchTransactionFee = useCallback(async (id: string) => {
const response = await GetData(`${API_URL}/transactionfees/getdata/${id}`, { id });
const formatDate = (dateString: string) => {
if (!dateString || dateString.includes('0001-01-01')) return '';
return dateString.split('T')[0];
};
if (response?.status) {
setFormField((prev) => ({
...prev,
name: response.data.name,
description: response.data.description,
minimum_amount: response.data.minimum_amount,
maximum_amount: response.data.maximum_amount,
period_start: response.data.period_start,
period_end: response.data.period_end,
deduct_amount: response.data.deduct_amount,
deduct_percentage: response.data.deduct_percentage,
priority: response.data.priority,
status: response.data.status,
status_include: response.data.status_include,
transaction_type: response.data.transaction_type.id
}));
}
}, []);
const fetchTransactionFee = useCallback(
async (id: string) => {
setIsLoadingTransferFee(true);
try {
const response = await GetData(`${API_URL}/transactionfees/getdata/${id}`, {});
if (response?.status) {
setFormField({
...initialState,
name: response.data.name || '',
description: response.data.description || '',
transaction_type: response.data.transaction_type?.id || '',
minimum_amount: response.data.minimum_amount || 0,
maximum_amount: response.data.maximum_amount || 0,
period_start: formatDate(response.data.period_start),
period_end: formatDate(response.data.period_end),
deduct_amount: response.data.deduct_amount || 0,
deduct_percentage: response.data.deduct_percentage || 0,
fee_amount: response.data.fee_amount || 0,
priority: response.data.priority || '',
status: response.data.status || '',
status_include: response.data.status_include || '',
deduct_from: response.data.deduct_from || '',
deduct_from_account: response.data.deduct_from_account?.id || '',
credit_to: response.data.credit_to || '',
credit_destination:
response.data.credit_destination?.id || '00000000-0000-0000-0000-000000000000',
credit_destination_account: response.data.credit_destination_account?.id || '',
updated_by: parsedUser?.username,
updated_at: new Date().toISOString().slice(0, 19).replace('T', ' ')
});
if (response.data.transaction_type?.name) {
setTransactionTypeName(response.data.transaction_type.name);
}
}
} catch (error) {
console.error('Error fetching transaction fee details', error);
setAlert({ show: true, message: 'Failed to fetch transaction fee details' });
} finally {
setIsLoadingTransferFee(false);
}
},
[GetData, parsedUser?.username]
);
const hasFetchedRef = useRef(false);
useEffect(() => {
if (selectedTransferFee) {
if (selectedTransferFee && showEditFeeDialog && !hasFetchedRef.current) {
fetchTransactionFee(selectedTransferFee);
hasFetchedRef.current = true;
}
}, [selectedTransferFee]);
const resetForm = () => {
setFormField({
name: '',
description: '',
minimum_amount: 0,
maximum_amount: 0,
period_start: '',
period_end: '',
deduct_amount: 0,
deduct_percentage: 0,
priority: '',
status: '',
status_include: '',
transaction_type: '',
updated_by: '',
updated_at: ''
});
if (!showEditFeeDialog) {
hasFetchedRef.current = false;
}
}, [selectedTransferFee, showEditFeeDialog, fetchTransactionFee]);
const handleCloseDialog = () => {
setFormField(initialState);
setAlert({ show: false, message: '' });
setCustomerSearchTerm('');
setOpen(false);
handleEditFeeDialog(false, null);
};
useEffect(() => {
if (!showEditFeeDialog) {
setCustomerSearchTerm('');
setOpen(false);
}
}, [showEditFeeDialog]);
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 (
<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">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
<DialogHeader className="p-5 border-0">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
<div className="flex items-center justify-between flex-wrap grow">
<div className="flex flex-col justify-center">
<h1 className="text-xl font-semibold leading-none text-gray-900">
Update Transaction Fee
Edit Transfer Fee
</h1>
<div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
</div>
<div
className="cursor-pointer hover:opacity-100 opacity-50"
onClick={() => handleEditFeeDialog(false, null)}
onClick={handleCloseDialog}
>
<KeenIcon icon="cross" className="text-1.5xl" />
</div>
</div>
</DialogHeader>
<DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
<div className="flex flex-col px-0">
{alert.show && (
<Alert variant="danger">
<DialogBody className="max-h-[1080px] overflow-y-auto">
{alert.show && (
<div className="sticky top-0 z-10 bg-white p-3">
<Alert variant="danger" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
)}
</div>
)}
{isLoadingTransferFee ? (
<div className="flex flex-col items-center justify-center p-8">
<div className="animate-pulse flex space-x-4 w-full">
<div className="flex-1 space-y-4 py-1">
<div className="h-4 bg-gray-200 rounded w-3/4"></div>
<div className="space-y-2">
<div className="h-4 bg-gray-200 rounded"></div>
<div className="h-4 bg-gray-200 rounded w-5/6"></div>
</div>
</div>
</div>
<p className="mt-4 text-gray-500">Loading transfer fee details...</p>
</div>
) : (
<form action="" onSubmit={doUpdateTransferFee}>
<div className="card flex flex-col gap-5">
<div className="card-body grid gap-5 p-0">
<div className="w-full">
<label className="form-label">
Transfer Free Name <span className="text-red-500">*</span>
Transaction Type ID <span className="text-red-500">*</span>
</label>
<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>
)}
<input
type="hidden"
name="transaction_type"
value={formField.transaction_type}
/>
</div>
</div>
<div className="w-full">
<label className="form-label">
Transfer Fee Name <span className="text-red-500">*</span>
</label>
<Input
className="input"
@ -266,6 +480,7 @@ const EditFeeDialog = () => {
}
/>
</div>
<div className="w-full">
<label className="form-label">
Description <span className="text-red-500">*</span>
@ -280,10 +495,9 @@ const EditFeeDialog = () => {
}
/>
</div>
<div className="w-full">
<label className="form-label">
Minimum Amount
</label>
<label className="form-label">Minimum Amount</label>
<NumericFormat
className="input"
value={formField.minimum_amount}
@ -299,10 +513,9 @@ const EditFeeDialog = () => {
placeholder="Enter Minimum Amount"
/>
</div>
<div className="w-full">
<label className="form-label">
Maximum Amount
</label>
<label className="form-label">Maximum Amount</label>
<NumericFormat
className="input"
value={formField.maximum_amount}
@ -315,9 +528,10 @@ const EditFeeDialog = () => {
maximum_amount: values.floatValue || 0
}));
}}
placeholder="Enter Minimum Amount"
placeholder="Enter Maximum Amount"
/>
</div>
<div className="w-full">
<label className="form-label">
Period Start <span className="text-red-500">*</span>
@ -326,12 +540,13 @@ const EditFeeDialog = () => {
className="input"
type="date"
autoComplete="off"
value={formField.period_start ? formField.period_start.split('T')[0] : ''}
value={formField.period_start}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, period_start: target.value }))
}
/>
</div>
<div className="w-full">
<label className="form-label">
Period End <span className="text-red-500">*</span>
@ -340,15 +555,15 @@ const EditFeeDialog = () => {
className="input"
type="date"
autoComplete="off"
value={formField.period_end ? formField.period_end.split('T')[0] : ''}
value={formField.period_end}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, period_end: target.value }))
}
/>
</div>
<div className="w-full">
<label className="form-label">
Deduct Amount</label>
<label className="form-label">Deduct Amount</label>
<NumericFormat
className="input"
value={formField.deduct_amount}
@ -361,12 +576,12 @@ const EditFeeDialog = () => {
deduct_amount: values.floatValue || 0
}));
}}
placeholder="Enter Minimum Amount"
placeholder="Enter Deduct Amount"
/>
</div>
<div className="w-full">
<label className="form-label">
Deduct Percentage </label>
<label className="form-label">Deduct Percentage</label>
<NumericFormat
className="input"
value={formField.deduct_percentage}
@ -379,31 +594,165 @@ const EditFeeDialog = () => {
deduct_percentage: values.floatValue || 0
}));
}}
placeholder="Enter Minimum Amount"
placeholder="Enter Deduct Percentage"
/>
</div>
<div className="w-full">
<label className="form-label">Fee Amount</label>
<NumericFormat
className="input"
value={formField.fee_amount}
thousandSeparator="."
decimalSeparator=","
allowNegative={false}
onValueChange={(values) => {
setFormField((prev) => ({
...prev,
fee_amount: values.floatValue || 0
}));
}}
placeholder="Enter Fee Amount"
/>
</div>
<div className="w-full">
<label className="form-label">
Transacsion Type ID <span className="text-red-500">*</span>
Deduct From <span className="text-red-500">*</span>
</label>
<Select
value={formField.transaction_type}
onValueChange={(transaction_type) =>
setFormField((prev) => ({ ...prev, transaction_type }))
}
value={formField.deduct_from}
onValueChange={(value) => setFormField({ ...formField, deduct_from: value })}
>
<SelectTrigger>
<SelectValue placeholder="Select Wallet" />
<SelectValue placeholder="Select Deduct From" />
</SelectTrigger>
<SelectContent>
{transactionTypes.map((transactiontype, idx) => (
<SelectItem value={transactiontype.id} key={transactiontype.id}>
{transactiontype.name}
</SelectItem>
))}
<SelectItem value="D">Destination Member</SelectItem>
<SelectItem value="S">Source Member</SelectItem>
</SelectContent>
</Select>
</div>
<div className="w-full">
<label className="form-label">
Deduct From Destination <span className="text-red-500">*</span>
</label>
{renderSelectWithLoading(
formField.deduct_from_account,
(value) => setFormField({ ...formField, deduct_from_account: value }),
wallets,
'Select Wallet',
isLoadingWallets
)}
</div>
<div className="w-full">
<label className="form-label">
Credit To <span className="text-red-500">*</span>
</label>
<Select
value={formField.credit_to}
onValueChange={(value) =>
setFormField({
...formField,
credit_to: value,
credit_destination:
value === 'I' ? '' : '00000000-0000-0000-0000-000000000000'
})
}
>
<SelectTrigger>
<SelectValue placeholder="Select Credit To" />
</SelectTrigger>
<SelectContent>
<SelectItem value="D">Destination Member</SelectItem>
<SelectItem value="S">Source Member</SelectItem>
<SelectItem value="I">Input Customer</SelectItem>
</SelectContent>
</Select>
</div>
{formField.credit_to === 'I' && (
<div className="w-full">
<label className="form-label">
Credit Destination <span className="text-red-500">*</span>
</label>
<div className="relative">
<div
className="flex w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 cursor-pointer"
onClick={() => setOpen(!open)}
>
<span className="truncate">
{customers.find(customer => customer.id === formField.credit_destination)?.username || 'Search customer...'}
</span>
<path d="m6 9 6 6 6-6"></path>
</div>
{open && (
<div className="absolute left-0 right-0 top-full z-50 mt-1 max-h-52 overflow-auto rounded-md border border-gray-200 bg-white shadow-lg">
<div className="sticky top-0 bg-white p-2 border-b">
<Input
className="h-8 text-sm"
type="text"
placeholder="Search customer..."
value={customerSearchTerm}
onChange={(e) => setCustomerSearchTerm(e.target.value)}
autoComplete="off"
onClick={(e) => e.stopPropagation()}
autoFocus
/>
</div>
<div>
{customers
.filter(customer =>
customer.username.toLowerCase().includes(customerSearchTerm.toLowerCase()) ||
customer.msisdn.includes(customerSearchTerm)
)
.map(customer => (
<div
key={customer.id}
className="cursor-pointer px-3 py-1.5 text-sm hover:bg-gray-100"
onClick={() => {
setFormField({
...formField,
credit_destination: customer.id
});
setOpen(false);
}}
>
{customer.username}
</div>
))}
{customers.filter(customer =>
customer.username.toLowerCase().includes(customerSearchTerm.toLowerCase()) ||
customer.msisdn.includes(customerSearchTerm)
).length === 0 && (
<div className="px-3 py-2 text-sm text-gray-500">No customer found</div>
)}
</div>
</div>
)}
</div>
</div>
)}
<div className="w-full">
<label className="form-label">
Credit Destination Account <span className="text-red-500">*</span>
</label>
{renderSelectWithLoading(
formField.credit_destination_account,
(value) => setFormField({ ...formField, credit_destination_account: value }),
wallets,
'Select Wallet',
isLoadingWallets
)}
</div>
<div className="w-full">
<label className="form-label">
Status <span className="text-red-500">*</span>
@ -421,15 +770,14 @@ const EditFeeDialog = () => {
</SelectContent>
</Select>
</div>
<div className="w-full">
<label className="form-label">
Status Included <span className="text-red-500">*</span>
Status Include <span className="text-red-500">*</span>
</label>
<Select
value={formField.status_include}
onValueChange={(value) =>
setFormField({ ...formField, status_include: value })
}
onValueChange={(value) => setFormField({ ...formField, status_include: value })}
>
<SelectTrigger>
<SelectValue placeholder="Select Status" />
@ -440,6 +788,7 @@ const EditFeeDialog = () => {
</SelectContent>
</Select>
</div>
<div className="w-full">
<label className="form-label">
Priority <span className="text-red-500">*</span>
@ -457,62 +806,37 @@ const EditFeeDialog = () => {
</SelectContent>
</Select>
</div>
{/* <div className="w-full">
<label className="form-label">Priotity <span className="text-red-500">*</span></label>
<Select
value={formField.priority}
onValueChange={(value) => setFormField({ ...formField, priority: value })}
>
<SelectTrigger>
<SelectValue placeholder="Select Status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Y">Y</SelectItem>
<SelectItem value="N">N</SelectItem>
</SelectContent>
</Select>
</div> */}
{/* <div className="w-full">
<label className="form-label">Priority <span className="text-red-500">*</span></label>
<Select
value={formField.priority ? 'Y' : 'N'}
onValueChange={(value) =>
setFormField({ ...formField, priority: value === 'Y' })
}
>
<SelectTrigger>
<SelectValue placeholder="Select Priority" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Y">Y</SelectItem>
<SelectItem value="N">N</SelectItem>
</SelectContent>
</Select>
</div> */}
<div className="flex justify-end pt-2.5 gap-5">
<Button
variant={'outline'}
type="reset"
onClick={() => {
resetForm();
}}
type="button"
onClick={resetForm}
>
Reset
</Button>
<Button variant={'default'} type="submit" disabled={isSubmitting}>
<Button
variant={'default'}
type="submit"
disabled={
isSubmitting ||
isLoadingTransferFee ||
isLoadingTransactionType ||
isLoadingWallets ||
isLoadingCustomers
}
>
{isSubmitting ? 'Saving...' : 'Save Changes'}
</Button>
</div>
</div>
</div>
</form>
</div>
)}
</DialogBody>
</DialogContent>
</Dialog>
);
};
export { EditFeeDialog };
export {EditFeeDialog};

View File

@ -7,6 +7,7 @@ import { createContext, useCallback, useEffect, useMemo, useState } from 'react'
import ListToolbar from '../blocks/ListToolBar';
import DeleteDialog from '../blocks/DeleteDialog';
import { EditFeeDialog } from '../blocks/EditDialog';
import { useManageTransferTypeContext } from '../../transfertype/hooks/useManageTransferTypeContext';
interface ContextProps {
showEditFeeDialog: boolean;
@ -16,6 +17,7 @@ interface ContextProps {
handleDeleteFeeDialog: (show: boolean, selected_TransferFee: string | null) => void;
showDeleteFeeDialog: boolean;
selectedTransferFee: string | null;
transactionTypeId: string | null;
}
const initialProps: ContextProps = {
@ -25,20 +27,41 @@ const initialProps: ContextProps = {
handleAddFeeDialog: () => {},
showDeleteFeeDialog: false,
handleDeleteFeeDialog: () => {},
selectedTransferFee: null
selectedTransferFee: null,
transactionTypeId: null
};
interface TransferFeeProps {
name: string;
description: string;
minimum_amount: number;
maximum_amount: number;
period_start: string;
period_end: string;
deduct_amount: number;
deduct_percentage: number;
transaction_type: string;
status: string;
status_include: string;
fee: number;
}
const ManageTransferFeeContext = createContext<ContextProps>(initialProps);
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 [showAddFeeDialog, setShowAddFeeDialog] = useState(false);
const [showDeleteFeeDialog, setShowDeleteFeeDialog] = useState(false);
const { showAddDialog, handleAddDialog, selectedTransferType } = useManageTransferTypeContext();
const [selectedTransferFee, setSelectedTransferFee] = useState<string | null>(null);
const { GetData } = useCallApi();
const handleEditFeeDialog = useCallback((show: boolean, selected_TransferFee: string | null) => {
setSelectedTransferFee(show ? selected_TransferFee : null);
setShowEditFeeDialog(show);
@ -48,28 +71,44 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
setShowAddFeeDialog(show);
}, []);
const handleDeleteFeeDialog = useCallback((show: boolean, selected_TransferFee: string | null) => {
setSelectedTransferFee(show ? selected_TransferFee : null);
setShowDeleteFeeDialog(show);
}, []);
const handleDeleteFeeDialog = useCallback(
(show: boolean, selected_TransferFee: string | null) => {
setSelectedTransferFee(show ? selected_TransferFee : null);
setShowDeleteFeeDialog(show);
},
[]
);
const doGetTransferFeeListData = async (
page: number,
limit: number,
sorting: any,
filter: any
) => {
sorting = sorting.length == 0 ? [{ id: 'id', desc: false }] : sorting;
filter = filter.length == 0 ? {} : { any: filter[0].value.toLowerCase() };
const response = await GetData(`${API_URL}/transactionfees/list`, {
limit: limit,
page: page+1,
with_deleted: false,
order_field: sorting[0].id,
order_direction: sorting[0].desc ? 'ASC' : 'DESC',
filter: JSON.stringify(filter)
});
return { data: response?.data.list, totalCount: response?.data.total_count };
if (!selectedTransferType) {
return { data: [], totalCount: 0 };
}
sorting = sorting.length === 0 ? [{ id: 'id', desc: false }] : sorting;
filter = filter.length === 0 ? {} : { any: filter[0].value.toLowerCase() };
try {
const response = await GetData(
`${API_URL}/transactionfees/getdatabytransactiontype/${selectedTransferType}`,
{}
);
// console.log('API Response:', response?.data);
return {
data: response?.data,
totalCount: 1
};
} catch (error) {
console.error('Error fetching transaction fees by transaction type:', error);
return { data: [], totalCount: 0 };
}
};
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
@ -105,20 +144,12 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
meta: { headerClassName: 'w-[150px]' }
},
{
accessorFn: (row) => row.period_start?.split('T')[0],
id: 'period_start',
header: ({ column }) => <DataGridColumnHeader title="Period Start" column={column} />,
accessorFn: (row) => row.fee_amount,
id: 'fee_amount',
header: ({ column }) => <DataGridColumnHeader title="Fee Amount" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[200px]' }
},
{
accessorFn: (row) => row.period_end?.split('T')[0],
id: 'period_end',
header: ({ column }) => <DataGridColumnHeader title="Period End" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[200px]' }
meta: { headerClassName: 'w-[150px]' }
},
{
accessorFn: (row) => row.deduct_amount,
@ -136,6 +167,23 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
enableHiding: false,
meta: { headerClassName: 'w-[150px]' }
},
{
accessorFn: (row) => row.period_start?.split('T')[0],
id: 'period_start',
header: ({ column }) => <DataGridColumnHeader title="Period Start" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[200px]' }
},
{
accessorFn: (row) => row.period_end?.split('T')[0],
id: 'period_end',
header: ({ column }) => <DataGridColumnHeader title="Period End" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[200px]' }
},
{
accessorFn: (row) => row.transaction_type?.name,
id: 'transactionTypeId',
@ -145,28 +193,140 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
meta: { headerClassName: 'w-[250px]' }
},
{
accessorFn: (row) => (row.priority === 'Y' ? 'Yes' : 'No'),
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',
header: ({ column }) => <DataGridColumnHeader title="Credit Destination" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[250px]' }
},
{
accessorFn: (row) => row.credit_destination_account?.description,
id: 'credit_destination_account',
header: ({ column }) => (
<DataGridColumnHeader title="Credit Destination Account" column={column} />
),
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[250px]' }
},
{
accessorFn: (row: { deduct_from: string }) => {
const mapping: Record<string, string> = {
D: 'Destination Member',
S: 'Source Member'
};
return mapping[row.deduct_from];
},
id: 'deduct_from',
header: ({ column }) => <DataGridColumnHeader title="Deduct From" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[250px]' }
},
{
accessorFn: (row) => row.deduct_from_account?.description,
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',
header: ({ column }) => <DataGridColumnHeader title="Priority" column={column} />,
enableSorting: true,
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',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
enableSorting: true,
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',
header: ({ column }) => <DataGridColumnHeader title="Status Include" column={column} />,
enableSorting: true,
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',
@ -204,8 +364,8 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
return (
<div className="container mx-auto py-5">
<div className="flex justify-between items-center mt-6">
<h1 className="text-xl font-semibold text-gray-900">Manage Transaction Fee</h1>
</div>
<h1 className="text-xl font-semibold text-gray-900">Manage Transaction Fee</h1>
</div>
<ManageTransferFeeContext.Provider
value={{
showEditFeeDialog,
@ -214,7 +374,8 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
handleAddFeeDialog,
selectedTransferFee,
showDeleteFeeDialog,
handleDeleteFeeDialog
handleDeleteFeeDialog,
transactionTypeId
}}
>
<Toaster expand visibleToasts={9} duration={3000} />
@ -230,8 +391,6 @@ const ManageTransferFeeContextProvider = ({ children }: { children: React.ReactN
}
>
{children}
<DeleteDialog />
<EditFeeDialog />
</DataGridProvider>
</ManageTransferFeeContext.Provider>
</div>

View File

@ -37,7 +37,7 @@ const TransferType = () => {
</div>
<AddDialog />
<DeleteDialog />
{/* <EditDialog /> */}
<EditDialog />
</Container>
</ManageTransferTypeContextProvider>

View File

@ -39,6 +39,7 @@ import {
CommandItem,
CommandList
} from '@/components/ui/command';
import { doSaveLogActivity } from '@/actions/GlobalActions';
interface WalletProps {
id: string;
@ -75,7 +76,6 @@ const AddDialog = () => {
wallet_origin: '',
wallet_destination: '',
minimum_amount: 0,
maximum_amount: 0,
max_transaction_per_day: 0,
@ -95,7 +95,6 @@ const AddDialog = () => {
const parsedUser = getAuth()?.user;
// Updated validation function to make only certain fields required
const validateForm = () => {
const requiredFields = [
'name',
@ -141,6 +140,13 @@ const AddDialog = () => {
toast.success('Success Create Transfer Type');
reload();
resetForm();
const createActivity = {
module: 'Manage Transfer Type',
description: `Create Transfer Type => ${formField.name}`,
action: 'C'
};
doSaveLogActivity(createActivity);
}
})
.finally(() => {
@ -215,7 +221,7 @@ const AddDialog = () => {
page: 1,
with_deleted: false,
order_field: 'wallets.name',
order_direction: 'ASC',
order_direction: 'ASC'
};
const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, params);
// console.log(response)
@ -258,11 +264,11 @@ const AddDialog = () => {
<DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
<div className="flex flex-col px-0">
{alert.show && (
<div className="sticky top-0 z-10 bg-white p-3">
<Alert variant="danger" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
</div>
<div className="sticky top-0 z-10 bg-white p-3">
<Alert variant="danger" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
</div>
)}
<form action="" onSubmit={handleSubmit}>
<div className="card-body grid gap-5 p-0">
@ -432,11 +438,10 @@ const AddDialog = () => {
</div>
</div>
<div className="w-full">
<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">
TransactionType Status
Status Transaction Type
<span className="text-red-500"> *</span>
</label>
@ -453,12 +458,15 @@ const AddDialog = () => {
<SelectContent>
<SelectItem value="D">Disbursement </SelectItem>
<SelectItem value="O">Other </SelectItem>
<SelectItem value="CA">Change Customer to Agent </SelectItem>
<SelectItem value="AC">Change Agent to Customer </SelectItem>
<SelectItem value="CA">Change Group Emoney Customer to Agent </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="AD">Return Agent Deposit </SelectItem>
<SelectItem value="AM">Return Agent Merchant </SelectItem>
<SelectItem value="AE">Return Agent Emoney </SelectItem>
<SelectItem value="R">Reward Point </SelectItem>
</SelectContent>
</Select>
</div>

View File

@ -1,4 +1,10 @@
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Alert, useDataGrid } from '@/components';
import { useCallback, useState } from 'react';
@ -7,11 +13,13 @@ import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { useManageTransferTypeContext } from '../hooks/useManageTransferTypeContext';
import { DialogDescription } from '@radix-ui/react-dialog';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_transaction;
const DeleteDialog = () => {
const { showDeleteDialog, handleDeleteDialog, selectedTransferType } = useManageTransferTypeContext();
const { showDeleteDialog, handleDeleteDialog, selectedTransferType } =
useManageTransferTypeContext();
const { reload } = useDataGrid();
const { DeleteData } = useCallApi();
const [alert, setAlert] = useState({
@ -25,14 +33,23 @@ const DeleteDialog = () => {
return;
}
const response = await DeleteData(`${API_URL}/transactiontype/delete/${selectedTransferType}/false`, {
id: selectedTransferType
});
const response = await DeleteData(
`${API_URL}/transactiontype/delete/${selectedTransferType}/false`,
{
id: selectedTransferType
}
);
if (response?.status) {
setAlert({ show: false, message: '' });
handleDeleteDialog(false, null);
reload();
const createActivity = {
module: 'Manage Transfer Type',
description: `Delete Transfer Type => ${selectedTransferType}`,
action: 'D'
};
doSaveLogActivity(createActivity);
// setTimeout(() => toast.success('Success Delete Transaction Type'), 0);
} else {
setAlert({ show: true, message: response?.message });
@ -44,7 +61,9 @@ const DeleteDialog = () => {
<DialogContent className="container-fixed max-w-md flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0 block">
<DialogTitle className="text-lg">Delete Transfer Type</DialogTitle>
<DialogDescription className="text-sm">Are you sure you want to delete this data?</DialogDescription>
<DialogDescription className="text-sm">
Are you sure you want to delete this data?
</DialogDescription>
<Alert variant="warning">
<h3 className="text-lg">Are you sure?</h3>
<span className="text-sm">You will delete this data!</span>

View File

@ -25,23 +25,18 @@ import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
import { ManageTransferFeeContextProvider } from '../../transferfee/hooks/ManageTransferFeeContext';
import AddFeeDialog from '../../transferfee/blocks/AddDialog';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList
} from '@/components/ui/command';
import { EditFeeDialog } from '../../transferfee/blocks/EditDialog';
import DeleteFeeDialog from '../../transferfee/blocks/DeleteDialog';
import { Checkbox } from '@/components/ui/checkbox';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_transaction;
const API_URL_MASTERDATA = apiConfig.service_master_data;
const API_URL_CUSTOMER = apiConfig.service_customer;
interface WalletProps {
Wallet_id: string;
Wallet_name: string;
id: string;
name: string;
}
interface CustomerProps {
@ -50,80 +45,103 @@ interface CustomerProps {
msisdn: string;
}
interface TranssactionTypeProps {
interface PermissionObject {
id: string;
name: string;
description: string;
minimum_amount: number;
maximum_amount: number;
max_transaction_per_day: number;
status_approval: string;
status: string;
type: string;
wallet_origin: WalletProps;
wallet_destination: WalletProps;
wallet_fee_destination: WalletProps;
customer_fee_destination: CustomerProps;
}
const EditDialog = () => {
const parentRef = useRef<any | null>(null);
const { showEditDialog, handleEditDialog, selectedTransferType } =
useManageTransferTypeContext();
const { showEditDialog, handleEditDialog, selectedTransferType } = useManageTransferTypeContext();
const { reload } = useDataGrid();
const [wallets, setWallets] = useState<WalletProps[]>([]);
const [groups, setGroups] = useState<PermissionObject[]>([]);
const { GetData, PutData } = useCallApi();
const [isSubmitting, setIsSubmitting] = useState(false);
const parsedUser = getAuth()?.user;
const [customers, setCustomers] = useState<CustomerProps[]>([]);
const [open, setOpen] = useState(false);
const [selectedGroups, setSelectedGroups] = useState<string[]>([]);
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState = {
const initialState: {
name: string;
description: string;
wallet_origin: string;
wallet_destination: string;
minimum_amount: number;
maximum_amount: number;
max_transaction_per_day: number;
status: string;
type: string;
status_approval: string;
updated_by: string;
updated_at: string;
permission: string[];
} = {
name: '',
description: '',
wallet_origin: '',
wallet_destination: '',
wallet_fee_destination: '',
customer_fee_destination: '',
minimum_amount: 0,
maximum_amount: 0,
max_transaction_per_day: 0,
status_approval: '',
type: '',
status: '',
permission: [],
updated_by: '',
updated_at: ''
};
const [formField, setFormField] = useState(initialState);
const resetForm = () => {
setFormField(initialState);
setSelectedGroups([]);
setAlert({ show: false, message: '' });
};
const handleGroupChange = (groupId: string) => {
setFormField((prevState) => {
const isSelected = prevState.permission.includes(groupId);
if (isSelected) {
return {
...prevState,
permission: prevState.permission.filter((id) => id !== groupId)
};
} else {
return {
...prevState,
permission: [...prevState.permission, groupId]
};
}
});
};
// Validation function to make certain fields required
const validateForm = () => {
const requiredFields = [
'name',
'description',
'wallet_origin',
'wallet_destination',
'wallet_fee_destination',
'customer_fee_destination',
'status',
'status_approval',
'type'
];
const missingFields = requiredFields.filter(
(field) =>
const missingFields = requiredFields.filter((field) => {
return (
formField[field as keyof typeof formField] === '' ||
formField[field as keyof typeof formField] === null ||
formField[field as keyof typeof formField] === undefined
);
);
});
if (missingFields.length > 0) {
setAlert({
@ -133,6 +151,14 @@ const EditDialog = () => {
return false;
}
if (formField.permission.length === 0) {
setAlert({
show: true,
message: 'Please select at least one group permission'
});
return false;
}
setAlert({ show: false, message: '' });
return true;
};
@ -148,8 +174,13 @@ const EditDialog = () => {
updated_at: formattedTime
}));
}
}, [showEditDialog]);
}, [showEditDialog, parsedUser]);
const selectedPermissionNames = groups
.filter((g) => formField.permission.includes(g.id))
.map((g) => g.name)
.join(', ');
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setIsSubmitting(true);
@ -165,19 +196,33 @@ const EditDialog = () => {
handleEditDialog(false, null);
toast.success('Success Update Transfer Type');
reload();
const createActivity = {
module: 'Manage Transfer Type',
description: `Edit Transfer Type => ${selectedTransferType}`,
action: 'U'
};
doSaveLogActivity(createActivity);
}
})
.finally(() => {
setIsSubmitting(false);
});
};
const doUpdateTransferType = useCallback(async () => {
try {
const response = await PutData(`${API_URL}/transactiontype/update/${selectedTransferType}`, {
...formField
});
const formDataToSend = {
...formField,
permission: formField.permission.filter((id) => typeof id === 'string')
};
const response = await PutData(
`${API_URL}/transactiontype/update/${selectedTransferType}`,
formDataToSend
);
if (response?.status) {
setAlert({ show: false, message: '' });
return true;
@ -189,9 +234,7 @@ const EditDialog = () => {
setAlert({
show: true,
message:
error instanceof Error
? error.message
: 'An error occurred while updating transfer type'
error instanceof Error ? error.message : 'An error occurred while updating transfer type'
});
return false;
}
@ -199,9 +242,10 @@ const EditDialog = () => {
useEffect(() => {
if (!showEditDialog) return;
const getCustomerList = async (sorting: any) => {
const getCustomerList = async () => {
try {
sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
const sorting = [{ id: 'id', desc: false }];
const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
limit: 100,
page: 1,
@ -209,74 +253,123 @@ const EditDialog = () => {
order_field: sorting[0].id,
order_direction: sorting[0].desc ? 'DESC' : 'ASC'
});
setCustomers(response?.data.list);
if (response?.status && response?.data) {
setCustomers(response.data.list);
}
} catch (error) {
console.error('Error fetching customer', error);
}
};
getCustomerList([{ id: 'id', desc: false }]);
getCustomerList();
}, [showEditDialog, GetData]);
const fetchWallets = useCallback(async () => {
const params = {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
filter: JSON.stringify({
status: 'Y'
})
};
const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, params);
if (response?.status && response?.data) {
setWallets(response.data.list);
} else {
setWallets([]);
}
}, [GetData]);
useEffect(() => {
if (!showEditDialog) return;
fetchWallets();
}, [showEditDialog, fetchWallets]);
const fetchTransactionType = useCallback(async (id: string) => {
try {
const response = await GetData(`${API_URL}/transactiontype/getdata/${id}`, { id });
if (response?.status) {
setFormField((prev) => ({
...prev,
name: response.data.name,
description: response.data.description,
wallet_origin: response.data.wallet_origin.id,
wallet_destination: response.data.wallet_destination.id,
wallet_fee_destination: response.data.wallet_fee_destination.id,
customer_fee_destination: response.data.customer_fee_destination.id,
minimum_amount: response.data.minimum_amount,
maximum_amount: response.data.maximum_amount,
max_transaction_per_day: response.data.max_transaction_per_day,
status_approval: response.data.status_approval,
type: response.data.type || '',
status: response.data.status
}));
const getGroupList = async () => {
try {
const response = await GetData(`${API_URL_MASTERDATA}/groups/list`, {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC'
});
if (response?.status && response?.data) {
setGroups(response.data.list);
}
} catch (error) {
console.error('Error fetching groups', error);
}
// console.log(response);
} catch (error) {
console.error('Error fetching transaction type', error);
setAlert({
show: true,
message: 'Failed to load transaction type data'
});
}
}, [GetData]);
};
getGroupList();
}, [showEditDialog, GetData]);
useEffect(() => {
if (selectedTransferType) {
fetchTransactionType(selectedTransferType);
if (!showEditDialog) return;
const getWalletList = async () => {
try {
const response = await GetData(`${API_URL_MASTERDATA}/wallet/list`, {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'Wallets.name',
order_direction: 'ASC'
});
if (response?.status && response?.data) {
setWallets(response.data.list);
}
} catch (error) {
console.error('Error fetching wallets', error);
}
};
getWalletList();
}, [showEditDialog, GetData]);
useEffect(() => {
if (!showEditDialog || !selectedTransferType) return;
const fetchTransactionType = async () => {
try {
const response = await GetData(
`${API_URL}/transactiontype/getdata/${selectedTransferType}`,
{}
);
// console.log(response);
if (response?.status) {
let permissionIds: string[] = [];
if (Array.isArray(response.data.permission)) {
permissionIds = response.data.permission.map((perm: any) => {
if (typeof perm === 'object' && perm !== null) {
return perm.id;
}
return perm;
});
}
setFormField((prev) => ({
...prev,
name: response.data.name,
description: response.data.description,
wallet_origin: response.data.wallet_origin?.id || '',
wallet_destination: response.data.wallet_destination?.id || '',
minimum_amount: response.data.minimum_amount,
maximum_amount: response.data.maximum_amount,
max_transaction_per_day: response.data.max_transaction_per_day,
status_approval: response.data.status_approval,
type: response.data.type || '',
status: response.data.status,
permission: permissionIds
}));
}
} catch (error) {
console.error('Error fetching transaction type', error);
setAlert({
show: true,
message: 'Failed to load transaction type data'
});
}
};
const timer = setTimeout(() => {
fetchTransactionType();
}, 150);
return () => clearTimeout(timer);
}, [showEditDialog, selectedTransferType, GetData]);
useEffect(() => {
if (showEditDialog === false) {
resetForm();
}
}, [selectedTransferType, fetchTransactionType]);
}, [showEditDialog]);
return (
<Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
@ -305,9 +398,11 @@ const EditDialog = () => {
<DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
<div className="flex flex-col px-0">
{alert.show && (
<Alert variant="danger" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
<div className="sticky top-0 z-10 bg-white p-3">
<Alert variant="danger" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
</div>
)}
<form action="" onSubmit={handleSubmit}>
<div className="card-body grid gap-5 p-0">
@ -439,8 +534,8 @@ const EditDialog = () => {
</SelectTrigger>
<SelectContent>
{wallets.map((wallet) => (
<SelectItem value={wallet.Wallet_id} key={wallet.Wallet_id}>
{wallet.Wallet_name}
<SelectItem value={wallet.id} key={wallet.id}>
{wallet.name}
</SelectItem>
))}
</SelectContent>
@ -467,8 +562,8 @@ const EditDialog = () => {
</SelectTrigger>
<SelectContent>
{wallets.map((wallet) => (
<SelectItem value={wallet.Wallet_id} key={wallet.Wallet_id}>
{wallet.Wallet_name}
<SelectItem value={wallet.id} key={wallet.id}>
{wallet.name}
</SelectItem>
))}
</SelectContent>
@ -476,91 +571,11 @@ const EditDialog = () => {
</div>
</div>
</div>
<div className="w-full">
<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">
Wallet Destination Fee
<span className="text-red-500">*</span>
</label>
<div className="grow">
<Select
value={formField.wallet_fee_destination}
onValueChange={(wallet_fee_destination) =>
setFormField((prev) => ({ ...prev, wallet_fee_destination }))
}
>
<SelectTrigger>
<SelectValue placeholder="Select Wallet" />
</SelectTrigger>
<SelectContent>
{wallets.map((wallet) => (
<SelectItem value={wallet.Wallet_id} key={wallet.Wallet_id}>
{wallet.Wallet_name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="w-full">
<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">
Customer Fee Destination<span className="text-red-500">*</span>
</label>
<div className="grow">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
className="input col-span-5 text-left"
style={{ color: 'inherit' }}
>
{customers.find(
(customer) => customer.id === formField.customer_fee_destination
)?.username || 'Select Customer'}
</button>
</PopoverTrigger>
<PopoverContent className="w-[400px] p-0">
<Command>
<CommandInput placeholder="Search Customer..." />
<CommandList
className="max-h-[300px] overflow-y-auto"
style={{ touchAction: 'pan-y' }}
onWheel={(e) => {
e.currentTarget.scrollTop += e.deltaY;
}}
>
<CommandEmpty>No Customer found.</CommandEmpty>
<CommandGroup>
{customers.map((customer) => (
<CommandItem
key={customer.id}
value={customer.username}
onSelect={() => {
setFormField({
...formField,
customer_fee_destination: customer.id
});
setOpen(false);
}}
>
{customer.username} - {customer.msisdn}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
</div>
</div>
<div className="w-full">
<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">
Type
Status Transaction Type
<span className="text-red-500"> *</span>
</label>
<div className="grow">
@ -576,12 +591,15 @@ const EditDialog = () => {
<SelectContent>
<SelectItem value="D">Disbursement </SelectItem>
<SelectItem value="O">Other </SelectItem>
<SelectItem value="CA">Change Customer to Agent </SelectItem>
<SelectItem value="AC">Change Agent to Customer </SelectItem>
<SelectItem value="CA">Change Group Emoney Customer to Agent </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="AD">Return Agent Deposit </SelectItem>
<SelectItem value="AM">Return Agent Merchant </SelectItem>
<SelectItem value="AE">Return Agent Emoney </SelectItem>
<SelectItem value="R">Reward Point </SelectItem>
</SelectContent>
</Select>
</div>
@ -638,30 +656,59 @@ const EditDialog = () => {
</div>
</div>
<div className="w-full">
<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">
Groups
<span className="text-red-500">*</span>
</label>
<div className="relative w-full">
<Input
type="text"
placeholder="No groups selected"
value={selectedPermissionNames || ''}
readOnly
className="bg-gray-100 mb-2"
/>
<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">
{groups.map((group) => (
<div key={group.id} className="flex items-center space-x-2">
<Checkbox
id={`group-${group.id}`}
checked={formField.permission.includes(group.id)}
onCheckedChange={() => handleGroupChange(group.id)}
/>
<label
htmlFor={`group-${group.id}`}
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
{group.name}
</label>
</div>
))}
</div>
</div>
</div>
</div>
</div>
<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}>
{isSubmitting ? 'Saving...' : 'Save Changes'}
</Button>
</div>
</div>
</form>
{/* Transaction Fee Section */}
<ManageTransferFeeContextProvider>
<ManageTransferFeeContextProvider transactionTypeId={selectedTransferType}>
<Container>
<div className="grid gap-5 lg:gap-7.5 mt-5">
<DataGridInner />
</div>
<AddFeeDialog />
<DeleteFeeDialog />
<EditFeeDialog />
</Container>
</ManageTransferFeeContextProvider>
</div>
@ -671,4 +718,4 @@ const EditDialog = () => {
);
};
export { EditDialog };
export { EditDialog };

View File

@ -76,6 +76,16 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.id,
id: 'id',
header: ({ column }) => (
<DataGridColumnHeader title="Transaction Type ID" column={column} />
),
enableSorting: false,
enableHiding: false,
meta: { headerClassName: 'w-[250px]' }
},
{
accessorFn: (row) => row.name,
id: 'name',
@ -137,12 +147,28 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
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',
header: ({ column }) => (
<DataGridColumnHeader title="TransactionType Status" column={column} />
<DataGridColumnHeader title="Status Transaction Type" column={column} />
),
enableSorting: false,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[250px]' }
},
@ -191,20 +217,19 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
],
[handleEditDialog, handleDeleteDialog]
);
const doGetTransferTypeListData = async (
page: number,
limit: number,
sorting: any,
filter: any
) => {
const orderField = 'created_at';
const orderDirection = sorting.length > 0 ? (sorting[0].desc ? 'DESC' : 'ASC') : 'DESC';
filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
const response = await GetData(`${API_URL}/transactiontype/list`, {
limit: limit,
page: page + 1,
@ -213,7 +238,7 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
order_direction: orderDirection,
filter: JSON.stringify(filter)
});
// console.log(response?.data.list);
return { data: response?.data.list, totalCount: response?.data.total_count };
};
@ -240,7 +265,7 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
pagination={{ size: 10 }}
layout={{ card: true }}
toolbar={<ListToolbar />}
sorting={[{ id: 'created_at', desc: true }]} // Default sorting
sorting={[{ id: 'created_at', desc: true }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
doGetTransferTypeListData(pageIndex, pageSize, sorting, columnFilters)
@ -255,4 +280,4 @@ const ManageTransferTypeContextProvider = ({ children }: { children: React.React
};
export { ManageTransferTypeContext, ManageTransferTypeContextProvider };
export type { TransferType };
export type { TransferType };