Search in sources :

Example 1 with Cart

use of com.wayn.mobile.api.domain.Cart in project waynboot-mall by wayn111.

the class CartServiceImpl method add.

@Override
public R add(Cart cart) {
    Long goodsId = cart.getGoodsId();
    Long productId = cart.getProductId();
    Integer number = cart.getNumber();
    if (!ObjectUtils.allNotNull(goodsId, productId, number) || number <= 0) {
        return R.error(ReturnCodeEnum.PARAMETER_TYPE_ERROR);
    }
    Goods goods = iGoodsService.getById(goodsId);
    if (!goods.getIsOnSale()) {
        return R.error(ReturnCodeEnum.GOODS_HAS_OFFSHELF_ERROR);
    }
    Long userId = MobileSecurityUtils.getLoginUser().getMember().getId();
    GoodsProduct product = iGoodsProductService.getById(productId);
    Cart existsCart = checkExistsGoods(userId, goodsId, productId);
    if (Objects.isNull(existsCart)) {
        if (Objects.isNull(product) || product.getNumber() < number) {
            return R.error(ReturnCodeEnum.GOODS_STOCK_NOT_ENOUGH_ERROR);
        }
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName(goods.getName());
        if (StringUtils.isEmpty(product.getUrl())) {
            cart.setPicUrl(goods.getPicUrl());
        } else {
            cart.setPicUrl(product.getUrl());
        }
        cart.setPrice(product.getPrice());
        cart.setSpecifications((product.getSpecifications()));
        cart.setUserId(Math.toIntExact(userId));
        cart.setChecked(true);
        cart.setRemark(goods.getBrief());
        cart.setCreateTime(LocalDateTime.now());
        save(cart);
    } else {
        int num = existsCart.getNumber() + number;
        if (num > product.getNumber()) {
            return R.error(ReturnCodeEnum.GOODS_STOCK_NOT_ENOUGH_ERROR);
        }
        existsCart.setNumber(num);
        cart.setUpdateTime(LocalDateTime.now());
        if (!updateById(existsCart)) {
            return R.error();
        }
    }
    return R.success();
}
Also used : GoodsProduct(com.wayn.common.core.domain.shop.GoodsProduct) Goods(com.wayn.common.core.domain.shop.Goods) Cart(com.wayn.mobile.api.domain.Cart)

Example 2 with Cart

use of com.wayn.mobile.api.domain.Cart in project waynboot-mall by wayn111.

the class OrderServiceImpl method asyncSubmit.

@Override
public R asyncSubmit(OrderVO orderVO) {
    OrderDTO orderDTO = new OrderDTO();
    MyBeanUtil.copyProperties(orderVO, orderDTO);
    Long userId = orderDTO.getUserId();
    // 获取用户订单商品,为空默认取购物车已选中商品
    List<Long> cartIdArr = orderDTO.getCartIdArr();
    List<Cart> checkedGoodsList;
    if (CollectionUtils.isEmpty(cartIdArr)) {
        checkedGoodsList = iCartService.list(new QueryWrapper<Cart>().eq("checked", true).eq("user_id", userId));
    } else {
        checkedGoodsList = iCartService.listByIds(cartIdArr);
    }
    List<Long> goodsIds = checkedGoodsList.stream().map(Cart::getGoodsId).collect(Collectors.toList());
    List<GoodsProduct> goodsProducts = iGoodsProductService.list(new QueryWrapper<GoodsProduct>().in("goods_id", goodsIds));
    Map<Long, GoodsProduct> goodsIdMap = goodsProducts.stream().collect(Collectors.toMap(GoodsProduct::getId, goodsProduct -> goodsProduct));
    // 商品货品数量减少
    for (Cart checkGoods : checkedGoodsList) {
        Long productId = checkGoods.getProductId();
        Long goodsId = checkGoods.getGoodsId();
        GoodsProduct product = goodsIdMap.get(productId);
        int remainNumber = product.getNumber() - checkGoods.getNumber();
        if (remainNumber < 0) {
            Goods goods = iGoodsService.getById(goodsId);
            String goodsName = goods.getName();
            String[] specifications = product.getSpecifications();
            throw new BusinessException(String.format("%s,%s 库存不足", goodsName, StringUtils.join(specifications, " ")));
        }
        if (!iGoodsProductService.reduceStock(productId, checkGoods.getNumber())) {
            throw new BusinessException("商品货品库存减少失败");
        }
    }
    // 商品费用
    BigDecimal checkedGoodsPrice = new BigDecimal("0.00");
    for (Cart checkGoods : checkedGoodsList) {
        checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
    }
    // 根据订单商品总价计算运费,满足条件(例如88元)则免运费,否则需要支付运费(例如8元);
    BigDecimal freightPrice = new BigDecimal("0.00");
    /*if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
            freightPrice = SystemConfig.getFreight();
        }*/
    // 可以使用的其他钱,例如用户积分
    BigDecimal integralPrice = new BigDecimal("0.00");
    // 优惠卷抵扣费用
    BigDecimal couponPrice = new BigDecimal("0.00");
    // 团购抵扣费用
    BigDecimal grouponPrice = new BigDecimal("0.00");
    // 订单费用
    BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal("0.00"));
    // 最终支付费用
    BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);
    String orderSn = OrderSnGenUtil.generateOrderSn(userId);
    orderDTO.setOrderSn(orderSn);
    // 异步下单
    String uid = IdUtil.getUid();
    System.out.println(uid);
    CorrelationData correlationData = new CorrelationData(uid);
    Map<String, Object> map = new HashMap<>();
    map.put("order", orderDTO);
    map.put("notifyUrl", WaynConfig.getMobileUrl() + "/message/order/submit");
    try {
        Message message = MessageBuilder.withBody(JSON.toJSONString(map).getBytes(Constants.UTF_ENCODING)).setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
        rabbitTemplate.convertAndSend(SysConstants.ORDER_DIRECT_EXCHANGE, SysConstants.ORDER_DIRECT_ROUTING, message, correlationData);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    }
    return R.success().add("actualPrice", actualPrice).add("orderSn", orderSn);
}
Also used : RedisCache(com.wayn.data.redis.manager.RedisCache) MessageBuilder(org.springframework.amqp.core.MessageBuilder) MessageDeliveryMode(org.springframework.amqp.core.MessageDeliveryMode) WxPayMpOrderResult(com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult) Cart(com.wayn.mobile.api.domain.Cart) OrderUtil(com.wayn.common.core.util.OrderUtil) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) BeanUtil(cn.hutool.core.bean.BeanUtil) StringUtils(org.apache.commons.lang3.StringUtils) OrderUnpaidTask(com.wayn.mobile.api.task.OrderUnpaidTask) BigDecimal(java.math.BigDecimal) WxPayUnifiedOrderRequest(com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest) AlipayConfig(com.wayn.common.config.AlipayConfig) ServiceImpl(com.baomidou.mybatisplus.extension.service.impl.ServiceImpl) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) Wrappers(com.baomidou.mybatisplus.core.toolkit.Wrappers) WxPayService(com.github.binarywang.wxpay.service.WxPayService) com.wayn.common.core.domain.shop(com.wayn.common.core.domain.shop) MobileSecurityUtils(com.wayn.mobile.framework.security.util.MobileSecurityUtils) SysConstants(com.wayn.message.core.constant.SysConstants) R(com.wayn.common.util.R) OrderSnGenUtil(com.wayn.mobile.api.util.OrderSnGenUtil) Collectors(java.util.stream.Collectors) ReturnCodeEnum(com.wayn.common.enums.ReturnCodeEnum) MyBeanUtil(com.wayn.common.util.bean.MyBeanUtil) IOUtils(org.apache.commons.io.IOUtils) OrderGoodsVO(com.wayn.common.core.domain.vo.order.OrderGoodsVO) Slf4j(lombok.extern.slf4j.Slf4j) PayTypeEnum(com.wayn.common.enums.PayTypeEnum) Constants(com.wayn.common.constant.Constants) BusinessException(com.wayn.common.exception.BusinessException) IPage(com.baomidou.mybatisplus.core.metadata.IPage) OrderVO(com.wayn.common.core.domain.vo.OrderVO) UnsupportedEncodingException(java.io.UnsupportedEncodingException) java.util(java.util) OrderDetailVO(com.wayn.common.core.domain.vo.order.OrderDetailVO) IdUtil(com.wayn.common.util.IdUtil) BaseWxPayResult(com.github.binarywang.wxpay.bean.result.BaseWxPayResult) CorrelationData(org.springframework.amqp.rabbit.connection.CorrelationData) LocalDateTime(java.time.LocalDateTime) IOrderService(com.wayn.mobile.api.service.IOrderService) MessageProperties(org.springframework.amqp.core.MessageProperties) CollectionUtils(org.apache.commons.collections4.CollectionUtils) WaynConfig(com.wayn.common.config.WaynConfig) HttpServletRequest(javax.servlet.http.HttpServletRequest) com.wayn.common.core.service.shop(com.wayn.common.core.service.shop) IpUtils(com.wayn.common.util.ip.IpUtils) Service(org.springframework.stereotype.Service) Message(org.springframework.amqp.core.Message) WxPayConstants(com.github.binarywang.wxpay.constant.WxPayConstants) WxPayOrderNotifyResult(com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult) DefaultAlipayClient(com.alipay.api.DefaultAlipayClient) OrderHandleOption(com.wayn.common.core.util.OrderHandleOption) RabbitTemplate(org.springframework.amqp.rabbit.core.RabbitTemplate) AlipayClient(com.alipay.api.AlipayClient) OrderMapper(com.wayn.mobile.api.mapper.OrderMapper) ICartService(com.wayn.mobile.api.service.ICartService) AlipaySignature(com.alipay.api.internal.util.AlipaySignature) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) WxPayException(com.github.binarywang.wxpay.exception.WxPayException) TaskService(com.wayn.common.task.TaskService) OrderDTO(com.wayn.message.core.messsage.OrderDTO) AlipayTradeWapPayRequest(com.alipay.api.request.AlipayTradeWapPayRequest) WxPayNotifyResponse(com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse) JSON(com.alibaba.fastjson.JSON) AllArgsConstructor(lombok.AllArgsConstructor) AlipayApiException(com.alipay.api.AlipayApiException) Transactional(org.springframework.transaction.annotation.Transactional) Message(org.springframework.amqp.core.Message) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BigDecimal(java.math.BigDecimal) BusinessException(com.wayn.common.exception.BusinessException) CorrelationData(org.springframework.amqp.rabbit.connection.CorrelationData) OrderDTO(com.wayn.message.core.messsage.OrderDTO) Cart(com.wayn.mobile.api.domain.Cart)

Example 3 with Cart

use of com.wayn.mobile.api.domain.Cart in project waynboot-mall by wayn111.

the class CartServiceImpl method list.

@Override
public R list(Page<Cart> page, Long userId) {
    IPage<Cart> goodsIPage = cartMapper.selectCartPageList(page, userId);
    List<Cart> cartList = goodsIPage.getRecords();
    List<Long> goodsIdList = cartList.stream().map(Cart::getGoodsId).collect(Collectors.toList());
    JSONArray array = new JSONArray();
    if (CollectionUtils.isEmpty(goodsIdList)) {
        return R.success().add("data", array);
    }
    Map<Long, Goods> goodsIdMap = iGoodsService.selectGoodsByIds(goodsIdList).stream().collect(Collectors.toMap(Goods::getId, goods -> goods));
    for (Cart cart : cartList) {
        JSONObject jsonObject = new JSONObject();
        try {
            MyBeanUtil.copyProperties2Map(cart, jsonObject);
            Goods goods = goodsIdMap.get(cart.getGoodsId());
            if (goods.getIsNew()) {
                jsonObject.put("tag", "新品");
            }
            if (goods.getIsHot()) {
                jsonObject.put("tag", "热品");
            }
        } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
            log.error(e.getMessage(), e);
        }
        array.add(jsonObject);
    }
    return R.success().add("data", array);
}
Also used : Cart(com.wayn.mobile.api.domain.Cart) LocalDateTime(java.time.LocalDateTime) StringUtils(org.apache.commons.lang3.StringUtils) CollectionUtils(org.apache.commons.collections4.CollectionUtils) JSONArray(com.alibaba.fastjson.JSONArray) IGoodsProductService(com.wayn.common.core.service.shop.IGoodsProductService) ObjectUtils(org.apache.commons.lang3.ObjectUtils) Service(org.springframework.stereotype.Service) Map(java.util.Map) IGoodsService(com.wayn.common.core.service.shop.IGoodsService) ServiceImpl(com.baomidou.mybatisplus.extension.service.impl.ServiceImpl) ICartService(com.wayn.mobile.api.service.ICartService) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) Wrappers(com.baomidou.mybatisplus.core.toolkit.Wrappers) MobileSecurityUtils(com.wayn.mobile.framework.security.util.MobileSecurityUtils) GoodsProduct(com.wayn.common.core.domain.shop.GoodsProduct) R(com.wayn.common.util.R) Collectors(java.util.stream.Collectors) Goods(com.wayn.common.core.domain.shop.Goods) ReturnCodeEnum(com.wayn.common.enums.ReturnCodeEnum) MyBeanUtil(com.wayn.common.util.bean.MyBeanUtil) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Objects(java.util.Objects) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) List(java.util.List) JSONObject(com.alibaba.fastjson.JSONObject) BusinessException(com.wayn.common.exception.BusinessException) CartMapper(com.wayn.mobile.api.mapper.CartMapper) AllArgsConstructor(lombok.AllArgsConstructor) IPage(com.baomidou.mybatisplus.core.metadata.IPage) JSONArray(com.alibaba.fastjson.JSONArray) IntrospectionException(java.beans.IntrospectionException) Goods(com.wayn.common.core.domain.shop.Goods) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONObject(com.alibaba.fastjson.JSONObject) Cart(com.wayn.mobile.api.domain.Cart)

Example 4 with Cart

use of com.wayn.mobile.api.domain.Cart in project waynboot-mall by wayn111.

the class CartServiceImpl method changeNum.

@Override
public R changeNum(Long cartId, Integer number) {
    Cart cart = getById(cartId);
    Long productId = cart.getProductId();
    GoodsProduct goodsProduct = iGoodsProductService.getById(productId);
    Integer productNumber = goodsProduct.getNumber();
    if (number > productNumber) {
        throw new BusinessException(String.format("库存不足,该商品只剩%d件了", productNumber));
    }
    boolean update = lambdaUpdate().setSql("number = " + number).eq(Cart::getId, cartId).update();
    return R.result(update);
}
Also used : BusinessException(com.wayn.common.exception.BusinessException) GoodsProduct(com.wayn.common.core.domain.shop.GoodsProduct) Cart(com.wayn.mobile.api.domain.Cart)

Example 5 with Cart

use of com.wayn.mobile.api.domain.Cart in project waynboot-mall by wayn111.

the class OrderServiceImpl method submit.

@Override
@Transactional(rollbackFor = Exception.class)
public R submit(OrderDTO orderDTO) {
    Long userId = orderDTO.getUserId();
    // 获取用户地址
    Long addressId = orderDTO.getAddressId();
    Address checkedAddress;
    if (Objects.isNull(addressId)) {
        throw new BusinessException("收获地址为空,请求参数" + JSON.toJSONString(orderDTO));
    }
    checkedAddress = iAddressService.getById(addressId);
    // 获取用户订单商品,为空默认取购物车已选中商品
    List<Long> cartIdArr = orderDTO.getCartIdArr();
    List<Cart> checkedGoodsList;
    if (CollectionUtils.isEmpty(cartIdArr)) {
        checkedGoodsList = iCartService.list(new QueryWrapper<Cart>().eq("checked", true).eq("user_id", userId));
    } else {
        checkedGoodsList = iCartService.listByIds(cartIdArr);
    }
    // 商品费用
    BigDecimal checkedGoodsPrice = new BigDecimal("0.00");
    for (Cart checkGoods : checkedGoodsList) {
        checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
    }
    // 根据订单商品总价计算运费,满足条件(例如88元)则免运费,否则需要支付运费(例如8元);
    BigDecimal freightPrice = new BigDecimal("0.00");
    /*if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
            freightPrice = SystemConfig.getFreight();
        }*/
    // 可以使用的其他钱,例如用户积分
    BigDecimal integralPrice = new BigDecimal("0.00");
    // 优惠卷抵扣费用
    BigDecimal couponPrice = new BigDecimal("0.00");
    // 团购抵扣费用
    BigDecimal grouponPrice = new BigDecimal("0.00");
    // 订单费用
    BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal("0.00"));
    // 最终支付费用
    BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);
    // 组装订单数据
    Order order = new Order();
    order.setUserId(userId);
    order.setOrderSn(orderDTO.getOrderSn());
    order.setOrderStatus(OrderUtil.STATUS_CREATE);
    order.setConsignee(checkedAddress.getName());
    order.setMobile(checkedAddress.getTel());
    order.setMessage(orderDTO.getMessage());
    String detailedAddress = checkedAddress.getProvince() + checkedAddress.getCity() + checkedAddress.getCounty() + " " + checkedAddress.getAddressDetail();
    order.setAddress(detailedAddress);
    order.setFreightPrice(freightPrice);
    order.setCouponPrice(couponPrice);
    order.setGrouponPrice(grouponPrice);
    order.setIntegralPrice(integralPrice);
    order.setGoodsPrice(checkedGoodsPrice);
    order.setOrderPrice(orderTotalPrice);
    order.setActualPrice(actualPrice);
    order.setCreateTime(new Date());
    if (!save(order)) {
        throw new BusinessException("订单创建失败" + JSON.toJSONString(order));
    }
    Long orderId = order.getId();
    List<OrderGoods> orderGoodsList = new ArrayList<>();
    // 添加订单商品表项
    for (Cart cartGoods : checkedGoodsList) {
        // 订单商品
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderId(orderId);
        orderGoods.setGoodsId(cartGoods.getGoodsId());
        orderGoods.setGoodsSn(cartGoods.getGoodsSn());
        orderGoods.setProductId(cartGoods.getProductId());
        orderGoods.setGoodsName(cartGoods.getGoodsName());
        orderGoods.setPicUrl(cartGoods.getPicUrl());
        orderGoods.setPrice(cartGoods.getPrice());
        orderGoods.setNumber(cartGoods.getNumber());
        orderGoods.setSpecifications(cartGoods.getSpecifications());
        orderGoods.setCreateTime(LocalDateTime.now());
        orderGoodsList.add(orderGoods);
    }
    if (!iOrderGoodsService.saveBatch(orderGoodsList)) {
        throw new BusinessException("添加订单商品表项失败" + JSON.toJSONString(orderGoodsList));
    }
    // 删除购物车里面的商品信息
    if (CollectionUtils.isEmpty(cartIdArr)) {
        iCartService.remove(new QueryWrapper<Cart>().eq("user_id", userId));
    } else {
        iCartService.removeByIds(cartIdArr);
    }
    // 下单60s内未支付自动取消订单
    long delay = 1000;
    redisCache.setCacheZset("order_zset", order.getId(), System.currentTimeMillis() + 60 * delay);
    taskService.addTask(new OrderUnpaidTask(order.getId(), delay * 60));
    return R.success().add("orderId", order.getId());
}
Also used : LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) OrderUnpaidTask(com.wayn.mobile.api.task.OrderUnpaidTask) BigDecimal(java.math.BigDecimal) BusinessException(com.wayn.common.exception.BusinessException) Cart(com.wayn.mobile.api.domain.Cart) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

Cart (com.wayn.mobile.api.domain.Cart)6 BusinessException (com.wayn.common.exception.BusinessException)4 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)3 GoodsProduct (com.wayn.common.core.domain.shop.GoodsProduct)3 LambdaQueryWrapper (com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)2 IPage (com.baomidou.mybatisplus.core.metadata.IPage)2 Wrappers (com.baomidou.mybatisplus.core.toolkit.Wrappers)2 ServiceImpl (com.baomidou.mybatisplus.extension.service.impl.ServiceImpl)2 Goods (com.wayn.common.core.domain.shop.Goods)2 ReturnCodeEnum (com.wayn.common.enums.ReturnCodeEnum)2 R (com.wayn.common.util.R)2 MyBeanUtil (com.wayn.common.util.bean.MyBeanUtil)2 BigDecimal (java.math.BigDecimal)2 BeanUtil (cn.hutool.core.bean.BeanUtil)1 JSON (com.alibaba.fastjson.JSON)1 JSONArray (com.alibaba.fastjson.JSONArray)1 JSONObject (com.alibaba.fastjson.JSONObject)1 AlipayApiException (com.alipay.api.AlipayApiException)1 AlipayClient (com.alipay.api.AlipayClient)1 DefaultAlipayClient (com.alipay.api.DefaultAlipayClient)1