litemall icon indicating copy to clipboard operation
litemall copied to clipboard

代码缺少美感

Open softyu opened this issue 5 years ago • 8 comments

@PostMapping("submit") public Object submit(@LoginUser Integer userId, @RequestBody String body) { if (userId == null) { return ResponseUtil.unlogin(); } if (body == null) { return ResponseUtil.badArgument(); } Integer cartId = JacksonUtil.parseInteger(body, "cartId"); Integer addressId = JacksonUtil.parseInteger(body, "addressId"); Integer couponId = JacksonUtil.parseInteger(body, "couponId"); String message = JacksonUtil.parseString(body, "message"); Integer grouponRulesId = JacksonUtil.parseInteger(body, "grouponRulesId"); Integer grouponLinkId = JacksonUtil.parseInteger(body, "grouponLinkId");

    //如果是团购项目,验证活动是否有效
    if (grouponRulesId != null && grouponRulesId > 0) {
        LitemallGrouponRules rules = grouponRulesService.queryById(grouponRulesId);
        //找不到记录
        if (rules == null) {
            return ResponseUtil.badArgument();
        }
        //团购活动已经过期
        if (grouponRulesService.isExpired(rules)) {
            return ResponseUtil.fail(GROUPON_EXPIRED, "团购活动已过期!");
        }
    }

    if (cartId == null || addressId == null || couponId == null) {
        return ResponseUtil.badArgument();
    }

    // 收货地址
    LitemallAddress checkedAddress = addressService.findById(addressId);
    if (checkedAddress == null) {
        return ResponseUtil.badArgument();
    }

    // 团购优惠
    BigDecimal grouponPrice = new BigDecimal(0.00);
    LitemallGrouponRules grouponRules = grouponRulesService.queryById(grouponRulesId);
    if (grouponRules != null) {
        grouponPrice = grouponRules.getDiscount();
    }

    // 货品价格
    List<LitemallCart> checkedGoodsList = null;
    if (cartId.equals(0)) {
        checkedGoodsList = cartService.queryByUidAndChecked(userId);
    } else {
        LitemallCart cart = cartService.findById(cartId);
        checkedGoodsList = new ArrayList<>(1);
        checkedGoodsList.add(cart);
    }
    if (checkedGoodsList.size() == 0) {
        return ResponseUtil.badArgumentValue();
    }
    BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
    for (LitemallCart checkGoods : checkedGoodsList) {
        //  只有当团购规格商品ID符合才进行团购优惠
        if (grouponRules != null && grouponRules.getGoodsId().equals(checkGoods.getGoodsId())) {
            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().subtract(grouponPrice).multiply(new BigDecimal(checkGoods.getNumber())));
        } else {
            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
        }
    }

    // 获取可用的优惠券信息
    // 使用优惠券减免的金额
    BigDecimal couponPrice = new BigDecimal(0.00);
    // 如果couponId=0则没有优惠券,couponId=-1则不使用优惠券
    if(couponId != 0 && couponId != -1){
        LitemallCoupon coupon = couponVerifyService.checkCoupon(userId, couponId, checkedGoodsPrice);
        if(coupon == null){
            return ResponseUtil.badArgumentValue();
        }
        couponPrice = coupon.getDiscount();
    }


    // 根据订单商品总价计算运费,满足条件(例如88元)则免运费,否则需要支付运费(例如8元);
    BigDecimal freightPrice = new BigDecimal(0.00);
    if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
        freightPrice = SystemConfig.getFreight();
    }

    // 可以使用的其他钱,例如用户积分
    BigDecimal integralPrice = new BigDecimal(0.00);

    // 订单费用
    BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice);
    // 最终支付费用
    BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);

    // TODO: 2019/3/3 真的需要手动处理事务吗 代码写的没有美感
    // 开启事务管理
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txManager.getTransaction(def);
    Integer orderId = null;
    LitemallOrder order = null;
    try {
        // 订单
        order = new LitemallOrder();
        order.setUserId(userId);
        order.setOrderSn(orderService.generateOrderSn(userId));
        order.setOrderStatus(OrderUtil.STATUS_CREATE);
        order.setConsignee(checkedAddress.getName());
        order.setMobile(checkedAddress.getMobile());
        order.setMessage(message);
        String detailedAddress = detailedAddress(checkedAddress);
        order.setAddress(detailedAddress);
        order.setGoodsPrice(checkedGoodsPrice);
        order.setFreightPrice(freightPrice);
        order.setCouponPrice(couponPrice);
        order.setIntegralPrice(integralPrice);
        order.setOrderPrice(orderTotalPrice);
        order.setActualPrice(actualPrice);

        // 有团购活动
        if (grouponRules != null) {
            order.setGrouponPrice(grouponPrice);    //  团购价格
        } else {
            order.setGrouponPrice(new BigDecimal(0.00));    //  团购价格
        }

        // 添加订单表项
        orderService.add(order);
        orderId = order.getId();

        // 添加订单商品表项
        for (LitemallCart cartGoods : checkedGoodsList) {
            // 订单商品
            LitemallOrderGoods orderGoods = new LitemallOrderGoods();
            orderGoods.setOrderId(order.getId());
            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.setAddTime(LocalDateTime.now());

            orderGoodsService.add(orderGoods);
        }

        // 删除购物车里面的商品信息
        cartService.clearGoods(userId);

        // 商品货品数量减少
        for (LitemallCart checkGoods : checkedGoodsList) {
            Integer productId = checkGoods.getProductId();
            LitemallGoodsProduct product = productService.findById(productId);

            Integer remainNumber = product.getNumber() - checkGoods.getNumber();
            if (remainNumber < 0) {
                throw new RuntimeException("下单的商品货品数量大于库存量");
            }
            if (productService.reduceStock(productId, checkGoods.getNumber()) == 0) {
                throw new Exception("商品货品库存减少失败");
            }
        }

        // 如果使用了优惠券,设置优惠券使用状态
        if(couponId != 0 && couponId != -1){
            LitemallCouponUser couponUser = couponUserService.queryOne(userId, couponId);
            couponUser.setStatus(CouponUserConstant.STATUS_USED);
            couponUser.setUsedTime(LocalDateTime.now());
            couponUser.setOrderId(orderId);
            couponUserService.update(couponUser);
        }

        //如果是团购项目,添加团购信息
        if (grouponRulesId != null && grouponRulesId > 0) {
            LitemallGroupon groupon = new LitemallGroupon();
            groupon.setOrderId(orderId);
            groupon.setPayed(false);
            groupon.setUserId(userId);
            groupon.setRulesId(grouponRulesId);

            //参与者
            if (grouponLinkId != null && grouponLinkId > 0) {
                //参与的团购记录
                LitemallGroupon baseGroupon = grouponService.queryById(grouponLinkId);
                groupon.setCreatorUserId(baseGroupon.getCreatorUserId());
                groupon.setGrouponId(grouponLinkId);
                groupon.setShareUrl(baseGroupon.getShareUrl());
            } else {
                groupon.setCreatorUserId(userId);
                groupon.setGrouponId(0);
            }

            grouponService.createGroupon(groupon);
        }
    } catch (Exception ex) {
        txManager.rollback(status);
        logger.error("系统内部错误", ex);
        return ResponseUtil.fail(ORDER_CHECKOUT_FAIL, "下单失败");
    }
    txManager.commit(status);

    Map<String, Object> data = new HashMap<>();
    data.put("orderId", orderId);
    return ResponseUtil.ok(data);
}

不过能前后端都搞出来真的很牛逼,建议把后端代码好好优化一下,一个方法都这么长很难阅读。

softyu avatar Mar 03 '19 13:03 softyu

好的,谢谢。不知道有没有可以推荐的项目看看,或者类似代码。

另外,事务管理现在采用了注解的方式。

linlinjava avatar Mar 04 '19 11:03 linlinjava

哈哈,不好意思没有,我有时间给你提pr,小程序我也想上手,有什么好的建议吗?

softyu avatar Mar 04 '19 11:03 softyu

没有好的建议,看代码,看官方文档,多练习

linlinjava avatar Mar 04 '19 11:03 linlinjava

建议Json2Bean或者直接请求封装成bean,然后对象赋值时,使用BeanUtils或者BeanCopier

owenwong avatar Mar 05 '19 03:03 owenwong

if (userId == null) { return ResponseUtil.unlogin(); } if (body == null) { return ResponseUtil.badArgument(); } 第一个判断,这个方法如果是需要登录才能访问的,这个userid肯定不会为null吧,有点多余的判断 第二个判断,RequstBody注解 required默认为true,也就是说访问这个方法如果没有http body的话会报错的,根本到不了第二个判断这里,所以这里也是多余的

spinachomes avatar Oct 19 '19 07:10 spinachomes

重构过了吗

cnstephen avatar May 08 '21 13:05 cnstephen

重构过了吗

What are you thinking?

Liocco avatar May 05 '22 09:05 Liocco