• 极客专栏正式上线!欢迎访问 https://www.jikewenku.com/topic.html
  • 极客专栏正式上线!欢迎访问 https://www.jikewenku.com/topic.html

从零到企业级SSM电商项目实战教程(四十)创建订单,清空购物车等功能开发

项目实战 Geekerstar 10个月前 (06-25) 836次浏览 已收录 0个评论 扫描二维码
文章目录[隐藏]

前台功能介绍

1、创建订单

2、商品信息

3、订单列表

4、订单详情

5、取消订单

后台功能介绍

1、订单列表

2、订单搜索

3、订单详情

4、订单发货

学习目标

1、避免业务逻辑中横向越权和纵向越权等安全漏洞

2、设计实用、安全、扩展性强大的常量、枚举类

3、订单号生成规则、订单严谨性判断

4、PJO和VO之间的实际操练

5、Mybatis批量插入

OrderController.java

@RequestMapping("create.do")
@ResponseBody
public ServerResponse create(HttpSession session, Integer shippingId) {
    User user = (User) session.getAttribute(Const.CURRENT_USER);
    if (user == null) {
        return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
    }

    return iOrderService.createOrder(user.getId(), shippingId);
}

IOrderService.java

ServerResponse createOrder(Integer userId, Integer shippingId);

OrderServiceImpl.java

@Autowired
private CartMapper cartMapper;
@Autowired
private ProductMapper productMapper;
@Autowired
private ShippingMapper shippingMapper;

public ServerResponse createOrder(Integer userId, Integer shippingId) {
    //从购物车中获取数据
    List<Cart> cartList = cartMapper.selectCheckedCartByUserId(userId);
    //计算这个订单的总价
    ServerResponse serverResponse = this.getCartOrderItem(userId, cartList);
    if (!serverResponse.isSuccess()) {
        return serverResponse;
    }
    List<OrderItem> orderItemList = (List<OrderItem>) serverResponse.getData();
    BigDecimal payment = this.getOrderTotalPrice(orderItemList);
    //生成订单
    Order order = this.assembleOrder(userId, shippingId, payment);
    if (order == null) {
        return ServerResponse.createByErrorMessage("生成订单错误");
    }
    if (CollectionUtils.isEmpty(orderItemList)) {
        return ServerResponse.createByErrorMessage("购物车为空");
    }

    for (OrderItem orderItem : orderItemList) {
        orderItem.setOrderNo(order.getOrderNo());
    }

    //mybatis批量插入
    orderItemMapper.batchInsert(orderItemList);
    //生成成功,减少库存
    this.reduceProductStock(orderItemList);
    //清空购物车
    this.cleanCart(cartList);

    //返回给前端数据
    OrderVo orderVo = assembleOrderVo(order, orderItemList);
    return ServerResponse.createBySuccess(orderVo);
}

private OrderVo assembleOrderVo(Order order, List<OrderItem> orderItemList) {
    OrderVo orderVo = new OrderVo();
    orderVo.setOrderNo(order.getOrderNo());
    orderVo.setPayment(order.getPayment());
    orderVo.setPaymentType(order.getPaymentType());
    orderVo.setPaymentTypeDesc(Const.PaymentTypeEnum.codeOf(order.getPaymentType()).getValue());

    orderVo.setPostage(order.getPostage());
    orderVo.setStatus(order.getStatus());
    orderVo.setStatusDesc(Const.OrderStatusEnum.codeOf(order.getStatus()).getValue());

    orderVo.setShippingId(order.getShippingId());
    Shipping shipping = shippingMapper.selectByPrimaryKey(order.getShippingId());
    if (shipping != null) {
        orderVo.setReceiverName(shipping.getReceiverName());
        orderVo.setShippingVo(assembleShippingVo(shipping));
    }
    orderVo.setPaymentTime(DateTimeUtil.dateToStr(order.getPaymentTime()));
    orderVo.setSendTime(DateTimeUtil.dateToStr(order.getSendTime()));
    orderVo.setEndTime(DateTimeUtil.dateToStr(order.getEndTime()));
    orderVo.setCreateTime(DateTimeUtil.dateToStr(order.getCreateTime()));
    orderVo.setCloseTime(DateTimeUtil.dateToStr(order.getCloseTime()));

    orderVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

    List<OrderItemVo> orderItemVoList = Lists.newArrayList();
    for (OrderItem orderItem : orderItemList) {
        OrderItemVo orderItemVo = assembleOrderItemVo(orderItem);
        orderItemVoList.add(orderItemVo);
    }
    orderVo.setOrderItemVoList(orderItemVoList);
    return orderVo;
}

private OrderItemVo assembleOrderItemVo(OrderItem orderItem) {
    OrderItemVo orderItemVo = new OrderItemVo();
    orderItemVo.setOrderNo(orderItem.getOrderNo());
    orderItemVo.setProductId(orderItem.getProductId());
    orderItemVo.setProductName(orderItem.getProductName());
    orderItemVo.setProductImage(orderItem.getProductImage());
    orderItemVo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
    orderItemVo.setQuantity(orderItem.getQuantity());
    orderItemVo.setTotalPrice(orderItem.getTotalPrice());

    orderItemVo.setCreateTime(DateTimeUtil.dateToStr(orderItem.getCreateTime()));
    return orderItemVo;
}

private ShippingVo assembleShippingVo(Shipping shipping) {
    ShippingVo shippingVo = new ShippingVo();
    shippingVo.setReceiverName(shipping.getReceiverName());
    shippingVo.setReceiverAddress(shipping.getReceiverAddress());
    shippingVo.setReceiverProvince(shipping.getReceiverProvince());
    shippingVo.setReceiverCity(shipping.getReceiverCity());
    shippingVo.setReceiverDistrict(shipping.getReceiverDistrict());
    shippingVo.setReceiverMobile(shipping.getReceiverMobile());
    shippingVo.setReceiverZip(shipping.getReceiverZip());
    shippingVo.setReceiverPhone(shippingVo.getReceiverPhone());
    return shippingVo;
}

private void cleanCart(List<Cart> cartList) {
    for (Cart cart : cartList) {
        cartMapper.deleteByPrimaryKey(cart.getId());
    }
}

private void reduceProductStock(List<OrderItem> orderItemList) {
    for (OrderItem orderItem : orderItemList) {
        Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
        product.setStock(product.getStock() - orderItem.getQuantity());
        productMapper.updateByPrimaryKeySelective(product);
    }
}

private Order assembleOrder(Integer userId, Integer shippingId, BigDecimal payment) {
    Order order = new Order();
    Long orderNo = this.generateOrderNo();
    order.setOrderNo(orderNo);
    order.setStatus(Const.OrderStatusEnum.NO_PAY.getCode());
    order.setPostage(0);
    order.setPaymentType(Const.PaymentTypeEnum.ONLINE_PAY.getCode());
    order.setPayment(payment);
    order.setUserId(userId);
    order.setShippingId(shippingId);
    //todo 各种时间
    int rowCount = orderMapper.insert(order);
    if (rowCount > 0) {
        return order;
    }
    return null;
}

private Long generateOrderNo() {
    Long currentTime = System.currentTimeMillis();
    //100个人并发,下单,不会失败。数据库中是唯一索引。
    return currentTime + new Random().nextInt(100);
}

private BigDecimal getOrderTotalPrice(List<OrderItem> orderItemList) {
    BigDecimal payment = new BigDecimal("0");
    for (OrderItem orderItem : orderItemList) {
        payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
    }
    return payment;
}

private ServerResponse getCartOrderItem(Integer userId, List<Cart> cartList) {
    List<OrderItem> orderItemList = Lists.newArrayList();
    if (CollectionUtils.isEmpty(cartList)) {
        return ServerResponse.createByErrorMessage("购物车为空");
    }
    //校验购物车的数据,包括产品的状态和数量
    for (Cart cartItem : cartList) {
        OrderItem orderItem = new OrderItem();
        Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
        if (Const.ProductStatusEnum.ON_SALE.getCode() != product.getStatus()) {
            return ServerResponse.createByErrorMessage("产品" + product.getName() + "不是在售商品");
        }
        //校验库存
        if (cartItem.getQuantity() > product.getStock()) {
            return ServerResponse.createByErrorMessage("产品" + product.getName() + "库存不足");
        }
        orderItem.setUserId(userId);
        orderItem.setProductId(product.getId());
        orderItem.setProductName(product.getName());
        orderItem.setProductImage(product.getMainImage());
        orderItem.setCurrentUnitPrice(product.getPrice());
        orderItem.setQuantity(cartItem.getQuantity());
        orderItem.setTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartItem.getQuantity()));
        orderItemList.add(orderItem);
    }
    return ServerResponse.createBySuccess(orderItemList);
}

CartMapper.java

List<Cart> selectCheckedCartByUserId(Integer userId);

CartMapper.xml

<select id="selectCheckedCartByUserId" parameterType="int" resultMap="BaseResultMap">
  SELECT
  <include refid="Base_Column_List"/>
  from mmall_cart
  where user_id = #{userId}
  and checked = 1
</select>

OrderItemMapper.java

void batchInsert(@Param("orderItemList") List<OrderItem> orderItemList);

OrderItemMapper.xml

<insert id="batchInsert" parameterType="list">
  insert into mmall_order_item (id, order_no,user_id, product_id,
  product_name, product_image, current_unit_price,
  quantity, total_price, create_time,
  update_time)
  values
  <foreach collection="orderItemList" index="index" item="item" separator=",">
    (
    #{item.id},#{item.orderNo},#{item.userId},#{item.productId},#{item.productName},#{item.productImage},#{item.currentUnitPrice},#{item.quantity},#{item.totalPrice},now(),now()
    )
  </foreach>
</insert>

OrderVo.java

package com.mmall.vo;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author: Geekerstar(jikewenku.com)
 * @Date: 2018/6/25 12:20
 * @Description:
 */
public class OrderVo {
    private Long orderNo;
    private BigDecimal payment;
    private Integer paymentType;
    private String paymentTypeDesc;
    private Integer postage;

    private Integer status;
    private String statusDesc;
    private String paymentTime;

    private String sendTime;

    private String endTime;

    private String closeTime;

    private String createTime;

    //订单明细
    private List<OrderItemVo> orderItemVoList;

    private String imageHost;
    private Integer shippingId;
    private String receiverName;

    private ShippingVo shippingVo;

    public Long getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(Long orderNo) {
        this.orderNo = orderNo;
    }

    public BigDecimal getPayment() {
        return payment;
    }

    public void setPayment(BigDecimal payment) {
        this.payment = payment;
    }

    public Integer getPaymentType() {
        return paymentType;
    }

    public void setPaymentType(Integer paymentType) {
        this.paymentType = paymentType;
    }

    public String getPaymentTypeDesc() {
        return paymentTypeDesc;
    }

    public void setPaymentTypeDesc(String paymentTypeDesc) {
        this.paymentTypeDesc = paymentTypeDesc;
    }

    public Integer getPostage() {
        return postage;
    }

    public void setPostage(Integer postage) {
        this.postage = postage;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getStatusDesc() {
        return statusDesc;
    }

    public void setStatusDesc(String statusDesc) {
        this.statusDesc = statusDesc;
    }

    public String getPaymentTime() {
        return paymentTime;
    }

    public void setPaymentTime(String paymentTime) {
        this.paymentTime = paymentTime;
    }

    public String getSendTime() {
        return sendTime;
    }

    public void setSendTime(String sendTime) {
        this.sendTime = sendTime;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public String getCloseTime() {
        return closeTime;
    }

    public void setCloseTime(String closeTime) {
        this.closeTime = closeTime;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public List<OrderItemVo> getOrderItemVoList() {
        return orderItemVoList;
    }

    public void setOrderItemVoList(List<OrderItemVo> orderItemVoList) {
        this.orderItemVoList = orderItemVoList;
    }

    public String getImageHost() {
        return imageHost;
    }

    public void setImageHost(String imageHost) {
        this.imageHost = imageHost;
    }

    public Integer getShippingId() {
        return shippingId;
    }

    public void setShippingId(Integer shippingId) {
        this.shippingId = shippingId;
    }

    public String getReceiverName() {
        return receiverName;
    }

    public void setReceiverName(String receiverName) {
        this.receiverName = receiverName;
    }

    public ShippingVo getShippingVo() {
        return shippingVo;
    }

    public void setShippingVo(ShippingVo shippingVo) {
        this.shippingVo = shippingVo;
    }
}

OrderItemVo.java

package com.mmall.vo;

import java.math.BigDecimal;

/**
 * @Author: Geekerstar(jikewenku.com)
 * @Date: 2018/6/25 12:21
 * @Description:
 */
public class OrderItemVo {
    private Long orderNo;

    private Integer productId;

    private String productName;

    private String productImage;

    private BigDecimal currentUnitPrice;

    private Integer quantity;

    private BigDecimal totalPrice;

    private String createTime;

    public Long getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(Long orderNo) {
        this.orderNo = orderNo;
    }

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getProductImage() {
        return productImage;
    }

    public void setProductImage(String productImage) {
        this.productImage = productImage;
    }

    public BigDecimal getCurrentUnitPrice() {
        return currentUnitPrice;
    }

    public void setCurrentUnitPrice(BigDecimal currentUnitPrice) {
        this.currentUnitPrice = currentUnitPrice;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public BigDecimal getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(BigDecimal totalPrice) {
        this.totalPrice = totalPrice;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
}

ShippingVo.java

package com.mmall.vo;

/**
 * @Author: Geekerstar(jikewenku.com)
 * @Date: 2018/6/25 12:23
 * @Description:
 */
public class ShippingVo {
    private String receiverName;

    private String receiverPhone;

    private String receiverMobile;

    private String receiverProvince;

    private String receiverCity;

    private String receiverDistrict;

    private String receiverAddress;

    private String receiverZip;

    public String getReceiverName() {
        return receiverName;
    }

    public void setReceiverName(String receiverName) {
        this.receiverName = receiverName;
    }

    public String getReceiverPhone() {
        return receiverPhone;
    }

    public void setReceiverPhone(String receiverPhone) {
        this.receiverPhone = receiverPhone;
    }

    public String getReceiverMobile() {
        return receiverMobile;
    }

    public void setReceiverMobile(String receiverMobile) {
        this.receiverMobile = receiverMobile;
    }

    public String getReceiverProvince() {
        return receiverProvince;
    }

    public void setReceiverProvince(String receiverProvince) {
        this.receiverProvince = receiverProvince;
    }

    public String getReceiverCity() {
        return receiverCity;
    }

    public void setReceiverCity(String receiverCity) {
        this.receiverCity = receiverCity;
    }

    public String getReceiverDistrict() {
        return receiverDistrict;
    }

    public void setReceiverDistrict(String receiverDistrict) {
        this.receiverDistrict = receiverDistrict;
    }

    public String getReceiverAddress() {
        return receiverAddress;
    }

    public void setReceiverAddress(String receiverAddress) {
        this.receiverAddress = receiverAddress;
    }

    public String getReceiverZip() {
        return receiverZip;
    }

    public void setReceiverZip(String receiverZip) {
        this.receiverZip = receiverZip;
    }
}

喜欢 (0)
[247507792@qq.com]
分享 (0)
Geekerstar
关于作者:
本站技术支持

您必须 登录 才能发表评论!

  • 精品技术教程
  • 编程资源分享
  • 问答交流社区
  • 极客文库知识库

客服QQ


QQ:2248886839


工作时间:09:00-23:00