bwsamern-ohne_standortplaner/server.js

124 lines
4.3 KiB
JavaScript

require('dotenv').config();
const express = require('express');
const { Pool } = require('pg');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(bodyParser.json());
// Serve static files from the root directory
app.use(express.static(path.join(__dirname, './')));
const pool = new Pool({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
});
// In-memory logs for remote debugging
const serverLogs = [];
function log(msg) {
const entry = `[${new Date().toISOString()}] ${msg}`;
console.log(entry);
serverLogs.push(entry);
if (serverLogs.length > 50) serverLogs.shift();
}
// Status-Endpunkt für Diagnose
app.get('/api/status', async (req, res) => {
try {
const result = await pool.query('SELECT NOW()');
res.json({
status: 'online',
database: 'connected',
time: result.rows[0].now,
schema: process.env.DB_SCHEMA || 'geodaten'
});
} catch (err) {
res.status(500).json({ status: 'error', database: 'disconnected', error: err.message });
}
});
app.get('/api/logs', (req, res) => {
res.type('text/plain').send(serverLogs.join('\n'));
});
// API to save turbines
app.post('/api/wea', async (req, res) => {
const { projekt_id, turbines } = req.body;
const targetProject = projekt_id || 'BWSamern-Ohne';
const schema = process.env.DB_SCHEMA || 'geodaten';
log(`Empfange Save-Request für Projekt: ${targetProject} (${turbines?.length || 0} WEAs)`);
const client = await pool.connect();
try {
await client.query('BEGIN');
// 1. Bestehende WEAs für dieses Projekt löschen
const delRes = await client.query(
`DELETE FROM ${schema}.wea_standorte WHERE projekt_id = $1`,
[targetProject]
);
log(`Gelöscht: ${delRes.rowCount} bestehende Anlagen.`);
// 2. Neue WEAs einfügen
if (turbines && turbines.length > 0) {
for (const t of turbines) {
log(`Füge WEA ein: Nr=${t.nr}, Typ=${t.type}, Pos=${t.latlng?.lat},${t.latlng?.lng}`);
await client.query(
`INSERT INTO ${schema}.wea_standorte
(projekt_id, wea_nummer, anlagentyp, nabenhoehe, rotordurchmesser, ksf_drehung, variante, geom)
VALUES ($1, $2, $3, $4, $5, $6, $7, ST_Transform(ST_SetSRID(ST_MakePoint($8, $9), 4326), 25832))`,
[targetProject, t.nr, t.type, t.hh, t.rd, t.ksfAngle, t.variant, t.latlng.lng, t.latlng.lat]
);
}
}
await client.query('COMMIT');
log(`Erfolgreich gespeichert: ${turbines?.length || 0} WEAs.`);
res.json({ message: `${turbines?.length || 0} WEAs erfolgreich in Datenbank gespeichert.` });
} catch (err) {
await client.query('ROLLBACK');
log(`FEHLER beim Speichern: ${err.message}`);
res.status(500).json({ error: 'Datenbankfehler beim Speichern', details: err.message });
} finally {
client.release();
}
});
// API to load turbines
app.get('/api/wea/:projekt_id', async (req, res) => {
const { projekt_id } = req.params;
log(`Lade WEAs für Projekt: ${projekt_id}`);
try {
const result = await pool.query(
`SELECT wea_nummer as nr, anlagentyp as type, nabenhoehe as hh, rotordurchmesser as rd, ksf_drehung as ksfAngle, variante as variant,
ST_X(ST_Transform(geom, 4326)) as lng, ST_Y(ST_Transform(geom, 4326)) as lat
FROM geodaten.wea_standorte WHERE projekt_id = $1`,
[projekt_id]
);
log(`Geladen: ${result.rowCount} Anlagen.`);
res.status(200).json(result.rows);
} catch (e) {
log(`FEHLER beim Laden: ${e.message}`);
res.status(500).json({ error: e.message });
}
});
// Catch-all route to serve index.html for any other request (optional, good for SPAs)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(port, '0.0.0.0', () => {
console.log(`Server running at http://0.0.0.0:${port}`);
});