'use client'; import React, { useState, useEffect } from 'react'; import Header from '@/components/Header'; import { useLocale } from '@/lib/i18n/LocaleContext'; import { useUser } from '@/lib/auth/UserContext'; import styles from './page.module.css'; interface Settlement { id: number; period: string; salesAmount: string | number; goalAmount: string | number; achievementPercentage: string | number; calculatedCommission: string | number; calculatedBonus: string | number; adjustmentAmount: string | number; totalPayout: string | number; status: string; aiAuditNotes: any; colaborador: { username: string; email: string; hotel: { name: string; }; }; plan: { name: string; code: string; }; } interface UserOption { id: number; username: string; } export default function HistoryPage() { const { t, locale } = useLocale(); const { role, user } = useUser(); const [settlements, setSettlements] = useState([]); const [users, setUsers] = useState([]); const [isLoading, setIsLoading] = useState(true); // Filters state const [period, setPeriod] = useState(''); const [status, setStatus] = useState(''); const [selectedUserId, setSelectedUserId] = useState(''); const [expandedRowId, setExpandedRowId] = useState(null); const fetchSettlements = async () => { setIsLoading(true); try { const queryParams = new URLSearchParams(); if (period) queryParams.append('period', period); if (status) queryParams.append('status', status); if (selectedUserId) queryParams.append('userId', selectedUserId); const res = await fetch(`/api/settlements?${queryParams.toString()}`); if (res.ok) { const data = await res.json(); setSettlements(data.settlements || []); } } catch (err) { console.error('Failed to fetch settlements', err); } finally { setIsLoading(false); } }; const fetchUsers = async () => { if (role !== 'admin' && role !== 'director') return; try { const res = await fetch('/api/users'); if (res.ok) { const data = await res.json(); setUsers(data.users || []); } } catch (err) { console.error('Failed to fetch users', err); } }; useEffect(() => { fetchSettlements(); }, [period, status, selectedUserId]); useEffect(() => { fetchUsers(); }, [role]); const toggleRow = (id: number) => { if (expandedRowId === id) { setExpandedRowId(null); } else { setExpandedRowId(id); } }; const formatCurrency = (val: string | number) => { const num = typeof val === 'string' ? parseFloat(val) : val; if (isNaN(num)) return '$0.00'; return new Intl.NumberFormat(locale === 'es' ? 'es-CO' : 'en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2 }).format(num); }; const formatPercent = (val: string | number) => { const num = typeof val === 'string' ? parseFloat(val) : val; if (isNaN(num)) return '0%'; return `${(num * 100).toFixed(1)}%`; }; const getAuditNotes = (notes: any) => { if (!notes) return null; if (typeof notes === 'string') return notes; if (notes[locale]) return notes[locale]; if (notes.es) return notes.es; if (notes.en) return notes.en; return JSON.stringify(notes); }; const handlePrint = () => { window.print(); }; const showUserFilter = role === 'admin' || role === 'director'; return (

{t('history.title')}

{/* Filter Card */}
setPeriod(e.target.value)} id="filter-period" />
{showUserFilter && (
)}
{/* History Table */} {isLoading ? (
{t('history.loading')}
) : settlements.length === 0 ? (
{t('history.empty')}
) : (
{showUserFilter && } {settlements.map((item) => ( {showUserFilter && ( )} {expandedRowId === item.id && item.aiAuditNotes && ( )} ))}
{t('history.period')}{t('simulation.thCollaborator')}{t('simulation.thPlan')} {t('history.goal')} {t('history.sales')} % {t('history.commission')} {t('history.adjustment')} {t('history.payout')} {t('history.status')} {t('simulation.thAiAudit')}
{item.period}
{item.colaborador.username}
{item.colaborador.hotel.name}
{item.plan.name}
{item.plan.code}
{formatCurrency(item.goalAmount)} {formatCurrency(item.salesAmount)} {formatPercent(item.achievementPercentage)} {formatCurrency(item.calculatedCommission)} {formatCurrency(item.adjustmentAmount)} {formatCurrency(item.totalPayout)} {t(`status.${item.status}`)} {item.aiAuditNotes ? ( ) : ( - )}

{t('history.audit_notes')}

{getAuditNotes(item.aiAuditNotes)}

)}
); }