Files
bussines_case_automation/server.js

80 lines
2.5 KiB
JavaScript

const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const { updateConfig } = require('./index');
// Create Express app
const app = express();
const PORT = process.env.PORT || 3001;
// Middleware
app.use(express.static(__dirname)); // Serve static files
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Route to serve the HTML form
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Route to serve the thank you page
app.get('/thank-you.html', (req, res) => {
res.sendFile(path.join(__dirname, 'thank-you.html'));
});
// API endpoint to handle form submissions
app.post('/calculate', async (req, res) => {
try {
console.log('Received form submission');
const formData = req.body;
console.log('Form data received:', JSON.stringify(formData, null, 2));
// Update config file with form data
await updateConfig(formData);
console.log('Config file updated successfully');
// Run Python script to create Excel file synchronously
const { execSync } = require('child_process');
try {
console.log('Executing Python script...');
const stdout = execSync('python3 create_excel.py', { encoding: 'utf8' });
console.log(`Python script output: ${stdout}`);
// Send success response after Python script completes
res.json({
success: true,
message: 'Form data saved and Excel file created successfully'
});
console.log('Success response sent');
} catch (execError) {
console.error(`Error executing Python script: ${execError.message}`);
if (execError.stderr) {
console.error(`stderr: ${execError.stderr}`);
}
// Send error response for Python script failure
res.status(500).json({
success: false,
message: 'Error creating Excel file',
error: execError.message
});
console.error('Error response sent for Python script failure');
}
} catch (error) {
console.error('Error processing form data:', error);
console.error('Error stack:', error.stack);
res.status(500).json({
success: false,
message: 'Error processing form data',
error: error.message
});
console.error('Error response sent');
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});