1.用户地址
1.1实体类
/**
* 地址簿
*/
@Data
public class AddressBook implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//用户id
private Long userId;
//收货人
private String consignee;
//手机号
private String phone;
//性别 0 女 1 男
private String sex;
//省级区划编号
private String provinceCode;
//省级名称
private String provinceName;
//市级区划编号
private String cityCode;
//市级名称
private String cityName;
//区级区划编号
private String districtCode;
//区级名称
private String districtName;
//详细地址
private String detail;
//标签
private String label;
//是否默认 0 否 1是
private Integer isDefault;
//创建时间
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
//更新时间
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
//创建人
@TableField(fill = FieldFill.INSERT)
private Long createUser;
//修改人
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
//是否删除
private Integer isDeleted;
}
1.2mapper
@Mapper
public interface AddressBookMapper extends BaseMapper {
}
1.3service
public interface AddressBookService extends IService {
}
@Service
public class AddressBookServiceImpl extends ServiceImpl implements AddressBookService {
}
1.4controller
/**
* 地址簿管理
*/
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
@Autowired
private AddressBookService addressBookService;
/**
* 新增
*/
@PostMapping
public R save(@RequestBody AddressBook addressBook) {
Long userId = BaseContext.getCurrentId();
/*
* 这里留了个坑,我把数据库create_Id和更新时间等字段改成了非空了,算是遗留Bug
* 不知道为什么BaseContext拿不到用户Id数据,所以拿不到create_Id
*
* */
addressBook.setUserId(userId);
log.info("addressBook:{}", addressBook);
addressBookService.save(addressBook);
return R.success(addressBook);
}
/**
* 设置默认地址
*/
@PutMapping("default")
public R setDefault(@RequestBody AddressBook addressBook) {
log.info("addressBook:{}", addressBook);
LambdaUpdateWrapper wrapper = new LambdaUpdateWrapper<>();
wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
wrapper.set(AddressBook::getIsDefault, 0);
//SQL:update address_book set is_default = 0 where user_id = ?
addressBookService.update(wrapper);
addressBook.setIsDefault(1);
//SQL:update address_book set is_default = 1 where id = ?
addressBookService.updateById(addressBook);
return R.success(addressBook);
}
/**
* 根据id查询地址
*/
@GetMapping("/{id}")
public R get(@PathVariable Long id) {
AddressBook addressBook = addressBookService.getById(id);
if (addressBook != null) {
return R.success(addressBook);
} else {
return R.error("没有找到该对象");
}
}
/**
* 查询默认地址
*/
@GetMapping("default")
public R getDefault() {
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
queryWrapper.eq(AddressBook::getIsDefault, 1);
//SQL:select * from address_book where user_id = ? and is_default = 1
AddressBook addressBook = addressBookService.getOne(queryWrapper);
if (null == addressBook) {
return R.error("没有找到该对象");
} else {
return R.success(addressBook);
}
}
/**
* 查询指定用户的全部地址
*/
@GetMapping("/list")
public R> list(AddressBook addressBook) {
addressBook.setUserId(BaseContext.getCurrentId());
log.info("addressBook:{}", addressBook);
//条件构造器
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
queryWrapper.orderByDesc(AddressBook::getUpdateTime);
//SQL:select * from address_book where user_id = ? order by update_time desc
return R .success(addressBookService.list(queryWrapper));
}
}
2.购物车
2.1实体类
/**
* 购物车
*/
@Data
public class ShoppingCart implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//名称
private String name;
//用户id
private Long userId;
//菜品id
private Long dishId;
//套餐id
private Long setmealId;
//口味
private String dishFlavor;
//数量
private Integer number;
//金额
private BigDecimal amount;
//图片
private String image;
private LocalDateTime createTime;
}
2.2mapper
@Mapper
public interface ShoppingCartMapper extends BaseMapper {
}
2.3service
public interface ShoppingCartService extends IService {
}
@Service
public class ShoppingCartServiceImpl extends ServiceImpl implements ShoppingCartService {
}
2.4controller
@Slf4j
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {
@Autowired
private ShoppingCartService shoppingCartService;
/**
* 往购物车内部添加
* @param shoppingCart
* @return
*/
@PostMapping("/add")
public R add(@RequestBody ShoppingCart shoppingCart) {
log.info("购物车数据:{}",shoppingCart.toString());
//解析一下接受的对象不难发现没有用户ID,所以我们得设置一下用户Id,也就是当前购物车是谁的
Long userId=BaseContext.getCurrentId();
shoppingCart.setUserId(userId);
//判断当前传来的Id是菜品还是套餐,这两个肯定会有一个是Null
Long dishId=shoppingCart.getDishId();
Long setmealId = shoppingCart.getSetmealId();
LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
//动态拼接一下添加的查询条件
if (dishId!=null){
//传过来的是菜品而不是套餐
lambdaQueryWrapper.eq(ShoppingCart::getDishId, dishId);
}
if (setmealId!=null){
//传过来的是套餐而不是菜品
lambdaQueryWrapper.eq(ShoppingCart::getSetmealId, setmealId);
}
/*
SQL:select * from shopping_cart where user_Id=? and dish_Id=?/setmealId=?
如果可以查出来,说明购物车已经加入了相关菜品
*/
ShoppingCart cartServiceOne=shoppingCartService.getOne(lambdaQueryWrapper);
//已经存在在购物车里
if (cartServiceOne!=null){
//在数量原有基础上+1
Integer count = cartServiceOne.getNumber();
cartServiceOne.setNumber(count + 1);
/*
update shopping_cart set number=(更新后数量)
*/
shoppingCartService.updateById(cartServiceOne);
}else {
//尚未存在购物车,就添加到购物车
shoppingCart.setNumber(1);
/*
insert into shopping_cart (ShoppingCart解析出来的字段) values (ShoppingCart解析出来的数据)
*/
shoppingCart.setCreateTime(LocalDateTime.now());
shoppingCartService.save(shoppingCart);
//因为这个分支的cartServiceOne是null,所以要覆盖一下
cartServiceOne = shoppingCart;
}
return R.success(cartServiceOne);
}
/**
* @return 购物车列表
*/
@GetMapping("/list")
public R> list(){
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(BaseContext.getCurrentId()!=null,ShoppingCart::getUserId, BaseContext.getCurrentId());
// 最晚下单的 菜品或套餐在购物车中最先展示
queryWrapper.orderByDesc(ShoppingCart::getCreateTime);
List list = shoppingCartService.list(queryWrapper);
return R.success(list);
}
/**
* 一次性清空购物车
* @return
*/
@DeleteMapping("/clean")
public R clean(){
//获取当前购物车用户Id
Long userId = BaseContext.getCurrentId();
LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper();
lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
shoppingCartService.remove(lambdaQueryWrapper);
return R.success("清空成功");
}
}
3.用户下单
3.1service
@Service
public class OrdersServiceImpl extends ServiceImpl implements OrdersService {
@Autowired
private ShoppingCartService shoppingCartService;
@Autowired
private ShoppingCartController shoppingCartController;
@Autowired
private UserService userService;
@Autowired
private AddressBookService addressBookService;
@Autowired
private OrderDetailService orderDetailService;
/**
* 订单提交(下单)
*
* @param orders
*/
@Transactional
@Override
public void submit(Orders orders) {
//获取用户Id
Long userId = BaseContext.getCurrentId();
//根据用户Id查询所对应的购物车内容
LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(userId != null, ShoppingCart::getUserId, userId);
List shoppingCartList = shoppingCartService.list(lambdaQueryWrapper);
//如果订单是空就没必要下单了
if (shoppingCartList == null || shoppingCartList.size() == 0) {
throw new CustomException("购物车为空,不能下单");
}
//拿到用户数据
User user = userService.getById(userId);
//拿到用户的地址数据
Long addressId = orders.getAddressBookId();
AddressBook addressBook = addressBookService.getById(addressId);
if (addressBook == null) {
throw new CustomException("地址有误,不能下单");
}
long orderId = IdWorker.getId(); // 订单号
//遍历购物车列表,来算一下总金额
// 购物车中 商品 的总金额 需要保证在多线程的情况下 也是能计算正确的,故需要使用原子类
AtomicInteger amount = new AtomicInteger(0);
List orderDetails = shoppingCartList.stream().map((item) -> {
OrderDetail orderDetail = new OrderDetail();
orderDetail.setOrderId(orderId);
orderDetail.setName(item.getName());
orderDetail.setImage(item.getImage());
orderDetail.setDishId(item.getDishId());
orderDetail.setSetmealId(item.getSetmealId());
orderDetail.setDishFlavor(item.getDishFlavor());
orderDetail.setNumber(item.getNumber());
orderDetail.setAmount(item.getAmount());
amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
return orderDetail;
}).collect(Collectors.toList());
//填充订单对象信息(CV的)
orders.setId(orderId);
orders.setOrderTime(LocalDateTime.now());
orders.setCheckoutTime(LocalDateTime.now());
orders.setStatus(2);
orders.setAmount(new BigDecimal(amount.get()));//总金额,需要 遍历购物车,计算相关金额来得到
orders.setUserId(userId);
orders.setNumber(String.valueOf(orderId));
orders.setUserName(user.getName());
orders.setConsignee(addressBook.getConsignee());
orders.setPhone(addressBook.getPhone());
orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
+ (addressBook.getCityName() == null ? "" : addressBook.getCityName())
+ (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
+ (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
// 向订单表插入数据,一条数据,插入数据之前,需要填充如上属性
this.save(orders); // --> ordersService.save(orders);
// 向订单明细表插入数据,多条数据
orderDetailService.saveBatch(orderDetails);
//调用接口清空购物车
shoppingCartController.clean();
}
}
3.2controller
@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
@Autowired
private OrdersService ordersService;
@PostMapping("/submit")
public R submit(@RequestBody Orders orders){
//比较繁琐,在service实现
ordersService.submit(orders);
return R.success("下单成功");
}
}