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)