diff --git a/prisma/migrations/20250925171652_add_chutil_channel_id/migration.sql b/prisma/migrations/20250925171652_add_chutil_channel_id/migration.sql new file mode 100644 index 0000000..771f018 --- /dev/null +++ b/prisma/migrations/20250925171652_add_chutil_channel_id/migration.sql @@ -0,0 +1,5 @@ +-- AlterTable +ALTER TABLE `channel_utilization_stats` ADD COLUMN `channel_id` VARCHAR(191) NULL; + +-- CreateIndex +CREATE INDEX `channel_utilization_stats_channel_id_idx` ON `channel_utilization_stats`(`channel_id`); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index db6aab7..723e4e4 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -341,7 +341,9 @@ model ChannelUtilizationStats { id BigInt @id @default(autoincrement()) recorded_at DateTime? @default(now()) avg_channel_utilization Decimal? + channel_id String? + @@index([channel_id]) @@index([recorded_at]) @@map("channel_utilization_stats") } \ No newline at end of file diff --git a/src/stats.js b/src/stats.js index 5129c96..ba39ed9 100644 --- a/src/stats.js +++ b/src/stats.js @@ -185,21 +185,48 @@ router.get('/battery-stats', async (req, res) => { }); router.get('/channel-utilization-stats', async (req, res) => { - const days = parseInt(req.query.days || '1', 10); - + const days = parseInt(req.query.days || '1', 10); + const channelId = req.query.channel_id; // optional string + try { - const stats = await prisma.$queryRaw` - SELECT recorded_at, avg_channel_utilization - FROM channel_utilization_stats - WHERE recorded_at >= NOW() - INTERVAL ${days} DAY - ORDER BY recorded_at DESC; - `; - - res.json(stats); + const stats = await prisma.$queryRaw( + Prisma.sql` + SELECT recorded_at, channel_id, avg_channel_utilization + FROM channel_utilization_stats + WHERE recorded_at >= NOW() - INTERVAL ${days} DAY + ${channelId ? Prisma.sql`AND channel_id = ${channelId}` : Prisma.sql``} + ORDER BY recorded_at DESC; + ` + ); + + res.json(stats); } catch (err) { - console.error('Error fetching channel utilization stats:', err); - res.status(500).json({ error: 'Internal server error' }); + console.error('Error fetching channel utilization stats:', err); + res.status(500).json({ error: 'Internal server error' }); } -}); + }); + + router.get('/channel-utilization', async (req, res) => { + const channelId = req.query.channel_id; + + try { + const snapshot = await prisma.$queryRaw( + Prisma.sql` + SELECT recorded_at, channel_id, avg_channel_utilization + FROM channel_utilization_stats + WHERE recorded_at = ( + SELECT MAX(recorded_at) FROM channel_utilization_stats + ) + ${channelId ? Prisma.sql`AND channel_id = ${channelId}` : Prisma.sql``} + ORDER BY channel_id; + ` + ); + + res.json(snapshot); + } catch (err) { + console.error('Error fetching latest channel utilization:', err); + res.status(500).json({ error: 'Internal server error' }); + } + }); module.exports = router; \ No newline at end of file