Merge branch 'master' of https://git.shiblysolution.id/TPAY/dashboard
This commit is contained in:
@ -20,6 +20,9 @@ import BalanceCard from './blocks/BalanceCard';
|
||||
import { getAuth } from '@/auth';
|
||||
import { useCallApi } from '@/hooks';
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import TransactionValue from './blocks/TransactionValue';
|
||||
import TransactionPieChart from './blocks/TransactionPieChart';
|
||||
import MemberActivity from './blocks/MemberActivity';
|
||||
|
||||
// sum -> nominal, count-> total
|
||||
type CountType = 'sum' | 'count';
|
||||
@ -37,6 +40,98 @@ const DashboardHomePage = () => {
|
||||
from: new Date(),
|
||||
to: new Date()
|
||||
});
|
||||
|
||||
const getFirstDayOfMonth = () => {
|
||||
const now = new Date();
|
||||
return new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
};
|
||||
|
||||
const getToday = () => {
|
||||
return new Date();
|
||||
};
|
||||
|
||||
const [fromDate, setFromDate] = useState(getFirstDayOfMonth());
|
||||
const [toDate, setToDate] = useState(getToday());
|
||||
|
||||
|
||||
const API_URL = apiConfig.api_dashboard;
|
||||
const { GetData } = useCallApi();
|
||||
|
||||
const [responseStatisticCard, setResponseStatisticCard] = useState<any>(null);
|
||||
|
||||
const fetchData = async () => {
|
||||
const res = await GetData(`${API_URL}/card-statistic`, {});
|
||||
setResponseStatisticCard(res);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const [responseGraphic, setresponseGraphic] = useState<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchDataGraphic = async () => {
|
||||
const res = await GetData(`${API_URL}/cashin-vs-cashout`, {
|
||||
date_from: fromDate.toISOString(),
|
||||
date_to: toDate.toISOString()
|
||||
});
|
||||
setresponseGraphic(res);
|
||||
};
|
||||
|
||||
fetchDataGraphic();
|
||||
}, [fromDate, toDate]);
|
||||
|
||||
let staticChartDataApiFetch = [];
|
||||
|
||||
// Make map for date => { cashin: 0, cashout: 0 }
|
||||
const dataMap: Record<string, { cashin: number; cashout: number }> = {};
|
||||
const current = moment(fromDate);
|
||||
const end = moment(toDate);
|
||||
|
||||
// Inisialization dataMap with all dates
|
||||
while (current.isSameOrBefore(end, 'day')) {
|
||||
const dateStr = current.format('DD-MM-YYYY');
|
||||
dataMap[dateStr] = { cashin: 0, cashout: 0 };
|
||||
current.add(1, 'day');
|
||||
}
|
||||
|
||||
// Add cashin
|
||||
if (Array.isArray(responseGraphic?.data.total_cashin)) {
|
||||
responseGraphic.data.total_cashin.forEach((item: any) => {
|
||||
const date = moment(item.created_date).format('DD-MM-YYYY');
|
||||
// Only update cashin if it's not already set (meaning no value was added before)
|
||||
if (dataMap[date]) {
|
||||
dataMap[date].cashin = Number(item.total_count ?? 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Add cashout
|
||||
if (Array.isArray(responseGraphic?.data.total_cashout)) {
|
||||
responseGraphic.data.total_cashout.forEach((item: any) => {
|
||||
const date = moment(item.created_date).format('DD-MM-YYYY');
|
||||
// Only update cashout if it's not already set (meaning no value was added before)
|
||||
if (dataMap[date]) {
|
||||
dataMap[date].cashout = Number(item.total_count ?? 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Change to array for chart
|
||||
staticChartDataApiFetch = Object.entries(dataMap).map(([month, values]) => ({
|
||||
month,
|
||||
cashin: values.cashin,
|
||||
cashout: values.cashout
|
||||
}));
|
||||
|
||||
// Change to array for chart
|
||||
staticChartDataApiFetch = Object.entries(dataMap).map(([month, values]) => ({
|
||||
month,
|
||||
cashin: values.cashin,
|
||||
cashout: values.cashout
|
||||
}));
|
||||
|
||||
const currentRole = getAuth()?.role_name;
|
||||
const idCustomer = getAuth()?.user.customer?.id;
|
||||
// console.log(currentRole);
|
||||
@ -85,21 +180,15 @@ const DashboardHomePage = () => {
|
||||
setChartLegend(value);
|
||||
};
|
||||
|
||||
// const handleFilter = useCallback(
|
||||
// (date: DateRange | undefined) => {
|
||||
// setDateRange({
|
||||
// from: date?.from ?? moment(`${selectedYear}-01-01`, 'YYYY-MM-DD').toDate(),
|
||||
// to: date?.to ?? moment(`${selectedYear}-12-31`, 'YYYY-MM-DD').toDate()
|
||||
// });
|
||||
// },
|
||||
// [selectedYear]
|
||||
// );
|
||||
|
||||
const resetFilter = useCallback(() => {
|
||||
setDateRange({
|
||||
from: moment(`${initialYear}-01-01`, 'YYYY-MM-DD').toDate(),
|
||||
to: moment(`${initialYear}-12-31`, 'YYYY-MM-DD').toDate()
|
||||
});
|
||||
const firstDay = getFirstDayOfMonth();
|
||||
const today = getToday();
|
||||
|
||||
setFromDate(firstDay);
|
||||
setToDate(today);
|
||||
|
||||
// reset filter yang lain kalau perlu
|
||||
setDateRange({ from: firstDay, to: today });
|
||||
setSelectedYear(initialYear);
|
||||
setCount('sum');
|
||||
setChartType('line');
|
||||
@ -158,24 +247,76 @@ const DashboardHomePage = () => {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex gap-3 items-center mb-6">
|
||||
<YearPicker selectedYear={selectedYear} setSelectedYear={handleYearChange} />
|
||||
<div className="w-auto min-w-[120px]">
|
||||
<Select value={count} onValueChange={handleCountType}>
|
||||
<SelectTrigger size="sm">
|
||||
<SelectValue placeholder="Select Count Type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="w-32">
|
||||
<SelectItem value="sum">Nominal</SelectItem>
|
||||
<SelectItem value="count">Status</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{/* Cards */}
|
||||
<div className="flex gap-6 overflow-x-auto pb-2">
|
||||
<Card
|
||||
title="Registered Users"
|
||||
total={responseStatisticCard?.data.total_registered ?? 0}
|
||||
growth={responseStatisticCard?.data.registered_last_week.percent ?? 0}
|
||||
surplus={responseStatisticCard?.data.registered_last_week.surplus ?? false}
|
||||
icon="test"
|
||||
/>
|
||||
<Card
|
||||
title="Unregistered Users"
|
||||
total={responseStatisticCard?.data.total_unregistered ?? 0}
|
||||
growth={responseStatisticCard?.data.unregistered_last_week.percent ?? 0}
|
||||
surplus={responseStatisticCard?.data.unregistered_last_week.surplus ?? false}
|
||||
icon="test"
|
||||
|
||||
/>
|
||||
<Card
|
||||
title="Total Cash-in"
|
||||
total={responseStatisticCard?.data.total_cash_in ?? 0}
|
||||
growth={responseStatisticCard?.data.cash_in_last_week.percent ?? 0}
|
||||
surplus={responseStatisticCard?.data.cash_in_last_week.surplus ?? false}
|
||||
icon="test"
|
||||
/>
|
||||
<Card
|
||||
title="Total Cash-out"
|
||||
total={responseStatisticCard?.data.total_cash_out ?? 0}
|
||||
growth={responseStatisticCard?.data.cash_out_last_week.percent ?? 0}
|
||||
surplus={responseStatisticCard?.data.cash_out_last_week.surplus ?? false}
|
||||
icon="test"
|
||||
/>
|
||||
<Card
|
||||
title="Active Event"
|
||||
total={responseStatisticCard?.data.total_event ?? 0}
|
||||
growth={responseStatisticCard?.data.event_last_week.percent ?? 0}
|
||||
surplus={responseStatisticCard?.data.event_last_week.surplus ?? false}
|
||||
icon="test"
|
||||
/>
|
||||
<Card
|
||||
title="Total Billing"
|
||||
total={responseStatisticCard?.data.total_billing ?? 0}
|
||||
growth={responseStatisticCard?.data.billing_last_week.percent ?? 0}
|
||||
surplus={responseStatisticCard?.data.billing_last_week.surplus ?? false}
|
||||
icon='test'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 items-center mb-6 mt-6">
|
||||
<div className="flex gap-3 items-center w-full md:w-auto">
|
||||
<label className="input input-sm w-[160px]">
|
||||
From
|
||||
<input
|
||||
type="date"
|
||||
name="from"
|
||||
value={moment(fromDate).format('YYYY-MM-DD')}
|
||||
onChange={(e) => setFromDate(new Date(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="input input-sm w-[160px]">
|
||||
To
|
||||
<input
|
||||
type="date"
|
||||
name="to"
|
||||
value={moment(toDate).format('YYYY-MM-DD')}
|
||||
onChange={(e) => setToDate(new Date(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{/* <DefaultTooltip title="Filter" placement="top">
|
||||
<Button variant="outline" className="h-7.5" onClick={() => handleFilter(dateRange)}>
|
||||
<KeenIcon icon="filter" />
|
||||
</Button>
|
||||
</DefaultTooltip> */}
|
||||
|
||||
<DefaultTooltip title="Reset Filter" placement="top">
|
||||
<Button variant="outline" className="h-7.5" onClick={resetFilter}>
|
||||
<KeenIcon icon="arrow-circle-left" />
|
||||
@ -183,37 +324,29 @@ const DashboardHomePage = () => {
|
||||
</DefaultTooltip>
|
||||
</div>
|
||||
|
||||
{/* Cards */}
|
||||
<div className="grid gap-5 lg:gap-7.5 mb-5">
|
||||
<div className="grid lg:grid-cols-4 gap-y-5 lg:gap-5 items-stretch">
|
||||
{cardData.map((data: any) => (
|
||||
<div className="lg:col-span-1" key={data.type}>
|
||||
<Card
|
||||
title={data.type.toUpperCase()}
|
||||
total={data.total}
|
||||
type={data.type}
|
||||
count={count}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chart */}
|
||||
<div className="grid gap-5 lg:gap-7.5">
|
||||
<div className="grid gap-5 lg:gap-7.5 mt-5">
|
||||
<div className="grid lg:grid-cols-1 gap-y-5 lg:gap-5 items-stretch">
|
||||
<div className="lg:col-span-1">
|
||||
<Chart
|
||||
title="Overview"
|
||||
count={12}
|
||||
toolbar={toolbar}
|
||||
chartData={staticChartData.series.map((data: any) => data.data)}
|
||||
chartData={staticChartDataApiFetch}
|
||||
chartType={chartType}
|
||||
chartLegend={chartLegend}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-4 mt-5">
|
||||
<TransactionValue startdate={fromDate.toISOString()} enddate={toDate.toISOString()} />
|
||||
<TransactionPieChart startdate={fromDate.toISOString()} enddate={toDate.toISOString()} />
|
||||
<MemberActivity startdate={fromDate.toISOString()} enddate={toDate.toISOString()} />
|
||||
</div>
|
||||
|
||||
</Container>
|
||||
</>
|
||||
);
|
||||
|
||||
@ -4,46 +4,31 @@ import { toAbsoluteUrl } from '@/utils/Assets';
|
||||
|
||||
interface CardDataProduct {
|
||||
title: string;
|
||||
total: string;
|
||||
type: Array<{ label: string; value: string; total: string }>;
|
||||
count: 'sum' | 'count';
|
||||
total: number;
|
||||
growth: number;
|
||||
surplus: boolean;
|
||||
icon: string;
|
||||
}
|
||||
|
||||
const Card = ({ title, total, type, count }: CardDataProduct) => {
|
||||
const Card = ({ title, total, growth, surplus,icon }: CardDataProduct) => {
|
||||
const { isRTL } = useLanguage();
|
||||
|
||||
return (
|
||||
<div className="card h-full bg-[length:85%] bg-[length:85%] [background-position:9rem_-4rem] rtl:[background-position:-4rem_-4rem] bg-no-repeat channel-stats-bg">
|
||||
<div className="card h-full w-full bg-[length:85%] [background-position:9rem_-4rem] rtl:[background-position:-4rem_-4rem] bg-no-repeat channel-stats-bg">
|
||||
<div className="card-body flex flex-col gap-4 p-5 lg:p-b-7.5 lg:pt-4">
|
||||
<div className="flex justify-between">
|
||||
<div className="flex flex-col w-8/12" style={{ background: '' }}>
|
||||
<div className="flex flex-col w-full">
|
||||
<span className="text-sm font-normal text-gray-600 mb-5">{title}</span>
|
||||
<span className="text-3xl font-semibold text-gray-900 mb-0">
|
||||
{count === 'sum' ? fCurrency(total) : total}
|
||||
<span className="text-3xl font-semibold text-gray-900 mb-0">{total}</span>
|
||||
<span
|
||||
className={`text-sm font-semibold mt-2 flex items-center gap-1 ${
|
||||
surplus ? 'text-green-500' : 'text-red-500'
|
||||
}`}
|
||||
>
|
||||
{surplus ? '▲' : '▼'} {growth} % From Last Week
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col w-4/12 justify-between" style={{ background: '' }}>
|
||||
<img
|
||||
src={toAbsoluteUrl('/media/file-types/chart.svg')}
|
||||
className="dark:hidden h-5 h-8"
|
||||
alt="Chart Icon"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* <hr className="" />
|
||||
<div className="">
|
||||
{type.map((data: any, index: number) => (
|
||||
<div key={data.label}>
|
||||
<div className="flex justify-between mb-1">
|
||||
<div className="w-8/12 text-sm">{data.label}</div>
|
||||
<div className="w-4/12 text-sm text-end">
|
||||
{count === 'sum' ? fCurrency(data.total) : data.total}{' '}
|
||||
</div>
|
||||
</div>
|
||||
{index !== type.length - 1 && <hr className="border-dashed my-2" />}
|
||||
</div>
|
||||
))}
|
||||
</div> */}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
114
src/pages/dashboards/home/blocks/MemberActivity.tsx
Normal file
114
src/pages/dashboards/home/blocks/MemberActivity.tsx
Normal file
@ -0,0 +1,114 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { UsersIcon, UserCheckIcon } from "lucide-react";
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import { useCallApi } from '@/hooks';
|
||||
|
||||
const API_URL = apiConfig.api_dashboard;
|
||||
|
||||
interface Props {
|
||||
startdate: string;
|
||||
enddate: string;
|
||||
}
|
||||
|
||||
const MemberActivity = ({ startdate, enddate }: Props) => {
|
||||
const { GetData } = useCallApi();
|
||||
const [responseTransactionValue, setResponseTransactionValue] = useState<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchDataTransactionValue = async () => {
|
||||
try {
|
||||
const res = await GetData(`${API_URL}/active-user`, {
|
||||
date_from: startdate,
|
||||
date_to: enddate,
|
||||
});
|
||||
setResponseTransactionValue(res);
|
||||
} catch (error) {
|
||||
console.error('Error fetching transaction value:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchDataTransactionValue();
|
||||
}, [startdate, enddate, GetData]);
|
||||
|
||||
const percentage = parseFloat((responseTransactionValue?.data?.total_customer_active_percentage ?? 0).toFixed(2)) ?? 0;
|
||||
const totalCustomer = responseTransactionValue?.data?.total_customer ?? 0;
|
||||
const activeCustomer = responseTransactionValue?.data?.total_customer_active ?? 0;
|
||||
|
||||
// Hitung sudut pointer
|
||||
const angle = (percentage / 100) * 180; // 0° (kiri) ke 180° (kanan)
|
||||
const radians = (angle * Math.PI) / 180;
|
||||
const radius = 40; // Radius dari setengah lingkaran
|
||||
const center = 50; // Titik pusat lingkaran
|
||||
const pointerLength = 25; // Panjang pointer
|
||||
|
||||
const x = center + pointerLength * Math.cos(radians - Math.PI); // offset agar mulai dari kiri
|
||||
const y = center + pointerLength * Math.sin(radians - Math.PI);
|
||||
|
||||
// Hitung titik akhir untuk arc aktif
|
||||
const arcAngle = (Math.PI * percentage) / 100;
|
||||
const arcX = 50 + radius * Math.cos(Math.PI - arcAngle);
|
||||
const arcY = 50 - radius * Math.sin(arcAngle);
|
||||
|
||||
return (
|
||||
<div className="p-6 bg-white rounded-lg shadow-md w-full max-w-xl">
|
||||
<div className="flex justify-between items-center pb-3 mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-700">Member Activity</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-6">
|
||||
{/* Sidebar */}
|
||||
<ul className="space-y-4 w-1/2 text-gray-700 text-sm">
|
||||
<li className="flex items-center gap-2">
|
||||
<UsersIcon className="w-4 h-4" />
|
||||
<span>Total Customer: {totalCustomer}</span>
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<UserCheckIcon className="w-4 h-4" />
|
||||
<span>Active Customer: {activeCustomer}</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
{/* Gauge Chart */}
|
||||
<div className="w-1/2">
|
||||
<div className="border border-gray-200 rounded-md p-4 text-center">
|
||||
<h3 className="text-sm text-gray-600 font-medium mb-2">Active User</h3>
|
||||
<div className="relative h-24 w-full">
|
||||
<svg className="w-full h-full" viewBox="0 0 100 50">
|
||||
{/* Background arc */}
|
||||
<path
|
||||
d="M 10 50 A 40 40 0 0 1 90 50"
|
||||
fill="none"
|
||||
stroke="#e5e7eb"
|
||||
strokeWidth="10"
|
||||
/>
|
||||
{/* Active arc */}
|
||||
<path
|
||||
d={`M 10 50 A 40 40 0 ${percentage > 50 ? 1 : 0} 1 ${arcX} ${arcY}`}
|
||||
fill="none"
|
||||
stroke="#34d399"
|
||||
strokeWidth="10"
|
||||
/>
|
||||
{/* Pointer */}
|
||||
<line
|
||||
x1="50"
|
||||
y1="50"
|
||||
x2={x}
|
||||
y2={y}
|
||||
stroke="#111827"
|
||||
strokeWidth="4"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
<div className="flex justify-between text-xs text-gray-500 px-1">
|
||||
<span>{percentage}%</span>
|
||||
<span>100%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MemberActivity;
|
||||
89
src/pages/dashboards/home/blocks/TransactionPieChart.tsx
Normal file
89
src/pages/dashboards/home/blocks/TransactionPieChart.tsx
Normal file
@ -0,0 +1,89 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
ResponsiveContainer,
|
||||
} from 'recharts';
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import { useCallApi } from '@/hooks';
|
||||
|
||||
const API_URL = apiConfig.api_dashboard;
|
||||
|
||||
interface Props {
|
||||
startdate: string;
|
||||
enddate: string;
|
||||
}
|
||||
|
||||
const TransactionPieChart = ({ startdate, enddate }: Props) => {
|
||||
|
||||
const { GetData } = useCallApi();
|
||||
const [responseTransactionValue, setResponseTransactionValue] = useState<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchDataTransactionValue = async () => {
|
||||
try {
|
||||
const res = await GetData(`${API_URL}/transaction-chart`, {
|
||||
date_from: startdate,
|
||||
date_to: enddate,
|
||||
});
|
||||
setResponseTransactionValue(res);
|
||||
} catch (error) {
|
||||
console.error('Error fetching transaction value:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchDataTransactionValue();
|
||||
}, [startdate, enddate, GetData]);
|
||||
|
||||
const data = [
|
||||
{ name: 'Transfer', value: parseFloat((responseTransactionValue?.data?.T ?? 0).toFixed(2)), color: '#3490dc' },
|
||||
{ name: 'Return', value: parseFloat((responseTransactionValue?.data?.R ?? 0).toFixed(2)), color: '#a0aec0' },
|
||||
{ name: 'Topup', value: parseFloat((responseTransactionValue?.data?.U ?? 0).toFixed(2)), color: '#9f7aea' },
|
||||
{ name: 'Purchase', value: parseFloat((responseTransactionValue?.data?.P ?? 0).toFixed(2)), color: '#baf7c5' },
|
||||
{ name: 'Withdraw', value: parseFloat((responseTransactionValue?.data?.W ?? 0).toFixed(2)), color: '#f56565' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow-md p-6 w-full max-w-md">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-700">Transaction Chart</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-6">
|
||||
<div className="w-40 h-40">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={data}
|
||||
dataKey="value"
|
||||
innerRadius={40}
|
||||
outerRadius={60}
|
||||
paddingAngle={3}
|
||||
>
|
||||
{data.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
<div className="text-sm space-y-2">
|
||||
<div className="font-semibold text-gray-500">Active Transaction</div>
|
||||
{data.map((entry, index) => (
|
||||
<div key={index} className="flex items-center justify-between w-48">
|
||||
<div className="flex items-center">
|
||||
<div className="w-3 h-3 rounded-full mr-2" style={{ backgroundColor: entry.color }}></div>
|
||||
<span className="text-gray-700">{entry.name}</span>
|
||||
</div>
|
||||
<span className="text-gray-700">{entry.value}%</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransactionPieChart;
|
||||
110
src/pages/dashboards/home/blocks/TransactionValue.tsx
Normal file
110
src/pages/dashboards/home/blocks/TransactionValue.tsx
Normal file
@ -0,0 +1,110 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import { useCallApi } from '@/hooks';
|
||||
|
||||
const API_URL = apiConfig.api_dashboard;
|
||||
|
||||
interface Props {
|
||||
startdate: string;
|
||||
enddate: string;
|
||||
}
|
||||
|
||||
const TransactionValue = ({ startdate, enddate }: Props) => {
|
||||
const { GetData } = useCallApi();
|
||||
const [responseTransactionValue, setResponseTransactionValue] = useState<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchDataTransactionValue = async () => {
|
||||
try {
|
||||
const res = await GetData(`${API_URL}/transaction-value`, {
|
||||
date_from: startdate,
|
||||
date_to: enddate,
|
||||
});
|
||||
setResponseTransactionValue(res);
|
||||
} catch (error) {
|
||||
console.error('Error fetching transaction value:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchDataTransactionValue();
|
||||
}, [startdate, enddate, GetData]);
|
||||
|
||||
let transactionData: any[] = [];
|
||||
if (responseTransactionValue?.data?.length > 0) {
|
||||
for (let i = 0; i < responseTransactionValue.data.length; i++) {
|
||||
let type = "";
|
||||
let unit = "";
|
||||
|
||||
const amount = responseTransactionValue.data[i].total_amount;
|
||||
|
||||
if (amount >= 1000 && amount < 1000000) {
|
||||
unit = "K";
|
||||
} else if (amount >= 1000000 && amount < 1000000000) {
|
||||
unit = "M";
|
||||
} else if (amount >= 1000000000) {
|
||||
unit = "B";
|
||||
}
|
||||
|
||||
switch (responseTransactionValue.data[i].kind) {
|
||||
case "P":
|
||||
type = "Purchase";
|
||||
break;
|
||||
case "T":
|
||||
type = "Transfer";
|
||||
break;
|
||||
case "U":
|
||||
type = "Top Up";
|
||||
break;
|
||||
case "W":
|
||||
type = "Withdraw";
|
||||
break;
|
||||
case "R":
|
||||
type = "Return";
|
||||
break;
|
||||
default:
|
||||
type = "Unknown";
|
||||
break;
|
||||
}
|
||||
|
||||
transactionData.push({
|
||||
label: type,
|
||||
value: amount,
|
||||
unit: unit
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const maxValue = transactionData.length > 0 ? Math.max(...transactionData.map(item => item.value)) : 1;
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-xl shadow p-6 w-full max-w-md">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-800">Transaction Value</h2>
|
||||
</div>
|
||||
{transactionData.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{transactionData.map((item, index) => (
|
||||
<div key={index} className="flex items-center justify-between">
|
||||
<span className="w-24 text-sm text-gray-700">{item.label}</span>
|
||||
<div className="flex-1 mx-2">
|
||||
<div className="w-full h-3 bg-gray-200 rounded-full">
|
||||
<div
|
||||
className="h-3 bg-teal-500 rounded-full"
|
||||
style={{ width: `${(item.value / maxValue) * 100}%` }}
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
<span className="w-14 text-right text-sm text-gray-700">{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(item.value)}{item.unit}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center text-sm text-gray-500 mt-4">
|
||||
No Data Available
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransactionValue;
|
||||
@ -248,7 +248,7 @@ const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
limit,
|
||||
page: page + 1,
|
||||
with_deleted: false,
|
||||
order_field: "id",
|
||||
order_field: "execution_date",
|
||||
order_direction: 'DESC',
|
||||
filter: JSON.stringify(formattedFilter)
|
||||
});
|
||||
@ -286,7 +286,7 @@ const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
pagination={{ size: 10 }}
|
||||
toolbar={<ListToolbar />}
|
||||
layout={{ card: true }}
|
||||
sorting={[{ id: 'id', desc: false }]}
|
||||
sorting={[{ id: 'execution_date', desc: false }]}
|
||||
serverSide={true}
|
||||
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
|
||||
getTransactionLists(pageIndex, pageSize, sorting, columnFilters)
|
||||
|
||||
@ -137,16 +137,16 @@ const ManageConversionContextProvider = ({ children }: { children: React.ReactNo
|
||||
>
|
||||
<KeenIcon icon="notepad-edit" />
|
||||
</button>
|
||||
<button
|
||||
{/* <button
|
||||
className="btn btn-sm btn-icon btn-clear btn-light"
|
||||
onClick={() => handleDeleteDialog(true, row.ID)}
|
||||
>
|
||||
<KeenIcon icon="trash" />
|
||||
</button>
|
||||
</button> */}
|
||||
</>
|
||||
);
|
||||
},
|
||||
meta: { headerClassName: 'w-[100px]', cellClassName: 'text-center' }
|
||||
meta: { headerClassName: 'w-[100px] text-center', cellClassName: 'text-center' }
|
||||
}
|
||||
],
|
||||
[handleEditDialog, handleDeleteDialog]
|
||||
|
||||
@ -124,16 +124,16 @@ const ManageCurrencyContextProvider = ({ children }: { children: React.ReactNode
|
||||
>
|
||||
<KeenIcon icon="notepad-edit" />
|
||||
</button>
|
||||
<button
|
||||
{/* <button
|
||||
className="btn btn-sm btn-icon btn-clear btn-light"
|
||||
onClick={() => handleDeleteDialog(true, row.ID)}
|
||||
>
|
||||
<KeenIcon icon="trash" />
|
||||
</button>
|
||||
</button> */}
|
||||
</>
|
||||
);
|
||||
},
|
||||
meta: { headerClassName: 'w-[100px]', cellClassName: 'text-center' }
|
||||
meta: { headerClassName: 'w-[100px] text-center', cellClassName: 'text-center' }
|
||||
}
|
||||
],
|
||||
[handleEditDialog, handleDeleteDialog]
|
||||
|
||||
@ -192,17 +192,17 @@ const ManageWalletRuleContextProvider = ({ children }: { children: React.ReactNo
|
||||
>
|
||||
<KeenIcon icon="notepad-edit" />
|
||||
</button>
|
||||
<button
|
||||
{/* <button
|
||||
className="btn btn-sm btn-icon btn-clear btn-light"
|
||||
onClick={() => handleDeleteDialog(true, row)}
|
||||
>
|
||||
<KeenIcon icon="trash" />
|
||||
</button>
|
||||
</button> */}
|
||||
</>
|
||||
);
|
||||
},
|
||||
meta: {
|
||||
headerClassName: 'w-[100px]',
|
||||
headerClassName: 'w-[100px] text-center',
|
||||
cellClassName: 'text-center'
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,17 +1,23 @@
|
||||
import { Container, DataGridInner } from '@/components';
|
||||
import { ManageFeedbackMemberProvider } from './hooks/ManageFeedbackMemberContext';
|
||||
import { ManageFeedbackMemberProvider } from './hooks/ManageFeedbackMemberContext';
|
||||
// import EditDialog from './blocks/EditDialog';
|
||||
// import DeleteDialog from './blocks/DeleteDialog';
|
||||
import { Breadcrumbs, Link } from '@mui/material';
|
||||
import { Helmet } from 'react-helmet';
|
||||
import FeedbackDetail from './blocks/FeedbackDetail';
|
||||
import EditDialog from './blocks/EditDialog';
|
||||
|
||||
const FeedbackMemberMaster = () => {
|
||||
return (
|
||||
<>
|
||||
<Helmet><title>TPAY | Manage Provider</title></Helmet>
|
||||
<Helmet>
|
||||
<title>TPAY | Manage Provider</title>
|
||||
</Helmet>
|
||||
<ManageFeedbackMemberProvider>
|
||||
<Container>
|
||||
<h1 className="text-xl font-medium leading-none text-gray-900 mb-3">Manage Feedback Member</h1>
|
||||
<h1 className="text-xl font-medium leading-none text-gray-900 mb-3">
|
||||
Manage Feedback Member
|
||||
</h1>
|
||||
<Breadcrumbs sx={{ mb: 2 }}>
|
||||
<Link underline="none" color="inherit" href="/">
|
||||
<span className="text-sm hover:underline">Dashboard</span>
|
||||
@ -28,9 +34,12 @@ const FeedbackMemberMaster = () => {
|
||||
<div className="grid gap-5 lg:gap-7.5">
|
||||
<DataGridInner />
|
||||
</div>
|
||||
<FeedbackDetail />
|
||||
<EditDialog />
|
||||
{/* <AddDialog />
|
||||
<EditDialog />
|
||||
<DeleteDialog /> */}
|
||||
{/* <FeedbackDetail/> */}
|
||||
</Container>
|
||||
</ManageFeedbackMemberProvider>
|
||||
</>
|
||||
|
||||
189
src/pages/members/feedback-member/blocks/EditDialog.tsx
Normal file
189
src/pages/members/feedback-member/blocks/EditDialog.tsx
Normal file
@ -0,0 +1,189 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select';
|
||||
import { useCallApi } from '@/hooks';
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import { getAuth } from '@/auth';
|
||||
import { useManageFeedbackContext } from '../hooks/useManageFeedbackMemberContext';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { toast } from 'sonner';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
const API_URL = apiConfig.service_feedback;
|
||||
|
||||
// Define status types
|
||||
type StatusCode = 'W' | 'N' | 'Y';
|
||||
|
||||
// Status display mapping for Select component
|
||||
const statusDisplayMap: Record<StatusCode, string> = {
|
||||
W: 'Waiting Follow Up',
|
||||
N: 'Rejected',
|
||||
Y: 'Accepted'
|
||||
};
|
||||
|
||||
const EditDialog = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { PutData, GetData } = useCallApi();
|
||||
const { handleEditDialog, showEditDialog, selectedFeedback, handleDetailDialog, refreshData } =
|
||||
useManageFeedbackContext();
|
||||
|
||||
const [reviewNotes, setReviewNotes] = useState('');
|
||||
const [status, setStatus] = useState<StatusCode>('Y'); // Default to Accepted
|
||||
|
||||
useEffect(() => {
|
||||
if (showEditDialog && selectedFeedback) {
|
||||
fetchFeedbackDetail();
|
||||
}
|
||||
}, [showEditDialog, selectedFeedback]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const username = getAuth()?.user.username;
|
||||
const payload = {
|
||||
review_by: username,
|
||||
review_notes: reviewNotes,
|
||||
status: status
|
||||
};
|
||||
|
||||
const response = await PutData(`${API_URL}/feedback/update/${selectedFeedback}`, payload);
|
||||
|
||||
if (response?.status) {
|
||||
toast.success('Feedback reviewed successfully');
|
||||
|
||||
// Close the edit dialog
|
||||
handleEditDialog(false, null);
|
||||
|
||||
// First close the detail dialog to reset its state
|
||||
handleDetailDialog(false, null);
|
||||
|
||||
// Refresh the main data grid first
|
||||
refreshData();
|
||||
|
||||
// Wait a tiny bit then reopen the detail with refreshed data
|
||||
setTimeout(() => {
|
||||
handleDetailDialog(true, selectedFeedback);
|
||||
}, 300);
|
||||
} else {
|
||||
toast.error(response?.message || 'Failed to update feedback');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating feedback:', error);
|
||||
toast.error('An error occurred while updating feedback');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchFeedbackDetail = async () => {
|
||||
if (!selectedFeedback) return;
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await GetData(`${API_URL}/feedback/detail/${selectedFeedback}`, {
|
||||
id: selectedFeedback
|
||||
});
|
||||
|
||||
if (!response || !response.data) {
|
||||
console.error('Invalid response format');
|
||||
return;
|
||||
}
|
||||
|
||||
const data = response.data;
|
||||
console.log('Fetched data:', data);
|
||||
|
||||
setReviewNotes(data.review_notes || '');
|
||||
|
||||
const currentStatus = (data.status as StatusCode) || 'Y';
|
||||
setStatus(currentStatus);
|
||||
} catch (error) {
|
||||
console.error('Error fetching feedback details:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
|
||||
<DialogContent className="p-0 w-full sm:max-w-2xl bg-white rounded-lg overflow-hidden">
|
||||
<div className="relative">
|
||||
<div className="p-6 flex items-center justify-between border-b">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-gray-900">Review Feedback</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">Review and update feedback status</p>
|
||||
</div>
|
||||
<button
|
||||
className="absolute right-6 top-6 text-gray-400 hover:text-gray-600"
|
||||
onClick={() => handleEditDialog(false, null)}
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6">
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<label className="block text-gray-700 text-lg">
|
||||
Review Notes <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
className="w-full min-h-48 p-4 text-gray-700 bg-white border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
placeholder="Enter your review notes here..."
|
||||
value={reviewNotes}
|
||||
onChange={(e) => setReviewNotes(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<label className="block text-gray-700 text-lg">
|
||||
Status <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(value: string) => setStatus(value as StatusCode)}
|
||||
>
|
||||
<SelectTrigger className="w-full p-3 text-gray-700">
|
||||
<SelectValue placeholder="Select status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Y">Accept</SelectItem>
|
||||
<SelectItem value="N">Reject</SelectItem>
|
||||
<SelectItem value="W">Waiting</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-4 mt-8">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => handleEditDialog(false, null)}
|
||||
disabled={loading}
|
||||
className="px-6 py-3 h-12 border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 rounded-md"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="px-6 py-3 h-12 bg-blue-600 hover:bg-blue-700 text-white rounded-md"
|
||||
>
|
||||
{loading ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditDialog;
|
||||
@ -1,199 +1,304 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { useCallApi } from '@/hooks';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog';
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import { useCallApi } from '@/hooks';
|
||||
import { format } from 'date-fns';
|
||||
import { Image as ImageIcon, X } from 'lucide-react';
|
||||
import { useManageFeedbackContext } from '../hooks/useManageFeedbackMemberContext';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import FeedbackEditDialog from './EditDialog';
|
||||
|
||||
interface FeedbackDetailProps {
|
||||
showDialog: boolean;
|
||||
handleDialog: (show: boolean) => void;
|
||||
feedbackId: string | null;
|
||||
interface ImageModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
imageUrl: string;
|
||||
}
|
||||
|
||||
interface FeedbackDetailData {
|
||||
Feedback_id: string;
|
||||
Feedback_feedback_notes: string;
|
||||
Feedback_feedback_screenshoot: string;
|
||||
Feedback_review_notes: string;
|
||||
Feedback_emotion: string;
|
||||
Feedback_review_screenshoot: string | null;
|
||||
Feedback_category: string;
|
||||
Feedback_status: string;
|
||||
Feedback_created_at: string;
|
||||
Feedback_review_by: string | null;
|
||||
Feedback_review_at: string;
|
||||
Feedback_deleted_by: string | null;
|
||||
Feedback_deleted_at: string | null;
|
||||
Feedback_createdById: string;
|
||||
}
|
||||
|
||||
const API_URL = apiConfig.service_feedback;
|
||||
|
||||
const FeedbackDetail: React.FC<FeedbackDetailProps> = ({ showDialog, handleDialog, feedbackId }) => {
|
||||
const [feedbackDetail, setFeedbackDetail] = useState<FeedbackDetailData | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const { GetData } = useCallApi();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchFeedbackDetail = async () => {
|
||||
if (!feedbackId) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await GetData(`${API_URL}/feedback/${feedbackId}`,{});
|
||||
if (response?.data) {
|
||||
setFeedbackDetail(response.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching feedback detail:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (showDialog && feedbackId) {
|
||||
fetchFeedbackDetail();
|
||||
} else {
|
||||
setFeedbackDetail(null);
|
||||
}
|
||||
}, [showDialog, feedbackId, GetData]);
|
||||
|
||||
const formatDate = (dateString: string | null) => {
|
||||
if (!dateString) return '-';
|
||||
try {
|
||||
return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss');
|
||||
} catch (e) {
|
||||
return dateString;
|
||||
}
|
||||
};
|
||||
|
||||
const getEmotionText = (emotion: string) => {
|
||||
const emotions: Record<string, string> = {
|
||||
'1': 'Very Disappointed',
|
||||
'2': 'Disappointed',
|
||||
'3': 'Happy',
|
||||
'4': 'Very Happy',
|
||||
'5': 'Extremely Happy'
|
||||
};
|
||||
return emotions[emotion] || emotion;
|
||||
};
|
||||
|
||||
const getStatusText = (status: string) => {
|
||||
const statuses: Record<string, string> = {
|
||||
'W': 'Waiting',
|
||||
'P': 'Processed',
|
||||
'D': 'Done'
|
||||
};
|
||||
return statuses[status] || status;
|
||||
};
|
||||
// New Image Modal Component
|
||||
const ImageModal: React.FC<ImageModalProps> = ({ isOpen, onClose, imageUrl }) => {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<Dialog open={showDialog} onOpenChange={handleDialog}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Feedback Detail</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center p-8">
|
||||
<div className="spinner-border text-primary" role="status">
|
||||
<span className="visually-hidden">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
) : feedbackDetail ? (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Feedback ID</label>
|
||||
<div>{feedbackDetail.Feedback_id}</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Category</label>
|
||||
<div>{feedbackDetail.Feedback_category}</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Emotion</label>
|
||||
<div>{getEmotionText(feedbackDetail.Feedback_emotion)}</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Status</label>
|
||||
<div>{getStatusText(feedbackDetail.Feedback_status)}</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Created At</label>
|
||||
<div>{formatDate(feedbackDetail.Feedback_created_at)}</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Created By</label>
|
||||
<div>{feedbackDetail.Feedback_createdById}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Feedback Notes</label>
|
||||
<div className="p-3 bg-gray-50 rounded">{feedbackDetail.Feedback_feedback_notes}</div>
|
||||
</div>
|
||||
|
||||
{feedbackDetail.Feedback_feedback_screenshoot && (
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Feedback Screenshot</label>
|
||||
<div>
|
||||
<img
|
||||
src={feedbackDetail.Feedback_feedback_screenshoot.replace(/^'|'$/g, '')}
|
||||
alt="Feedback Screenshot"
|
||||
className="max-h-64 rounded"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).style.display = 'none';
|
||||
(e.target as HTMLImageElement).parentElement?.appendChild(
|
||||
Object.assign(document.createElement('div'), {
|
||||
className: 'text-sm text-gray-500',
|
||||
textContent: 'Image not available or invalid URL'
|
||||
})
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Review Notes</label>
|
||||
<div className="p-3 bg-gray-50 rounded">{feedbackDetail.Feedback_review_notes || '-'}</div>
|
||||
</div>
|
||||
|
||||
{feedbackDetail.Feedback_review_screenshoot && (
|
||||
<div className="form-group">
|
||||
<label className="form-label font-semibold">Review Screenshot</label>
|
||||
<div>
|
||||
<img
|
||||
src={feedbackDetail.Feedback_review_screenshoot}
|
||||
alt="Review Screenshot"
|
||||
className="max-h-64 rounded"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).style.display = 'none';
|
||||
(e.target as HTMLImageElement).parentElement?.appendChild(
|
||||
Object.assign(document.createElement('div'), {
|
||||
className: 'text-sm text-gray-500',
|
||||
textContent: 'Image not available or invalid URL'
|
||||
})
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-4 text-center text-gray-500">No feedback details found</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75">
|
||||
<div className="relative w-11/12 h-5/6 max-w-4xl">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-4 right-4 bg-white rounded-full p-1 shadow-lg z-10"
|
||||
>
|
||||
<X size={24} className="text-gray-800" />
|
||||
</button>
|
||||
<img src={imageUrl} alt="Enlarged view" className="w-full h-full object-contain" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default FeedbackDetail;
|
||||
const ScreenshotGrid = ({ title, images }: { title: string; images: string[] }) => {
|
||||
const [selectedImage, setSelectedImage] = useState<string | null>(null);
|
||||
|
||||
const openImageModal = (url: string) => {
|
||||
setSelectedImage(url);
|
||||
};
|
||||
|
||||
const closeImageModal = () => {
|
||||
setSelectedImage(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-semibold text-gray-600">{title}</h3>
|
||||
{images && images.length > 0 ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{images.map((url, index) => (
|
||||
<div
|
||||
key={`${title}-${index}`}
|
||||
className="relative h-48 rounded-md overflow-hidden border border-gray-200 bg-white cursor-pointer hover:opacity-90 transition-opacity"
|
||||
onClick={() => url && openImageModal(url)}
|
||||
>
|
||||
{url ? (
|
||||
<img
|
||||
src={url}
|
||||
alt={`${title} ${index + 1}`}
|
||||
className="w-full h-full object-cover rounded-md"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex justify-center items-center h-full bg-gray-100">
|
||||
<ImageIcon size={48} className="text-gray-400" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-800">N/A</p>
|
||||
)}
|
||||
|
||||
<ImageModal
|
||||
isOpen={!!selectedImage}
|
||||
onClose={closeImageModal}
|
||||
imageUrl={selectedImage || ''}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const FeedbackDetail = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [feedbackDetail, setFeedbackDetail] = useState<any>(null);
|
||||
const { GetData } = useCallApi();
|
||||
const API_URL = apiConfig.service_feedback;
|
||||
const {
|
||||
handleDetailDialog,
|
||||
selectedFeedback,
|
||||
showDetailDialog,
|
||||
handleEditDialog,
|
||||
showEditDialog
|
||||
} = useManageFeedbackContext();
|
||||
|
||||
const formatDateTime = (dateString: string) => {
|
||||
if (!dateString) return 'N/A';
|
||||
try {
|
||||
return format(new Date(dateString), 'MMM dd, yyyy HH:mm');
|
||||
} catch {
|
||||
return 'N/A';
|
||||
}
|
||||
};
|
||||
|
||||
const formatValue = (value: any) => {
|
||||
if (value === null || value === undefined || (typeof value === 'string' && value.trim() === ''))
|
||||
return 'N/A';
|
||||
return value;
|
||||
};
|
||||
|
||||
const getEmotionLabel = (emotion: string) => {
|
||||
const emotions: Record<string, string> = {
|
||||
'1': 'Very Dissatisfied',
|
||||
'2': 'Dissatisfied',
|
||||
'3': 'Neutral',
|
||||
'4': 'Satisfied',
|
||||
'5': 'Very Satisfied'
|
||||
};
|
||||
return emotions[emotion] || 'N/A';
|
||||
};
|
||||
|
||||
const getStatusLabel = (status: string) => {
|
||||
if (!status) return { label: 'N/A', color: 'text-gray-500' };
|
||||
|
||||
const statuses: Record<string, { label: string; color: string }> = {
|
||||
W: { label: 'Waiting', color: 'text-yellow-500' },
|
||||
Y: { label: 'Accepted', color: 'text-green-500' },
|
||||
N: { label: 'Rejected', color: 'text-red-500' },
|
||||
C: { label: 'Completed', color: 'text-blue-500' },
|
||||
R: { label: 'Rejected', color: 'text-red-500' }
|
||||
};
|
||||
return statuses[status] || { label: 'N/A', color: 'text-gray-500' };
|
||||
};
|
||||
|
||||
const fetchFeedbackDetail = async () => {
|
||||
if (!selectedFeedback) return;
|
||||
try {
|
||||
setLoading(true);
|
||||
const timestamp = new Date().getTime();
|
||||
const response = await GetData(`${API_URL}/feedback/detail/${selectedFeedback}`, {
|
||||
id: selectedFeedback,
|
||||
_t: timestamp
|
||||
});
|
||||
|
||||
if (!response || !response.data) {
|
||||
console.error('Invalid response format');
|
||||
return;
|
||||
}
|
||||
|
||||
const data = response.data;
|
||||
|
||||
const normalizedData = {
|
||||
...data,
|
||||
feedback_screenshoot: Array.isArray(data?.feedback_screenshoot)
|
||||
? data.feedback_screenshoot
|
||||
: data?.feedback_screenshoot
|
||||
? [data.feedback_screenshoot]
|
||||
: [],
|
||||
review_screenshoot: Array.isArray(data?.review_screenshoot)
|
||||
? data.review_screenshoot
|
||||
: data?.review_screenshoot
|
||||
? [data.review_screenshoot]
|
||||
: []
|
||||
};
|
||||
|
||||
setFeedbackDetail(normalizedData);
|
||||
} catch (error) {
|
||||
console.error('Error fetching feedback detail:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (showDetailDialog && selectedFeedback) {
|
||||
fetchFeedbackDetail();
|
||||
} else if (!showDetailDialog) {
|
||||
setFeedbackDetail(null);
|
||||
}
|
||||
}, [showDetailDialog, selectedFeedback]);
|
||||
|
||||
const handleReviewClick = () => {
|
||||
handleEditDialog(true, selectedFeedback);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
open={showDetailDialog}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setFeedbackDetail(null);
|
||||
}
|
||||
handleDetailDialog(open, open ? selectedFeedback : null);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-4xl rounded-2xl p-6 shadow-lg border border-gray-200">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-xl font-bold">Feedback Detail</DialogTitle>
|
||||
<DialogDescription className="text-sm text-gray-500"></DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center h-60">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary" />
|
||||
</div>
|
||||
) : feedbackDetail ? (
|
||||
<div className="space-y-8">
|
||||
<div className="p-4 border border-gray-200 rounded-lg">
|
||||
<h3 className="text-md font-semibold mb-4 border-b pb-2">Feedback Information</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-600">Feedback ID</p>
|
||||
<p className="text-sm text-gray-800">{formatValue(feedbackDetail.id)}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-600">Created By</p>
|
||||
<p className="text-sm text-gray-800">
|
||||
{formatValue(feedbackDetail.created_by?.fullname)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-600">Created Date</p>
|
||||
<p className="text-sm text-gray-800">
|
||||
{formatDateTime(feedbackDetail.created_at)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-600">Emotion</p>
|
||||
<p className="text-sm text-gray-800">
|
||||
{getEmotionLabel(feedbackDetail.emotion)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
<p className="text-sm font-semibold text-gray-600">Feedback Notes</p>
|
||||
<p className="text-sm text-gray-800 whitespace-pre-wrap mt-1 p-2 bg-gray-50 rounded">
|
||||
{formatValue(feedbackDetail.feedback_notes)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border border-gray-200 rounded-lg">
|
||||
<h3 className="text-md font-semibold mb-4 border-b pb-2">Feedback Screenshots</h3>
|
||||
<ScreenshotGrid title="" images={feedbackDetail.feedback_screenshoot} />
|
||||
</div>
|
||||
|
||||
<div className="p-4 border border-gray-200 rounded-lg">
|
||||
<h3 className="text-md font-semibold mb-4 border-b pb-2">Review Information</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-600">Reviewed By</p>
|
||||
<p className="text-sm text-gray-800">{formatValue(feedbackDetail.review_by)}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-600">Status</p>
|
||||
<p
|
||||
className={`text-sm font-semibold ${getStatusLabel(feedbackDetail.status).color}`}
|
||||
>
|
||||
{getStatusLabel(feedbackDetail.status).label}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
<p className="text-sm font-semibold text-gray-600">Review Notes</p>
|
||||
<p className="text-sm text-gray-800 whitespace-pre-wrap mt-1 p-2 bg-gray-50 rounded">
|
||||
{formatValue(feedbackDetail.review_notes)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{feedbackDetail.status !== 'C' && feedbackDetail.status !== 'R' && (
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={handleReviewClick}
|
||||
className="bg-primary hover:bg-primary/90 text-white"
|
||||
>
|
||||
Review Feedback
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default FeedbackDetail;
|
||||
|
||||
@ -2,10 +2,11 @@ import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import { useCallApi } from '@/hooks';
|
||||
import { ColumnDef } from '@tanstack/react-table';
|
||||
import React, { createContext, useCallback, useMemo, useState } from 'react';
|
||||
import React, { createContext, useCallback, useMemo, useState, useEffect } from 'react';
|
||||
import { Toaster } from 'sonner';
|
||||
// import FeedbackDetail from './blocks/FeedbackDetail';
|
||||
import FeedbackDetail from '../blocks/FeedbackDetail';
|
||||
import FeedbackEditDialog from '../blocks/EditDialog';
|
||||
import { useNavigate } from 'react-router';
|
||||
|
||||
interface feedbackProps {
|
||||
id: string;
|
||||
@ -17,17 +18,20 @@ interface feedbackProps {
|
||||
agentId: string;
|
||||
}
|
||||
|
||||
interface FetchParams {
|
||||
pageIndex: number;
|
||||
pageSize: number;
|
||||
sorting: any[];
|
||||
columnFilters: any[];
|
||||
}
|
||||
|
||||
interface ContextProps {
|
||||
feedback: feedbackProps[];
|
||||
showEditDialog: boolean;
|
||||
handleEditDialog: (show: boolean, selected_sucos: string | null) => void;
|
||||
showAddDialog: boolean;
|
||||
handleAddDialog: (show: boolean) => void;
|
||||
showDeleteDialog: boolean;
|
||||
handleDeleteDialog: (show: boolean, selected_sucos: string | null) => void;
|
||||
showDetailDialog: boolean;
|
||||
handleDetailDialog: (show: boolean, selected_sucos: string | null) => void;
|
||||
selectedfeedback: string | null;
|
||||
handleDetailDialog: (show: boolean, selected_feedback: string | null) => void;
|
||||
selectedFeedback: string | null;
|
||||
showEditDialog: boolean;
|
||||
handleEditDialog: (show: boolean, selected_feedback: string | null) => void;
|
||||
getfeedbackLists: (
|
||||
limit: number,
|
||||
page: number,
|
||||
@ -35,20 +39,18 @@ interface ContextProps {
|
||||
order_field: any,
|
||||
order_direction: any
|
||||
) => Promise<{ data: feedbackProps[]; totalCount: number } | undefined>;
|
||||
refreshData: () => void;
|
||||
}
|
||||
|
||||
const initialProps: ContextProps = {
|
||||
feedback: [],
|
||||
showEditDialog: false,
|
||||
handleEditDialog: () => {},
|
||||
showAddDialog: false,
|
||||
handleAddDialog: () => {},
|
||||
showDeleteDialog: false,
|
||||
handleDeleteDialog: () => {},
|
||||
showDetailDialog: false,
|
||||
handleDetailDialog: () => {},
|
||||
selectedfeedback: null,
|
||||
getfeedbackLists: async () => undefined
|
||||
selectedFeedback: null,
|
||||
showEditDialog: false,
|
||||
handleEditDialog: () => {},
|
||||
getfeedbackLists: async () => undefined,
|
||||
refreshData: () => {}
|
||||
};
|
||||
|
||||
const ManageFeedbackMemberContext = createContext<ContextProps>(initialProps);
|
||||
@ -60,32 +62,37 @@ const ManageFeedbackMemberProvider = ({ children }: { children: React.ReactNode
|
||||
const [showEditDialog, setShowEditDialog] = useState(false);
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [showDetailDialog, setShowDetailDialog] = useState(false);
|
||||
const [selectedfeedback, setSelectedfeedback] = useState<string | null>(null);
|
||||
const [selectedFeedback, setSelectedFeedback] = useState<string | null>(null);
|
||||
const { GetData } = useCallApi();
|
||||
|
||||
const [refreshTrigger, setRefreshTrigger] = useState(0);
|
||||
|
||||
const [lastFetchParams, setLastFetchParams] = useState<FetchParams | null>(null);
|
||||
|
||||
const handleAddDialog = useCallback((show: boolean) => {
|
||||
setShowAddDialog(show);
|
||||
}, []);
|
||||
|
||||
const handleEditDialog = useCallback((show: boolean, selected_feedback: string | null) => {
|
||||
setShowEditDialog(show);
|
||||
setSelectedfeedback(show ? selected_feedback : null);
|
||||
}, []);
|
||||
|
||||
const handleDeleteDialog = useCallback((show: boolean, selected_feedback: string | null) => {
|
||||
setShowDeleteDialog(show);
|
||||
setSelectedfeedback(show ? selected_feedback : null);
|
||||
}, []);
|
||||
|
||||
const handleDetailDialog = useCallback((show: boolean, selected_feedback: string | null) => {
|
||||
setShowDetailDialog(show);
|
||||
setSelectedfeedback(show ? selected_feedback : null);
|
||||
setSelectedFeedback(show ? selected_feedback : null);
|
||||
}, []);
|
||||
|
||||
const handleEditDialog = useCallback((show: boolean, selected_feedback: string | null) => {
|
||||
setShowEditDialog(show);
|
||||
if (show) {
|
||||
setSelectedFeedback(selected_feedback);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const refreshData = useCallback(() => {
|
||||
setRefreshTrigger((prev) => prev + 1);
|
||||
}, []);
|
||||
|
||||
const columns = useMemo<ColumnDef<any>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorFn: (row) => row.customer,
|
||||
accessorFn: (row) => row.customerid,
|
||||
id: 'customer_id',
|
||||
header: ({ column }) => <DataGridColumnHeader title="Customer Name" column={column} />,
|
||||
enableSorting: false,
|
||||
@ -95,7 +102,7 @@ const ManageFeedbackMemberProvider = ({ children }: { children: React.ReactNode
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.Feedback_emotion,
|
||||
accessorFn: (row) => row.feedbacks_emotion,
|
||||
id: 'feedback_emotion',
|
||||
header: ({ column }) => <DataGridColumnHeader title="Emotion" column={column} />,
|
||||
enableSorting: false,
|
||||
@ -105,7 +112,7 @@ const ManageFeedbackMemberProvider = ({ children }: { children: React.ReactNode
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.Feedback_feedback_notes,
|
||||
accessorFn: (row) => row.feedbacks_feedback_notes,
|
||||
id: 'feedback_notes',
|
||||
header: ({ column }) => <DataGridColumnHeader title="Feedback Notes" column={column} />,
|
||||
enableSorting: false,
|
||||
@ -125,25 +132,14 @@ const ManageFeedbackMemberProvider = ({ children }: { children: React.ReactNode
|
||||
<>
|
||||
<button
|
||||
className="btn btn-sm btn-icon btn-clear btn-light"
|
||||
onClick={() => handleDetailDialog(true, row.Feedback_id)}
|
||||
onClick={() => {
|
||||
setSelectedFeedback(row.feedbacks_id);
|
||||
handleDetailDialog(true, row.feedbacks_id);
|
||||
}}
|
||||
title="View Details"
|
||||
>
|
||||
<KeenIcon icon="eye" />
|
||||
</button>
|
||||
{/* <button
|
||||
className="btn btn-sm btn-icon btn-clear btn-light"
|
||||
onClick={() => handleEditDialog(true, row.Feedback_id)}
|
||||
title="Edit"
|
||||
>
|
||||
<KeenIcon icon="notepad-edit" />
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-sm btn-icon btn-clear btn-light"
|
||||
onClick={() => handleDeleteDialog(true, row.Feedback_id)}
|
||||
title="Delete"
|
||||
>
|
||||
<KeenIcon icon="trash" />
|
||||
</button> */}
|
||||
</>
|
||||
);
|
||||
},
|
||||
@ -153,20 +149,26 @@ const ManageFeedbackMemberProvider = ({ children }: { children: React.ReactNode
|
||||
}
|
||||
}
|
||||
],
|
||||
[handleEditDialog, handleDeleteDialog, handleDetailDialog]
|
||||
[]
|
||||
);
|
||||
|
||||
const getfeedbackLists = async (page: number, limit: number, sorting: any, filter: any) => {
|
||||
try {
|
||||
sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
|
||||
setLastFetchParams({
|
||||
pageIndex: page,
|
||||
pageSize: limit,
|
||||
sorting: sorting,
|
||||
columnFilters: filter
|
||||
});
|
||||
|
||||
sorting = sorting.length == 0 ? [{ id: 'feedbacks_created_at', desc: true }] : sorting;
|
||||
filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
|
||||
const response = await GetData(`${API_URL}/feedback/list`, {
|
||||
limit,
|
||||
page: page + 1,
|
||||
with_deleted: false,
|
||||
order_field: sorting[0].id,
|
||||
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
|
||||
// filter: JSON.stringify(filter)
|
||||
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
|
||||
});
|
||||
// console.log(response?.data);
|
||||
setFeedback(response?.data.list);
|
||||
@ -176,37 +178,37 @@ const ManageFeedbackMemberProvider = ({ children }: { children: React.ReactNode
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (refreshTrigger > 0 && lastFetchParams) {
|
||||
getfeedbackLists(
|
||||
lastFetchParams.pageIndex,
|
||||
lastFetchParams.pageSize,
|
||||
lastFetchParams.sorting,
|
||||
lastFetchParams.columnFilters
|
||||
);
|
||||
}
|
||||
}, [refreshTrigger]);
|
||||
|
||||
return (
|
||||
<ManageFeedbackMemberContext.Provider
|
||||
value={{
|
||||
feedback,
|
||||
showEditDialog,
|
||||
handleEditDialog,
|
||||
showAddDialog,
|
||||
handleAddDialog,
|
||||
showDeleteDialog,
|
||||
handleDeleteDialog,
|
||||
showDetailDialog,
|
||||
handleDetailDialog,
|
||||
selectedfeedback,
|
||||
getfeedbackLists
|
||||
selectedFeedback,
|
||||
showEditDialog,
|
||||
handleEditDialog,
|
||||
getfeedbackLists,
|
||||
refreshData
|
||||
}}
|
||||
>
|
||||
<Toaster expand visibleToasts={9} duration={3000} />
|
||||
|
||||
{/* Feedback Detail Modal Component */}
|
||||
<FeedbackDetail
|
||||
showDialog={showDetailDialog}
|
||||
handleDialog={(show) => handleDetailDialog(show, show ? selectedfeedback : null)}
|
||||
feedbackId={selectedfeedback}
|
||||
/>
|
||||
|
||||
<DataGridProvider
|
||||
columns={columns}
|
||||
pagination={{ size: 10 }}
|
||||
// toolbar={<ListToolbar />}
|
||||
layout={{ card: true }}
|
||||
sorting={[{ id: 'created_at', desc: true }]}
|
||||
sorting={[{ id: 'feedbacks_created_at', desc: true }]}
|
||||
serverSide={true}
|
||||
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
|
||||
getfeedbackLists(pageIndex, pageSize, sorting, columnFilters)
|
||||
@ -219,4 +221,4 @@ const ManageFeedbackMemberProvider = ({ children }: { children: React.ReactNode
|
||||
};
|
||||
|
||||
export { ManageFeedbackMemberContext, ManageFeedbackMemberProvider };
|
||||
export type { feedbackProps };
|
||||
export type { feedbackProps };
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { useContext } from 'react';
|
||||
import { ManageFeedbackMemberContext } from './ManageFeedbackMemberContext';
|
||||
|
||||
const useManageProviderContext = () => {
|
||||
const useManageFeedbackContext = () => {
|
||||
const context = useContext(ManageFeedbackMemberContext);
|
||||
|
||||
if (!context) throw new Error('useManageProviderContext must be used within AuthProvider');
|
||||
@ -9,4 +9,4 @@ const useManageProviderContext = () => {
|
||||
return context;
|
||||
};
|
||||
|
||||
export { useManageProviderContext };
|
||||
export { useManageFeedbackContext };
|
||||
|
||||
@ -209,6 +209,15 @@ const ManageKycDeletionContextProvider = ({ children }: { children: React.ReactN
|
||||
headerClassName: 'w-[350px]'
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.msisdn,
|
||||
id: 'msdisdn',
|
||||
header: ({ column }) => <DataGridColumnHeader title="Phone Number" column={column} />,
|
||||
enableSorting: true,
|
||||
meta: {
|
||||
headerClassName: 'w-[350px]'
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.registered_email,
|
||||
id: 'email',
|
||||
|
||||
@ -70,6 +70,20 @@ export const getColumns = (handleUpdate: (data: any) => void): ColumnDef<Members
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'msisdn',
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
||||
>
|
||||
Phone Number
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'group_name',
|
||||
header: ({ column }) => {
|
||||
|
||||
@ -62,6 +62,20 @@ export const getColumns = (handleUpdate: (data: any) => void): ColumnDef<Members
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'msisdn',
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
|
||||
>
|
||||
Phone Number
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'group_name',
|
||||
header: ({ column }) => {
|
||||
|
||||
@ -1,616 +0,0 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import axios from 'axios';
|
||||
import { Dialog,DialogActions,DialogContent,DialogTitle,TextField,Button,MenuItem,Select,InputLabel,FormControl,Typography,
|
||||
InputAdornment,Grid,Box,List,ListItem,
|
||||
} from "@mui/material";
|
||||
import UploadFileIcon from "@mui/icons-material/UploadFile";
|
||||
import Divider from '@mui/material/Divider';
|
||||
import { initialMember } from "./Columns";
|
||||
import { apiConfig } from '@/config/api.config';
|
||||
import ConfirmDialog from '@/components/confirm';
|
||||
import { toast } from 'sonner';
|
||||
const BASE_URL_MASTER_DATA = apiConfig.service_master_data;
|
||||
const BASE_URL_CUSTOMER = apiConfig.service_customer;
|
||||
// MAIN PAGE
|
||||
const CustomerDialog = ({ open, handleClose, handleSubmit, initialData, viewStats, handleReject, page, fetchCustomers }: any) => {
|
||||
const [formData, setFormData] = useState(initialData || initialMember);
|
||||
const [viewOnly, setViewOnly] = useState(viewStats || false);
|
||||
const [municipios, setMunicipios] = useState([]);
|
||||
const [aldeias, setAldeias] = useState([]);
|
||||
const [postoAdm, setPostoAdm] = useState([]);
|
||||
const [sucos, setSucos] = useState([]);
|
||||
const [profession, setProfession] = useState([]);
|
||||
const [groupData] = useState({
|
||||
reguler: `This fill can not be empty!`,
|
||||
premium: `This field required only for Premium or Agent`,
|
||||
agent: `This field required only for Agent`
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(initialData || {}); // Sync formData when initialData changes
|
||||
fetchMasterData()
|
||||
}, [initialData]);
|
||||
|
||||
async function fetchMasterData() {
|
||||
try {
|
||||
let getProfession = 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)
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const handleChange = async (e: any) => {
|
||||
const { name, value } = e.target;
|
||||
if (name === 'municipio' || name === 'posto_adms' || name === 'suco') await getMasterAfter(name, value);
|
||||
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 {
|
||||
setFormData({ ...formData, [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 onSubmit = () => {
|
||||
if (page === 'kyc' && !formData.description) return toast.warning(`Description for approval needed!`)
|
||||
handleSubmit(formData);
|
||||
// handleClose();
|
||||
};
|
||||
|
||||
const onReject = () => {
|
||||
handleReject(formData);
|
||||
handleClose();
|
||||
}
|
||||
|
||||
function generateDate(date: any, type: any) {
|
||||
if (!date) return ''
|
||||
const today = new Date(date);
|
||||
if (type === 'datetime') return today.toISOString().replace('T', ' ').substring(0, 19);
|
||||
return today.toISOString().split('T')[0];
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={handleClose} fullWidth maxWidth="sm">
|
||||
<DialogTitle>Customer Form ({viewOnly ? 'View' : 'Edit'})</DialogTitle>
|
||||
<DialogContent>
|
||||
<div className="flex justify-between pb-5">
|
||||
<Typography sx={{color:'grey'}}>Customer Data</Typography>
|
||||
<Typography sx={{color:'grey'}} display="flex" justifyContent="flex-end">Created: {generateDate(formData.created_at, 'datetime')}</Typography>
|
||||
</div>
|
||||
{
|
||||
formData.isneedapproval == 1 ? (
|
||||
<div className="flex justify-between pb-5">
|
||||
<Typography sx={{color:'orange'}}>User Request for approval </Typography>
|
||||
</div>
|
||||
) : ('')
|
||||
}
|
||||
|
||||
<TextField disabled={viewOnly} required multiline fullWidth margin="dense" label="Full Name" name="fullname" value={formData.fullname} onChange={handleChange} />
|
||||
{/* <Typography fontSize={13} paddingLeft={2} marginTop={-2.5} color="red">{groupData.reguler}</Typography> */}
|
||||
<TextField disabled={viewOnly} required fullWidth margin="dense" label="Email" name="email" value={formData.email} onChange={handleChange} />
|
||||
<TextField disabled fullWidth required margin="dense" label="Group" name="group" value={formData.group_name} onChange={handleChange} />
|
||||
{fileTextFile("Photo", formData.photouser, "photouser", handleChange)}
|
||||
<TextField disabled={viewOnly} required fullWidth margin="dense" label="Username" name="username" value={formData.username} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} required fullWidth margin="dense" label="Mother Fullname" name="mother_fullname" value={formData.mother_fullname} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} required fullWidth margin="dense" label="MSISDN" name="msisdn" value={formData.msisdn} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} required fullWidth margin="dense" label="Address" name="address" value={formData.address} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} required fullWidth margin="dense" label="Nationality" name="nationality" value={formData.nationality} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} required fullWidth margin="dense" label="Date of Birth" name="date_birth" type="date" value={generateDate(formData.date_birth, null)} onChange={handleChange} InputLabelProps={{ shrink: true }} />
|
||||
<FormControl required fullWidth margin="dense">
|
||||
<InputLabel>Gender</InputLabel>
|
||||
<Select required disabled={viewOnly} name="gender" value={formData.gender} onChange={handleChange}>
|
||||
<MenuItem key={1} value="M">Male</MenuItem>
|
||||
<MenuItem key={2} value="F">Female</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl fullWidth margin="dense">
|
||||
<InputLabel>Identity Type</InputLabel>
|
||||
<Select disabled={viewOnly} name="identity_type" value={formData.identity_type} onChange={handleChange}>
|
||||
<MenuItem key={1} value="eleitoral_id">Eleitoral ID</MenuItem>
|
||||
<MenuItem key={2} value="bihete_de_identidade">Bihete de Identidade</MenuItem>
|
||||
<MenuItem key={3} value="passport">Passport</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{/* AGENT & PREMIUM DATA */}
|
||||
<TextField disabled={viewOnly} fullWidth margin="dense" label="Identity Number" name="identity_number" value={formData.identity_number} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} type="text" fullWidth margin="dense" label="License Number" name="license_number" value={formData.license_number} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} type="text" fullWidth margin="dense" label="Merchant Address" name="merchantaddress" value={formData.merchantaddress} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} type="text" fullWidth margin="dense" label="Longitude Merchant" name="longitudemerchant" value={formData.longitudemerchant} onChange={handleChange} />
|
||||
<TextField disabled={viewOnly} type="text" fullWidth margin="dense" label="Latitude Merchant" name="latitudemerchant" value={formData.latitudemerchant} onChange={handleChange} />
|
||||
{fileTextFile("File Selfie", formData.file_selfie, "file_selfie", handleChange)}
|
||||
<img width={300} height={250} srcSet={formData.file_selfie} src={formData.file_selfie} alt={"file_selfie"} style={{borderRadius: 10}}/>
|
||||
{fileTextFile("File Document", formData.file_document_id, "file_document_id", handleChange)}
|
||||
<img width={300} height={250} srcSet={formData.file_document_id} src={formData.file_document_id} alt={"file_document_id"} style={{borderRadius: 10}}/>
|
||||
{fileTextFile("File Document & Selfie", formData.file_document_id_selfie, "file_document_id_selfie", handleChange)}
|
||||
<img width={300} height={250} srcSet={formData.file_document_id_selfie} src={formData.file_document_id_selfie} alt={"file_document_id_selfie"} style={{borderRadius: 10}}/>
|
||||
{fileTextFile("File Commercial License", formData.file_commercial_license, "file_commercial_license", handleChange)}
|
||||
<img width={300} height={250} srcSet={formData.file_commercial_license} src={formData.file_commercial_license} alt={"file_commercial_license"} style={{borderRadius: 10}}/>
|
||||
{/* AGENT & PREMIUM DATA */}
|
||||
|
||||
{/* <TextField disabled={viewOnly} fullWidth margin="dense" label="Profession" name="profession" value={formData.profession} onChange={handleChange} /> */}
|
||||
<FormControl fullWidth margin="dense">
|
||||
<InputLabel>Profession</InputLabel>
|
||||
<Select disabled={viewOnly} name="profession" value={formData.profession} onChange={handleChange}>
|
||||
{
|
||||
profession ? profession.map((el: any) => (
|
||||
<MenuItem key={el.id} value={el.id}>{el.name}</MenuItem>
|
||||
)) : ""
|
||||
}
|
||||
</Select>
|
||||
</FormControl>
|
||||
{/* <TextField fullWidth margin="dense" label="Password" name="password" type="password" value={formData.password} onChange={handleChange} /> */}
|
||||
{/* <TextField fullWidth margin="dense" label="PIN" name="pin" value={formData.pin} onChange={handleChange} /> */}
|
||||
<FormControl fullWidth margin="dense">
|
||||
<InputLabel>Status</InputLabel>
|
||||
<Select disabled={viewOnly} name="status" value={formData.status} onChange={handleChange}>
|
||||
<MenuItem key={1} value="Y">Active</MenuItem>
|
||||
<MenuItem key={2} value="N">Inactive</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl fullWidth margin="dense">
|
||||
<InputLabel>Municipio</InputLabel>
|
||||
<Select disabled={viewOnly} name="municipio" value={formData.municipio} onChange={handleChange}>
|
||||
{
|
||||
municipios ? municipios.map((el: any) => (
|
||||
<MenuItem key={el.id} value={el.id}>{el.name}</MenuItem>
|
||||
)) : ""
|
||||
}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl fullWidth margin="dense">
|
||||
<InputLabel>Posto</InputLabel>
|
||||
<Select disabled={viewOnly || !formData.municipio} name="posto_adms" value={formData.posto_adms} onChange={handleChange}>
|
||||
{
|
||||
postoAdm ? postoAdm.map((el: any) => (
|
||||
<MenuItem key={el.posto_adms_id || el.id} value={el.posto_adms_id || el.id}>{el.posto_adms_name || el.name}</MenuItem>
|
||||
)) : ""
|
||||
}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl fullWidth margin="dense">
|
||||
<InputLabel>Suco</InputLabel>
|
||||
<Select disabled={viewOnly || !formData.posto_adms} name="suco" value={formData.suco} onChange={handleChange}>
|
||||
{
|
||||
sucos ? sucos.map((el: any) => (
|
||||
<MenuItem key={el.sucos_id || el.id} value={el.sucos_id || el.id}>{el.sucos_name || el.name}</MenuItem>
|
||||
)) : ""
|
||||
}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl fullWidth margin="dense">
|
||||
<InputLabel>Aldeia</InputLabel>
|
||||
<Select disabled={viewOnly || !formData.suco} name="aldeia" value={formData.aldeia} onChange={handleChange}>
|
||||
{
|
||||
aldeias ? aldeias.map((el: any) => (
|
||||
<MenuItem key={el.id} value={el.id}>{el.name}</MenuItem>
|
||||
)) : ""
|
||||
}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<Divider className="pt-7"/>
|
||||
<Typography sx={{color:'grey'}}>Bank</Typography>
|
||||
<FormControl fullWidth margin="dense">
|
||||
<InputLabel>Bank Name</InputLabel>
|
||||
<Select disabled={viewOnly} name="bank_name" value={formData.bank_name} onChange={handleChange}>
|
||||
<MenuItem key={1} value="BNCTL">BNCTL</MenuItem>
|
||||
<MenuItem key={2} value="BRI">BRI</MenuItem>
|
||||
<MenuItem key={3} value="BNU">BNU</MenuItem>
|
||||
<MenuItem key={4} value="Mandiri">Mandiri</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField disabled={viewOnly} fullWidth margin="dense" label="Bank Account" name="bank_account" value={formData.bank_account} onChange={handleChange} />
|
||||
<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' ? (
|
||||
<>
|
||||
<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} />
|
||||
</>
|
||||
) : (<>
|
||||
{getAdmAccess(page, formData, handleClose, fetchCustomers, viewOnly, setViewOnly)}
|
||||
<Divider className="pt-7"/>
|
||||
{formData.id ? showCustomerWallet(formData.id) : ""}
|
||||
</>)
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
{
|
||||
page === 'kyc' ? (
|
||||
<Button onClick={() => viewOnly ? setViewOnly(false) : setViewOnly(true)} color="secondary">{ viewOnly ? (`Open Edit`) : (`Close Edit`) }</Button>
|
||||
) : ('')
|
||||
}
|
||||
<Button onClick={handleClose} color="secondary">Cancel</Button>
|
||||
{
|
||||
formData.isneedapproval == 1 && page === 'kyc' ? (
|
||||
<Button onClick={onReject} color="warning" variant="contained">Reject</Button>
|
||||
) : ('')
|
||||
}
|
||||
<Button onClick={onSubmit} color="primary" variant="contained">
|
||||
{ formData.id ? (formData.isneedapproval == 1 && page === 'kyc' ? (`Edit & Approve`) : (`Edit`)) : ("Create") }
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomerDialog;
|
||||
|
||||
function fileTextFile(label: string, value: any, name: string, handleChange: any) {
|
||||
return (
|
||||
<TextField
|
||||
margin="dense"
|
||||
label={label}
|
||||
variant="outlined"
|
||||
fullWidth
|
||||
value={value}
|
||||
placeholder="Choose a file..."
|
||||
InputProps={{
|
||||
readOnly: true,
|
||||
endAdornment: (
|
||||
<InputAdornment position="end">
|
||||
<input
|
||||
type="file"
|
||||
id="file-upload"
|
||||
// style={{ display: "none" }}
|
||||
onChange={handleChange}
|
||||
name={name}
|
||||
/>
|
||||
{/* <label htmlFor="file-upload">
|
||||
<Button
|
||||
component="span"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<UploadFileIcon />}
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
</label> */}
|
||||
</InputAdornment>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
// ACCESS ADM
|
||||
function getAdmAccess(page: string, data: any, handleClose: any, fetchCustomers: any, viewOnly: any, 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) {
|
||||
console.error(error.message);
|
||||
toast.error(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
const handleYes = async () => {
|
||||
try {
|
||||
if (dialogType === "update status") {
|
||||
let statusNext = getPinStatus(data.status).res;
|
||||
if (statusNext) await axios.put(`${BASE_URL_CUSTOMER}/customer/statuspin`, { customerid: data.id, status: statusNext })
|
||||
else toast.error("Handle Active/Suspend only")
|
||||
toast.success("Success Update Status")
|
||||
}
|
||||
if (dialogType === "reset pin") {
|
||||
if (data.id) await axios.post(`${BASE_URL_CUSTOMER}/customer/resetpin`, { customerid: data.id })
|
||||
else throw({ message: 'data.id not found' })
|
||||
toast.success("Pin will send to customer MSISDN")
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(error.message)
|
||||
} finally {
|
||||
setDialogOpen(false)
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
|
||||
function buttonStatus() {
|
||||
setDialogType('update status')
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
function buttonResetPin() {
|
||||
setDialogType('reset pin')
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
async function buttonChangeGroup() {
|
||||
try {
|
||||
let dataObj = {
|
||||
customerid: data.id,
|
||||
destination_group: changeGroup
|
||||
}
|
||||
if (data.group_id === changeGroup) return toast.warning(`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)
|
||||
}
|
||||
await fetchCustomers()
|
||||
toast.success('Success Change group')
|
||||
} catch (error: any) {
|
||||
console.log(error);
|
||||
toast.error(error.message)
|
||||
} finally {
|
||||
await fetchCustomers()
|
||||
setChangeGroupD(false)
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
|
||||
function openChangeGroupDialog() {
|
||||
setChangeGroup(data.group_id);
|
||||
setChangeGroupD(true)
|
||||
}
|
||||
|
||||
if (page !== "kyc") {
|
||||
return (
|
||||
<Box p={3} boxShadow={3} borderRadius={2} bgcolor="white">
|
||||
<Typography variant="h6" gutterBottom>Access Administration</Typography>
|
||||
<Grid container spacing={3}>
|
||||
<Grid item xs={6} container direction="column" spacing={2}>
|
||||
<Grid item>
|
||||
<Typography variant="body2">Pin Status : {getPinStatus(data.status).msg}</Typography>
|
||||
<Button onClick={() => buttonStatus()} variant="contained" color="primary">{getPinStatus(data.status).btn}</Button>
|
||||
</Grid>
|
||||
<Grid item>
|
||||
<Typography variant="body2">Reset PIN</Typography>
|
||||
<Button onClick={() => buttonResetPin()} variant="contained" color="primary">Reset PIN</Button>
|
||||
</Grid>
|
||||
</Grid>
|
||||
<Grid item xs={6} container direction="column" spacing={2}>
|
||||
<Grid item>
|
||||
<Typography variant="body2">Change Group</Typography>
|
||||
<Button onClick={() => openChangeGroupDialog()} variant="contained" color="primary">Change Group</Button>
|
||||
</Grid>
|
||||
<Grid item>
|
||||
<Typography variant="body2">Edit Member</Typography>
|
||||
{/* <Button variant="contained" color="primary">Edit Member</Button> */}
|
||||
<Button onClick={() => viewOnly ? setViewOnly(false) : setViewOnly(true)} variant="contained">{ viewOnly ? (`Open Edit`) : (`Close Edit`) }</Button>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<Dialog open={changeGroupD} onClose={() => setChangeGroupD(false)} fullWidth>
|
||||
<Grid container padding={3}>
|
||||
<Typography variant="h6" gutterBottom color="orange">Are you sure to change customer Group?</Typography>
|
||||
<FormControl fullWidth margin="dense">
|
||||
<Typography gutterBottom>Destination Group</Typography>
|
||||
<Select name="groups" value={changeGroup} onChange={(e: any) => setChangeGroup(e.target.value)}>
|
||||
{
|
||||
groups ? groups.map((el: any) => (
|
||||
<MenuItem key={el.id} value={el.id}>{el.name}</MenuItem>
|
||||
)) : ""
|
||||
}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Grid>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setChangeGroupD(false)} color="secondary">
|
||||
No
|
||||
</Button>
|
||||
<Button onClick={buttonChangeGroup} color="primary">
|
||||
Yes
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={dialogOpen}
|
||||
onClose={() => setDialogOpen(false)}
|
||||
title="Confirm Action"
|
||||
content={`Are you sure you want to ${dialogType}?`}
|
||||
onYes={handleYes}
|
||||
onNo={() => setDialogOpen(false)}
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
} 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
|
||||
}
|
||||
}
|
||||
// CUSTOMER WALLET
|
||||
function showCustomerWallet(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.wallets)
|
||||
} catch (error: any) {
|
||||
toast.error(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Box p={3} boxShadow={3} borderRadius={2} bgcolor="white">
|
||||
<Typography variant="h6" gutterBottom>Wallet Member</Typography>
|
||||
<Grid>
|
||||
<List>
|
||||
{customerWallet.length ? (customerWallet.map((item:any, index:any) => (
|
||||
<React.Fragment key={item.id}>
|
||||
<ListItem
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
px: 2,
|
||||
py: 1.5,
|
||||
bgcolor: index % 2 === 0 ? 'grey.50' : 'background.paper',
|
||||
borderRadius: 2,
|
||||
'&:hover': {
|
||||
bgcolor: 'grey.100',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box>
|
||||
<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="body1">{item.wallet.description}</Typography>
|
||||
</Box>
|
||||
<Box>
|
||||
<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>
|
||||
{index < customerWallet.length - 1 && <Divider sx={{ my: 1 }} />}
|
||||
</React.Fragment>
|
||||
))): "No wallet"}
|
||||
</List>
|
||||
</Grid>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@ -11,10 +11,12 @@ import { DataGridProvider } from '@/components';
|
||||
import { toast } from 'sonner';
|
||||
import { Breadcrumbs, Link } from '@mui/material';
|
||||
const BASE_URL_MASTER_DATA = apiConfig.service_master_data;
|
||||
const BASE_URL_CUSTOMER = apiConfig.service_customer;
|
||||
const BASE_URL = apiConfig.service_customer;
|
||||
import { Helmet } from 'react-helmet';
|
||||
import ListToolbar from './blocks/ListToolBar';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
|
||||
const ManageMembers = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [members, setMembers] = useState([]);
|
||||
@ -24,6 +26,7 @@ const ManageMembers = () => {
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [dialogType, setDialogType] = useState('');
|
||||
const [groups, setGroups] = useState([]);
|
||||
const [isReloading, setIsReloading] = useState(false);
|
||||
const closeDialog = () => {
|
||||
setIsDialogOpen(false);
|
||||
@ -69,6 +72,16 @@ const ManageMembers = () => {
|
||||
}
|
||||
});
|
||||
setProfession(getProfession.data.data.list);
|
||||
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);
|
||||
console.log(error);
|
||||
@ -259,6 +272,7 @@ const ManageMembers = () => {
|
||||
createMember={createMember}
|
||||
onReload={handleReload}
|
||||
isReloading={isReloading}
|
||||
groups={groups}
|
||||
/>
|
||||
}
|
||||
onRowSelectionChange={(selected, table: any) => {
|
||||
|
||||
@ -40,6 +40,11 @@ const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialDa
|
||||
const [postoAdm, setPostoAdm] = useState([]);
|
||||
const [sucos, setSucos] = useState<any>([]);
|
||||
const [groups, setGroups] = useState([]);
|
||||
const [identity_type] = useState([
|
||||
{ id: 'eleitoral_id', name: 'Eleitoral ID' },
|
||||
{ id: 'bihete_de_identidade', name: 'Bihete de Identidade' },
|
||||
{ id: 'passport', name: 'Passport' },
|
||||
]);
|
||||
const [genders] = useState([ { name: 'Male',id: 'M' }, { name: 'Female',id: 'F' }])
|
||||
const [previewImg, setPreviewImg] = useState({
|
||||
status: false,
|
||||
@ -65,9 +70,9 @@ const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialDa
|
||||
name === "file_commercial_license") { // FOR FILE ONLY
|
||||
setFormData({ ...formData, [name]: e.target.files[0] });
|
||||
} else if(name === "nationality") {
|
||||
setFormData({ ...formData, [name]: value });
|
||||
let getNationality = await axios.get(`${URL_NATIONALITY}/${value}`);
|
||||
setNationality(getNationality.data.data)
|
||||
setFormData({ ...formData, [name]: value });
|
||||
} else {
|
||||
if (name === 'municipio_id' || name === 'posto_adms_id' || name === 'suco_id') await getMasterAfter(name, value);
|
||||
if (name==='msisdn') setFormData({ ...formData, [name]: value.replace(/\D/g, '') })
|
||||
@ -215,6 +220,8 @@ const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialDa
|
||||
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Email', 'email', 'text', true, viewOnly): ''}
|
||||
{/* {generateList(formData, handleChange, status, 'status', 'Status', null, true)} */}
|
||||
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Mother Fullname', 'mother_fullname', 'text', true, viewOnly): ''}
|
||||
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, identity_type, 'identity_type', 'Identity Type', false, false): ''}
|
||||
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Address', 'address', 'text', true, viewOnly): ''}
|
||||
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Identity Number', 'identity_number', 'text', false, viewOnly): ''}
|
||||
<div className="bg-white space-y-6">
|
||||
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, profession, 'profession', 'Profession', false, false): ''}
|
||||
@ -238,7 +245,6 @@ const DetailMember = ({ showAddDialog, setShowAddDialog, handleSubmit, initialDa
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
{(formData.id || dialogType === "create") ? generateInput(formData, handleChange, 'Address', 'address', 'text', true, viewOnly): ''}
|
||||
<div className="bg-white p-6 rounded-md shadow-md space-y-6">
|
||||
<h2 className="text-lg font-semibold">Bank Information</h2>
|
||||
{(formData.id || dialogType === "create") ? generateList(formData, handleChange, banks, 'bank_name', 'Bank Name', false, false): ''}
|
||||
|
||||
@ -3,14 +3,22 @@ import { UserPlus } from 'lucide-react';
|
||||
import { KeenIcon, useDataGrid } from '@/components';
|
||||
import { DefaultTooltip } from '@/components';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select';
|
||||
|
||||
interface ListToolbarProps {
|
||||
createMember: () => void;
|
||||
onReload: () => void;
|
||||
isReloading: boolean;
|
||||
groups: any;
|
||||
}
|
||||
|
||||
const ListToolbar = ({ createMember, onReload, isReloading }: ListToolbarProps) => {
|
||||
const ListToolbar = ({ createMember, onReload, isReloading, groups }: ListToolbarProps) => {
|
||||
|
||||
const [groupFilter, setGroupFilter] = useState('');
|
||||
const [usernameFilter, setUsernameFilter] = useState('');
|
||||
@ -20,9 +28,11 @@ const ListToolbar = ({ createMember, onReload, isReloading }: ListToolbarProps)
|
||||
table.getColumn('username')?.setFilterValue(e.target.value);
|
||||
};
|
||||
|
||||
const handleGroupChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setGroupFilter(e.target.value);
|
||||
table.getColumn('group_name')?.setFilterValue(e.target.value);
|
||||
const handleGroupChange = (e: any) => {
|
||||
let value = e.target.value;
|
||||
if (value === '__all__') value = '';
|
||||
setGroupFilter(value);
|
||||
table.getColumn('group_name')?.setFilterValue(value);
|
||||
};
|
||||
|
||||
return (
|
||||
@ -35,15 +45,21 @@ const ListToolbar = ({ createMember, onReload, isReloading }: ListToolbarProps)
|
||||
placeholder="Search Username"
|
||||
value={usernameFilter}
|
||||
onChange={handleUsernameChange}
|
||||
className="input input-sm w-40"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search Group"
|
||||
value={groupFilter}
|
||||
onChange={handleGroupChange}
|
||||
className="input input-sm w-40"
|
||||
className="input w-40"
|
||||
/>
|
||||
<Select value={groupFilter} onValueChange={(e) => (handleGroupChange({ target : { value: e }}))}>
|
||||
<SelectTrigger className="input input-sm w-40 text-gray-500">
|
||||
<SelectValue placeholder="Select Group" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={"__all__"}>All Group</SelectItem>
|
||||
{groups.map((el: any, idx: any) => (
|
||||
<SelectItem key={idx} value={el.name}>
|
||||
{el.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex gap-3 items-center">
|
||||
<Button variant="outline" className="h-7.5 text-[0.8rem]" onClick={createMember}>
|
||||
|
||||
@ -8,6 +8,7 @@ import {
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
@ -26,7 +27,7 @@ const API_URL = apiConfig.transaction;
|
||||
|
||||
const ApprovalDialog = () => {
|
||||
const { GetData, PostData } = useCallApi();
|
||||
const { reload } = useDataGrid();
|
||||
const { reload } = useDataGrid();
|
||||
|
||||
const {
|
||||
showApprovalDialog,
|
||||
@ -40,6 +41,7 @@ const ApprovalDialog = () => {
|
||||
transaction_code: '',
|
||||
status: '',
|
||||
notes: '',
|
||||
pin: ''
|
||||
});
|
||||
|
||||
const [alert, setAlert] = useState({
|
||||
@ -63,8 +65,9 @@ const ApprovalDialog = () => {
|
||||
|
||||
const response = await PostData(`${API_URL}/transaction/set-approval`, {
|
||||
id_transaction: transactionDetails.id,
|
||||
status: formField.status,
|
||||
notes: formField.notes,
|
||||
status: formField.status,
|
||||
pin: formField.pin,
|
||||
});
|
||||
|
||||
if (response?.status === false) {
|
||||
@ -97,8 +100,9 @@ const ApprovalDialog = () => {
|
||||
if (showApprovalDialog) {
|
||||
setFormField({
|
||||
transaction_code: '',
|
||||
status: '',
|
||||
notes: '',
|
||||
status: '',
|
||||
pin:''
|
||||
});
|
||||
setTransactionDetails(null);
|
||||
setAlert({ show: false, message: '' });
|
||||
@ -142,6 +146,7 @@ const ApprovalDialog = () => {
|
||||
<DialogHeader>
|
||||
<DialogTitle>Approval Transaction</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogDescription></DialogDescription>
|
||||
<DialogBody>
|
||||
<form onSubmit={doApproval}>
|
||||
<div className="card-body grid gap-5 p-0">
|
||||
@ -165,6 +170,26 @@ const ApprovalDialog = () => {
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center flex-wrap gap-2.5 mt-3 mb-3">
|
||||
|
||||
<label className="form-label max-w-56">PIN</label>
|
||||
<div className="grow">
|
||||
<Input
|
||||
required
|
||||
type="password"
|
||||
placeholder="PIN"
|
||||
name="pin"
|
||||
id="pin"
|
||||
value={formField.pin}
|
||||
onChange={(e) =>
|
||||
setFormField((prev) => ({
|
||||
...prev,
|
||||
pin: e.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{formField.status === 'N' && (
|
||||
<div className="flex items-center flex-wrap gap-2.5 mt-4">
|
||||
|
||||
@ -58,6 +58,7 @@ const DetailApprovalTransaction = () => {
|
||||
<DialogHeader>
|
||||
<DialogTitle>Transaction Details</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogDescription></DialogDescription>
|
||||
<DialogBody>
|
||||
{/* Tabs Navigation */}
|
||||
<div className="flex border-b border-gray-200">
|
||||
|
||||
@ -1,31 +1,86 @@
|
||||
import { Container, DataGridInner } from '@/components';
|
||||
import { Alert, Container, DataGridInner } from '@/components';
|
||||
import { TransactionDisbursementProvider } from './hooks/TransactionDisbursementContext';
|
||||
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 } from 'react';
|
||||
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 TransactionDisbursement = () => {
|
||||
const [form, setForm] = useState({
|
||||
const initialForm: {
|
||||
msisdn: string;
|
||||
amount: string;
|
||||
pin: string;
|
||||
} = {
|
||||
msisdn: '',
|
||||
amount: '',
|
||||
pin: ''
|
||||
});
|
||||
};
|
||||
|
||||
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_WALLET = apiConfig.service_wallet;
|
||||
const API_URL_CUSTOMER = apiConfig.service_customer;
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [alert, setAlert] = useState({
|
||||
show: false,
|
||||
message: ''
|
||||
});
|
||||
|
||||
const fetchCustomerMsisdn = async (sorting: any, filterValue: string) => {
|
||||
const filter: any =
|
||||
filterValue.trim().length === 0 ? {} : { msisdn: { like: `%${filterValue}%` } };
|
||||
|
||||
const query: any = {
|
||||
limit: 25,
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchWallets = async () => {
|
||||
try {
|
||||
const response = await GetData(`${API_URL_WALLET}/dashboard/balance/account/${parsedUser.customer.id}`, {});
|
||||
const response = await GetData(
|
||||
`${API_URL_WALLET}/dashboard/balance/account/${parsedUser.customer.id}`,
|
||||
{}
|
||||
);
|
||||
if (response?.status === true) {
|
||||
setWallets(response.data || []);
|
||||
} else {
|
||||
@ -37,32 +92,84 @@ const TransactionDisbursement = () => {
|
||||
};
|
||||
|
||||
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 handleSubmit = async (e: any) => {
|
||||
e.preventDefault();
|
||||
console.log('Submitted Data:', form);
|
||||
if (form.amount == '' || form.msisdn == '' || form.pin == '') {
|
||||
toast.warning('Please fill in all required fields.')
|
||||
return
|
||||
}
|
||||
const doPostData = async (form: typeof initialForm) => {
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
let requestTopup = await PostData(`${API_URL}/transaction/topup-downline`, {
|
||||
let response = await PostData(`${API_URL}/transaction/topup-downline`, {
|
||||
msisdn_destination: form.msisdn,
|
||||
amount: form.amount,
|
||||
pin: form.pin
|
||||
})
|
||||
if (requestTopup?.status == true) {
|
||||
toast.success('Success Request Topup')
|
||||
});
|
||||
if (response?.status == true) {
|
||||
toast.success('Success Request Topup');
|
||||
} else {
|
||||
toast.warning(`${requestTopup?.message}`)
|
||||
toast.error(`${response?.message?.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
toast.warning('Failed')
|
||||
} 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);
|
||||
}
|
||||
};
|
||||
|
||||
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 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);
|
||||
};
|
||||
|
||||
const filteredMsisdn = customerMsisdn
|
||||
.filter((item) => item.label.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
.slice(0, 10);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
@ -70,7 +177,9 @@ const TransactionDisbursement = () => {
|
||||
</Helmet>
|
||||
<TransactionDisbursementProvider>
|
||||
<Container className="mb-7">
|
||||
<h1 className="text-xl font-medium leading-none text-gray-900 mb-5">MANAGE TRANSACTION DISBURSEMENT SALDO</h1>
|
||||
<h1 className="text-xl font-medium leading-none text-gray-900 mb-5">
|
||||
MANAGE TRANSACTION DISBURSEMENT SALDO
|
||||
</h1>
|
||||
<Breadcrumbs sx={{ mb: 2 }}>
|
||||
<Link underline="none" color="inherit" href="/">
|
||||
<span className="text-sm hover:underline">Dashboard</span>
|
||||
@ -90,51 +199,121 @@ const TransactionDisbursement = () => {
|
||||
<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)}
|
||||
{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">
|
||||
<div>
|
||||
<label htmlFor="msisdn">Destination MSISDN</label><span className="text-red-500">*</span>
|
||||
<Input
|
||||
id="msisdn"
|
||||
type="number"
|
||||
value={form.msisdn}
|
||||
onChange={(e) => setForm({ ...form, msisdn: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="amount">Amount</label><span className="text-red-500">*</span>
|
||||
<Input
|
||||
id="amount"
|
||||
type="number"
|
||||
value={form.amount}
|
||||
onChange={(e) => setForm({ ...form, amount: e.target.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>
|
||||
<Button type="submit">Submit</Button>
|
||||
</div>
|
||||
</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="amount"
|
||||
type="number"
|
||||
value={form.amount}
|
||||
onChange={(e) => setForm({ ...form, amount: e.target.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>
|
||||
<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 disbursement 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>
|
||||
</TransactionDisbursementProvider>
|
||||
</>
|
||||
|
||||
@ -45,6 +45,8 @@ const DetailTransaction = () => {
|
||||
id: selectedTransactionId
|
||||
});
|
||||
setTransactionDetails(response?.data);
|
||||
console.log(response?.data);
|
||||
console.log(selectedTransactionId);
|
||||
} catch (error) {
|
||||
console.error('Error fetching transaction', error);
|
||||
}
|
||||
@ -72,6 +74,7 @@ const DetailTransaction = () => {
|
||||
<DialogHeader>
|
||||
<DialogTitle>Transaction Details</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogDescription></DialogDescription>
|
||||
<DialogBody>
|
||||
{/* Tabs Navigation */}
|
||||
<div className="flex border-b border-gray-200">
|
||||
@ -207,7 +210,7 @@ const DetailTransaction = () => {
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Description</p>
|
||||
<p className="font-medium">{transactionDetails?.description}</p>
|
||||
<p className="font-medium">{transactionDetails?.description || '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Name</p>
|
||||
|
||||
@ -1,31 +1,46 @@
|
||||
import { Container, DataGridInner } from '@/components';
|
||||
import { Alert, Container, DataGridInner } from '@/components';
|
||||
import { TransactionTopupProvider } from './hooks/TransactionTopupContext';
|
||||
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 } from 'react';
|
||||
import React, { useState, useEffect } 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 TransactionTopup = () => {
|
||||
const [form, setForm] = useState({
|
||||
const initialState: {
|
||||
topupAmount: string;
|
||||
pin: string;
|
||||
} = {
|
||||
topupAmount: '',
|
||||
pin: ''
|
||||
};
|
||||
|
||||
const [form, setForm] = useState(initialState);
|
||||
const [alert, setAlert] = useState({
|
||||
show: false,
|
||||
message: ''
|
||||
});
|
||||
|
||||
const [wallets, setWallets] = useState([]);
|
||||
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_WALLET = apiConfig.service_wallet;
|
||||
|
||||
useEffect(() => {
|
||||
const fetchWallets = async () => {
|
||||
try {
|
||||
const response = await GetData(`${API_URL_WALLET}/dashboard/balance/account/${parsedUser.customer.id}`, {});
|
||||
const response = await GetData(
|
||||
`${API_URL_WALLET}/dashboard/balance/account/${parsedUser.customer.id}`,
|
||||
{}
|
||||
);
|
||||
if (response?.status === true) {
|
||||
setWallets(response.data || []);
|
||||
} else {
|
||||
@ -39,30 +54,49 @@ const TransactionTopup = () => {
|
||||
fetchWallets();
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: any) => {
|
||||
e.preventDefault();
|
||||
console.log('Submitted Data:', form);
|
||||
const doPostData = async (form: typeof initialState) => {
|
||||
setIsSubmitting(true);
|
||||
|
||||
if (form.pin == '' || form.topupAmount == '') {
|
||||
toast.warning('Please fill in all required fields.')
|
||||
return
|
||||
}
|
||||
try {
|
||||
let requestTopup = await PostData(`${API_URL}/transaction/request-topup`, {
|
||||
let response = await PostData(`${API_URL}/transaction/request-topup`, {
|
||||
amount: form.topupAmount,
|
||||
pin: form.pin
|
||||
})
|
||||
if (requestTopup?.status == true) {
|
||||
toast.success('Success Request Topup')
|
||||
});
|
||||
console.log(response);
|
||||
if (response?.status == true) {
|
||||
toast.success('Success Request Topup');
|
||||
} else {
|
||||
toast.warning(`${requestTopup?.message}`)
|
||||
toast.warning(`${response?.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
toast.warning('Failed')
|
||||
} catch (error: any) {
|
||||
const errorMessage =
|
||||
error?.response?.data?.message || error?.message || 'Something went wrong';
|
||||
toast.error(errorMessage);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
setShowConfirmation(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
// console.log('Submitted Data:', form);
|
||||
|
||||
if (form.pin == '' || form.topupAmount == '') {
|
||||
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 handleCancelSubmit = () => {
|
||||
setShowConfirmation(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
@ -70,7 +104,9 @@ const TransactionTopup = () => {
|
||||
</Helmet>
|
||||
<TransactionTopupProvider>
|
||||
<Container className="mb-7">
|
||||
<h1 className="text-xl font-medium leading-none text-gray-900 mb-5">MANAGE TRANSACTION TOPUP REQUEST</h1>
|
||||
<h1 className="text-xl font-medium leading-none text-gray-900 mb-5">
|
||||
MANAGE TRANSACTION TOPUP REQUEST
|
||||
</h1>
|
||||
<Breadcrumbs sx={{ mb: 2 }}>
|
||||
<Link underline="none" color="inherit" href="/">
|
||||
<span className="text-sm hover:underline">Dashboard</span>
|
||||
@ -82,6 +118,7 @@ const TransactionTopup = () => {
|
||||
<span className="text-sm">Topup</span>
|
||||
</Link>
|
||||
</Breadcrumbs>
|
||||
|
||||
{/* Wallet Section */}
|
||||
<div className="mb-6">
|
||||
<h2 className="text-md font-semibold text-gray-700 mb-3">Your Wallets</h2>
|
||||
@ -90,7 +127,9 @@ const TransactionTopup = () => {
|
||||
<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)}
|
||||
{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(
|
||||
wallet.amount
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
@ -99,10 +138,16 @@ const TransactionTopup = () => {
|
||||
<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">
|
||||
<form onSubmit={handleSubmit} className="space-y-6 mt-5">
|
||||
<div>
|
||||
<label htmlFor="topupAmount">Topup Amount</label><span className="text-red-500">*</span>
|
||||
<label htmlFor="topupAmount">Topup Amount</label>
|
||||
<span className="text-red-500">*</span>
|
||||
<Input
|
||||
id="topupAmount"
|
||||
type="number"
|
||||
@ -111,7 +156,8 @@ const TransactionTopup = () => {
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="pin">PIN</label><span className="text-red-500">*</span>
|
||||
<label htmlFor="pin">PIN</label>
|
||||
<span className="text-red-500">*</span>
|
||||
<Input
|
||||
id="pin"
|
||||
type="password"
|
||||
@ -120,12 +166,46 @@ const TransactionTopup = () => {
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="submit">Submit</Button>
|
||||
<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 request a topup of{' '}
|
||||
<span className="font-semibold">
|
||||
{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(
|
||||
Number(form.topupAmount)
|
||||
)}{' '}
|
||||
</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>
|
||||
</TransactionTopupProvider>
|
||||
</>
|
||||
|
||||
Reference in New Issue
Block a user