sql bug fix?

This should fix the sql server issue with the server
This commit is contained in:
JoshBaneyCS 2025-04-30 03:43:04 +00:00
parent 66d95fb9c8
commit f34be42792

View File

@ -14,10 +14,12 @@ const PORT = process.env.PORT || 3000;
const shiftCounters = {}; const shiftCounters = {};
// ─── Helpers ────────────────────────────────────────────────────────────────── // ─── Helpers ──────────────────────────────────────────────────────────────────
// Pad to 2 digits // pad to two digits
function pad2(n) { return n.toString().padStart(2, '0'); } function pad2(n) {
return n.toString().padStart(2, '0');
}
// Format epoch_ms → "M/D/YY @HH:mm" in America/New_York for Slack/SSE // Format epoch_ms → "M/D/YY @HH:mm" (24-hour) in America/New_York
function formatForSlack(epoch) { function formatForSlack(epoch) {
return new Date(epoch).toLocaleString('en-US', { return new Date(epoch).toLocaleString('en-US', {
timeZone: 'America/New_York', timeZone: 'America/New_York',
@ -30,7 +32,7 @@ function formatForSlack(epoch) {
}).replace(',', ' @'); }).replace(',', ' @');
} }
// NOAA heatindex formula // NOAA heat-index formula
function computeHeatIndex(T, R) { function computeHeatIndex(T, R) {
const [c1,c2,c3,c4,c5,c6,c7,c8,c9] = [ const [c1,c2,c3,c4,c5,c6,c7,c8,c9] = [
-42.379,2.04901523,10.14333127,-0.22475541, -42.379,2.04901523,10.14333127,-0.22475541,
@ -42,9 +44,9 @@ function computeHeatIndex(T, R) {
return Math.round(HI * 100) / 100; return Math.round(HI * 100) / 100;
} }
// Determine shift (Day/Night) and period key from epoch_ms // Determine Day/Night shift & period key from epoch_ms
function getShiftInfo(epoch) { function getShiftInfo(epoch) {
// Convert epoch to EST Date by string-roundtrip // Convert to EST by string-round-trip
const estString = new Date(epoch) const estString = new Date(epoch)
.toLocaleString('en-US', { timeZone: 'America/New_York' }); .toLocaleString('en-US', { timeZone: 'America/New_York' });
const est = new Date(estString); const est = new Date(estString);
@ -67,16 +69,14 @@ function getShiftInfo(epoch) {
return { shift, key, estNow: est }; return { shift, key, estNow: est };
} }
// Fetch current weather forecast for Baltimore // Fetch current Baltimore weather
async function fetchCurrentWeather() { async function fetchCurrentWeather() {
const key = process.env.WEATHER_API_KEY; const key = process.env.WEATHER_API_KEY, zip = process.env.ZIP_CODE;
const zip = process.env.ZIP_CODE;
if (!key || !zip) return 'Unavailable'; if (!key || !zip) return 'Unavailable';
try { try {
const { data } = await axios.get( const { data } = await axios.get(
'https://api.openweathermap.org/data/2.5/weather', { 'https://api.openweathermap.org/data/2.5/weather',
params: { zip: `${zip},us`, appid: key, units: 'imperial' } { params: { zip:`${zip},us`, appid:key, units:'imperial' } }
}
); );
const desc = data.weather[0].description.replace(/^\w/,c=>c.toUpperCase()); const desc = data.weather[0].description.replace(/^\w/,c=>c.toUpperCase());
const hi = Math.round(data.main.temp_max); const hi = Math.round(data.main.temp_max);
@ -102,7 +102,7 @@ const pool = mysql.createPool({
}); });
(async () => { (async () => {
// Create readings table with only epoch_ms (no timestamp column) // Create table with epoch_ms only
await pool.execute(` await pool.execute(`
CREATE TABLE IF NOT EXISTS readings ( CREATE TABLE IF NOT EXISTS readings (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
@ -139,7 +139,7 @@ function broadcast(event, data) {
clients.forEach(c=>c.write(msg)); clients.forEach(c=>c.write(msg));
} }
// ─── Dual Dock-Door Readings Endpoint ───────────────────────────────────────── // ─── Dual Dock-Door Endpoint ───────────────────────────────────────────────────
app.post('/api/readings', async (req,res) => { app.post('/api/readings', async (req,res) => {
try { try {
const { inbound={}, outbound={} } = req.body; const { inbound={}, outbound={} } = req.body;
@ -157,13 +157,13 @@ app.post('/api/readings', async (req, res) => {
const period = shiftCounters[key]; const period = shiftCounters[key];
const slackTs = formatForSlack(epoch); const slackTs = formatForSlack(epoch);
// Insert inbound/outbound into epoch_ms // Insert inbound + outbound
const insertSQL = ` const sql = `
INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex) INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?) VALUES(?,?,?,?,?,?)
`; `;
await pool.execute(insertSQL, ['Inbound', String(inD), epoch, inT, inH, hiIn]); await pool.execute(sql, ['Inbound', String(inD), epoch, inT, inH, hiIn]);
await pool.execute(insertSQL, ['Outbound', String(outD), epoch, outT, outH, hiOut]); await pool.execute(sql, ['Outbound', String(outD), epoch, outT, outH, hiOut]);
// SSE broadcast // SSE broadcast
broadcast('new-reading', { broadcast('new-reading', {
@ -183,7 +183,7 @@ app.post('/api/readings', async (req, res) => {
heatIndex: hiOut heatIndex: hiOut
}); });
// Upload CSV of todays readings // CSV upload
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate()); const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey=`${y}${m}${d}`; const dateKey=`${y}${m}${d}`;
const [rows] = await pool.execute(` const [rows] = await pool.execute(`
@ -195,7 +195,7 @@ app.post('/api/readings', async (req, res) => {
try { csvUrl = await uploadTrendsCsv(dateKey, rows); } try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
catch(e){ console.error('CSV upload error:', e); } catch(e){ console.error('CSV upload error:', e); }
// Slack notification // Slack message
const weather = await fetchCurrentWeather(); const weather = await fetchCurrentWeather();
const text = const text =
`*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\n`+ `*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\n`+
@ -209,11 +209,9 @@ app.post('/api/readings', async (req, res) => {
`*_Humidity:_* ${outH} % 💦\n`+ `*_Humidity:_* ${outH} % 💦\n`+
`*_Heat Index:_* ${hiOut} °F 🥵`; `*_Heat Index:_* ${hiOut} °F 🥵`;
await axios.post( await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, {
process.env.SLACK_WEBHOOK_URL, headers:{ 'Content-Type':'application/json' }
{ text }, });
{ headers: { 'Content-Type': 'application/json' } }
);
res.json({ success:true, shift, period, csvUrl }); res.json({ success:true, shift, period, csvUrl });
} catch (err) { } catch (err) {
@ -222,7 +220,7 @@ app.post('/api/readings', async (req, res) => {
} }
}); });
// ─── Area/Mod Station Readings Endpoint ─────────────────────────────────────── // ─── Area/Mod Endpoint ───────────────────────────────────────────────────────
app.post('/api/area-readings', async (req,res) => { app.post('/api/area-readings', async (req,res) => {
try { try {
const { area, stationCode, temperature:T, humidity:H } = req.body; const { area, stationCode, temperature:T, humidity:H } = req.body;
@ -269,11 +267,9 @@ app.post('/api/area-readings', async (req, res) => {
`*_Humidity:_* ${H} % 💦\n`+ `*_Humidity:_* ${H} % 💦\n`+
`*_Heat Index:_* ${hi} °F 🥵`; `*_Heat Index:_* ${hi} °F 🥵`;
await axios.post( await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, {
process.env.SLACK_WEBHOOK_URL, headers:{ 'Content-Type':'application/json' }
{ text }, });
{ headers: { 'Content-Type': 'application/json' } }
);
res.json({ success:true, csvUrl }); res.json({ success:true, csvUrl });
} catch (err) { } catch (err) {
@ -282,7 +278,7 @@ app.post('/api/area-readings', async (req, res) => {
} }
}); });
// ─── Fetch All & Export ─────────────────────────────────────────────────────── // ─── Fetch & Export ─────────────────────────────────────────────────────────
app.get('/api/readings', async (req,res) => { app.get('/api/readings', async (req,res) => {
try { try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`); const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
@ -299,7 +295,10 @@ app.get('/api/export', async (req, res) => {
res.set('Content-Type','text/csv'); res.set('Content-Type','text/csv');
res.write('id,location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex\n'); res.write('id,location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex\n');
rows.forEach(r => { rows.forEach(r => {
res.write(`${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},${r.temperature},${r.humidity},${r.heatIndex}\n`); res.write(
`${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},` +
`${r.temperature},${r.humidity},${r.heatIndex}\n`
);
}); });
res.end(); res.end();
} catch (err) { } catch (err) {
@ -312,4 +311,3 @@ app.get('/api/export', async (req, res) => {
app.listen(PORT, () => { app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`); console.log(`Server running on http://localhost:${PORT}`);
}); });