소스 검색

fix 更换用户车票

zoujiajian 3 년 전
부모
커밋
3bf92e1214

+ 3 - 0
netflix-dao/src/main/java/com/cyksj/mapper/GroupsMapper.java

@@ -27,4 +27,7 @@ public interface GroupsMapper extends BaseMapper<GroupsTrips> {
 			" and not EXISTS (select account_id from account_double_verify_record where account_id = gt.account_id and deleted is true)" +
 			" and DATE_SUB(now(),INTERVAL 3 day) >= (select max(update_time) from groups_relation gr where gr.groups_id = gt.groups_id and gr.`status` = 'validity')")
 	List<AccountDoubleVerifyRecord> selectGPTDoubleVerifyTrips(Long goodsId);
+
+	@Update("update groups_trips set available_num = (select count(*) from groups_relation where groups_id = #{groupsId} and status = 'none') where id = #{groupsId}")
+	Integer updateAvailableNum(Long groupsId);
 }

+ 2 - 0
netflix-dao/src/main/java/com/cyksj/mapper/GroupsRelationMapper.java

@@ -34,4 +34,6 @@ public interface GroupsRelationMapper extends BaseMapper<GroupsRelation> {
 	String getBindPhoneByUserId(Long userId);
 
 	Integer selectViewPwdCount(Long groupsId);
+
+	GroupsRelation selectRandomOneRelationByGroupsId(Long groupsId);
 }

+ 7 - 0
netflix-dao/src/main/java/com/cyksj/model/entity/GroupsRelation.java

@@ -65,6 +65,13 @@ public class GroupsRelation extends BaseEntity {
     @DbIgnore
     private Long orderId;
 
+    /**
+     * 更换车票时,新车票id
+     */
+    @TableField(exist = false)
+    @DbIgnore
+    private Long newRelationId;
+
 
     @AllArgsConstructor
     @Getter

+ 2 - 0
netflix-dao/src/main/java/com/cyksj/model/entity/UserTicketClearedRecord.java

@@ -31,6 +31,8 @@ public class UserTicketClearedRecord extends BaseEntity{
 
 	private Long relationId;
 
+	private Long newRelationId;
+
 	private Date startTime;
 
 	private Date expiryTime;

+ 3 - 0
netflix-dao/src/main/java/com/cyksj/model/manage/views/OrderDonBackView.java

@@ -127,6 +127,9 @@ public class OrderDonBackView {
 	@DbField("o.source")
 	private OrderDon.Source source;
 
+	@DbField("o.label_source")
+	private String labelSource;
+
 	@DbField("o.num")
 	private Integer num;
 

+ 4 - 3
netflix-dao/src/main/java/com/cyksj/model/request/ChangeRelationReq.java

@@ -14,9 +14,10 @@ import javax.validation.constraints.NotNull;
 @Getter
 @Setter
 public class ChangeRelationReq {
-	@NotNull(message = "订单id为空")
-	private Long orderId;
+
+	@NotNull(message = "车票id为空")
+	private Long relationId;
 
 	@NotNull(message = "新车队id为空")
-	private Long groupId;
+	private Long groupsId;
 }

+ 5 - 1
netflix-dao/src/main/java/com/cyksj/model/views/EmptyGroupsRelationView.java

@@ -1,5 +1,6 @@
 package com.cyksj.model.views;
 
+import com.cyksj.model.entity.GroupsTrips;
 import com.ejlchina.searcher.bean.DbField;
 import com.ejlchina.searcher.bean.SearchBean;
 import lombok.Getter;
@@ -21,7 +22,7 @@ public class EmptyGroupsRelationView {
 	@DbField("a.account")
 	private String account;
 
-	@DbField("gt.id")
+	@DbField("gt.sku_id")
 	private Long skuId;
 
 	@DbField("gt.id")
@@ -29,4 +30,7 @@ public class EmptyGroupsRelationView {
 
 	@DbField("gt.available_num")
 	private Integer availableNum;
+
+	@DbField("gt.status")
+	private GroupsTrips.Status status;
 }

+ 9 - 0
netflix-dao/src/main/resources/mapper/GroupRelationMapper.xml

@@ -91,4 +91,13 @@
         from (select id, user_id from `groups_relation` where groups_id = #{groupsId} and `status` = 'validity') s
                  inner join chat_gpt_pwd_view_record cr on cr.relation_id = s.id and s.user_id = cr.user_id
     </select>
+
+    <select id="selectRandomOneRelationByGroupsId" resultType="com.cyksj.model.entity.GroupsRelation">
+        select *
+        from groups_relation
+        where groups_id = #{groupsId}
+          and user_id = 0
+          and status = 'none'
+        order by rand() limit 1
+    </select>
 </mapper>

+ 1 - 0
netflix-service/src/main/java/com/cyksj/service/exchange/impl/ExchangeCodeServiceImpl.java

@@ -379,6 +379,7 @@ public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, Exc
 			int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
 			if (count == 0) {
 				log.error("车位异常 groupId:{}", relation.getGroupsId());
+				groupsMapper.updateAvailableNum(relation.getGroupsId());
 				throw new BusinessRuntimeException("车位异常");
 			}
 		}

+ 48 - 38
netflix-service/src/main/java/com/cyksj/service/mange/impl/CmsOrderDonServiceImpl.java

@@ -15,10 +15,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.cyksj.common.constant.Constant;
 import com.cyksj.common.exception.BusinessRuntimeException;
 import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
-import com.cyksj.common.util.Codec;
-import com.cyksj.common.util.Jsons;
-import com.cyksj.common.util.StringUtil;
-import com.cyksj.common.util.Xmls;
+import com.cyksj.common.util.*;
 import com.cyksj.config.WeChatConfig;
 import com.cyksj.config.zfb.AliPayClientFactory;
 import com.cyksj.dto.RedisKey;
@@ -305,43 +302,73 @@ public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon>
     @Override
     @Transactional(rollbackFor = Throwable.class)
     public void changeRelation(ChangeRelationReq req) {
-        Long orderId = req.getOrderId();
-        Long groupId = req.getGroupId();
-        OrderDon orderDon = this.getById(orderId);
-        Assert.notNull(orderDon, "订单不存在");
-        if (orderDon.getRelationId() == 0) throw BusinessRuntimeException.getInstance("车票不存在");
-        GroupsRelation relation = relationMapper.selectById(orderDon.getRelationId());
+        Long relationId = req.getRelationId();
+        Long groupId = req.getGroupsId();
+        GroupsRelation relation = relationMapper.selectById(relationId);
         Assert.notNull(relation, "车票已不存在");
-        //清除原先车票
-        relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.change_ticket);
-        //移入新车队
+        Long userId = relation.getUserId();
+        OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
+                .eq(OrderDon::getUserId, userId)
+                .eq(OrderDon::getRelationId, relationId)
+                .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
+                .last("limit 1"));
+        Assert.notNull(orderDon, "订单不存在");
+
+        //获取新车队
         LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
                 .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
                 .eq(GroupsTrips::getId, groupId)
                 .gt(GroupsTrips::getAvailableNum, 0).last("limit 1")
+                .ne(GroupsTrips::getId, relation.getGroupsId())
                 .ne(GroupsTrips::getStatus, GroupsTrips.Status.down);
         GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
         if (groups == null) throw BusinessRuntimeException.getInstance("该新车位人员已满");
 
-        //更新新车队车位
+        //获取新车队车位
         GroupsRelation newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
+
         newRelation.setUserId(relation.getUserId());
         newRelation.setStartTime(relation.getStartTime());
         newRelation.setExpiryTime(relation.getExpiryTime());
         newRelation.setCustomerService(relation.getCustomerService());
         newRelation.setStatus(GroupsRelation.Status.validity);
-        if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null) && groups.getStatus() != GroupsTrips.Status.waiting) {
-            List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, relation.getUserId()).eq(OrderDon::getRelationId, relation.getId()).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
-            orderDonList.forEach((relationOrder) -> {
+
+        //清除原先车票
+        relation.setNewRelationId(newRelation.getId());
+        relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.change_ticket);
+
+        if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
+            List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
+            if (groups.getStatus() == GroupsTrips.Status.waiting) {
+                orderDonList.forEach(hasPaymentOrder -> {
+                    hasPaymentOrder.setRelationId(newRelation.getId());
+                    orderDonMapper.updateById(hasPaymentOrder);
+                });
+                relationMapper.updateById(newRelation);
+                return;
+            }
+            orderDonList.forEach((hasPaymentOrder) -> {
                 //如果续费增加时间,如果首次则设置当前时间为初始时间
                 Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
-                GoodsDonSku donSku = skuMapper.selectById(relationOrder.getSkuId());
-                Date newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * relationOrder.getNum());
+                GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
+                Date newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
                 newRelation.setExpiryTime(newDate);
                 newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
                 relationMapper.updateById(newRelation);
+
+                hasPaymentOrder.setStatus(OrderDon.Status.complete);
+                hasPaymentOrder.setRelationId(newRelation.getId());
+                orderDonMapper.updateById(hasPaymentOrder);
             });
+            return;
         }
+        List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
+        orderDonList.forEach(completeOrder->{
+            completeOrder.setRelationId(newRelation.getId());
+            orderDonMapper.updateById(completeOrder);
+        });
+        redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + newRelation.getId());
+        relationMapper.updateById(newRelation);
     }
 
     public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
@@ -582,29 +609,11 @@ public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon>
      */
     public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
         //寻找快满编车队进行占座
-        GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
-                .eq(GroupsRelation::getGroupsId, groupsId)
-                .eq(GroupsRelation::getStatus, "none")
-                .eq(GroupsRelation::getUserId, 0)
-                .orderByDesc(GroupsRelation::getNum)
-                .last("limit 1")
-        );
+        GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
         if (relation == null) {
             throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
         }
         Long relationId = relation.getId();
-        Object value = redisService.get(RedisKey.GROUPS_RELATION_NUM_KEY + relationId);
-        if (value != null) {
-            relation = relationMapper.selectById(relationId);
-            if (relation != null && relation.getUserId() == 0l) {
-                redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + relationId);
-            }
-            if (relation != null && relation.getUserId() != 0l) {
-                if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
-                retryNum++;
-                getRelationThisTrips(userId, groupsId, retryNum);
-            }
-        }
         if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
             if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
             retryNum++;
@@ -613,6 +622,7 @@ public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon>
         int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
         if (count == 0) {
             log.error("车位异常 groupId:{}", groupsId);
+            groupsMapper.updateAvailableNum(groupsId);
             throw new BusinessRuntimeException("车位异常");
         }
         return relation;

+ 1 - 0
netflix-service/src/main/java/com/cyksj/service/order/impl/OrderCommonServiceImpl.java

@@ -130,6 +130,7 @@ public class OrderCommonServiceImpl implements OrderCommonService {
 		int count = groupsMapper.incrAvailableNum(relation.getGroupsId());
 		if (count == 0) {
 			log.error("车位异常 groupId:{}", relation.getGroupsId());
+			groupsMapper.updateAvailableNum(relation.getGroupsId());
 			throw new BusinessRuntimeException("车位异常");
 		}
 	}

+ 4 - 18
netflix-service/src/main/java/com/cyksj/service/order/impl/OrderDonServiceImpl.java

@@ -847,17 +847,6 @@ public class OrderDonServiceImpl extends ServiceImpl<OrderDonMapper, OrderDon> i
 				throw new BusinessRuntimeException("您有未支付订单.");
 			}
 		}
-		Object value = redisService.get(RedisKey.GROUPS_RELATION_NUM_KEY + relationId);
-		if (value != null) {
-			GroupsRelation relation = groupsRelationMapper.selectById(relationId);
-			if (relation != null && relation.getUserId() == 0l) {
-				redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + relationId);
-			}
-			if (relation != null && relation.getUserId() != 0l) {
-				log.info("=====>用户:{}获取了已有人座位:{}", userId, relationId);
-				throw new BusinessRuntimeException("客官手慢啦,该座位已经有人啦!");
-			}
-		}
 		if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
 			log.info("=====>用户:{}未抢到座位:{}", userId, relationId);
 			throw new BusinessRuntimeException("客官手慢啦,该座位已经有人啦!");
@@ -865,6 +854,8 @@ public class OrderDonServiceImpl extends ServiceImpl<OrderDonMapper, OrderDon> i
 		int count = groupsMapper.decrAvailableNum(groupsId);
 		if (count == 0) {
 			log.error("车位异常 groupId:{}", groupsId);
+			groupsMapper.updateAvailableNum(groupsId);
+			redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + relationId);
 			throw new BusinessRuntimeException("车位异常");
 		}
 	}
@@ -1809,13 +1800,7 @@ public class OrderDonServiceImpl extends ServiceImpl<OrderDonMapper, OrderDon> i
 					relation = createNewGroupsTrips(sku);
 				} else {
 					//寻找快满编车队进行占座
-					relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
-							.eq(GroupsRelation::getGroupsId, groups.getId())
-							.eq(GroupsRelation::getStatus, "none")
-							.eq(GroupsRelation::getUserId, 0)
-							.orderByAsc(GroupsRelation::getNum)
-							.last("limit 1")
-					);
+					relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
 					if (relation == null) {
 						throw new BusinessRuntimeException(GROUP_INDEX_NOT_FIND.getCode(), GROUP_INDEX_NOT_FIND.getMsg());
 					}
@@ -1828,6 +1813,7 @@ public class OrderDonServiceImpl extends ServiceImpl<OrderDonMapper, OrderDon> i
 		relation.setUserId(userId);
 		relation.setStatus(GroupsRelation.Status.locking);
 		groupsRelationMapper.updateById(relation);
+		redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + relation.getId());
 		return relation.getId();
 	}
 

+ 6 - 3
netflix-service/src/main/java/com/cyksj/service/relation/impl/GroupRelationClearServiceImpl.java

@@ -1,11 +1,11 @@
 package com.cyksj.service.relation.impl;
 
-import com.cyksj.common.exception.BusinessRuntimeException;
 import com.cyksj.mapper.GroupsMapper;
 import com.cyksj.mapper.GroupsRelationMapper;
 import com.cyksj.mapper.GroupsTripsDeleteRecordMapper;
 import com.cyksj.mapper.UserTicketClearedRecordMapper;
-import com.cyksj.model.entity.*;
+import com.cyksj.model.entity.GroupsRelation;
+import com.cyksj.model.entity.UserTicketClearedRecord;
 import com.cyksj.model.manage.views.GroupsRelationView;
 import com.cyksj.service.mange.CmsAccountService;
 import com.cyksj.service.mange.CmsGroupService;
@@ -48,6 +48,7 @@ public class GroupRelationClearServiceImpl implements GroupRelationClearService
 	@Transactional(rollbackFor = Throwable.class)
 	public void clearTicket(GroupsRelation relation, UserTicketClearedRecord.Source source) {
 		Long relationId = relation.getId();
+		Long newRelationId = relation.getNewRelationId();
 		//记录用户被清除车票历史记录
 		GroupsRelationView groupsRelation = beanSearcher.searchFirst(GroupsRelationView.class,
 				MapUtils.builder().field(GroupsRelationView::getId, relationId).build());
@@ -74,7 +75,7 @@ public class GroupRelationClearServiceImpl implements GroupRelationClearService
 				int count = groupsMapper.incrAvailableNum(relation.getGroupsId());
 				if (count == 0) {
 					log.error("车位异常 groupId:{}", relation.getGroupsId());
-					throw new BusinessRuntimeException("车位异常");
+					groupsMapper.updateAvailableNum(relation.getGroupsId());
 				}
 				UserTicketClearedRecord userTicketClearedRecord = new UserTicketClearedRecord();
 				userTicketClearedRecord.setAccountId(groupsRelation.getAccountId());
@@ -86,6 +87,7 @@ public class GroupRelationClearServiceImpl implements GroupRelationClearService
 				userTicketClearedRecord.setSkuId(groupsRelation.getSkuId());
 				userTicketClearedRecord.setStartTime(startTime);
 				userTicketClearedRecord.setExpiryTime(expireTime);
+				userTicketClearedRecord.setNewRelationId(newRelationId);
 				userTicketClearedRecordMapper.insert(userTicketClearedRecord);
 //				if (!isFlag) {
 //					//清除之前规格的车队
@@ -130,6 +132,7 @@ public class GroupRelationClearServiceImpl implements GroupRelationClearService
 			log.info("续费后更换车票,座位号:{}", relation.getId());
 			int count = groupsMapper.incrAvailableNum(relation.getGroupsId());
 			if (count == 0) {
+				groupsMapper.updateAvailableNum(relation.getGroupsId());
 				log.error("续费更换车位异常 groupId:{}", relation.getGroupsId());
 			}
 		}

+ 7 - 5
netflix-web/src/main/java/com/cyksj/web/controller/manage/CmsOrderController.java

@@ -11,7 +11,6 @@ import com.cyksj.common.annotation.NoSubmit;
 import com.cyksj.common.constant.Constant;
 import com.cyksj.common.exception.BusinessRuntimeException;
 import com.cyksj.common.util.IoKit;
-import com.cyksj.common.util.StringUtil;
 import com.cyksj.common.util.Xmls;
 import com.cyksj.dto.Result;
 import com.cyksj.enums.BusinessType;
@@ -491,10 +490,10 @@ public class CmsOrderController {
 	}
 
 	/**
-	 * 更换账号
+	 * 更换用户车票
 	 */
-	@PutMapping("/get/sameSpec/empty/relation")
-	public Result<String> changeRelation(@RequestBody ChangeRelationReq req) {
+	@PutMapping("/put/sameSpec/empty/relation")
+	public Result<String> changeRelation(@RequestBody @Validated ChangeRelationReq req) {
 		cmsOrderDonService.changeRelation(req);
 		return GatewayResponse.SUCCESS.newBuilder().toResult();
 	}
@@ -504,8 +503,11 @@ public class CmsOrderController {
 	 * 多余车位的空账号
 	 */
 	@GetMapping("/get/sameSpec/empty/relation")
-	public Result<SearchResult<EmptyGroupsRelationView>> getSameSpecEmptyRelation(Long skuId) {
+	public Result<SearchResult<EmptyGroupsRelationView>> getSameSpecEmptyRelation(Long skuId, Long groupsId) {
 		SearchResult<EmptyGroupsRelationView> search = beanSearcher.search(EmptyGroupsRelationView.class, MapUtils.builder()
+				.field(EmptyGroupsRelationView::getGroupsId, groupsId).op(Operator.NotEqual)
+				.field(EmptyGroupsRelationView::getAvailableNum, 0).op(Operator.GreaterThan)
+				.field(EmptyGroupsRelationView::getStatus, GroupsTrips.Status.down.name()).op(Operator.NotEqual)
 				.field(EmptyGroupsRelationView::getSkuId, skuId).orderBy(EmptyGroupsRelationView::getAvailableNum).desc()
 				.build());
 		return GatewayResponse.SUCCESS.newBuilder().toResult(search);