Bläddra i källkod

订单状态推进

yubin 1 vecka sedan
förälder
incheckning
4579f792df
21 ändrade filer med 811 tillägg och 215 borttagningar
  1. 19 0
      mall-service/src/main/java/com/txz/mall/controller/OrderController.java
  2. 1 1
      mall-service/src/main/java/com/txz/mall/controller/PinkController.java
  3. 2 0
      mall-service/src/main/java/com/txz/mall/dao/StoreProductMapper.java
  4. 1 4
      mall-service/src/main/java/com/txz/mall/enums/OrderEventsEnum.java
  5. 1 1
      mall-service/src/main/java/com/txz/mall/enums/PinkOrderStatusEnum.java
  6. 43 0
      mall-service/src/main/java/com/txz/mall/enums/StorePinkStatusEnum.java
  7. 5 0
      mall-service/src/main/java/com/txz/mall/model/StoreCombination.java
  8. 6 1
      mall-service/src/main/java/com/txz/mall/model/StoreOrder.java
  9. 11 0
      mall-service/src/main/java/com/txz/mall/model/StorePinkSummary.java
  10. 6 0
      mall-service/src/main/java/com/txz/mall/model/StoreProduct.java
  11. 1 1
      mall-service/src/main/java/com/txz/mall/service/ProductAttrValueService.java
  12. 9 0
      mall-service/src/main/java/com/txz/mall/service/StoreOrderService.java
  13. 2 1
      mall-service/src/main/java/com/txz/mall/service/StorePinkService.java
  14. 1 1
      mall-service/src/main/java/com/txz/mall/service/StoreProductService.java
  15. 28 28
      mall-service/src/main/java/com/txz/mall/service/impl/ProductAttrValueServiceImpl.java
  16. 73 18
      mall-service/src/main/java/com/txz/mall/service/impl/StoreCombinationServiceImpl.java
  17. 411 77
      mall-service/src/main/java/com/txz/mall/service/impl/StoreOrderServiceImpl.java
  18. 88 8
      mall-service/src/main/java/com/txz/mall/service/impl/StorePinkServiceImpl.java
  19. 69 56
      mall-service/src/main/java/com/txz/mall/service/impl/StorePinkSummaryServiceImpl.java
  20. 31 15
      mall-service/src/main/java/com/txz/mall/service/impl/StoreProductServiceImpl.java
  21. 3 3
      mall-service/src/main/java/com/txz/mall/util/OrderStateMachine.java

+ 19 - 0
mall-service/src/main/java/com/txz/mall/controller/OrderController.java

@@ -163,6 +163,16 @@ public class OrderController {
         return Result.success();
     }
 
+
+    @ApiOperation("定时任务关闭订单测试")
+    @PostMapping("/scheduled/task/close")
+    public Result close() {
+        storeOrderService.scheduledTaskClose();
+        return Result.success();
+    }
+
+
+
     @ApiOperation("取消订单")
     @PostMapping("/cancel")
     public Result cancel(@RequestParam("id") Long id) {
@@ -184,6 +194,15 @@ public class OrderController {
         return Result.success();
     }
 
+
+    @ApiOperation("批量签收目前由定时任务触发")
+    @PostMapping("/batch/signing")
+    public Result batchSigning() {
+        storeOrderService.batchSigning();
+        return Result.success();
+    }
+
+
 //    @ApiOperation(value = "预下单")
 //    @PostMapping(value = "/pre/order")
 //    public Result preOrder(@RequestBody @Validated PreOrderRequest request) {

+ 1 - 1
mall-service/src/main/java/com/txz/mall/controller/PinkController.java

@@ -183,7 +183,7 @@ public class PinkController {
     @ApiOperation(value = "天选")
     @PostMapping(value = "/theSelection")
     public Result theSelection(@RequestParam("id") Long orderId) {
-        storePinkService.theSelection(orderId);
+        storePinkService.theSelection(orderId,new Date());
         return Result.success();
     }
 }

+ 2 - 0
mall-service/src/main/java/com/txz/mall/dao/StoreProductMapper.java

@@ -4,4 +4,6 @@ import com.txz.mall.core.Mapper;
 import com.txz.mall.model.StoreProduct;
 
 public interface StoreProductMapper extends Mapper<StoreProduct> {
+
+
 }

+ 1 - 4
mall-service/src/main/java/com/txz/mall/enums/OrderEventsEnum.java

@@ -3,13 +3,10 @@ package com.txz.mall.enums;
 import java.util.Objects;
 
 /**
- * 订单状态类型枚举
+ * 订单事件类型枚举
  */
 public enum OrderEventsEnum {
 
-
-
-
     GROUP_PURCHASE_PAY(1, "支付订单"),
     GROUP_PURCHASE_CANCEL(2, "取消订单"),
 

+ 1 - 1
mall-service/src/main/java/com/txz/mall/enums/PinkOrderStatusEnum.java

@@ -11,7 +11,7 @@ public enum PinkOrderStatusEnum {
     GROUP_ORDER_CANCELLATION(2, "拼团订单取消"),
 
     GROUP_ORDER_PAID(3, "拼团已支付"),
-    GROUP_ORDER_REFUND(4, "拼团失败已退款"),
+    GROUP_ORDER_REFUND(4, "拼团失败已退款"),   //拼团超时失败  和 拼团成功后用户主动发起退款都会进到这个状态
 
     GROUP_ORDER_TO_SHIP(5, "拼团待发货"),
     GROUP_ORDER_TO_CLOSED(6, "拼团未中奖关闭"),

+ 43 - 0
mall-service/src/main/java/com/txz/mall/enums/StorePinkStatusEnum.java

@@ -0,0 +1,43 @@
+package com.txz.mall.enums;
+
+import java.util.Objects;
+
+/**
+ * 拼团状态
+ */
+public enum StorePinkStatusEnum {
+
+    NOT_DRAWN(1, "未开奖"),
+    RESULTS_ANNOUNCED(2, "已开奖"),
+    LOTTERY_FAILED(3,"开奖失败")
+
+    ;
+
+    private Integer key;
+    private String value;
+
+    StorePinkStatusEnum(Integer key, String value) {
+        this.key = key;
+        this.value = value;
+    }
+
+    public static StorePinkStatusEnum getEnum(Integer inType) {
+        if (inType == null) {
+            return null;
+        }
+        for (StorePinkStatusEnum temp : values()) {
+            if (Objects.equals(temp.key, inType)) {
+                return temp;
+            }
+        }
+        return null;
+    }
+
+    public Integer getKey() {
+        return key;
+    }
+
+    public String getValue() {
+        return value;
+    }
+}

+ 5 - 0
mall-service/src/main/java/com/txz/mall/model/StoreCombination.java

@@ -276,5 +276,10 @@ public class StoreCombination {
     @Column(name = "is_delete")
     private Integer isDelete;
 
+    /**
+     * 数据版本
+     */
+    @Column(name = "version")
+    private Integer version;
 
 }

+ 6 - 1
mall-service/src/main/java/com/txz/mall/model/StoreOrder.java

@@ -390,7 +390,12 @@ public class StoreOrder {
     @Column(name = "out_trade_no")
     private String outTradeNo;
 
+    @ApiModelProperty(value = "签收时间目前是定时任务签收")
+    @Column(name = "signing_time")
+    private Date signingTime;
 
-
+    @ApiModelProperty(value = "发货时间")
+    @Column(name = "delivery_time")
+    private Date deliveryTime;
 
 }

+ 11 - 0
mall-service/src/main/java/com/txz/mall/model/StorePinkSummary.java

@@ -127,8 +127,19 @@ public class StorePinkSummary {
     @Column(name = "is_delete")
     private Integer isDelete;
 
+    @Column(name = "version")
+    private Integer version;
 
 
+
+    public Integer getVersion() {
+        return version;
+    }
+
+    public void setVersion(Integer version) {
+        this.version = version;
+    }
+
     public Integer getPeopleCount() {
         return peopleCount;
     }

+ 6 - 0
mall-service/src/main/java/com/txz/mall/model/StoreProduct.java

@@ -320,4 +320,10 @@ public class StoreProduct {
     @ApiModelProperty("展示图(详情图)")
     private String flatPattern;
 
+
+    @Column(name = "version")
+    @ApiModelProperty("版本")
+    private Integer version;
+
+
 }

+ 1 - 1
mall-service/src/main/java/com/txz/mall/service/ProductAttrValueService.java

@@ -47,5 +47,5 @@ public interface ProductAttrValueService extends Service<ProductAttrValue> {
      * @param operationType 类型:add—添加,sub—扣减
      * @param type          活动类型 0=商品,1=秒杀,2=砍价,3=拼团
      */
-    //void operationStock(Integer id, Integer num, String operationType, Integer type);
+    void operationStock(Integer id, Integer num, String operationType, Integer type);
 }

+ 9 - 0
mall-service/src/main/java/com/txz/mall/service/StoreOrderService.java

@@ -127,6 +127,12 @@ public interface StoreOrderService extends Service<StoreOrder> {
      */
     void close(Long id);
 
+
+    /**
+     * 定时订单关闭
+     */
+    void scheduledTaskClose();
+
     /**
      * 订单取消
      *
@@ -153,4 +159,7 @@ public interface StoreOrderService extends Service<StoreOrder> {
 
     void bindingAddress(StoreOrder storeOrder);
 
+
+    void batchSigning();
+
 }

+ 2 - 1
mall-service/src/main/java/com/txz/mall/service/StorePinkService.java

@@ -5,6 +5,7 @@ import com.txz.mall.model.StoreOrder;
 import com.txz.mall.model.StorePink;
 import vo.StorePinkOngoingVO;
 
+import java.util.Date;
 import java.util.List;
 
 
@@ -34,7 +35,7 @@ public interface StorePinkService extends Service<StorePink> {
      */
   //  void theSelection(String orderId);
 
-    void theSelection(Long spsId);
+    void theSelection(Long spsId, Date date);
     /**
      * 已存在拼团列表
      */

+ 1 - 1
mall-service/src/main/java/com/txz/mall/service/StoreProductService.java

@@ -65,5 +65,5 @@ public interface StoreProductService extends Service<StoreProduct> {
      * @param num  数量
      * @param type 类型:add—添加,sub—扣减
      */
-    void operationStock(Integer id, Integer num, String type);
+    void operationStock(Long id, Integer num, String type);
 }

+ 28 - 28
mall-service/src/main/java/com/txz/mall/service/impl/ProductAttrValueServiceImpl.java

@@ -68,33 +68,33 @@ public class ProductAttrValueServiceImpl extends AbstractService<ProductAttrValu
         return null;
     }
 
-//    @Override
-//    public void operationStock(Integer id, Integer num, String operationType, Integer type) {
-//        UpdateWrapper<ProductAttrValue> updateWrapper = new UpdateWrapper<>();
-//        if ("add".equals(operationType)) {
-//            updateWrapper.setSql(StrUtil.format("stock = stock + {}", num));
-//            updateWrapper.setSql(StrUtil.format("sales = sales - {}", num));
-//            if (type > 0) {
-//                updateWrapper.setSql(StrUtil.format("quota = quota + {}", num));
-//            }
-//        }
-//        if ("sub".equals(operationType)) {
-//            updateWrapper.setSql(StrUtil.format("stock = stock - {}", num));
-//            updateWrapper.setSql(StrUtil.format("sales = sales + {}", num));
-//            if (type > 0) {
-//                updateWrapper.setSql(StrUtil.format("quota = quota - {}", num));
-//                // 扣减时加乐观锁保证库存不为负
-//                updateWrapper.last(StrUtil.format("and (quota - {} >= 0)", num));
-//            } else {
-//                // 扣减时加乐观锁保证库存不为负
-//                updateWrapper.last(StrUtil.format("and (stock - {} >= 0)", num));
-//            }
+    @Override
+    public void operationStock(Integer id, Integer num, String operationType, Integer type) {
+        UpdateWrapper<ProductAttrValue> updateWrapper = new UpdateWrapper<>();
+        if ("add".equals(operationType)) {
+            updateWrapper.setSql(StrUtil.format("stock = stock + {}", num));
+            updateWrapper.setSql(StrUtil.format("sales = sales - {}", num));
+            if (type > 0) {
+                updateWrapper.setSql(StrUtil.format("quota = quota + {}", num));
+            }
+        }
+        if ("sub".equals(operationType)) {
+            updateWrapper.setSql(StrUtil.format("stock = stock - {}", num));
+            updateWrapper.setSql(StrUtil.format("sales = sales + {}", num));
+            if (type > 0) {
+                updateWrapper.setSql(StrUtil.format("quota = quota - {}", num));
+                // 扣减时加乐观锁保证库存不为负
+                updateWrapper.last(StrUtil.format("and (quota - {} >= 0)", num));
+            } else {
+                // 扣减时加乐观锁保证库存不为负
+                updateWrapper.last(StrUtil.format("and (stock - {} >= 0)", num));
+            }
+        }
+        updateWrapper.eq("id", id);
+        updateWrapper.eq("type", type);
+//        boolean update = update(updateWrapper);
+//        if (!update) {
+//            throw new ServiceException("更新商品attrValue失败,attrValueId = " + id);
 //        }
-//        updateWrapper.eq("id", id);
-//        updateWrapper.eq("type", type);
-////        boolean update = update(updateWrapper);
-////        if (!update) {
-////            throw new ServiceException("更新商品attrValue失败,attrValueId = " + id);
-////        }
-//    }
+    }
 }

+ 73 - 18
mall-service/src/main/java/com/txz/mall/service/impl/StoreCombinationServiceImpl.java

@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.txz.mall.core.AbstractService;
 import com.txz.mall.core.ServiceException;
+import com.txz.mall.dao.StoreCombinationMapper;
 import com.txz.mall.model.StoreCombination;
 import com.txz.mall.model.StoreFlashActivity;
 import com.txz.mall.model.StoreProduct;
@@ -17,10 +18,12 @@ import lombok.AllArgsConstructor;
 import org.springframework.beans.BeanUtils;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.ObjectUtils;
 import tk.mybatis.mapper.entity.Condition;
 import tk.mybatis.mapper.entity.Example;
 import vo.FlashActivityVO;
 
+import javax.annotation.Resource;
 import java.util.Date;
 import java.util.List;
 import java.util.stream.Collectors;
@@ -123,31 +126,83 @@ public class StoreCombinationServiceImpl extends AbstractService<StoreCombinatio
         return combinationList.get(0);
     }
 
+    @Resource
+    private StoreCombinationMapper storeCombinationMapper;
+
     @Override
     public synchronized void operationStock(Long id, Integer num, String type) {
         StoreCombination combination = findById(id);
-        UpdateWrapper<StoreCombination> updateWrapper = new UpdateWrapper<>();
+       if(ObjectUtils.isEmpty(combination)){
+           throw new ServiceException("拼团活动不存在id:" + id);
+       }
+
+        StoreCombination storeCombinationForUpdate = new StoreCombination();
         if ("add".equals(type)) {
-            combination.setSales(combination.getNum() - num);
-            combination.setStock(combination.getStock() + num);
-            combination.setQuota(combination.getQuota() + num);
+
+            int sales = combination.getSales() - num;
+            int stock = combination.getStock() + num;
+            int quota = combination.getQuota() + num;
+            if(sales<0){
+                throw new ServiceException("拼团活动m_store_combination销量扣减为负数id:"+id);
+            }
+
+            storeCombinationForUpdate.setSales(sales);
+            storeCombinationForUpdate.setStock(stock);
+            storeCombinationForUpdate.setQuota(quota);
         }
         if ("sub".equals(type)) {
-            combination.setStock(combination.getStock() - num);
-            combination.setSales(combination.getSales() + num);
-            combination.setQuota(combination.getQuota() - num);
-
-            Condition condition = new Condition(StoreCombination.class);
-            Example.Criteria criteria = condition.createCriteria();
-            criteria.andEqualTo("id", id);
-            criteria.andGreaterThanOrEqualTo("quota", num);
-            criteria.andEqualTo("isDelete", 0);
-            criteria.andGreaterThanOrEqualTo("stock", num);
-            List<StoreCombination> combinationList = findByCondition(condition);
-            if (CollectionUtils.isEmpty(combinationList)) {
-                throw new ServiceException("更新拼团商品库存失败,商品id = " + id + ",库存不足");
+
+            int sales = combination.getSales() + num;
+            int stock = combination.getStock() - num;
+            int quota = combination.getQuota() - num;
+            if(stock<0){
+                throw new ServiceException("拼团活动m_store_combination.stock扣减为负数id:"+id);
+            }
+            if(quota<0){
+                throw new ServiceException("拼团活动m_store_combination.quota扣减为负数id:"+id);
             }
+
+            storeCombinationForUpdate.setSales(sales);
+            storeCombinationForUpdate.setStock(stock);
+            storeCombinationForUpdate.setQuota(quota);
+
+        }
+        storeCombinationForUpdate.setVersion(combination.getVersion()+1);
+        Example example = new Example(StoreCombination.class);
+        example.createCriteria().andEqualTo("id",id).andEqualTo("version",combination.getVersion());
+        int i = storeCombinationMapper.updateByConditionSelective(storeCombinationForUpdate, example);
+        if(!(i==1)){
+            throw new ServiceException("StoreCombination库存操作失败id:"+id);
         }
-        update(combination);
+
     }
+
+
+//    @Override
+//    public synchronized void operationStock(Long id, Integer num, String type) {
+//        StoreCombination combination = findById(id);
+//        UpdateWrapper<StoreCombination> updateWrapper = new UpdateWrapper<>();
+//        if ("add".equals(type)) {
+//            combination.setSales(combination.getNum() - num);
+//            combination.setStock(combination.getStock() + num);
+//            combination.setQuota(combination.getQuota() + num);
+//        }
+//        if ("sub".equals(type)) {
+//            combination.setSales(combination.getSales() + num);
+//            combination.setStock(combination.getStock() - num);
+//            combination.setQuota(combination.getQuota() - num);
+//
+//            Condition condition = new Condition(StoreCombination.class);
+//            Example.Criteria criteria = condition.createCriteria();
+//            criteria.andEqualTo("id", id);
+//            criteria.andGreaterThanOrEqualTo("quota", num);
+//            criteria.andEqualTo("isDelete", 0);
+//            criteria.andGreaterThanOrEqualTo("stock", num);
+//            List<StoreCombination> combinationList = findByCondition(condition);
+//            if (CollectionUtils.isEmpty(combinationList)) {
+//                throw new ServiceException("更新拼团商品库存失败,商品id = " + id + ",库存不足");
+//            }
+//        }
+//        update(combination);
+//    }
 }

+ 411 - 77
mall-service/src/main/java/com/txz/mall/service/impl/StoreOrderServiceImpl.java

@@ -16,6 +16,7 @@ import com.github.pagehelper.PageInfo;
 import com.txz.cif.dto.AccountDTO;
 import com.txz.cif.dto.Result;
 import com.txz.cif.dto.UserDTO;
+import com.txz.cif.param.AccomplishParam;
 import com.txz.cif.param.JoinParam;
 import com.txz.cif.param.OpenParam;
 import com.txz.mall.constants.Constants;
@@ -25,10 +26,12 @@ import com.txz.mall.core.ResultCode;
 import com.txz.mall.core.ServiceException;
 import com.txz.mall.dao.StoreOrderMapper;
 import com.txz.mall.dao.StorePinkMapper;
+import com.txz.mall.dao.StorePinkSummaryMapper;
 import com.txz.mall.dubbo.client.CifAccountDubboServiceClient;
 import com.txz.mall.dubbo.client.CifUserDubboServiceClient;
 import com.txz.mall.enums.OrderEventsEnum;
 import com.txz.mall.enums.PinkOrderStatusEnum;
+import com.txz.mall.enums.StorePinkStatusEnum;
 import com.txz.mall.model.*;
 import com.txz.mall.service.*;
 import com.txz.mall.util.EasyExcelUtil;
@@ -38,6 +41,7 @@ import com.txz.mall.util.OrderUtils;
 import dto.*;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.AllArgsConstructor;
+import lombok.Data;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang.time.DateUtils;
 import org.apache.commons.lang3.StringEscapeUtils;
@@ -220,7 +224,7 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
         storePinkSummary.setIsRefund(0);
 
 
-        EasyToUseUtil.appCreateAssignment(date,storePinkSummary);
+        EasyToUseUtil.appCreateAssignment(date, storePinkSummary);
         storePinkSummaryService.save(storePinkSummary);
 
         //插入拼团详情表
@@ -275,8 +279,6 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
 //    }
 
 
-
-
     @Override
     public void goPink(GoPinkDTO dto) {
         Date date = new Date();
@@ -317,11 +319,11 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
 //            if (uidList.contains(dto.getUserId())) {
 //                throw new ServiceException("重复拼团");
 //            }
-            joinGroup(teamPink, dto, count,pinkList.size());
+            joinGroup(teamPink, dto, count, pinkList.size());
         }
     }
 
-    private void joinGroup(StorePink teamPink, GoPinkDTO dto, int count,int pinkSize) {
+    private void joinGroup(StorePink teamPink, GoPinkDTO dto, int count, int pinkSize) {
         //拼团剩余人数
         Date date = new Date();
 
@@ -340,8 +342,8 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
         BeanUtils.copyProperties(teamPink, storePink);
         storePink.setId(null);
         storePink.setSpsId(dto.getSpsId());
-            storePink.setOrderId(dto.getOrderId());
-            storePink.setOrderIdKey(dto.getOrderIdKey());
+        storePink.setOrderId(dto.getOrderId());
+        storePink.setOrderIdKey(dto.getOrderIdKey());
         storePink.setUid(dto.getUserId());
         storePink.setStatus(1);
         storePink.setOrderStatus(PinkOrderStatusEnum.GROUP_ORDER_TO_PAY.getKey());
@@ -400,18 +402,19 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
         }
 
         List<Long> storePinkSummaryId = pinkSummaryList.stream().map(StorePinkSummary::getId).collect(Collectors.toList());
-        log.info("storePinkSummaryId:"+storePinkSummaryId.toString());
+        log.info("storePinkSummaryId:" + storePinkSummaryId.toString());
         Condition pinkCondition = new Condition(StorePink.class);
         Example.Criteria pinkCriteria = pinkCondition.createCriteria();
         pinkCriteria.andEqualTo("isDelete", 0);
         pinkCriteria.andEqualTo("cid", dto.getCid());
-//        pinkCriteria.andEqualTo("status", 1);
-        pinkCriteria.andIn("spsId",storePinkSummaryId);
+        List<Integer> orderStatusList = CollUtil.newArrayList(PinkOrderStatusEnum.GROUP_ORDER_TO_PAY.getKey(), PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey());
+        pinkCriteria.andIn("orderStatus", orderStatusList);
+        pinkCriteria.andIn("spsId", storePinkSummaryId);
         List<StorePink> pinkList = storePinkService.findByCondition(pinkCondition);
-        log.info("pinkList:"+pinkList.toString());
+        log.info("pinkList:" + pinkList.toString());
 
         Map<Long, List<StorePink>> collect = pinkList.stream().collect(Collectors.groupingBy(StorePink::getSpsId));
-        log.info("collect:"+collect.toString());
+        log.info("collect:" + collect.toString());
 //记得将重复拼团校验放开
 //        List<List<StorePink>> availableGroups = collect.values().stream()
 //                .filter(list -> !list.stream().map(StorePink::getUid).collect(Collectors.toList()).contains(dto.getUserId()))
@@ -422,7 +425,7 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
                 .filter(list -> true)
                 .collect(Collectors.toList());
 
-        log.info("availableGroups:"+availableGroups.toString());
+        log.info("availableGroups:" + availableGroups.toString());
         // 如果没有用户未参与的拼团,直接返回,让调用方处理创建新团的逻辑
         if (CollUtil.isEmpty(availableGroups)) {
             throw new ServiceException("所有的团均已参加");
@@ -433,25 +436,25 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
 //                .orElse(Collections.emptyList());
         //随机挑选一个拼团去参加
         Random random = new Random();
-        int num = random.nextInt(availableGroups.size()) ;  //  生成 可用列表随机下标的整数有效增加并发量
-        log.info("randomNum:"+num);
+        int num = random.nextInt(availableGroups.size());  //  生成 可用列表随机下标的整数有效增加并发量
+        log.info("randomNum:" + num);
         List<StorePink> maxPinkList = availableGroups.get(num);
-        log.info("maxPinkList:"+maxPinkList.toString());
+        log.info("maxPinkList:" + maxPinkList.toString());
         if (CollectionUtils.isNotEmpty(maxPinkList)) {
             List<Long> uidList = maxPinkList.stream().map(StorePink::getUid).collect(Collectors.toList());
             //记得将重复拼团校验放开
-          //  if (!uidList.contains(dto.getUserId())) {
-                //团长
-                StorePink pink = maxPinkList.stream().filter(i -> i.getKId().equals(0)).collect(Collectors.toList()).get(0);
-                int count = pink.getPeople() - (CollUtil.isEmpty(maxPinkList) ? 0 : maxPinkList.size());
-            log.info("count:"+count);
-                if (count > 0) {
-                    dto.setSpsId(pink.getSpsId()); //拼团汇总表id
-                    joinGroup(pink, dto, count,pinkList.size());
-                }else{
-                    throw new ServiceException("拼团人数超员请重新发起拼团 pinkid:"+pink.getId());
-                }
-          //  }
+            //  if (!uidList.contains(dto.getUserId())) {
+            //团长
+            StorePink pink = maxPinkList.stream().filter(i -> i.getKId().equals(0)).collect(Collectors.toList()).get(0);
+            int count = pink.getPeople() - (CollUtil.isEmpty(maxPinkList) ? 0 : maxPinkList.size());
+            log.info("count:" + count);
+            if (count > 0) {
+                dto.setSpsId(pink.getSpsId()); //拼团汇总表id
+                joinGroup(pink, dto, count, pinkList.size());
+            } else {
+                throw new ServiceException("拼团人数超员请重新发起拼团 pinkid:" + pink.getId());
+            }
+            //  }
         }
     }
 
@@ -517,8 +520,58 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
         }
     }
 
+    /**
+     * 山哥说批量发货要能支持5000条数据这块得设计成异步处理,不然性能扛不住
+     */
+
     @Override
     public void batchDelivery(List<StoreOrderDeliveryDTO> dto) {
+        if(CollectionUtils.isEmpty(dto)){
+            throw new ServiceException("批量发货入参为空dto:"+dto);
+        }
+        List<String> orderIdList = dto.stream().map(StoreOrderDeliveryDTO::getOrderId).collect(Collectors.toList());
+        if(CollectionUtils.isEmpty(orderIdList)){
+            throw new ServiceException("批量发货订单orderid为空orderIdList:"+orderIdList);
+        }
+        if(dto.size()>500){
+            throw new ServiceException("1次批量发货订单不要超过500条");
+        }
+
+        Condition condition = new Condition(StoreOrder.class);
+        Example.Criteria criteria = condition.createCriteria();
+        criteria.andIn("orderId", orderIdList);
+        criteria.andEqualTo("isDelete", 0);
+        List<StoreOrder> storeOrderList = findByCondition(condition);
+        if(CollectionUtils.isEmpty(storeOrderList)){
+            throw new ServiceException("批量发货订单订单列表不存在:"+storeOrderList);
+        }
+        Map<String, StoreOrderDeliveryDTO> storeOrderDeliveryMap = dto.stream().collect(Collectors.toMap(StoreOrderDeliveryDTO::getOrderId, a -> a, (b, c) -> b));
+        for (StoreOrder storeOrder : storeOrderList) {
+            StoreOrderDeliveryDTO storeOrderDeliveryDTO = storeOrderDeliveryMap.get(storeOrder.getOrderId());
+            PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_DELIVER, null);
+            if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
+                throw new ServiceException("当前状态不支持发货storeOrder:"+storeOrder.toString());
+            }
+            Date date = DateUtil.date();
+            StoreOrder storeOrderForUpdate = new StoreOrder();
+            storeOrderForUpdate.setStatus(pinkOrderStatusEnum.getKey());
+            storeOrderForUpdate.setDeliveryName(storeOrderDeliveryDTO.getDeliveryName());
+            storeOrderForUpdate.setDeliveryCode(storeOrderDeliveryDTO.getDeliveryNo());
+            storeOrderForUpdate.setDeliveryTime(date);
+
+            Example example = new Example(StoreOrder.class);
+            example.createCriteria().andEqualTo("orderId",storeOrder.getOrderId());
+            storeOrderMapper.updateByConditionSelective(storeOrderForUpdate,example);
+            storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_STATUS_DELIVERY_ORDER, "订单发货");
+
+            //维护拼团订单状态
+            StorePink storePinkForUpdate = new StorePink();
+            storePinkForUpdate.setOrderStatus(pinkOrderStatusEnum.getKey());
+            Example exampleStorePink = new Example(StorePink.class);
+            exampleStorePink.createCriteria().andEqualTo("orderId",storeOrder.getOrderId());
+            storePinkMapper.updateByConditionSelective(storePinkForUpdate,exampleStorePink);
+
+        }
 
     }
 
@@ -1132,7 +1185,10 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
             Condition addressCondition = new Condition(UserAddress.class);
             Example.Criteria addressCriteria = addressCondition.createCriteria();
             addressCriteria.andEqualTo("isDelete", 0);
-            addressCriteria.andIn("id", list.stream().map(StoreOrder::getAddressId).filter(Objects::nonNull).collect(Collectors.toList()));
+            List<Long> collect = list.stream().map(StoreOrder::getAddressId).filter(Objects::nonNull).collect(Collectors.toList());
+           if(!org.springframework.util.CollectionUtils.isEmpty(collect)){
+            addressCriteria.andIn("id", collect);
+           }
             addressList = userAddressService.findByCondition(addressCondition);
         }
         List<StoreOrderInfo> finalInfoArrayList = infoArrayList;
@@ -1152,10 +1208,10 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
     }
 
     /**
-     *  @ApiModelProperty(value = "类型 0-全部all  1-待支付topay 2-拼团成功success 3-拼团失败failed 4-拼团奖励reward")
-     *     private Integer type;
-     *     ****************************
-     *GROUP_ORDER_TO_PAY(1, "拼团待支付"),
+     * @ApiModelProperty(value = "类型 0-全部all  1-待支付topay 2-拼团成功success 3-拼团失败failed 4-拼团奖励reward")
+     * private Integer type;
+     * ****************************
+     * GROUP_ORDER_TO_PAY(1, "拼团待支付"),
      * GROUP_ORDER_CANCELLATION(2, "拼团订单取消"),
      * GROUP_ORDER_PAID(3, "拼团已支付"),
      * GROUP_ORDER_REFUND(4, "拼团失败已退款"),
@@ -1163,8 +1219,8 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
      * GROUP_ORDER_TO_CLOSED(6, "拼团未中奖关闭"),
      * GROUP_ORDER_TO_RECEVIE(7, "拼团待收货"),
      * GROUP_ORDER_COMPLETED(8, "拼团订单完成")
-     *     *****************************
-     *  `status` tinyint unsigned NOT NULL DEFAULT '1' COMMENT '状态  1进行中  2已完成  3未完成',
+     * *****************************
+     * `status` tinyint unsigned NOT NULL DEFAULT '1' COMMENT '状态  1进行中  2已完成  3未完成',
      */
     @Override
     public List<StoreOrderVO> appList(StoreOrderAppDTO dto) {
@@ -1209,7 +1265,7 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
                 break;
             case 4:
                 pinkCriteria.andEqualTo("status", 2);
-                pinkCriteria.andIn("orderStatus", Arrays.asList(5,7,8));
+                pinkCriteria.andIn("orderStatus", Arrays.asList(5, 7, 8));
                 pinkList = storePinkService.findByCondition(pinkCondition);
                 if (CollUtil.isNotEmpty(pinkList)) {
                     criteria.andIn("id", pinkList.stream().map(StorePink::getOrderIdKey).collect(Collectors.toList()));
@@ -1462,7 +1518,7 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
         storeOrder.setMark(StringEscapeUtils.escapeHtml4(request.getMark()));
         storeOrder.setCombinationId(orderInfoVo.getCombinationId());
         storeOrder.setPinkId(orderInfoVo.getPinkId());
-      //  storeOrder.setBargainUserId(orderInfoVo.getBargainUserId());
+        //  storeOrder.setBargainUserId(orderInfoVo.getBargainUserId());
         storeOrder.setCreateTime(new Date());
         storeOrder.setShippingType(request.getShippingType());
         storeOrder.setIsChannel(isChannel);
@@ -1487,17 +1543,17 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
             // 拼团商品扣库存
             storeCombinationService.operationStock(skuRecord.getLong("activityId"), skuRecord.getInt("num"), "sub");
             // 拼团商品规格扣库存
-        //**    productAttrValueService.operationStock(skuRecord.getInt("activityAttrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_PINGTUAN);
+            //   productAttrValueService.operationStock(skuRecord.getInt("activityAttrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_PINGTUAN);
             // 普通商品口库存
-            storeProductService.operationStock(skuRecord.getInt("productId"), skuRecord.getInt("num"), "sub");
+            storeProductService.operationStock(skuRecord.getLong("productId"), skuRecord.getInt("num"), "sub");
             // 普通商品规格扣库存
-         //**   productAttrValueService.operationStock(skuRecord.getInt("attrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_NORMAL);
+            //**   productAttrValueService.operationStock(skuRecord.getInt("attrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_NORMAL);
         } else { // 普通商品
             for (MyRecord skuRecord : skuRecordList) {
                 // 普通商品口库存
-                storeProductService.operationStock(skuRecord.getInt("productId"), skuRecord.getInt("num"), "sub");
+                storeProductService.operationStock(skuRecord.getLong("productId"), skuRecord.getInt("num"), "sub");
                 // 普通商品规格扣库存
-         //**   productAttrValueService.operationStock(skuRecord.getInt("attrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_NORMAL);
+                //**   productAttrValueService.operationStock(skuRecord.getInt("attrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_NORMAL);
             }
         }
 
@@ -1530,7 +1586,6 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
         }
 
 
-
 //        // 生成订单日志
         storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_STATUS_CREATE_ORDER, "订单生成");
 //
@@ -1541,8 +1596,6 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
 //        return Boolean.TRUE;
 
 
-
-
         // 删除缓存订单
         if (redisUtil.hasKey(key)) {
             redisUtil.del(key);
@@ -1560,9 +1613,20 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
     @Transactional(propagation = Propagation.REQUIRED)
     public Boolean goPay(GoPinkDTO dto) {
         StoreOrder storeOrder = findBy("orderId", dto.getOrderId());
-        if(ObjectUtils.isEmpty(storeOrder)){
-            throw new ServiceException("订单为空orderId:"+dto.getOrderId());
+        if (ObjectUtils.isEmpty(storeOrder)) {
+            throw new ServiceException("订单为空orderId:" + dto.getOrderId());
         }
+        if (storeOrder.getStatus().equals(PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey())) {
+            throw new ServiceException("订单已支付orderId:" + dto.getOrderId());
+        }
+
+        PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_PAY, null);
+
+        if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
+            throw new ServiceException("当前状态不支持去支持去支付orderId:" + dto.getOrderId());
+        }
+
+
         // 检验余额够不够
         Result result = accountDubboServiceClient.getWalletAccount(storeOrder.getUid());
         if (result.getCode().equals(ResultCode.SUCCESS.getCode())) {
@@ -1584,10 +1648,10 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
             openParam.setTransTime(new Date());
 
             //
-          //  accountDubboServiceClient.openGroup(openParam);
-            updateOrderStatus(storeOrder.getId(), PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey());
-            storePinkService.pinkSuccess(storeOrder.getPinkId(),storeOrder);
-           // goOpen(dto.getOrderId());
+            //  accountDubboServiceClient.openGroup(openParam);
+            updateOrderStatus(storeOrder.getId(), pinkOrderStatusEnum.getKey());
+            storePinkService.pinkSuccess(storeOrder.getPinkId(), storeOrder);
+            // goOpen(dto.getOrderId());
         }
         if ("join".equals(dto.getType())) {
             JoinParam joinParam = new JoinParam();
@@ -1596,45 +1660,190 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
             joinParam.setUserId(storeOrder.getUid());
             joinParam.setAmount(storeOrder.getPayPrice());
             joinParam.setTransTime(new Date());
-           // accountDubboServiceClient.joinGroup(joinParam);
-            updateOrderStatus(storeOrder.getId(), PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey());
-            storePinkService.pinkSuccess(storeOrder.getPinkId(),storeOrder);
-           // goPink(dto);
+            // accountDubboServiceClient.joinGroup(joinParam);
+            updateOrderStatus(storeOrder.getId(), pinkOrderStatusEnum.getKey());
+            storePinkService.pinkSuccess(storeOrder.getPinkId(), storeOrder);
+            // goPink(dto);
         }
         return true;
     }
 
+
+    //这是由pc端发起端针对个人的主动退款 不是定时任务扫描活动超时导致的退款,所以这个退款是不影响其他拼团成员的。拼团汇总表也不会上锁,拼团状态仍然是进行中
     @Override
     public void refund(Long id) {
         StoreOrder storeOrder = findById(id);
-//        if (storeOrder.getPaid().equals(Constants.ORDER_STATUS_H5_UNPAID)) {
+////        if (storeOrder.getPaid().equals(Constants.ORDER_STATUS_H5_UNPAID)) {
+////            throw new ServiceException("当前状态不支持退款");
+////        }
+//
+//        PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_APPLY_REFUND, null);
+//
+//        if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
 //            throw new ServiceException("当前状态不支持退款");
 //        }
+//        updateOrderStatus(storeOrder.getId(), PinkOrderStatusEnum.GROUP_ORDER_REFUND.getKey());
+//
+//        // 归还用户余额
+        //  accountDubboServiceClient.refund(id.toString(), storeOrder.getOrderId(), storeOrder.getPayPrice());
+//        // 库存增加
+//        storeCombinationService.operationStock(storeOrder.getCombinationId(), storeOrder.getTotalNum(), "add");
+//
+//
+        if (ObjectUtils.isEmpty(storeOrder)) {
+            throw new ServiceException("订单主动退款时订单不存在id:" + id);
+        }
 
-        PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_APPLY_REFUND, null);
-
+        PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_FAIL, null);
         if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
-            throw new ServiceException("当前状态不支持退款");
+            throw new ServiceException("当前状态不支持退款关闭id:"+id);
+        }
+
+        StorePink storePink = storePinkService.findById(storeOrder.getPinkId());
+        // 批量退款接口调用 这块要前置,退款成功后再去改状态
+        if (ObjectUtils.isEmpty(storePink)) {
+            throw new ServiceException("拼团时间过期关闭时时拼团信息不存在ID:" + storeOrder.getPinkId());
         }
-        updateOrderStatus(storeOrder.getId(), PinkOrderStatusEnum.GROUP_ORDER_REFUND.getKey());
 
-        // 归还用户余额
-//        accountDubboServiceClient.refund(id.toString(), storeOrder.getOrderId(), storeOrder.getPayPrice());
-        // 库存增加
-        storeCombinationService.operationStock(storeOrder.getCombinationId(), storeOrder.getTotalNum(), "add");
+        Date date = new Date();
+        //主动退款
+        AccomplishParam param = new AccomplishParam();
+        param.setBizNo(storeOrder.getOrderId());
+        param.setBizId(storeOrder.getId().toString());
+        List<Long> userIds = CollUtil.newArrayList();
+        param.setUserIds(userIds);
+        param.setAmount(storePink.getTotalPrice());
+        param.setTransTime(date);
+//        Result result = accountDubboServiceClient.accomplishGroup(param);
+//        boolean equals = result.getCode().equals("200");
+//        if(!equals){
+//            throw new ServiceException("退款失败请重新发起");
+//        }
+        updateOrderStatus(storeOrder.getId(), pinkOrderStatusEnum.getKey());
+        //订单状态回退
+        //拼团状态回退
+
+        StorePink storePinkForUpdate = new StorePink();
+        storePinkForUpdate.setId(storeOrder.getPinkId());
+        // storePinkForUpdate.setStatus(StorePinkStatusEnum.LOTTERY_FAILED.getKey());   //定时任务触发的拼团失败导致的订单退款需要设置这个状态为拼团失败状态
+        storePinkForUpdate.setOrderStatus(pinkOrderStatusEnum.getKey());
+        storePinkService.update(storePinkForUpdate);
+        //拼团汇总数量维护以及锁单标识维护
+        Boolean b = storePinkSummaryService.maintainQuantityStatusOfTheStorePinkSummary(storePink.getSpsId());
+        //拼团商品数量以及m_store_combination
+        storeCombinationService.operationStock(storePink.getCid(), storePink.getTotalNum(), "add");
+        // 拼团商品规格扣库存
+        //   productAttrValueService.operationStock(skuRecord.getInt("activityAttrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_PINGTUAN);
+        // 普通商品口库存
+        storeProductService.operationStock(storePink.getPid(), storePink.getTotalNum(), "add");
+
+
+
     }
 
 
-    // 中奖回收状态逻辑还没加    关闭指系统层面的自动结束  如活动时间超时或者拼团超时由定时任务触发
+    //    关闭指系统层面的自动结束  如活动时间超时或者拼团超时由定时任务触发  不暴露给客户端
     @Override
     public void close(Long id) {
-        StoreOrder storeOrder = findById(id);
-        PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_NOT_WIN, null);
 
-        if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
-            throw new ServiceException("当前状态不支持关闭");
+
+        // PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_FAIL, null);
+//        if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
+//            throw new ServiceException("当前状态不支持关闭");
+//        }
+
+        try {
+
+            StoreOrder storeOrder = findById(id);
+            if (ObjectUtils.isEmpty(storeOrder)) {
+                throw new ServiceException("订单不存在id:" + id);
+            }
+
+            if (PinkOrderStatusEnum.GROUP_ORDER_TO_PAY.getKey().equals(storeOrder.getStatus())) {
+                //如果是待支付状态   状态推到取消状态
+                // cancel(id);
+                PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_CANCEL, null);
+
+                if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
+                    throw new ServiceException("当前状态不支持取消");
+                }
+                //订单状态回退
+                updateOrderStatus(storeOrder.getId(), pinkOrderStatusEnum.getKey());
+
+                //拼团状态回退
+                StorePink storePink = storePinkService.findById(storeOrder.getPinkId());
+                if (ObjectUtils.isEmpty(storePink)) {
+                    throw new ServiceException("订单取消时拼团信息不存在ID:" + storeOrder.getPinkId());
+                }
+                StorePink storePinkForUpdate = new StorePink();
+                storePinkForUpdate.setId(storeOrder.getPinkId());
+                storePinkForUpdate.setStatus(StorePinkStatusEnum.LOTTERY_FAILED.getKey());
+                storePinkForUpdate.setOrderStatus(pinkOrderStatusEnum.getKey());
+                storePinkService.update(storePinkForUpdate);
+                //拼团汇总数量维护以及锁单标识维护
+                Boolean b = storePinkSummaryService.maintainQuantityStatusOfTheStorePinkSummary(storePink.getSpsId());
+                //拼团商品数量以及m_store_combination
+                storeCombinationService.operationStock(storePink.getCid(), storePink.getTotalNum(), "add");
+                // 拼团商品规格扣库存
+                //   productAttrValueService.operationStock(skuRecord.getInt("activityAttrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_PINGTUAN);
+                // 普通商品口库存
+                storeProductService.operationStock(storePink.getPid(), storePink.getTotalNum(), "add");
+
+
+            } else if (PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey().equals(storeOrder.getStatus())) {
+
+                PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_FAIL, null);
+                if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
+                    throw new ServiceException("当前状态不支持退款关闭");
+                }
+
+                //订单状态回退
+                //拼团状态回退
+                StorePink storePink = storePinkService.findById(storeOrder.getPinkId());
+
+                if (ObjectUtils.isEmpty(storePink)) {
+                    throw new ServiceException("主动发起退款时拼团信息不存在ID:" + storeOrder.getPinkId());
+                }
+
+                Date date = new Date();
+                //主动退款
+                AccomplishParam param = new AccomplishParam();
+                param.setBizNo(storeOrder.getOrderId());
+                param.setBizId(storeOrder.getId().toString());
+                List<Long> userIds = CollUtil.newArrayList();
+                param.setUserIds(userIds);
+                param.setAmount(storePink.getTotalPrice());
+                param.setTransTime(date);
+//        Result result = accountDubboServiceClient.accomplishGroup(param);
+//        boolean equals = result.getCode().equals("200");
+//        if(!equals){
+//            throw new ServiceException("退款失败请重新发起");
+//        }
+
+                updateOrderStatus(storeOrder.getId(), pinkOrderStatusEnum.getKey());
+
+                StorePink storePinkForUpdate = new StorePink();
+                storePinkForUpdate.setId(storeOrder.getPinkId());
+                storePinkForUpdate.setStatus(StorePinkStatusEnum.LOTTERY_FAILED.getKey());   //定时任务触发的拼团失败导致的订单退款需要设置这个状态为拼团失败状态
+                storePinkForUpdate.setOrderStatus(pinkOrderStatusEnum.getKey());
+                storePinkService.update(storePinkForUpdate);
+                //拼团汇总数量维护以及锁单标识维护
+                Boolean b = storePinkSummaryService.maintainQuantityStatusOfTheStorePinkSummary(storePink.getSpsId());
+                //拼团商品数量以及m_store_combination
+                storeCombinationService.operationStock(storePink.getCid(), storePink.getTotalNum(), "add");
+                // 拼团商品规格扣库存
+                //   productAttrValueService.operationStock(skuRecord.getInt("activityAttrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_PINGTUAN);
+                // 普通商品口库存
+                storeProductService.operationStock(storePink.getPid(), storePink.getTotalNum(), "add");
+
+            } else {
+                throw new ServiceException("当前状态不支持退款关闭:id"+id);
+            }
+        }catch (Exception e){
+            log.error("定时任务关单处理失败订单id:"+id,e);
         }
-        updateOrderStatus(storeOrder.getId(), pinkOrderStatusEnum.getKey());
+
+        //如果是已支付状态状态推到拼团失败退款状态
 
 
 //        if (storeOrder.getStatus().equals(Constants.ORDER_STATUS_H5_COMPLETE)) {
@@ -1644,15 +1853,87 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
 //        }
     }
 
+    @Resource
+    private StorePinkSummaryMapper storePinkSummaryMapper;
+    @Override
+    public void scheduledTaskClose() {
+
+        Date date = new Date();
+        PageHelper.startPage(1, 10);
+        Condition pinkSummaryCondition = new Condition(StorePinkSummary.class);
+        Example.Criteria pinkSummaryCriteria = pinkSummaryCondition.createCriteria();
+        pinkSummaryCriteria.andEqualTo("isDelete", 0);
+        pinkSummaryCriteria.andEqualTo("status", StorePinkStatusEnum.NOT_DRAWN.getKey());
+        pinkSummaryCriteria.andLessThanOrEqualTo("stopTime",date);
+        List<StorePinkSummary> byCondition = storePinkSummaryService.findByCondition(pinkSummaryCondition);
+        //先锁定汇总表防止有新的成员加入进来,
+
+
+        if(!CollectionUtils.isEmpty(byCondition)){
+            List<Long> storePinkSummaryidList = byCondition.stream().map(StorePinkSummary::getId).collect(Collectors.toList());
+
+            Condition condition = new Condition(StorePink.class);
+            Example.Criteria criteria = condition.createCriteria();
+            criteria.andIn("spsId", storePinkSummaryidList);
+
+            criteria.andEqualTo("isDelete", 0);
+             //找出拼团待支付 和 拼团已支付的数据进行 关闭
+            List<Integer> statusList = CollUtil.newArrayList(
+                    PinkOrderStatusEnum.GROUP_ORDER_TO_PAY.getKey()
+                    ,PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey()
+            );
+            criteria.andIn("orderStatus",statusList);
+
+            List<StorePink> storePinkListForUpdate = storePinkService.findByCondition(condition);
+            if(!CollectionUtils.isEmpty(storePinkListForUpdate)){
+                storePinkListForUpdate.forEach(a->
+                        close(a.getOrderIdKey())
+                );
+            }
+        }
+
+
+    }
+
     @Override
     public void cancel(Long id) {
         StoreOrder storeOrder = findById(id);
+        if (ObjectUtils.isEmpty(storeOrder)) {
+            throw new ServiceException("订单取消时订单不存在id:" + id);
+        }
         PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_CANCEL, null);
 
         if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
             throw new ServiceException("当前状态不支持取消");
         }
-        updateOrderStatus(storeOrder.getId(), PinkOrderStatusEnum.GROUP_ORDER_CANCELLATION.getKey());
+
+        //订单状态回退
+        updateOrderStatus(storeOrder.getId(), pinkOrderStatusEnum.getKey());
+
+
+        //拼团状态回退
+        StorePink storePink = storePinkService.findById(storeOrder.getPinkId());
+        if (ObjectUtils.isEmpty(storePink)) {
+            throw new ServiceException("订单取消时拼团信息不存在ID:" + storeOrder.getPinkId());
+        }
+        StorePink storePinkForUpdate = new StorePink();
+        storePinkForUpdate.setId(storeOrder.getPinkId());
+        storePinkForUpdate.setOrderStatus(pinkOrderStatusEnum.getKey());
+        storePinkService.update(storePinkForUpdate);
+
+        //拼团汇总数量维护以及锁单标识维护
+
+        Boolean b = storePinkSummaryService.maintainQuantityStatusOfTheStorePinkSummary(storePink.getSpsId());
+
+        //拼团商品数量以及m_store_combination
+
+        storeCombinationService.operationStock(storePink.getCid(), storePink.getTotalNum(), "add");
+        // 拼团商品规格扣库存
+        //   productAttrValueService.operationStock(skuRecord.getInt("activityAttrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_PINGTUAN);
+        // 普通商品口库存
+        storeProductService.operationStock(storePink.getPid(), storePink.getTotalNum(), "add");
+
+        //库存数量回退
 
 //        if (storeOrder.getPaid().equals(0)) {
 //            updateOrderStatus(storeOrder.getId(), PinkOrderStatusEnum.CANCEL.getKey());
@@ -1693,8 +1974,8 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
                 storeOrder.setDeliveryId(po.getDeliveryId());
                 storeOrder.setDeliveryName(po.getDeliveryName());
                 update(storeOrder);
-             //   updateOrderStatus(po.getId(), PinkOrderStatusEnum.WAIT_RECEIVER.getKey());
-               updateOrderStatus(po.getId(), PinkOrderStatusEnum.GROUP_ORDER_TO_RECEVIE.getKey());
+                //   updateOrderStatus(po.getId(), PinkOrderStatusEnum.WAIT_RECEIVER.getKey());
+                updateOrderStatus(po.getId(), PinkOrderStatusEnum.GROUP_ORDER_TO_RECEVIE.getKey());
             }
         } catch (IOException e) {
             throw new RuntimeException(e);
@@ -1703,6 +1984,7 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
 
     @Resource
     private StorePinkMapper storePinkMapper;
+
     @Override
     public void updateOrderStatus(Long id, Integer status) {
         StoreOrder storeOrder = findById(id);
@@ -1715,12 +1997,11 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
 //        storePink.setOrderStatus(status);
 //        int i = storePinkMapper.updateByConditionSelective(storePink, example);
 
-        storeOrderStatusService.createLog(id, "", PinkOrderStatusEnum.getEnum(status).getValue());
+      //  storeOrderStatusService.createLog(id, "", PinkOrderStatusEnum.getEnum(status).getValue());
 
     }
 
 
-
     /**
      * 校验商品库存(生成订单)
      *
@@ -1792,10 +2073,63 @@ public class StoreOrderServiceImpl extends AbstractService<StoreOrder> implement
 
     @Resource
     private StoreOrderMapper storeOrderMapper;
+
     @Override
     public void bindingAddress(StoreOrder storeOrder) {
         Example example = new Example(StoreOrder.class);
-        example.createCriteria().andEqualTo("orderId",storeOrder.getOrderId());
-        storeOrderMapper.updateByConditionSelective(storeOrder,example);
+        example.createCriteria().andEqualTo("orderId", storeOrder.getOrderId());
+        storeOrderMapper.updateByConditionSelective(storeOrder, example);
     }
+
+
+    @Override
+    public void batchSigning() {
+
+
+        try{
+            Date date = new Date();
+            Date settleTime = DateUtil.offsetDay(date,-1);
+
+            PageHelper.startPage(1, 100);
+            Condition condition = new Condition(StoreOrder.class);
+            Example.Criteria criteria = condition.createCriteria();
+            criteria.andEqualTo("isDelete", 0);
+            criteria.andEqualTo("status", PinkOrderStatusEnum.GROUP_ORDER_TO_RECEVIE.getKey());
+            criteria.andLessThanOrEqualTo("deliveryTime", settleTime);
+            List<StoreOrder> storeOrderList = findByCondition(condition);
+            if(!CollectionUtils.isEmpty(storeOrderList)){
+                for (StoreOrder storeOrder : storeOrderList) {
+                    PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_CONFIRM_RECEIPT, null);
+                    if (ObjectUtils.isEmpty(pinkOrderStatusEnum)) {
+                        throw new ServiceException("当前状态不支持签收storeOrder:"+storeOrder.toString());
+                    }
+                    StoreOrder storeOrderForUpdate = new StoreOrder();
+                    storeOrderForUpdate.setStatus(pinkOrderStatusEnum.getKey());
+                    storeOrderForUpdate.setSigningTime(date);
+                    Example example = new Example(StoreOrder.class);
+                    example.createCriteria().andEqualTo("orderId",storeOrder.getOrderId());
+                    storeOrderMapper.updateByConditionSelective(storeOrderForUpdate,example);
+
+
+                    storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_STATUS_RECEIVE_ORDER, "订单自动签收");
+
+                    //维护拼团订单状态
+                    StorePink storePinkForUpdate = new StorePink();
+                    storePinkForUpdate.setOrderStatus(pinkOrderStatusEnum.getKey());
+                    Example exampleStorePink = new Example(StorePink.class);
+                    exampleStorePink.createCriteria().andEqualTo("orderId",storeOrder.getOrderId());
+                    storePinkMapper.updateByConditionSelective(storePinkForUpdate,exampleStorePink);
+
+                }
+            }
+
+
+
+        }catch(Exception e){
+            log.error("定时任务自动签收异常",e);
+        }
+
+    }
+
+
 }

+ 88 - 8
mall-service/src/main/java/com/txz/mall/service/impl/StorePinkServiceImpl.java

@@ -5,21 +5,26 @@ import cn.hutool.core.util.ObjectUtil;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.github.pagehelper.PageHelper;
 import com.txz.cif.param.AccomplishParam;
+import com.txz.mall.constants.Constants;
 import com.txz.mall.core.AbstractService;
 import com.txz.mall.core.ServiceException;
 import com.txz.mall.dao.StorePinkMapper;
 import com.txz.mall.dubbo.client.CifAccountDubboServiceClient;
+import com.txz.mall.enums.OrderEventsEnum;
 import com.txz.mall.enums.PinkOrderStatusEnum;
+import com.txz.mall.enums.StorePinkStatusEnum;
 import com.txz.mall.model.StoreOrder;
 import com.txz.mall.model.StorePink;
 import com.txz.mall.model.StorePinkSummary;
-import com.txz.mall.service.StorePinkService;
-import com.txz.mall.service.StorePinkSummaryService;
+import com.txz.mall.service.*;
+import com.txz.mall.util.OrderStateMachine;
 import com.txz.mall.util.RandomUtil;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.annotation.Lazy;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.ObjectUtils;
 import tk.mybatis.mapper.entity.Condition;
 import tk.mybatis.mapper.entity.Example;
 import vo.StorePinkOngoingVO;
@@ -76,11 +81,13 @@ public class StorePinkServiceImpl extends AbstractService<StorePink> implements
         List<StorePink> memberList = getListByCidAndKid(teamPink.getCid(), id);
         StorePink storePink2 = new StorePink();
         storePink2.setId(teamPink.getId());
-        storePink2.setStatus(2);
-        storePink2.setStopTime(date);
+       // storePink2.setStatus(2);
+       // storePink2.setStopTime(date);
         storePink2.setOrderStatus(PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey());
         log.info("storePink2:"+storePink2);
         update(storePink2);
+
+        storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_LOG_PAY_SUCCESS, "支付成功");
         memberList.add(teamPink);
 //        memberList.forEach(i -> {
 //            i.setStatus(2);
@@ -92,8 +99,14 @@ public class StorePinkServiceImpl extends AbstractService<StorePink> implements
         //拼团校验异常则证明在 add时就有问题,没有挡住异常的拼团数据
         Boolean b = storePinkSummaryService.maintainQuantityStatusOfTheStorePinkSummary(teamPink.getSpsId());
         if(b){
-        // 算出天选
-        theSelection(teamPink.getSpsId());
+
+
+
+        // 算出天选  同时推进订单状态到 代发货状态/订单关闭状态
+        theSelection(teamPink.getSpsId(),date);
+
+
+
 
         Condition condition = new Condition(StorePink.class);
         Example.Criteria criteria = condition.createCriteria();
@@ -146,10 +159,22 @@ public class StorePinkServiceImpl extends AbstractService<StorePink> implements
 //            update(luckPink);
 //        });
 //    }
+    @Lazy
+    @Resource
+    private StoreOrderService storeOrderService;
+    @Lazy
+    @Resource
+    private StoreCombinationService storeCombinationService;
+    @Lazy
+    @Resource
+    private StoreProductService storeProductService;
 
+    @Lazy
+    @Resource
+    private StoreOrderStatusService storeOrderStatusService;
 
     @Override
-    public void theSelection(Long spsId) {
+    public void theSelection(Long spsId,Date date) {
         // 假设只有1个用户是天选
         long luckNum = 1;
 
@@ -160,7 +185,7 @@ public class StorePinkServiceImpl extends AbstractService<StorePink> implements
         // 排除团长
 //        criteria.andEqualTo("kId", 1);
         // 支付成功的
-        criteria.andEqualTo("status", 2);
+        criteria.andEqualTo("orderStatus", PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey());
         List<StorePink> list = findByCondition(condition);
         if (CollUtil.isEmpty(list)) {
             throw new ServiceException("没有拼团订单");
@@ -170,15 +195,70 @@ public class StorePinkServiceImpl extends AbstractService<StorePink> implements
             throw new ServiceException("已有天选");
         }
 
+        Map<Long, StorePink> idStorePinkMap = list.stream().collect(Collectors.toMap(StorePink::getId, a -> a, (b, c) -> c));
+
         List<Long> idCollect = list.stream().map(StorePink::getId).collect(Collectors.toList());
         List<Long> randomIds = RandomUtil.uniqueRandom(idCollect, (int) luckNum);
 
+        //选出中奖单号 推进状态
         randomIds.forEach(i -> {
             StorePink luckPink = new StorePink();
+            StorePink storePink = idStorePinkMap.get(i);
             luckPink.setId(i);
             luckPink.setLId(1);
+            luckPink.setOrderStatus(PinkOrderStatusEnum.GROUP_ORDER_TO_SHIP.getKey());
+            luckPink.setStatus(StorePinkStatusEnum.RESULTS_ANNOUNCED.getKey());
+            luckPink.setStopTime(date);
+            StoreOrder storeOrder = storeOrderService.findById(storePink.getOrderIdKey());
+            PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_WIN, null);
+            if(ObjectUtils.isEmpty(pinkOrderStatusEnum)){
+                throw new ServiceException("当前订单状态不允许推进到待发货order.id:"+storePink.getOrderIdKey());
+            }
+
             update(luckPink);
+            //推进订单状态到待发货状态
+            storeOrderService.updateOrderStatus(storePink.getOrderIdKey(),pinkOrderStatusEnum.getKey());
+
+            storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_STATUS_PINK_SUCCESS_ORDER, "拼团成功");
+
+            //获奖者的状态联动已经完成了所以把他从列表中移除
+            list.remove(storePink);
+        });
+
+
+        //将所有参团成员的status设置为 已开奖
+        list.forEach(a->{
+
+            StoreOrder storeOrder = storeOrderService.findById(a.getOrderIdKey());
+            PinkOrderStatusEnum pinkOrderStatusEnum = OrderStateMachine.handleEvent(storeOrder, OrderEventsEnum.GROUP_PURCHASE_NOT_WIN, null);
+            if(ObjectUtils.isEmpty(pinkOrderStatusEnum)){
+                throw new ServiceException("当前订单状态不允许推进到未中奖订单关闭状态 order.id:"+a.getOrderIdKey());
+            }
+            // storePink2.setStopTime(date);
+            StorePink unLuckPink = new StorePink();
+            unLuckPink.setId(a.getId());
+            unLuckPink.setStatus(StorePinkStatusEnum.RESULTS_ANNOUNCED.getKey());
+            unLuckPink.setOrderStatus(pinkOrderStatusEnum.getKey());
+            unLuckPink.setStopTime(date);
+            update(unLuckPink);
+
+            //推进订单状态到未中奖关闭状态
+            storeOrderService.updateOrderStatus(a.getOrderIdKey(),pinkOrderStatusEnum.getKey());
+            storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_STATUS_PINK_SUCCESS_ORDER, "拼团成功");
+            //库存回退
+            // 拼团商品扣库存
+            storeCombinationService.operationStock(a.getCid(), a.getTotalNum(), "add");
+            // 拼团商品规格扣库存
+            //   productAttrValueService.operationStock(skuRecord.getInt("activityAttrValueId"), skuRecord.getInt("num"), "sub", Constants.PRODUCT_TYPE_PINGTUAN);
+            // 普通商品口库存
+            storeProductService.operationStock(a.getPid(), a.getTotalNum(), "add");
+
+
         });
+
+
+
+
     }
 
 

+ 69 - 56
mall-service/src/main/java/com/txz/mall/service/impl/StorePinkSummaryServiceImpl.java

@@ -3,6 +3,8 @@ package com.txz.mall.service.impl;
 import com.txz.mall.core.ServiceException;
 import com.txz.mall.dao.StorePinkMapper;
 import com.txz.mall.dao.StorePinkSummaryMapper;
+import com.txz.mall.enums.PinkOrderStatusEnum;
+import com.txz.mall.enums.StorePinkStatusEnum;
 import com.txz.mall.model.StorePink;
 import com.txz.mall.model.StorePinkSummary;
 import com.txz.mall.service.StorePinkSummaryService;
@@ -52,67 +54,78 @@ public class StorePinkSummaryServiceImpl extends AbstractService<StorePinkSummar
         }
 
         Integer status = storePinkSummary.getStatus();
-        Integer num = 2; //拼团成员已付款
-        if(num.equals(status)){
-            throw new ServiceException("拼团已成功不允许任何更改 id:"+id);
-        }
-        Integer people = storePinkSummary.getPeople();
-
-        int countOneInteger = 0;   //未付款的人数
-        int countTwoInteger = 0;  //付款成功的人数
-        if(!CollectionUtils.isEmpty(storePinks)){
-
-            Integer deleteInteger = new Integer(0);
-            Integer oneInteger = new Integer(1);
-            Integer twoInteger = new Integer(2);
-             countOneInteger = (int) storePinks.stream().filter(a -> {
-                return deleteInteger.equals(a.getIsDelete())
-                        && oneInteger.equals(a.getStatus());
-            }).count();
-
-             countTwoInteger = (int) storePinks.stream().filter(a -> {
-                return deleteInteger.equals(a.getIsDelete())
-                        && twoInteger.equals(a.getStatus());
-            }).count();
-
-            peopleCount = countOneInteger + countTwoInteger;
-        }
+        boolean successFlag = false;
 
+        //未开团的情况下退款要维护开团汇总表的实时状态  其他状态像已开团和开团失败就不再维护开团汇总表了因为开团失败和已开团的数据都已经被锁定,新的成员无法加入了
+        if(StorePinkStatusEnum.NOT_DRAWN.getKey().equals(status)){
 
-        if(people < peopleCount){
-            throw new ServiceException("拼团超员 id:"+id);
-        }
+            Integer people = storePinkSummary.getPeople();
 
-        boolean updateFlag = false;
-        //成团标识只有成团后才返回true
-        boolean successFlag = false;
-        StorePinkSummary storePinkSummaryForUpdate = new StorePinkSummary();
-        storePinkSummaryForUpdate.setId(id);
-        storePinkSummaryForUpdate.setPeopleCount(peopleCount);
-
-        //这里判断  已经付款成功的订单 总数==活动总人数的时候代表拼团锁定
-        if(people==peopleCount){
-            storePinkSummaryForUpdate.setIsVirtual(Boolean.TRUE);
-            updateFlag = true;
-        }
-        if(people>peopleCount){
-            storePinkSummaryForUpdate.setIsVirtual(Boolean.FALSE);
-            updateFlag = true;
-        }
-        //这里判断  已经付款成功的订单 总数==活动总人数的时候代表拼团成功
-        if(people== countTwoInteger){
-            storePinkSummaryForUpdate.setIsVirtual(Boolean.TRUE);
-            storePinkSummaryForUpdate.setStatus(num);
-            updateFlag = true;
-            successFlag = true;   //拼团成功标识
-        }
+            int countOneInteger = 0;   //未付款的人数
+            int countTwoInteger = 0;  //付款成功的人数
+            int countThreeInteger = 0;  //评团超时失败的数量,只要有1个那么就认为总体都失败
+
+            if(!CollectionUtils.isEmpty(storePinks)){
+
+                Integer deleteInteger = 0;
+
+                countOneInteger = (int) storePinks.stream().filter(a -> {
+                    return deleteInteger.equals(a.getIsDelete())
+                            && PinkOrderStatusEnum.GROUP_ORDER_TO_PAY.getKey().equals(a.getOrderStatus());
+                }).count();
+
+                countTwoInteger = (int) storePinks.stream().filter(a -> {
+                    return deleteInteger.equals(a.getIsDelete())
+                            && PinkOrderStatusEnum.GROUP_ORDER_PAID.getKey().equals(a.getOrderStatus());
+                }).count();
 
-        if(people > countTwoInteger){
-            storePinkSummaryForUpdate.setStatus(1);
-            updateFlag = true;
+                countThreeInteger = (int) storePinks.stream().filter(a -> {
+                    return deleteInteger.equals(a.getIsDelete())
+                            && StorePinkStatusEnum.LOTTERY_FAILED.getKey().equals(a.getStatus());
+                }).count();
+
+                peopleCount = countOneInteger + countTwoInteger;
+            }
+
+
+            if(people < peopleCount){
+                throw new ServiceException("拼团超员 id:"+id);
+            }
+
+
+            //成团标识只有成团后才返回true
+
+            StorePinkSummary storePinkSummaryForUpdate = new StorePinkSummary();
+            storePinkSummaryForUpdate.setId(id);
+            storePinkSummaryForUpdate.setPeopleCount(peopleCount);
+
+            //这里判断  已经付款成功的订单 总数==活动总人数的时候代表拼团锁定
+            if(people==peopleCount){
+                storePinkSummaryForUpdate.setIsVirtual(Boolean.TRUE);
+            }
+            if(people>peopleCount){
+                storePinkSummaryForUpdate.setIsVirtual(Boolean.FALSE);
+            }
+            //这里判断  已经付款成功的订单 总数==活动总人数的时候代表拼团成功
+            if(people== countTwoInteger){
+                storePinkSummaryForUpdate.setIsVirtual(Boolean.TRUE);
+                storePinkSummaryForUpdate.setStatus(StorePinkStatusEnum.RESULTS_ANNOUNCED.getKey());
+                successFlag = true;   //拼团成功标识
+            }
+
+            if(people > countTwoInteger){
+                storePinkSummaryForUpdate.setStatus(StorePinkStatusEnum.NOT_DRAWN.getKey());
+            }
+
+            if(countThreeInteger>0){
+                storePinkSummaryForUpdate.setIsVirtual(Boolean.TRUE);
+                storePinkSummaryForUpdate.setStatus(StorePinkStatusEnum.LOTTERY_FAILED.getKey());
+            }
+
+            mStorePinkSummaryMapper.updateByPrimaryKeySelective(storePinkSummaryForUpdate);
         }
 
-        mStorePinkSummaryMapper.updateByPrimaryKeySelective(storePinkSummaryForUpdate);
-        return successFlag;
+
+       return successFlag;
     }
 }

+ 31 - 15
mall-service/src/main/java/com/txz/mall/service/impl/StoreProductServiceImpl.java

@@ -31,6 +31,7 @@ import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.BeanUtils;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.ObjectUtils;
 import org.springframework.web.multipart.MultipartFile;
 import tk.mybatis.mapper.entity.Condition;
 import tk.mybatis.mapper.entity.Example;
@@ -326,25 +327,40 @@ public class StoreProductServiceImpl extends AbstractService<StoreProduct> imple
     }
 
     @Override
-    public void operationStock(Integer id, Integer num, String type) {
-        UpdateWrapper<StoreProduct> updateWrapper = new UpdateWrapper<>();
+    public void operationStock(Long id, Integer num, String type) {
+        StoreProduct storeProduct = storeProductMapper.selectByPrimaryKey(id);
+        if(ObjectUtils.isEmpty(storeProduct)){
+            throw new ServiceException("商品不存在id:"+id);
+        }
+
+        StoreProduct forUpdatestoreProduct = new StoreProduct();
         if ("add".equals(type)) {
-            updateWrapper.setSql(StrUtil.format("stock = stock + {}", num));
-            updateWrapper.setSql(StrUtil.format("sales = sales - {}", num));
-            updateWrapper.setSql(StrUtil.format("quota = quota + {}", num));
+            int stock = storeProduct.getStock()+num;
+            int sales = storeProduct.getSales()-num;
+            if(sales<0){
+                throw new ServiceException("销量扣减为负数productId:"+id);
+            }
+
+            forUpdatestoreProduct.setStock(stock);
+            forUpdatestoreProduct.setSales(sales);
+
         }
         if ("sub".equals(type)) {
-            updateWrapper.setSql(StrUtil.format("stock = stock - {}", num));
-            updateWrapper.setSql(StrUtil.format("sales = sales + {}", num));
-            updateWrapper.setSql(StrUtil.format("quota = quota - {}", num));
-            // 扣减时加乐观锁保证库存不为负
-            updateWrapper.last(StrUtil.format(" and (quota - {} >= 0)", num));
+            int stock = storeProduct.getStock()-num;
+            int sales = storeProduct.getSales()+num;
+            if(stock<0){
+                throw new ServiceException("库存扣减为负数productId:"+id);
+            }
+            forUpdatestoreProduct.setStock(stock);
+            forUpdatestoreProduct.setSales(sales);
+        }
+        forUpdatestoreProduct.setVersion(storeProduct.getVersion()+1);
+        Example example = new Example(StoreProduct.class);
+        example.createCriteria().andEqualTo("id",id).andEqualTo("version",storeProduct.getVersion());
+        int i = storeProductMapper.updateByConditionSelective(forUpdatestoreProduct, example);
+        if (!(i==1)) {
+            throw new ServiceException("更新商品库存失败!商品id = " + id);
         }
-        updateWrapper.eq("id", id);
-//        boolean update = update(updateWrapper);
-//        if (!update) {
-//            throw new ServiceException("更新商品库存失败!商品id = " + id);
-//        }
     }
 
     // 生成货号的方法

+ 3 - 3
mall-service/src/main/java/com/txz/mall/util/OrderStateMachine.java

@@ -36,7 +36,7 @@ public class OrderStateMachine {
 
         // 已支付状态下的可能转移
         Map<OrderEventsEnum, PinkOrderStatusEnum> pendingDeliveryTransitions = new HashMap<>();
-        pendingDeliveryTransitions.put(OrderEventsEnum.GROUP_PURCHASE_FAIL, PinkOrderStatusEnum.GROUP_ORDER_REFUND);
+        pendingDeliveryTransitions.put(OrderEventsEnum.GROUP_PURCHASE_FAIL, PinkOrderStatusEnum.GROUP_ORDER_REFUND);//已支付状态下都可以退款
         pendingDeliveryTransitions.put(OrderEventsEnum.GROUP_PURCHASE_NOT_WIN, PinkOrderStatusEnum.GROUP_ORDER_TO_CLOSED);
         pendingDeliveryTransitions.put(OrderEventsEnum.GROUP_PURCHASE_WIN, PinkOrderStatusEnum.GROUP_ORDER_TO_SHIP);
         transitionTable.put(PinkOrderStatusEnum.GROUP_ORDER_PAID, pendingDeliveryTransitions);
@@ -44,7 +44,7 @@ public class OrderStateMachine {
         // 待发货状态下的可能转移
         Map<OrderEventsEnum, PinkOrderStatusEnum> pendingReceiptTransitions = new HashMap<>();
         pendingReceiptTransitions.put(OrderEventsEnum.GROUP_PURCHASE_DELIVER, PinkOrderStatusEnum.GROUP_ORDER_TO_RECEVIE);
-
+       // pendingReceiptTransitions.put(OrderEventsEnum.GROUP_PURCHASE_FAIL, PinkOrderStatusEnum.GROUP_ORDER_REFUND); //已支付状态下都可以退款
         transitionTable.put(PinkOrderStatusEnum.GROUP_ORDER_TO_SHIP, pendingReceiptTransitions);
 
         // 待收获态下的可能转移
@@ -131,7 +131,7 @@ public class OrderStateMachine {
 
         // 执行状态转换
         PinkOrderStatusEnum targetState = allowedEvents.get(event);
-        order.setStatus(targetState.getKey());
+        // order.setStatus(targetState.getKey());
 
 //        logger.info("订单[{}]状态变更: {} -> {}",
 //                order.getOrderId(), currentState.getValue(), targetState.getValue());