Search in sources :

Example 1 with BusinessException

use of com.wayn.common.exception.BusinessException in project waynboot-mall by wayn111.

the class LoginService method login.

@SneakyThrows
public String login(String username, String password) {
    // 用户验证
    Authentication authentication;
    try {
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
    } catch (Exception e) {
        if (e instanceof BadCredentialsException) {
            throw new BadCredentialsException(e.getMessage(), e);
        } else {
            throw new BusinessException(e.getMessage());
        }
    }
    LoginUserDetail principal = (LoginUserDetail) authentication.getPrincipal();
    return tokenService.createToken(principal);
}
Also used : BusinessException(com.wayn.common.exception.BusinessException) Authentication(org.springframework.security.core.Authentication) LoginUserDetail(com.wayn.common.core.model.LoginUserDetail) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) BusinessException(com.wayn.common.exception.BusinessException) SneakyThrows(lombok.SneakyThrows)

Example 2 with BusinessException

use of com.wayn.common.exception.BusinessException in project waynboot-mall by wayn111.

the class GoodsServiceImpl method syncGoods2Es.

/**
 * 同步商品信息到es中
 *
 * @param goods 商品信息
 */
public boolean syncGoods2Es(Goods goods) throws IOException {
    // 同步es
    ElasticEntity elasticEntity = new ElasticEntity();
    elasticEntity.setId(goods.getId().toString());
    Map<String, Object> map = new HashMap<>();
    map.put("id", goods.getId());
    map.put("name", goods.getName());
    map.put("countPrice", goods.getCounterPrice());
    map.put("retailPrice", goods.getRetailPrice());
    map.put("keyword", Objects.isNull(goods.getKeywords()) ? Collections.emptyList() : goods.getKeywords().split(","));
    map.put("isOnSale", goods.getIsOnSale());
    map.put("createTime", goods.getCreateTime());
    elasticEntity.setData(map);
    if (!elasticDocument.insertOrUpdateOne(SysConstants.ES_GOODS_INDEX, elasticEntity)) {
        throw new BusinessException("商品同步es失败");
    }
    return true;
}
Also used : BusinessException(com.wayn.common.exception.BusinessException) ElasticEntity(com.wayn.data.elastic.manager.ElasticEntity)

Example 3 with BusinessException

use of com.wayn.common.exception.BusinessException in project waynboot-mall by wayn111.

the class RoleServiceImpl method deleteRoleByIds.

@Override
public boolean deleteRoleByIds(List<Long> roleIds) {
    for (Long roleId : roleIds) {
        checkRoleAllowed(new Role(roleId));
        Role role = getById(roleId);
        long count = countUserRoleByRoleId(roleId);
        if (count > 0) {
            throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName()));
        }
    }
    return removeByIds(roleIds);
}
Also used : UserRole(com.wayn.common.core.domain.system.UserRole) Role(com.wayn.common.core.domain.system.Role) BusinessException(com.wayn.common.exception.BusinessException)

Example 4 with BusinessException

use of com.wayn.common.exception.BusinessException in project waynboot-mall by wayn111.

the class FileUploadUtil method uploadFile.

/**
 * @param fileBytes 文件base64编码后内容
 * @param fileName  文件名称
 * @param filePath  要保存的文件按目录
 * @return 新文件名称
 * @throws IOException 上传异常
 */
public static String uploadFile(byte[] fileBytes, String fileName, String filePath) throws IOException {
    int fileNameLength = Objects.requireNonNull(fileName).length();
    if (fileNameLength > 100) {
        throw new BusinessException("文件名称过长");
    }
    String encodingFilename = FileUtils.encodingFilename(fileName);
    String extension = FilenameUtils.getExtension(fileName);
    fileName = genNewFilename(encodingFilename, extension);
    File desc = new File(filePath, fileName);
    if (!desc.getParentFile().exists()) {
        desc.getParentFile().mkdirs();
    }
    if (!desc.exists()) {
        desc.createNewFile();
    }
    IOUtils.write(fileBytes, new FileOutputStream(desc));
    return fileName;
}
Also used : BusinessException(com.wayn.common.exception.BusinessException) FileOutputStream(java.io.FileOutputStream) MultipartFile(org.springframework.web.multipart.MultipartFile) File(java.io.File)

Example 5 with BusinessException

use of com.wayn.common.exception.BusinessException 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)

Aggregations

BusinessException (com.wayn.common.exception.BusinessException)14 Transactional (org.springframework.transaction.annotation.Transactional)4 LambdaQueryWrapper (com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)3 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)3 LoginUserDetail (com.wayn.mobile.framework.security.LoginUserDetail)3 Member (com.wayn.common.core.domain.shop.Member)2 OrderHandleOption (com.wayn.common.core.util.OrderHandleOption)2 ReturnCodeEnum (com.wayn.common.enums.ReturnCodeEnum)2 Cart (com.wayn.mobile.api.domain.Cart)2 File (java.io.File)2 BeanUtil (cn.hutool.core.bean.BeanUtil)1 JSON (com.alibaba.fastjson.JSON)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 AlipaySignature (com.alipay.api.internal.util.AlipaySignature)1 AlipayTradeWapPayRequest (com.alipay.api.request.AlipayTradeWapPayRequest)1 IPage (com.baomidou.mybatisplus.core.metadata.IPage)1 Wrappers (com.baomidou.mybatisplus.core.toolkit.Wrappers)1