withdraw saldo
This commit is contained in:
359
src/pages/transaction/withdrawl-saldo/TransactionWithdraw.tsx
Normal file
359
src/pages/transaction/withdrawl-saldo/TransactionWithdraw.tsx
Normal file
@ -0,0 +1,359 @@
|
||||
import { Alert, Container, DataGridInner } from '@/components';
|
||||
import { TransactionWithdrawProvider } from './hooks/TransactionWithdrawContext';
|
||||
import { Breadcrumbs, Link } from '@mui/material';
|
||||
import { Helmet } from 'react-helmet';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useCallApi } from '@/hooks';
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import { toast } from 'sonner';
|
||||
import { getAuth } from '@/auth';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
|
||||
const TransactionWithdraw = () => {
|
||||
const initialForm: {
|
||||
msisdn: string;
|
||||
amount: string;
|
||||
pin: string;
|
||||
purpose: string;
|
||||
} = {
|
||||
msisdn: '',
|
||||
amount: '',
|
||||
pin: '',
|
||||
purpose: ''
|
||||
};
|
||||
|
||||
const [form, setForm] = useState(initialForm);
|
||||
const [wallets, setWallets] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [customerMsisdn, setCustomerMsisdn] = useState<{ value: string; label: string }[]>([]);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [dropdownOpen, setDropdownOpen] = useState(false);
|
||||
const { GetData, PostData } = useCallApi();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [showConfirmation, setShowConfirmation] = useState(false);
|
||||
const parsedUser = getAuth()?.user;
|
||||
const API_URL = apiConfig.transaction;
|
||||
const API_URL_WALLET = apiConfig.service_wallet;
|
||||
const API_URL_CUSTOMER = apiConfig.service_customer;
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [alert, setAlert] = useState({
|
||||
show: false,
|
||||
message: ''
|
||||
});
|
||||
|
||||
const fetchWallets = async () => {
|
||||
try {
|
||||
const response = await GetData(
|
||||
`${API_URL_WALLET}/dashboard/balance/account/${parsedUser.customer.id}`,
|
||||
{}
|
||||
);
|
||||
if (response?.status === true) {
|
||||
setWallets(response.data || []);
|
||||
} else {
|
||||
toast.warning(response?.message || 'Failed to fetch wallet data');
|
||||
}
|
||||
} catch (error) {
|
||||
toast.warning('Failed to fetch wallet data');
|
||||
}
|
||||
};
|
||||
|
||||
const fetchCustomerMsisdn = async (sorting: any, filterValue: string) => {
|
||||
const filter: any =
|
||||
filterValue.trim().length === 0
|
||||
? {}
|
||||
: {
|
||||
or: [
|
||||
{ msisdn: { like: `%${filterValue}%` } },
|
||||
{ fullname: { like: `%${filterValue}%` } }
|
||||
]
|
||||
};
|
||||
|
||||
const query: any = {
|
||||
limit: 100,
|
||||
page: 1,
|
||||
with_deleted: false,
|
||||
order_field: sorting[0].id,
|
||||
order_direction: sorting[0].desc ? 'DESC' : 'ASC'
|
||||
};
|
||||
|
||||
if (filter && Object.keys(filter).length > 0) {
|
||||
query.filter = JSON.stringify(filter);
|
||||
// query.page = page + 1;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, query);
|
||||
setCustomerMsisdn(
|
||||
response?.data.list.map((item: any) => ({
|
||||
value: item.msisdn,
|
||||
label: `${item.msisdn} - ${item.fullname}`
|
||||
}))
|
||||
);
|
||||
} catch (error) {
|
||||
toast.error('Failed to fetch customer msisdn');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const doPostData = async (form: typeof initialForm) => {
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
let response = await PostData(`${API_URL}/transaction/transfer`, {
|
||||
msisdn_destination: form.msisdn,
|
||||
amount: form.amount,
|
||||
pin: form.pin,
|
||||
purpose: form.purpose,
|
||||
id_transaction_type: "20c8a690-dc02-463d-b391-324184d1fefa",
|
||||
id_origin_customer: getAuth()?.id
|
||||
});
|
||||
if (response?.status == true) {
|
||||
await fetchWallets();
|
||||
toast.success('Success Request Topup');
|
||||
} else {
|
||||
toast.error(`${response?.message?.message}`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
const errorMessage =
|
||||
error?.response?.data?.message || error?.message || 'Something went wrong';
|
||||
toast.error(errorMessage);
|
||||
setAlert({ show: true, message: errorMessage });
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
setShowConfirmation(false);
|
||||
ResetForm();
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (form.amount == '' || form.msisdn == '' || form.pin == '') {
|
||||
setAlert({
|
||||
show: true,
|
||||
message: 'Please fill in all required fields.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
setAlert({ show: false, message: '' });
|
||||
setShowConfirmation(true);
|
||||
// TODO: Kirim ke backend atau proses lainnya
|
||||
};
|
||||
|
||||
const ResetForm = () => {
|
||||
setForm(initialForm);
|
||||
setAlert({ show: false, message: '' });
|
||||
setSearchTerm('');
|
||||
};
|
||||
|
||||
const handleCancelSubmit = () => {
|
||||
setShowConfirmation(false);
|
||||
};
|
||||
|
||||
const handleMsisdnSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setIsLoading(true);
|
||||
setSearchTerm(e.target.value);
|
||||
setDropdownOpen(true);
|
||||
const timer = setTimeout(() => {
|
||||
fetchCustomerMsisdn([{ id: 'msisdn', desc: false }], e.target.value);
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
};
|
||||
|
||||
const handleMsisdnSelect = (msisdn: string) => {
|
||||
setForm({ ...form, msisdn });
|
||||
setDropdownOpen(false);
|
||||
setSearchTerm(msisdn);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchWallets();
|
||||
fetchCustomerMsisdn([{ id: 'msisdn', desc: false }], '');
|
||||
|
||||
const handleClickOutside = (event: any) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
|
||||
setDropdownOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const filteredMsisdn = customerMsisdn
|
||||
.filter((item) => item.label.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
.slice(0, 10);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
<title>TPAY | Transaction Withdraw Saldo</title>
|
||||
</Helmet>
|
||||
<TransactionWithdrawProvider>
|
||||
<Container className="mb-7">
|
||||
<h1 className="text-xl font-medium leading-none text-gray-900 mb-5">
|
||||
MANAGE TRANSACTION WITHDRAW SALDO
|
||||
</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">Transaction</span>
|
||||
</Link>
|
||||
<Link underline="none" color="inherit">
|
||||
<span className="text-sm">Withdraw Saldo</span>
|
||||
</Link>
|
||||
</Breadcrumbs>
|
||||
{/* Wallet Section */}
|
||||
<div className="mb-6">
|
||||
<h2 className="text-md font-semibold text-gray-700 mb-3">Your Wallets</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
{wallets.map((wallet: any) => (
|
||||
<div key={wallet.id_wallet} className="border rounded-lg p-4 bg-white">
|
||||
<p className="text-sm text-gray-500">{wallet.wallet}</p>
|
||||
<p className="text-lg font-semibold text-green-600">
|
||||
{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(
|
||||
wallet.amount
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Container className="flex items-center justify-center">
|
||||
<div className="card max-w-[750px] w-full">
|
||||
<div className="card-body p-10">
|
||||
{alert.show && (
|
||||
<Alert variant="danger">
|
||||
<h3>{alert.message}</h3>
|
||||
</Alert>
|
||||
)}
|
||||
{/* form */}
|
||||
<form onSubmit={handleSubmit} className="space-y-6 mt-5">
|
||||
<div className="relative" ref={dropdownRef}>
|
||||
<label htmlFor="msisdn">MSISDN (Phone Number)</label>
|
||||
<span className="text-red-500">*</span>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="msisdn"
|
||||
type="text"
|
||||
value={searchTerm}
|
||||
onChange={handleMsisdnSearch}
|
||||
placeholder="Search MSISDN"
|
||||
onClick={() => setDropdownOpen(true)}
|
||||
/>
|
||||
{dropdownOpen && (
|
||||
<div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto">
|
||||
{filteredMsisdn.length > 0 ? (
|
||||
filteredMsisdn.map((item, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
|
||||
onClick={() => handleMsisdnSelect(item.value)}
|
||||
>
|
||||
{item.label}
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="px-4 py-2 text-gray-500">
|
||||
{isLoading ? 'Loading...' : 'No results found'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="amount">Amount</label>
|
||||
<span className="text-red-500">*</span>
|
||||
<Input
|
||||
id="topupAmount"
|
||||
type="number"
|
||||
min={0}
|
||||
value={form.amount}
|
||||
onChange={(e) => {
|
||||
const value = Number(e.target.value);
|
||||
if (value >= 0) {
|
||||
setForm({ ...form, amount: String(value) });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="pin">PIN</label>
|
||||
<span className="text-red-500">*</span>
|
||||
<Input
|
||||
id="pin"
|
||||
type="password"
|
||||
value={form.pin}
|
||||
onChange={(e) => setForm({ ...form, pin: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="pin">Purpose</label>
|
||||
<span className="text-red-500">*</span>
|
||||
<Input
|
||||
id="purpose"
|
||||
type="text"
|
||||
value={form.purpose}
|
||||
onChange={(e) => setForm({ ...form, purpose: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="button" onClick={handleSubmit}>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</Container>
|
||||
|
||||
{showConfirmation && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white p-6 rounded-lg shadow-lg max-w-md w-full">
|
||||
<h3 className="text-lg font-semibold mb-4">Confirm Transaction</h3>
|
||||
<p className="mb-6">
|
||||
Are you sure you want to withdraw saldo of{' '}
|
||||
<span className="font-semibold">
|
||||
{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(
|
||||
Number(form.amount)
|
||||
)}{' '}
|
||||
</span>
|
||||
?
|
||||
</p>
|
||||
<div className="flex justify-end space-x-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCancelSubmit}
|
||||
className="border-gray-300 text-gray-700"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={() => doPostData(form)} disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
|
||||
) : (
|
||||
'Confirm'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Container>
|
||||
</TransactionWithdrawProvider>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransactionWithdraw;
|
||||
61
src/pages/transaction/withdrawl-saldo/blocks/ListToolbar.tsx
Normal file
61
src/pages/transaction/withdrawl-saldo/blocks/ListToolbar.tsx
Normal 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;
|
||||
@ -0,0 +1,80 @@
|
||||
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';
|
||||
|
||||
interface TransactionWithdrawProps {
|
||||
id: string;
|
||||
customers_id: string;
|
||||
group_id: string;
|
||||
username: string;
|
||||
fullname: string;
|
||||
email: string;
|
||||
status: string;
|
||||
created_at: Date;
|
||||
}
|
||||
|
||||
interface ContextProps {
|
||||
|
||||
}
|
||||
|
||||
const initialProps: ContextProps = {
|
||||
|
||||
};
|
||||
|
||||
const TransactionWithdrawContext = 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 TransactionWithdrawProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
|
||||
return (
|
||||
<TransactionWithdrawContext.Provider
|
||||
value={{}}
|
||||
>
|
||||
<Toaster expand visibleToasts={9} duration={3000} />
|
||||
<div>
|
||||
{children}
|
||||
</div>
|
||||
</TransactionWithdrawContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export { TransactionWithdrawProvider, TransactionWithdrawContext };
|
||||
export type { TransactionWithdrawProps };
|
||||
2
src/pages/transaction/withdrawl-saldo/hooks/index.tsx
Normal file
2
src/pages/transaction/withdrawl-saldo/hooks/index.tsx
Normal file
@ -0,0 +1,2 @@
|
||||
export * from './TransactionWithdrawContext';
|
||||
export * from './useTransactionWithdrawContext';
|
||||
@ -0,0 +1,12 @@
|
||||
import { useContext } from 'react';
|
||||
import { TransactionWithdrawContext } from './TransactionWithdrawContext';
|
||||
|
||||
const useTransactionWithdrawContext = () => {
|
||||
const context = useContext(TransactionWithdrawContext);
|
||||
|
||||
if (!context) throw new Error('useTransactionWithdrawContext must be used within AuthProvider');
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export { useTransactionWithdrawContext };
|
||||
Reference in New Issue
Block a user