package services import ( "context" "encoding/json" "fmt" "relynolli-server/internal" "relynolli-server/models" ) func GetCartItems(fuserId int) []models.CatalogWithQuantityWeb { rdb := internal.InitRedis() keys, _ := rdb.Keys(context.Background(), fmt.Sprintf("api.api_cart.%d.*", fuserId)).Result() result := []models.CatalogWithQuantityWeb{} for _, key := range keys { str, _ := rdb.Get(context.Background(), key).Result() item := models.CatalogWithQuantityWeb{} json.Unmarshal([]byte(str), &item) result = append(result, item) } return result } func CreateFuser() int64 { stmt := "insert into b_sale_fuser (DATE_INSERT, DATE_UPDATE, CODE) values (now(), now(), md5(rand()));" db := internal.InitDatabase() result := db.Execute(stmt) lastInsertId, _ := result.LastInsertId() return lastInsertId } func AddItemToCart(fuserId int, productId int) { rdb := internal.InitRedis() item, _ := GetCatalogItemById(productId) itemWithQuantity := models.CatalogWithQuantityWeb{ Id: item.Id, Code: item.Code, Name: item.Name, IsActive: item.IsActive, Properties: item.Properties, DetailText: item.DetailText, Price: item.Price, Quantity: 1, AvailableQuantity: item.AvailableQuantity, } marshaled, _ := json.Marshal(itemWithQuantity) err := rdb.Set(context.Background(), fmt.Sprintf("api.api_cart.%d.%d", fuserId, productId), string(marshaled), 0).Err() if err != nil { panic(err.Error()) } } func UpdateCartItem(fuserId int, productId int, quantity int) error { if quantity <= 0 { DeleteCartItem(fuserId, productId) return nil } item, _ := GetCatalogItemById(productId) if item.AvailableQuantity < quantity { return fmt.Errorf("Available quantity is less than requested. Available %d, requested %d", item.AvailableQuantity, quantity) } itemWithQuantity := models.CatalogWithQuantityWeb{ Id: item.Id, Code: item.Code, Name: item.Name, IsActive: item.IsActive, Properties: item.Properties, DetailText: item.DetailText, Price: item.Price, Quantity: quantity, AvailableQuantity: item.AvailableQuantity, } marshaled, _ := json.Marshal(itemWithQuantity) rdb := internal.InitRedis() rdb.Set(context.Background(), fmt.Sprintf("api.api_cart.%d.%d", fuserId, productId), string(marshaled), 0) return nil //var availableQunatity int //stmtQuantity := fmt.Sprintf("select QUANTITY as q from b_catalog_product where ID = %d;", productId) //updateStmt := fmt.Sprintf("update api_cart set quantity = %d where product_id = %d and fuser_id = %d", quantity, productId, fuserId) //db := internal.InitDatabase() //rows := db.Query(stmtQuantity) //rows.Next() //rows.Scan(&availableQunatity) //if quantity > availableQunatity { // return fmt.Errorf("Available quantity is less than requested. Available %d, requested %d", availableQunatity, quantity) //} //db.Execute(updateStmt) //return nil } func DeleteCartItem(fuserId int, productId int) { rdb := internal.InitRedis() rdb.Del(context.Background(), fmt.Sprintf("api.api_cart.%d.%d", fuserId, productId)).Err() }