251 lines
8.2 KiB
JavaScript
251 lines
8.2 KiB
JavaScript
// index.js
|
|
const express = require('express');
|
|
const path = require('path');
|
|
const dotenv = require('dotenv');
|
|
const mysql = require('mysql2/promise');
|
|
const cors = require('cors');
|
|
|
|
const app = express();
|
|
const port = process.env.PORT || 3000;
|
|
|
|
// Cargar las variables de entorno dependiendo del entorno
|
|
const envFile = process.env.NODE_ENV === 'production' ? '.env.production' : '.env.development';
|
|
dotenv.config({ path: envFile });
|
|
|
|
// Configuración de conexión MySQL
|
|
const dbConfig = {
|
|
host: process.env.DB_HOST || 'db',
|
|
user: process.env.DB_USER,
|
|
password: process.env.DB_PASS,
|
|
database: process.env.DB_NAME,
|
|
port: process.env.DB_DOCKER_PORT || 3306
|
|
};
|
|
|
|
app.use(cors());
|
|
app.use(express.json());
|
|
|
|
|
|
// Servir archivos estáticos de la carpeta 'src'
|
|
app.use(express.static(path.join(__dirname, 'src')));
|
|
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
// --------------------------------- RENDERIZADO --------------------------------------
|
|
// --------------------------------------------------------------------------------------
|
|
|
|
// Ruta principal
|
|
app.get('/', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'src', 'index.html'));
|
|
});
|
|
|
|
// Ruta para comandas
|
|
app.get('/comandas', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'src', 'pages', 'comandas.html'));
|
|
});
|
|
// Ruta para dashboard
|
|
app.get('/lectura', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'src', 'pages', 'lectura.html'));
|
|
});
|
|
// Ruta para dashboard
|
|
app.get('/carga', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'src', 'pages', 'carga.html'));
|
|
});
|
|
|
|
// Ruta para obtener las tablas de la base de datos
|
|
app.get('/tablas', async (req, res) => {
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
const [rows] = await connection.execute(
|
|
`SHOW TABLES FROM \`${dbConfig.database}\``
|
|
);
|
|
const tablas = rows.map(row => Object.values(row)[0]);
|
|
res.json({ tablas });
|
|
|
|
} catch (error) {
|
|
console.error('Error al conectar o consultar la base de datos:', error);
|
|
res.status(500).json({ error: 'Error interno al consultar la base de datos' });
|
|
|
|
} finally {
|
|
if (connection) {
|
|
await connection.end();
|
|
}
|
|
}
|
|
});
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
// ----------------------------------- LECTURAS ---------------------------------------
|
|
// --------------------------------------------------------------------------------------
|
|
|
|
|
|
// Obtener mesas
|
|
app.get('/api/obtenerMesas', async (req, res) => {
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
const [results] = await connection.query('SELECT * FROM mesas');
|
|
res.json(results);
|
|
} catch (error) {
|
|
console.error('Error al obtener mesas:', error);
|
|
res.status(500).json({ error: 'Error al obtener mesas' });
|
|
} finally {
|
|
if (connection) await connection.end();
|
|
}
|
|
});
|
|
|
|
// Obtener productos
|
|
app.get('/api/obtenerProductos', async (req, res) => {
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
const [results] = await connection.query('SELECT * FROM productos');
|
|
res.json(results);
|
|
} catch (error) {
|
|
console.error('Error al obtener productos:', error);
|
|
res.status(500).json({ error: 'Error al obtener productos' });
|
|
} finally {
|
|
if (connection) await connection.end();
|
|
}
|
|
});
|
|
|
|
// Obtener categorías
|
|
app.get('/api/obtenerCategorias', async (req, res) => {
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
const [results] = await connection.query('SELECT * FROM categorias');
|
|
res.json(results);
|
|
} catch (error) {
|
|
console.error('Error al obtener categorías:', error);
|
|
res.status(500).json({ error: 'Error al obtener categorías' });
|
|
} finally {
|
|
if (connection) await connection.end();
|
|
}
|
|
});
|
|
|
|
// Obtener comandas
|
|
app.get('/api/obtenerComandas', async (req, res) => {
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
const [results] = await connection.execute('SELECT * FROM comandas');
|
|
res.json(results);
|
|
} catch (error) {
|
|
console.error('Error al obtener comandas:', error);
|
|
res.status(500).json({ error: 'Error al obtener comandas' });
|
|
} finally {
|
|
if (connection) await connection.end();
|
|
}
|
|
});
|
|
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
// ------------------------------------ CARGAS ----------------------------------------
|
|
// --------------------------------------------------------------------------------------
|
|
|
|
|
|
// Cargar nueva mesa
|
|
app.post('/api/cargarMesas', async (req, res) => {
|
|
const { numero } = req.body;
|
|
if (!numero) return res.status(400).json({ error: 'Falta el número de mesa' });
|
|
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
await connection.execute('INSERT INTO mesas (numero) VALUES (?)', [numero]);
|
|
res.status(201).json({ mensaje: 'Mesa cargada correctamente' });
|
|
} catch (error) {
|
|
console.error('Error al cargar mesa:', error);
|
|
res.status(500).json({ error: 'Error al cargar mesa' });
|
|
} finally {
|
|
if (connection) await connection.end();
|
|
}
|
|
});
|
|
|
|
// Cargar nuevo producto
|
|
app.post('/api/cargarProductos', async (req, res) => {
|
|
const { nombre, precio, categoria_id } = req.body;
|
|
if (!nombre || !precio || !categoria_id) {
|
|
return res.status(400).json({ error: 'Faltan datos para cargar el producto' });
|
|
}
|
|
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
await connection.execute(
|
|
'INSERT INTO productos (nombre, precio, categoria_id) VALUES (?, ?, ?)',
|
|
[nombre, precio, categoria_id]
|
|
);
|
|
res.status(201).json({ mensaje: 'Producto cargado correctamente' });
|
|
} catch (error) {
|
|
console.error('Error al cargar producto:', error);
|
|
res.status(500).json({ error: 'Error al cargar producto' });
|
|
} finally {
|
|
if (connection) await connection.end();
|
|
}
|
|
});
|
|
|
|
// Cargar nueva categoría
|
|
app.post('/api/cargarCategorias', async (req, res) => {
|
|
const { nombre } = req.body;
|
|
if (!nombre) return res.status(400).json({ error: 'Falta el nombre de la categoría' });
|
|
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
await connection.execute('INSERT INTO categorias (nombre) VALUES (?)', [nombre]);
|
|
res.status(201).json({ mensaje: 'Categoría cargada correctamente' });
|
|
} catch (error) {
|
|
console.error('Error al cargar categoría:', error);
|
|
res.status(500).json({ error: 'Error al cargar categoría' });
|
|
} finally {
|
|
if (connection) await connection.end();
|
|
}
|
|
});
|
|
|
|
// Cargar nueva comanda
|
|
app.post('/api/cargarComandas', async (req, res) => {
|
|
const { mesa_id, productos, total } = req.body;
|
|
if (!mesa_id || !productos || !Array.isArray(productos) || total == null) {
|
|
return res.status(400).json({ error: 'Datos inválidos para cargar comanda' });
|
|
}
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection(dbConfig);
|
|
await connection.execute(
|
|
'INSERT INTO comandas (mesa_id, productos, total, fecha) VALUES (?, ?, ?, NOW())',
|
|
[mesa_id, JSON.stringify(productos), total]
|
|
);
|
|
res.status(201).json({ mensaje: 'Comanda cargada correctamente' });
|
|
} catch (error) {
|
|
console.error('Error al cargar comanda:', error);
|
|
res.status(500).json({ error: 'Error al cargar comanda' });
|
|
} finally {
|
|
if (connection) await connection.end();
|
|
}
|
|
});
|
|
|
|
|
|
// --------------------------------------------------------------------------------------
|
|
// --------------------------------- VERIFICACIONES -----------------------------------
|
|
// --------------------------------------------------------------------------------------
|
|
|
|
async function verificarConexion() {
|
|
try {
|
|
const connection = await mysql.createConnection(dbConfig);
|
|
const [rows] = await connection.execute('SELECT NOW() AS hora');
|
|
console.log('Conexión con la base de datos fue exitosa.');
|
|
console.log('Fecha y hora actual de la base de datos:', rows[0].hora);
|
|
await connection.end();
|
|
} catch (error) {
|
|
console.error('Error al conectar con la base de datos al iniciar:', error.message);
|
|
}
|
|
}
|
|
|
|
// Iniciar servidor
|
|
app.listen(port, () => {
|
|
console.log(`Servidor corriendo en http://localhost:${port}`);
|
|
console.log('Estableciendo conexión...');
|
|
verificarConexion();
|
|
});
|