xin
2025-07-08 83396a38be3c69c81f8acc4681c18f5dd0e698be
oying-system/src/main/java/com/oying/modules/sh/service/impl/OrderServiceImpl.java
@@ -1,7 +1,28 @@
package com.oying.modules.sh.service.impl;
import com.alibaba.fastjson2.JSONObject;
import com.oying.exception.BadRequestException;
import com.oying.modules.hwc.domain.HwcResponse;
import com.oying.modules.hwc.service.SwiftPassService;
import com.oying.modules.pc.product.domain.Product;
import com.oying.modules.pc.product.domain.enums.ProductStatusEnum;
import com.oying.modules.pc.product.service.ProductService;
import com.oying.modules.pc.store.domain.Store;
import com.oying.modules.pc.store.service.StoreService;
import com.oying.modules.sh.domain.Order;
import com.oying.utils.FileUtil;
import com.oying.modules.sh.domain.OrderProductSnapshot;
import com.oying.modules.sh.domain.request.GeneratorOrder;
import com.oying.modules.sh.domain.request.ProductOrder;
import com.oying.modules.sh.domain.request.SubmitOrder;
import com.oying.modules.sh.domain.vo.OrderInfo;
import com.oying.modules.sh.domain.vo.ProductInfo;
import com.oying.modules.sh.service.OrderProductSnapshotService;
import com.oying.modules.sh.service.UserAddressService;
import com.oying.utils.*;
import com.oying.utils.enums.GenerateEnum;
import com.oying.utils.enums.OrderStatusEnum;
import com.oying.utils.enums.PayStateEnum;
import com.oying.utils.enums.PayTypeEnum;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -10,34 +31,208 @@
import com.oying.modules.sh.mapper.OrderMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.oying.utils.PageUtil;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import com.oying.utils.PageResult;
/**
* @description 服务实现
* @author lixin
* @date 2025-06-11
**/
 * @author lixin
 * @description 服务实现
 * @date 2025-06-11
 **/
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    private final OrderMapper orderMapper;
    private final UserAddressService userAddressService;
    private final ProductService productService;
    private final SwiftPassService swiftPassService;
    private final OrderProductSnapshotService productSnapshotService;
    private final RedisUtils redisUtils;
    private final StoreService storeService;
    private final static String DESCRIBE = "哦应:";
    @Override
    public PageResult<Order> queryAll(OrderQueryCriteria criteria, Page<Object> page){
    public PageResult<Order> queryAll(OrderQueryCriteria criteria, Page<Object> page) {
        return PageUtil.toPage(orderMapper.findAll(criteria, page));
    }
    @Override
    public List<Order> queryAll(OrderQueryCriteria criteria){
    public List<Order> queryAll(OrderQueryCriteria criteria) {
        return orderMapper.findAll(criteria);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Order submitOrder(SubmitOrder submit, HttpServletRequest request) {
        if (!submit.getPayType().equals(PayTypeEnum.HWC)) {
            throw new BadRequestException("支付类型暂未开放");
        }
        String orderNum = redisUtils.generateOrderSn(GenerateEnum.ORDER.getKey());
        // 总金额
        BigDecimal amount = BigDecimal.ZERO;
        GeneratorOrder generator = new GeneratorOrder();
        generator.setProducts(submit.getProducts());
        generator.setStoreId(submit.getStoreId());
        OrderInfo info = generatorOrder(generator);
        // 商品快照
        List<OrderProductSnapshot> snapshots = new ArrayList<>();
        for (ProductInfo productInfo : info.getProducts()) {
            Product product = productInfo.getProduct();
            OrderProductSnapshot snapshot = new OrderProductSnapshot();
            snapshot.setOrderNum(orderNum);
            snapshot.setStoreId(submit.getStoreId());
            snapshot.setProductId(product.getProductId());
            snapshot.setProductBarcode(product.getBarcode());
            snapshot.setProductName(product.getName());
            snapshot.setProductTitle(product.getTitle());
            snapshot.setProductMainImage(product.getMainImageUrl());
            snapshot.setParamData(JSONObject.toJSONString(productInfo.getProductLabels()));
            snapshot.setUnitPrice(product.getPrice());
            snapshot.setDetailCount(productInfo.getCount());
            snapshot.setOriginalPrice(product.getPrice());
            snapshot.setPaidPrice(product.getPrice());
            BigDecimal decimal = BigDecimalUtils.multiply(product.getPrice(), productInfo.getCount());
            amount = BigDecimalUtils.add(amount, decimal);
            snapshot.setActuallyPayPrice(decimal);
            snapshot.setPayState(PayStateEnum.NOTPAY.getKey());
            snapshots.add(snapshot);
        }
        Timestamp now = DateUtil.getTimeStamp();
        // 下单后30分钟失效
        Timestamp time = DateUtil.addMinute(now, 30);
        String expire = DateUtil.localDateTimeFormat(time.toLocalDateTime(), DateUtil.SDF_YMDHMS);
        String openid = SecurityUtils.getCurrentOpenid();
        if (openid == null || openid.isEmpty()) {
            throw new BadRequestException("OPENID错误");
        }
        // 订单信息
        Order order = new Order();
        order.setOrderNum(orderNum);
        order.setOrderStatus(OrderStatusEnum.ZERO.getKey());
        order.setOrderStatusDescribe(OrderStatusEnum.ZERO.getValue());
        order.setUserId(SecurityUtils.getCurrentUserId());
        order.setUsername(SecurityUtils.getCurrentUsername());
        Store store = storeService.getMerchantStore(submit.getStoreId());
        order.setStoreId(submit.getStoreId());
        order.setStoreName(store.getStoreName());
        order.setStoreLogo(store.getLogoImageUrl());
        order.setOrderDescribe(DESCRIBE + submit.getStoreId());
        order.setOriginalPrice(amount);
        order.setPaidPrice(amount);
        order.setActuallyPayPrice(amount);
        order.setOpenid(openid);
        order.setPayType(submit.getPayType().getKey());
        order.setExpireTime(expire);
        order.setOpenid(openid);
        Long total = BigDecimalUtils.yuanToCents(amount);
        if (total > 0) {
            HwcResponse response = swiftPassService.pay(StringUtils.getIp(request), total.toString(), expire,
                    DESCRIBE + submit.getStoreId(), openid, orderNum, submit.getPayType());
            //微信支付下单放回值
            order.setAppId(response.getAppId());
            order.setTimestamp(response.getTimeStamp());
            order.setNonceStr(response.getNonceStr());
            order.setPackageVal(response.getPackageVal());
            order.setSignType(response.getSignType());
            order.setPaySign(response.getPaySign());
            order.setPayState(PayStateEnum.NOTPAY.getKey());
            order.setPayMessage(PayStateEnum.NOTPAY.getValue());
            order.setPayTime(null);
        } else {
            order.setPayState(PayStateEnum.SUCCESS.getKey());
            order.setPayMessage(PayStateEnum.SUCCESS.getValue());
            order.setPayTime(DateUtil.localDateTimeFormat(now.toLocalDateTime(), DateUtil.SDF_YMDHMS));
        }
        orderMapper.insert(order);
        productSnapshotService.saveBatch(snapshots);
        return order;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized OrderInfo generatorOrder(GeneratorOrder criteria) {
        List<ProductInfo> products = new ArrayList<>();
        BigDecimal amount = BigDecimal.ZERO;
        for (ProductOrder productOrder : criteria.getProducts()) {
            Product product = productService.getById(productOrder.getProductId());
            if (product == null) {
                throw new BadRequestException("商品不存在");
            }
            if (product.getStoreId().equals(criteria.getStoreId())) {
                throw new BadRequestException("不支持跨门店下单");
            }
            if (!product.getStatus().equals(ProductStatusEnum.AVAILABLE.getValue())) {
                ProductStatusEnum statusEnum = ProductStatusEnum.get(product.getStatus());
                throw new BadRequestException(product.getName() + ":" + (statusEnum != null ? statusEnum.getReasonPhrase() : "状态"));
            }
            if (productOrder.getCount() > product.getStockQuantity()) {
                throw new BadRequestException("商品库存不足");
            }
            if (productOrder.getCount() < product.getMinPurchaseQuantity()) {
                throw new BadRequestException("起售数量不足");
            }
            ProductInfo info = new ProductInfo();
            info.setProduct(product);
            info.setProductLabels(product.getLabels());
            info.setCount(productOrder.getCount());
            products.add(info);
            amount = BigDecimalUtils.add(amount, BigDecimalUtils.multiply(product.getPrice(), productOrder.getCount()));
        }
        OrderInfo info = new OrderInfo();
        info.setProducts(products);
        info.setAmount(amount);
        info.setPayAmount(amount);
        info.setPromotionAmount(BigDecimal.ZERO);
        info.setUserAddresses(userAddressService.queryUserAddress());
        return info;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order getByOrderNum(String orderNum) {
        return orderMapper.getByOrderNum(orderNum);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccess(Order order) {
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePayStatus(String orderNum, PayStateEnum payState, String payMessage, String payTime) {
        orderMapper.updatePayStatus(orderNum, payState.getKey(), payMessage, payTime);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void closeOrder(String orderNum) {
        Order order = getByOrderNum(orderNum);
        if (order == null) {
            throw new BadRequestException("订单不存在");
        }
        PayTypeEnum anEnum = PayTypeEnum.find(order.getPayType());
        switch (anEnum) {
            case HWC:
            case HWC2:
                JSONObject object = swiftPassService.query(orderNum, anEnum);
                if (object.getString("trade_state").equals(PayStateEnum.SUCCESS.getKey())) {
                    throw new BadRequestException("订单已支付");
                }
                if (object.getString("trade_state").equals(PayStateEnum.CLOSED.getKey())) {
                    throw new BadRequestException("订单已关闭");
                }
                swiftPassService.closeOrder(orderNum, anEnum);
                break;
        }
        orderMapper.updateCloseStatus(orderNum, PayStateEnum.CLOSED.getKey());
    }
    @Override
@@ -68,6 +263,7 @@
            map.put("订单号", order.getOrderNum());
            map.put("用户id", order.getUserId());
            map.put("门店ID", order.getStoreId());
            map.put("门店", order.getStoreName());
            map.put("描述", order.getOrderDescribe());
            map.put("原金额", order.getOriginalPrice());
            map.put("折扣价", order.getPaidPrice());
@@ -79,11 +275,6 @@
            map.put("订单失效时间RFC3339", order.getExpireTime());
            map.put("openid", order.getOpenid());
            map.put("APPID", order.getAppId());
            map.put("时间戳", order.getTimestamp());
            map.put(" nonceStr",  order.getNonceStr());
            map.put(" packageVal",  order.getPackageVal());
            map.put(" signType",  order.getSignType());
            map.put("签名", order.getPaySign());
            map.put("创建人", order.getCreateBy());
            map.put("创建时间", order.getCreateTime());
            map.put("修改者", order.getUpdateBy());