[OQI-004] feat: Complete investment module with all pages
- Add Withdrawals.tsx with global withdrawals list and status filters - Add Transactions.tsx with global transaction history and type/account filters - Add Reports.tsx with allocation chart, performance bars, and export - Add ProductDetail.tsx with performance chart and investment form - Add routes for all new pages in App.tsx OQI-004 progress: 45% -> 75% Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
e158d4228e
commit
639c70587a
@ -30,6 +30,10 @@ const Investment = lazy(() => import('./modules/investment/pages/Investment'));
|
||||
const InvestmentPortfolio = lazy(() => import('./modules/investment/pages/Portfolio'));
|
||||
const InvestmentProducts = lazy(() => import('./modules/investment/pages/Products'));
|
||||
const AccountDetail = lazy(() => import('./modules/investment/pages/AccountDetail'));
|
||||
const Withdrawals = lazy(() => import('./modules/investment/pages/Withdrawals'));
|
||||
const InvestmentTransactions = lazy(() => import('./modules/investment/pages/Transactions'));
|
||||
const InvestmentReports = lazy(() => import('./modules/investment/pages/Reports'));
|
||||
const ProductDetail = lazy(() => import('./modules/investment/pages/ProductDetail'));
|
||||
const Settings = lazy(() => import('./modules/settings/pages/Settings'));
|
||||
const Assistant = lazy(() => import('./modules/assistant/pages/Assistant'));
|
||||
|
||||
@ -93,6 +97,10 @@ function App() {
|
||||
<Route path="/investment/portfolio" element={<InvestmentPortfolio />} />
|
||||
<Route path="/investment/products" element={<InvestmentProducts />} />
|
||||
<Route path="/investment/accounts/:accountId" element={<AccountDetail />} />
|
||||
<Route path="/investment/withdrawals" element={<Withdrawals />} />
|
||||
<Route path="/investment/transactions" element={<InvestmentTransactions />} />
|
||||
<Route path="/investment/reports" element={<InvestmentReports />} />
|
||||
<Route path="/investment/products/:productId" element={<ProductDetail />} />
|
||||
|
||||
{/* Portfolio Manager */}
|
||||
<Route path="/portfolio" element={<PortfolioDashboard />} />
|
||||
|
||||
447
src/modules/investment/pages/ProductDetail.tsx
Normal file
447
src/modules/investment/pages/ProductDetail.tsx
Normal file
@ -0,0 +1,447 @@
|
||||
/**
|
||||
* Product Detail Page
|
||||
* Shows detailed information about an investment product
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useRef } from 'react';
|
||||
import { useParams, useNavigate, Link } from 'react-router-dom';
|
||||
import { ArrowLeft, Shield, TrendingUp, Zap, AlertCircle, Info, CheckCircle } from 'lucide-react';
|
||||
import investmentService, { Product, ProductPerformance } from '../../../services/investment.service';
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type Period = 'week' | 'month' | '3months' | 'year';
|
||||
|
||||
// ============================================================================
|
||||
// Subcomponents
|
||||
// ============================================================================
|
||||
|
||||
interface PerformanceChartProps {
|
||||
data: ProductPerformance[];
|
||||
}
|
||||
|
||||
const PerformanceChart: React.FC<PerformanceChartProps> = ({ data }) => {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas || data.length === 0) return;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
const padding = { top: 20, right: 20, bottom: 40, left: 60 };
|
||||
const chartWidth = width - padding.left - padding.right;
|
||||
const chartHeight = height - padding.top - padding.bottom;
|
||||
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
|
||||
const returns = data.map(d => d.cumulativeReturn * 100);
|
||||
const minReturn = Math.min(...returns, 0) - 5;
|
||||
const maxReturn = Math.max(...returns) + 5;
|
||||
|
||||
// Draw grid
|
||||
ctx.strokeStyle = '#374151';
|
||||
ctx.lineWidth = 0.5;
|
||||
for (let i = 0; i <= 4; i++) {
|
||||
const y = padding.top + (chartHeight / 4) * i;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(padding.left, y);
|
||||
ctx.lineTo(width - padding.right, y);
|
||||
ctx.stroke();
|
||||
|
||||
const value = maxReturn - ((maxReturn - minReturn) / 4) * i;
|
||||
ctx.fillStyle = '#9CA3AF';
|
||||
ctx.font = '11px system-ui';
|
||||
ctx.textAlign = 'right';
|
||||
ctx.fillText(`${value.toFixed(1)}%`, padding.left - 10, y + 4);
|
||||
}
|
||||
|
||||
// Zero line
|
||||
const zeroY = padding.top + ((maxReturn - 0) / (maxReturn - minReturn)) * chartHeight;
|
||||
ctx.strokeStyle = '#6B7280';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.setLineDash([5, 5]);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(padding.left, zeroY);
|
||||
ctx.lineTo(width - padding.right, zeroY);
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
|
||||
// Draw line
|
||||
const isPositive = returns[returns.length - 1] >= 0;
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = isPositive ? '#10B981' : '#EF4444';
|
||||
ctx.lineWidth = 2;
|
||||
|
||||
data.forEach((point, i) => {
|
||||
const x = padding.left + (chartWidth / (data.length - 1)) * i;
|
||||
const y = padding.top + ((maxReturn - point.cumulativeReturn * 100) / (maxReturn - minReturn)) * chartHeight;
|
||||
|
||||
if (i === 0) {
|
||||
ctx.moveTo(x, y);
|
||||
} else {
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
});
|
||||
ctx.stroke();
|
||||
|
||||
// Gradient fill
|
||||
const gradient = ctx.createLinearGradient(0, padding.top, 0, height - padding.bottom);
|
||||
gradient.addColorStop(0, isPositive ? 'rgba(16, 185, 129, 0.2)' : 'rgba(239, 68, 68, 0.2)');
|
||||
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
|
||||
|
||||
ctx.beginPath();
|
||||
data.forEach((point, i) => {
|
||||
const x = padding.left + (chartWidth / (data.length - 1)) * i;
|
||||
const y = padding.top + ((maxReturn - point.cumulativeReturn * 100) / (maxReturn - minReturn)) * chartHeight;
|
||||
if (i === 0) ctx.moveTo(x, y);
|
||||
else ctx.lineTo(x, y);
|
||||
});
|
||||
ctx.lineTo(padding.left + chartWidth, zeroY);
|
||||
ctx.lineTo(padding.left, zeroY);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fill();
|
||||
|
||||
// X-axis labels
|
||||
const labelIndices = [0, Math.floor(data.length / 2), data.length - 1];
|
||||
ctx.fillStyle = '#9CA3AF';
|
||||
ctx.font = '11px system-ui';
|
||||
ctx.textAlign = 'center';
|
||||
labelIndices.forEach(i => {
|
||||
if (data[i]) {
|
||||
const x = padding.left + (chartWidth / (data.length - 1)) * i;
|
||||
const date = new Date(data[i].date);
|
||||
ctx.fillText(date.toLocaleDateString('es-ES', { month: 'short', day: 'numeric' }), x, height - 15);
|
||||
}
|
||||
});
|
||||
}, [data]);
|
||||
|
||||
return <canvas ref={canvasRef} width={800} height={300} className="w-full h-auto" />;
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Main Component
|
||||
// ============================================================================
|
||||
|
||||
export const ProductDetail: React.FC = () => {
|
||||
const { productId } = useParams<{ productId: string }>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [product, setProduct] = useState<Product | null>(null);
|
||||
const [performance, setPerformance] = useState<ProductPerformance[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [period, setPeriod] = useState<Period>('month');
|
||||
const [investing, setInvesting] = useState(false);
|
||||
const [investAmount, setInvestAmount] = useState<number>(1000);
|
||||
|
||||
useEffect(() => {
|
||||
if (productId) {
|
||||
loadProduct();
|
||||
}
|
||||
}, [productId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (productId) {
|
||||
loadPerformance();
|
||||
}
|
||||
}, [productId, period]);
|
||||
|
||||
const loadProduct = async () => {
|
||||
if (!productId) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const data = await investmentService.getProductById(productId);
|
||||
setProduct(data);
|
||||
setInvestAmount(data.minInvestment);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error loading product');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadPerformance = async () => {
|
||||
if (!productId) return;
|
||||
|
||||
try {
|
||||
const data = await investmentService.getProductPerformance(productId, period);
|
||||
setPerformance(data);
|
||||
} catch (err) {
|
||||
console.error('Error loading performance:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInvest = async () => {
|
||||
if (!product || investing) return;
|
||||
|
||||
try {
|
||||
setInvesting(true);
|
||||
await investmentService.createAccount(product.id, investAmount);
|
||||
navigate('/investment/portfolio');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error creating account');
|
||||
} finally {
|
||||
setInvesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const periodOptions: { value: Period; label: string }[] = [
|
||||
{ value: 'week', label: '7 días' },
|
||||
{ value: 'month', label: '30 días' },
|
||||
{ value: '3months', label: '3 meses' },
|
||||
{ value: 'year', label: '1 año' },
|
||||
];
|
||||
|
||||
const icons: Record<string, React.ReactNode> = {
|
||||
atlas: <Shield className="w-8 h-8 text-blue-500" />,
|
||||
orion: <TrendingUp className="w-8 h-8 text-purple-500" />,
|
||||
nova: <Zap className="w-8 h-8 text-orange-500" />,
|
||||
};
|
||||
|
||||
const riskColors = {
|
||||
conservative: 'text-green-500 bg-green-100 dark:bg-green-900/30',
|
||||
moderate: 'text-yellow-500 bg-yellow-100 dark:bg-yellow-900/30',
|
||||
aggressive: 'text-red-500 bg-red-100 dark:bg-red-900/30',
|
||||
};
|
||||
|
||||
const riskLabels = {
|
||||
conservative: 'Conservador',
|
||||
moderate: 'Moderado',
|
||||
aggressive: 'Agresivo',
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-96">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !product) {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 py-8">
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-6 text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<h2 className="text-xl font-bold text-red-700 dark:text-red-400 mb-2">
|
||||
Error al cargar el producto
|
||||
</h2>
|
||||
<p className="text-red-600 dark:text-red-300 mb-4">{error || 'Producto no encontrado'}</p>
|
||||
<button
|
||||
onClick={() => navigate('/investment/products')}
|
||||
className="px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
|
||||
>
|
||||
Volver a Productos
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const currentReturn = performance.length > 0 ? performance[performance.length - 1].cumulativeReturn * 100 : 0;
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto px-4 py-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4 mb-8">
|
||||
<button
|
||||
onClick={() => navigate('/investment/products')}
|
||||
className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
</button>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-3">
|
||||
{icons[product.code] || icons.atlas}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
{product.name}
|
||||
</h1>
|
||||
<span className={`px-3 py-1 rounded-full text-sm font-medium ${riskColors[product.riskProfile]}`}>
|
||||
{riskLabels[product.riskProfile]}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-3 gap-8">
|
||||
{/* Main Content */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
{/* Description */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">
|
||||
Descripción
|
||||
</h2>
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
{product.description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Performance Chart */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-bold text-gray-900 dark:text-white">
|
||||
Rendimiento Histórico
|
||||
</h2>
|
||||
<div className="flex gap-1">
|
||||
{periodOptions.map(option => (
|
||||
<button
|
||||
key={option.value}
|
||||
onClick={() => setPeriod(option.value)}
|
||||
className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
|
||||
period === option.value
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{performance.length > 0 ? (
|
||||
<>
|
||||
<PerformanceChart data={performance} />
|
||||
<div className="mt-4 text-center">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Retorno acumulado</p>
|
||||
<p className={`text-3xl font-bold ${currentReturn >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{currentReturn >= 0 ? '+' : ''}{currentReturn.toFixed(2)}%
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-gray-500 dark:text-gray-400 text-center py-12">
|
||||
No hay datos de rendimiento disponibles
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Features */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">
|
||||
Características
|
||||
</h2>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-white">Target Mensual</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{product.targetReturnMin}% - {product.targetReturnMax}%
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-white">Max Drawdown</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">{product.maxDrawdown}%</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-white">Comisión de Gestión</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">{product.managementFee}% anual</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-white">Comisión de Éxito</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">{product.performanceFee}% sobre ganancias</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sidebar - Investment Card */}
|
||||
<div className="lg:col-span-1">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg sticky top-4">
|
||||
<h2 className="text-lg font-bold text-gray-900 dark:text-white mb-6">
|
||||
Invertir
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4 mb-6">
|
||||
<div>
|
||||
<label className="block text-sm text-gray-500 dark:text-gray-400 mb-2">
|
||||
Monto a invertir
|
||||
</label>
|
||||
<div className="relative">
|
||||
<span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500">$</span>
|
||||
<input
|
||||
type="number"
|
||||
min={product.minInvestment}
|
||||
step="100"
|
||||
value={investAmount}
|
||||
onChange={(e) => setInvestAmount(Number(e.target.value))}
|
||||
className="w-full pl-8 pr-4 py-3 bg-gray-100 dark:bg-gray-900 rounded-lg text-lg font-medium text-gray-900 dark:text-white border-0 focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
Mínimo: ${product.minInvestment.toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{[500, 1000, 5000, 10000].map(amount => (
|
||||
<button
|
||||
key={amount}
|
||||
onClick={() => setInvestAmount(amount)}
|
||||
className={`flex-1 px-2 py-1.5 text-sm rounded-lg transition-colors ${
|
||||
investAmount === amount
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
${amount >= 1000 ? `${amount / 1000}k` : amount}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleInvest}
|
||||
disabled={investing || investAmount < product.minInvestment}
|
||||
className="w-full py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"
|
||||
>
|
||||
{investing ? 'Procesando...' : 'Invertir Ahora'}
|
||||
</button>
|
||||
|
||||
<div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
|
||||
<div className="flex items-start gap-2">
|
||||
<Info className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-blue-700 dark:text-blue-300">
|
||||
Tu inversión será gestionada automáticamente por nuestros agentes de IA.
|
||||
Podrás retirar fondos en cualquier momento.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Risk Warning */}
|
||||
<div className="mt-8 p-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
|
||||
<p className="text-sm text-yellow-800 dark:text-yellow-200">
|
||||
<strong>Advertencia de riesgo:</strong> El trading de activos financieros conlleva riesgos significativos.
|
||||
Los rendimientos pasados no garantizan rendimientos futuros. Los rendimientos objetivo son estimados
|
||||
y pueden variar. Solo invierte lo que puedas permitirte perder.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductDetail;
|
||||
422
src/modules/investment/pages/Reports.tsx
Normal file
422
src/modules/investment/pages/Reports.tsx
Normal file
@ -0,0 +1,422 @@
|
||||
/**
|
||||
* Reports Page
|
||||
* Investment analytics and performance reports
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useRef } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { ArrowLeft, TrendingUp, TrendingDown, PieChart, BarChart3, Download, Calendar, AlertCircle } from 'lucide-react';
|
||||
import investmentService, { AccountSummary, InvestmentAccount } from '../../../services/investment.service';
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type Period = 'week' | 'month' | '3months' | 'year' | 'all';
|
||||
|
||||
// ============================================================================
|
||||
// Subcomponents
|
||||
// ============================================================================
|
||||
|
||||
interface AllocationChartProps {
|
||||
accounts: InvestmentAccount[];
|
||||
}
|
||||
|
||||
const AllocationChart: React.FC<AllocationChartProps> = ({ accounts }) => {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas || accounts.length === 0) return;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const total = accounts.reduce((sum, a) => sum + a.balance, 0);
|
||||
if (total === 0) return;
|
||||
|
||||
const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];
|
||||
const centerX = canvas.width / 2;
|
||||
const centerY = canvas.height / 2;
|
||||
const radius = Math.min(centerX, centerY) - 20;
|
||||
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
let startAngle = -Math.PI / 2;
|
||||
accounts.forEach((account, i) => {
|
||||
const sliceAngle = (account.balance / total) * 2 * Math.PI;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(centerX, centerY);
|
||||
ctx.arc(centerX, centerY, radius, startAngle, startAngle + sliceAngle);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = colors[i % colors.length];
|
||||
ctx.fill();
|
||||
|
||||
startAngle += sliceAngle;
|
||||
});
|
||||
|
||||
// Inner circle (donut)
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, radius * 0.6, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = '#1F2937';
|
||||
ctx.fill();
|
||||
|
||||
// Center text
|
||||
ctx.fillStyle = '#FFFFFF';
|
||||
ctx.font = 'bold 24px system-ui';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(`$${(total / 1000).toFixed(1)}k`, centerX, centerY);
|
||||
}, [accounts]);
|
||||
|
||||
const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];
|
||||
const total = accounts.reduce((sum, a) => sum + a.balance, 0);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-6">
|
||||
<canvas ref={canvasRef} width={200} height={200} />
|
||||
<div className="space-y-2">
|
||||
{accounts.map((account, i) => (
|
||||
<div key={account.id} className="flex items-center gap-2">
|
||||
<div
|
||||
className="w-3 h-3 rounded-full"
|
||||
style={{ backgroundColor: colors[i % colors.length] }}
|
||||
/>
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||
{account.product.name}
|
||||
</span>
|
||||
<span className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{total > 0 ? ((account.balance / total) * 100).toFixed(1) : 0}%
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface PerformanceBarChartProps {
|
||||
data: { label: string; value: number }[];
|
||||
}
|
||||
|
||||
const PerformanceBarChart: React.FC<PerformanceBarChartProps> = ({ data }) => {
|
||||
const maxValue = Math.max(...data.map(d => Math.abs(d.value)), 1);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{data.map((item, i) => (
|
||||
<div key={i}>
|
||||
<div className="flex justify-between text-sm mb-1">
|
||||
<span className="text-gray-600 dark:text-gray-400">{item.label}</span>
|
||||
<span className={`font-medium ${item.value >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{item.value >= 0 ? '+' : ''}{item.value.toFixed(2)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full ${item.value >= 0 ? 'bg-green-500' : 'bg-red-500'}`}
|
||||
style={{ width: `${(Math.abs(item.value) / maxValue) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Main Component
|
||||
// ============================================================================
|
||||
|
||||
export const Reports: React.FC = () => {
|
||||
const [summary, setSummary] = useState<AccountSummary | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [period, setPeriod] = useState<Period>('month');
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
const loadData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const data = await investmentService.getAccountSummary();
|
||||
setSummary(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error loading reports');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const periodOptions: { value: Period; label: string }[] = [
|
||||
{ value: 'week', label: '7 días' },
|
||||
{ value: 'month', label: '30 días' },
|
||||
{ value: '3months', label: '3 meses' },
|
||||
{ value: 'year', label: '1 año' },
|
||||
{ value: 'all', label: 'Todo' },
|
||||
];
|
||||
|
||||
const performanceByAccount = summary?.accounts.map(account => {
|
||||
const totalReturn = account.balance - account.totalDeposited + account.totalWithdrawn;
|
||||
const returnPercent = account.totalDeposited > 0 ? (totalReturn / account.totalDeposited) * 100 : 0;
|
||||
return {
|
||||
label: account.product.name,
|
||||
value: returnPercent,
|
||||
};
|
||||
}) || [];
|
||||
|
||||
const handleExport = () => {
|
||||
if (!summary) return;
|
||||
|
||||
const reportData = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
summary: {
|
||||
totalBalance: summary.totalBalance,
|
||||
totalDeposited: summary.totalDeposited,
|
||||
totalWithdrawn: summary.totalWithdrawn,
|
||||
overallReturn: summary.overallReturn,
|
||||
overallReturnPercent: summary.overallReturnPercent,
|
||||
},
|
||||
accounts: summary.accounts.map(a => ({
|
||||
name: a.product.name,
|
||||
balance: a.balance,
|
||||
deposited: a.totalDeposited,
|
||||
withdrawn: a.totalWithdrawn,
|
||||
earnings: a.totalEarnings,
|
||||
})),
|
||||
};
|
||||
|
||||
const blob = new Blob([JSON.stringify(reportData, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `investment-report-${new Date().toISOString().split('T')[0]}.json`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-96">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 py-8">
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-6 text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<p className="text-red-600 dark:text-red-400">{error}</p>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="mt-4 px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
|
||||
>
|
||||
Reintentar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!summary) return null;
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto px-4 py-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link
|
||||
to="/investment/portfolio"
|
||||
className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
Reportes
|
||||
</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">
|
||||
Análisis de rendimiento de inversiones
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleExport}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
Exportar
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Period Filter */}
|
||||
<div className="flex items-center gap-2 mb-8 overflow-x-auto pb-2">
|
||||
<Calendar className="w-4 h-4 text-gray-500 flex-shrink-0" />
|
||||
{periodOptions.map(option => (
|
||||
<button
|
||||
key={option.value}
|
||||
onClick={() => setPeriod(option.value)}
|
||||
className={`px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${
|
||||
period === option.value
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Summary Cards */}
|
||||
<div className="grid md:grid-cols-4 gap-4 mb-8">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-gray-500 dark:text-gray-400 text-sm">Valor Total</span>
|
||||
<TrendingUp className="w-5 h-5 text-blue-500" />
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
${summary.totalBalance.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-gray-500 dark:text-gray-400 text-sm">Total Invertido</span>
|
||||
<BarChart3 className="w-5 h-5 text-purple-500" />
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
${summary.totalDeposited.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-gray-500 dark:text-gray-400 text-sm">Ganancia/Pérdida</span>
|
||||
{summary.overallReturn >= 0 ? (
|
||||
<TrendingUp className="w-5 h-5 text-green-500" />
|
||||
) : (
|
||||
<TrendingDown className="w-5 h-5 text-red-500" />
|
||||
)}
|
||||
</div>
|
||||
<p className={`text-2xl font-bold ${summary.overallReturn >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{summary.overallReturn >= 0 ? '+' : ''}${Math.abs(summary.overallReturn).toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
<p className={`text-sm ${summary.overallReturnPercent >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{summary.overallReturnPercent >= 0 ? '+' : ''}{summary.overallReturnPercent.toFixed(2)}%
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-gray-500 dark:text-gray-400 text-sm">Total Retirado</span>
|
||||
<PieChart className="w-5 h-5 text-orange-500" />
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
${summary.totalWithdrawn.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Charts */}
|
||||
<div className="grid md:grid-cols-2 gap-6 mb-8">
|
||||
{/* Allocation Chart */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<h3 className="text-lg font-bold text-gray-900 dark:text-white mb-6">
|
||||
Distribución del Portfolio
|
||||
</h3>
|
||||
{summary.accounts.length > 0 ? (
|
||||
<AllocationChart accounts={summary.accounts} />
|
||||
) : (
|
||||
<p className="text-gray-500 dark:text-gray-400 text-center py-8">
|
||||
No hay cuentas para mostrar
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Performance by Account */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<h3 className="text-lg font-bold text-gray-900 dark:text-white mb-6">
|
||||
Rendimiento por Cuenta
|
||||
</h3>
|
||||
{performanceByAccount.length > 0 ? (
|
||||
<PerformanceBarChart data={performanceByAccount} />
|
||||
) : (
|
||||
<p className="text-gray-500 dark:text-gray-400 text-center py-8">
|
||||
No hay datos de rendimiento
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Account Details Table */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg overflow-hidden">
|
||||
<div className="p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<h3 className="text-lg font-bold text-gray-900 dark:text-white">
|
||||
Detalle por Cuenta
|
||||
</h3>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-50 dark:bg-gray-900/50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Cuenta
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Balance
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Invertido
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Ganancias
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Retorno
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
{summary.accounts.map(account => {
|
||||
const totalReturn = account.balance - account.totalDeposited + account.totalWithdrawn;
|
||||
const returnPercent = account.totalDeposited > 0 ? (totalReturn / account.totalDeposited) * 100 : 0;
|
||||
return (
|
||||
<tr key={account.id} className="hover:bg-gray-50 dark:hover:bg-gray-900/30">
|
||||
<td className="px-6 py-4">
|
||||
<Link
|
||||
to={`/investment/accounts/${account.id}`}
|
||||
className="font-medium text-blue-600 hover:text-blue-700"
|
||||
>
|
||||
{account.product.name}
|
||||
</Link>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 capitalize">
|
||||
{account.product.riskProfile}
|
||||
</p>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right font-medium text-gray-900 dark:text-white">
|
||||
${account.balance.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right text-gray-600 dark:text-gray-400">
|
||||
${account.totalDeposited.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</td>
|
||||
<td className={`px-6 py-4 text-right font-medium ${totalReturn >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{totalReturn >= 0 ? '+' : ''}${Math.abs(totalReturn).toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</td>
|
||||
<td className={`px-6 py-4 text-right font-medium ${returnPercent >= 0 ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{returnPercent >= 0 ? '+' : ''}{returnPercent.toFixed(2)}%
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Reports;
|
||||
328
src/modules/investment/pages/Transactions.tsx
Normal file
328
src/modules/investment/pages/Transactions.tsx
Normal file
@ -0,0 +1,328 @@
|
||||
/**
|
||||
* Transactions Page
|
||||
* Global transaction history across all investment accounts
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { ArrowLeft, ArrowDownCircle, ArrowUpCircle, Gift, Receipt, RefreshCw, Filter, Calendar, AlertCircle } from 'lucide-react';
|
||||
import investmentService, { Transaction, InvestmentAccount } from '../../../services/investment.service';
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type TransactionType = 'all' | 'deposit' | 'withdrawal' | 'distribution' | 'fee';
|
||||
|
||||
interface TransactionWithAccount extends Transaction {
|
||||
accountName?: string;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Subcomponents
|
||||
// ============================================================================
|
||||
|
||||
interface TransactionRowProps {
|
||||
transaction: TransactionWithAccount;
|
||||
}
|
||||
|
||||
const TransactionRow: React.FC<TransactionRowProps> = ({ transaction }) => {
|
||||
const typeConfig = {
|
||||
deposit: {
|
||||
icon: <ArrowDownCircle className="w-5 h-5" />,
|
||||
color: 'text-green-500',
|
||||
bg: 'bg-green-100 dark:bg-green-900/30',
|
||||
label: 'Depósito',
|
||||
sign: '+',
|
||||
},
|
||||
withdrawal: {
|
||||
icon: <ArrowUpCircle className="w-5 h-5" />,
|
||||
color: 'text-red-500',
|
||||
bg: 'bg-red-100 dark:bg-red-900/30',
|
||||
label: 'Retiro',
|
||||
sign: '-',
|
||||
},
|
||||
distribution: {
|
||||
icon: <Gift className="w-5 h-5" />,
|
||||
color: 'text-blue-500',
|
||||
bg: 'bg-blue-100 dark:bg-blue-900/30',
|
||||
label: 'Distribución',
|
||||
sign: '+',
|
||||
},
|
||||
fee: {
|
||||
icon: <Receipt className="w-5 h-5" />,
|
||||
color: 'text-orange-500',
|
||||
bg: 'bg-orange-100 dark:bg-orange-900/30',
|
||||
label: 'Comisión',
|
||||
sign: '-',
|
||||
},
|
||||
adjustment: {
|
||||
icon: <RefreshCw className="w-5 h-5" />,
|
||||
color: 'text-purple-500',
|
||||
bg: 'bg-purple-100 dark:bg-purple-900/30',
|
||||
label: 'Ajuste',
|
||||
sign: '',
|
||||
},
|
||||
};
|
||||
|
||||
const config = typeConfig[transaction.type] || typeConfig.adjustment;
|
||||
const isCredit = ['deposit', 'distribution'].includes(transaction.type);
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
|
||||
completed: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
|
||||
failed: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
|
||||
cancelled: 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between py-4 px-4 bg-white dark:bg-gray-800 rounded-lg shadow mb-2 hover:shadow-md transition-shadow">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className={`p-2 rounded-lg ${config.bg} ${config.color}`}>
|
||||
{config.icon}
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="font-medium text-gray-900 dark:text-white">{config.label}</p>
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full ${statusColors[transaction.status]}`}>
|
||||
{transaction.status}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{new Date(transaction.createdAt).toLocaleDateString()} - {transaction.description || transaction.accountName || 'Sin descripción'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className={`font-bold text-lg ${isCredit ? 'text-green-500' : 'text-red-500'}`}>
|
||||
{config.sign}${Math.abs(transaction.amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
Balance: ${transaction.balanceAfter.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Main Component
|
||||
// ============================================================================
|
||||
|
||||
export const Transactions: React.FC = () => {
|
||||
const [transactions, setTransactions] = useState<TransactionWithAccount[]>([]);
|
||||
const [accounts, setAccounts] = useState<InvestmentAccount[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [typeFilter, setTypeFilter] = useState<TransactionType>('all');
|
||||
const [selectedAccount, setSelectedAccount] = useState<string>('all');
|
||||
const [dateRange, setDateRange] = useState<'week' | 'month' | '3months' | 'all'>('month');
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (accounts.length > 0) {
|
||||
loadTransactions();
|
||||
}
|
||||
}, [typeFilter, selectedAccount, accounts]);
|
||||
|
||||
const loadData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const accountsData = await investmentService.getUserAccounts();
|
||||
setAccounts(accountsData);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error loading accounts');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadTransactions = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const allTransactions: TransactionWithAccount[] = [];
|
||||
|
||||
const accountsToFetch = selectedAccount === 'all'
|
||||
? accounts
|
||||
: accounts.filter(a => a.id === selectedAccount);
|
||||
|
||||
for (const account of accountsToFetch) {
|
||||
const { transactions: txs } = await investmentService.getTransactions(account.id, {
|
||||
type: typeFilter === 'all' ? undefined : typeFilter,
|
||||
limit: 50,
|
||||
});
|
||||
allTransactions.push(
|
||||
...txs.map(tx => ({ ...tx, accountName: account.product.name }))
|
||||
);
|
||||
}
|
||||
|
||||
// Sort by date descending
|
||||
allTransactions.sort((a, b) =>
|
||||
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
||||
);
|
||||
|
||||
setTransactions(allTransactions);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error loading transactions');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const typeOptions: { value: TransactionType; label: string }[] = [
|
||||
{ value: 'all', label: 'Todos' },
|
||||
{ value: 'deposit', label: 'Depósitos' },
|
||||
{ value: 'withdrawal', label: 'Retiros' },
|
||||
{ value: 'distribution', label: 'Distribuciones' },
|
||||
{ value: 'fee', label: 'Comisiones' },
|
||||
];
|
||||
|
||||
const stats = {
|
||||
deposits: transactions.filter(t => t.type === 'deposit').reduce((sum, t) => sum + t.amount, 0),
|
||||
withdrawals: transactions.filter(t => t.type === 'withdrawal').reduce((sum, t) => sum + t.amount, 0),
|
||||
distributions: transactions.filter(t => t.type === 'distribution').reduce((sum, t) => sum + t.amount, 0),
|
||||
fees: transactions.filter(t => t.type === 'fee').reduce((sum, t) => sum + t.amount, 0),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto px-4 py-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4 mb-8">
|
||||
<Link
|
||||
to="/investment/portfolio"
|
||||
className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
Transacciones
|
||||
</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">
|
||||
Historial completo de movimientos
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Depósitos</p>
|
||||
<p className="text-xl font-bold text-green-500">
|
||||
+${stats.deposits.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Retiros</p>
|
||||
<p className="text-xl font-bold text-red-500">
|
||||
-${stats.withdrawals.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Distribuciones</p>
|
||||
<p className="text-xl font-bold text-blue-500">
|
||||
+${stats.distributions.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Comisiones</p>
|
||||
<p className="text-xl font-bold text-orange-500">
|
||||
-${stats.fees.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow mb-6">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
{/* Type Filter */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Filter className="w-4 h-4 text-gray-500" />
|
||||
<div className="flex gap-1">
|
||||
{typeOptions.map(option => (
|
||||
<button
|
||||
key={option.value}
|
||||
onClick={() => setTypeFilter(option.value)}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
|
||||
typeFilter === option.value
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Account Filter */}
|
||||
{accounts.length > 1 && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-gray-500">Cuenta:</span>
|
||||
<select
|
||||
value={selectedAccount}
|
||||
onChange={(e) => setSelectedAccount(e.target.value)}
|
||||
className="px-3 py-1.5 bg-gray-100 dark:bg-gray-700 rounded-lg text-sm text-gray-900 dark:text-white border-0 focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="all">Todas las cuentas</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>
|
||||
{account.product.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-6 text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<p className="text-red-600 dark:text-red-400">{error}</p>
|
||||
<button
|
||||
onClick={loadData}
|
||||
className="mt-4 px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
|
||||
>
|
||||
Reintentar
|
||||
</button>
|
||||
</div>
|
||||
) : transactions.length === 0 ? (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-800 rounded-xl shadow-lg">
|
||||
<span className="text-6xl mb-4 block">📋</span>
|
||||
<h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
|
||||
No hay transacciones
|
||||
</h3>
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-6">
|
||||
{typeFilter === 'all'
|
||||
? 'Aún no tienes transacciones registradas'
|
||||
: `No hay transacciones de tipo "${typeOptions.find(f => f.value === typeFilter)?.label}"`}
|
||||
</p>
|
||||
<Link
|
||||
to="/investment/portfolio"
|
||||
className="inline-block px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
|
||||
>
|
||||
Ir al Portfolio
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{transactions.map(transaction => (
|
||||
<TransactionRow key={transaction.id} transaction={transaction} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Transactions;
|
||||
269
src/modules/investment/pages/Withdrawals.tsx
Normal file
269
src/modules/investment/pages/Withdrawals.tsx
Normal file
@ -0,0 +1,269 @@
|
||||
/**
|
||||
* Withdrawals Page
|
||||
* Lists all user withdrawal requests across all investment accounts
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { ArrowLeft, Clock, CheckCircle, XCircle, AlertCircle, Filter } from 'lucide-react';
|
||||
import investmentService, { Withdrawal } from '../../../services/investment.service';
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type StatusFilter = 'all' | 'pending' | 'approved' | 'processing' | 'completed' | 'rejected';
|
||||
|
||||
// ============================================================================
|
||||
// Subcomponents
|
||||
// ============================================================================
|
||||
|
||||
interface WithdrawalCardProps {
|
||||
withdrawal: Withdrawal;
|
||||
}
|
||||
|
||||
const WithdrawalCard: React.FC<WithdrawalCardProps> = ({ withdrawal }) => {
|
||||
const statusConfig = {
|
||||
pending: {
|
||||
icon: <Clock className="w-5 h-5" />,
|
||||
color: 'text-yellow-500',
|
||||
bg: 'bg-yellow-100 dark:bg-yellow-900/30',
|
||||
label: 'Pendiente',
|
||||
},
|
||||
approved: {
|
||||
icon: <CheckCircle className="w-5 h-5" />,
|
||||
color: 'text-blue-500',
|
||||
bg: 'bg-blue-100 dark:bg-blue-900/30',
|
||||
label: 'Aprobado',
|
||||
},
|
||||
processing: {
|
||||
icon: <Clock className="w-5 h-5" />,
|
||||
color: 'text-purple-500',
|
||||
bg: 'bg-purple-100 dark:bg-purple-900/30',
|
||||
label: 'Procesando',
|
||||
},
|
||||
completed: {
|
||||
icon: <CheckCircle className="w-5 h-5" />,
|
||||
color: 'text-green-500',
|
||||
bg: 'bg-green-100 dark:bg-green-900/30',
|
||||
label: 'Completado',
|
||||
},
|
||||
rejected: {
|
||||
icon: <XCircle className="w-5 h-5" />,
|
||||
color: 'text-red-500',
|
||||
bg: 'bg-red-100 dark:bg-red-900/30',
|
||||
label: 'Rechazado',
|
||||
},
|
||||
};
|
||||
|
||||
const config = statusConfig[withdrawal.status];
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-2 rounded-lg ${config.bg} ${config.color}`}>
|
||||
{config.icon}
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-bold text-2xl text-gray-900 dark:text-white">
|
||||
${withdrawal.amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{new Date(withdrawal.requestedAt).toLocaleDateString()} {new Date(withdrawal.requestedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className={`px-3 py-1 rounded-full text-sm font-medium ${config.bg} ${config.color}`}>
|
||||
{config.label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-sm">
|
||||
{withdrawal.bankInfo && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500 dark:text-gray-400">Destino</span>
|
||||
<span className="text-gray-900 dark:text-white">
|
||||
{withdrawal.bankInfo.bankName} ****{withdrawal.bankInfo.accountLast4}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{withdrawal.cryptoInfo && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500 dark:text-gray-400">Destino</span>
|
||||
<span className="text-gray-900 dark:text-white font-mono">
|
||||
{withdrawal.cryptoInfo.network}: ...{withdrawal.cryptoInfo.addressLast8}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{withdrawal.processedAt && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500 dark:text-gray-400">Procesado</span>
|
||||
<span className="text-gray-900 dark:text-white">
|
||||
{new Date(withdrawal.processedAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{withdrawal.rejectionReason && (
|
||||
<div className="mt-3 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
|
||||
<p className="text-sm text-red-600 dark:text-red-400">
|
||||
<strong>Motivo:</strong> {withdrawal.rejectionReason}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Main Component
|
||||
// ============================================================================
|
||||
|
||||
export const Withdrawals: React.FC = () => {
|
||||
const [withdrawals, setWithdrawals] = useState<Withdrawal[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
||||
|
||||
useEffect(() => {
|
||||
loadWithdrawals();
|
||||
}, [statusFilter]);
|
||||
|
||||
const loadWithdrawals = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const status = statusFilter === 'all' ? undefined : statusFilter;
|
||||
const data = await investmentService.getWithdrawals(status);
|
||||
setWithdrawals(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error loading withdrawals');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const stats = {
|
||||
total: withdrawals.length,
|
||||
pending: withdrawals.filter(w => ['pending', 'approved', 'processing'].includes(w.status)).length,
|
||||
completed: withdrawals.filter(w => w.status === 'completed').length,
|
||||
totalAmount: withdrawals
|
||||
.filter(w => w.status === 'completed')
|
||||
.reduce((sum, w) => sum + w.amount, 0),
|
||||
};
|
||||
|
||||
const filterOptions: { value: StatusFilter; label: string }[] = [
|
||||
{ value: 'all', label: 'Todos' },
|
||||
{ value: 'pending', label: 'Pendientes' },
|
||||
{ value: 'processing', label: 'En Proceso' },
|
||||
{ value: 'completed', label: 'Completados' },
|
||||
{ value: 'rejected', label: 'Rechazados' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto px-4 py-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4 mb-8">
|
||||
<Link
|
||||
to="/investment/portfolio"
|
||||
className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
Mis Retiros
|
||||
</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">
|
||||
Historial de solicitudes de retiro
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Total Solicitudes</p>
|
||||
<p className="text-2xl font-bold text-gray-900 dark:text-white">{stats.total}</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">En Proceso</p>
|
||||
<p className="text-2xl font-bold text-yellow-500">{stats.pending}</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Completados</p>
|
||||
<p className="text-2xl font-bold text-green-500">{stats.completed}</p>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Total Retirado</p>
|
||||
<p className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
${stats.totalAmount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="flex items-center gap-2 mb-6 overflow-x-auto pb-2">
|
||||
<Filter className="w-4 h-4 text-gray-500 flex-shrink-0" />
|
||||
{filterOptions.map(option => (
|
||||
<button
|
||||
key={option.value}
|
||||
onClick={() => setStatusFilter(option.value)}
|
||||
className={`px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${
|
||||
statusFilter === option.value
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-6 text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<p className="text-red-600 dark:text-red-400">{error}</p>
|
||||
<button
|
||||
onClick={loadWithdrawals}
|
||||
className="mt-4 px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
|
||||
>
|
||||
Reintentar
|
||||
</button>
|
||||
</div>
|
||||
) : withdrawals.length === 0 ? (
|
||||
<div className="text-center py-16 bg-white dark:bg-gray-800 rounded-xl shadow-lg">
|
||||
<span className="text-6xl mb-4 block">💸</span>
|
||||
<h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">
|
||||
No hay retiros
|
||||
</h3>
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-6">
|
||||
{statusFilter === 'all'
|
||||
? 'Aún no has solicitado ningún retiro'
|
||||
: `No hay retiros con estado "${filterOptions.find(f => f.value === statusFilter)?.label}"`}
|
||||
</p>
|
||||
<Link
|
||||
to="/investment/portfolio"
|
||||
className="inline-block px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
|
||||
>
|
||||
Ir al Portfolio
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
{withdrawals.map(withdrawal => (
|
||||
<WithdrawalCard key={withdrawal.id} withdrawal={withdrawal} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Withdrawals;
|
||||
Loading…
Reference in New Issue
Block a user