ExchangeCodeServiceImpl.java 22 KB

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