Initial commit - cleaned for CV

This commit is contained in:
Renato97
2026-03-31 01:23:33 -03:00
commit 9c11f23af0
142 changed files with 13690 additions and 0 deletions

46
app/alerts/page.tsx Normal file
View File

@@ -0,0 +1,46 @@
'use client'
import { DashboardLayout } from '@/components/layout/DashboardLayout'
import { AlertPanel, useAlerts } from '@/components/alerts'
import { RefreshCw } from 'lucide-react'
export default function AlertsPage() {
const { regenerateAlerts, dismissAll } = useAlerts()
const handleRegenerateAlerts = () => {
regenerateAlerts()
}
const handleDismissAll = () => {
dismissAll()
}
return (
<DashboardLayout title="Alertas">
<div className="space-y-6">
{/* Action Buttons */}
<div className="flex flex-wrap gap-3">
<button
onClick={handleRegenerateAlerts}
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/20"
>
<RefreshCw className="h-4 w-4" />
Regenerar Alertas
</button>
<button
onClick={handleDismissAll}
className="inline-flex items-center gap-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white text-sm font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-slate-500/20"
>
Limpiar Todas
</button>
</div>
{/* Alert Panel */}
<div className="w-full">
<AlertPanel />
</div>
</div>
</DashboardLayout>
)
}

View File

@@ -0,0 +1,54 @@
import { NextResponse } from 'next/server';
import { findUser, verifyPassword, createSession } from '@/lib/auth';
import { generateOTP } from '@/lib/otp';
import TelegramBot from 'node-telegram-bot-api';
const BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
async function sendTelegramOTP(chatId: string, otp: string) {
if (!BOT_TOKEN) return false;
try {
const bot = new TelegramBot(BOT_TOKEN, { polling: false });
await bot.sendMessage(chatId, `🔐 *Código de Acceso Finanzas*\n\nTu código es: \`${otp}\`\n\nSi no intentaste ingresar, ignora este mensaje.`, { parse_mode: 'Markdown' });
return true;
} catch (e) {
console.error('Telegram send error:', e);
return false;
}
}
export async function POST(req: Request) {
try {
const { username, password } = await req.json();
const ip = req.headers.get('x-forwarded-for')?.split(',')[0].trim() || 'unknown';
const user = findUser(username);
if (!user || !(await verifyPassword(password, user.passwordHash))) {
return NextResponse.json({ error: 'Credenciales inválidas' }, { status: 401 });
}
// Check IP
const isKnownIp = user.knownIps.includes(ip);
if (isKnownIp) {
// Login success directly
await createSession(user);
return NextResponse.json({ success: true, requireOtp: false });
} else {
// Require OTP
const otp = generateOTP(user.username);
const sent = await sendTelegramOTP(user.chatId, otp);
if (!sent) {
return NextResponse.json({ error: 'No se pudo enviar el código OTP a Telegram' }, { status: 500 });
}
return NextResponse.json({ success: true, requireOtp: true });
}
} catch (error) {
console.error('Login error:', error);
return NextResponse.json({ error: 'Error interno' }, { status: 500 });
}
}

View File

@@ -0,0 +1,7 @@
import { NextResponse } from 'next/server';
import { destroySession } from '@/lib/auth';
export async function POST() {
destroySession();
return NextResponse.json({ success: true });
}

View File

@@ -0,0 +1,41 @@
import { NextResponse } from 'next/server';
import { saveUser, findUser, hashPassword, createSession } from '@/lib/auth';
import { randomUUID } from 'crypto';
export async function POST(req: Request) {
try {
const { username, password, chatId } = await req.json();
if (!username || !password || !chatId) {
return NextResponse.json({ error: 'Faltan datos requeridos' }, { status: 400 });
}
if (findUser(username)) {
return NextResponse.json({ error: 'El usuario ya existe' }, { status: 409 });
}
// Hash password
const passwordHash = await hashPassword(password);
// Get IP
const ip = req.headers.get('x-forwarded-for') || '127.0.0.1';
const newUser = {
id: randomUUID(),
username,
passwordHash,
chatId,
knownIps: [ip] // Register current IP as known initially
};
saveUser(newUser);
// Auto login after register
await createSession(newUser);
return NextResponse.json({ success: true });
} catch (error) {
console.error('Register error:', error);
return NextResponse.json({ error: 'Error interno del servidor' }, { status: 500 });
}
}

View File

@@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';
import { findUser, saveUser, createSession } from '@/lib/auth';
import { verifyOTP } from '@/lib/otp';
export async function POST(req: Request) {
try {
const { username, otp } = await req.json();
const ip = req.headers.get('x-forwarded-for')?.split(',')[0].trim() || 'unknown';
if (!verifyOTP(username, otp)) {
return NextResponse.json({ error: 'Código inválido o expirado' }, { status: 401 });
}
const user = findUser(username);
if (!user) {
return NextResponse.json({ error: 'Usuario no encontrado' }, { status: 404 });
}
// Add IP to known list if not exists
if (!user.knownIps.includes(ip) && ip !== 'unknown') {
user.knownIps.push(ip);
saveUser(user);
}
// Login success
await createSession(user);
return NextResponse.json({ success: true });
} catch (error) {
console.error('OTP Verify error:', error);
return NextResponse.json({ error: 'Error interno' }, { status: 500 });
}
}

View File

@@ -0,0 +1,48 @@
import { NextResponse } from 'next/server'
export async function POST(request: Request) {
try {
const { endpoint, token } = await request.json()
if (!endpoint || !token) {
return NextResponse.json({ success: false, error: 'Faltan datos' }, { status: 400 })
}
// Try standard /v1/models endpoint
// If user provided "https://api.example.com/v1", we append "/models"
let targetUrl = endpoint
if (targetUrl.endsWith('/')) {
targetUrl = `${targetUrl}v1/models`
} else if (!targetUrl.endsWith('/models')) {
targetUrl = `${targetUrl}/v1/models`
}
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'x-api-key': token
}
})
if (!response.ok) {
const text = await response.text()
return NextResponse.json({ success: false, error: text }, { status: response.status })
}
const data = await response.json()
// Normalizing response: OpenAI/Anthropic usually return { data: [{ id: 'model-name' }, ...] }
let models: string[] = []
if (Array.isArray(data.data)) {
models = data.data.map((m: any) => m.id)
} else if (Array.isArray(data)) {
models = data.map((m: any) => m.id || m.model || m)
}
return NextResponse.json({ success: true, models })
} catch (error: any) {
return NextResponse.json({ success: false, error: error.message }, { status: 500 })
}
}

48
app/api/settings/route.ts Normal file
View File

@@ -0,0 +1,48 @@
import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { AppSettings } from '@/lib/types'
const SETTINGS_FILE = path.join(process.cwd(), 'server-settings.json')
const DEFAULT_SETTINGS: AppSettings = {
telegram: {
botToken: '',
chatId: '',
},
aiProviders: [],
}
export async function GET() {
try {
if (!fs.existsSync(SETTINGS_FILE)) {
return NextResponse.json(DEFAULT_SETTINGS)
}
const data = fs.readFileSync(SETTINGS_FILE, 'utf8')
const settings = JSON.parse(data)
return NextResponse.json(settings)
} catch (error) {
console.error('Error reading settings:', error)
return NextResponse.json(DEFAULT_SETTINGS, { status: 500 })
}
}
export async function POST(request: Request) {
try {
const body = await request.json()
// Basic validation could go here
const settings: AppSettings = {
telegram: {
botToken: body.telegram?.botToken || '',
chatId: body.telegram?.chatId || ''
},
aiProviders: Array.isArray(body.aiProviders) ? body.aiProviders : []
}
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2))
return NextResponse.json({ success: true, settings })
} catch (error) {
console.error('Error saving settings:', error)
return NextResponse.json({ success: false, error: 'Failed to save settings' }, { status: 500 })
}
}

28
app/api/sync/route.ts Normal file
View File

@@ -0,0 +1,28 @@
import { NextResponse } from 'next/server';
import { getDatabase, saveDatabase } from '@/lib/server-db';
import { verifySession } from '@/lib/auth';
export async function GET() {
const session = await verifySession();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const data = getDatabase(session.username);
return NextResponse.json(data);
}
export async function POST(req: Request) {
const session = await verifySession();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const body = await req.json();
saveDatabase(session.username, body);
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: 'Invalid Data' }, { status: 400 });
}
}

59
app/api/test/ai/route.ts Normal file
View File

@@ -0,0 +1,59 @@
import { NextResponse } from 'next/server'
export async function POST(request: Request) {
try {
const { endpoint, token, model } = await request.json()
if (!endpoint || !token) {
return NextResponse.json(
{ success: false, error: 'Faltan credenciales (Endpoint o Token)' },
{ status: 400 }
)
}
// Prepare target URL
let targetUrl = endpoint
if (!targetUrl.endsWith('/messages') && !targetUrl.endsWith('/chat/completions')) {
targetUrl = targetUrl.endsWith('/') ? `${targetUrl}v1/messages` : `${targetUrl}/v1/messages`
}
const start = Date.now()
// Payload for Anthropic /v1/messages
const body = {
model: model || "gpt-3.5-turbo", // Fallback if no model selected
messages: [{ role: "user", content: "Ping" }],
max_tokens: 10
}
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': token,
'anthropic-version': '2023-06-01',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(body)
})
const duration = Date.now() - start
if (!response.ok) {
const text = await response.text()
return NextResponse.json(
{ success: false, error: `Error ${response.status}: ${text.slice(0, 100)}` },
{ status: response.status }
)
}
return NextResponse.json({ success: true, latency: duration })
} catch (error: any) {
console.error('AI Test Error:', error)
return NextResponse.json(
{ success: false, error: error.message || 'Error de conexión' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,45 @@
import { NextResponse } from 'next/server'
export async function POST(request: Request) {
try {
const { botToken, chatId } = await request.json()
if (!botToken || !chatId) {
return NextResponse.json(
{ success: false, error: 'Faltan credenciales (Token o Chat ID)' },
{ status: 400 }
)
}
const message = "🤖 *Prueba de Conexión*\n\n¡Hola! Si lees esto, tu bot de Finanzas está correctamente configurado. 🚀"
const url = `https://api.telegram.org/bot${botToken}/sendMessage`
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text: message,
parse_mode: 'Markdown'
})
})
const data = await response.json()
if (!data.ok) {
return NextResponse.json(
{ success: false, error: data.description || 'Error desconocido de Telegram' },
{ status: 500 }
)
}
return NextResponse.json({ success: true, data })
} catch (error: any) {
console.error('Telegram Test Error:', error)
return NextResponse.json(
{ success: false, error: error.message || 'Error interno del servidor' },
{ status: 500 }
)
}
}

12
app/budget/page.tsx Normal file
View File

@@ -0,0 +1,12 @@
'use client'
import { DashboardLayout } from '@/components/layout/DashboardLayout'
import { BudgetSection } from '@/components/budget'
export default function BudgetPage() {
return (
<DashboardLayout title="Presupuesto">
<BudgetSection />
</DashboardLayout>
)
}

12
app/cards/page.tsx Normal file
View File

@@ -0,0 +1,12 @@
'use client';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { CardSection } from '@/components/cards';
export default function CardsPage() {
return (
<DashboardLayout title="Tarjetas de Crédito">
<CardSection />
</DashboardLayout>
);
}

12
app/debts/page.tsx Normal file
View File

@@ -0,0 +1,12 @@
'use client'
import { DashboardLayout } from '@/components/layout/DashboardLayout'
import { DebtSection } from '@/components/debts'
export default function DebtsPage() {
return (
<DashboardLayout title="Deudas">
<DebtSection />
</DashboardLayout>
)
}

308
app/globals.css Normal file
View File

@@ -0,0 +1,308 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
/* Base Colors - Dark Theme (slate/emerald) */
--background: 222 47% 11%;
--foreground: 210 40% 98%;
/* Card Colors */
--card: 217 33% 17%;
--card-foreground: 210 40% 98%;
/* Popover Colors */
--popover: 217 33% 17%;
--popover-foreground: 210 40% 98%;
/* Primary - Emerald */
--primary: 160 84% 39%;
--primary-foreground: 210 40% 98%;
/* Secondary */
--secondary: 217 33% 17%;
--secondary-foreground: 210 40% 98%;
/* Muted */
--muted: 217 33% 17%;
--muted-foreground: 215 20% 65%;
/* Accent */
--accent: 217 33% 17%;
--accent-foreground: 210 40% 98%;
/* Destructive */
--destructive: 0 84% 60%;
--destructive-foreground: 210 40% 98%;
/* Border & Input */
--border: 215 28% 25%;
--input: 215 28% 25%;
/* Ring - Emerald */
--ring: 160 84% 39%;
/* Radius */
--radius: 0.5rem;
}
/* Base Styles */
html {
scroll-behavior: smooth;
}
body {
background-color: hsl(var(--background));
color: hsl(var(--foreground));
font-feature-settings: "rlig" 1, "calt" 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Input Styles */
input,
textarea,
select {
background-color: hsl(var(--card));
border-color: hsl(var(--border));
color: hsl(var(--foreground));
}
input::placeholder,
textarea::placeholder {
color: hsl(var(--muted-foreground));
}
/* Selection */
::selection {
background-color: hsl(160 84% 39% / 0.3);
color: hsl(var(--foreground));
}
/* Focus Ring */
:focus-visible {
outline: none;
ring: 2px;
ring-color: hsl(var(--ring));
ring-offset: 2px;
ring-offset-color: hsl(var(--background));
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: hsl(var(--background));
}
::-webkit-scrollbar-thumb {
background: hsl(var(--border));
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: hsl(var(--muted-foreground) / 0.5);
}
/* Firefox Scrollbar */
* {
scrollbar-width: thin;
scrollbar-color: hsl(var(--border)) hsl(var(--background));
}
/* Utility Classes */
.gradient-text {
background: linear-gradient(135deg, hsl(160 84% 39%) 0%, hsl(168 76% 42%) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.glass-card {
background: hsl(var(--card) / 0.8);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid hsl(var(--border) / 0.5);
}
.text-balance {
text-wrap: balance;
}
/* Loading States */
.skeleton {
background: linear-gradient(
90deg,
hsl(var(--muted)) 25%,
hsl(var(--muted-foreground) / 0.3) 50%,
hsl(var(--muted)) 75%
);
background-size: 200% 100%;
animation: skeleton-pulse 1.5s ease-in-out infinite;
border-radius: var(--radius);
}
@keyframes skeleton-pulse {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.spinner {
width: 24px;
height: 24px;
border: 2px solid hsl(var(--border));
border-top-color: hsl(var(--primary));
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.spinner-sm {
width: 16px;
height: 16px;
border-width: 2px;
}
.spinner-lg {
width: 32px;
height: 32px;
border-width: 3px;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Animations */
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideInLeft {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes pulse-slow {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}
@keyframes bounce-slight {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-3px);
}
}
/* Animation Utility Classes */
.animate-fade-in {
animation: fadeIn 0.3s ease-out forwards;
}
.animate-fade-in-up {
animation: fadeInUp 0.3s ease-out forwards;
}
.animate-fade-in-down {
animation: fadeInDown 0.3s ease-out forwards;
}
.animate-slide-in-left {
animation: slideInLeft 0.3s ease-out forwards;
}
.animate-slide-in-right {
animation: slideInRight 0.3s ease-out forwards;
}
.animate-pulse-slow {
animation: pulse-slow 2s ease-in-out infinite;
}
.animate-bounce-slight {
animation: bounce-slight 1s ease-in-out infinite;
}
/* Stagger Animation Delays */
.stagger-1 { animation-delay: 0.05s; }
.stagger-2 { animation-delay: 0.1s; }
.stagger-3 { animation-delay: 0.15s; }
.stagger-4 { animation-delay: 0.2s; }
.stagger-5 { animation-delay: 0.25s; }
.stagger-6 { animation-delay: 0.3s; }
.stagger-7 { animation-delay: 0.35s; }
.stagger-8 { animation-delay: 0.4s; }
/* Reduced Motion */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}

165
app/incomes/page.tsx Normal file
View File

@@ -0,0 +1,165 @@
'use client'
import { useState } from 'react'
import { useFinanzasStore } from '@/lib/store'
import { Plus, Trash2, TrendingUp, DollarSign } from 'lucide-react'
import { format } from 'date-fns'
import { es } from 'date-fns/locale'
import { DashboardLayout } from '@/components/layout/DashboardLayout'
export default function IncomesPage() {
const incomes = useFinanzasStore((state) => state.incomes) || []
const addIncome = useFinanzasStore((state) => state.addIncome)
const removeIncome = useFinanzasStore((state) => state.removeIncome)
const [newIncome, setNewIncome] = useState({
amount: '',
description: '',
category: 'salary' as const,
})
const handleAdd = () => {
if (!newIncome.amount || !newIncome.description) return
addIncome({
amount: parseFloat(newIncome.amount),
description: newIncome.description,
category: newIncome.category,
date: new Date().toISOString(),
})
setNewIncome({ amount: '', description: '', category: 'salary' })
}
const totalIncomes = incomes.reduce((acc, curr) => acc + curr.amount, 0)
return (
<DashboardLayout title="Ingresos">
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-3xl font-bold flex items-center gap-2 text-white">
<TrendingUp className="text-green-500" /> Ingresos
</h2>
<div className="text-right">
<p className="text-sm text-gray-400">Total Acumulado</p>
<p className="text-2xl font-bold text-green-400">
${totalIncomes.toLocaleString()}
</p>
</div>
</div>
<div className="grid md:grid-cols-3 gap-6">
{/* Formulario */}
<div className="bg-slate-800 border border-slate-700 rounded-xl md:col-span-1 h-fit overflow-hidden">
<div className="p-6 border-b border-slate-700">
<h3 className="font-semibold text-lg text-white">Nuevo Ingreso</h3>
</div>
<div className="p-6 space-y-4">
<div>
<label className="text-sm text-gray-400 block mb-2">Descripción</label>
<input
placeholder="Ej. Pago Freelance"
value={newIncome.description}
onChange={(e) =>
setNewIncome({ ...newIncome, description: e.target.value })
}
className="w-full bg-slate-700 border-slate-600 border rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-emerald-500"
/>
</div>
<div>
<label className="text-sm text-gray-400 block mb-2">Monto</label>
<div className="relative">
<DollarSign className="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
<input
type="number"
placeholder="0.00"
value={newIncome.amount}
onChange={(e) =>
setNewIncome({ ...newIncome, amount: e.target.value })
}
className="w-full pl-9 bg-slate-700 border-slate-600 border rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-emerald-500"
/>
</div>
</div>
<div>
<label className="text-sm text-gray-400 block mb-2">Categoría</label>
<select
className="w-full bg-slate-700 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-emerald-500"
value={newIncome.category}
onChange={(e) =>
setNewIncome({
...newIncome,
category: e.target.value as any,
})
}
>
<option value="salary">Salario</option>
<option value="freelance">Freelance</option>
<option value="business">Negocio</option>
<option value="gift">Regalo</option>
<option value="other">Otro</option>
</select>
</div>
<button
onClick={handleAdd}
className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-semibold py-2 px-4 rounded-lg flex items-center justify-center gap-2 transition-colors"
>
<Plus className="w-4 h-4" /> Agregar Ingreso
</button>
</div>
</div>
{/* Lista */}
<div className="bg-slate-800 border border-slate-700 rounded-xl md:col-span-2 overflow-hidden">
<div className="p-6 border-b border-slate-700">
<h3 className="font-semibold text-lg text-white">Historial de Ingresos</h3>
</div>
<div className="p-6">
{incomes.length === 0 ? (
<p className="text-center text-gray-500 py-8">
No hay ingresos registrados aún.
</p>
) : (
<div className="space-y-4">
{incomes
.sort(
(a, b) =>
new Date(b.date).getTime() - new Date(a.date).getTime()
)
.map((income) => (
<div
key={income.id}
className="flex items-center justify-between p-4 bg-slate-700/50 rounded-lg border border-slate-700 hover:border-slate-600 transition-colors"
>
<div>
<p className="font-semibold text-white">
{income.description}
</p>
<p className="text-xs text-gray-400 capitalize">
{income.category} {' '}
{format(new Date(income.date), "d 'de' MMMM", {
locale: es,
})}
</p>
</div>
<div className="flex items-center gap-4">
<span className="text-emerald-400 font-mono font-bold">
+${income.amount.toLocaleString()}
</span>
<button
onClick={() => removeIncome(income.id)}
className="text-slate-500 hover:text-red-400 transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
</div>
</DashboardLayout>
)
}

30
app/layout.tsx Normal file
View File

@@ -0,0 +1,30 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { Providers } from "./providers";
const inter = Inter({
subsets: ["latin"],
variable: "--font-inter",
display: "swap",
});
export const metadata: Metadata = {
title: "Finanzas Personales",
description: "Gestiona tus finanzas personales de forma inteligente",
keywords: ["finanzas", "presupuesto", "gastos", "ingresos", "ahorro"],
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="es" className={inter.variable} suppressHydrationWarning>
<body className={`${inter.className} antialiased min-h-screen bg-slate-950 text-slate-50`}>
<Providers>{children}</Providers>
</body>
</html>
);
}

193
app/login/page.tsx Normal file
View File

@@ -0,0 +1,193 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Lock, User, Key, ArrowRight, ShieldCheck, Loader2 } from 'lucide-react';
import Link from 'next/link';
export default function LoginPage() {
const router = useRouter();
const [step, setStep] = useState<'credentials' | 'otp'>('credentials');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [formData, setFormData] = useState({
username: '',
password: '',
otp: ''
});
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: formData.username, password: formData.password })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Error al iniciar sesión');
if (data.requireOtp) {
setStep('otp');
} else {
router.push('/');
router.refresh();
}
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleVerifyOtp = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
const res = await fetch('/api/auth/verify-otp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: formData.username, otp: formData.otp })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Código incorrecto');
router.push('/');
router.refresh();
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen bg-slate-950 flex items-center justify-center p-4">
<div className="w-full max-w-md bg-slate-900 border border-slate-800 rounded-2xl shadow-xl overflow-hidden">
{/* Header */}
<div className="bg-slate-950/50 p-6 text-center border-b border-slate-800">
<div className="mx-auto w-12 h-12 bg-emerald-500/10 rounded-xl flex items-center justify-center mb-4">
<Lock className="w-6 h-6 text-emerald-500" />
</div>
<h1 className="text-2xl font-bold text-white mb-1">Bienvenido</h1>
<p className="text-slate-400 text-sm">Sistema de Finanzas Personales</p>
</div>
<div className="p-6">
{error && (
<div className="mb-6 p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm text-center">
{error}
</div>
)}
{step === 'credentials' ? (
<form onSubmit={handleLogin} className="space-y-4">
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider">Usuario</label>
<div className="relative">
<User className="absolute left-3 top-2.5 w-5 h-5 text-slate-500" />
<input
type="text"
required
value={formData.username}
onChange={e => setFormData({...formData, username: e.target.value})}
className="w-full pl-10 pr-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg text-white focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 outline-none transition-all placeholder:text-slate-600"
placeholder="Ingresa tu usuario"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider">Contraseña</label>
<div className="relative">
<Key className="absolute left-3 top-2.5 w-5 h-5 text-slate-500" />
<input
type="password"
required
value={formData.password}
onChange={e => setFormData({...formData, password: e.target.value})}
className="w-full pl-10 pr-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg text-white focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 outline-none transition-all placeholder:text-slate-600"
placeholder="••••••••"
/>
</div>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-medium py-2.5 rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed mt-2"
>
{loading ? <Loader2 className="animate-spin w-5 h-5" /> : (
<>
Ingresar <ArrowRight className="w-4 h-4" />
</>
)}
</button>
</form>
) : (
<form onSubmit={handleVerifyOtp} className="space-y-4 animate-in slide-in-from-right-8 fade-in duration-300">
<div className="text-center mb-6">
<div className="inline-flex items-center justify-center w-16 h-16 bg-blue-500/10 rounded-full mb-4">
<ShieldCheck className="w-8 h-8 text-blue-500" />
</div>
<h3 className="text-lg font-medium text-white">Verificación de Identidad</h3>
<p className="text-slate-400 text-sm mt-1">
Hemos enviado un código a tu Telegram.
<br />Ingrésalo para continuar.
</p>
</div>
<div className="space-y-2">
<input
type="text"
required
autoFocus
maxLength={6}
value={formData.otp}
onChange={e => setFormData({...formData, otp: e.target.value.replace(/\D/g, '')})}
className="w-full text-center text-2xl tracking-[0.5em] font-mono py-3 bg-slate-950 border border-slate-800 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all"
placeholder="000000"
/>
</div>
<button
type="submit"
disabled={loading || formData.otp.length !== 6}
className="w-full bg-blue-600 hover:bg-blue-500 text-white font-medium py-2.5 rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? <Loader2 className="animate-spin w-5 h-5" /> : 'Verificar Código'}
</button>
<button
type="button"
onClick={() => setStep('credentials')}
className="w-full text-slate-500 text-sm hover:text-slate-300 transition-colors"
>
Volver atrás
</button>
</form>
)}
</div>
<div className="bg-slate-950/50 p-4 text-center border-t border-slate-800">
<p className="text-slate-500 text-sm">
¿No tienes cuenta?{' '}
<Link href="/register" className="text-emerald-500 hover:text-emerald-400 font-medium hover:underline">
Regístrate aquí
</Link>
</p>
</div>
</div>
</div>
);
}

94
app/page.tsx Normal file
View File

@@ -0,0 +1,94 @@
'use client'
import { useEffect, useState } from 'react'
import { SummarySection, QuickActions, RecentActivity } from '@/components/dashboard'
import { useFinanzasStore } from '@/lib/store'
import { AlertBanner, useAlerts } from '@/components/alerts'
import { AddDebtModal } from '@/components/modals/AddDebtModal'
import { AddCardModal } from '@/components/modals/AddCardModal'
import { AddPaymentModal } from '@/components/modals/AddPaymentModal'
import { DashboardLayout } from '@/components/layout/DashboardLayout'
export default function Home() {
// Datos del store
const markAlertAsRead = useFinanzasStore((state) => state.markAlertAsRead)
const deleteAlert = useFinanzasStore((state) => state.deleteAlert)
// Alertas
const { unreadAlerts, regenerateAlerts } = useAlerts()
// Estados locales para modales
const [isAddDebtModalOpen, setIsAddDebtModalOpen] = useState(false)
const [isAddCardModalOpen, setIsAddCardModalOpen] = useState(false)
const [isAddPaymentModalOpen, setIsAddPaymentModalOpen] = useState(false)
// Efecto para regenerar alertas al cargar la página
useEffect(() => {
regenerateAlerts()
}, [regenerateAlerts])
// Handlers para modales
const handleAddDebt = () => {
setIsAddDebtModalOpen(true)
}
const handleAddCard = () => {
setIsAddCardModalOpen(true)
}
const handleAddPayment = () => {
setIsAddPaymentModalOpen(true)
}
// Primeras 3 alertas no leídas
const topAlerts = unreadAlerts.slice(0, 3)
return (
<DashboardLayout title="Dashboard">
<div className="space-y-6">
{/* Alertas destacadas */}
{topAlerts.length > 0 && (
<div className="space-y-3">
{topAlerts.map((alert) => (
<AlertBanner
key={alert.id}
alert={alert}
onDismiss={() => deleteAlert(alert.id)}
onMarkRead={() => markAlertAsRead(alert.id)}
/>
))}
</div>
)}
{/* Sección de resumen */}
<SummarySection />
{/* Acciones rápidas */}
<QuickActions
onAddDebt={handleAddDebt}
onAddCard={handleAddCard}
onAddPayment={handleAddPayment}
/>
{/* Actividad reciente */}
<RecentActivity limit={5} />
</div>
{/* Modales */}
<AddDebtModal
isOpen={isAddDebtModalOpen}
onClose={() => setIsAddDebtModalOpen(false)}
/>
<AddCardModal
isOpen={isAddCardModalOpen}
onClose={() => setIsAddCardModalOpen(false)}
/>
<AddPaymentModal
isOpen={isAddPaymentModalOpen}
onClose={() => setIsAddPaymentModalOpen(false)}
/>
</DashboardLayout>
)
}

43
app/providers.tsx Normal file
View File

@@ -0,0 +1,43 @@
"use client";
import { createContext, useContext, useState, ReactNode } from "react";
import { DataSync } from "@/components/DataSync";
interface SidebarContextType {
isOpen: boolean;
toggle: () => void;
close: () => void;
open: () => void;
}
const SidebarContext = createContext<SidebarContextType | undefined>(undefined);
export function Providers({ children }: { children: ReactNode }) {
const [isSidebarOpen, setIsSidebarOpen] = useState(true);
const toggleSidebar = () => setIsSidebarOpen((prev) => !prev);
const closeSidebar = () => setIsSidebarOpen(false);
const openSidebar = () => setIsSidebarOpen(true);
return (
<SidebarContext.Provider
value={{
isOpen: isSidebarOpen,
toggle: toggleSidebar,
close: closeSidebar,
open: openSidebar,
}}
>
<DataSync />
{children}
</SidebarContext.Provider>
);
}
export function useSidebar() {
const context = useContext(SidebarContext);
if (context === undefined) {
throw new Error("useSidebar must be used within a Providers");
}
return context;
}

135
app/register/page.tsx Normal file
View File

@@ -0,0 +1,135 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { UserPlus, User, Key, MessageSquare, Loader2 } from 'lucide-react';
import Link from 'next/link';
export default function RegisterPage() {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [formData, setFormData] = useState({
username: '',
password: '',
chatId: ''
});
const handleRegister = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Error al registrarse');
router.push('/');
router.refresh();
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen bg-slate-950 flex items-center justify-center p-4">
<div className="w-full max-w-md bg-slate-900 border border-slate-800 rounded-2xl shadow-xl overflow-hidden">
{/* Header */}
<div className="bg-slate-950/50 p-6 text-center border-b border-slate-800">
<div className="mx-auto w-12 h-12 bg-blue-500/10 rounded-xl flex items-center justify-center mb-4">
<UserPlus className="w-6 h-6 text-blue-500" />
</div>
<h1 className="text-2xl font-bold text-white mb-1">Crear Cuenta</h1>
<p className="text-slate-400 text-sm">Configura tu acceso a Finanzas</p>
</div>
<div className="p-6">
{error && (
<div className="mb-6 p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm text-center">
{error}
</div>
)}
<form onSubmit={handleRegister} className="space-y-4">
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider">Usuario</label>
<div className="relative">
<User className="absolute left-3 top-2.5 w-5 h-5 text-slate-500" />
<input
type="text"
required
value={formData.username}
onChange={e => setFormData({...formData, username: e.target.value})}
className="w-full pl-10 pr-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all placeholder:text-slate-600"
placeholder="Elige un usuario"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider">Contraseña</label>
<div className="relative">
<Key className="absolute left-3 top-2.5 w-5 h-5 text-slate-500" />
<input
type="password"
required
value={formData.password}
onChange={e => setFormData({...formData, password: e.target.value})}
className="w-full pl-10 pr-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all placeholder:text-slate-600"
placeholder="Mínimo 6 caracteres"
minLength={6}
/>
</div>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider">Telegram Chat ID</label>
<div className="relative">
<MessageSquare className="absolute left-3 top-2.5 w-5 h-5 text-slate-500" />
<input
type="text"
required
value={formData.chatId}
onChange={e => setFormData({...formData, chatId: e.target.value})}
className="w-full pl-10 pr-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all placeholder:text-slate-600"
placeholder="Ej: 123456789"
/>
</div>
<p className="text-[10px] text-slate-500 flex gap-1">
<span></span>
Envía /start a tu bot para obtener este ID.
</p>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-blue-600 hover:bg-blue-500 text-white font-medium py-2.5 rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed mt-2"
>
{loading ? <Loader2 className="animate-spin w-5 h-5" /> : 'Registrar Cuenta'}
</button>
</form>
</div>
<div className="bg-slate-950/50 p-4 text-center border-t border-slate-800">
<p className="text-slate-500 text-sm">
¿Ya tienes cuenta?{' '}
<Link href="/login" className="text-blue-500 hover:text-blue-400 font-medium hover:underline">
Inicia Sesión
</Link>
</p>
</div>
</div>
</div>
);
}

145
app/services/page.tsx Normal file
View File

@@ -0,0 +1,145 @@
'use client'
import { useState } from 'react'
import { useFinanzasStore } from '@/lib/store'
import { predictNextBill, calculateTrend } from '@/lib/predictions'
import { formatCurrency } from '@/lib/utils'
import { Zap, Droplets, Flame, Wifi, TrendingUp, TrendingDown, Plus, History } from 'lucide-react'
import { cn } from '@/lib/utils'
import { AddServiceModal } from '@/components/modals/AddServiceModal'
import { DashboardLayout } from '@/components/layout/DashboardLayout'
const SERVICES = [
{ id: 'electricity', label: 'Luz (Electricidad)', icon: Zap, color: 'text-yellow-400', bg: 'bg-yellow-400/10' },
{ id: 'water', label: 'Agua', icon: Droplets, color: 'text-blue-400', bg: 'bg-blue-400/10' },
{ id: 'gas', label: 'Gas', icon: Flame, color: 'text-orange-400', bg: 'bg-orange-400/10' },
{ id: 'internet', label: 'Internet', icon: Wifi, color: 'text-cyan-400', bg: 'bg-cyan-400/10' },
]
export default function ServicesPage() {
const serviceBills = useFinanzasStore((state) => state.serviceBills)
const [isAddModalOpen, setIsAddModalOpen] = useState(false)
return (
<DashboardLayout title="Servicios">
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold text-white">Servicios y Predicciones</h2>
<p className="text-slate-400 text-sm">Gestiona tus consumos de Luz, Agua y Gas.</p>
</div>
<button
onClick={() => setIsAddModalOpen(true)}
className="flex items-center gap-2 px-4 py-2 bg-cyan-500 hover:bg-cyan-400 text-white rounded-lg transition shadow-lg shadow-cyan-500/20 font-medium self-start sm:self-auto"
>
<Plus size={18} /> Nuevo Pago
</button>
</div>
{/* Service Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{SERVICES.map((service) => {
const Icon = service.icon
const prediction = predictNextBill(serviceBills, service.id as any)
const trend = calculateTrend(serviceBills, service.id as any)
const lastBill = serviceBills
.filter(b => b.type === service.id)
.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())[0]
return (
<div key={service.id} className="bg-slate-900 border border-slate-800 rounded-xl p-5 space-y-4">
<div className="flex items-center justify-between">
<div className={cn("p-2 rounded-lg", service.bg)}>
<Icon className={cn("w-6 h-6", service.color)} />
</div>
{trend !== 0 && (
<div className={cn("flex items-center gap-1 text-xs font-medium px-2 py-1 rounded-full", trend > 0 ? "bg-red-500/10 text-red-400" : "bg-emerald-500/10 text-emerald-400")}>
{trend > 0 ? <TrendingUp size={12} /> : <TrendingDown size={12} />}
{Math.abs(trend).toFixed(0)}%
</div>
)}
</div>
<div>
<p className="text-slate-400 text-sm font-medium">{service.label}</p>
<div className="flex items-baseline gap-2">
<h3 className="text-2xl font-bold text-white mt-1">
{formatCurrency(prediction || (lastBill?.amount ?? 0))}
</h3>
{prediction > 0 && <span className="text-xs text-slate-500 font-mono">(est.)</span>}
</div>
<p className="text-xs text-slate-500 mt-1">
{lastBill
? `Último: ${formatCurrency(lastBill.amount)}`
: 'Sin historial'}
</p>
</div>
</div>
)
})}
</div>
{/* History List */}
<div className="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden">
<div className="p-5 border-b border-slate-800 flex items-center gap-2">
<History size={18} className="text-slate-400" />
<h3 className="text-lg font-semibold text-white">Historial de Pagos</h3>
</div>
<div className="divide-y divide-slate-800">
{serviceBills.length === 0 ? (
<div className="p-8 text-center text-slate-500 text-sm">
No hay facturas registradas. Comienza agregando una para ver predicciones.
</div>
) : (
serviceBills
.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
.map((bill) => {
const service = SERVICES.find(s => s.id === bill.type)
const Icon = service?.icon || Zap
return (
<div key={bill.id} className="p-4 flex items-center justify-between hover:bg-slate-800/50 transition-colors">
<div className="flex items-center gap-4">
<div className={cn("p-2 rounded-lg", service?.bg || 'bg-slate-800')}>
<Icon className={cn("w-5 h-5", service?.color || 'text-slate-400')} />
</div>
<div>
<p className="text-white font-medium capitalize">{service?.label || bill.type}</p>
<div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2">
<p className="text-xs text-slate-500 capitalize">{new Date(bill.date).toLocaleDateString('es-AR', { dateStyle: 'long' })}</p>
{bill.usage && (
<>
<span className="hidden sm:inline text-slate-700"></span>
<p className="text-xs text-slate-400">
Consumo: <span className="text-slate-300 font-medium">{bill.usage} {bill.unit}</span>
</p>
</>
)}
</div>
</div>
</div>
<div className="text-right">
<p className="text-white font-mono font-medium">{formatCurrency(bill.amount)}</p>
<div className="flex flex-col items-end">
<p className="text-xs text-slate-500 uppercase">{bill.period}</p>
{bill.usage && bill.amount && (
<p className="text-[10px] text-cyan-500/80 font-mono">
{formatCurrency(bill.amount / bill.usage)} / {bill.unit}
</p>
)}
</div>
</div>
</div>
)
})
)}
</div>
</div>
<AddServiceModal isOpen={isAddModalOpen} onClose={() => setIsAddModalOpen(false)} />
</div>
</DashboardLayout>
)
}

372
app/settings/page.tsx Normal file
View File

@@ -0,0 +1,372 @@
'use client'
import { useState, useEffect } from 'react'
import { Save, Plus, Trash2, Bot, MessageSquare, Key, Link as LinkIcon, Lock, Send, CheckCircle2, XCircle, Loader2, Sparkles, Box } from 'lucide-react'
import { cn } from '@/lib/utils'
import { AIServiceConfig, AppSettings } from '@/lib/types'
import { DashboardLayout } from '@/components/layout/DashboardLayout'
export default function SettingsPage() {
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [settings, setSettings] = useState<AppSettings>({
telegram: { botToken: '', chatId: '' },
aiProviders: []
})
const [message, setMessage] = useState<{ text: string, type: 'success' | 'error' } | null>(null)
// Test loading states
const [testingTelegram, setTestingTelegram] = useState(false)
const [testingAI, setTestingAI] = useState<string | null>(null)
const [detectingModels, setDetectingModels] = useState<string | null>(null)
const [availableModels, setAvailableModels] = useState<Record<string, string[]>>({})
useEffect(() => {
fetch('/api/settings')
.then(res => res.json())
.then(data => {
setSettings(data)
setLoading(false)
})
.catch(err => {
console.error(err)
setLoading(false)
setMessage({ text: 'Error cargando configuración', type: 'error' })
})
}, [])
const handleSave = async () => {
setSaving(true)
setMessage(null)
try {
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settings)
})
if (!res.ok) throw new Error('Error saving')
setMessage({ text: 'Configuración guardada correctamente', type: 'success' })
} catch (err) {
setMessage({ text: 'Error al guardar la configuración', type: 'error' })
} finally {
setSaving(false)
}
}
const testTelegram = async () => {
setTestingTelegram(true)
setMessage(null)
try {
const res = await fetch('/api/test/telegram', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settings.telegram)
})
const data = await res.json()
if (data.success) {
setMessage({ text: 'Mensaje de prueba enviado con éxito ✅', type: 'success' })
} else {
setMessage({ text: `Error: ${data.error}`, type: 'error' })
}
} catch (err: any) {
setMessage({ text: 'Error de conexión al probar Telegram', type: 'error' })
} finally {
setTestingTelegram(false)
}
}
const testAI = async (provider: AIServiceConfig) => {
setTestingAI(provider.id)
setMessage(null)
try {
const res = await fetch('/api/test/ai', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(provider)
})
const data = await res.json()
if (data.success) {
setMessage({ text: `Conexión exitosa con ${provider.model || provider.name} (${data.latency}ms) ✅`, type: 'success' })
} else {
setMessage({ text: `Error con ${provider.name}: ${data.error}`, type: 'error' })
}
} catch (err) {
setMessage({ text: 'Error al conectar con el proveedor', type: 'error' })
} finally {
setTestingAI(null)
}
}
const detectModels = async (provider: AIServiceConfig) => {
setDetectingModels(provider.id)
setMessage(null)
try {
const res = await fetch('/api/proxy/models', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ endpoint: provider.endpoint, token: provider.token })
})
const data = await res.json()
if (data.success && data.models.length > 0) {
setAvailableModels(prev => ({ ...prev, [provider.id]: data.models }))
// Auto select first if none selected
if (!provider.model) {
updateProvider(provider.id, 'model', data.models[0])
}
setMessage({ text: `Se detectaron ${data.models.length} modelos ✅`, type: 'success' })
} else {
setMessage({ text: `No se pudieron detectar modelos. Ingrésalo manualmente.`, type: 'error' })
}
} catch (err) {
console.error(err)
setMessage({ text: 'Error al consultar modelos', type: 'error' })
} finally {
setDetectingModels(null)
}
}
const addProvider = () => {
if (settings.aiProviders.length >= 3) return
setSettings(prev => ({
...prev,
aiProviders: [
...prev.aiProviders,
{ id: crypto.randomUUID(), name: '', endpoint: '', token: '', model: '' }
]
}))
}
const removeProvider = (id: string) => {
setSettings(prev => ({
...prev,
aiProviders: prev.aiProviders.filter(p => p.id !== id)
}))
}
const updateProvider = (id: string, field: keyof AIServiceConfig, value: string) => {
setSettings(prev => ({
...prev,
aiProviders: prev.aiProviders.map(p =>
p.id === id ? { ...p, [field]: value } : p
)
}))
}
if (loading) return <div className="p-8 text-center text-slate-400">Cargando configuración...</div>
return (
<DashboardLayout title="Configuración">
<div className="max-w-4xl mx-auto space-y-8 pb-10">
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold text-white">Configuración</h2>
<p className="text-slate-400 text-sm">Gestiona la integración con Telegram e Inteligencia Artificial.</p>
</div>
<button
onClick={handleSave}
disabled={saving}
className="flex items-center gap-2 px-6 py-2 bg-emerald-500 hover:bg-emerald-400 text-white rounded-lg transition shadow-lg shadow-emerald-500/20 font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
<Save size={18} />
{saving ? 'Guardando...' : 'Guardar Cambios'}
</button>
</div>
{message && (
<div className={cn(
"p-4 rounded-lg text-sm font-medium border flex items-center gap-2 animate-in fade-in slide-in-from-top-2",
message.type === 'success' ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-400" : "bg-red-500/10 border-red-500/20 text-red-400"
)}>
{message.type === 'success' ? <CheckCircle2 size={18} /> : <XCircle size={18} />}
{message.text}
</div>
)}
{/* Telegram Configuration */}
<section className="space-y-4">
<div className="flex items-center justify-between text-white border-b border-slate-800 pb-2">
<div className="flex items-center gap-2">
<Bot className="text-cyan-400" />
<h2 className="text-lg font-semibold">Telegram Bot</h2>
</div>
<button
onClick={testTelegram}
disabled={testingTelegram || !settings.telegram.botToken || !settings.telegram.chatId}
className="text-xs flex items-center gap-1.5 bg-cyan-500/10 hover:bg-cyan-500/20 text-cyan-400 border border-cyan-500/20 px-3 py-1.5 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
>
{testingTelegram ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />}
Probar Envío
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-6 bg-slate-900 border border-slate-800 rounded-xl">
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
<Key size={12} /> Bot Token
</label>
<input
type="text"
placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
value={settings.telegram.botToken}
onChange={(e) => setSettings({ ...settings, telegram: { ...settings.telegram, botToken: e.target.value } })}
className="w-full px-4 py-3 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500 text-white font-mono text-sm outline-none transition-all placeholder:text-slate-700"
/>
<p className="text-[10px] text-slate-500">El token que te da @BotFather.</p>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
<MessageSquare size={12} /> Chat ID
</label>
<input
type="text"
placeholder="123456789"
value={settings.telegram.chatId}
onChange={(e) => setSettings({ ...settings, telegram: { ...settings.telegram, chatId: e.target.value } })}
className="w-full px-4 py-3 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500 text-white font-mono text-sm outline-none transition-all placeholder:text-slate-700"
/>
<p className="text-[10px] text-slate-500">Tu ID numérico de Telegram (o el ID del grupo).</p>
</div>
</div>
</section>
{/* AI Providers Configuration */}
<section className="space-y-4">
<div className="flex items-center justify-between text-white border-b border-slate-800 pb-2">
<div className="flex items-center gap-2">
<Bot className="text-purple-400" />
<h2 className="text-lg font-semibold">Proveedores de IA</h2>
</div>
<button
onClick={addProvider}
disabled={settings.aiProviders.length >= 3}
className="text-xs flex items-center gap-1 bg-slate-800 hover:bg-slate-700 text-slate-200 px-3 py-1.5 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
>
<Plus size={14} /> Agregar Provider ({settings.aiProviders.length}/3)
</button>
</div>
<div className="space-y-4">
{settings.aiProviders.length === 0 && (
<div className="p-8 text-center text-slate-500 border border-dashed border-slate-800 rounded-xl">
No hay proveedores de IA configurados. Agrega uno para empezar.
</div>
)}
{settings.aiProviders.map((provider, index) => (
<div key={provider.id} className="p-6 bg-slate-900 border border-slate-800 rounded-xl relative group">
<div className="flex justify-between items-start mb-4">
<h3 className="text-sm font-semibold text-slate-300 bg-slate-950 inline-block px-3 py-1 rounded-md border border-slate-800">
Provider #{index + 1}
</h3>
<div className="flex gap-2">
<button
onClick={() => testAI(provider)}
disabled={testingAI === provider.id || !provider.endpoint || !provider.token || !provider.model}
className={cn("text-xs flex items-center gap-1 bg-slate-800 hover:bg-slate-700 text-purple-300 border border-purple-500/20 px-2 py-1.5 rounded-lg transition disabled:opacity-50", !provider.model && "opacity-50")}
title="Verificar conexión"
>
{testingAI === provider.id ? <Loader2 size={12} className="animate-spin" /> : <LinkIcon size={12} />}
Test
</button>
<button
onClick={() => removeProvider(provider.id)}
className="text-slate-500 hover:text-red-400 transition-colors p-1.5 hover:bg-red-500/10 rounded-lg"
title="Eliminar"
>
<Trash2 size={16} />
</button>
</div>
</div>
<div className="grid grid-cols-1 gap-4">
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider">Nombre</label>
<input
type="text"
placeholder="Ej: MiniMax, Z.ai"
value={provider.name}
onChange={(e) => updateProvider(provider.id, 'name', e.target.value)}
className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white text-sm outline-none"
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
<LinkIcon size={12} /> Endpoint URL
</label>
<input
type="text"
placeholder="https://api.example.com/v1"
value={provider.endpoint}
onChange={(e) => updateProvider(provider.id, 'endpoint', e.target.value)}
className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white font-mono text-sm outline-none"
/>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
<Lock size={12} /> API Key / Token
</label>
<input
type="password"
placeholder="sk-..."
value={provider.token}
onChange={(e) => updateProvider(provider.id, 'token', e.target.value)}
className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white font-mono text-sm outline-none"
/>
</div>
</div>
{/* Model Selection */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
<Box size={12} /> Model
</label>
<button
onClick={() => detectModels(provider)}
disabled={detectingModels === provider.id || !provider.endpoint || !provider.token}
className="text-[10px] flex items-center gap-1 text-cyan-400 hover:text-cyan-300 disabled:opacity-50"
>
{detectingModels === provider.id ? <Loader2 size={10} className="animate-spin" /> : <Sparkles size={10} />}
Auto Detectar
</button>
</div>
{availableModels[provider.id] ? (
<select
value={provider.model || ''}
onChange={(e) => updateProvider(provider.id, 'model', e.target.value)}
className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white text-sm outline-none"
>
<option value="" disabled>Selecciona un modelo</option>
{availableModels[provider.id].map(m => (
<option key={m} value={m}>{m}</option>
))}
</select>
) : (
<input
type="text"
placeholder="Ej: gpt-3.5-turbo, glm-4"
value={provider.model || ''}
onChange={(e) => updateProvider(provider.id, 'model', e.target.value)}
className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white font-mono text-sm outline-none"
/>
)}
</div>
</div>
</div>
))}
</div>
</section>
</div>
</DashboardLayout>
)
}