小程序添加购物车业务逻辑
数据库设计
DTO设计
实现步骤
1 判断当前加入购物车中的的商品是否已经存在了
2 如果已经存在 只需要将数量加一
3 如果不存在 插入一条购物车数据
4 判断加到本次购物车的是菜品还是套餐
Impl代码实现
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
@Autowired
private ShoppingCartMapper shoppingCartMapper;
@Autowired
private DishMapper dishMapper;
@Autowired
private SetmealMapper setmealMapper;
/**
* 添加购物车
* @param shoppingCartDTO
*/
@Override
public void add(ShoppingCartDTO shoppingCartDTO) {
//判断当前加入购物车中的的商品是否已经存在了
ShoppingCart shoppingCart = new ShoppingCart();
BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
shoppingCart.setUserId(BaseContext.getCurrentId());
List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
//如果已经存在 只需要将数量加一
if (list!=null&&list.size()>0){
ShoppingCart cart = list.get(0);
cart.setNumber(cart.getNumber()+1);
shoppingCartMapper.updateNumberById(cart);
}else{
//如果不存在 插入一条购物车数据
//判断加到本次购物车的是菜品还是套餐
Long dishId = shoppingCartDTO.getDishId();
if (dishId!=null){
//添加到购物车的是菜品
Dish dish = dishMapper.getById(dishId);
shoppingCart.setName(dish.getName());
shoppingCart.setImage(dish.getImage());
shoppingCart.setAmount(dish.getPrice());
}else{
//添加到购物车的是套餐
Long setmealId = shoppingCartDTO.getSetmealId();
Setmeal setmeal = setmealMapper.getById(setmealId);
shoppingCart.setName(setmeal.getName());
shoppingCart.setImage(setmeal.getImage());
shoppingCart.setAmount(setmeal.getPrice());
}
shoppingCart.setNumber(1);
shoppingCart.setCreateTime(LocalDateTime.now());
shoppingCartMapper.insert(shoppingCart);
}
}
@Override
public List<ShoppingCart> showShoppingCart() {
Long userId = BaseContext.getCurrentId();
ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
return list;
}
@Override
public void clean() {
shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
}
}