2020-11-01 18:56:36 +03:00
|
|
|
package repositories
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/muety/wakapi/models"
|
2020-11-01 22:14:10 +03:00
|
|
|
"gorm.io/gorm"
|
2021-02-06 02:33:20 +03:00
|
|
|
"gorm.io/gorm/clause"
|
2020-11-01 18:56:36 +03:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HeartbeatRepository struct {
|
|
|
|
db *gorm.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewHeartbeatRepository(db *gorm.DB) *HeartbeatRepository {
|
|
|
|
return &HeartbeatRepository{db: db}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *HeartbeatRepository) InsertBatch(heartbeats []*models.Heartbeat) error {
|
2021-02-06 02:33:20 +03:00
|
|
|
if err := r.db.
|
|
|
|
Clauses(clause.OnConflict{
|
|
|
|
DoNothing: true,
|
|
|
|
}).
|
|
|
|
Create(&heartbeats).Error; err != nil {
|
2020-11-01 18:56:36 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-05 20:47:28 +03:00
|
|
|
func (r *HeartbeatRepository) CountByUser(user *models.User) (int64, error) {
|
|
|
|
var count int64
|
|
|
|
if err := r.db.
|
|
|
|
Model(&models.Heartbeat{}).
|
|
|
|
Where(&models.Heartbeat{UserID: user.ID}).
|
|
|
|
Count(&count).Error; err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
return count, nil
|
|
|
|
}
|
|
|
|
|
2021-02-06 02:31:30 +03:00
|
|
|
func (r *HeartbeatRepository) GetLatestByOriginAndUser(origin string, user *models.User) (*models.Heartbeat, error) {
|
|
|
|
var heartbeat models.Heartbeat
|
|
|
|
if err := r.db.
|
|
|
|
Model(&models.Heartbeat{}).
|
|
|
|
Where(&models.Heartbeat{
|
|
|
|
UserID: user.ID,
|
|
|
|
Origin: origin,
|
|
|
|
}).
|
|
|
|
Order("time desc").
|
|
|
|
First(&heartbeat).Error; err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &heartbeat, nil
|
|
|
|
}
|
|
|
|
|
2020-11-01 18:56:36 +03:00
|
|
|
func (r *HeartbeatRepository) GetAllWithin(from, to time.Time, user *models.User) ([]*models.Heartbeat, error) {
|
|
|
|
var heartbeats []*models.Heartbeat
|
|
|
|
if err := r.db.
|
|
|
|
Where(&models.Heartbeat{UserID: user.ID}).
|
|
|
|
Where("time >= ?", from).
|
|
|
|
Where("time < ?", to).
|
|
|
|
Order("time asc").
|
|
|
|
Find(&heartbeats).Error; err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return heartbeats, nil
|
|
|
|
}
|
|
|
|
|
2020-11-07 14:01:35 +03:00
|
|
|
func (r *HeartbeatRepository) GetFirstByUsers() ([]*models.TimeByUser, error) {
|
|
|
|
var result []*models.TimeByUser
|
|
|
|
r.db.Model(&models.User{}).
|
|
|
|
Select("users.id as user, min(time) as time").
|
|
|
|
Joins("left join heartbeats on users.id = heartbeats.user_id").
|
|
|
|
Group("user").
|
|
|
|
Scan(&result)
|
|
|
|
return result, nil
|
2020-11-01 18:56:36 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *HeartbeatRepository) DeleteBefore(t time.Time) error {
|
|
|
|
if err := r.db.
|
|
|
|
Where("time <= ?", t).
|
|
|
|
Delete(models.Heartbeat{}).Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|