Passport/pkg/internal/services/check_in.go

79 lines
2.2 KiB
Go
Raw Normal View History

2024-09-01 08:38:09 +00:00
package services
import (
"errors"
"fmt"
"git.solsynth.dev/hypernet/passport/pkg/authkit/models"
"git.solsynth.dev/hypernet/passport/pkg/internal/database"
2024-09-01 08:38:09 +00:00
"gorm.io/gorm"
"math/rand"
2024-09-01 08:51:13 +00:00
"time"
2024-09-01 08:38:09 +00:00
)
2024-11-27 13:57:10 +00:00
func CheckCanCheckIn(user models.Account) error {
probe := time.Now().Format("2006-01-02")
2024-09-01 08:51:13 +00:00
2024-11-27 13:57:10 +00:00
var record models.CheckInRecord
if err := database.C.Where("account_id = ? AND created_at::date = ?", user.ID, probe).First(&record).Error; err != nil {
2024-09-01 08:38:09 +00:00
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
}
return fmt.Errorf("unable get check in record: %v", err)
2024-09-01 08:38:09 +00:00
}
return fmt.Errorf("today's check in record exists")
2024-09-01 08:38:09 +00:00
}
2024-11-27 13:57:10 +00:00
func GetTodayCheckIn(user models.Account) (models.CheckInRecord, error) {
probe := time.Now().Format("2006-01-02")
2024-11-27 13:57:10 +00:00
var record models.CheckInRecord
if err := database.C.Where("account_id = ? AND created_at::date = ?", user.ID, probe).First(&record).Error; err != nil {
return record, fmt.Errorf("unable get check in record: %v", err)
}
return record, nil
}
const CheckInResultModifiersLength = 4
2024-11-27 13:57:10 +00:00
func CheckIn(user models.Account) (models.CheckInRecord, error) {
2024-09-01 08:38:09 +00:00
tier := rand.Intn(5)
expMax := 100 * (tier + 1)
expMin := 100
2024-11-27 13:57:10 +00:00
record := models.CheckInRecord{
2024-09-01 08:38:09 +00:00
ResultTier: tier,
ResultExperience: rand.Intn(expMax-expMin) + expMin,
AccountID: user.ID,
2024-09-01 08:38:09 +00:00
}
modifiers := make([]int, CheckInResultModifiersLength)
for i := 0; i < CheckInResultModifiersLength; i++ {
modifiers[i] = rand.Intn(1025) // from 0 to 1024 as the comment said
}
record.ResultModifiers = modifiers
2024-11-27 13:57:10 +00:00
if err := CheckCanCheckIn(user); err != nil {
2024-09-01 08:38:09 +00:00
return record, fmt.Errorf("today already signed")
}
tx := database.C.Begin()
var profile models.AccountProfile
if err := database.C.Where("account_id = ?", user.ID).First(&profile).Error; err != nil {
return record, fmt.Errorf("unable get account profile: %v", err)
} else {
profile.Experience += uint64(record.ResultExperience)
if err := tx.Save(&profile).Error; err != nil {
tx.Rollback()
return record, fmt.Errorf("unable update account profile: %v", err)
}
}
if err := tx.Save(&record).Error; err != nil {
return record, fmt.Errorf("unable do check in: %v", err)
2024-09-01 08:38:09 +00:00
}
tx.Commit()
2024-09-01 08:38:09 +00:00
return record, nil
}