This commit is contained in:
2023-03-11 18:30:12 +07:00
parent 57755d28d2
commit 78aaa9b80a
4 changed files with 91 additions and 27 deletions
+53 -12
View File
@@ -5,6 +5,7 @@ import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"time"
"valera/config"
)
@@ -21,9 +22,8 @@ type chatDTO struct {
}
type ChatInfoDTO struct {
ChatID int64 `bson:"chat_id"`
Status string `bson:"status"`
Workouts []Workout `bson:"workouts"`
ChatID int64 `bson:"chat_id"`
Status string `bson:"status"`
}
func (c *ChatInfoDTO) GetStatus() UserState {
@@ -34,17 +34,22 @@ func (c *ChatInfoDTO) GetStatus() UserState {
}
type Workout struct {
Name string `bson:"name"`
Count int `bson:"count"`
ChatID int64 `bson:"chat_id"`
Name string `bson:"name"`
Count int `bson:"count"`
CreatedAt time.Time `bson:"created_at"`
Username string `bson:"username"`
}
func NewWorkout(
name string,
count int,
username string,
) *Workout {
return &Workout{
Name: name,
Count: count,
Name: name,
Count: count,
Username: username,
}
}
@@ -75,10 +80,13 @@ func AddChat(chatID int64) error {
return result.Err()
}
func AddWorkoutInUser(chatID int64, workout *Workout) error {
func AddWorkout(chatID int64, workout *Workout) error {
if err := AddChat(chatID); err != nil {
return err
}
workout.ChatID = chatID
loc, _ := time.LoadLocation("Asia/Novosibirsk")
workout.CreatedAt = time.Now().In(loc)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
@@ -88,16 +96,18 @@ func AddWorkoutInUser(chatID int64, workout *Workout) error {
return err
}
collection := client.Database(cfg.DBName).Collection(cfg.ChatsCollectionName)
_, err = collection.UpdateOne(
collection := client.Database(cfg.DBName).Collection(cfg.WorkoutsCollectionName)
_, err = collection.InsertOne(
ctx,
bson.M{"chat_id": chatID},
bson.M{"$push": bson.M{"workouts": workout}},
workout,
)
return err
}
func GetUserInfo(chatID int64) (*ChatInfoDTO, error) {
if err := AddChat(chatID); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
@@ -131,3 +141,34 @@ func SetStatusInUser(chatID int64, status UserState) error {
)
return err
}
func GetStat(chatID int64) (map[string]int, error) {
if err := AddChat(chatID); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.MongoURL))
if err != nil {
return nil, err
}
collection := client.Database(cfg.DBName).Collection(cfg.WorkoutsCollectionName)
cursor, err := collection.Find(ctx, bson.M{"chat_id": chatID})
if err != nil {
return nil, err
}
res := map[string]int{}
for cursor.Next(context.Background()) {
var result Workout
if err := cursor.Decode(&result); err != nil {
log.Fatal(err)
}
res[result.Name] += result.Count
}
if err := cursor.Err(); err != nil {
log.Fatal(err)
}
return res, err
}