From c72335196074dd74db40cee907dac383bc11468d Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sun, 11 Aug 2024 11:44:43 +0200 Subject: [PATCH] vingo: add anonymous recent scans --- vingo/database/scans.go | 26 ++++++++++++++++++++++++++ vingo/handlers/public.go | 18 ++++++++++++++++++ vingo/main.go | 2 ++ 3 files changed, 46 insertions(+) create mode 100644 vingo/handlers/public.go diff --git a/vingo/database/scans.go b/vingo/database/scans.go index 36347f4..c3b1ea4 100644 --- a/vingo/database/scans.go +++ b/vingo/database/scans.go @@ -18,6 +18,11 @@ type LeaderboardItem struct { PositionChange int `json:"positionChange"` } +type AnonymousScan struct { + Id int `json:"id"` + ScanTime time.Time `json:"scan_time"` +} + func CreateScan(card_serial string) error { return gorm_db.Create(&Scan{ScanTime: time.Now(), CardSerial: card_serial}).Error } @@ -96,3 +101,24 @@ func TotalDaysPerUser(before_time time.Time) ([]LeaderboardItem, error) { return leaderboard, nil } + +func GetRecentScans() ([]AnonymousScan, error) { + scans := []AnonymousScan{} + twoWeeksAgo := time.Now().AddDate(0, 0, -14) + + subQuery := gorm_db. + Table("scans"). + Select("scans.id, scans.scan_time, users.id as user_id"). + Joins("INNER JOIN cards ON cards.serial = scans.card_serial"). + Joins("INNER JOIN users ON users.id = cards.user_id"). + Where("scans.scan_time >= ?", twoWeeksAgo) + + err := gorm_db. + Table("(?) as scans", subQuery). + Select("DISTINCT ON (user_id, DATE(scan_time)) id, scan_time"). + Order("user_id, DATE(scan_time), id"). + Scan(&scans). + Error + + return scans, err +} diff --git a/vingo/handlers/public.go b/vingo/handlers/public.go new file mode 100644 index 0000000..87bce59 --- /dev/null +++ b/vingo/handlers/public.go @@ -0,0 +1,18 @@ +package handlers + +import ( + "vingo/database" + + "github.com/gofiber/fiber/v2" +) + +func PublicRecentScans(c *fiber.Ctx) error { + scans, err := database.GetRecentScans() + + if err != nil { + logger.Println("Error get recent scans:", err) + return c.Status(500).SendString("Error getting recent scans") + } + + return c.JSON(scans) +} diff --git a/vingo/main.go b/vingo/main.go index 8a6405c..1fcc5cd 100644 --- a/vingo/main.go +++ b/vingo/main.go @@ -39,6 +39,8 @@ func main() { public.Post("/scans", handlers.ScanRegister) + public.Get("/recent_scans", handlers.PublicRecentScans) + api := public.Group("/api", handlers.IsLoggedIn) { api.Post("/logout", handlers.Logout)