-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #46 from Prodeko/analytics-timeseries
Analytics timeseries
- Loading branch information
Showing
3 changed files
with
118 additions
and
50 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import _ from "lodash"; | ||
import { prisma } from "../../config"; | ||
import { GUILDS } from "../common/constants"; | ||
import type { TimeSeriesData } from "../common/types"; | ||
|
||
export const getTimeSeriesData = async (): Promise<TimeSeriesData> => { | ||
const data = await prisma.$queryRaw` | ||
WITH "PointsByDate" AS ( | ||
SELECT | ||
DATE_TRUNC('day', "Entry"."createdAt") as "date", | ||
"guild", | ||
SUM("earnedPoints") as "totalPoints" | ||
FROM | ||
"Entry" JOIN "User" ON "Entry"."userId" = "User"."telegramUserId" | ||
GROUP BY | ||
"date", | ||
"guild" | ||
) | ||
SELECT | ||
"date", | ||
"guild", | ||
SUM("totalPoints") OVER (ORDER BY "date") as "totalPoints" | ||
FROM | ||
"PointsByDate" | ||
ORDER BY | ||
"date" ASC | ||
` as { | ||
date: Date; | ||
guild: string; | ||
totalPoints: number; | ||
}[]; | ||
|
||
return data; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,66 +1,90 @@ | ||
import express from 'express'; | ||
import { validatePeriod } from './middleware'; | ||
import { calculateGuildStatistics } from '../analytics/statistics'; | ||
import topUsersByGuild from '../analytics/rankings'; | ||
import { arrayToCSV } from '../common/utils'; | ||
import express from "express"; | ||
import { validatePeriod } from "./middleware"; | ||
import { calculateGuildStatistics } from "../analytics/statistics"; | ||
import topUsersByGuild from "../analytics/rankings"; | ||
import { arrayToCSV } from "../common/utils"; | ||
import { getTimeSeriesData } from "../analytics/timeseries"; | ||
import entry from "../commands/entry"; | ||
import { GUILDS } from "../common/constants"; | ||
|
||
const router = express.Router({mergeParams: true}); | ||
const router = express.Router({ mergeParams: true }); | ||
|
||
export interface StatisticsResponse extends express.Response { | ||
locals: { | ||
guild: string; | ||
periodStart: Date; | ||
periodEnd: Date; | ||
}; | ||
locals: { | ||
guild: string; | ||
periodStart: Date; | ||
periodEnd: Date; | ||
}; | ||
} | ||
|
||
router.get('/ranking/:guild', async (req, res: StatisticsResponse) => { | ||
if (req.query.pass !== process.env.ADMIN_PASSWORD) { | ||
console.log("Wrong password"); | ||
return res.status(401).send("Wrong password!"); | ||
} | ||
|
||
const guild = req.params.guild; | ||
if (!req.query.limit || ! ((typeof req.query.limit) === 'string')) { | ||
return res.status(400).send('Limit query parameter is required as a string'); | ||
} | ||
const limit = Number.parseInt(req.query.limit as string ?? '10'); | ||
try { | ||
const topUsers = await topUsersByGuild(guild, limit) as Record<string, unknown>[]; | ||
const csv = arrayToCSV([ | ||
"userId", | ||
"telegramUsername", | ||
"firstName", | ||
"lastName", | ||
"totalPoints", | ||
"totalEntries" | ||
], topUsers); | ||
res.header("Content-Type", "text/csv"); | ||
res.status(200).send(csv); | ||
} catch (error) { | ||
console.error(error); | ||
res.status(500).send('An error occurred while calculating rankings'); | ||
} | ||
router.get("/ranking/:guild", async (req, res: StatisticsResponse) => { | ||
if (req.query.pass !== process.env.ADMIN_PASSWORD) { | ||
console.log("Wrong password"); | ||
return res.status(401).send("Wrong password!"); | ||
} | ||
|
||
const guild = req.params.guild; | ||
if (!req.query.limit || !(typeof req.query.limit === "string")) { | ||
return res | ||
.status(400) | ||
.send("Limit query parameter is required as a string"); | ||
} | ||
const limit = Number.parseInt((req.query.limit as string) ?? "10"); | ||
try { | ||
const topUsers = (await topUsersByGuild(guild, limit)) as Record< | ||
string, | ||
unknown | ||
>[]; | ||
const csv = arrayToCSV( | ||
[ | ||
"userId", | ||
"telegramUsername", | ||
"firstName", | ||
"lastName", | ||
"totalPoints", | ||
"totalEntries", | ||
], | ||
topUsers, | ||
); | ||
res.header("Content-Type", "text/csv"); | ||
res.status(200).send(csv); | ||
} catch (error) { | ||
console.error(error); | ||
res.status(500).send("An error occurred while calculating rankings"); | ||
} | ||
}); | ||
|
||
router.get("/time-series", async (req, res) => { | ||
if (req.query.pass !== process.env.ADMIN_PASSWORD) { | ||
console.log("Wrong password"); | ||
return res.status(401).send("Wrong password!"); | ||
} | ||
|
||
const timeSeries = await getTimeSeriesData(); | ||
|
||
const csv = arrayToCSV(["date", "guild", "totalPoints"], timeSeries); | ||
|
||
res.header("Content-Type", "text/csv"); | ||
res.status(200).send(csv); | ||
}); | ||
|
||
// Middleware to validate the period start and end query parameters | ||
router.use(validatePeriod); | ||
|
||
router.get('/statistics', async (req, res: StatisticsResponse) => { | ||
if (req.query.pass !== process.env.ADMIN_PASSWORD) { | ||
router.get("/statistics", async (req, res: StatisticsResponse) => { | ||
if (req.query.pass !== process.env.ADMIN_PASSWORD) { | ||
console.log("Wrong password"); | ||
return res.status(401).send("Wrong password!"); | ||
} | ||
|
||
const { periodStart, periodEnd } = res.locals; | ||
try { | ||
const statistics = await calculateGuildStatistics(periodStart, periodEnd); | ||
res.json(Object.fromEntries(statistics)); | ||
} catch (error) { | ||
console.error(error); | ||
res.status(500).send('An error occurred while calculating statistics'); | ||
} | ||
}); | ||
|
||
const { periodStart, periodEnd } = res.locals; | ||
try { | ||
const statistics = await calculateGuildStatistics(periodStart, periodEnd); | ||
res.json(Object.fromEntries(statistics)); | ||
} catch (error) { | ||
console.error(error); | ||
res.status(500).send("An error occurred while calculating statistics"); | ||
} | ||
}); | ||
|
||
export default router; |