60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package repository
|
|
|
|
import (
|
|
"codeword/internal/models"
|
|
"context"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"time"
|
|
)
|
|
|
|
type StatsRepository struct {
|
|
mdb *mongo.Collection
|
|
}
|
|
|
|
func NewStatsRepository(deps Deps) *StatsRepository {
|
|
|
|
return &StatsRepository{mdb: deps.Mdb}
|
|
}
|
|
|
|
func (r *StatsRepository) UpdateStatistics(ctx context.Context, key, userID string) error {
|
|
update := bson.M{
|
|
"$inc": bson.M{"usageCount." + userID: 1},
|
|
"$push": bson.M{"usageHistory." + userID: time.Now()},
|
|
}
|
|
|
|
opts := options.Update().SetUpsert(true)
|
|
filter := bson.M{"_id": key}
|
|
|
|
_, err := r.mdb.UpdateOne(ctx, filter, update, opts)
|
|
return err
|
|
}
|
|
|
|
func (r *StatsRepository) GetAllStatistics(ctx context.Context) ([]models.PromoCodeStats, error) {
|
|
filter := bson.M{}
|
|
|
|
opts := options.Find()
|
|
|
|
cursor, err := r.mdb.Find(ctx, filter, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer cursor.Close(ctx)
|
|
|
|
var promoCodeStatsList []models.PromoCodeStats
|
|
for cursor.Next(ctx) {
|
|
var promoCodeStats models.PromoCodeStats
|
|
if err := cursor.Decode(&promoCodeStats); err != nil {
|
|
return nil, err
|
|
}
|
|
promoCodeStatsList = append(promoCodeStatsList, promoCodeStats)
|
|
}
|
|
|
|
if err := cursor.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return promoCodeStatsList, nil
|
|
}
|