Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vingo: add anonymous recent scans #42

Merged
merged 2 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions vingo/database/scans.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
18 changes: 18 additions & 0 deletions vingo/handlers/public.go
Original file line number Diff line number Diff line change
@@ -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(fiber.Map{"scans": scans})
}
2 changes: 2 additions & 0 deletions vingo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down