feat: Implement BolsaLocalWidget and configure API CORS

This commit is contained in:
2025-07-01 13:26:46 -03:00
parent 5e9270eda7
commit 4cfb248f54
22 changed files with 4823 additions and 0 deletions

24
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

69
frontend/README.md Normal file
View File

@@ -0,0 +1,69 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
frontend/eslint.config.js Normal file
View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { globalIgnores } from 'eslint/config'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

4328
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

34
frontend/package.json Normal file
View File

@@ -0,0 +1,34 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.2.0",
"@mui/material": "^7.2.0",
"axios": "^1.10.0",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@eslint/js": "^9.29.0",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.5.2",
"eslint": "^9.29.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.2.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.34.1",
"vite": "^7.0.0"
}
}

1
frontend/public/vite.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

59
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,59 @@
import { Box, Container, Typography, AppBar, Toolbar, CssBaseline } from '@mui/material';
import { BolsaLocalWidget } from './components/BolsaLocalWidget';
function App() {
return (
<>
<CssBaseline />
<AppBar position="static" sx={{ backgroundColor: '#028fbe' }}>
<Toolbar>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
Mercados Modernos - Demo
</Typography>
</Toolbar>
</AppBar>
<Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
<Typography variant="h4" gutterBottom>
Datos del Mercado
</Typography>
{/* --- Sección 1: Mercado Agroganadero de Cañuelas --- */}
<Box component="section" sx={{ mb: 5 }}>
<Typography variant="h5" gutterBottom>Mercado Agroganadero de Cañuelas</Typography>
{/* Aquí irá el <MercadoAgroWidget /> */}
<Typography color="text.secondary">Widget en construcción...</Typography>
</Box>
{/* --- Sección 2: Granos - Bolsa de Comercio de Rosario --- */}
<Box component="section" sx={{ mb: 5 }}>
<Typography variant="h5" gutterBottom>Granos - Bolsa de Comercio de Rosario</Typography>
{/* Aquí irá el <GranosWidget /> */}
<Typography color="text.secondary">Widget en construcción...</Typography>
</Box>
{/* --- Sección 3: Mercado de Valores de Estados Unidos --- */}
<Box component="section" sx={{ mb: 5 }}>
<Typography variant="h5" gutterBottom>Mercado de Valores de Estados Unidos</Typography>
{/* Aquí irá el <BolsaUsaWidget /> */}
<Typography color="text.secondary">Widget en construcción...</Typography>
</Box>
{/* --- Sección 4: Mercado de Valores Local --- */}
<Box component="section" sx={{ mb: 5 }}>
<Typography variant="h5" gutterBottom>Mercado de Valores Argentina</Typography>
<BolsaLocalWidget />
</Box>
</Container>
<Box component="footer" sx={{ p: 2, mt: 'auto', backgroundColor: '#f5f5f5', textAlign: 'center' }}>
<Typography variant="body2" color="text.secondary">
Desarrollado con Arquitectura Moderna - {new Date().getFullYear()}
</Typography>
</Box>
</>
);
}
export default App;

View File

@@ -0,0 +1,14 @@
import axios from 'axios';
// Durante el desarrollo, nuestra API corre en un puerto específico (ej. 5045).
// En producción, esto debería apuntar a la URL real del servidor donde se despliegue la API.
const API_BASE_URL = 'http://localhost:5045/api';
const apiClient = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
export default apiClient;

View File

@@ -0,0 +1,94 @@
import {
Box,
CircularProgress,
Alert,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
Typography,
Tooltip
} from '@mui/material';
import type { CotizacionBolsa } from '../models/mercadoModels';
import { useApiData } from '../hooks/useApiData';
import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward';
import ArrowDownwardIcon from '@mui/icons-material/ArrowDownward';
import RemoveIcon from '@mui/icons-material/Remove'; // Para cambios neutros
// Función para formatear números
const formatNumber = (num: number) => {
return new Intl.NumberFormat('es-AR', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(num);
};
// Componente para mostrar la variación con color e icono
const Variacion = ({ value }: { value: number }) => {
const color = value > 0 ? 'success.main' : value < 0 ? 'error.main' : 'text.secondary';
const Icon = value > 0 ? ArrowUpwardIcon : value < 0 ? ArrowDownwardIcon : RemoveIcon;
return (
<Box component="span" sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color }}>
<Icon sx={{ fontSize: '1rem', mr: 0.5 }} />
<Typography variant="body2" component="span" sx={{ fontWeight: 'bold' }}>
{formatNumber(value)}%
</Typography>
</Box>
);
};
export const BolsaLocalWidget = () => {
const { data, loading, error } = useApiData<CotizacionBolsa[]>('/mercados/bolsa/local');
if (loading) {
return <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}><CircularProgress /></Box>;
}
if (error) {
return <Alert severity="error">{error}</Alert>;
}
if (!data || data.length === 0) {
return <Alert severity="info">No hay datos disponibles para el mercado local en este momento.</Alert>;
}
return (
<TableContainer component={Paper}>
<Table size="small" aria-label="tabla bolsa local">
<TableHead>
<TableRow>
<TableCell>Símbolo</TableCell>
<TableCell align="right">Precio Actual</TableCell>
<TableCell align="right">Apertura</TableCell>
<TableCell align="right">Cierre Anterior</TableCell>
<TableCell align="center">% Cambio</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map((row) => (
<TableRow key={row.ticker} hover>
<TableCell component="th" scope="row">
<Typography variant="body2" sx={{ fontWeight: 'bold' }}>{row.ticker}</Typography>
</TableCell>
<TableCell align="right">${formatNumber(row.precioActual)}</TableCell>
<TableCell align="right">${formatNumber(row.apertura)}</TableCell>
<TableCell align="right">${formatNumber(row.cierreAnterior)}</TableCell>
<TableCell align="center">
<Variacion value={row.porcentajeCambio} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<Tooltip title={`Última actualización: ${new Date(data[0].fechaRegistro).toLocaleString('es-AR')}`}>
<Typography variant="caption" sx={{ p: 1, display: 'block', textAlign: 'right', color: 'text.secondary' }}>
Fuente: Yahoo Finance
</Typography>
</Tooltip>
</TableContainer>
);
};

View File

View File

@@ -0,0 +1,34 @@
import { useState, useEffect, useCallback } from 'react';
import apiClient from '../api/apiClient';
import { AxiosError } from 'axios';
// T es el tipo de dato que esperamos de la API (ej. CotizacionBolsa[])
export function useApiData<T>(url: string) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const fetchData = useCallback(async () => {
setLoading(true);
setError(null);
try {
const response = await apiClient.get<T>(url);
setData(response.data);
} catch (err) {
if (err instanceof AxiosError) {
setError(`Error al cargar datos: ${err.message}`);
} else {
setError('Ocurrió un error inesperado.');
}
console.error(err);
} finally {
setLoading(false);
}
}, [url]);
useEffect(() => {
fetchData();
}, [fetchData]);
return { data, loading, error, refetch: fetchData };
}

9
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,9 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,37 @@
// Nombres de propiedad en minúscula (camelCase) para seguir la convención de JavaScript/JSON
// La deserialización de JSON se encargará de mapearlos automáticamente.
export interface CotizacionGanado {
id: number;
categoria: string;
especificaciones: string;
maximo: number;
minimo: number;
promedio: number;
mediano: number;
cabezas: number;
kilosTotales: number;
kilosPorCabeza: number;
importeTotal: number;
fechaRegistro: string;
}
export interface CotizacionGrano {
id: number;
nombre: string;
precio: number;
variacionPrecio: number;
fechaOperacion: string;
fechaRegistro: string;
}
export interface CotizacionBolsa {
id: number;
ticker: string;
mercado: string;
precioActual: number;
apertura: number;
cierreAnterior: number;
porcentajeCambio: number;
fechaRegistro: string;
}

1
frontend/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

7
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})

View File

@@ -7,6 +7,21 @@ using System.Reflection;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Nombre para política de CORS
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// Añadimos el servicio de CORS
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:5173")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// 1. Registramos nuestra fábrica de conexiones a la BD. // 1. Registramos nuestra fábrica de conexiones a la BD.
builder.Services.AddSingleton<IDbConnectionFactory, SqlConnectionFactory>(); builder.Services.AddSingleton<IDbConnectionFactory, SqlConnectionFactory>();
@@ -56,6 +71,8 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization(); app.UseAuthorization();
app.MapControllers(); app.MapControllers();