SchedulerServiceImpl.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package com.cyksj.service.scheduler.impl;
  2. import cn.hutool.core.date.DateTime;
  3. import cn.hutool.core.date.DateUnit;
  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.cyksj.common.constant.Constant;
  8. import com.cyksj.common.util.StringUtil;
  9. import com.cyksj.dto.RedisKey;
  10. import com.cyksj.mapper.*;
  11. import com.cyksj.model.entity.*;
  12. import com.cyksj.model.manage.views.GroupsRelationView;
  13. import com.cyksj.model.request.ChangeRelationReq;
  14. import com.cyksj.redis.RedisService;
  15. import com.cyksj.service.error.UserRelationChangeErrorRecordService;
  16. import com.cyksj.service.groups.GroupsFuncService;
  17. import com.cyksj.service.mange.CmsOrderDonService;
  18. import com.cyksj.service.relation.GroupRelationClearService;
  19. import com.cyksj.service.scheduler.SchedulerService;
  20. import com.cyksj.service.user.UserBenefitsService;
  21. import com.ejlchina.searcher.BeanSearcher;
  22. import com.ejlchina.searcher.param.Operator;
  23. import com.ejlchina.searcher.util.MapUtils;
  24. import lombok.RequiredArgsConstructor;
  25. import lombok.extern.slf4j.Slf4j;
  26. import org.springframework.stereotype.Service;
  27. import java.math.BigDecimal;
  28. import java.math.RoundingMode;
  29. import java.util.Date;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.concurrent.ConcurrentHashMap;
  33. /*
  34. *项目名: netflix
  35. *文件名: SchedulerServiceImpl
  36. *创建者: JavaZou
  37. *创建时间:2023/6/8 16:48
  38. */
  39. @Service
  40. @RequiredArgsConstructor
  41. @Slf4j
  42. public class SchedulerServiceImpl implements SchedulerService {
  43. private final GoodsDonSkuMapper skuMapper;
  44. private final GroupsMapper groupsMapper;
  45. private final BeanSearcher beanSearcher;
  46. private final OrderDonMapper orderDonMapper;
  47. private final GroupsRelationMapper groupsRelationMapper;
  48. private final GroupRelationClearService groupRelationClearService;
  49. private final UserBenefitsService userBenefitsService;
  50. private final GroupsFuncService groupsFuncService;
  51. private final CmsOrderDonService cmsOrderDonService;
  52. private final UserRelationChangeErrorRecordService changeErrorRecordService;
  53. private final UserRelationChangeErrorRecordMapper userRelationChangeErrorRecordMapper;
  54. private final GoodsDonMapper goodsDonMapper;
  55. private final RedisService redisService;
  56. @Override
  57. public void transExpiryAccountValidRelation() {
  58. DateTime now = new DateTime();
  59. DateTime nextBeginDay = DateUtil.offsetDay(DateUtil.beginOfDay(now), 1);
  60. //针对AI类 CHAT PLUS、MidJourney 月付
  61. List<Long> aiSkuIds = skuMapper.selectAIMonthSkuIds(Constant.AI_goodsIds);
  62. List<GroupsTrips> expiryAccountGroups = groupsMapper.getExpiryAccountGroups(nextBeginDay, aiSkuIds);
  63. expiryAccountGroups.forEach(expiry_groups -> {
  64. if (expiry_groups.getStatus() != GroupsTrips.Status.down) {
  65. expiry_groups.setStatus(GroupsTrips.Status.down);
  66. groupsMapper.updateById(expiry_groups);
  67. }
  68. Long g_groupsId = expiry_groups.getId();
  69. Date a_expiryTime = expiry_groups.getExpiryTime();
  70. //未过期用户 只分配有效的用户车票 outside状态过滤
  71. List<GroupsRelationView> groupsRelations = beanSearcher.searchAll(GroupsRelationView.class, MapUtils.builder()
  72. .field(GroupsRelationView::getGroupsId, g_groupsId)
  73. .field(GroupsRelationView::getStatus, GroupsRelation.Status.validity.name())
  74. .field(GroupsRelationView::getExpiryTime, nextBeginDay).op(Operator.GreaterEqual)
  75. .build());
  76. reAssign(g_groupsId, now, groupsRelations);
  77. });
  78. }
  79. @Override
  80. public void assignUserGroupsRelation(Long groupsId) {
  81. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  82. if (groupsTrips == null || groupsTrips.getAccountId() == null) return;
  83. String key = RedisKey.DISABLE_ACCOUNT_ASSIGN + groupsId;
  84. if (!redisService.setNx(key, groupsId, 60 * 3l)) {
  85. return;
  86. }
  87. if (groupsTrips.getStatus() != GroupsTrips.Status.down) {
  88. groupsTrips.setStatus(GroupsTrips.Status.down);
  89. groupsMapper.updateById(groupsTrips);
  90. }
  91. DateTime now = DateTime.now();
  92. //迁移用户
  93. List<GroupsRelationView> groupsRelations = beanSearcher.searchAll(GroupsRelationView.class, MapUtils.builder()
  94. .field(GroupsRelationView::getGroupsId, groupsId)
  95. .field(GroupsRelationView::getStatus, List.of(GroupsRelation.Status.validity.name(), GroupsRelation.Status.outside.name())).op(Operator.InList)
  96. .field(GroupsRelationView::getExpiryTime, now).op(Operator.GreaterEqual)
  97. .build());
  98. reAssign(groupsId, now, groupsRelations);
  99. redisService.del(key);
  100. }
  101. /**
  102. * 重新分配车位
  103. */
  104. public void reAssign(Long g_groupsId, DateTime now, List<GroupsRelationView> groupsRelations) {
  105. log.info("迁移groupsId:{}未过期用户数量:{}", g_groupsId, groupsRelations.size());
  106. Map<Long, GoodsDon> goodsMap = new ConcurrentHashMap<>();
  107. Map<Long, GoodsDonSku> skuMap = new ConcurrentHashMap<>();
  108. groupsRelations.forEach(relationView -> {
  109. Long change_relationId = relationView.getId();
  110. Long userId = relationView.getUserId();
  111. UserRelationChangeErrorRecord exists = userRelationChangeErrorRecordMapper.selectOne(Wrappers.lambdaQuery(UserRelationChangeErrorRecord.class)
  112. .eq(UserRelationChangeErrorRecord::getRelationId, change_relationId)
  113. .eq(UserRelationChangeErrorRecord::getUserId, userId)
  114. .eq(UserRelationChangeErrorRecord::getDeleted, true)
  115. .last("limit 1"));
  116. if (exists != null) {
  117. log.info("存在userId:{}无法转移的车票relationId:{}", userId, change_relationId);
  118. return;
  119. }
  120. Date expiryTime = relationView.getExpiryTime();
  121. Long skuId = relationView.getSkuId();
  122. //仅针对chatGPT
  123. if (relationView.getGoodsId() == 18) {
  124. Long bet_day = DateUtil.between(now, expiryTime, DateUnit.DAY);
  125. //10天以内
  126. if (bet_day <= 10) {
  127. //分配到过期账号5天内误差的相同规格车队里
  128. DateTime five_day = DateUtil.offsetDay(expiryTime, 5);
  129. Long item_groupsId = groupsMapper.selectSameSpecItemGroupsByTime(g_groupsId, skuId, expiryTime, five_day, false);
  130. if (item_groupsId == null) {
  131. //无对应车队 退款
  132. //退款至余额
  133. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  134. .eq(OrderDon::getRelationId, change_relationId)
  135. .eq(OrderDon::getUserId, userId)
  136. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  137. .orderByDesc(OrderDon::getId)
  138. .last("limit 1"));
  139. if (orderDon == null) {
  140. //更换过车票
  141. orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  142. .eq(OrderDon::getSkuId, skuId)
  143. .eq(OrderDon::getUserId, userId)
  144. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  145. .orderByDesc(OrderDon::getId)
  146. .last("limit 1"));
  147. }
  148. if (orderDon == null) {
  149. log.error("用户userId:{}的车票relationId:{}账号过期后转移错误", userId, change_relationId);
  150. changeErrorRecordService.changeTicketErrorRecord(relationView, UserRelationChangeErrorRecord.Source.change);
  151. return;
  152. }
  153. //清除车票
  154. GroupsRelation relation = groupsRelationMapper.selectById(change_relationId);
  155. groupRelationClearService.clearTicket(relation, UserTicketClearedRecord.Source.timing_change_ticket);
  156. //退款至余额
  157. //实付金额 + 余额
  158. BigDecimal money = orderDon.getMoney().add(orderDon.getBalance());
  159. //当月天数
  160. Date payTime = orderDon.getPayTime();
  161. if (payTime == null) {
  162. payTime = orderDon.getCreatedTime();
  163. }
  164. if (money.compareTo(BigDecimal.ZERO) == 0) {
  165. GoodsDonSku sku = skuMapper.selectById(skuId);
  166. if (sku != null) {
  167. money = sku.getPrice();
  168. }
  169. }
  170. int dayNum = DateUtil.dayOfMonth(DateUtil.endOfMonth(payTime));
  171. BigDecimal re_balance = money.divide(BigDecimal.valueOf(dayNum), 0, RoundingMode.DOWN).multiply(BigDecimal.valueOf(bet_day));
  172. if (re_balance.compareTo(BigDecimal.ZERO) <= 0) {
  173. log.info("user_id:{},relationId:{}返回余额为0", userId, change_relationId);
  174. return;
  175. }
  176. userBenefitsService.addUserBalance(userId, re_balance);
  177. log.info("车票未到期清除,退款至用户user_id:{}余额:{}成功", userId, re_balance);
  178. userBenefitsService.recordBalanceBySource(userId, re_balance, UserBalanceSourceRecord.Source.clear_valid);
  179. //修改订单状态 为退款
  180. orderDon.setStatus(OrderDon.Status.refund);
  181. orderDon.setRefundBalance(re_balance);
  182. orderDon.setRefundMoney(BigDecimal.ZERO);
  183. orderDonMapper.updateById(orderDon);
  184. GoodsDon goodsDon = goodsMap.get(relationView.getGoodsId());
  185. if (goodsDon == null) {
  186. goodsDon = goodsDonMapper.selectById(relationView.getGoodsId());
  187. if (goodsDon == null) return;
  188. goodsMap.putIfAbsent(relationView.getGoodsId(), goodsDon);
  189. }
  190. GoodsDonSku sku = skuMap.get(orderDon.getSkuId());
  191. if (sku == null) {
  192. sku = skuMapper.selectById(orderDon.getSkuId());
  193. if (sku == null) return;
  194. skuMap.putIfAbsent(orderDon.getSkuId(), sku);
  195. }
  196. cmsOrderDonService.refundRecord(orderDon, goodsDon, sku, StrUtil.EMPTY, "balance");
  197. return;
  198. }
  199. changeTickerRelation(item_groupsId, relationView, UserTicketClearedRecord.Source.timing_change_ticket);
  200. return;
  201. }
  202. //大于10天
  203. //分配到过期账号10天内误差的相同规格车队里
  204. DateTime ten_day = DateUtil.offsetDay(expiryTime, 10);
  205. Long item_groupsId = groupsMapper.selectSameSpecItemGroupsByTime(g_groupsId, skuId, expiryTime, ten_day, true);
  206. if (item_groupsId == null) {
  207. //无对应车队 生成空车队
  208. //寻找空车队
  209. item_groupsId = groupsMapper.selectSameSpecEmptyGroups(skuId);
  210. if (item_groupsId == null) {
  211. //新增空车队
  212. GoodsDonSku sku = skuMapper.selectById(skuId);
  213. GroupsRelation new_relation = groupsFuncService.createNewGroupsTrips(sku);
  214. item_groupsId = new_relation.getGroupsId();
  215. }
  216. //新车队
  217. changeTickerRelation(item_groupsId, relationView, UserTicketClearedRecord.Source.new_groups_ticket);
  218. return;
  219. }
  220. changeTickerRelation(item_groupsId, relationView, UserTicketClearedRecord.Source.timing_change_ticket);
  221. return;
  222. }
  223. if (relationView.getGoodsId() == 26) {
  224. //移入合适车队
  225. Long item_groupsId = groupsMapper.selectMidJourneySameSpecItemGroups(g_groupsId, skuId, expiryTime);
  226. if (item_groupsId == null) {
  227. //midJourney 无合适车队
  228. log.error("midJourney账号过期groupsId:{},用户车票relation_id:{}", g_groupsId, change_relationId);
  229. changeErrorRecordService.changeTicketErrorRecord(relationView, UserRelationChangeErrorRecord.Source.change);
  230. return;
  231. }
  232. changeTickerRelation(item_groupsId, relationView, UserTicketClearedRecord.Source.timing_change_ticket);
  233. }
  234. });
  235. }
  236. public void changeTickerRelation(Long item_groupsId, GroupsRelationView relationView, UserTicketClearedRecord.Source source) {
  237. Long change_relationId = relationView.getId();
  238. try {
  239. ChangeRelationReq req = new ChangeRelationReq();
  240. req.setGroupsId(item_groupsId);
  241. req.setRelationId(change_relationId);
  242. req.setSource(source);
  243. cmsOrderDonService.changeRelation(req);
  244. } catch (Exception e) {
  245. log.error("更换用户relationId:{}错误:{}", change_relationId, StringUtil.getErrorText(e));
  246. relationView.setErrorMsg(StringUtil.getErrorMsg(e));
  247. changeErrorRecordService.changeTicketErrorRecord(relationView, UserRelationChangeErrorRecord.Source.change);
  248. }
  249. }
  250. }