ExchangeCodeServiceImpl.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. package com.cyksj.service.exchange.impl;
  2. import cn.hutool.core.date.DateField;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.core.date.DateUtil;
  5. import cn.hutool.core.util.StrUtil;
  6. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  7. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  8. import com.cyksj.common.annotation.NoSubmit;
  9. import com.cyksj.common.constant.Constant;
  10. import com.cyksj.common.exception.BusinessRuntimeException;
  11. import com.cyksj.common.snowflake.Sequence;
  12. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  13. import com.cyksj.common.util.Jsons;
  14. import com.cyksj.common.util.StringUtil;
  15. import com.cyksj.dto.RedisKey;
  16. import com.cyksj.dto.Result;
  17. import com.cyksj.enums.GatewayResponse;
  18. import com.cyksj.mapper.*;
  19. import com.cyksj.mapper.manage.exchange.ExchangeCodeMapper;
  20. import com.cyksj.mapper.market.draw.LuckyDrawRecordMapper;
  21. import com.cyksj.model.entity.*;
  22. import com.cyksj.model.excel.ExcelExchangeCodeData;
  23. import com.cyksj.model.manage.views.AccountView;
  24. import com.cyksj.model.request.ExchangeCodeReq;
  25. import com.cyksj.model.request.ExchangeCodeTicket;
  26. import com.cyksj.redis.RedisService;
  27. import com.cyksj.service.exchange.ExchangeCodeService;
  28. import com.cyksj.service.relation.GroupRelationFrontService;
  29. import com.cyksj.service.relation.GroupsRelationExpiryRecordService;
  30. import com.ejlchina.searcher.BeanSearcher;
  31. import com.ejlchina.searcher.util.MapUtils;
  32. import lombok.RequiredArgsConstructor;
  33. import lombok.extern.slf4j.Slf4j;
  34. import org.springframework.beans.BeanUtils;
  35. import org.springframework.stereotype.Service;
  36. import org.springframework.transaction.annotation.Transactional;
  37. import java.math.BigDecimal;
  38. import java.util.ArrayList;
  39. import java.util.Date;
  40. import java.util.List;
  41. import java.util.Optional;
  42. /*
  43. *项目名: netflix
  44. *文件名: ExchangeCodeServiceImpl
  45. *创建者: JavaZou
  46. *创建时间:2022/11/7 15:41
  47. */
  48. @Service
  49. @RequiredArgsConstructor
  50. @Slf4j
  51. public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements ExchangeCodeService {
  52. private final GoodsDonMapper goodsDonMapper;
  53. private final GoodsDonSkuMapper goodsDonSkuMapper;
  54. private final ExchangeCodeMapper exchangeCodeMapper;
  55. private final GroupsRelationMapper groupsRelationMapper;
  56. private final GroupsMapper groupsMapper;
  57. private final RedisService redisService;
  58. private static final Sequence SEQUENCE = new Sequence(0);
  59. private final UserMapper userMapper;
  60. private final OrderDonMapper orderDonMapper;
  61. private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  62. private final LuckyDrawRecordMapper luckyDrawRecordMapper;
  63. private final BeanSearcher beanSearcher;
  64. private final GroupRelationFrontService groupRelationFrontService;
  65. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  66. private final GroupsRelationExpiryRecordService groupsRelationExpiryRecordService;
  67. @Override
  68. @Transactional(rollbackFor = Throwable.class)
  69. public List<ExcelExchangeCodeData> createExchangeCode(ExchangeCodeReq exchangeCodeReq) {
  70. GoodsDon goodsDon = goodsDonMapper.selectById(exchangeCodeReq.getGoodsId());
  71. if (goodsDon == null) {
  72. throw BusinessRuntimeException.getInstance("所选平台已被删除");
  73. }
  74. if (Constant.realGoodsType.contains(goodsDon.getType())) {
  75. throw BusinessRuntimeException.getInstance("该类商品不支持生成兑换码");
  76. }
  77. GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(exchangeCodeReq.getSkuId());
  78. if (goodsDonSku == null) {
  79. throw BusinessRuntimeException.getInstance("所选规格已被删除");
  80. }
  81. if (!goodsDonSku.getGoodsId().equals(exchangeCodeReq.getGoodsId())) {
  82. throw BusinessRuntimeException.getInstance("规格与平台不匹配");
  83. }
  84. List<ExcelExchangeCodeData> data = new ArrayList<>(exchangeCodeReq.getNumber());
  85. for (int i = 0; i < exchangeCodeReq.getNumber(); i++) {
  86. StringBuilder sb = new StringBuilder(32);
  87. sb.append(goodsDon.getSecondType() == 1 ? "YQ" : "FY");
  88. sb.append(getFillByGoodsId(exchangeCodeReq.getGoodsId()));
  89. sb.append(getFillByMonth(exchangeCodeReq.getSkuId()));
  90. //随即补充12位随即数,组成20位兑换码
  91. StringUtil.getRandomStr(sb, 12);
  92. ExchangeCode exchangeCode = new ExchangeCode();
  93. exchangeCode.setGoodsId(exchangeCodeReq.getGoodsId());
  94. exchangeCode.setSkuId(exchangeCodeReq.getSkuId());
  95. exchangeCode.setCode(sb.toString());
  96. exchangeCode.setUseStatus(false);
  97. exchangeCode.setType(exchangeCodeReq.getType());
  98. exchangeCodeMapper.insert(exchangeCode);
  99. ExcelExchangeCodeData excelExchangeCodeData = new ExcelExchangeCodeData();
  100. BeanUtils.copyProperties(exchangeCode, excelExchangeCodeData);
  101. excelExchangeCodeData.setTitle(goodsDon.getTitle());
  102. String specVal = goodsDonSku.getSpecVal();
  103. BigDecimal price = goodsDonSku.getPrice();
  104. excelExchangeCodeData.setSpecVal(String.format("%s%s", specVal, price.divide(BigDecimal.valueOf(100))));
  105. excelExchangeCodeData.setUseStatusStr(exchangeCode.getUseStatus() ? "已使用" : "未使用");
  106. data.add(excelExchangeCodeData);
  107. }
  108. return data;
  109. }
  110. @Override
  111. @Transactional(rollbackFor = Throwable.class)
  112. @NoSubmit
  113. public Result<String> getTicketByExchangeCode(ExchangeCodeTicket exchangeCodeTicket, Long userId) {
  114. if (StrUtil.isEmpty(exchangeCodeTicket.getCode())) {
  115. throw BusinessRuntimeException.getInstance("兑换码有误,请使用正确的兑换码");
  116. }
  117. ExchangeCode exchangeCode = this.getOne(Wrappers.lambdaQuery(ExchangeCode.class).eq(ExchangeCode::getCode, exchangeCodeTicket.getCode()).last("limit 1"));
  118. if (exchangeCode == null) {
  119. throw BusinessRuntimeException.getInstance("兑换码有误,请使用正确的兑换码");
  120. }
  121. if (exchangeCode.getUseStatus()) {
  122. throw BusinessRuntimeException.getInstance("该兑换码已使用");
  123. }
  124. //兑换成功
  125. exchangeCode.setUseStatus(true);
  126. exchangeCode.setUserId(userId);
  127. exchangeCode.setUseTime(DateTime.now());
  128. int update = exchangeCodeMapper.update(exchangeCode, Wrappers.lambdaQuery(ExchangeCode.class).eq(ExchangeCode::getId, exchangeCode.getId()).eq(ExchangeCode::getUseStatus, false));
  129. if (update != 1) {
  130. throw BusinessRuntimeException.getInstance("该兑换码已使用");
  131. }
  132. //是否是推广用户未登录订单关联的兑换码
  133. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  134. .eq(OrderDon::getIsNoLogin, true)
  135. .eq(OrderDon::getExCode, exchangeCode.getCode())
  136. .notIn(OrderDon::getStatus, Constant.noOrderStatus)
  137. .last("limit 1"));
  138. // Long popularizeId = orderDon.getPopularizeId();
  139. //
  140. // //360 渠道兑换规则验证.
  141. // if(popularizeId != null && popularizeId != 0){
  142. // String channel = channelPopularizeMapper.selectChannelByPid(popularizeId);
  143. // if (Constant.CHANNEL_NAME_360.equals(channel)) {
  144. // //查询该用户之前是否存在订单.
  145. // Integer count = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
  146. // .eq(OrderDon::getUserId, userId)
  147. // .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  148. // if (count > 0) {
  149. // throw new BusinessRuntimeException("您不符合360活动条件.");
  150. // }
  151. // }
  152. // }
  153. if (orderDon != null && orderDon.getStatus() == OrderDon.Status.refund) {
  154. throw BusinessRuntimeException.getInstance("您的订单已退款,无法使用该兑换码");
  155. }
  156. //生成车票订单
  157. getGroupTripsTicket(goodsDonSkuMapper.selectById(exchangeCode.getSkuId()), userId, orderDon, OrderDon.Type.EX_CODE);
  158. log.info("用户:{}通过兑换码:{}兑换成功", userId, exchangeCodeTicket.getCode());
  159. if (exchangeCode.getType() == 1) {
  160. luckyDrawRecordMapper.updateExCodeStatus(userId, exchangeCode.getCode());
  161. }
  162. return GatewayResponse.SUCCESS.newBuilder().toResult("兑换成功");
  163. }
  164. @Override
  165. public String getExCode(Long goodsId, Long skuId, Integer type) {
  166. ExchangeCodeReq exchangeCodeReq = new ExchangeCodeReq();
  167. exchangeCodeReq.setNumber(1);
  168. exchangeCodeReq.setGoodsId(goodsId);
  169. exchangeCodeReq.setSkuId(skuId);
  170. if (type != null) {
  171. exchangeCodeReq.setType(type);
  172. }
  173. try {
  174. List<ExcelExchangeCodeData> exchangeCodes = this.createExchangeCode(exchangeCodeReq);
  175. return exchangeCodes.get(0).getCode();
  176. } catch (Exception e) {
  177. return null;
  178. }
  179. }
  180. /**
  181. * 根据平台id获取填充的字符串
  182. */
  183. private String getFillByGoodsId(Long goodsId) {
  184. String goodsIdStr = String.valueOf(goodsId);
  185. if (goodsIdStr.length() == 1) {
  186. return String.format("%s%s%s", 0, 0, goodsId);
  187. }
  188. if (goodsIdStr.length() == 2) {
  189. return String.format("%s%s", 0, goodsId);
  190. }
  191. //最大不超过999
  192. if (goodsIdStr.length() > 3) {
  193. return goodsIdStr.substring(0, 3);
  194. }
  195. return goodsIdStr;
  196. }
  197. /**
  198. * 根据月份长度获取填充的字符串
  199. */
  200. private String getFillByMonth(Long skuMonth) {
  201. String goodsIdStr = String.valueOf(skuMonth);
  202. if (goodsIdStr.length() == 1) {
  203. return String.format("%s%s%s", 0, 0, skuMonth);
  204. }
  205. return String.format("%s%s", 0, skuMonth);
  206. }
  207. /**
  208. * 获取车位
  209. */
  210. @Override
  211. public GroupsRelation getGroupTripsTicket(GoodsDonSku sku, Long userId, OrderDon exCodeOrderDon, OrderDon.Type orderDonTye) {
  212. if (sku == null) {
  213. throw BusinessRuntimeException.getInstance("规格不存在,请联系客服");
  214. }
  215. GoodsDon goodsDon = goodsDonMapper.selectById(sku.getGoodsId());
  216. if (goodsDon == null) {
  217. throw BusinessRuntimeException.getInstance("平台不存在,请联系客服");
  218. }
  219. User user = userMapper.selectById(userId);
  220. if (user == null) {
  221. throw BusinessRuntimeException.getInstance("用户不存在");
  222. }
  223. GroupsRelation relation = getRelationNoOrder(sku, userId);
  224. Long relationId = relation.getId();
  225. OrderDon orderDon;
  226. if (exCodeOrderDon != null) {
  227. orderDon = exCodeOrderDon;
  228. orderDon.setRelationId(relationId);
  229. orderDon.setUserId(userId);
  230. orderDon.setStatus(goodsDon.getType() == 1 && goodsDon.getSecondType() == 2 ? OrderDon.Status.complete : OrderDon.Status.hasPayment);
  231. orderDonMapper.updateById(orderDon);
  232. if (orderDon.getIsDp()) {
  233. //是否已经发送优惠加购车票
  234. OrderDiscountPlusPurchaseSkuRelation purchaseSkuRelation = orderDiscountPlusPurchaseSkuRelationMapper.selectOne(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  235. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId()));
  236. if (purchaseSkuRelation != null) {
  237. String plusSkuIdsStr = purchaseSkuRelation.getPlusSkuIds();
  238. String relationIdsStr = purchaseSkuRelation.getRelationIds();
  239. if (StrUtil.isNotEmpty(plusSkuIdsStr) && StrUtil.isEmpty(relationIdsStr)) {
  240. try {
  241. List<Long> plusSkuIds = Jsons.parseList(plusSkuIdsStr, Long.class);
  242. //发送优惠加购 规格车票
  243. List<Long> dis_relation_ids = new ArrayList<>();
  244. plusSkuIds.forEach(plus_skuId -> {
  245. GoodsDonSku plus_sku = goodsDonSkuMapper.selectById(plus_skuId);
  246. if (plus_sku == null) {
  247. log.error("订单id:{}优惠加购规格已被删除 skuId:{},车票未发送", orderDon.getId(), plus_skuId);
  248. return;
  249. }
  250. GroupsRelation relationNoOrder = getRelationNoOrder(plus_sku, orderDon.getUserId());
  251. dis_relation_ids.add(relationNoOrder.getId());
  252. });
  253. //保存订单关联优惠加购车票
  254. orderDiscountPlusPurchaseSkuRelationMapper.update(null, Wrappers.lambdaUpdate(OrderDiscountPlusPurchaseSkuRelation.class)
  255. .set(OrderDiscountPlusPurchaseSkuRelation::getRelationIds, dis_relation_ids.toString())
  256. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId())
  257. .isNull(OrderDiscountPlusPurchaseSkuRelation::getRelationIds));
  258. } catch (Exception e) {
  259. }
  260. }
  261. }
  262. }
  263. } else {
  264. /* 生成订单 */
  265. String donNo = SEQUENCE.nextId().toString();
  266. orderDon = new OrderDon();
  267. orderDon.setOrderNo(donNo);
  268. orderDon.setOpenId(user.getOpenId());
  269. orderDon.setMoney(BigDecimal.ZERO);
  270. orderDon.setSkuId(sku.getId());
  271. orderDon.setRelationId(relationId);
  272. //默认数量为1
  273. orderDon.setNum(1);
  274. orderDon.setGoodsId(sku.getGoodsId());
  275. orderDon.setStatus(goodsDon.getType() == 1 && goodsDon.getSecondType() == 2 ? OrderDon.Status.complete : OrderDon.Status.hasPayment);
  276. if (relation.getStartTime() == null || relation.getExpiryTime() == null) {
  277. orderDon.setStatus(OrderDon.Status.hasPayment);
  278. }
  279. //兑换码兑换
  280. orderDon.setType(orderDonTye);
  281. orderDon.setUserId(user.getId());
  282. StringBuilder payTitle = new StringBuilder();
  283. payTitle.append(goodsDon.getTitle());
  284. payTitle.append(sku.getSpecVal());
  285. orderDon.setPayTitle(payTitle.toString());
  286. orderDonMapper.insert(orderDon);
  287. log.info("用户{}兑换规格:{}车位成功", user.getId(), orderDon.getSkuId());
  288. }
  289. if (orderDonTye == OrderDon.Type.EX_CODE) {
  290. //同步车票是否重购 记录
  291. TASK_POOL.execute(() -> {
  292. groupsRelationExpiryRecordService.syncGroupsRelationExpiryRecord(orderDon, goodsDon, sku);
  293. });
  294. }
  295. // if (StrUtil.isNotEmpty(user.getOpenId())) {
  296. // //发送模板消息
  297. // THREAD_POOL_TASK_EXECUTOR.execute(() -> {
  298. // try {
  299. // if (StrUtil.isNotEmpty(user.getOpenId())) {
  300. // log.info("用户{}兑换车位成功,发送新订单模板消息", user.getId());
  301. // templateCommonService.newOderSendMsgByType(orderDon, goodsDon, user, user.getOpenId(), false);
  302. // }
  303. // } catch (Exception e) {
  304. // log.info("用户{}兑换车位成功,发送消息失败:{}", user.getId(), e);
  305. // }
  306. // });
  307. // }
  308. //
  309. // THREAD_POOL_TASK_EXECUTOR.execute(() -> {
  310. // try {
  311. // //发送至客服消息
  312. // List<CustomerService> customerServices = customerServiceMapper.selectList(null);
  313. // for (CustomerService customerService : customerServices) {
  314. // log.info("向客服{}发送用户兑换码兑换车票消息通知..", customerService.getNickName());
  315. // templateCommonService.newOderSendMsgByType(orderDon, goodsDon, user, customerService.getOpenId(), true);
  316. // }
  317. // } catch (Exception e) {
  318. // log.error("向客服发送用户{}兑换码兑换车票成功,发送消息失败:{}", user.getId(), e);
  319. // }
  320. // });
  321. relation.setOrderId(orderDon.getId());
  322. return relation;
  323. }
  324. @Override
  325. public GroupsRelation getRelationNoOrder(GoodsDonSku sku, Long userId) {
  326. GroupsRelation relation = null;
  327. Integer retryNum = 1;
  328. List<Long> errorsRelationIds = new ArrayList<>();
  329. relation = getFinalRelation(sku, userId, relation, retryNum, errorsRelationIds);
  330. return relation;
  331. }
  332. public GroupsRelation getFinalRelation(GoodsDonSku sku, Long userId, GroupsRelation relation, Integer retryNum, List<Long> errorsRelationIds) {
  333. //寻找差不多过期时间规格的车位
  334. relation = groupRelationFrontService.getSimilarExpiredGroupRelation(sku.getId(), sku.getDays(), sku.getMonths(), errorsRelationIds);
  335. if (relation == null) {
  336. GroupsTrips groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  337. .eq(GroupsTrips::getSkuId, sku.getId())
  338. .gt(GroupsTrips::getAvailableNum, 0).last("limit 1")
  339. .eq(GroupsTrips::getStatus, GroupsTrips.Status.validity)
  340. .orderByAsc(GroupsTrips::getAvailableNum));
  341. //待发车
  342. if (groups == null) {
  343. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  344. .eq(GroupsTrips::getSkuId, sku.getId())
  345. .gt(GroupsTrips::getAvailableNum, 0).last("limit 1")
  346. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  347. .orderByAsc(GroupsTrips::getAvailableNum));
  348. }
  349. if (groups == null) {
  350. //若是ChatGPT Plus 、MidJourney
  351. //获取额外的车位
  352. relation = getOutSideRelationIfAi(userId, groups, sku);
  353. } else {
  354. //寻找快满编车队进行占座
  355. relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  356. .eq(GroupsRelation::getGroupsId, groups.getId())
  357. .notIn(errorsRelationIds != null && errorsRelationIds.size() > 0, GroupsRelation::getId, errorsRelationIds)
  358. .eq(GroupsRelation::getStatus, "none")
  359. .eq(GroupsRelation::getUserId, 0)
  360. .orderByAsc(GroupsRelation::getNum)
  361. .last("limit 1")
  362. );
  363. log.info("寻找快满编车队的车位relationId:{}", relation.getId());
  364. //如果占位失败 新增车位并关联
  365. if (relation == null) {
  366. relation = getOutSideRelationIfAi(userId, groups, sku);
  367. }
  368. }
  369. }
  370. try {
  371. //锁定座位
  372. setRelation(relation.getId(), userId, relation.getGroupsId(), relation.getStatus());
  373. relation.setUserId(userId);
  374. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  375. if (GroupsTrips.Status.validity.equals(groupsTrips.getStatus())) {
  376. //如果续费增加时间,如果首次则设置当前时间为初始时间
  377. Date expiryTime = Optional.ofNullable(relation.getExpiryTime()).orElse(new Date());
  378. Date newDate;
  379. if (sku.getDays() != null && sku.getDays() > 0) {
  380. newDate = DateUtil.offsetDay(expiryTime, sku.getDays() * 1);
  381. } else {
  382. newDate = DateUtil.offset(expiryTime, DateField.MONTH, sku.getMonths() * 1);
  383. }
  384. relation.setExpiryTime(newDate);
  385. relation.setStartTime(relation.getStartTime() == null ? new Date() : null);
  386. }
  387. if (relation.getStatus() != GroupsRelation.Status.outside) {
  388. relation.setStatus(GroupsRelation.Status.validity);
  389. }
  390. groupsRelationMapper.updateById(relation);
  391. redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + relation.getId());
  392. } catch (Exception e) {
  393. Object value = redisService.get(RedisKey.GROUPS_RELATION_NUM_KEY + relation.getId());
  394. if (value != null && userId.equals(Long.parseLong(value.toString()))) {
  395. redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + relation.getId());
  396. }
  397. errorsRelationIds.add(relation.getId());
  398. if (retryNum == 15) {
  399. log.error("用户:{}获取车票:{}异常", userId, relation.getId());
  400. throw BusinessRuntimeException.getInstance("获取车票异常,请联系客服");
  401. }
  402. //失败重新给他分配车位
  403. getFinalRelation(sku, userId, relation, ++retryNum, errorsRelationIds);
  404. }
  405. return relation;
  406. }
  407. private void setRelation(Long relationId, Long userId, Long groupsId, GroupsRelation.Status status) {
  408. if (redisService.get(RedisKey.GROUPS_RELATION_NUM_KEY + relationId) != null) {
  409. log.info("=====>用户:{}获取了已有人座位:{}", userId, relationId);
  410. throw new BusinessRuntimeException("客官手慢啦,该座位已经有人啦!");
  411. } else {
  412. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  413. log.info("=====>用户:{}未抢到座位:{}", userId, relationId);
  414. throw new BusinessRuntimeException("客官手慢啦,该座位已经有人啦!");
  415. }
  416. if (status == GroupsRelation.Status.outside) {
  417. return;
  418. }
  419. int count = groupsMapper.decrAvailableNum(groupsId);
  420. if (count == 0) {
  421. log.error("车位异常 groupId:{}", groupsId);
  422. groupsMapper.updateAvailableNum(groupsId);
  423. throw new BusinessRuntimeException("车位异常");
  424. }
  425. }
  426. }
  427. /**
  428. * 新增新车位并关联车位
  429. */
  430. private GroupsRelation createNewGroupTripsAndRelation(GoodsDonSku sku, GroupsTrips groups, GroupsRelation relation) {
  431. //通过兑换码兑换车票 新增车位
  432. if (groups == null) {
  433. groups = new GroupsTrips();
  434. }
  435. //补充占位
  436. if (relation == null) {
  437. relation = new GroupsRelation();
  438. }
  439. groups.setSkuId(sku.getId());
  440. groups.setNum(sku.getNum());
  441. groups.setAvailableNum(sku.getNum());
  442. if (sku.getGoodsId() == 23) {
  443. AccountView accountView = beanSearcher.searchFirst(AccountView.class, MapUtils.builder().field(AccountView::getGoodsId, 23).onlySelect(AccountView::getId).build());
  444. if (accountView != null) {
  445. groups.setAccountId(accountView.getId());
  446. groups.setStatus(GroupsTrips.Status.validity);
  447. groups.setRemark("已设置唯一账号");
  448. }else {
  449. groups.setStatus(GroupsTrips.Status.waiting);
  450. groups.setRemark("等待设置账号");
  451. }
  452. } else {
  453. groups.setStatus(GroupsTrips.Status.waiting);
  454. groups.setRemark("等待设置账号");
  455. }
  456. groupsMapper.insert(groups);
  457. relation.setGroupsId(groups.getId());
  458. relation.setNum(1);
  459. relation.setStatus(GroupsRelation.Status.none);
  460. relation.setGroupsId(groups.getId());
  461. groupsRelationMapper.insert(relation);
  462. //补充其他占位
  463. for (int i = 2; i <= groups.getNum(); i++) {
  464. GroupsRelation groupsRelation = new GroupsRelation();
  465. groupsRelation.setGroupsId(groups.getId());
  466. groupsRelation.setNum(i);
  467. groupsRelation.setStatus(GroupsRelation.Status.none);
  468. groupsRelationMapper.insert(groupsRelation);
  469. }
  470. return relation;
  471. }
  472. public GroupsRelation getOutSideRelationIfAi(Long userId, GroupsTrips groups, GoodsDonSku sku) {
  473. //若是MidJourney、ChatGPT PLUS每个已满车队 硬塞5个座位
  474. //主账号过期时间10天以外
  475. GroupsRelation relation = null;
  476. if (Constant.AI_goodsIds.contains(sku.getGoodsId())) {
  477. DateTime tenExpiry = DateUtil.offsetDay(DateUtil.beginOfDay(DateTime.now()), 10);
  478. Long groupsId = groupsRelationMapper.getOutSideGroupsTripsRelationByGoodsId(sku.getId(), tenExpiry, 5);
  479. if (groupsId != null) {
  480. relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  481. .eq(GroupsRelation::getGroupsId, groupsId)
  482. .eq(GroupsRelation::getUserId, 0)
  483. .eq(GroupsRelation::getStatus, GroupsRelation.Status.outside)
  484. .last("limit 1"));
  485. if (relation == null) {
  486. if (!redisService.setNx(RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getName() + groupsId, groupsId, RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getTimeout())) {
  487. relation = new GroupsRelation();
  488. relation.setStatus(GroupsRelation.Status.outside);
  489. relation.setUserId(userId);
  490. relation.setGroupsId(groupsId);
  491. GroupsRelation maxNumRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  492. relation.setNum(maxNumRelation.getNum() + 1);
  493. groupsRelationMapper.insert(relation);
  494. }
  495. }
  496. }
  497. }
  498. if (relation == null) {
  499. //新增车位 并关联
  500. relation = createNewGroupTripsAndRelation(sku, groups, relation);
  501. log.info("无合适规格车队,新增新车队,获取车位relationId:{}", relation.getId());
  502. }
  503. return relation;
  504. }
  505. }