Add ui for csv update and import (broken) + fix build issues

This commit is contained in:
2025-01-10 00:56:14 -05:00
parent 8bdd188dfe
commit dbdf77331c
17 changed files with 406 additions and 67 deletions

View File

@@ -6,8 +6,8 @@ const dotenv = require('dotenv');
// For testing purposes, limit the number of rows to import (0 = no limit)
const PRODUCTS_TEST_LIMIT = 0;
const ORDERS_TEST_LIMIT = 5000;
const PURCHASE_ORDERS_TEST_LIMIT = 0;
const ORDERS_TEST_LIMIT = 10000;
const PURCHASE_ORDERS_TEST_LIMIT = 10000;
dotenv.config({ path: path.join(__dirname, '../.env') });

View File

@@ -4,18 +4,37 @@ const mysql = require('mysql2/promise');
const productsRouter = require('./routes/products');
const dashboardRouter = require('./routes/dashboard');
const ordersRouter = require('./routes/orders');
const csvRoutes = require('./routes/csv');
const app = express();
app.use(cors());
// Debug middleware to log all requests
app.use((req, res, next) => {
console.log(`[App Debug] ${new Date().toISOString()} - ${req.method} ${req.path}`);
next();
});
// Configure CORS with specific options
app.use(cors({
origin: [
'http://localhost:5173', // Local development
'https://inventory.kent.pw', // Production frontend
/\.kent\.pw$/ // Any subdomain of kent.pw
],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
optionsSuccessStatus: 200
}));
app.use(express.json());
// Database connection
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'inventory',
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || 'inventory',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
@@ -24,12 +43,73 @@ const pool = mysql.createPool({
// Make db pool available in routes
app.locals.pool = pool;
// Routes
// Debug endpoint to list all registered routes
app.get('/api/debug/routes', (req, res) => {
console.log('Debug routes endpoint hit');
const routes = [];
app._router.stack.forEach(middleware => {
if (middleware.route) {
routes.push({
path: middleware.route.path,
methods: Object.keys(middleware.route.methods)
});
} else if (middleware.name === 'router') {
middleware.handle.stack.forEach(handler => {
if (handler.route) {
const fullPath = (middleware.regexp.source === '^\\/?(?=\\/|$)' ? '' : middleware.regexp.source.replace(/\\\//g, '/').replace(/\^|\$/g, '')) + handler.route.path;
routes.push({
path: fullPath,
methods: Object.keys(handler.route.methods)
});
}
});
}
});
res.json(routes);
});
// Test endpoint to verify server is running
app.get('/api/health', (req, res) => {
res.json({ status: 'ok' });
});
// Mount all routes under /api
console.log('Mounting routes...');
console.log('Mounting products routes...');
app.use('/api/products', productsRouter);
console.log('Mounting dashboard routes...');
app.use('/api/dashboard', dashboardRouter);
console.log('Mounting orders routes...');
app.use('/api/orders', ordersRouter);
const PORT = process.env.PORT || 3001;
console.log('Mounting CSV routes...');
app.use('/api/csv', csvRoutes);
console.log('CSV routes mounted');
console.log('All routes mounted');
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({ error: err.message });
});
// 404 handler
app.use((req, res) => {
console.log('404 Not Found:', req.method, req.path);
res.status(404).json({ error: 'Not Found' });
});
const PORT = process.env.PORT || 3010;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log('Available routes:');
console.log('- GET /api/health');
console.log('- GET /api/debug/routes');
console.log('- GET /api/csv/status');
console.log('- GET /api/csv/test');
console.log('- POST /api/csv/update');
});

View File

@@ -0,0 +1,96 @@
const express = require('express');
const router = express.Router();
const { spawn } = require('child_process');
const path = require('path');
// Debug middleware MUST be first
router.use((req, res, next) => {
console.log(`[CSV Route Debug] ${req.method} ${req.path}`);
next();
});
// Store active import process and its progress
let activeImport = null;
let importProgress = null;
// SSE clients for progress updates
const clients = new Set();
// Helper to send progress to all connected clients
function sendProgressToClients(progress) {
clients.forEach(client => {
client.write(`data: ${JSON.stringify(progress)}\n\n`);
});
}
// Debug endpoint to verify route registration
router.get('/test', (req, res) => {
console.log('CSV test endpoint hit');
res.json({ message: 'CSV routes are working' });
});
// Route to check import status
router.get('/status', (req, res) => {
console.log('CSV status endpoint hit');
res.json({
active: !!activeImport,
progress: importProgress
});
});
// Route to update CSV files
router.post('/update', async (req, res) => {
console.log('CSV update endpoint hit');
if (activeImport) {
console.log('Import already in progress');
return res.status(409).json({ error: 'Import already in progress' });
}
try {
const scriptPath = path.join(__dirname, '..', '..', 'scripts', 'update-csv.js');
console.log('Running script:', scriptPath);
if (!require('fs').existsSync(scriptPath)) {
console.error('Script not found:', scriptPath);
return res.status(500).json({ error: 'Update script not found' });
}
activeImport = spawn('node', [scriptPath]);
activeImport.stdout.on('data', (data) => {
console.log(`CSV Update: ${data}`);
importProgress = data.toString();
sendProgressToClients({ status: 'running', progress: importProgress });
});
activeImport.stderr.on('data', (data) => {
console.error(`CSV Update Error: ${data}`);
sendProgressToClients({ status: 'error', error: data.toString() });
});
await new Promise((resolve, reject) => {
activeImport.on('close', (code) => {
console.log(`CSV update process exited with code ${code}`);
if (code === 0) {
sendProgressToClients({ status: 'complete' });
resolve();
} else {
sendProgressToClients({ status: 'error', error: `Process exited with code ${code}` });
reject(new Error(`Update process exited with code ${code}`));
}
activeImport = null;
importProgress = null;
});
});
res.json({ success: true });
} catch (error) {
console.error('Error updating CSV files:', error);
activeImport = null;
importProgress = null;
res.status(500).json({ error: 'Failed to update CSV files', details: error.message });
}
});
module.exports = router;