Versión 1.0: Aplicación funcionalmente completa con todas las características principales implementadas.
This commit is contained in:
@@ -1,28 +1,107 @@
|
||||
// frontend/src/App.tsx
|
||||
|
||||
import { ThemeProvider, createTheme, CssBaseline, Container } from '@mui/material';
|
||||
import { ThemeProvider, createTheme, CssBaseline, AppBar, Toolbar, Typography, Container, Box } from '@mui/material';
|
||||
import Dashboard from './components/Dashboard';
|
||||
|
||||
// Paleta de colores ajustada para coincidir con la nueva imagen (inspirada en Tailwind)
|
||||
const darkTheme = createTheme({
|
||||
palette: {
|
||||
mode: 'dark',
|
||||
primary: {
|
||||
main: '#90caf9', // Un azul más claro para mejor contraste en modo oscuro
|
||||
main: '#3b82f6', // blue-500
|
||||
},
|
||||
secondary: {
|
||||
main: '#4f46e5', // indigo-600 para el botón de guardar
|
||||
},
|
||||
success: {
|
||||
main: '#22c55e', // green-500
|
||||
},
|
||||
warning: {
|
||||
main: '#f59e0b', // amber-500
|
||||
},
|
||||
info: {
|
||||
main: '#3b82f6', // blue-500
|
||||
},
|
||||
background: {
|
||||
default: '#121212',
|
||||
paper: '#1e1e1e',
|
||||
default: '#111827', // gray-900
|
||||
paper: '#1F2937', // gray-800
|
||||
},
|
||||
text: {
|
||||
primary: '#e5e7eb', // gray-200
|
||||
secondary: '#9ca3af', // gray-400
|
||||
}
|
||||
},
|
||||
components: {
|
||||
MuiAppBar: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
backgroundColor: '#1F2937', // gray-800
|
||||
boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
|
||||
}
|
||||
}
|
||||
},
|
||||
MuiTextField: {
|
||||
defaultProps: {
|
||||
variant: 'filled',
|
||||
},
|
||||
styleOverrides: {
|
||||
root: {
|
||||
'& .MuiFilledInput-root': {
|
||||
backgroundColor: '#374151', // gray-700
|
||||
'&:hover': {
|
||||
backgroundColor: '#4b5563', // gray-600
|
||||
},
|
||||
'&.Mui-focused': {
|
||||
backgroundColor: '#4b5563', // gray-600
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiChip: {
|
||||
styleOverrides: {
|
||||
// Ejemplo para el chip 'Edited'
|
||||
colorWarning: {
|
||||
backgroundColor: 'rgba(245, 158, 11, 0.2)', // amber-500 con opacidad
|
||||
color: '#f59e0b',
|
||||
},
|
||||
// Chip 'Manual'
|
||||
colorInfo: {
|
||||
backgroundColor: 'rgba(59, 130, 246, 0.2)', // blue-500 con opacidad
|
||||
color: '#60a5fa',
|
||||
},
|
||||
// Chip 'Scraped'
|
||||
colorSuccess: {
|
||||
backgroundColor: 'rgba(34, 197, 94, 0.2)', // green-500 con opacidad
|
||||
color: '#4ade80',
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const Layout = ({ children }: { children: React.ReactNode }) => (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
|
||||
<AppBar position="sticky">
|
||||
<Toolbar>
|
||||
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
|
||||
Titulares Dashboard
|
||||
</Typography>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
<Container maxWidth="xl" component="main" sx={{ flexGrow: 1, py: 4 }}>
|
||||
{children}
|
||||
</Container>
|
||||
</Box>
|
||||
);
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<ThemeProvider theme={darkTheme}>
|
||||
<CssBaseline />
|
||||
<Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
|
||||
<Layout>
|
||||
<Dashboard />
|
||||
</Container>
|
||||
</Layout>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,53 +1,76 @@
|
||||
// frontend/src/components/Dashboard.tsx
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { Box, Button, Typography, Stack, Chip, CircularProgress } from '@mui/material';
|
||||
import {
|
||||
Box, Button, Stack, Chip, CircularProgress,
|
||||
Accordion, AccordionSummary, AccordionDetails, Typography
|
||||
} from '@mui/material';
|
||||
import AddIcon from '@mui/icons-material/Add';
|
||||
import SyncIcon from '@mui/icons-material/Sync';
|
||||
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
|
||||
|
||||
import type { Titular } from '../types';
|
||||
import type { Titular, Configuracion } from '../types';
|
||||
import * as api from '../services/apiService';
|
||||
import { useSignalR } from '../hooks/useSignalR';
|
||||
import FormularioConfiguracion from './FormularioConfiguracion';
|
||||
import TablaTitulares from './TablaTitulares';
|
||||
import AddTitularModal from './AddTitularModal';
|
||||
import EditarTitularModal from './EditarTitularModal';
|
||||
import { PowerSwitch } from './PowerSwitch';
|
||||
|
||||
const Dashboard = () => {
|
||||
const [titulares, setTitulares] = useState<Titular[]>([]);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [config, setConfig] = useState<Configuracion | null>(null);
|
||||
const [addModalOpen, setAddModalOpen] = useState(false);
|
||||
const [isGeneratingCsv, setIsGeneratingCsv] = useState(false);
|
||||
const [titularAEditar, setTitularAEditar] = useState<Titular | null>(null);
|
||||
|
||||
// Usamos useCallback para que la función de callback no se recree en cada render,
|
||||
// evitando que el useEffect del hook se ejecute innecesariamente.
|
||||
const onTitularesActualizados = useCallback((titularesActualizados: Titular[]) => {
|
||||
console.log("Datos recibidos desde SignalR:", titularesActualizados);
|
||||
setTitulares(titularesActualizados);
|
||||
}, []); // El array vacío significa que esta función nunca cambiará
|
||||
}, []);
|
||||
|
||||
// Usamos nuestro hook y le pasamos el evento que nos interesa escuchar
|
||||
const { connectionStatus } = useSignalR([
|
||||
{ eventName: 'TitularesActualizados', callback: onTitularesActualizados }
|
||||
]);
|
||||
|
||||
// La carga inicial de datos sigue siendo necesaria por si el componente se monta
|
||||
// antes de que llegue la primera notificación de SignalR.
|
||||
useEffect(() => {
|
||||
api.obtenerTitulares()
|
||||
.then(setTitulares)
|
||||
.catch(error => console.error("Error al cargar titulares:", error));
|
||||
// Obtenemos la configuración persistente
|
||||
const fetchConfig = api.obtenerConfiguracion();
|
||||
// Obtenemos el estado inicial del switch (que siempre será 'false')
|
||||
const fetchEstado = api.getEstadoProceso();
|
||||
|
||||
// Cuando ambas promesas se resuelvan, construimos el estado inicial
|
||||
Promise.all([fetchConfig, fetchEstado])
|
||||
.then(([configData, estadoData]) => {
|
||||
setConfig({
|
||||
...configData,
|
||||
scrapingActivo: estadoData.activo
|
||||
});
|
||||
})
|
||||
.catch(error => console.error("Error al cargar datos iniciales:", error));
|
||||
|
||||
api.obtenerTitulares().then(setTitulares);
|
||||
}, []);
|
||||
|
||||
const handleSwitchChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!config) return;
|
||||
const isChecked = event.target.checked;
|
||||
setConfig({ ...config, scrapingActivo: isChecked });
|
||||
try {
|
||||
// Llamamos al nuevo endpoint para cambiar solo el estado
|
||||
await api.setEstadoProceso(isChecked);
|
||||
} catch (err) {
|
||||
console.error("Error al cambiar estado del proceso", err);
|
||||
// Revertir en caso de error
|
||||
setConfig({ ...config, scrapingActivo: !isChecked });
|
||||
}
|
||||
};
|
||||
|
||||
const handleReorder = async (titularesReordenados: Titular[]) => {
|
||||
setTitulares(titularesReordenados);
|
||||
const payload = titularesReordenados.map((item, index) => ({ id: item.id, nuevoOrden: index }));
|
||||
try {
|
||||
await api.actualizarOrdenTitulares(payload);
|
||||
// Ya no necesitamos hacer nada más, SignalR notificará a todos los clientes.
|
||||
} catch (err) {
|
||||
console.error("Error al reordenar:", err);
|
||||
// En caso de error, volvemos a pedir los datos para no tener un estado inconsistente.
|
||||
api.obtenerTitulares().then(setTitulares);
|
||||
}
|
||||
};
|
||||
@@ -56,7 +79,6 @@ const Dashboard = () => {
|
||||
if (window.confirm('¿Estás seguro de que quieres eliminar este titular?')) {
|
||||
try {
|
||||
await api.eliminarTitular(id);
|
||||
// SignalR se encargará de actualizar el estado.
|
||||
} catch (err) {
|
||||
console.error("Error al eliminar:", err);
|
||||
}
|
||||
@@ -66,7 +88,6 @@ const Dashboard = () => {
|
||||
const handleAdd = async (texto: string) => {
|
||||
try {
|
||||
await api.crearTitularManual(texto);
|
||||
// SignalR se encargará de actualizar el estado.
|
||||
} catch (err) {
|
||||
console.error("Error al añadir titular:", err);
|
||||
}
|
||||
@@ -88,10 +109,8 @@ const Dashboard = () => {
|
||||
setIsGeneratingCsv(true);
|
||||
try {
|
||||
await api.generarCsvManual();
|
||||
// Opcional: mostrar una notificación de éxito
|
||||
} catch (error) {
|
||||
console.error("Error al generar CSV manualmente", error);
|
||||
// Opcional: mostrar una notificación de error
|
||||
console.error("Error al generar CSV manually", error);
|
||||
} finally {
|
||||
setIsGeneratingCsv(false);
|
||||
}
|
||||
@@ -100,7 +119,6 @@ const Dashboard = () => {
|
||||
const handleSaveEdit = async (id: number, texto: string, viñeta: string) => {
|
||||
try {
|
||||
await api.actualizarTitular(id, { texto, viñeta: viñeta || null });
|
||||
// SignalR se encargará de actualizar la UI
|
||||
} catch (err) {
|
||||
console.error("Error al guardar cambios:", err);
|
||||
}
|
||||
@@ -108,29 +126,56 @@ const Dashboard = () => {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: { xs: 'column', sm: 'row' },
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
gap: 2,
|
||||
mb: 3,
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" spacing={2} alignItems="center">
|
||||
<Typography variant="h4" component="h1">
|
||||
Titulares Dashboard
|
||||
<Typography variant="h5" component="h2" sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
|
||||
Estado del Servidor {getStatusChip()}
|
||||
</Typography>
|
||||
{getStatusChip()}
|
||||
{config ? (
|
||||
<PowerSwitch
|
||||
checked={config.scrapingActivo}
|
||||
onChange={handleSwitchChange}
|
||||
label={config.scrapingActivo ? "Proceso ON" : "Proceso OFF"}
|
||||
/>
|
||||
) : <CircularProgress size={24} />}
|
||||
</Stack>
|
||||
<Stack direction="row" spacing={2}>
|
||||
|
||||
<Stack direction="row" spacing={2} sx={{ width: { xs: '100%', sm: 'auto' } }}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
startIcon={isGeneratingCsv ? <CircularProgress size={20} /> : <SyncIcon />}
|
||||
onClick={handleGenerateCsv}
|
||||
disabled={isGeneratingCsv}
|
||||
variant="contained" color="success"
|
||||
startIcon={isGeneratingCsv ? <CircularProgress size={20} color="inherit" /> : <SyncIcon />}
|
||||
onClick={handleGenerateCsv} disabled={isGeneratingCsv}
|
||||
>
|
||||
{isGeneratingCsv ? 'Generando...' : 'Generate CSV'}
|
||||
Regenerar CSV
|
||||
</Button>
|
||||
<Button variant="contained" startIcon={<AddIcon />} onClick={() => setModalOpen(true)}>
|
||||
Add Manual
|
||||
<Button
|
||||
variant="contained" color="primary"
|
||||
startIcon={<AddIcon />}
|
||||
onClick={() => setAddModalOpen(true)}
|
||||
>
|
||||
Titular Manual
|
||||
</Button>
|
||||
</Stack>
|
||||
</Box>
|
||||
|
||||
<FormularioConfiguracion />
|
||||
<Accordion defaultExpanded={false} sx={{ mb: 3 }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||
<Typography variant="h6">Configuración</Typography>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
<FormularioConfiguracion config={config} setConfig={setConfig} />
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
|
||||
<TablaTitulares
|
||||
titulares={titulares}
|
||||
onReorder={handleReorder}
|
||||
@@ -139,8 +184,8 @@ const Dashboard = () => {
|
||||
/>
|
||||
|
||||
<AddTitularModal
|
||||
open={modalOpen}
|
||||
onClose={() => setModalOpen(false)}
|
||||
open={addModalOpen}
|
||||
onClose={() => setAddModalOpen(false)}
|
||||
onAdd={handleAdd}
|
||||
/>
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
// frontend/src/components/EditarTitularModal.tsx
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Modal, Box, Typography, TextField, Button } from '@mui/material';
|
||||
import type { Titular } from '../types';
|
||||
@@ -26,17 +24,20 @@ const EditarTitularModal = ({ open, onClose, onSave, titular }: Props) => {
|
||||
const [texto, setTexto] = useState('');
|
||||
const [viñeta, setViñeta] = useState('');
|
||||
|
||||
// Este efecto actualiza el estado del formulario cuando se selecciona un titular para editar
|
||||
useEffect(() => {
|
||||
if (titular) {
|
||||
setTexto(titular.texto);
|
||||
setViñeta(titular.viñeta ?? '•'); // Default a '•' si es nulo
|
||||
// Usamos el valor real, incluso si es solo espacios o una cadena vacía.
|
||||
setViñeta(titular.viñeta ?? '');
|
||||
}
|
||||
}, [titular]);
|
||||
|
||||
const handleSave = () => {
|
||||
// Verificamos que el titular exista y que el texto principal no esté vacío.
|
||||
if (titular && texto.trim()) {
|
||||
onSave(titular.id, texto.trim(), viñeta.trim());
|
||||
const textoLimpio = texto.trim();
|
||||
const viñetaSinLimpiar = viñeta;
|
||||
onSave(titular.id, textoLimpio, viñetaSinLimpiar);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,43 +1,40 @@
|
||||
// frontend/src/components/FormularioConfiguracion.tsx
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Box, TextField, Button, Paper, Typography, CircularProgress } from '@mui/material';
|
||||
import { Box, TextField, Button, Paper, CircularProgress, Typography } from '@mui/material';
|
||||
import type { Configuracion } from '../types';
|
||||
import * as api from '../services/apiService';
|
||||
import { useState } from 'react';
|
||||
|
||||
const FormularioConfiguracion = () => {
|
||||
const [config, setConfig] = useState<Configuracion | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
interface Props {
|
||||
config: Configuracion | null;
|
||||
setConfig: React.Dispatch<React.SetStateAction<Configuracion | null>>;
|
||||
}
|
||||
|
||||
const FormularioConfiguracion = ({ config, setConfig }: Props) => {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api.obtenerConfiguracion()
|
||||
.then(data => {
|
||||
setConfig(data);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(err => console.error("Error al cargar configuración", err));
|
||||
}, []);
|
||||
if (!config) {
|
||||
return <CircularProgress />;
|
||||
}
|
||||
|
||||
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!config) return;
|
||||
const { name, value } = event.target;
|
||||
setConfig({
|
||||
...config,
|
||||
[name]: name === 'rutaCsv' ? value : Number(value) // Convertir a número si no es la ruta
|
||||
});
|
||||
const numericFields = ['intervaloMinutos', 'cantidadTitularesAScrapear'];
|
||||
|
||||
setConfig(prevConfig => prevConfig ? {
|
||||
...prevConfig,
|
||||
[name]: numericFields.includes(name) ? Number(value) : value
|
||||
} : null);
|
||||
};
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!config) return;
|
||||
|
||||
setSaving(true);
|
||||
setSuccess(false);
|
||||
try {
|
||||
await api.guardarConfiguracion(config);
|
||||
setSuccess(true);
|
||||
setTimeout(() => setSuccess(false), 2000); // El mensaje de éxito desaparece después de 2s
|
||||
setTimeout(() => setSuccess(false), 2000);
|
||||
} catch (err) {
|
||||
console.error("Error al guardar configuración", err);
|
||||
} finally {
|
||||
@@ -45,32 +42,22 @@ const FormularioConfiguracion = () => {
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <CircularProgress />;
|
||||
}
|
||||
|
||||
if (!config) {
|
||||
return <Typography color="error">No se pudo cargar la configuración.</Typography>
|
||||
}
|
||||
|
||||
return (
|
||||
<Paper elevation={3} sx={{ padding: 2, marginBottom: 3 }}>
|
||||
<Typography variant="h6" gutterBottom>Configuración</Typography>
|
||||
<Paper elevation={0} sx={{ padding: 2 }}>
|
||||
<Box component="form" onSubmit={handleSubmit}>
|
||||
<TextField fullWidth name="rutaCsv" label="Ruta del archivo CSV" value={config.rutaCsv} onChange={handleChange} variant="outlined" sx={{ mb: 2 }} disabled={saving} />
|
||||
<TextField fullWidth name="intervaloMinutos" label="Intervalo de Actualización (minutos)" value={config.intervaloMinutos} onChange={handleChange} type="number" variant="outlined" sx={{ mb: 2 }} disabled={saving} />
|
||||
<TextField fullWidth name="cantidadTitularesAScrapear" label="Titulares a Capturar por Ciclo" value={config.cantidadTitularesAScrapear} onChange={handleChange} type="number" variant="outlined" sx={{ mb: 2 }} disabled={saving} />
|
||||
<TextField
|
||||
fullWidth name="rutaCsv" label="Ruta del archivo CSV"
|
||||
value={config.rutaCsv} onChange={handleChange}
|
||||
variant="outlined" sx={{ marginBottom: 2 }} disabled={saving}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth name="intervaloMinutos" label="Intervalo de Actualización (minutos)"
|
||||
value={config.intervaloMinutos} onChange={handleChange}
|
||||
type="number" variant="outlined" sx={{ marginBottom: 2 }} disabled={saving}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth name="cantidadTitularesAScrapear" label="Titulares a Capturar por Ciclo"
|
||||
value={config.cantidadTitularesAScrapear} onChange={handleChange}
|
||||
type="number" variant="outlined" sx={{ marginBottom: 2 }} disabled={saving}
|
||||
fullWidth
|
||||
name="viñetaPorDefecto"
|
||||
label="Viñeta por Defecto"
|
||||
value={config.viñetaPorDefecto}
|
||||
onChange={handleChange}
|
||||
variant="outlined"
|
||||
sx={{ mb: 2 }}
|
||||
disabled={saving}
|
||||
helperText="El símbolo a usar si un titular no tiene una viñeta específica."
|
||||
/>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
|
||||
{success && <Typography color="success.main" sx={{ mr: 2 }}>¡Guardado!</Typography>}
|
||||
|
||||
57
frontend/src/components/PowerSwitch.tsx
Normal file
57
frontend/src/components/PowerSwitch.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
// frontend/src/components/PowerSwitch.tsx
|
||||
|
||||
import { styled } from '@mui/material/styles';
|
||||
import Switch from '@mui/material/Switch';
|
||||
import FormControlLabel from '@mui/material/FormControlLabel';
|
||||
|
||||
const StyledSwitch = styled(Switch)(({ theme }) => ({
|
||||
width: 62,
|
||||
height: 34,
|
||||
padding: 7,
|
||||
'& .MuiSwitch-switchBase': {
|
||||
margin: 1,
|
||||
padding: 0,
|
||||
transform: 'translateX(6px)',
|
||||
'&.Mui-checked': {
|
||||
color: '#fff',
|
||||
transform: 'translateX(22px)',
|
||||
// Estilo para el thumb (el círculo) cuando está ON (verde)
|
||||
'& .MuiSwitch-thumb': {
|
||||
backgroundColor: theme.palette.success.main,
|
||||
},
|
||||
// Estilo para el track (la base) cuando está ON (verde claro)
|
||||
'& + .MuiSwitch-track': {
|
||||
opacity: 1,
|
||||
backgroundColor: theme.palette.success.light,
|
||||
},
|
||||
},
|
||||
},
|
||||
// Estilo para el thumb cuando está OFF (rojo)
|
||||
'& .MuiSwitch-thumb': {
|
||||
backgroundColor: theme.palette.error.main,
|
||||
width: 32,
|
||||
height: 32,
|
||||
},
|
||||
// Estilo para el track cuando está OFF (gris)
|
||||
'& .MuiSwitch-track': {
|
||||
opacity: 1,
|
||||
backgroundColor: theme.palette.mode === 'dark' ? '#8796A5' : '#aab4be',
|
||||
borderRadius: 20 / 2,
|
||||
},
|
||||
}));
|
||||
|
||||
interface PowerSwitchProps {
|
||||
checked: boolean;
|
||||
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
label: string;
|
||||
}
|
||||
|
||||
// Componente funcional que envuelve nuestro switch estilizado
|
||||
export const PowerSwitch = ({ checked, onChange, label }: PowerSwitchProps) => {
|
||||
return (
|
||||
<FormControlLabel
|
||||
control={<StyledSwitch checked={checked} onChange={onChange} />}
|
||||
label={label}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,17 +1,16 @@
|
||||
// frontend/src/components/TablaTitulares.tsx
|
||||
|
||||
import {
|
||||
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Chip, IconButton, Typography
|
||||
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Chip, IconButton, Typography, Link
|
||||
} from '@mui/material';
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import DragHandleIcon from '@mui/icons-material/DragHandle'; // Importar el ícono
|
||||
import DragHandleIcon from '@mui/icons-material/DragHandle';
|
||||
import EditIcon from '@mui/icons-material/Edit';
|
||||
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core';
|
||||
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import type { Titular } from '../types';
|
||||
import EditIcon from '@mui/icons-material/Edit';
|
||||
|
||||
// La prop `onDelete` se añade para comunicar el evento al componente padre
|
||||
interface SortableRowProps {
|
||||
titular: Titular;
|
||||
onDelete: (id: number) => void;
|
||||
@@ -26,28 +25,45 @@ const SortableRow = ({ titular, onDelete, onEdit }: SortableRowProps) => {
|
||||
transition,
|
||||
};
|
||||
|
||||
const getChipColor = (tipo: Titular['tipo']) => {
|
||||
const getChipColor = (tipo: Titular['tipo']): "success" | "warning" | "info" => {
|
||||
if (tipo === 'Edited') return 'warning';
|
||||
if (tipo === 'Manual') return 'info';
|
||||
return 'success';
|
||||
};
|
||||
|
||||
const formatFuente = (fuente: string | null) => {
|
||||
if (!fuente) return 'N/A';
|
||||
try {
|
||||
const url = new URL(fuente);
|
||||
return url.hostname.replace('www.', '');
|
||||
} catch {
|
||||
return fuente;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<TableRow ref={setNodeRef} style={style} {...attributes} >
|
||||
{/* El handle de arrastre ahora es un ícono */}
|
||||
<TableCell sx={{ cursor: 'grab' }} {...listeners}>
|
||||
<DragHandleIcon />
|
||||
<TableRow ref={setNodeRef} style={style} {...attributes} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
|
||||
<TableCell sx={{ cursor: 'grab', verticalAlign: 'middle' }} {...listeners}>
|
||||
<DragHandleIcon sx={{ color: 'text.secondary' }} />
|
||||
</TableCell>
|
||||
<TableCell>{titular.texto}</TableCell>
|
||||
<TableCell>
|
||||
<TableCell sx={{ verticalAlign: 'middle' }}>{titular.texto}</TableCell>
|
||||
<TableCell sx={{ verticalAlign: 'middle' }}>
|
||||
<Chip label={titular.tipo || 'Scraped'} color={getChipColor(titular.tipo)} size="small" />
|
||||
</TableCell>
|
||||
<TableCell>{titular.fuente}</TableCell>
|
||||
<TableCell>
|
||||
<TableCell sx={{ verticalAlign: 'middle' }}>
|
||||
{titular.urlFuente ? (
|
||||
<Link href={titular.urlFuente} target="_blank" rel="noopener noreferrer" underline="hover" color="primary.light">
|
||||
{formatFuente(titular.fuente)}
|
||||
</Link>
|
||||
) : (
|
||||
formatFuente(titular.fuente)
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell sx={{ verticalAlign: 'middle', textAlign: 'right' }}>
|
||||
<IconButton size="small" onClick={(e) => { e.stopPropagation(); onEdit(titular); }}>
|
||||
<EditIcon fontSize="small" />
|
||||
</IconButton>
|
||||
<IconButton size="small" onClick={(e) => { e.stopPropagation(); onDelete(titular.id); }}>
|
||||
<IconButton size="small" onClick={(e) => { e.stopPropagation(); onDelete(titular.id); }} sx={{ color: '#ef4444' }}>
|
||||
<DeleteIcon />
|
||||
</IconButton>
|
||||
</TableCell>
|
||||
@@ -63,39 +79,38 @@ interface TablaTitularesProps {
|
||||
}
|
||||
|
||||
const TablaTitulares = ({ titulares, onReorder, onDelete, onEdit }: TablaTitularesProps) => {
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } })); // Evita activar el drag con un simple clic
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
if (over && active.id !== over.id) {
|
||||
const oldIndex = titulares.findIndex((item) => item.id === active.id);
|
||||
const newIndex = titulares.findIndex((item) => item.id === over.id);
|
||||
const newArray = arrayMove(titulares, oldIndex, newIndex);
|
||||
onReorder(newArray); // Pasamos el nuevo array al padre para que gestione el estado y la llamada a la API
|
||||
onReorder(arrayMove(titulares, oldIndex, newIndex));
|
||||
}
|
||||
};
|
||||
|
||||
if (titulares.length === 0) {
|
||||
return (
|
||||
<Paper elevation={3} sx={{ padding: 3, textAlign: 'center' }}>
|
||||
<Paper elevation={0} sx={{ p: 3, textAlign: 'center' }}>
|
||||
<Typography>No hay titulares para mostrar.</Typography>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Paper elevation={3}>
|
||||
<Paper elevation={0} sx={{ overflow: 'hidden' }}>
|
||||
<TableContainer>
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||
<SortableContext items={titulares.map(t => t.id)} strategy={verticalListSortingStrategy}>
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell style={{ width: 50 }}></TableCell>
|
||||
<TableCell>Texto del Titular</TableCell>
|
||||
<TableCell>Tipo</TableCell>
|
||||
<TableCell>Fuente</TableCell>
|
||||
<TableCell>Acciones</TableCell>
|
||||
<TableRow sx={{ '& .MuiTableCell-root': { borderBottom: '1px solid rgba(255, 255, 255, 0.12)' } }}>
|
||||
<TableCell sx={{ width: 50 }} />
|
||||
<TableCell sx={{ textTransform: 'uppercase', color: 'text.secondary', letterSpacing: '0.05em' }}>Texto del Titular</TableCell>
|
||||
<TableCell sx={{ textTransform: 'uppercase', color: 'text.secondary', letterSpacing: '0.05em' }}>Tipo</TableCell>
|
||||
<TableCell sx={{ textTransform: 'uppercase', color: 'text.secondary', letterSpacing: '0.05em' }}>Fuente</TableCell>
|
||||
<TableCell sx={{ textTransform: 'uppercase', color: 'text.secondary', letterSpacing: '0.05em', textAlign: 'right' }}>Acciones</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
|
||||
@@ -42,10 +42,19 @@ export const obtenerConfiguracion = async (): Promise<Configuracion> => {
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const guardarConfiguracion = async (config: Configuracion): Promise<void> => {
|
||||
export const guardarConfiguracion = async (config: Omit<Configuracion, 'scrapingActivo'>): Promise<void> => {
|
||||
await apiClient.post('/configuracion', config);
|
||||
};
|
||||
|
||||
export const getEstadoProceso = async (): Promise<{ activo: boolean }> => {
|
||||
const response = await apiClient.get('/estado-proceso');
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const setEstadoProceso = async (activo: boolean): Promise<void> => {
|
||||
await apiClient.post('/estado-proceso', { activo });
|
||||
};
|
||||
|
||||
export const generarCsvManual = async (): Promise<void> => {
|
||||
await apiClient.post('/acciones/generar-csv');
|
||||
};
|
||||
|
||||
@@ -17,5 +17,6 @@ export interface Configuracion {
|
||||
rutaCsv: string;
|
||||
intervaloMinutos: number;
|
||||
cantidadTitularesAScrapear: number;
|
||||
//limiteTotalEnDb: number;
|
||||
scrapingActivo: boolean;
|
||||
viñetaPorDefecto: string;
|
||||
}
|
||||
Reference in New Issue
Block a user