Skip to content

Commit

Permalink
添加购物车功能
Browse files Browse the repository at this point in the history
  • Loading branch information
onenewcode committed Mar 20, 2024
1 parent 111dbba commit 6cb68a7
Show file tree
Hide file tree
Showing 12 changed files with 187 additions and 18 deletions.
1 change: 1 addition & 0 deletions internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ var UserDao userI = &userDao{}
var DishFDao dishFI = &dishFDao{}
var MealDishDao meal_dishI = &mealDishDao{}
var MealDao mealI = &mealDao{}
var ShopCartDao shoppingcartI = &shoppingcartDao{}

func InitDB() {
// 创建一个新的logger实例,设置为verbose模式以输出详细日志,包括SQL语句
Expand Down
5 changes: 3 additions & 2 deletions internal/db/dish_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package db

import (
"github.com/cloudwego/hertz/pkg/common/hlog"
"reggie/internal/models/constant/status_c"
"reggie/internal/models/dto"
"reggie/internal/models/model"
)
Expand Down Expand Up @@ -71,9 +72,9 @@ func (*dishDao) List(d *model.Dish) (*[]model.Dish, error) {
origin_sql = origin_sql.Where("name LIKE ?", "%"+d.Name+"%")
}
if d.CategoryID != 0 {
origin_sql = origin_sql.Where("categoryId=?", d.CategoryID)
origin_sql = origin_sql.Where("category_id=?", d.CategoryID)
}
if d.Status != 3 {
if d.Status != status_c.ALL {
origin_sql = origin_sql.Where("status =?", d.Status)
}
if err := origin_sql.Order("create_time desc").Find(&dish).Error; err != nil {
Expand Down
50 changes: 50 additions & 0 deletions internal/db/shoppingcart_dao.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package db

import (
"reggie/internal/models/model"
)

type shoppingcartI interface {
List(shoppingCart *model.ShoppingCart) *[]model.ShoppingCart
UpdateNumberById(shoppingCart *model.ShoppingCart) error
Insert(shoppingCart *model.ShoppingCart) *model.ShoppingCart
DeleteByUserId(userId int64)
}
type shoppingcartDao struct {
}

func (*shoppingcartDao) Insert(shoppingCart *model.ShoppingCart) *model.ShoppingCart {
DBEngine.Select("*").Create(shoppingCart)
return shoppingCart
}
func (*shoppingcartDao) List(shoppingCart *model.ShoppingCart) *[]model.ShoppingCart {
var (
shop []model.ShoppingCart
//count int64
)
origin_sql := DBEngine
// 判断是否含有name,有name不为nil,就进行模糊查询。
if shoppingCart.UserID != 0 {
origin_sql = origin_sql.Where("userId= ?", shoppingCart.UserID)
}
if shoppingCart.SetmealID != 0 {
origin_sql = origin_sql.Where("setmealId =?", shoppingCart.SetmealID)
}
if shoppingCart.DishID != 0 {
origin_sql = origin_sql.Where("dishId=?", shoppingCart.DishID)
}
if shoppingCart.DishFlavor != "" {
origin_sql = origin_sql.Where("dishFlavor =?", shoppingCart.DishFlavor)
}
//origin_sql.Model(&model.Category{}).Count(&count)
origin_sql.Find(&shop)
return &shop
}

func (*shoppingcartDao) UpdateNumberById(shoppingCart *model.ShoppingCart) error {
DBEngine.Updates(shoppingCart)
return nil
}
func (*shoppingcartDao) DeleteByUserId(userId int64) {
DBEngine.Where("user_id=?", userId).Delete(&model.ShoppingCart{})
}
17 changes: 17 additions & 0 deletions internal/models/dto/shoppingcartdto.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package dto

import "reggie/internal/models/model"

type ShoppingCartDTO struct {
DishId int64 `json:"dishId,omitempty"`
SetmealId int64 `json:"setmealId,omitempty"`
DishFlavor string `json:"dishFlavor,omitempty"`
}

func (s *ShoppingCartDTO) ToShoppingCart() model.ShoppingCart {
var sh model.ShoppingCart
sh.DishID = s.DishId
sh.SetmealID = s.SetmealId
sh.DishFlavor = s.DishFlavor
return sh
}
3 changes: 1 addition & 2 deletions internal/models/vo/dishvo.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ func (dv *DishVO) ForDishAndFlavor(d *model.Dish, f *[]model.DishFlavor) {
}
func Dish2DishVO(d *model.Dish) *DishVO {
var dv DishVO
d.ID, d.Name, d.CategoryID, d.Price, d.Image, d.Description, d.Status, d.UpdateTime =
dv.Id, dv.Name, dv.CategoryId, dv.Price, dv.Image, dv.Description, dv.Status, dv.UpdateTime
dv.Id, dv.Name, dv.CategoryId, dv.Price, dv.Image, dv.Description, dv.Status, dv.UpdateTime = d.ID, d.Name, d.CategoryID, d.Price, d.Image, d.Description, d.Status, d.UpdateTime
return &dv
}

Expand Down
2 changes: 2 additions & 0 deletions internal/router/admin/dish_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"reggie/internal/models/dto"
"reggie/internal/models/model"
"reggie/internal/router/service"
"reggie/pkg/redis"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -70,6 +71,7 @@ func UpdateDish(ctx context.Context, c *app.RequestContext) {

func StartOrStopDish(ctx context.Context, c *app.RequestContext) {
status, id := c.Param("status"), c.Query("id")
redis.RC.ClearCacheDishByCategoryId("*")
log.Printf("启用禁用菜品分类:{%s},{%s}", status, id)
status_r, _ := strconv.ParseInt(status, 10, 32)
id_r, _ := strconv.ParseInt(id, 10, 64)
Expand Down
28 changes: 18 additions & 10 deletions internal/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,20 +95,28 @@ func InitRouter(r *server.Hertz) {
shop.PUT("/:status", admin.SetStatusShop)
shop.GET("/status", admin.GetStatusShop)
}

users := r.Group("/user")
userJ := middleware.InitJwtUser()
user_jwt := middleware.InitJwtUser()
us := users.Group("/user")
us.POST("/login", userJ.LoginHandler)
users.Use(userJ.MiddlewareFunc())

uca := users.Group("/category")
us.POST("/login", user_jwt.LoginHandler)
users.Use(user_jwt.MiddlewareFunc())
u_category := users.Group("/category")
{
uca.GET("/list", user.ListCategory)

u_category.GET("/list", user.ListCategory)
}
ush := users.Group("/shop")
u_shop := users.Group("/shop")
{
ush.GET("/status", admin.GetStatusShop)
u_shop.GET("/status", admin.GetStatusShop)
}
u_dish := users.Group("/dish")
{
u_dish.GET("/list", user.ListDish)
}
u_shoppingCart := users.Group("/shoppingCart")
{
u_shoppingCart.POST("/add", user.AddShoppingCart)
u_shoppingCart.GET("/list", user.ListShoppingCart)
u_shoppingCart.DELETE("/clean", user.CleanShoppingCart)
}

}
5 changes: 5 additions & 0 deletions internal/router/service/dish_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ import (
"reggie/internal/models/dto"
"reggie/internal/models/model"
"reggie/internal/models/vo"
"reggie/pkg/redis"
"strconv"
"time"
)

// 第一个参数菜品,第二个参数菜品口味数组
func SaveWithFlavorDish(dish *model.Dish, flavors *[]model.DishFlavor) *model.Dish {
redis.RC.ClearCacheDishByCategoryId(strconv.FormatInt((*dish).CategoryID, 10))
db.DisDao.Save(dish)
for _, v := range *flavors {
v.DishID = dish.ID
Expand Down Expand Up @@ -43,6 +46,7 @@ func DeleteDish(ids *[]int64) *error {
hlog.Error(message_c.DISH_BE_RELATED_BY_SETMEAL)
return nil
}
redis.RC.ClearCacheDishByCategoryId("*")
//删除菜品表中的菜品数据
for i := 0; i < len(*ids); i++ {
db.DisDao.Delete((*ids)[i])
Expand All @@ -52,6 +56,7 @@ func DeleteDish(ids *[]int64) *error {
return nil
}
func UpdateDish(dish *model.Dish) {
redis.RC.ClearCacheDishByCategoryId("*")
db.DisDao.Update(dish)
}
func StartOrStopDish(status int32, id int64, update_user int64) {
Expand Down
45 changes: 45 additions & 0 deletions internal/router/service/shoppcart_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package service

import (
"reggie/internal/db"
"reggie/internal/models/model"
"time"
)

func AddShoppingCart(shoppingCart model.ShoppingCart) {
//判断当前商品是否在购物车中
shoppingCartList := db.ShopCartDao.List(&shoppingCart)
if shoppingCartList != &[]model.ShoppingCart{} {
shoppingCart := (*shoppingCartList)[0]
shoppingCart.Number += 1
(*shoppingCartList)[0] = shoppingCart
db.ShopCartDao.UpdateNumberById(&shoppingCart)
} else {
//如果不存在,插入数据,数量就是1
//判断当前添加到购物车的是菜品还是套餐
dishId := shoppingCart.DishID
if dishId != 0 {
dish := db.DisDao.GetById(dishId)
shoppingCart.Name = dish.Name
shoppingCart.Image = dish.Image
shoppingCart.Amount = dish.Price
} else {
setmealId := shoppingCart.SetmealID
setmeal := db.MealDao.GetByID(setmealId)
shoppingCart.Name = setmeal.Name
shoppingCart.Image = setmeal.Image
shoppingCart.Amount = setmeal.Price
}
shoppingCart.Number = 1
shoppingCart.CreateTime = time.Now()
db.ShopCartDao.Insert(&shoppingCart)
}
}
func ShowShoppingCart(id int64) *[]model.ShoppingCart {
shop_cart := model.ShoppingCart{}
shop_cart.UserID = id
return db.ShopCartDao.List(&shop_cart)
}
func CleanShoppingCart(userId int64) {
db.ShopCartDao.DeleteByUserId(userId)
}
2 changes: 1 addition & 1 deletion internal/router/user/dish_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func ListDish(ctx context.Context, c *app.RequestContext) {
//查询redis中是否存在菜品数据
list, err := redis.RC.GetListDishVO(c_id)
// redis有数据直接返回
if err != nil {
if err == nil {
c.JSON(http.StatusOK, common.Result{1, "", list})
}
// 无数据查询数据库
Expand Down
37 changes: 37 additions & 0 deletions internal/router/user/shoopingcart_router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package user

import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/hlog"
"net/http"
"reggie/internal/middleware"
"reggie/internal/models/common"
"reggie/internal/models/dto"
"reggie/internal/router/service"
)

// 添加购物车
// /user/shoppingCart/add
func AddShoppingCart(ctx context.Context, c *app.RequestContext) {
var shop_dto dto.ShoppingCartDTO
c.Bind(&shop_dto)
shop_cart := shop_dto.ToShoppingCart()
shop_cart.UserID = middleware.GetJwtPayload(c)
hlog.Infof("添加购物车:", shop_cart)
service.AddShoppingCart(shop_cart)
c.JSON(http.StatusOK, common.Result{1, "", nil})
}
func ListShoppingCart(ctx context.Context, c *app.RequestContext) {
// user
user_id := middleware.GetJwtPayload(c)
c.JSON(http.StatusOK, common.Result{1, "", service.ShowShoppingCart(user_id)})
}

// 清空购物车
func CleanShoppingCart(ctx context.Context, c *app.RequestContext) {
user_id := middleware.GetJwtPayload(c)
// 获取user_id
service.CleanShoppingCart(user_id)
c.JSON(http.StatusOK, common.Result{1, "", nil})
}
10 changes: 7 additions & 3 deletions pkg/redis/acl.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type RedisClient interface {
GetStatus() *int
GetListDishVO(categoryId string) (*[]vo.DishVO, error)
SetListDishVO(categoryId string, dvo *[]vo.DishVO) error
ClearCacheDishByCategoryId(categoryId string)
}
type redisClient struct {
}
Expand All @@ -35,16 +36,16 @@ func (*redisClient) GetStatus() *int {

// 获取失败直接返回nil
func (*redisClient) GetListDishVO(categoryId string) (*[]vo.DishVO, error) {
var dvo *[]vo.DishVO
var dvo []vo.DishVO
b, err := rc.Get(context.Background(), dish_vo+categoryId).Bytes()
if err != nil {
return nil, err
}
if err = json.Unmarshal(b, dvo); err != nil {
if err = json.Unmarshal(b, &dvo); err != nil {
hlog.Error("redis 解析ListDishVO失败")
return nil, err
}
return dvo, nil
return &dvo, nil
}
func (*redisClient) SetListDishVO(categoryId string, dvo *[]vo.DishVO) error {
b, err := json.Marshal(dvo)
Expand All @@ -58,3 +59,6 @@ func (*redisClient) SetListDishVO(categoryId string, dvo *[]vo.DishVO) error {
}
return nil
}
func (*redisClient) ClearCacheDishByCategoryId(categoryId string) {
rc.Del(context.Background(), dish_vo+categoryId)
}

0 comments on commit 6cb68a7

Please sign in to comment.