GroupRelationFrontServiceImpl.java 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  1. package com.cyksj.service.relation.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.collection.CollectionUtil;
  4. import cn.hutool.core.date.BetweenFormater;
  5. import cn.hutool.core.date.DateTime;
  6. import cn.hutool.core.date.DateUtil;
  7. import cn.hutool.core.lang.Assert;
  8. import cn.hutool.core.lang.Validator;
  9. import cn.hutool.core.util.ObjectUtil;
  10. import cn.hutool.core.util.StrUtil;
  11. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  12. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  13. import com.cyksj.common.constant.Constant;
  14. import com.cyksj.common.exception.BusinessRuntimeException;
  15. import com.cyksj.common.snowflake.Sequence;
  16. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  17. import com.cyksj.common.util.Jsons;
  18. import com.cyksj.common.util.StringUtil;
  19. import com.cyksj.enums.GatewayApiCode;
  20. import com.cyksj.mapper.*;
  21. import com.cyksj.mapper.manage.distribute.DistributeGeneralSkuRateMapper;
  22. import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
  23. import com.cyksj.mapper.manage.distribute.UserPlatDistributeRateMapper;
  24. import com.cyksj.mapper.manage.distribute.UserPlatSkuDistributeRateMapper;
  25. import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
  26. import com.cyksj.mapper.renew.RenewUpgradePackageMapper;
  27. import com.cyksj.mapper.sys.SysConfigMapper;
  28. import com.cyksj.mapper.sys.SysEmailMapper;
  29. import com.cyksj.mapper.vip.VipGoodsSkuMapper;
  30. import com.cyksj.mapper.vip.VipUserMapper;
  31. import com.cyksj.model.dto.ErrorNetflixChangeOtherSkuTicketDto;
  32. import com.cyksj.model.dto.TicketChangeDto;
  33. import com.cyksj.model.entity.*;
  34. import com.cyksj.model.manage.views.AccountView;
  35. import com.cyksj.model.manage.views.GroupsRelationView;
  36. import com.cyksj.model.request.ErrorNetflixChangeReq;
  37. import com.cyksj.model.request.OrderRefundReq;
  38. import com.cyksj.model.request.SpecialGoodsTicketReq;
  39. import com.cyksj.model.request.TicketLoginReq;
  40. import com.cyksj.model.response.NetflixErrorAccountStatus;
  41. import com.cyksj.model.response.NetflixRecoverResp;
  42. import com.cyksj.model.response.NetflixRefundInfoResp;
  43. import com.cyksj.model.views.*;
  44. import com.cyksj.redis.RedisService;
  45. import com.cyksj.service.chatgpt.ChatGptAccountService;
  46. import com.cyksj.service.chatgpt.ChatGptAuthService;
  47. import com.cyksj.service.claude.ClaudeService;
  48. import com.cyksj.service.groups.GroupsFuncService;
  49. import com.cyksj.service.luma.LumaService;
  50. import com.cyksj.service.mail.CommonMailService;
  51. import com.cyksj.service.mail.MailService;
  52. import com.cyksj.service.mange.coupon.CouponCommonService;
  53. import com.cyksj.service.midjourney.MidjourneyAccountService;
  54. import com.cyksj.service.order.OrderRefundService;
  55. import com.cyksj.service.relation.GroupRelationClearService;
  56. import com.cyksj.service.relation.GroupRelationFrontService;
  57. import com.cyksj.service.relation.GroupsRelationChangeService;
  58. import com.cyksj.service.relation.GroupsRelationNetflixService;
  59. import com.cyksj.service.user.UserBenefitsService;
  60. import com.cyksj.service.user.UserBindRelationService;
  61. import com.cyksj.service.user.UserLoginRecordService;
  62. import com.ejlchina.searcher.BeanSearcher;
  63. import com.ejlchina.searcher.SearchResult;
  64. import com.ejlchina.searcher.param.Operator;
  65. import com.ejlchina.searcher.util.MapBuilder;
  66. import com.ejlchina.searcher.util.MapUtils;
  67. import com.github.rholder.retry.*;
  68. import lombok.RequiredArgsConstructor;
  69. import lombok.extern.slf4j.Slf4j;
  70. import org.springframework.dao.DuplicateKeyException;
  71. import org.springframework.stereotype.Service;
  72. import org.springframework.transaction.annotation.Transactional;
  73. import javax.servlet.http.HttpServletRequest;
  74. import java.math.BigDecimal;
  75. import java.math.RoundingMode;
  76. import java.util.*;
  77. import java.util.concurrent.ExecutionException;
  78. import java.util.concurrent.TimeUnit;
  79. import java.util.concurrent.atomic.AtomicInteger;
  80. import java.util.stream.Collectors;
  81. import static com.cyksj.enums.GatewayApiCode.GROUP_INDEX_ALREADY_BE_USER;
  82. import static com.cyksj.enums.GatewayApiCode.GROUP_INDEX_NOT_FIND;
  83. /*
  84. *项目名: netflix
  85. *文件名: GroupRelationFrontServiceImpl
  86. *创建者: JavaZou
  87. *创建时间:2022/12/29 15:42
  88. */
  89. @Service
  90. @RequiredArgsConstructor
  91. @Slf4j
  92. public class GroupRelationFrontServiceImpl implements GroupRelationFrontService {
  93. private final UserBindRelationService userBindRelationService;
  94. private final UserMapper userMapper;
  95. private final BeanSearcher beanSearcher;
  96. private final CouponCommonService couponCommonService;
  97. private final GroupsRelationMapper groupsRelationMapper;
  98. private final GroupsMapper groupsMapper;
  99. private final ChatGptAuthService chatGptAuthService;
  100. private final RedisService redisService;
  101. private final MailService mailService;
  102. private final OrderDonMapper orderDonMapper;
  103. private final GroupsRelationExpiryNotifyRecordMapper groupsRelationExpiryNotifyRecordMapper;
  104. private final HttpServletRequest request;
  105. private final GroupsFuncService groupsFuncService;
  106. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  107. private final GroupsRelationLoginCodeRecordMapper groupsRelationLoginCodeRecordMapper;
  108. private final SysEmailMapper sysEmailMapper;
  109. private final GoodsDonSkuMapper goodsDonSkuMapper;
  110. private final UserFuncPropertyMapper userFuncPropertyMapper;
  111. private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
  112. private final UserLoginRecordService userLoginRecordService;
  113. private final UserCertRecordMapper userCertRecordMapper;
  114. private final MidjourneyAccountService midjourneyAccountService;
  115. private final ChatGptAccountService chatGptAccountService;
  116. private final UpgradePackageMapper upgradePackageMapper;
  117. private final LumaService lumaService;
  118. private final GroupsRelationNetflixService groupsRelationNetflixService;
  119. private final UserDistributeMapper userDistributeMapper;
  120. private final UserPlatDistributeRateMapper userPlatDistributeRateMapper;
  121. private final GoodsDonMapper goodsDonMapper;
  122. private final UserPlatSkuDistributeRateMapper userPlatSkuDistributeRateMapper;
  123. private final DistributeGeneralSkuRateMapper distributeGeneralSkuRateMapper;
  124. private final RenewUpgradePackageMapper renewUpgradePackageMapper;
  125. private final ClaudeService claudeService;
  126. private final UserDistributePosterRecordMapper userDistributePosterRecordMapper;
  127. private final OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  128. private final AccountMapper accountMapper;
  129. private final UserBenefitsMapper userBenefitsMapper;
  130. private final GroupsRelationChangeService changeTickerRelation;
  131. private final NetflixTempAccountUserMapper netflixTempAccountUserMapper;
  132. private final NetflixUserAccountStatusRecordMapper netflixUserAccountStatusRecordMapper;
  133. private final AccountNetflixStateMapper accountNetflixStateMapper;
  134. private final UserMirrorShopMapper userMirrorShopMapper;
  135. private final CommonMailService commonMailService;
  136. private final SysConfigMapper sysConfigMapper;
  137. private final GptMirrorDayCardGiveawayActivityMapper gptMirrorDayCardGiveawayActivityMapper;
  138. private final MirrorTicketPopupsRecordMapper mirrorTicketPopupsRecordMapper;
  139. private final VipUserMapper vipUserMapper;
  140. private final VipGoodsSkuMapper vipGoodsSkuMapper;
  141. private static final Sequence SEQUENCE = new Sequence(0);
  142. private final NetflixUserChangeOtherTicketRecordMapper netflixUserChangeOtherTicketRecordMapper;
  143. private final NetflixUserAccountSubmitRecoverRecordMapper netflixUserAccountSubmitRecoverRecordMapper;
  144. private final OrderRefundService orderRefundService;
  145. private final GroupRelationClearService clearService;
  146. private final UserBenefitsService userBenefitsService;
  147. @Override
  148. public SearchResult<RenewalView> getMyTicket(long userId, Boolean isLoginPopularize, String customId, String account, String orderNo, Integer cmt) {
  149. User u = userMapper.selectById(userId);
  150. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  151. if (u.getIsBlack()) {
  152. return new SearchResult<>();
  153. }
  154. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  155. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  156. if (cmt != null && cmt == 2 && StrUtil.isNotBlank(customId)) {
  157. UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
  158. .eq(UserMirrorShop::getCustomId, customId)
  159. .last("limit 1"));
  160. if (userMirrorShop != null) {
  161. builder.field(RenewalView::getCmt, cmt).field(RenewalView::getYhsId, userMirrorShop.getId());
  162. }
  163. }
  164. if (cmt == null || cmt != 2) {
  165. builder.field(RenewalView::getCmt, 2).op(Operator.NotEqual);
  166. }
  167. // Long yhsId = yhShopFrontService.getYhsIdByCustomId(customId);
  168. DateTime now = DateTime.now();
  169. if (StrUtil.isNotBlank(account)) {
  170. builder.field(RenewalView::getAccount, account).op(Operator.Contain);
  171. }
  172. String conditionSql = String.format("(gr.expiry_time is null or gr.expiry_time > '%s'", now);
  173. //镜像车票 过期7天后清除
  174. //个人店铺和AI店铺 暂不支持过期续费
  175. if (cmt == null && StrUtil.isEmpty(customId)) {
  176. conditionSql += String.format(" or (sku.is_mirror and gr.expiry_time > '%s')", DateUtil.offsetDay(now, -7));
  177. }
  178. conditionSql += ")";
  179. if (StrUtil.isNotEmpty(orderNo)) {
  180. conditionSql += String.format(" and exists(select 1 from order_don o where o.relation_id = gr.id and o.user_id = gr.user_id and o.order_no = %s and o.status not in ('close','noPayment','refund'))", orderNo);
  181. }
  182. SearchResult<RenewalView> list = beanSearcher.search(RenewalView.class, builder
  183. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  184. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  185. .put("condition", conditionSql)
  186. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  187. .orderBy(RenewalView::getExpiryTime).asc()
  188. .build());
  189. if (list.getDataList().size() > 0) {
  190. //过滤邀请制、已失效的车位
  191. Integer size = list.getTotalCount().intValue();
  192. //赠送GPT日卡 参与平台ids
  193. List<Long> renewReduceSkuIds = userBenefitsMapper.selectList(Wrappers.lambdaQuery(UserBenefits.class)
  194. .eq(UserBenefits::getType, UserBenefits.Type.RENEW).eq(UserBenefits::getStatus, 1).select(UserBenefits::getSkuId)).stream().map(UserBenefits::getSkuId).collect(Collectors.toList());
  195. List<Long> gptBuyGids = getGptMirrorGiveawayBuyGids();
  196. //gpt日卡活动
  197. GptMirrorDayCardGiveawayActivity gptMirrorDayCardGiveawayActivity = gptMirrorDayCardGiveawayActivityMapper.selectOne(Wrappers.lambdaQuery(GptMirrorDayCardGiveawayActivity.class)
  198. .last("limit 1"));
  199. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  200. .eq(SysConfig::getSysKey, Constant.EMAIL_PWD_SHOW_GID_KEY)
  201. .last("limit 1"));
  202. List<Long> showEmailPwdGids = new ArrayList<>();
  203. if (sysConfig != null && StrUtil.isNotBlank(sysConfig.getSysValue())) {
  204. try {
  205. showEmailPwdGids.addAll(Jsons.parseList(sysConfig.getSysValue(), Long.class));
  206. } catch (Exception e) {
  207. }
  208. }
  209. List<Long> vipSkuIds = vipGoodsSkuMapper.selectList(null).stream().map(VipGoodsSku::getSkuId).collect(Collectors.toList());
  210. Integer vipUserCount = vipUserMapper.selectCount(Wrappers.lambdaQuery(VipUser.class)
  211. .in(VipUser::getUserId, userIds)
  212. .gt(VipUser::getExpiryTime, now));
  213. list.getDataList().forEach(ticket -> {
  214. if (ticket.getSkuId() == null || ticket.getGoodsId() == null) {
  215. return;
  216. }
  217. if (ticket.getGoodsId() == 18 && ticket.getSkuNum() > 1) {
  218. ticket.setPassword(null);
  219. }
  220. ticket.setIsMulti(false);
  221. if (ticket.getSkuNum() > 1) {
  222. ticket.setIsMulti(true);
  223. }
  224. //chatGPT直连
  225. if (ticket.getGoodsId().equals(42l)) {
  226. if (StrUtil.isNotBlank(ticket.getAccount())) {
  227. String accessToken;
  228. try {
  229. accessToken = chatGptAuthService.getAccessToken(ticket.getAccount());
  230. ticket.setGptRefreshToken(accessToken);
  231. } catch (Exception e) {
  232. redisService.set(RedisService.key.CHAT_GPT_TOKEN_EXCEPTION_KEY.getName() + ticket.getAccount(), ticket.getAccount());
  233. }
  234. }
  235. ticket.setAccount(null);
  236. ticket.setPassword(null);
  237. } else {
  238. ticket.setGptRefreshToken(null);
  239. }
  240. if (ticket.getSecondType() == 1) {
  241. ticket.setAccount(null);
  242. ticket.setPassword(null);
  243. }
  244. //gpt 2月的独立账号可看到邮箱密码
  245. if (ticket.getGoodsId() == 18l && ticket.getSkuNum() == 1 && ticket.getAccount() != null && ticket.getCreatedTime().compareTo(DateUtil.parse("2025-02-01")) > 0) {
  246. } else {
  247. if (!showEmailPwdGids.contains(ticket.getGoodsId())) {
  248. ticket.setGptEmailPwd(null);
  249. }
  250. }
  251. if (isLoginPopularize != null && isLoginPopularize) {
  252. GoodsDonViews views = beanSearcher.searchFirst(GoodsDonViews.class, MapUtils.builder().field(GoodsDonViews::getId, ticket.getGoodsId()).build());
  253. views.setSpecs(beanSearcher.searchFirst(GoodsDonSpecFrontView.class, MapUtils.builder().field(GoodsDonSpecFrontView::getGoodsId, views.getId()).build()));
  254. views.setSkuList(beanSearcher.searchAll(GoodsDonSkuFrontView.class, MapUtils.builder().field(GoodsDonSkuFrontView::getGoodsId, views.getId()).field(GoodsDonSkuFrontView::getStatus, true).build()));
  255. ticket.setGoodsDonViews(views);
  256. }
  257. if (ticket.getMonths() != null && ticket.getMonths() >= 300) {
  258. ticket.setExpiryTime(null);
  259. }
  260. if (ticket.getExpiryTime() != null && ticket.getGoodsType() == 1) {
  261. String remainDays = DateUtil.formatBetween(now, ticket.getExpiryTime(), BetweenFormater.Level.DAY);
  262. if ("0天".equals(remainDays)) {
  263. remainDays = "小于1天";
  264. } else {
  265. //当天也算
  266. int days = Integer.parseInt(remainDays.substring(0, remainDays.indexOf("天")));
  267. remainDays = days + 1 + "天";
  268. }
  269. ticket.setRemainDays(remainDays);
  270. ticket.setTotal(DateUtil.betweenDay(ticket.getStartTime(), ticket.getExpiryTime(), false) + 1);
  271. }
  272. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  273. .eq(OrderDon::getRelationId, ticket.getRelationId())
  274. .eq(OrderDon::getUserId, ticket.getUserId())
  275. .eq(OrderDon::getOrderType, 1)
  276. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  277. .orderByDesc(OrderDon::getId)
  278. .last("limit 1"));
  279. if (orderDon != null) {
  280. ticket.setOrderNo(orderDon.getOrderNo());
  281. ticket.setOrderId(orderDon.getId());
  282. ticket.setTransactionId(orderDon.getTransactionId());
  283. if (ticket.getSecondType() == 1) {
  284. //是否完成邀请 根据订单状态
  285. ticket.setIsComplete(orderDon.getStatus() == OrderDon.Status.complete ? true : false);
  286. }
  287. }
  288. if (size > 1 && ticket.getGoodsId() != 18) {
  289. Date payTime = null;
  290. if (orderDon != null) {
  291. payTime = Optional.ofNullable(orderDon.getPayTime()).orElse(orderDon.getCreatedTime());
  292. }
  293. //加购订单
  294. if (orderDon == null) {
  295. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(ticket.getRelationId(), ticket.getUserId());
  296. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  297. String relationIds = data.getRelationIds();
  298. if (StrUtil.isEmpty(relationIds)) {
  299. return;
  300. }
  301. try {
  302. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  303. if (relationList.contains(ticket.getRelationId())) {
  304. OrderDon plusOrder = orderDonMapper.selectById(data.getOrderId());
  305. if (plusOrder != null) {
  306. payTime = Optional.ofNullable(plusOrder.getPayTime()).orElse(plusOrder.getCreatedTime());
  307. }
  308. break;
  309. }
  310. } catch (Exception e) {
  311. }
  312. }
  313. }
  314. ticket.setPayTime(payTime);
  315. }
  316. if (ticket.getSkuNum() != null && ticket.getSkuNum() == 1) {
  317. }
  318. //奈飞、gpt
  319. if (ticket.getGoodsId() == 1 || ticket.getGoodsId() == 18 || ticket.getGoodsId() == 33l) {
  320. ticket.setEmail(null);
  321. }
  322. //设置镜像车票信息
  323. setMirrorTicketInfo(ticket);
  324. // List<GroupsRelationUserView> relationUserViews = groupsRelationMapper.getUserRelationUserViews(ticket.getGroupId(), ticket.getRelationId(), ticket.getUserId(), List.of(GroupsRelation.Status.validity, GroupsRelation.Status.outside));
  325. // ticket.setRelationViews(relationUserViews);
  326. if (ticket.getExpiryTime() != null) {
  327. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  328. }
  329. //查看双重验证码
  330. if (StrUtil.isNotEmpty(ticket.getApiSecret())) {
  331. Boolean isHasVerifyCode = StrUtil.isNotBlank(ticket.getVerifyCode()) ? true : false;
  332. Integer codeNum = getUserCodeNumBySkuId(ticket.getUserId(), ticket.getSkuId(), isHasVerifyCode);
  333. ticket.setCodeNum(codeNum);
  334. }
  335. Long qaId = groupsRelationMapper.selectGoodsDonQaByGoodsId(ticket.getGoodsId());
  336. ticket.setQa(qaId > 0 ? true : false);
  337. //是否存在海报
  338. ticket.setPosterInfo(setGoodsPoster(ticket, u, userIds));
  339. //续费升级折扣
  340. setRenewDiscount(ticket);
  341. if (CollUtil.isNotEmpty(renewReduceSkuIds) && renewReduceSkuIds.contains(ticket.getSkuId())) {
  342. ticket.setIsRenewReduce(true);
  343. }
  344. if (CollUtil.isNotEmpty(gptBuyGids) && gptBuyGids.contains(ticket.getGoodsId())) {
  345. if (gptMirrorDayCardGiveawayActivity != null && orderDon != null && orderDon.getCreatedTime().compareTo(gptMirrorDayCardGiveawayActivity.getCreatedTime()) > 0) {
  346. //是否领取过GPT日卡
  347. Long orderId = orderDon.getId();
  348. Number count = beanSearcher.searchCount(GptMirrorDayCardActivityRecord.class, MapUtils.builder().field(GptMirrorDayCardActivityRecord::getOrderId, orderId).build());
  349. ticket.setReceivedGptGift(count.intValue() > 0);
  350. }
  351. }
  352. markVipDeductTicket(userIds, ticket, vipSkuIds, vipUserCount > 0);
  353. });
  354. }
  355. userLoginRecordService.saveUserLoginDayRecord(userId);
  356. return list;
  357. }
  358. @Override
  359. public Boolean isJoinCorpWx(Long userId, Boolean isJoin, Boolean noCoupon) {
  360. if (!isJoin) {
  361. User user = userMapper.selectById(userId);
  362. if (user == null || StrUtil.isEmpty(user.getUnionid())) {
  363. return true;
  364. }
  365. // CorpUser corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class)
  366. // .ne(CorpUser::getUnionid, "")
  367. // .eq(CorpUser::getUnionid, user.getUnionid())
  368. // .last("limit 1")
  369. // .select(CorpUser::getId)
  370. // );
  371. CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
  372. .field(CorpUserFollowView::getUnionId, user.getUnionid())
  373. .field(CorpUserFollowView::getStatus, 1).build());
  374. if (corpUserFollowView == null) {
  375. return false;
  376. }
  377. }
  378. //用户是否买了奈飞车票
  379. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  380. .field(RenewalView::getUserId, userId)
  381. .field(RenewalView::getGoodsId, 1)
  382. .field(RenewalView::getStatus, List.of("validity", "overdue")).op(Operator.InList)
  383. .build());
  384. if (number.intValue() > 0 && !noCoupon) {
  385. couponCommonService.sendCouponToUser(userId, 34l, 0l, 0l, 0l, CouponUser.Channel.wxCorp);
  386. }
  387. return true;
  388. }
  389. @Override
  390. public GroupsRelation getSimilarExpiredGroupRelation(GoodsDonSku sku, List<Long> errorsRelationIds, String ip) {
  391. Long skuId = sku.getId();
  392. Integer days = sku.getDays();
  393. Integer months = sku.getMonths();
  394. Integer maxNum = sku.getNum();
  395. DateTime expiryTime = null;
  396. if (days != null && days > 0) {
  397. expiryTime = DateUtil.offsetDay(DateTime.now(), days);
  398. } else {
  399. expiryTime = DateUtil.offsetMonth(DateTime.now(), months);
  400. }
  401. Integer extraNum = 5;
  402. if (sku.getId() == 178l) {
  403. extraNum = 2;
  404. }
  405. maxNum += extraNum;
  406. DateTime minExpiryTime = DateUtil.offsetDay(expiryTime, -5);
  407. Long groupsId = groupsRelationMapper.selectSimilarExpiredRelation(skuId, minExpiryTime, maxNum, ip);
  408. if (groupsId == null) {
  409. log.info("暂无相似过期时间车队");
  410. return null;
  411. }
  412. GroupsRelation relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  413. .notIn(errorsRelationIds != null && errorsRelationIds.size() > 0, GroupsRelation::getId, errorsRelationIds)
  414. .eq(GroupsRelation::getGroupsId, groupsId)
  415. .eq(GroupsRelation::getStatus, GroupsRelation.Status.none)
  416. .eq(GroupsRelation::getUserId, 0)
  417. .orderByAsc(GroupsRelation::getNum)
  418. .last("limit 1"));
  419. if (relation != null) {
  420. log.info("用户userId:{},获取相似车队的车位relationId:{}", relation.getId());
  421. }
  422. return relation;
  423. }
  424. @Override
  425. public Page<UserRecommendGoodsFrontView> getRecommendGoodsViews(Boolean isPayNf, List<Long> filter_goods_id, Boolean filterCourseGoods, Integer start, Integer limit) {
  426. return groupsRelationMapper.getRecommendGoodsViews(new Page<>(start, limit), filter_goods_id, isPayNf, filterCourseGoods);
  427. }
  428. @Override
  429. @Transactional(rollbackFor = Throwable.class)
  430. public void sendCourseWare(SpecialGoodsTicketReq request) throws Exception {
  431. Long userId = request.getUserId();
  432. Long relationId = request.getRelationId();
  433. String email = request.getEmail();
  434. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  435. RenewalView relation = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getRelationId, relationId).build());
  436. Assert.notNull(relation, "您的车票不存在");
  437. Long relationUserId = relation.getUserId();
  438. if (!userIdList.contains(relationUserId)) {
  439. throw BusinessRuntimeException.getInstance("您的车票不存在");
  440. }
  441. if (relation.getSpecialType() != GoodsDon.SpecialType.courseware) {
  442. throw BusinessRuntimeException.getInstance("");
  443. }
  444. //是否已发送
  445. if (StrUtil.isNotBlank(relation.getGrAccount())) {
  446. throw BusinessRuntimeException.getInstance("已领取课件,请前往邮箱查看");
  447. }
  448. if (!Validator.isEmail(email)) {
  449. throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
  450. }
  451. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  452. .set(GroupsRelation::getAccount, email)
  453. .and(qr -> qr.isNull(GroupsRelation::getAccount).or().eq(GroupsRelation::getAccount, StrUtil.EMPTY))
  454. .eq(GroupsRelation::getId, relationId));
  455. if (update > 0) {
  456. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  457. .set(OrderDon::getStatus, OrderDon.Status.complete)
  458. .eq(OrderDon::getRelationId, relationId)
  459. .eq(OrderDon::getUserId, userId)
  460. .eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  461. mailService.sendCoursewareByGoodsId(relation.getGoodsId(), relation.getRelationId(), relation.getUserId(), relation.getTitle(), email);
  462. }
  463. }
  464. @Override
  465. public GroupsRelation getRelation(Long payRelationId, Long userId, GoodsDonSku sku, String ip) {
  466. GroupsRelation relation = null;
  467. Integer maxNum = sku.getNum();
  468. if (payRelationId != null && payRelationId > 0) {
  469. relation = groupsRelationMapper.selectById(payRelationId);
  470. if (relation == null) {
  471. throw new BusinessRuntimeException(GROUP_INDEX_NOT_FIND.getCode(), GROUP_INDEX_NOT_FIND.getMsg());
  472. }
  473. if (relation.getUserId() != null && relation.getUserId() > 0L) {
  474. throw new BusinessRuntimeException(GROUP_INDEX_ALREADY_BE_USER.getCode(), GROUP_INDEX_ALREADY_BE_USER.getMsg());
  475. }
  476. } else {
  477. GroupsTrips groups = null;
  478. //ChatGpt Plus、Midjourney非独立规格 上车先获取硬塞座位 硬塞5个座位
  479. //主账号过期时间25天以外
  480. //23-12-06 MidJourney 不硬塞
  481. if (sku.getNum() > 1 && Constant.AI_goodsIds.get(0) == sku.getGoodsId()) {
  482. Integer extraNum = 5;
  483. if (sku.getId() == 178l || sku.getId() == 423l) {
  484. extraNum = 2;
  485. }
  486. maxNum += extraNum;
  487. DateTime time = DateUtil.offsetDay(DateUtil.beginOfDay(DateTime.now()), 25);
  488. //不塞存在该用户的车队
  489. Long groupsId = groupsRelationMapper.getOutSideGroupsTripsRelationByGoodsId(sku.getId(), time, extraNum, userId, sku.getNum(), maxNum);
  490. if (groupsId != null) {
  491. relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  492. .eq(GroupsRelation::getGroupsId, groupsId)
  493. .eq(GroupsRelation::getUserId, 0)
  494. .eq(GroupsRelation::getStatus, GroupsRelation.Status.outside)
  495. .last("limit 1"));
  496. if (relation == null) {
  497. relation = new GroupsRelation();
  498. relation.setStatus(GroupsRelation.Status.outside);
  499. relation.setUserId(userId);
  500. relation.setGroupsId(groupsId);
  501. GroupsRelation maxNumRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  502. Integer nextNum = maxNumRelation.getNum() + 1;
  503. if (redisService.setNx(RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getNameFormat(groupsId, nextNum), nextNum, RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getTimeout())) {
  504. relation.setNum(nextNum);
  505. groupsRelationMapper.insert(relation);
  506. } else {
  507. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  508. }
  509. }
  510. groups = groupsMapper.selectById(groupsId);
  511. }
  512. }
  513. if (groups == null) {
  514. //寻找差不多过期时间规格的车位
  515. relation = getSimilarExpiredGroupRelation(sku, null, ip);
  516. if (relation == null) {
  517. //TODO 如果没指定座位,等待逻辑确认
  518. DateTime filterAccountTime = null;
  519. //奈飞过滤6月23号之前的车队
  520. if (sku.getGoodsId() == Constant.NETFLIX_GID) {
  521. filterAccountTime = DateUtil.parse("2025-06-23");
  522. }
  523. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.validity, maxNum, ip, filterAccountTime);
  524. if (groups == null) {
  525. //待发车
  526. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.waiting, maxNum, ip, null);
  527. }
  528. //新增空车队
  529. if (groups == null) {
  530. relation = groupsFuncService.createNewGroupsTrips(sku);
  531. }
  532. //获取车位
  533. if (relation == null) {
  534. //寻找快满编车队进行占座
  535. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  536. if (relation == null) {
  537. Long groupsId = groups.getId();
  538. TASK_EXECUTOR.execute(() -> groupsMapper.updateAvailableNum(groupsId));
  539. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  540. }
  541. }
  542. }
  543. }
  544. if (groups == null) {
  545. groups = groupsMapper.selectById(relation.getGroupsId());
  546. }
  547. //车队目前可用停车数
  548. relation.setGroupsAvailParkingNum(groups.getAvailableParkingNum());
  549. relation.setMaxNum(maxNum);
  550. }
  551. return relation;
  552. }
  553. @Override
  554. public String getAiVerifyCode(TicketLoginReq loginReq) throws Exception {
  555. Integer type = loginReq.getType();
  556. RenewalView renewalView;
  557. String account;
  558. Long userId = 0l;
  559. Long relationId = 0l;
  560. if (loginReq.getMerchants()) {
  561. renewalView = new RenewalView();
  562. renewalView.setGoodsId(loginReq.getGoodsId());
  563. renewalView.setAccount(loginReq.getAccount());
  564. if (loginReq.getAccountId() != null && loginReq.getAccountId() != 0l) {
  565. GroupsTrips groupsTrips = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  566. .eq(GroupsTrips::getAccountId, loginReq.getAccountId())
  567. .last("limit 1"));
  568. if (groupsTrips != null) {
  569. renewalView.setSkuId(groupsTrips.getSkuId());
  570. }
  571. }
  572. renewalView.setUserId(userId);
  573. account = loginReq.getAccount();
  574. } else {
  575. userId = loginReq.getUserId();
  576. relationId = loginReq.getRelationId();
  577. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  578. renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  579. .field(RenewalView::getRelationId, relationId).build());
  580. if (renewalView == null) {
  581. throw BusinessRuntimeException.getInstance("您的车票不存在...");
  582. }
  583. if (StrUtil.isEmpty(renewalView.getAccount())) {
  584. throw BusinessRuntimeException.getInstance("车票未配置账号");
  585. }
  586. account = renewalView.getAccount();
  587. String password = renewalView.getPassword();
  588. if (StrUtil.hasEmpty(account, password)) {
  589. throw BusinessRuntimeException.getInstance("您的车票账号密码异常,请联系客服...");
  590. }
  591. }
  592. if (renewalView.getGoodsId() == 1l) {
  593. Integer linkType = loginReq.getLinkType();
  594. if (type == null && linkType == null) {
  595. throw BusinessRuntimeException.getInstance("系统异常");
  596. }
  597. if (linkType != null) {
  598. String key = RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getNameFormat(DateUtil.hour(DateTime.now(), true), linkType, renewalView.getUserId());
  599. if (!redisService.hasKey(key)) {
  600. redisService.set(key, 0l, RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getTimeout());
  601. } else {
  602. Integer value = (Integer) redisService.get(key);
  603. if (value >= 5) {
  604. throw BusinessRuntimeException.getInstance("获取奈飞同步更新装置过于频繁");
  605. }
  606. }
  607. }
  608. }
  609. String code = commonMailService.getTicketMailCode(renewalView.getGoodsId(), account, renewalView.getRelateEmail(), renewalView.getGptEmailPwd(), renewalView.getCreatedTime(), type, loginReq.getLinkType(), false);
  610. GroupsRelationLoginCodeRecord record = new GroupsRelationLoginCodeRecord();
  611. record.setUserId(userId);
  612. record.setRelationId(relationId);
  613. record.setAccount(renewalView.getAccount());
  614. record.setGoodsId(renewalView.getGoodsId());
  615. record.setSkuId(renewalView.getSkuId());
  616. groupsRelationLoginCodeRecordMapper.insert(record);
  617. //奈飞同步装置
  618. if (renewalView.getGoodsId() == 1l && loginReq.getLinkType() != null) {
  619. String key = RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getNameFormat(DateUtil.hour(DateTime.now(), true), loginReq.getLinkType(), renewalView.getUserId());
  620. redisService.incr(key, 1L);
  621. }
  622. return code;
  623. }
  624. @Override
  625. public void checkGroupsAvailParkingNum(Long skuId, Long groupsId, Integer availableParkingNum, Integer maxNum) {
  626. //GPT10人月付、4人月付
  627. if (skuId == 161l || skuId == 178l) {
  628. //为0时,不参与限制
  629. if (availableParkingNum == 0) {
  630. return;
  631. }
  632. //目前车队可用停车数
  633. //目前上车人数
  634. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  635. .eq(GroupsRelation::getGroupsId, groupsId)
  636. .ne(GroupsRelation::getUserId, 0)
  637. .le(GroupsRelation::getNum, maxNum));
  638. if (currentParkingNum > availableParkingNum) {
  639. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  640. }
  641. }
  642. }
  643. @Override
  644. public void adjustGroupsParkingTime(Long relationId, GoodsDonSku sku) {
  645. if (sku == null) {
  646. return;
  647. }
  648. Long skuId = sku.getId();
  649. //更新GPT Plus10人、4人月付车队状态 待优化
  650. if (skuId == 161l || skuId == 178l || skuId == 422l || skuId == 423l) {
  651. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  652. Long groupsId = relation.getGroupsId();
  653. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  654. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  655. //为0时 不参与限制
  656. if (availableParkingNum == 0) {
  657. return;
  658. }
  659. Integer extraNum = 5;
  660. if (skuId == 178l || skuId == 423l) {
  661. extraNum = 2;
  662. }
  663. Integer maxNum = sku.getNum() + extraNum;
  664. if (availableParkingNum >= maxNum) {
  665. return;
  666. }
  667. //目前上车人数
  668. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  669. .eq(GroupsRelation::getGroupsId, groupsId)
  670. .ne(GroupsRelation::getUserId, 0)
  671. .le(GroupsRelation::getNum, maxNum));
  672. if (currentParkingNum >= availableParkingNum) {
  673. //锁住
  674. DateTime parkingTime = DateUtil.offsetDay(DateTime.now(), 1);
  675. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  676. .eq(GroupsTrips::getId, groupsTrips.getId())
  677. .set(GroupsTrips::getParkingTime, parkingTime)
  678. .isNull(GroupsTrips::getParkingTime));
  679. }
  680. }
  681. }
  682. @Override
  683. public void setGroupsTripsParkingTimeEmpty(GoodsDonSku sku, Long relationId) {
  684. if (sku == null) {
  685. return;
  686. }
  687. Long skuId = sku.getId();
  688. if (skuId == 161l || skuId == 178l) {
  689. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  690. Long groupsId = relation.getGroupsId();
  691. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  692. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  693. if (groupsTrips.getParkingTime() == null || availableParkingNum == 0) {
  694. return;
  695. }
  696. Integer extraNum = 5;
  697. if (skuId == 178l) {
  698. extraNum = 2;
  699. }
  700. Integer skuNum = sku.getNum();
  701. if (availableParkingNum >= skuNum + extraNum) {
  702. return;
  703. }
  704. //目前上车人数
  705. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  706. .eq(GroupsRelation::getGroupsId, groupsId)
  707. .ne(GroupsRelation::getUserId, 0));
  708. if (currentParkingNum < availableParkingNum) {
  709. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  710. .eq(GroupsTrips::getId, groupsTrips.getId())
  711. .set(GroupsTrips::getParkingTime, null)
  712. .isNotNull(GroupsTrips::getParkingTime));
  713. }
  714. }
  715. }
  716. @Override
  717. public Integer getUserCodeNumBySkuId(Long userId, Long skuId, Boolean isHasVerifyCode) {
  718. //查看双重验证码
  719. UserFuncProperty userFuncProperty = userFuncPropertyMapper.selectOne(Wrappers.lambdaQuery(UserFuncProperty.class).eq(UserFuncProperty::getUserId, userId).last("limit 1"));
  720. //默认2次
  721. int num = 2;
  722. //有安全码查看次数 置为0
  723. if (isHasVerifyCode) {
  724. num = 0;
  725. //存在身份实名认证有两次机会
  726. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  727. Integer selectCount = userCertRecordMapper.selectCount(Wrappers.lambdaQuery(UserCertRecord.class)
  728. .in(UserCertRecord::getUserId, userIdList));
  729. if (selectCount > 0) {
  730. num = 2;
  731. }
  732. return num;
  733. }
  734. //查看双重验证码次数
  735. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  736. if (sku.getCodeNum() > 0) {
  737. num = sku.getCodeNum();
  738. }
  739. if (userFuncProperty != null) num = userFuncProperty.getVerifyCheckNum();
  740. return num;
  741. }
  742. @Override
  743. public List<RenewalView> getHasPayGoods(long userId) {
  744. User user = userMapper.selectById(userId);
  745. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, user);
  746. DateTime now = DateTime.now();
  747. List<RenewalView> list = groupsRelationMapper.getUserHasPayGoods(userIds, now);
  748. return list;
  749. }
  750. @Override
  751. public List<RenewalView> getExpiryRenewalNotify(Long userId) {
  752. DateTime now = DateTime.now();
  753. DateTime thisZero = DateUtil.beginOfDay(now);
  754. String thisDate = thisZero.toDateStr();
  755. Object exists = redisService.get(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId));
  756. if (exists != null) {
  757. return null;
  758. }
  759. User u = userMapper.selectById(userId);
  760. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  761. if (u.getIsBlack()) {
  762. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  763. return null;
  764. }
  765. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  766. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  767. List<RenewalView> list = beanSearcher.searchAll(RenewalView.class, builder
  768. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  769. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  770. .field(RenewalView::getExpiryTime, now).op(Operator.GreaterThan)
  771. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  772. .field(RenewalView::getAqType, 1)
  773. .field(RenewalView::getIsVip, Boolean.TRUE)
  774. .orderBy(RenewalView::getExpiryTime).asc()
  775. .build());
  776. if (list.size() > 5) {
  777. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  778. return null;
  779. }
  780. List<Long> renewReduceSkuIds = userBenefitsMapper.selectList(Wrappers.lambdaQuery(UserBenefits.class)
  781. .eq(UserBenefits::getType, UserBenefits.Type.RENEW).eq(UserBenefits::getStatus, 1).select(UserBenefits::getSkuId)).stream().map(UserBenefits::getSkuId).collect(Collectors.toList());
  782. //提前7天
  783. AtomicInteger day = new AtomicInteger(7);
  784. List<RenewalView> expiryTickets = list.stream().filter(ticket -> {
  785. //下架
  786. if (ticket.getGoodsStatus() == null || ticket.getSkuStatus() == null || !ticket.getGoodsStatus() || !ticket.getSkuStatus()) {
  787. return false;
  788. }
  789. Integer skuMonths = ticket.getMonths();
  790. if (skuMonths == null) {
  791. return false;
  792. }
  793. Date expiryTime = ticket.getExpiryTime();
  794. //年付 提前一个月
  795. if (skuMonths >= 12) {
  796. day.set(30);
  797. } else {
  798. day.set(7);
  799. }
  800. if (DateUtil.beginOfDay(expiryTime).compareTo(DateUtil.offsetDay(thisZero, day.get())) <= 0) {
  801. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  802. //GPT镜像信息
  803. setGptMirrorInfo(ticket);
  804. ticket.setExpiryTime(null);
  805. if (CollUtil.isNotEmpty(renewReduceSkuIds) && renewReduceSkuIds.contains(ticket.getSkuId())) {
  806. ticket.setIsRenewReduce(true);
  807. }
  808. return true;
  809. }
  810. return false;
  811. }).collect(Collectors.toList());
  812. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  813. if (CollUtil.isNotEmpty(expiryTickets)) {
  814. groupsRelationExpiryNotifyRecordMapper.batchInsert(userId, expiryTickets);
  815. }
  816. return expiryTickets;
  817. }
  818. @Override
  819. public void getCollegeStudentUserGptTicket(Long userId) {
  820. Retryer<Boolean> build = RetryerBuilder.<Boolean>newBuilder()
  821. .retryIfException()
  822. //运行时异常重试
  823. .retryIfRuntimeException()
  824. //false重试
  825. .retryIfResult(res -> Objects.equals(res, false))
  826. //1s 间隔
  827. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  828. //停止策略 : 尝试请求3次
  829. .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
  830. try {
  831. build.call(() -> {
  832. //体验规格
  833. Long gptMirrorSkuId = Constant.GPT_MIRROR_SKU_ID;
  834. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(gptMirrorSkuId);
  835. if (groups == null) {
  836. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  837. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  838. .eq(GroupsTrips::getSkuId, gptMirrorSkuId)
  839. .last("limit 1"));
  840. }
  841. GroupsRelation relation = null;
  842. if (groups != null) {
  843. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  844. }
  845. if (relation == null) {
  846. //生成空车队
  847. GoodsDonSku sku = goodsDonSkuMapper.selectById(gptMirrorSkuId);
  848. relation = groupsFuncService.createNewGroupsTrips(sku);
  849. }
  850. DateTime startTime = DateTime.now();
  851. DateTime expiryTime = DateUtil.offsetDay(startTime, 1);
  852. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  853. .set(GroupsRelation::getUserId, userId)
  854. .set(GroupsRelation::getStartTime, startTime)
  855. .set(GroupsRelation::getExpiryTime, expiryTime)
  856. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  857. .set(GroupsRelation::getAqType, 2)
  858. .eq(GroupsRelation::getId, relation.getId())
  859. .eq(GroupsRelation::getUserId, 0));
  860. if (update > 0) {
  861. groupsMapper.decrAvailableNum(relation.getGroupsId());
  862. return true;
  863. }
  864. log.error("发送用户:{} GPT镜像车票体验失败,进行重试", userId);
  865. return false;
  866. });
  867. } catch (ExecutionException | RetryException e) {
  868. log.error("发送用户GPT镜像体验失败:{}", StringUtil.getErrorText(e));
  869. }
  870. }
  871. @Override
  872. public RenewalView getTicketDetail(long userId, Long relationId) {
  873. User u = userMapper.selectById(userId);
  874. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  875. MapBuilder builder = MapUtils.builder();
  876. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, builder
  877. .field(RenewalView::getRelationId, relationId)
  878. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  879. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  880. .field("condition", String.format("(gr.expiry_time is null or gr.expiry_time > '%s')", DateTime.now()))
  881. .field(RenewalView::getStatus, List.of("validity", "outside")).op(Operator.InList)
  882. .orderBy(RenewalView::getExpiryTime).asc()
  883. .onlySelect(RenewalView::getRelationId, RenewalView::getExpiryTime, RenewalView::getTitle, RenewalView::getSpecVal, RenewalView::getGoodsId, RenewalView::getSkuId, RenewalView::getSkuNum, RenewalView::getSkuStatus, RenewalView::getGoodsStatus)
  884. .build());
  885. if (renewalView != null) {
  886. renewalView.setExpiryTimeStr(DateUtil.format(renewalView.getExpiryTime(), "yyyy-MM-dd"));
  887. }
  888. return renewalView;
  889. }
  890. @Override
  891. public GroupsRelation ticketLogin(TicketLoginReq loginReq) {
  892. String account = loginReq.getAccount();
  893. if (StrUtil.isEmpty(account)) {
  894. throw BusinessRuntimeException.getInstance("请输入对应账号");
  895. }
  896. if (loginReq.getMerchants()) {
  897. if (account.contains(Constant.YH_EMAIL_DOMAIN_SUFFIX)) {
  898. SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
  899. .eq(SysEmail::getEmail, account)
  900. .last("limit 1"));
  901. if (sysEmail == null) {
  902. throw BusinessRuntimeException.getInstance("账号错误,请联系客服");
  903. }
  904. }
  905. GroupsRelation relation = new GroupsRelation();
  906. relation.setId(0l);
  907. return relation;
  908. }
  909. String password = loginReq.getPassword();
  910. Integer num = loginReq.getNum();
  911. if (ObjectUtil.hasEmpty(password, num)) {
  912. throw BusinessRuntimeException.getInstance("参数错误");
  913. }
  914. Long goodsId = Optional.ofNullable(loginReq.getGoodsId()).orElse(1l);
  915. GroupsRelation relation = groupsRelationMapper.selectRelationByAccountAndNum(account, password, goodsId, num);
  916. if (relation == null) {
  917. log.info("外部入口使用账号account:{},pwd:{},座位num:{}登录失败...", account, password, num);
  918. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  919. throw BusinessRuntimeException.getInstance("Please enter the correct account information");
  920. }
  921. throw BusinessRuntimeException.getInstance("请输入正确的账号信息");
  922. }
  923. return relation;
  924. }
  925. @Override
  926. public String outsideTicketVerify(TicketLoginReq loginReq) {
  927. String account = loginReq.getAccount();
  928. if (StrUtil.isEmpty(account)) {
  929. throw BusinessRuntimeException.getInstance("账号错误");
  930. }
  931. if (loginReq.getMerchants()) {
  932. if (account.contains(Constant.YH_EMAIL_DOMAIN_SUFFIX)) {
  933. SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
  934. .eq(SysEmail::getEmail, account)
  935. .last("limit 1"));
  936. if (sysEmail == null) {
  937. throw BusinessRuntimeException.getInstance("账号错误,请联系客服");
  938. }
  939. }
  940. loginReq.setGoodsId(1l);
  941. loginReq.setAccountId(0l);
  942. } else {
  943. String password = loginReq.getPassword();
  944. Integer num = loginReq.getNum();
  945. if (ObjectUtil.hasEmpty(password, num)) {
  946. throw BusinessRuntimeException.getInstance("参数错误");
  947. }
  948. Long goodsId = Optional.ofNullable(loginReq.getGoodsId()).orElse(1l);
  949. GroupsRelation relation = groupsRelationMapper.selectRelationByAccountAndNum(account, password, goodsId, num);
  950. if (relation == null) {
  951. log.info("外部入口使用账号account:{},pwd:{},座位num:{}同步验证链接失败...", account, password, num);
  952. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  953. throw BusinessRuntimeException.getInstance("This account is no longer valid");
  954. }
  955. throw BusinessRuntimeException.getInstance("该账号已失效");
  956. }
  957. loginReq.setUserId(relation.getUserId());
  958. loginReq.setRelationId(relation.getId());
  959. loginReq.setGoodsId(goodsId);
  960. }
  961. try {
  962. String aiVerifyCode = getAiVerifyCode(loginReq);
  963. if (StrUtil.isEmpty(aiVerifyCode)) {
  964. throw BusinessRuntimeException.getInstance("");
  965. }
  966. return aiVerifyCode;
  967. } catch (Exception e) {
  968. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  969. throw BusinessRuntimeException.getInstance("Please verify that the link was sent");
  970. }
  971. throw BusinessRuntimeException.getInstance("请校验链接是否已发送");
  972. }
  973. }
  974. @Override
  975. public String getNfHouseholdDevice(long userId, Long relationId) throws Exception {
  976. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  977. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  978. .field(RenewalView::getRelationId, relationId).build());
  979. if (renewalView == null) {
  980. throw BusinessRuntimeException.getInstance("您的车票不存在...");
  981. }
  982. if (StrUtil.isEmpty(renewalView.getAccount())) {
  983. throw BusinessRuntimeException.getInstance("车票未配置账号");
  984. }
  985. String account = renewalView.getAccount();
  986. String password = renewalView.getPassword();
  987. if (StrUtil.hasEmpty(account, password)) {
  988. throw BusinessRuntimeException.getInstance("您的车票账号密码异常,请联系客服...");
  989. }
  990. String code = commonMailService.getTicketMailCode(renewalView.getGoodsId(), account, renewalView.getRelateEmail(), renewalView.getGptEmailPwd(), renewalView.getCreatedTime(), null, 1, true);
  991. return code;
  992. }
  993. @Override
  994. public String getVerifyCode(String account) throws Exception {
  995. Account at = accountMapper.selectOne(Wrappers.lambdaQuery(Account.class)
  996. .eq(Account::getAccount, account)
  997. .eq(Account::getGoodsId, 18));
  998. if (at == null) {
  999. return null;
  1000. }
  1001. String password = at.getPassword();
  1002. if (StrUtil.hasEmpty(account, password)) {
  1003. throw BusinessRuntimeException.getInstance("账号异常");
  1004. }
  1005. String code = commonMailService.getTicketMailCode(at.getGoodsId(), account, at.getRelateEmail(), at.getGptEmailPwd(), at.getCreatedTime(), null, null, false);
  1006. return code;
  1007. }
  1008. @Override
  1009. public void changeTicket(long userId, Long relationId) {
  1010. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1011. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  1012. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1013. .field(RenewalView::getRelationId, relationId)
  1014. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1015. .build());
  1016. if (renewalView == null) {
  1017. throw BusinessRuntimeException.getInstance("车票不存在");
  1018. }
  1019. if (renewalView.getGoodsId() != 1) {
  1020. throw BusinessRuntimeException.getInstance("只针对奈飞车票");
  1021. }
  1022. AccountNetflixState accountNetflixState = accountNetflixStateMapper.selectOne(Wrappers.lambdaQuery(AccountNetflixState.class)
  1023. .eq(AccountNetflixState::getAccount, renewalView.getAccount())
  1024. .orderByDesc(AccountNetflixState::getId)
  1025. .last("limit 1"));
  1026. if (accountNetflixState == null || accountNetflixState.getState() != 3) {
  1027. throw BusinessRuntimeException.getInstance("只支持异常账号更换车票");
  1028. }
  1029. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  1030. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  1031. throw BusinessRuntimeException.getInstance("正在更换车票中..");
  1032. }
  1033. Long groupId = renewalView.getGroupId();
  1034. Long skuId = renewalView.getSkuId();
  1035. Date expiryTime = renewalView.getExpiryTime();
  1036. //随机选择同规格得车票
  1037. Long item_groupsId = groupsMapper.selectRandomGroupsTripsBySkuId(groupId, skuId, expiryTime);
  1038. GroupsRelation newRelation = null;
  1039. if (item_groupsId != null) {
  1040. //存在就随机分配一个,没有就不做处理
  1041. newRelation = changeTickerRelation.changeTicket(renewalView.getUserId(), relationId, item_groupsId, renewalView.getSkuId());
  1042. }
  1043. //若无移至空车队
  1044. if (newRelation == null) {
  1045. newRelation = changeTickerRelation.getEmptyGroupsRelation(renewalView.getUserId(), renewalView.getRelationId(), renewalView.getSkuId());
  1046. }
  1047. if (newRelation == null) {
  1048. throw BusinessRuntimeException.getInstance("更换异常,请重新提交");
  1049. }
  1050. NetflixUserAccountStatusRecord netflixUserAccountStatusRecord = netflixUserAccountStatusRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1051. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1052. .last("limit 1"));
  1053. if (netflixUserAccountStatusRecord != null) {
  1054. netflixUserAccountStatusRecord.setDeleted(false);
  1055. netflixUserAccountStatusRecordMapper.updateById(netflixUserAccountStatusRecord);
  1056. }
  1057. redisService.del(key);
  1058. }
  1059. @Override
  1060. public AccountView getTempAccount(long userId, Long relationId) {
  1061. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1062. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  1063. .field(RenewalView::getRelationId, relationId)
  1064. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1065. .field(RenewalView::getGroupsStatus, GroupsTrips.Status.waiting.name())
  1066. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1067. .build());
  1068. if (renewalView == null) {
  1069. throw BusinessRuntimeException.getInstance("车票不存在");
  1070. }
  1071. AccountView accountView = new AccountView();
  1072. //奈飞超过3帐车票不给看
  1073. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  1074. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1075. .field(RenewalView::getGoodsId, 1)
  1076. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1077. .build());
  1078. if (number.intValue() > 2) {
  1079. return accountView;
  1080. }
  1081. NetflixTempAccountUser netflixTempAccountUser = netflixTempAccountUserMapper.selectOne(Wrappers.lambdaQuery(NetflixTempAccountUser.class)
  1082. .eq(NetflixTempAccountUser::getRelationId, relationId)
  1083. .in(NetflixTempAccountUser::getUserId, userIdList)
  1084. .last("limit 1"));
  1085. Account account;
  1086. if (netflixTempAccountUser == null) {
  1087. account = accountMapper.selectNetflixTempAccount();
  1088. if (account != null) {
  1089. netflixTempAccountUser = new NetflixTempAccountUser();
  1090. netflixTempAccountUser.setAccountId(account.getId());
  1091. netflixTempAccountUser.setRelationId(relationId);
  1092. netflixTempAccountUser.setUserId(renewalView.getUserId());
  1093. netflixTempAccountUserMapper.insert(netflixTempAccountUser);
  1094. }
  1095. } else {
  1096. account = accountMapper.selectById(netflixTempAccountUser.getAccountId());
  1097. }
  1098. if (account != null) {
  1099. accountView.setAccount(account.getAccount());
  1100. accountView.setPassword(account.getPassword());
  1101. }
  1102. return accountView;
  1103. }
  1104. @Override
  1105. public void nfErrorAccountSubmit(long userId, Long relationId) {
  1106. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1107. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  1108. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1109. .field(RenewalView::getRelationId, relationId)
  1110. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan).build());
  1111. if (renewalView == null) {
  1112. throw BusinessRuntimeException.getInstance("车票不存在");
  1113. }
  1114. if (renewalView.getGoodsId() != 1) {
  1115. throw BusinessRuntimeException.getInstance("只支持奈飞车票");
  1116. }
  1117. String account = renewalView.getAccount();
  1118. String password = renewalView.getPassword();
  1119. Integer selectCount = netflixUserAccountStatusRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1120. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1121. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1122. .eq(NetflixUserAccountStatusRecord::getAccount, account)
  1123. .eq(NetflixUserAccountStatusRecord::getState, 0)
  1124. .eq(NetflixUserAccountStatusRecord::getDeleted, 1));
  1125. if (selectCount > 0) {
  1126. throw BusinessRuntimeException.getInstance("该账号正在检测中");
  1127. }
  1128. AccountNetflixState accountNetflixState = accountNetflixStateMapper.selectOne(Wrappers.lambdaQuery(AccountNetflixState.class)
  1129. .eq(AccountNetflixState::getAccount, account)
  1130. .last("limit 1"));
  1131. Integer state = 0;
  1132. if (accountNetflixState != null && accountNetflixState.getState() == 3) {
  1133. state = accountNetflixState.getState();
  1134. }
  1135. //非正常状态
  1136. if (state != 1) {
  1137. //20号之前得校验 直接失败
  1138. if (renewalView.getCreatedTime().compareTo(DateUtil.parse("2025-06-20")) < 0) {
  1139. state = 3;
  1140. }
  1141. //如果账号下架了 直接失败
  1142. if (StrUtil.equals(GroupsTrips.Status.down.name(), renewalView.getGroupsStatus()) && renewalView.getSkuNum() > 1) {
  1143. state = 3;
  1144. }
  1145. }
  1146. NetflixUserAccountStatusRecord netflixUserAccountStatusRecord = new NetflixUserAccountStatusRecord();
  1147. netflixUserAccountStatusRecord.setAccount(account);
  1148. netflixUserAccountStatusRecord.setRelationId(relationId);
  1149. netflixUserAccountStatusRecord.setPassword(password);
  1150. netflixUserAccountStatusRecord.setUserId(renewalView.getUserId());
  1151. netflixUserAccountStatusRecord.setState(state);
  1152. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1153. .eq(OrderDon::getRelationId, renewalView.getRelationId())
  1154. .in(OrderDon::getUserId, userIdList)
  1155. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1156. .orderByDesc(OrderDon::getId)
  1157. .last("limit 1"));
  1158. if (orderDon != null) {
  1159. netflixUserAccountStatusRecord.setOrderId(orderDon.getId());
  1160. }
  1161. netflixUserAccountStatusRecordMapper.insert(netflixUserAccountStatusRecord);
  1162. }
  1163. @Override
  1164. public NetflixErrorAccountStatus getNetflixErrorAccountStatus(long userId, Long relationId) {
  1165. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1166. NetflixUserAccountStatusRecord netflixUseAccountStatusRecord = netflixUserAccountStatusRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1167. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1168. .eq(NetflixUserAccountStatusRecord::getDeleted, 1)
  1169. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1170. .orderByDesc(NetflixUserAccountStatusRecord::getId)
  1171. .last("limit 1"));
  1172. NetflixErrorAccountStatus status = new NetflixErrorAccountStatus();
  1173. if (netflixUseAccountStatusRecord == null) {
  1174. //是否已经更换
  1175. NetflixUserAccountSubmitRecoverRecord replaceRecover = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1176. .eq(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1177. .eq(NetflixUserAccountSubmitRecoverRecord::getReplaceRelationId, relationId)
  1178. .last("limit 1"));
  1179. if (replaceRecover != null) {
  1180. status.setRecoverStatus(replaceRecover.getStatus());
  1181. }
  1182. return status;
  1183. }
  1184. Integer state = netflixUseAccountStatusRecord.getState();
  1185. //2是登录失败 3是被封号
  1186. // if (state == 3) {
  1187. // if (netflixUseAccountStatusRecord.getCreatedTime().compareTo(DateUtil.offsetMinute(DateTime.now(), -10)) > 0) {
  1188. // state = 0;
  1189. // }
  1190. // }
  1191. //登录失败 可继续申请检测
  1192. if (state == 2) {
  1193. return status;
  1194. }
  1195. //账号检测状态
  1196. status.setNfStatus(state);
  1197. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1198. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1199. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  1200. .last("limit 1"));
  1201. if (recoverRecord != null) {
  1202. //申请恢复状态
  1203. status.setRecoverStatus(recoverRecord.getStatus());
  1204. }
  1205. return status;
  1206. }
  1207. @Override
  1208. public List<NetflixUserAccountStatusRecord> getUserNetflixSubmitRecord(long userId) {
  1209. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1210. List<NetflixUserAccountStatusRecord> netflixUseAccountStatusRecords = netflixUserAccountStatusRecordMapper.selectList(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1211. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1212. .eq(NetflixUserAccountStatusRecord::getDeleted, 1)
  1213. .select(NetflixUserAccountStatusRecord::getOrderId, NetflixUserAccountStatusRecord::getRelationId, NetflixUserAccountStatusRecord::getState, NetflixUserAccountStatusRecord::getCreatedTime));
  1214. return netflixUseAccountStatusRecords;
  1215. }
  1216. @Override
  1217. public Long getTrialTicketByUserIdAndGoodsId(Long userId, Long trialSkuId, Integer ticketType) {
  1218. Retryer<Long> build = RetryerBuilder.<Long>newBuilder()
  1219. .retryIfException()
  1220. //运行时异常重试
  1221. .retryIfRuntimeException()
  1222. //false重试
  1223. .retryIfResult(res -> res == null)
  1224. //1s 间隔
  1225. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  1226. //停止策略 : 尝试请求3次
  1227. .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
  1228. try {
  1229. return build.call(() -> {
  1230. //体验规格
  1231. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(trialSkuId);
  1232. GroupsRelation relation = null;
  1233. if (groups == null) {
  1234. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  1235. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  1236. .eq(GroupsTrips::getSkuId, trialSkuId)
  1237. .last("limit 1"));
  1238. }
  1239. if (groups != null) {
  1240. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  1241. }
  1242. if (relation == null) {
  1243. //生成空车队
  1244. GoodsDonSku sku = goodsDonSkuMapper.selectById(trialSkuId);
  1245. relation = groupsFuncService.createNewGroupsTrips(sku);
  1246. }
  1247. DateTime startTime = DateTime.now();
  1248. DateTime expiryTime = DateUtil.offsetDay(startTime, 1);
  1249. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1250. .set(GroupsRelation::getUserId, userId)
  1251. .set(GroupsRelation::getStartTime, startTime)
  1252. .set(GroupsRelation::getExpiryTime, expiryTime)
  1253. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  1254. .set(GroupsRelation::getAqType, ticketType)
  1255. .eq(GroupsRelation::getId, relation.getId())
  1256. .eq(GroupsRelation::getUserId, 0));
  1257. if (update > 0) {
  1258. groupsMapper.decrAvailableNum(relation.getGroupsId());
  1259. return relation.getId();
  1260. }
  1261. log.error("发送用户:{} GPT镜像车票体验失败,进行重试", userId);
  1262. return null;
  1263. });
  1264. } catch (ExecutionException | RetryException e) {
  1265. log.error("发送用户GPT镜像体验失败:{}", StringUtil.getErrorText(e));
  1266. return null;
  1267. }
  1268. }
  1269. @Override
  1270. public Boolean getMirrorPopups(long userId) {
  1271. //是否弹窗 默认否
  1272. Boolean flag = false;
  1273. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1274. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  1275. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1276. .field(RenewalView::getStatus, GroupsRelation.Status.validity.name())
  1277. .field(RenewalView::getIsMirror, true)
  1278. .build());
  1279. if (number.intValue() == 0) {
  1280. flag = true;
  1281. }
  1282. if (!flag) {
  1283. String thisWeekBegin = DateUtil.beginOfWeek(DateTime.now()).toDateStr();
  1284. Integer selectCount = mirrorTicketPopupsRecordMapper.selectCount(Wrappers.lambdaQuery(MirrorTicketPopupsRecord.class)
  1285. .in(MirrorTicketPopupsRecord::getUserId, userIdList)
  1286. .eq(MirrorTicketPopupsRecord::getThisWeek, thisWeekBegin));
  1287. if (selectCount == 0) {
  1288. MirrorTicketPopupsRecord mirrorTicketPopupsRecord = new MirrorTicketPopupsRecord();
  1289. mirrorTicketPopupsRecord.setThisWeek(thisWeekBegin);
  1290. mirrorTicketPopupsRecord.setUserId(userId);
  1291. mirrorTicketPopupsRecordMapper.insert(mirrorTicketPopupsRecord);
  1292. } else {
  1293. flag = true;
  1294. }
  1295. }
  1296. return flag;
  1297. }
  1298. @Override
  1299. public Long getTicket(Long userId, Long skuId, Boolean isVip) {
  1300. Retryer<Long> build = RetryerBuilder.<Long>newBuilder()
  1301. .retryIfException()
  1302. //运行时异常重试
  1303. .retryIfRuntimeException()
  1304. //false重试
  1305. .retryIfResult(res -> res == null)
  1306. //1s 间隔
  1307. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  1308. //停止策略 : 尝试请求1次
  1309. .withStopStrategy(StopStrategies.stopAfterAttempt(1)).build();
  1310. try {
  1311. return build.call(() -> {
  1312. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(skuId);
  1313. GroupsRelation relation = null;
  1314. if (groups == null) {
  1315. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  1316. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  1317. .eq(GroupsTrips::getSkuId, skuId)
  1318. .last("limit 1"));
  1319. }
  1320. if (groups != null) {
  1321. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  1322. }
  1323. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1324. //生成空车队
  1325. if (relation == null) {
  1326. relation = groupsFuncService.createNewGroupsTrips(sku);
  1327. }
  1328. DateTime startTime = DateTime.now();
  1329. DateTime expiryTime;
  1330. if (sku.getDays() != null) {
  1331. expiryTime = DateUtil.offsetDay(startTime, sku.getDays());
  1332. } else {
  1333. expiryTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  1334. }
  1335. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1336. .set(GroupsRelation::getUserId, userId)
  1337. .set(GroupsRelation::getStartTime, startTime)
  1338. .set(GroupsRelation::getExpiryTime, expiryTime)
  1339. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  1340. .set(GroupsRelation::getIsVip, isVip)
  1341. .eq(GroupsRelation::getId, relation.getId())
  1342. .eq(GroupsRelation::getUserId, 0));
  1343. if (update > 0) {
  1344. groupsMapper.decrAvailableNum(relation.getGroupsId());
  1345. return relation.getId();
  1346. }
  1347. log.error("发送用户:{} GPT镜像车票失败,进行重试", userId);
  1348. return null;
  1349. });
  1350. } catch (ExecutionException | RetryException e) {
  1351. log.error("发送用户GPT镜像失败:{}", StringUtil.getErrorText(e));
  1352. return null;
  1353. }
  1354. }
  1355. @Override
  1356. public Boolean getVipMirrorTicketIfEmpty(long userId, Long skuId) {
  1357. Integer selectCount = vipGoodsSkuMapper.selectCount(Wrappers.lambdaQuery(VipGoodsSku.class)
  1358. .eq(VipGoodsSku::getSkuId, skuId));
  1359. if (selectCount == 0) {
  1360. return false;
  1361. }
  1362. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1363. VipUser vipUser = vipUserMapper.selectOne(Wrappers.lambdaQuery(VipUser.class)
  1364. .in(VipUser::getUserId, userIdList)
  1365. .gt(VipUser::getExpiryTime, DateTime.now())
  1366. .last("limit 1"));
  1367. //不是会员 或已到期
  1368. if (vipUser == null) {
  1369. return false;
  1370. }
  1371. Number number = beanSearcher.searchCount(GroupsRelationView.class, MapUtils.builder()
  1372. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  1373. .field(GroupsRelationView::getSkuId, skuId)
  1374. .field(GroupsRelationView::getIsVip, Boolean.TRUE)
  1375. .build());
  1376. if (number.intValue() == 0) {
  1377. Long relationId = getTicket(vipUser.getUserId(), skuId, Boolean.TRUE);
  1378. //同步时间
  1379. groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1380. .set(GroupsRelation::getExpiryTime, vipUser.getExpiryTime())
  1381. .eq(GroupsRelation::getUserId, vipUser.getUserId())
  1382. .eq(GroupsRelation::getId, relationId));
  1383. return true;
  1384. }
  1385. return false;
  1386. }
  1387. @Override
  1388. public NetflixRecoverResp netflixSubmitRecover(ErrorNetflixChangeReq req) {
  1389. Long relationId = req.getRelationId();
  1390. Long userId = req.getUserId();
  1391. //校验奈飞账号状态
  1392. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1393. Date expiryTime = netflixRelationView.getExpiryTime();
  1394. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1395. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1396. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  1397. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1398. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1399. .last("limit 1"));
  1400. if (recoverRecord == null) {
  1401. recoverRecord = new NetflixUserAccountSubmitRecoverRecord();
  1402. recoverRecord.setRelationId(relationId);
  1403. recoverRecord.setUserId(netflixRelationView.getUserId());
  1404. recoverRecord.setSkuId(netflixRelationView.getSkuId());
  1405. recoverRecord.setAccount(netflixRelationView.getAccount());
  1406. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1407. recoverRecord.setRemainDays(betweenDay);
  1408. recoverRecord.setAccount(netflixRelationView.getTripsAccount());
  1409. try {
  1410. netflixUserAccountSubmitRecoverRecordMapper.insert(recoverRecord);
  1411. } catch (DuplicateKeyException e) {
  1412. throw BusinessRuntimeException.getInstance("您已申请恢复");
  1413. }
  1414. }
  1415. //等待位数
  1416. Integer selectCount = netflixUserAccountSubmitRecoverRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1417. .lt(NetflixUserAccountSubmitRecoverRecord::getCreatedTime, recoverRecord.getCreatedTime())
  1418. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0));
  1419. NetflixRecoverResp recoverResp = new NetflixRecoverResp();
  1420. //往前加100位
  1421. recoverResp.setIndex(100 + selectCount + 1);
  1422. recoverResp.setRemainDays(recoverRecord.getRemainDays());
  1423. return recoverResp;
  1424. }
  1425. @Override
  1426. @Transactional(rollbackFor = Throwable.class)
  1427. public void errorNetflixSubmitChangeOtherTicket(ErrorNetflixChangeReq req) throws Exception {
  1428. Long relationId = req.getRelationId();
  1429. Long userId = req.getUserId();
  1430. //校验奈飞账号状态
  1431. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1432. Date expiryTime = netflixRelationView.getExpiryTime();
  1433. //小于15 不可替换其他车票
  1434. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1435. if (betweenDay <= 30) {
  1436. throw BusinessRuntimeException.getInstance("您的车票有效期未超过30天");
  1437. }
  1438. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1439. Integer count = netflixUserAccountSubmitRecoverRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1440. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  1441. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList));
  1442. if (count > 0) {
  1443. throw BusinessRuntimeException.getInstance("您的车票申请恢复中...");
  1444. }
  1445. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  1446. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  1447. throw BusinessRuntimeException.getInstance("正在更换其他车票中..");
  1448. }
  1449. try {
  1450. Long skuId = req.getSkuId();
  1451. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  1452. .eq(SysConfig::getSysKey, Constant.ERROR_NETFLIX_CHANGE_OTHER_SKU_KEY)
  1453. .last("limit 1"));
  1454. List<ErrorNetflixChangeOtherSkuTicketDto> errorNetflixChangeOtherSkuTicketDtos = Jsons.parseList(sysConfig.getSysValue(), ErrorNetflixChangeOtherSkuTicketDto.class);
  1455. ErrorNetflixChangeOtherSkuTicketDto errorNetflixChangeOtherSkuTicketDto;
  1456. //自定义顺序 直接获取
  1457. if (betweenDay <= 60) {
  1458. //检验规格
  1459. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(0);
  1460. } else if (betweenDay <= 120) {
  1461. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(1);
  1462. } else {
  1463. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(2);
  1464. }
  1465. List<Long> availableSkuIds = errorNetflixChangeOtherSkuTicketDto.getSkuIds();
  1466. if (!availableSkuIds.contains(skuId)) {
  1467. throw BusinessRuntimeException.getInstance("不支持更换该类型车票");
  1468. }
  1469. //替换车票
  1470. TicketChangeDto changeDto = getTicketAndGenerateOrder(userId, skuId, null, null);
  1471. if (changeDto == null) {
  1472. throw BusinessRuntimeException.getInstance("系统繁忙,请重试");
  1473. }
  1474. //替换记录
  1475. NetflixUserChangeOtherTicketRecord changeOtherTicketRecord = new NetflixUserChangeOtherTicketRecord();
  1476. changeOtherTicketRecord.setUserId(userId);
  1477. changeOtherTicketRecord.setRelationId(relationId);
  1478. changeOtherTicketRecord.setOtherRelationId(changeDto.getOtherRelationId());
  1479. changeOtherTicketRecord.setRelateOrderId(changeDto.getOtherOrderId());
  1480. //该车票订单id
  1481. changeOtherTicketRecord.setOrderId(netflixRelationView.getNfOriOrderId());
  1482. changeOtherTicketRecord.setStartTime(netflixRelationView.getStartTime());
  1483. changeOtherTicketRecord.setExpiryTime(expiryTime);
  1484. netflixUserChangeOtherTicketRecordMapper.insert(changeOtherTicketRecord);
  1485. if (netflixRelationView.getNfCheckId() != null) {
  1486. netflixUserAccountStatusRecordMapper.update(null, Wrappers.lambdaUpdate(NetflixUserAccountStatusRecord.class)
  1487. .set(NetflixUserAccountStatusRecord::getDeleted, false)
  1488. .eq(NetflixUserAccountStatusRecord::getId, netflixRelationView.getNfCheckId()));
  1489. }
  1490. Long ticketUserId = null;
  1491. //清除车票
  1492. GroupsRelation clearRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  1493. .eq(GroupsRelation::getId, relationId)
  1494. .in(GroupsRelation::getUserId, userIdList)
  1495. .last("limit 1"));
  1496. if (clearRelation != null) {
  1497. ticketUserId = clearRelation.getUserId();
  1498. clearService.clearTicket(clearRelation, UserTicketClearedRecord.Source.ticket_replace);
  1499. }
  1500. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1501. .eq(OrderDon::getRelationId, relationId)
  1502. .in(OrderDon::getUserId, userIdList)
  1503. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1504. .orderByDesc(OrderDon::getId)
  1505. .last("limit 1"));
  1506. if (orderDon != null) {
  1507. if (ticketUserId == null) {
  1508. ticketUserId = orderDon.getUserId();
  1509. }
  1510. //替换sku
  1511. GoodsDonSku replaceSku = goodsDonSkuMapper.selectById(skuId);
  1512. GoodsDonSku oriTicketSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  1513. //每天单价
  1514. BigDecimal dayPrice = oriTicketSku.getPrice().divide(BigDecimal.valueOf(oriTicketSku.getMonths() * 30), RoundingMode.DOWN);
  1515. //需要退款金额
  1516. BigDecimal refundMoney = dayPrice.multiply(BigDecimal.valueOf(betweenDay));
  1517. BigDecimal balance = Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO);
  1518. BigDecimal finalOrderMoney = orderDon.getMoney().add(balance);
  1519. if (refundMoney.compareTo(finalOrderMoney) > 0) {
  1520. refundMoney = finalOrderMoney;
  1521. }
  1522. //车票价格高于替换的规格价格 退余额
  1523. if (refundMoney.compareTo(replaceSku.getPrice()) > 0) {
  1524. BigDecimal refundBalance = refundMoney.subtract(replaceSku.getPrice());
  1525. if (refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  1526. userBenefitsService.addUserBalance(ticketUserId, refundBalance, UserBalanceSourceRecord.Source.TICKET_REPLACE, 0L, orderDon.getId(), UserBalanceSourceRecord.Source.TICKET_REPLACE.getDesc(), true);
  1527. }
  1528. }
  1529. }
  1530. } finally {
  1531. redisService.del(key);
  1532. }
  1533. }
  1534. @Override
  1535. public List<GoodsCategorySkuView> getNetflixReplaceOtherSkus(long userId, Long relationId) throws Exception {
  1536. //校验奈飞账号状态
  1537. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1538. Date expiryTime = netflixRelationView.getExpiryTime();
  1539. //小于15 不可替换其他车票
  1540. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1541. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  1542. .eq(SysConfig::getSysKey, Constant.ERROR_NETFLIX_CHANGE_OTHER_SKU_KEY)
  1543. .last("limit 1"));
  1544. List<ErrorNetflixChangeOtherSkuTicketDto> errorNetflixChangeOtherSkuTicketDtos = Jsons.parseList(sysConfig.getSysValue(), ErrorNetflixChangeOtherSkuTicketDto.class);
  1545. ErrorNetflixChangeOtherSkuTicketDto errorNetflixChangeOtherSkuTicketDto;
  1546. if (betweenDay <= 30) {
  1547. return null;
  1548. }
  1549. //自定义顺序 直接获取
  1550. if (betweenDay <= 60) {
  1551. //检验规格
  1552. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(0);
  1553. } else if (betweenDay <= 120) {
  1554. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(1);
  1555. } else {
  1556. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(2);
  1557. }
  1558. List<GoodsCategorySkuView> goodsCategorySkuViews = beanSearcher.searchAll(GoodsCategorySkuView.class, MapUtils.builder()
  1559. .field(GoodsCategorySkuView::getSkuId, errorNetflixChangeOtherSkuTicketDto.getSkuIds()).op(Operator.InList)
  1560. .orderBy(GoodsCategorySkuView::getPrice).desc()
  1561. .build());
  1562. return goodsCategorySkuViews;
  1563. }
  1564. @Override
  1565. public NetflixRefundInfoResp refundNetflixInfo(Long userId, Long relationId) {
  1566. //校验奈飞账号状态
  1567. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1568. Date expiryTime = netflixRelationView.getExpiryTime();
  1569. //小于15
  1570. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1571. NetflixRefundInfoResp refundInfoResp = new NetflixRefundInfoResp();
  1572. refundInfoResp.setIsRefund(true);
  1573. if (betweenDay > 30) {
  1574. refundInfoResp.setIsRefund(false);
  1575. }
  1576. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1577. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1578. .eq(OrderDon::getRelationId, relationId)
  1579. .in(OrderDon::getUserId, userIdList)
  1580. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1581. .orderByDesc(OrderDon::getId)
  1582. .last("limit 1"));
  1583. if (orderDon == null) {
  1584. refundInfoResp.setIsRefund(false);
  1585. }
  1586. Long skuId = netflixRelationView.getSkuId();
  1587. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1588. BigDecimal orderMoney = orderDon == null ? BigDecimal.ZERO : orderDon.getMoney();
  1589. if (orderMoney.compareTo(BigDecimal.ZERO) == 0) {
  1590. refundInfoResp.setIsRefund(false);
  1591. }
  1592. //每天单价
  1593. BigDecimal dayPrice = sku.getPrice().divide(BigDecimal.valueOf(sku.getMonths() * 30), RoundingMode.DOWN);
  1594. //需要退款金额
  1595. BigDecimal refundMoney = dayPrice.multiply(BigDecimal.valueOf(betweenDay));
  1596. refundInfoResp.setPrice(refundMoney);
  1597. BigDecimal balance = orderDon == null ? BigDecimal.ZERO : Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO);
  1598. //超过本身订单金额 不允许退款
  1599. if (refundMoney.compareTo(orderMoney) > 0) {
  1600. refundInfoResp.setIsRefund(false);
  1601. }
  1602. if (refundMoney.compareTo(orderMoney.add(balance)) > 0) {
  1603. refundInfoResp.setPrice(orderMoney.add(balance));
  1604. }
  1605. refundInfoResp.setRemainDays(betweenDay);
  1606. return refundInfoResp;
  1607. }
  1608. @Override
  1609. public Boolean refundNetflix(ErrorNetflixChangeReq req) throws Exception {
  1610. Long relationId = req.getRelationId();
  1611. Long userId = req.getUserId();
  1612. //校验奈飞账号状态
  1613. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1614. Date expiryTime = netflixRelationView.getExpiryTime();
  1615. //小于15
  1616. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1617. if (betweenDay > 30) {
  1618. throw BusinessRuntimeException.getInstance("车票有效期不超过30天可退款");
  1619. }
  1620. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1621. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1622. .eq(OrderDon::getRelationId, relationId)
  1623. .in(OrderDon::getUserId, userIdList)
  1624. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1625. .orderByDesc(OrderDon::getId)
  1626. .last("limit 1"));
  1627. if (orderDon == null) {
  1628. throw BusinessRuntimeException.getInstance("对应车票订单不存在,请联系客服");
  1629. }
  1630. Long skuId = netflixRelationView.getSkuId();
  1631. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1632. BigDecimal orderMoney = orderDon.getMoney();
  1633. if (orderMoney.compareTo(BigDecimal.ZERO) == 0) {
  1634. throw BusinessRuntimeException.getInstance("不符合退款条件");
  1635. }
  1636. //每天单价
  1637. BigDecimal dayPrice = sku.getPrice().divide(BigDecimal.valueOf(sku.getMonths() * 30), RoundingMode.DOWN);
  1638. //需要退款金额
  1639. BigDecimal refundMoney = dayPrice.multiply(BigDecimal.valueOf(betweenDay));
  1640. if (refundMoney.compareTo(orderMoney) > 0) {
  1641. throw BusinessRuntimeException.getInstance("不符合退款条件");
  1642. }
  1643. //调用第三方接口退款
  1644. OrderRefundReq refundReq = new OrderRefundReq();
  1645. refundReq.setRefundMoney(refundMoney);
  1646. refundReq.setRefundType("money");
  1647. String outNo = orderRefundService.centerRefund(refundReq, orderDon);
  1648. orderDon.setStatus(OrderDon.Status.refund);
  1649. orderDon.setRefundMoney(refundMoney);
  1650. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  1651. orderDonMapper.updateById(orderDon);
  1652. orderRefundService.refundRecord(orderDon, refundMoney, "系统", goodsDon, sku, outNo, orderDon.getType().name(), null);
  1653. //清除车票
  1654. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  1655. clearService.clearTicket(relation, UserTicketClearedRecord.Source.refund);
  1656. if (netflixRelationView.getNfCheckId() != null) {
  1657. netflixUserAccountStatusRecordMapper.update(null, Wrappers.lambdaUpdate(NetflixUserAccountStatusRecord.class)
  1658. .set(NetflixUserAccountStatusRecord::getDeleted, false)
  1659. .eq(NetflixUserAccountStatusRecord::getId, netflixRelationView.getNfCheckId()));
  1660. }
  1661. return true;
  1662. }
  1663. private DistributePosterGoodsDetailView setGoodsPoster(RenewalView ticket, User user, List<Long> userIds) {
  1664. DistributePosterGoodsDetailView distributePosterGoodsDetailView = beanSearcher.searchFirst(DistributePosterGoodsDetailView.class, MapUtils.flatBuilder(request.getParameterMap())
  1665. .field(DistributePosterGoodsFrontView::getGoodsId, ticket.getGoodsId()).build());
  1666. if (distributePosterGoodsDetailView == null) {
  1667. return null;
  1668. }
  1669. distributePosterGoodsDetailView.setNickname(user.getNickname());
  1670. UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
  1671. .eq(UserDistribute::getUserId, user.getId())
  1672. .eq(UserDistribute::getDeleted, 1)
  1673. .last("limit 1"));
  1674. if (userDistribute != null) {
  1675. UserPlatDistributeRate userPlatDistributeRate = userPlatDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatDistributeRate.class)
  1676. .eq(UserPlatDistributeRate::getDistributeId, userDistribute.getId())
  1677. .eq(UserPlatDistributeRate::getGoodsId, ticket.getGoodsId())
  1678. .last("limit 1"));
  1679. if (userPlatDistributeRate != null) {
  1680. distributePosterGoodsDetailView.setRate(userPlatDistributeRate.getRate());
  1681. }
  1682. }
  1683. GoodsDon goodsDon = goodsDonMapper.selectById(ticket.getGoodsId());
  1684. if (goodsDon.getIsSkuDistribute()) {
  1685. if (userDistribute != null) {
  1686. UserPlatSkuDistributeRate userPlatSkuDistributeRate = userPlatSkuDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatSkuDistributeRate.class)
  1687. .eq(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId())
  1688. .eq(UserPlatSkuDistributeRate::getSkuId, ticket.getSkuId())
  1689. .last("limit 1"));
  1690. if (userPlatSkuDistributeRate != null) {
  1691. distributePosterGoodsDetailView.setRate(userPlatSkuDistributeRate.getRate());
  1692. }
  1693. } else {
  1694. DistributeGeneralSkuRate distributeGeneralSkuRate = distributeGeneralSkuRateMapper.selectOne(Wrappers.lambdaQuery(DistributeGeneralSkuRate.class)
  1695. .eq(DistributeGeneralSkuRate::getSkuId, ticket.getSkuId())
  1696. .last("limit 1"));
  1697. if (distributeGeneralSkuRate != null) {
  1698. distributePosterGoodsDetailView.setRate(distributeGeneralSkuRate.getRate());
  1699. }
  1700. }
  1701. }
  1702. //用户推广海报记录id
  1703. Optional.ofNullable(userDistributePosterRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributePosterRecord.class)
  1704. .eq(UserDistributePosterRecord::getPosterId, distributePosterGoodsDetailView.getId())
  1705. .in(UserDistributePosterRecord::getUserId, userIds)
  1706. .last("limit 1"))).ifPresent(re -> distributePosterGoodsDetailView.setRid(re.getId()));
  1707. return distributePosterGoodsDetailView;
  1708. }
  1709. private void setRenewDiscount(RenewalView ticket) {
  1710. //镜像或者独立规格
  1711. if (ticket.getIsMirror() || (ticket.getSkuNum() != null && ticket.getSkuNum() == 1)) {
  1712. RenewUpgradePackage renewUpgradePackage = renewUpgradePackageMapper.selectOne(Wrappers.lambdaQuery(RenewUpgradePackage.class)
  1713. .eq(RenewUpgradePackage::getGoodsId, ticket.getGoodsId())
  1714. .eq(RenewUpgradePackage::getStatus, 1)
  1715. .eq(RenewUpgradePackage::getDeleted, 1)
  1716. .eq(RenewUpgradePackage::getSkuId, ticket.getSkuId())
  1717. .orderByAsc(RenewUpgradePackage::getDiscount)
  1718. .last("limit 1")
  1719. .select(RenewUpgradePackage::getId, RenewUpgradePackage::getDiscount));
  1720. if (renewUpgradePackage != null) {
  1721. ticket.setDiscount(renewUpgradePackage.getDiscount());
  1722. }
  1723. }
  1724. }
  1725. private void setMirrorTicketInfo(RenewalView ticket) {
  1726. //设置MJ镜像信息
  1727. setMjMirrorInfo(ticket);
  1728. //设置GPT镜像信息
  1729. setGptMirrorInfo(ticket);
  1730. //clause pro
  1731. setClaudeProInfo(ticket);
  1732. //luma
  1733. setLumaInfo(ticket);
  1734. }
  1735. private void setMjMirrorInfo(RenewalView ticket) {
  1736. if (ticket.getGoodsId() == 26 && ticket.getIsMirror()) {
  1737. List<UpgradePackage> upgradePackages = upgradePackageMapper.selectList(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + ticket.getSkuId() + "\"')").eq(UpgradePackage::getStatus, Boolean.TRUE).eq(UpgradePackage::getDeleted, Boolean.TRUE));
  1738. if (CollectionUtil.isNotEmpty(upgradePackages)) {
  1739. upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(ticket::setMjPackagePrice);
  1740. }
  1741. try {
  1742. MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  1743. .field(MidjourneyUserView::getUserId, ticket.getUserId()).field(MidjourneyUserView::getRelationId, ticket.getRelationId())
  1744. .onlySelect(MidjourneyUserView::getMjUserRelaxNum, MidjourneyUserView::getMjUserFastNum,MidjourneyUserView::getMjUserUpgradeNum, MidjourneyUserView::getIsCar)
  1745. .build());
  1746. if (search == null) {
  1747. MidjourneyUser midjourneyUser = midjourneyAccountService.getMidjourneyUserToken(ticket.getUserId(), ticket.getRelationId());
  1748. ticket.setMjUserFastNum(midjourneyUser.getMjFastNum());
  1749. ticket.setMjUserUpgradeNum(midjourneyUser.getMjUpgradeNum());
  1750. ticket.setMjUserRelaxNum(midjourneyUser.getMjRelaxNum());
  1751. ticket.setIsCar(false);
  1752. } else {
  1753. ticket.setIsCar(search.getIsCar());
  1754. ticket.setMjUserFastNum(search.getMjUserFastNum());
  1755. ticket.setMjUserUpgradeNum(search.getMjUserUpgradeNum());
  1756. ticket.setMjUserRelaxNum(search.getMjUserRelaxNum());
  1757. }
  1758. midjourneyAccountService.updateUserExpiryTime(ticket.getRelationId(), ticket.getExpiryTime());
  1759. } catch (Exception e) {
  1760. }
  1761. }
  1762. }
  1763. public void setGptMirrorInfo(RenewalView ticket) {
  1764. if (ticket.getGoodsId() == 18 && ticket.getIsCar() && ticket.getExpiryTime() != null) {
  1765. try {
  1766. //gpt用户镜像
  1767. ChatGptUserView userInfo = chatGptAccountService.getUserInfo(ticket.getUserId(), ticket.getRelationId());
  1768. ticket.setGptUserLimitNum(userInfo.getLimitNum());
  1769. ticket.setGptUserLimitTime(userInfo.getLimitTime());
  1770. ticket.setUserDsLimitNum(userInfo.getDsLimitNum());
  1771. ticket.setUserDsLimitTime(userInfo.getDsLimitTime());
  1772. ticket.setUserOtherLimitNum(userInfo.getOtherLimitNum());
  1773. ticket.setUserOtherLimitTime(userInfo.getOtherLimitTime());
  1774. ticket.setUserToken(userInfo.getUserToken());
  1775. ticket.setUse(userInfo.getUse());
  1776. ticket.setModel(userInfo.getModel());
  1777. Integer count = upgradePackageMapper.selectCount(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + ticket.getSkuId() + "\"')")
  1778. .gt(UpgradePackage::getNum, userInfo.getLimitNum())
  1779. .eq(UpgradePackage::getStatus, Boolean.TRUE)
  1780. .eq(UpgradePackage::getGptType, 0)
  1781. .eq(UpgradePackage::getDeleted, Boolean.TRUE));
  1782. ticket.setUpgrade(count > 0 ? true : false);
  1783. ticket.setPackageId(userInfo.getPackageId());
  1784. if (userInfo.getPackageId() != 0) {
  1785. UpgradePackage upgradePackage = upgradePackageMapper.selectById(userInfo.getPackageId());
  1786. ticket.setPackagePrice(upgradePackage.getPrice());
  1787. Long upgradeOrderDonSkuId = upgradePackage.getUpgradeSkuId();
  1788. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, upgradeOrderDonSkuId).build());
  1789. renewSku.setPackageId(userInfo.getPackageId());
  1790. ticket.setRenewSku(renewSku);
  1791. }
  1792. ticket.setIsRenewPackage(userInfo.getIsRenewPackage());
  1793. Long renewSkuId = userInfo.getRenewSkuId();
  1794. if (renewSkuId != null) {
  1795. GoodsDonSkuRenewView upgradeSkuRenewView = ticket.getRenewSku();
  1796. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  1797. //续费升级是更高级规格
  1798. if (upgradeSkuRenewView == null || (renewSku.getGptUserLimitNum() >= upgradeSkuRenewView.getGptUserLimitNum() && renewSku.getMonths() >= userInfo.getMonths())) {
  1799. Optional.ofNullable(orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  1800. .eq(OrderDonRenewRecord::getOrderId, userInfo.getRenewOrderId())
  1801. .last("limit 1"))).ifPresent(e -> renewSku.setOriginalOrderId(e.getOrderId()));
  1802. ticket.setRenewSku(renewSku);
  1803. }
  1804. }
  1805. } catch (Exception e) {
  1806. }
  1807. }
  1808. }
  1809. public void setClaudeProInfo(RenewalView ticket) {
  1810. //clause pro
  1811. if (ticket.getGoodsId() == 75l && ticket.getExpiryTime() != null) {
  1812. try {
  1813. ClaudeUserView userInfo = claudeService.getUserInfo(ticket.getUserId(), ticket.getRelationId());
  1814. ticket.setGptUserLimitNum(userInfo.getLimitNum());
  1815. ticket.setGptUserLimitTime(userInfo.getLimitTime());
  1816. ticket.setUse(userInfo.getUse());
  1817. Long renewSkuId = userInfo.getRenewSkuId();
  1818. if (renewSkuId != null) {
  1819. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  1820. ticket.setRenewSku(renewSku);
  1821. }
  1822. } catch (Exception e) {
  1823. }
  1824. }
  1825. }
  1826. public void setLumaInfo(RenewalView ticket) {
  1827. if (ticket.getGoodsId() == Constant.LUMA_GOODS_ID && ticket.getExpiryTime() != null) {
  1828. try {
  1829. List<UpgradePackage> upgradePackages = upgradePackageMapper.selectList(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + ticket.getSkuId() + "\"')").eq(UpgradePackage::getStatus, Boolean.TRUE).eq(UpgradePackage::getDeleted, Boolean.TRUE));
  1830. if (CollectionUtil.isNotEmpty(upgradePackages)){
  1831. upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(ticket::setLumaPackagePrice);
  1832. }
  1833. LumaUser lumaUser = lumaService.getLumaUser(ticket.getUserId(), ticket.getRelationId());
  1834. ticket.setLumaUserNum(lumaUser.getNum());
  1835. } catch (Exception e) {
  1836. }
  1837. }
  1838. }
  1839. /**
  1840. * 获取gpt镜像天卡活动参与平台ids
  1841. * @return
  1842. */
  1843. private List<Long> getGptMirrorGiveawayBuyGids() {
  1844. GptMirrorDayCardGiveawayActivity gptMirrorDayCardGiveawayActivity = beanSearcher.searchFirst(GptMirrorDayCardGiveawayActivity.class, MapUtils.builder().build());
  1845. if (gptMirrorDayCardGiveawayActivity != null) {
  1846. String buyGoodsIds = gptMirrorDayCardGiveawayActivity.getBuyGoodsIds();
  1847. try {
  1848. return Jsons.parseList(buyGoodsIds, Long.class);
  1849. } catch (Exception e) {
  1850. }
  1851. }
  1852. return null;
  1853. }
  1854. /**
  1855. * 标记是否可抵扣会员车票
  1856. */
  1857. private void markVipDeductTicket(List<Long> userIds, RenewalView ticket, List<Long> vipSkuIds, Boolean isVip) {
  1858. if (CollUtil.isNotEmpty(vipSkuIds) && !isVip) {
  1859. Long skuId = ticket.getSkuId();
  1860. if (vipSkuIds.contains(skuId)) {
  1861. //是否时长最长
  1862. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  1863. .field(RenewalView::getRelationId, ticket.getRelationId()).op(Operator.NotEqual)
  1864. .field(RenewalView::getSkuId, skuId)
  1865. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  1866. .field(RenewalView::getExpiryTime, ticket.getExpiryTime()).op(Operator.GreaterThan)
  1867. .build());
  1868. if (number.intValue() == 0) {
  1869. ticket.setIsVipDeduct(true);
  1870. }
  1871. }
  1872. }
  1873. }
  1874. /**
  1875. * 检验奈飞账号状态
  1876. */
  1877. public GroupsRelationView checkNetflixErrorStatus(Long relationId, Long userId) {
  1878. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1879. NetflixUserAccountStatusRecord netflixUseAccountStatusRecord = netflixUserAccountStatusRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1880. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1881. .eq(NetflixUserAccountStatusRecord::getDeleted, 1)
  1882. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1883. .orderByDesc(NetflixUserAccountStatusRecord::getId)
  1884. .last("limit 1"));
  1885. if (netflixUseAccountStatusRecord == null) {
  1886. throw BusinessRuntimeException.getInstance("请先提交账号检测");
  1887. }
  1888. Integer state = netflixUseAccountStatusRecord.getState();
  1889. if (state == 0) {
  1890. throw BusinessRuntimeException.getInstance("您的账号检测中");
  1891. }
  1892. //2是登录失败 3是被封号
  1893. if (state != 3) {
  1894. throw BusinessRuntimeException.getInstance("您的账号未封禁");
  1895. }
  1896. GroupsRelationView netflixRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  1897. .field(GroupsRelationView::getId, relationId)
  1898. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  1899. .field(GroupsRelationView::getGoodsId, Constant.NETFLIX_GID)
  1900. .field(GroupsRelationView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1901. .build());
  1902. if (netflixRelationView == null) {
  1903. throw BusinessRuntimeException.getInstance("奈飞车票已过期");
  1904. }
  1905. netflixRelationView.setNfCheckId(netflixUseAccountStatusRecord.getId());
  1906. netflixRelationView.setNfOriOrderId(netflixUseAccountStatusRecord.getOrderId());
  1907. return netflixRelationView;
  1908. }
  1909. /**
  1910. * 获取车票 并生成订单
  1911. */
  1912. public TicketChangeDto getTicketAndGenerateOrder(Long userId, Long skuId, Date startTime, Date expiryTime) {
  1913. Retryer<TicketChangeDto> build = RetryerBuilder.<TicketChangeDto>newBuilder()
  1914. .retryIfException()
  1915. //运行时异常重试
  1916. .retryIfRuntimeException()
  1917. //false重试
  1918. .retryIfResult(res -> res == null)
  1919. //1s 间隔
  1920. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  1921. //停止策略 : 尝试请求1次
  1922. .withStopStrategy(StopStrategies.stopAfterAttempt(1)).build();
  1923. if (startTime == null) {
  1924. startTime = DateTime.now();
  1925. }
  1926. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1927. if (expiryTime == null) {
  1928. if (sku.getDays() != null) {
  1929. expiryTime = DateUtil.offsetDay(startTime, sku.getDays());
  1930. } else {
  1931. expiryTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  1932. }
  1933. }
  1934. Date finalStartTime = startTime;
  1935. Date finalExpiryTime = expiryTime;
  1936. try {
  1937. return build.call(() -> {
  1938. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(skuId);
  1939. if (groups == null) {
  1940. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  1941. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  1942. .eq(GroupsTrips::getSkuId, skuId)
  1943. .last("limit 1"));
  1944. }
  1945. GroupsRelation relation = null;
  1946. if (groups != null) {
  1947. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  1948. }
  1949. //生成空车队
  1950. if (relation == null) {
  1951. relation = groupsFuncService.createNewGroupsTrips(sku);
  1952. }
  1953. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1954. .set(GroupsRelation::getUserId, userId)
  1955. .set(GroupsRelation::getStartTime, finalStartTime)
  1956. .set(GroupsRelation::getExpiryTime, finalExpiryTime)
  1957. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  1958. .eq(GroupsRelation::getId, relation.getId())
  1959. .eq(GroupsRelation::getUserId, 0));
  1960. if (update > 0) {
  1961. groupsMapper.decrAvailableNum(relation.getGroupsId());
  1962. Long relationId = relation.getId();
  1963. //生成新的订单
  1964. OrderDon otherOrderDon = generateNewTicketOrder(relationId, userId, sku);
  1965. TicketChangeDto ticketChangeDto = new TicketChangeDto();
  1966. ticketChangeDto.setOtherRelationId(relationId);
  1967. ticketChangeDto.setOtherOrderId(otherOrderDon.getId());
  1968. return ticketChangeDto;
  1969. }
  1970. log.error("发送用户:{} GPT镜像车票失败,进行重试", userId);
  1971. return null;
  1972. });
  1973. } catch (ExecutionException | RetryException e) {
  1974. log.error("发送用户GPT镜像失败:{}", StringUtil.getErrorText(e));
  1975. return null;
  1976. }
  1977. }
  1978. private OrderDon generateNewTicketOrder(Long relationId, Long userId, GoodsDonSku sku) {
  1979. OrderDon orderDon = new OrderDon();
  1980. orderDon.setUserId(userId);
  1981. orderDon.setOrderNo(SEQUENCE.nextId().toString());
  1982. orderDon.setMoney(BigDecimal.ZERO);
  1983. orderDon.setRelationId(relationId);
  1984. orderDon.setGoodsId(sku.getGoodsId());
  1985. orderDon.setSkuId(sku.getId());
  1986. orderDon.setType(OrderDon.Type.TICKET_REPLACE);
  1987. orderDon.setStatus(OrderDon.Status.complete);
  1988. orderDonMapper.insert(orderDon);
  1989. return orderDon;
  1990. }
  1991. }