From 40b24a3b738f3c4fa7a0594cf2882868a8736d74 Mon Sep 17 00:00:00 2001 From: Hannes Date: Wed, 17 Jul 2024 00:47:44 +0200 Subject: [PATCH] vingo: return extra stats for cards --- vingo/database/cards.go | 20 ++++++++++++++++++++ vingo/database/models.go | 34 +++++++++++++++++++++++++++++----- vingo/handlers/cards.go | 2 +- 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/vingo/database/cards.go b/vingo/database/cards.go index 8c6cdc6..15962b8 100644 --- a/vingo/database/cards.go +++ b/vingo/database/cards.go @@ -10,6 +10,26 @@ func GetCardsForUser(user_id int) ([]Card, error) { return cards, result.Error } +func GetCardsAndStatsForUser(user_id int) ([]CardAPI, error) { + rows, err := db.Query(` + SELECT cards.id, cards.created_at, serial, name, COUNT(scans.id), (select MAX(scan_time) from scans where card_serial = cards.serial) from cards LEFT JOIN scans on scans.card_serial = serial WHERE + user_id = $1 GROUP BY cards.id; + `, user_id) + + if err != nil { + return nil, err + } + + cards := []CardAPI{} + for rows.Next() { + var item CardAPI + _ = rows.Scan(&item.Id, &item.CreatedAt, &item.Serial, &item.Name, &item.AmountUsed, &item.LastUsed) + cards = append(cards, item) + } + + return cards, nil +} + func UpdateCardName(id int, name string, user_id int) error { return gorm_db.Model(&Card{}).Where("id = ? AND user_id = ?", id, user_id).Update("name", name).Error } diff --git a/vingo/database/models.go b/vingo/database/models.go index 229fb3b..ce66161 100644 --- a/vingo/database/models.go +++ b/vingo/database/models.go @@ -31,11 +31,35 @@ type Settings struct { type Card struct { BaseModel - Serial string `json:"serial" gorm:"uniqueIndex"` - Name string `json:"name"` - UserId int `json:"-"` - User User `json:"-"` - Scans []Scan `json:"-" gorm:"foreignKey:CardSerial;references:Serial"` + Serial string `gorm:"uniqueIndex"` + Name string + UserId int + User User + Scans []Scan `gorm:"foreignKey:CardSerial;references:Serial"` +} + +func Card_to_API(card Card) CardAPI { + var lastUsed time.Time = card.CreatedAt + if len(card.Scans) != 0 { + lastUsed = card.Scans[len(card.Scans)-1].ScanTime + } + + return CardAPI{ + Id: card.Id, + Serial: card.Serial, + Name: card.Name, + LastUsed: lastUsed, + AmountUsed: len(card.Scans), + } +} + +type CardAPI struct { + Id int `json:"id"` + CreatedAt time.Time `json:"createdAt"` + Serial string `json:"serial"` + Name string `json:"name"` + LastUsed time.Time `json:"lastUsed"` + AmountUsed int `json:"amountUsed"` } type Scan struct { diff --git a/vingo/handlers/cards.go b/vingo/handlers/cards.go index e6829d5..4d127f2 100644 --- a/vingo/handlers/cards.go +++ b/vingo/handlers/cards.go @@ -27,7 +27,7 @@ func StartCardRegister(c *fiber.Ctx) error { func Cards(c *fiber.Ctx) error { user := getUserFromStore(c) - cards, err := database.GetCardsForUser(user.Id) + cards, err := database.GetCardsAndStatsForUser(user.Id) if err != nil { logger.Println("", err) return c.Status(500).SendString("Error getting cards")