ExchangeCodeServiceImpl.java 23 KB

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