GroupRelationFrontServiceImpl.java 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  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.task.GlobalThreadPoolTaskExecutor;
  16. import com.cyksj.common.util.Jsons;
  17. import com.cyksj.common.util.StringUtil;
  18. import com.cyksj.enums.GatewayApiCode;
  19. import com.cyksj.mapper.*;
  20. import com.cyksj.mapper.manage.distribute.DistributeGeneralSkuRateMapper;
  21. import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
  22. import com.cyksj.mapper.manage.distribute.UserPlatDistributeRateMapper;
  23. import com.cyksj.mapper.manage.distribute.UserPlatSkuDistributeRateMapper;
  24. import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
  25. import com.cyksj.mapper.renew.RenewUpgradePackageMapper;
  26. import com.cyksj.mapper.sys.SysConfigMapper;
  27. import com.cyksj.mapper.sys.SysEmailMapper;
  28. import com.cyksj.mapper.vip.VipGoodsSkuMapper;
  29. import com.cyksj.mapper.vip.VipUserMapper;
  30. import com.cyksj.model.entity.*;
  31. import com.cyksj.model.manage.views.AccountView;
  32. import com.cyksj.model.manage.views.GroupsRelationView;
  33. import com.cyksj.model.request.SpecialGoodsTicketReq;
  34. import com.cyksj.model.request.TicketLoginReq;
  35. import com.cyksj.model.views.*;
  36. import com.cyksj.redis.RedisService;
  37. import com.cyksj.service.chatgpt.ChatGptAccountService;
  38. import com.cyksj.service.chatgpt.ChatGptAuthService;
  39. import com.cyksj.service.claude.ClaudeService;
  40. import com.cyksj.service.groups.GroupsFuncService;
  41. import com.cyksj.service.luma.LumaService;
  42. import com.cyksj.service.mail.CommonMailService;
  43. import com.cyksj.service.mail.MailService;
  44. import com.cyksj.service.mange.coupon.CouponCommonService;
  45. import com.cyksj.service.midjourney.MidjourneyAccountService;
  46. import com.cyksj.service.relation.GroupRelationFrontService;
  47. import com.cyksj.service.relation.GroupsRelationChangeService;
  48. import com.cyksj.service.relation.GroupsRelationNetflixService;
  49. import com.cyksj.service.user.UserBindRelationService;
  50. import com.cyksj.service.user.UserLoginRecordService;
  51. import com.ejlchina.searcher.BeanSearcher;
  52. import com.ejlchina.searcher.SearchResult;
  53. import com.ejlchina.searcher.param.Operator;
  54. import com.ejlchina.searcher.util.MapBuilder;
  55. import com.ejlchina.searcher.util.MapUtils;
  56. import com.github.rholder.retry.*;
  57. import lombok.RequiredArgsConstructor;
  58. import lombok.extern.slf4j.Slf4j;
  59. import org.springframework.stereotype.Service;
  60. import org.springframework.transaction.annotation.Transactional;
  61. import javax.servlet.http.HttpServletRequest;
  62. import java.math.BigDecimal;
  63. import java.math.RoundingMode;
  64. import java.util.*;
  65. import java.util.concurrent.ExecutionException;
  66. import java.util.concurrent.TimeUnit;
  67. import java.util.concurrent.atomic.AtomicInteger;
  68. import java.util.stream.Collectors;
  69. import static com.cyksj.enums.GatewayApiCode.GROUP_INDEX_ALREADY_BE_USER;
  70. import static com.cyksj.enums.GatewayApiCode.GROUP_INDEX_NOT_FIND;
  71. /*
  72. *项目名: netflix
  73. *文件名: GroupRelationFrontServiceImpl
  74. *创建者: JavaZou
  75. *创建时间:2022/12/29 15:42
  76. */
  77. @Service
  78. @RequiredArgsConstructor
  79. @Slf4j
  80. public class GroupRelationFrontServiceImpl implements GroupRelationFrontService {
  81. private final UserBindRelationService userBindRelationService;
  82. private final UserMapper userMapper;
  83. private final BeanSearcher beanSearcher;
  84. private final CouponCommonService couponCommonService;
  85. private final GroupsRelationMapper groupsRelationMapper;
  86. private final GroupsMapper groupsMapper;
  87. private final ChatGptAuthService chatGptAuthService;
  88. private final RedisService redisService;
  89. private final MailService mailService;
  90. private final OrderDonMapper orderDonMapper;
  91. private final GroupsRelationExpiryNotifyRecordMapper groupsRelationExpiryNotifyRecordMapper;
  92. private final HttpServletRequest request;
  93. private final GroupsFuncService groupsFuncService;
  94. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  95. private final GroupsRelationLoginCodeRecordMapper groupsRelationLoginCodeRecordMapper;
  96. private final SysEmailMapper sysEmailMapper;
  97. private final GoodsDonSkuMapper goodsDonSkuMapper;
  98. private final UserFuncPropertyMapper userFuncPropertyMapper;
  99. private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
  100. private final UserLoginRecordService userLoginRecordService;
  101. private final UserCertRecordMapper userCertRecordMapper;
  102. private final MidjourneyAccountService midjourneyAccountService;
  103. private final ChatGptAccountService chatGptAccountService;
  104. private final UpgradePackageMapper upgradePackageMapper;
  105. private final LumaService lumaService;
  106. private final GroupsRelationNetflixService groupsRelationNetflixService;
  107. private final UserDistributeMapper userDistributeMapper;
  108. private final UserPlatDistributeRateMapper userPlatDistributeRateMapper;
  109. private final GoodsDonMapper goodsDonMapper;
  110. private final UserPlatSkuDistributeRateMapper userPlatSkuDistributeRateMapper;
  111. private final DistributeGeneralSkuRateMapper distributeGeneralSkuRateMapper;
  112. private final RenewUpgradePackageMapper renewUpgradePackageMapper;
  113. private final ClaudeService claudeService;
  114. private final UserDistributePosterRecordMapper userDistributePosterRecordMapper;
  115. private final OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  116. private final AccountMapper accountMapper;
  117. private final UserBenefitsMapper userBenefitsMapper;
  118. private final GroupsRelationChangeService changeTickerRelation;
  119. private final NetflixTempAccountUserMapper netflixTempAccountUserMapper;
  120. private final NetflixUserAccountStatusRecordMapper netflixUserAccountStatusRecordMapper;
  121. private final AccountNetflixStateMapper accountNetflixStateMapper;
  122. private final UserMirrorShopMapper userMirrorShopMapper;
  123. private final CommonMailService commonMailService;
  124. private final SysConfigMapper sysConfigMapper;
  125. private final GptMirrorDayCardGiveawayActivityMapper gptMirrorDayCardGiveawayActivityMapper;
  126. private final MirrorTicketPopupsRecordMapper mirrorTicketPopupsRecordMapper;
  127. private final VipUserMapper vipUserMapper;
  128. private final VipGoodsSkuMapper vipGoodsSkuMapper;
  129. @Override
  130. public SearchResult<RenewalView> getMyTicket(long userId, Boolean isLoginPopularize, String customId, String account, String orderNo, Integer cmt, Boolean isVip) {
  131. User u = userMapper.selectById(userId);
  132. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  133. if (u.getIsBlack()) {
  134. return new SearchResult<>();
  135. }
  136. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  137. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  138. if (cmt != null && cmt == 2 && StrUtil.isNotBlank(customId)) {
  139. UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
  140. .eq(UserMirrorShop::getCustomId, customId)
  141. .last("limit 1"));
  142. if (userMirrorShop != null) {
  143. builder.field(RenewalView::getCmt, cmt).field(RenewalView::getYhsId, userMirrorShop.getId());
  144. }
  145. }
  146. if (cmt == null || cmt != 2) {
  147. builder.field(RenewalView::getCmt, 2).op(Operator.NotEqual);
  148. }
  149. // Long yhsId = yhShopFrontService.getYhsIdByCustomId(customId);
  150. DateTime now = DateTime.now();
  151. if (StrUtil.isNotBlank(account)) {
  152. builder.field(RenewalView::getAccount, account).op(Operator.Contain);
  153. }
  154. String conditionSql = String.format("(gr.expiry_time is null or gr.expiry_time > '%s'", now);
  155. //镜像车票 过期7天后清除
  156. //个人店铺和AI店铺 暂不支持过期续费
  157. if (cmt == null && StrUtil.isEmpty(customId)) {
  158. conditionSql += String.format(" or (sku.is_mirror and gr.expiry_time > '%s')", DateUtil.offsetDay(now, -7));
  159. }
  160. conditionSql += ")";
  161. if (StrUtil.isNotEmpty(orderNo)) {
  162. 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);
  163. }
  164. SearchResult<RenewalView> list = beanSearcher.search(RenewalView.class, builder
  165. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  166. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  167. .put("condition", conditionSql)
  168. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  169. .field(RenewalView::getIsVip, Optional.ofNullable(isVip).orElse(false))
  170. .orderBy(RenewalView::getExpiryTime).asc()
  171. .build());
  172. if (list.getDataList().size() > 0) {
  173. //过滤邀请制、已失效的车位
  174. Integer size = list.getTotalCount().intValue();
  175. //赠送GPT日卡 参与平台ids
  176. List<Long> renewReduceSkuIds = userBenefitsMapper.selectList(Wrappers.lambdaQuery(UserBenefits.class)
  177. .eq(UserBenefits::getType, UserBenefits.Type.RENEW).eq(UserBenefits::getStatus, 1).select(UserBenefits::getSkuId)).stream().map(UserBenefits::getSkuId).collect(Collectors.toList());
  178. List<Long> gptBuyGids = getGptMirrorGiveawayBuyGids();
  179. //gpt日卡活动
  180. GptMirrorDayCardGiveawayActivity gptMirrorDayCardGiveawayActivity = gptMirrorDayCardGiveawayActivityMapper.selectOne(Wrappers.lambdaQuery(GptMirrorDayCardGiveawayActivity.class)
  181. .last("limit 1"));
  182. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  183. .eq(SysConfig::getSysKey, Constant.EMAIL_PWD_SHOW_GID_KEY)
  184. .last("limit 1"));
  185. List<Long> showEmailPwdGids = new ArrayList<>();
  186. if (sysConfig != null && StrUtil.isNotBlank(sysConfig.getSysValue())) {
  187. try {
  188. showEmailPwdGids.addAll(Jsons.parseList(sysConfig.getSysValue(), Long.class));
  189. } catch (Exception e) {
  190. }
  191. }
  192. list.getDataList().forEach(ticket -> {
  193. if (ticket.getSkuId() == null || ticket.getGoodsId() == null) {
  194. return;
  195. }
  196. if (ticket.getGoodsId() == 18 && ticket.getSkuNum() > 1) {
  197. ticket.setPassword(null);
  198. }
  199. ticket.setIsMulti(false);
  200. if (ticket.getSkuNum() > 1) {
  201. ticket.setIsMulti(true);
  202. }
  203. //chatGPT直连
  204. if (ticket.getGoodsId().equals(42l)) {
  205. if (StrUtil.isNotBlank(ticket.getAccount())) {
  206. String accessToken;
  207. try {
  208. accessToken = chatGptAuthService.getAccessToken(ticket.getAccount());
  209. ticket.setGptRefreshToken(accessToken);
  210. } catch (Exception e) {
  211. redisService.set(RedisService.key.CHAT_GPT_TOKEN_EXCEPTION_KEY.getName() + ticket.getAccount(), ticket.getAccount());
  212. }
  213. }
  214. ticket.setAccount(null);
  215. ticket.setPassword(null);
  216. } else {
  217. ticket.setGptRefreshToken(null);
  218. }
  219. if (ticket.getSecondType() == 1) {
  220. ticket.setAccount(null);
  221. ticket.setPassword(null);
  222. }
  223. //gpt 2月的独立账号可看到邮箱密码
  224. if (ticket.getGoodsId() == 18l && ticket.getNum() == 1 && ticket.getAccount() != null && ticket.getCreatedTime().compareTo(DateUtil.parse("2025-02-01")) > 0) {
  225. } else {
  226. if (!showEmailPwdGids.contains(ticket.getGoodsId())) {
  227. ticket.setGptEmailPwd(null);
  228. }
  229. }
  230. if (isLoginPopularize != null && isLoginPopularize) {
  231. GoodsDonViews views = beanSearcher.searchFirst(GoodsDonViews.class, MapUtils.builder().field(GoodsDonViews::getId, ticket.getGoodsId()).build());
  232. views.setSpecs(beanSearcher.searchFirst(GoodsDonSpecFrontView.class, MapUtils.builder().field(GoodsDonSpecFrontView::getGoodsId, views.getId()).build()));
  233. views.setSkuList(beanSearcher.searchAll(GoodsDonSkuFrontView.class, MapUtils.builder().field(GoodsDonSkuFrontView::getGoodsId, views.getId()).field(GoodsDonSkuFrontView::getStatus, true).build()));
  234. ticket.setGoodsDonViews(views);
  235. }
  236. if (ticket.getMonths() != null && ticket.getMonths() >= 300) {
  237. ticket.setExpiryTime(null);
  238. }
  239. if (ticket.getExpiryTime() != null && ticket.getGoodsType() == 1) {
  240. String remainDays = DateUtil.formatBetween(now, ticket.getExpiryTime(), BetweenFormater.Level.DAY);
  241. if ("0天".equals(remainDays)) {
  242. remainDays = "小于1天";
  243. } else {
  244. //当天也算
  245. int days = Integer.parseInt(remainDays.substring(0, remainDays.indexOf("天")));
  246. remainDays = days + 1 + "天";
  247. }
  248. ticket.setRemainDays(remainDays);
  249. ticket.setTotal(DateUtil.betweenDay(ticket.getStartTime(), ticket.getExpiryTime(), false) + 1);
  250. }
  251. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  252. .eq(OrderDon::getRelationId, ticket.getRelationId())
  253. .eq(OrderDon::getUserId, ticket.getUserId())
  254. .eq(OrderDon::getOrderType, 1)
  255. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  256. .orderByDesc(OrderDon::getId)
  257. .last("limit 1"));
  258. if (orderDon != null) {
  259. ticket.setOrderNo(orderDon.getOrderNo());
  260. ticket.setOrderId(orderDon.getId());
  261. ticket.setTransactionId(orderDon.getTransactionId());
  262. if (ticket.getSecondType() == 1) {
  263. //是否完成邀请 根据订单状态
  264. ticket.setIsComplete(orderDon.getStatus() == OrderDon.Status.complete ? true : false);
  265. }
  266. }
  267. if (size > 1 && ticket.getGoodsId() != 18) {
  268. Date payTime = null;
  269. if (orderDon != null) {
  270. payTime = Optional.ofNullable(orderDon.getPayTime()).orElse(orderDon.getCreatedTime());
  271. }
  272. //加购订单
  273. if (orderDon == null) {
  274. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(ticket.getRelationId(), ticket.getUserId());
  275. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  276. String relationIds = data.getRelationIds();
  277. if (StrUtil.isEmpty(relationIds)) {
  278. return;
  279. }
  280. try {
  281. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  282. if (relationList.contains(ticket.getRelationId())) {
  283. OrderDon plusOrder = orderDonMapper.selectById(data.getOrderId());
  284. if (plusOrder != null) {
  285. payTime = Optional.ofNullable(plusOrder.getPayTime()).orElse(plusOrder.getCreatedTime());
  286. }
  287. break;
  288. }
  289. } catch (Exception e) {
  290. }
  291. }
  292. }
  293. ticket.setPayTime(payTime);
  294. }
  295. if (ticket.getSkuNum() != null && ticket.getSkuNum() == 1) {
  296. }
  297. //奈飞、gpt
  298. if (ticket.getGoodsId() == 1 || ticket.getGoodsId() == 18 || ticket.getGoodsId() == 33l) {
  299. ticket.setEmail(null);
  300. }
  301. //设置镜像车票信息
  302. setMirrorTicketInfo(ticket);
  303. // List<GroupsRelationUserView> relationUserViews = groupsRelationMapper.getUserRelationUserViews(ticket.getGroupId(), ticket.getRelationId(), ticket.getUserId(), List.of(GroupsRelation.Status.validity, GroupsRelation.Status.outside));
  304. // ticket.setRelationViews(relationUserViews);
  305. if (ticket.getExpiryTime() != null) {
  306. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  307. }
  308. //查看双重验证码
  309. if (StrUtil.isNotEmpty(ticket.getApiSecret())) {
  310. Boolean isHasVerifyCode = StrUtil.isNotBlank(ticket.getVerifyCode()) ? true : false;
  311. Integer codeNum = getUserCodeNumBySkuId(ticket.getUserId(), ticket.getSkuId(), isHasVerifyCode);
  312. ticket.setCodeNum(codeNum);
  313. }
  314. Long qaId = groupsRelationMapper.selectGoodsDonQaByGoodsId(ticket.getGoodsId());
  315. ticket.setQa(qaId > 0 ? true : false);
  316. //是否存在海报
  317. ticket.setPosterInfo(setGoodsPoster(ticket, u, userIds));
  318. //续费升级折扣
  319. setRenewDiscount(ticket);
  320. if (CollUtil.isNotEmpty(renewReduceSkuIds) && renewReduceSkuIds.contains(ticket.getSkuId())) {
  321. ticket.setIsRenewReduce(true);
  322. }
  323. if (CollUtil.isNotEmpty(gptBuyGids) && gptBuyGids.contains(ticket.getGoodsId())) {
  324. if (gptMirrorDayCardGiveawayActivity != null && orderDon != null && orderDon.getCreatedTime().compareTo(gptMirrorDayCardGiveawayActivity.getCreatedTime()) > 0) {
  325. //是否领取过GPT日卡
  326. Long orderId = orderDon.getId();
  327. Number count = beanSearcher.searchCount(GptMirrorDayCardActivityRecord.class, MapUtils.builder().field(GptMirrorDayCardActivityRecord::getOrderId, orderId).build());
  328. ticket.setReceivedGptGift(count.intValue() > 0);
  329. }
  330. }
  331. });
  332. }
  333. userLoginRecordService.saveUserLoginDayRecord(userId);
  334. return list;
  335. }
  336. @Override
  337. public Boolean isJoinCorpWx(Long userId, Boolean isJoin, Boolean noCoupon) {
  338. if (!isJoin) {
  339. User user = userMapper.selectById(userId);
  340. if (user == null || StrUtil.isEmpty(user.getUnionid())) {
  341. return true;
  342. }
  343. // CorpUser corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class)
  344. // .ne(CorpUser::getUnionid, "")
  345. // .eq(CorpUser::getUnionid, user.getUnionid())
  346. // .last("limit 1")
  347. // .select(CorpUser::getId)
  348. // );
  349. CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
  350. .field(CorpUserFollowView::getUnionId, user.getUnionid())
  351. .field(CorpUserFollowView::getStatus, 1).build());
  352. if (corpUserFollowView == null) {
  353. return false;
  354. }
  355. }
  356. //用户是否买了奈飞车票
  357. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  358. .field(RenewalView::getUserId, userId)
  359. .field(RenewalView::getGoodsId, 1)
  360. .field(RenewalView::getStatus, List.of("validity", "overdue")).op(Operator.InList)
  361. .build());
  362. if (number.intValue() > 0 && !noCoupon) {
  363. couponCommonService.sendCouponToUser(userId, 34l, 0l, 0l, 0l, CouponUser.Channel.wxCorp);
  364. }
  365. return true;
  366. }
  367. @Override
  368. public GroupsRelation getSimilarExpiredGroupRelation(GoodsDonSku sku, List<Long> errorsRelationIds, String ip) {
  369. Long skuId = sku.getId();
  370. Integer days = sku.getDays();
  371. Integer months = sku.getMonths();
  372. Integer maxNum = sku.getNum();
  373. DateTime expiryTime = null;
  374. if (days != null && days > 0) {
  375. expiryTime = DateUtil.offsetDay(DateTime.now(), days);
  376. } else {
  377. expiryTime = DateUtil.offsetMonth(DateTime.now(), months);
  378. }
  379. Integer extraNum = 5;
  380. if (sku.getId() == 178l) {
  381. extraNum = 2;
  382. }
  383. maxNum += extraNum;
  384. DateTime minExpiryTime = DateUtil.offsetDay(expiryTime, -5);
  385. Long groupsId = groupsRelationMapper.selectSimilarExpiredRelation(skuId, minExpiryTime, maxNum, ip);
  386. if (groupsId == null) {
  387. log.info("暂无相似过期时间车队");
  388. return null;
  389. }
  390. GroupsRelation relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  391. .notIn(errorsRelationIds != null && errorsRelationIds.size() > 0, GroupsRelation::getId, errorsRelationIds)
  392. .eq(GroupsRelation::getGroupsId, groupsId)
  393. .eq(GroupsRelation::getStatus, GroupsRelation.Status.none)
  394. .eq(GroupsRelation::getUserId, 0)
  395. .orderByAsc(GroupsRelation::getNum)
  396. .last("limit 1"));
  397. if (relation != null) {
  398. log.info("用户userId:{},获取相似车队的车位relationId:{}", relation.getId());
  399. }
  400. return relation;
  401. }
  402. @Override
  403. public Page<UserRecommendGoodsFrontView> getRecommendGoodsViews(Boolean isPayNf, List<Long> filter_goods_id, Boolean filterCourseGoods, Integer start, Integer limit) {
  404. return groupsRelationMapper.getRecommendGoodsViews(new Page<>(start, limit), filter_goods_id, isPayNf, filterCourseGoods);
  405. }
  406. @Override
  407. @Transactional(rollbackFor = Throwable.class)
  408. public void sendCourseWare(SpecialGoodsTicketReq request) throws Exception {
  409. Long userId = request.getUserId();
  410. Long relationId = request.getRelationId();
  411. String email = request.getEmail();
  412. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  413. RenewalView relation = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getRelationId, relationId).build());
  414. Assert.notNull(relation, "您的车票不存在");
  415. Long relationUserId = relation.getUserId();
  416. if (!userIdList.contains(relationUserId)) {
  417. throw BusinessRuntimeException.getInstance("您的车票不存在");
  418. }
  419. if (relation.getSpecialType() != GoodsDon.SpecialType.courseware) {
  420. throw BusinessRuntimeException.getInstance("");
  421. }
  422. //是否已发送
  423. if (StrUtil.isNotBlank(relation.getGrAccount())) {
  424. throw BusinessRuntimeException.getInstance("已领取课件,请前往邮箱查看");
  425. }
  426. if (!Validator.isEmail(email)) {
  427. throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
  428. }
  429. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  430. .set(GroupsRelation::getAccount, email)
  431. .and(qr -> qr.isNull(GroupsRelation::getAccount).or().eq(GroupsRelation::getAccount, StrUtil.EMPTY))
  432. .eq(GroupsRelation::getId, relationId));
  433. if (update > 0) {
  434. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  435. .set(OrderDon::getStatus, OrderDon.Status.complete)
  436. .eq(OrderDon::getRelationId, relationId)
  437. .eq(OrderDon::getUserId, userId)
  438. .eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  439. mailService.sendCoursewareByGoodsId(relation.getGoodsId(), relation.getRelationId(), relation.getUserId(), relation.getTitle(), email);
  440. }
  441. }
  442. @Override
  443. public GroupsRelation getRelation(Long payRelationId, Long userId, GoodsDonSku sku, String ip) {
  444. GroupsRelation relation = null;
  445. Integer maxNum = sku.getNum();
  446. if (payRelationId != null && payRelationId > 0) {
  447. relation = groupsRelationMapper.selectById(payRelationId);
  448. if (relation == null) {
  449. throw new BusinessRuntimeException(GROUP_INDEX_NOT_FIND.getCode(), GROUP_INDEX_NOT_FIND.getMsg());
  450. }
  451. if (relation.getUserId() != null && relation.getUserId() > 0L) {
  452. throw new BusinessRuntimeException(GROUP_INDEX_ALREADY_BE_USER.getCode(), GROUP_INDEX_ALREADY_BE_USER.getMsg());
  453. }
  454. } else {
  455. GroupsTrips groups = null;
  456. //ChatGpt Plus、Midjourney非独立规格 上车先获取硬塞座位 硬塞5个座位
  457. //主账号过期时间25天以外
  458. //23-12-06 MidJourney 不硬塞
  459. if (sku.getNum() > 1 && Constant.AI_goodsIds.get(0) == sku.getGoodsId()) {
  460. Integer extraNum = 5;
  461. if (sku.getId() == 178l || sku.getId() == 423l) {
  462. extraNum = 2;
  463. }
  464. maxNum += extraNum;
  465. DateTime time = DateUtil.offsetDay(DateUtil.beginOfDay(DateTime.now()), 25);
  466. //不塞存在该用户的车队
  467. Long groupsId = groupsRelationMapper.getOutSideGroupsTripsRelationByGoodsId(sku.getId(), time, extraNum, userId, sku.getNum(), maxNum);
  468. if (groupsId != null) {
  469. relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  470. .eq(GroupsRelation::getGroupsId, groupsId)
  471. .eq(GroupsRelation::getUserId, 0)
  472. .eq(GroupsRelation::getStatus, GroupsRelation.Status.outside)
  473. .last("limit 1"));
  474. if (relation == null) {
  475. relation = new GroupsRelation();
  476. relation.setStatus(GroupsRelation.Status.outside);
  477. relation.setUserId(userId);
  478. relation.setGroupsId(groupsId);
  479. GroupsRelation maxNumRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  480. Integer nextNum = maxNumRelation.getNum() + 1;
  481. if (redisService.setNx(RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getNameFormat(groupsId, nextNum), nextNum, RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getTimeout())) {
  482. relation.setNum(nextNum);
  483. groupsRelationMapper.insert(relation);
  484. } else {
  485. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  486. }
  487. }
  488. groups = groupsMapper.selectById(groupsId);
  489. }
  490. }
  491. if (groups == null) {
  492. //寻找差不多过期时间规格的车位
  493. relation = getSimilarExpiredGroupRelation(sku, null, ip);
  494. if (relation == null) {
  495. //TODO 如果没指定座位,等待逻辑确认
  496. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.validity, maxNum, ip);
  497. if (groups == null) {
  498. //待发车
  499. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.waiting, maxNum, ip);
  500. }
  501. //新增空车队
  502. if (groups == null) {
  503. relation = groupsFuncService.createNewGroupsTrips(sku);
  504. }
  505. //获取车位
  506. if (relation == null) {
  507. //寻找快满编车队进行占座
  508. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  509. if (relation == null) {
  510. Long groupsId = groups.getId();
  511. TASK_EXECUTOR.execute(() -> groupsMapper.updateAvailableNum(groupsId));
  512. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  513. }
  514. }
  515. }
  516. }
  517. if (groups == null) {
  518. groups = groupsMapper.selectById(relation.getGroupsId());
  519. }
  520. //车队目前可用停车数
  521. relation.setGroupsAvailParkingNum(groups.getAvailableParkingNum());
  522. relation.setMaxNum(maxNum);
  523. }
  524. return relation;
  525. }
  526. @Override
  527. public String getAiVerifyCode(TicketLoginReq loginReq) throws Exception {
  528. Integer type = loginReq.getType();
  529. RenewalView renewalView;
  530. String account;
  531. Long userId = 0l;
  532. Long relationId = 0l;
  533. if (loginReq.getMerchants()) {
  534. renewalView = new RenewalView();
  535. renewalView.setGoodsId(loginReq.getGoodsId());
  536. renewalView.setAccount(loginReq.getAccount());
  537. if (loginReq.getAccountId() != null && loginReq.getAccountId() != 0l) {
  538. GroupsTrips groupsTrips = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  539. .eq(GroupsTrips::getAccountId, loginReq.getAccountId())
  540. .last("limit 1"));
  541. if (groupsTrips != null) {
  542. renewalView.setSkuId(groupsTrips.getSkuId());
  543. }
  544. }
  545. renewalView.setUserId(userId);
  546. account = loginReq.getAccount();
  547. } else {
  548. userId = loginReq.getUserId();
  549. relationId = loginReq.getRelationId();
  550. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  551. renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  552. .field(RenewalView::getRelationId, relationId).build());
  553. if (renewalView == null) {
  554. throw BusinessRuntimeException.getInstance("您的车票不存在...");
  555. }
  556. if (StrUtil.isEmpty(renewalView.getAccount())) {
  557. throw BusinessRuntimeException.getInstance("车票未配置账号");
  558. }
  559. account = renewalView.getAccount();
  560. String password = renewalView.getPassword();
  561. if (StrUtil.hasEmpty(account, password)) {
  562. throw BusinessRuntimeException.getInstance("您的车票账号密码异常,请联系客服...");
  563. }
  564. }
  565. if (renewalView.getGoodsId() == 1l) {
  566. Integer linkType = loginReq.getLinkType();
  567. if (type == null && linkType == null) {
  568. throw BusinessRuntimeException.getInstance("系统异常");
  569. }
  570. if (linkType != null) {
  571. String key = RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getNameFormat(DateUtil.hour(DateTime.now(), true), linkType, renewalView.getUserId());
  572. if (!redisService.hasKey(key)) {
  573. redisService.set(key, 0l, RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getTimeout());
  574. } else {
  575. Integer value = (Integer) redisService.get(key);
  576. if (value >= 5) {
  577. throw BusinessRuntimeException.getInstance("获取奈飞同步更新装置过于频繁");
  578. }
  579. }
  580. }
  581. }
  582. String code = commonMailService.getTicketMailCode(renewalView.getGoodsId(), account, renewalView.getRelateEmail(), renewalView.getGptEmailPwd(), renewalView.getCreatedTime(), type, loginReq.getLinkType(), false);
  583. GroupsRelationLoginCodeRecord record = new GroupsRelationLoginCodeRecord();
  584. record.setUserId(userId);
  585. record.setRelationId(relationId);
  586. record.setAccount(renewalView.getAccount());
  587. record.setGoodsId(renewalView.getGoodsId());
  588. record.setSkuId(renewalView.getSkuId());
  589. groupsRelationLoginCodeRecordMapper.insert(record);
  590. //奈飞同步装置
  591. if (renewalView.getGoodsId() == 1l && loginReq.getLinkType() != null) {
  592. String key = RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getNameFormat(DateUtil.hour(DateTime.now(), true), loginReq.getLinkType(), renewalView.getUserId());
  593. redisService.incr(key, 1L);
  594. }
  595. return code;
  596. }
  597. @Override
  598. public void checkGroupsAvailParkingNum(Long skuId, Long groupsId, Integer availableParkingNum, Integer maxNum) {
  599. //GPT10人月付、4人月付
  600. if (skuId == 161l || skuId == 178l) {
  601. //为0时,不参与限制
  602. if (availableParkingNum == 0) {
  603. return;
  604. }
  605. //目前车队可用停车数
  606. //目前上车人数
  607. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  608. .eq(GroupsRelation::getGroupsId, groupsId)
  609. .ne(GroupsRelation::getUserId, 0)
  610. .le(GroupsRelation::getNum, maxNum));
  611. if (currentParkingNum > availableParkingNum) {
  612. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  613. }
  614. }
  615. }
  616. @Override
  617. public void adjustGroupsParkingTime(Long relationId, GoodsDonSku sku) {
  618. if (sku == null) {
  619. return;
  620. }
  621. Long skuId = sku.getId();
  622. //更新GPT Plus10人、4人月付车队状态 待优化
  623. if (skuId == 161l || skuId == 178l || skuId == 422l || skuId == 423l) {
  624. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  625. Long groupsId = relation.getGroupsId();
  626. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  627. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  628. //为0时 不参与限制
  629. if (availableParkingNum == 0) {
  630. return;
  631. }
  632. Integer extraNum = 5;
  633. if (skuId == 178l || skuId == 423l) {
  634. extraNum = 2;
  635. }
  636. Integer maxNum = sku.getNum() + extraNum;
  637. if (availableParkingNum >= maxNum) {
  638. return;
  639. }
  640. //目前上车人数
  641. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  642. .eq(GroupsRelation::getGroupsId, groupsId)
  643. .ne(GroupsRelation::getUserId, 0)
  644. .le(GroupsRelation::getNum, maxNum));
  645. if (currentParkingNum >= availableParkingNum) {
  646. //锁住
  647. DateTime parkingTime = DateUtil.offsetDay(DateTime.now(), 1);
  648. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  649. .eq(GroupsTrips::getId, groupsTrips.getId())
  650. .set(GroupsTrips::getParkingTime, parkingTime)
  651. .isNull(GroupsTrips::getParkingTime));
  652. }
  653. }
  654. }
  655. @Override
  656. public void setGroupsTripsParkingTimeEmpty(GoodsDonSku sku, Long relationId) {
  657. if (sku == null) {
  658. return;
  659. }
  660. Long skuId = sku.getId();
  661. if (skuId == 161l || skuId == 178l) {
  662. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  663. Long groupsId = relation.getGroupsId();
  664. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  665. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  666. if (groupsTrips.getParkingTime() == null || availableParkingNum == 0) {
  667. return;
  668. }
  669. Integer extraNum = 5;
  670. if (skuId == 178l) {
  671. extraNum = 2;
  672. }
  673. Integer skuNum = sku.getNum();
  674. if (availableParkingNum >= skuNum + extraNum) {
  675. return;
  676. }
  677. //目前上车人数
  678. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  679. .eq(GroupsRelation::getGroupsId, groupsId)
  680. .ne(GroupsRelation::getUserId, 0));
  681. if (currentParkingNum < availableParkingNum) {
  682. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  683. .eq(GroupsTrips::getId, groupsTrips.getId())
  684. .set(GroupsTrips::getParkingTime, null)
  685. .isNotNull(GroupsTrips::getParkingTime));
  686. }
  687. }
  688. }
  689. @Override
  690. public Integer getUserCodeNumBySkuId(Long userId, Long skuId, Boolean isHasVerifyCode) {
  691. //查看双重验证码
  692. UserFuncProperty userFuncProperty = userFuncPropertyMapper.selectOne(Wrappers.lambdaQuery(UserFuncProperty.class).eq(UserFuncProperty::getUserId, userId).last("limit 1"));
  693. //默认2次
  694. int num = 2;
  695. //有安全码查看次数 置为0
  696. if (isHasVerifyCode) {
  697. num = 0;
  698. //存在身份实名认证有两次机会
  699. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  700. Integer selectCount = userCertRecordMapper.selectCount(Wrappers.lambdaQuery(UserCertRecord.class)
  701. .in(UserCertRecord::getUserId, userIdList));
  702. if (selectCount > 0) {
  703. num = 2;
  704. }
  705. return num;
  706. }
  707. //查看双重验证码次数
  708. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  709. if (sku.getCodeNum() > 0) {
  710. num = sku.getCodeNum();
  711. }
  712. if (userFuncProperty != null) num = userFuncProperty.getVerifyCheckNum();
  713. return num;
  714. }
  715. @Override
  716. public List<RenewalView> getHasPayGoods(long userId) {
  717. User user = userMapper.selectById(userId);
  718. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, user);
  719. DateTime now = DateTime.now();
  720. List<RenewalView> list = groupsRelationMapper.getUserHasPayGoods(userIds, now);
  721. return list;
  722. }
  723. @Override
  724. public List<RenewalView> getExpiryRenewalNotify(Long userId) {
  725. DateTime now = DateTime.now();
  726. DateTime thisZero = DateUtil.beginOfDay(now);
  727. String thisDate = thisZero.toDateStr();
  728. Object exists = redisService.get(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId));
  729. if (exists != null) {
  730. return null;
  731. }
  732. User u = userMapper.selectById(userId);
  733. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  734. if (u.getIsBlack()) {
  735. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  736. return null;
  737. }
  738. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  739. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  740. List<RenewalView> list = beanSearcher.searchAll(RenewalView.class, builder
  741. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  742. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  743. .field(RenewalView::getExpiryTime, now).op(Operator.GreaterThan)
  744. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  745. .field(RenewalView::getAqType, 1)
  746. .field(RenewalView::getIsVip, Boolean.TRUE)
  747. .orderBy(RenewalView::getExpiryTime).asc()
  748. .build());
  749. if (list.size() > 5) {
  750. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  751. return null;
  752. }
  753. List<Long> renewReduceSkuIds = userBenefitsMapper.selectList(Wrappers.lambdaQuery(UserBenefits.class)
  754. .eq(UserBenefits::getType, UserBenefits.Type.RENEW).eq(UserBenefits::getStatus, 1).select(UserBenefits::getSkuId)).stream().map(UserBenefits::getSkuId).collect(Collectors.toList());
  755. //提前7天
  756. AtomicInteger day = new AtomicInteger(7);
  757. List<RenewalView> expiryTickets = list.stream().filter(ticket -> {
  758. //下架
  759. if (ticket.getGoodsStatus() == null || ticket.getSkuStatus() == null || !ticket.getGoodsStatus() || !ticket.getSkuStatus()) {
  760. return false;
  761. }
  762. Integer skuMonths = ticket.getMonths();
  763. if (skuMonths == null) {
  764. return false;
  765. }
  766. Date expiryTime = ticket.getExpiryTime();
  767. //年付 提前一个月
  768. if (skuMonths >= 12) {
  769. day.set(30);
  770. } else {
  771. day.set(7);
  772. }
  773. if (DateUtil.beginOfDay(expiryTime).compareTo(DateUtil.offsetDay(thisZero, day.get())) <= 0) {
  774. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  775. //GPT镜像信息
  776. setGptMirrorInfo(ticket);
  777. ticket.setExpiryTime(null);
  778. if (CollUtil.isNotEmpty(renewReduceSkuIds) && renewReduceSkuIds.contains(ticket.getSkuId())) {
  779. ticket.setIsRenewReduce(true);
  780. }
  781. return true;
  782. }
  783. return false;
  784. }).collect(Collectors.toList());
  785. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  786. if (CollUtil.isNotEmpty(expiryTickets)) {
  787. groupsRelationExpiryNotifyRecordMapper.batchInsert(userId, expiryTickets);
  788. }
  789. return expiryTickets;
  790. }
  791. @Override
  792. public void getCollegeStudentUserGptTicket(Long userId) {
  793. Retryer<Boolean> build = RetryerBuilder.<Boolean>newBuilder()
  794. .retryIfException()
  795. //运行时异常重试
  796. .retryIfRuntimeException()
  797. //false重试
  798. .retryIfResult(res -> Objects.equals(res, false))
  799. //1s 间隔
  800. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  801. //停止策略 : 尝试请求3次
  802. .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
  803. try {
  804. build.call(() -> {
  805. //体验规格
  806. Long gptMirrorSkuId = Constant.GPT_MIRROR_SKU_ID;
  807. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(gptMirrorSkuId);
  808. GroupsRelation relation = null;
  809. if (groups != null) {
  810. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  811. }
  812. if (relation == null) {
  813. //生成空车队
  814. GoodsDonSku sku = goodsDonSkuMapper.selectById(gptMirrorSkuId);
  815. relation = groupsFuncService.createNewGroupsTrips(sku);
  816. }
  817. DateTime startTime = DateTime.now();
  818. DateTime expiryTime = DateUtil.offsetDay(startTime, 1);
  819. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  820. .set(GroupsRelation::getUserId, userId)
  821. .set(GroupsRelation::getStartTime, startTime)
  822. .set(GroupsRelation::getExpiryTime, expiryTime)
  823. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  824. .set(GroupsRelation::getAqType, 2)
  825. .eq(GroupsRelation::getId, relation.getId())
  826. .eq(GroupsRelation::getUserId, 0));
  827. if (update > 0) {
  828. groupsMapper.decrAvailableNum(groups.getId());
  829. return true;
  830. }
  831. log.error("发送用户:{} GPT镜像车票体验失败,进行重试", userId);
  832. return false;
  833. });
  834. } catch (ExecutionException | RetryException e) {
  835. log.error("发送用户GPT镜像体验失败:{}", StringUtil.getErrorText(e));
  836. }
  837. }
  838. @Override
  839. public RenewalView getTicketDetail(long userId, Long relationId) {
  840. User u = userMapper.selectById(userId);
  841. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  842. MapBuilder builder = MapUtils.builder();
  843. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, builder
  844. .field(RenewalView::getRelationId, relationId)
  845. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  846. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  847. .field("condition", String.format("(gr.expiry_time is null or gr.expiry_time > '%s')", DateTime.now()))
  848. .field(RenewalView::getStatus, List.of("validity", "outside")).op(Operator.InList)
  849. .orderBy(RenewalView::getExpiryTime).asc()
  850. .onlySelect(RenewalView::getRelationId, RenewalView::getExpiryTime, RenewalView::getTitle, RenewalView::getSpecVal, RenewalView::getGoodsId, RenewalView::getSkuId, RenewalView::getSkuNum, RenewalView::getSkuStatus, RenewalView::getGoodsStatus)
  851. .build());
  852. if (renewalView != null) {
  853. renewalView.setExpiryTimeStr(DateUtil.format(renewalView.getExpiryTime(), "yyyy-MM-dd"));
  854. }
  855. return renewalView;
  856. }
  857. @Override
  858. public GroupsRelation ticketLogin(TicketLoginReq loginReq) {
  859. String account = loginReq.getAccount();
  860. if (StrUtil.isEmpty(account)) {
  861. throw BusinessRuntimeException.getInstance("请输入对应账号");
  862. }
  863. if (loginReq.getMerchants()) {
  864. if (account.contains(Constant.YH_EMAIL_DOMAIN_SUFFIX)) {
  865. SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
  866. .eq(SysEmail::getEmail, account)
  867. .last("limit 1"));
  868. if (sysEmail == null) {
  869. throw BusinessRuntimeException.getInstance("账号错误,请联系客服");
  870. }
  871. }
  872. GroupsRelation relation = new GroupsRelation();
  873. relation.setId(0l);
  874. return relation;
  875. }
  876. String password = loginReq.getPassword();
  877. Integer num = loginReq.getNum();
  878. if (ObjectUtil.hasEmpty(password, num)) {
  879. throw BusinessRuntimeException.getInstance("参数错误");
  880. }
  881. Long goodsId = Optional.ofNullable(loginReq.getGoodsId()).orElse(1l);
  882. GroupsRelation relation = groupsRelationMapper.selectRelationByAccountAndNum(account, password, goodsId, num);
  883. if (relation == null) {
  884. log.info("外部入口使用账号account:{},pwd:{},座位num:{}登录失败...", account, password, num);
  885. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  886. throw BusinessRuntimeException.getInstance("Please enter the correct account information");
  887. }
  888. throw BusinessRuntimeException.getInstance("请输入正确的账号信息");
  889. }
  890. return relation;
  891. }
  892. @Override
  893. public String outsideTicketVerify(TicketLoginReq loginReq) {
  894. String account = loginReq.getAccount();
  895. if (StrUtil.isEmpty(account)) {
  896. throw BusinessRuntimeException.getInstance("账号错误");
  897. }
  898. if (loginReq.getMerchants()) {
  899. if (account.contains(Constant.YH_EMAIL_DOMAIN_SUFFIX)) {
  900. SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
  901. .eq(SysEmail::getEmail, account)
  902. .last("limit 1"));
  903. if (sysEmail == null) {
  904. throw BusinessRuntimeException.getInstance("账号错误,请联系客服");
  905. }
  906. }
  907. loginReq.setGoodsId(1l);
  908. loginReq.setAccountId(0l);
  909. } else {
  910. String password = loginReq.getPassword();
  911. Integer num = loginReq.getNum();
  912. if (ObjectUtil.hasEmpty(password, num)) {
  913. throw BusinessRuntimeException.getInstance("参数错误");
  914. }
  915. Long goodsId = Optional.ofNullable(loginReq.getGoodsId()).orElse(1l);
  916. GroupsRelation relation = groupsRelationMapper.selectRelationByAccountAndNum(account, password, goodsId, num);
  917. if (relation == null) {
  918. log.info("外部入口使用账号account:{},pwd:{},座位num:{}同步验证链接失败...", account, password, num);
  919. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  920. throw BusinessRuntimeException.getInstance("This account is no longer valid");
  921. }
  922. throw BusinessRuntimeException.getInstance("该账号已失效");
  923. }
  924. loginReq.setUserId(relation.getUserId());
  925. loginReq.setRelationId(relation.getId());
  926. loginReq.setGoodsId(goodsId);
  927. }
  928. try {
  929. String aiVerifyCode = getAiVerifyCode(loginReq);
  930. if (StrUtil.isEmpty(aiVerifyCode)) {
  931. throw BusinessRuntimeException.getInstance("");
  932. }
  933. return aiVerifyCode;
  934. } catch (Exception e) {
  935. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  936. throw BusinessRuntimeException.getInstance("Please verify that the link was sent");
  937. }
  938. throw BusinessRuntimeException.getInstance("请校验链接是否已发送");
  939. }
  940. }
  941. @Override
  942. public String getNfHouseholdDevice(long userId, Long relationId) throws Exception {
  943. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  944. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  945. .field(RenewalView::getRelationId, relationId).build());
  946. if (renewalView == null) {
  947. throw BusinessRuntimeException.getInstance("您的车票不存在...");
  948. }
  949. if (StrUtil.isEmpty(renewalView.getAccount())) {
  950. throw BusinessRuntimeException.getInstance("车票未配置账号");
  951. }
  952. String account = renewalView.getAccount();
  953. String password = renewalView.getPassword();
  954. if (StrUtil.hasEmpty(account, password)) {
  955. throw BusinessRuntimeException.getInstance("您的车票账号密码异常,请联系客服...");
  956. }
  957. String code = commonMailService.getTicketMailCode(renewalView.getGoodsId(), account, renewalView.getRelateEmail(), renewalView.getGptEmailPwd(), renewalView.getCreatedTime(), null, 1, true);
  958. return code;
  959. }
  960. @Override
  961. public String getVerifyCode(String account) throws Exception {
  962. Account at = accountMapper.selectOne(Wrappers.lambdaQuery(Account.class)
  963. .eq(Account::getAccount, account)
  964. .eq(Account::getGoodsId, 18));
  965. if (at == null) {
  966. return null;
  967. }
  968. String password = at.getPassword();
  969. if (StrUtil.hasEmpty(account, password)) {
  970. throw BusinessRuntimeException.getInstance("账号异常");
  971. }
  972. String code = commonMailService.getTicketMailCode(at.getGoodsId(), account, at.getRelateEmail(), at.getGptEmailPwd(), at.getCreatedTime(), null, null, false);
  973. return code;
  974. }
  975. @Override
  976. public void changeTicket(long userId, Long relationId) {
  977. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  978. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  979. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  980. .field(RenewalView::getRelationId, relationId)
  981. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  982. .build());
  983. if (renewalView == null) {
  984. throw BusinessRuntimeException.getInstance("车票不存在");
  985. }
  986. if (renewalView.getGoodsId() != 1) {
  987. throw BusinessRuntimeException.getInstance("只针对奈飞车票");
  988. }
  989. AccountNetflixState accountNetflixState = accountNetflixStateMapper.selectOne(Wrappers.lambdaQuery(AccountNetflixState.class)
  990. .eq(AccountNetflixState::getAccount, renewalView.getAccount())
  991. .orderByDesc(AccountNetflixState::getId)
  992. .last("limit 1"));
  993. if (accountNetflixState == null || accountNetflixState.getState() != 3) {
  994. throw BusinessRuntimeException.getInstance("只支持异常账号更换车票");
  995. }
  996. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  997. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  998. throw BusinessRuntimeException.getInstance("正在更换车票中..");
  999. }
  1000. Long groupId = renewalView.getGroupId();
  1001. Long skuId = renewalView.getSkuId();
  1002. Date expiryTime = renewalView.getExpiryTime();
  1003. //随机选择同规格得车票
  1004. Long item_groupsId = groupsMapper.selectRandomGroupsTripsBySkuId(groupId, skuId, expiryTime);
  1005. GroupsRelation newRelation = null;
  1006. if (item_groupsId != null) {
  1007. //存在就随机分配一个,没有就不做处理
  1008. newRelation = changeTickerRelation.changeTicket(renewalView.getUserId(), relationId, item_groupsId, renewalView.getSkuId());
  1009. }
  1010. //若无移至空车队
  1011. if (newRelation == null) {
  1012. newRelation = changeTickerRelation.getEmptyGroupsRelation(renewalView.getUserId(), renewalView.getRelationId(), renewalView.getSkuId());
  1013. }
  1014. if (newRelation == null) {
  1015. throw BusinessRuntimeException.getInstance("更换异常,请重新提交");
  1016. }
  1017. NetflixUserAccountStatusRecord netflixUserAccountStatusRecord = netflixUserAccountStatusRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1018. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1019. .last("limit 1"));
  1020. if (netflixUserAccountStatusRecord != null) {
  1021. netflixUserAccountStatusRecord.setDeleted(false);
  1022. netflixUserAccountStatusRecordMapper.updateById(netflixUserAccountStatusRecord);
  1023. }
  1024. redisService.del(key);
  1025. }
  1026. @Override
  1027. public AccountView getTempAccount(long userId, Long relationId) {
  1028. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1029. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  1030. .field(RenewalView::getRelationId, relationId)
  1031. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1032. .field(RenewalView::getGroupsStatus, GroupsTrips.Status.waiting.name())
  1033. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1034. .build());
  1035. if (renewalView == null) {
  1036. throw BusinessRuntimeException.getInstance("车票不存在");
  1037. }
  1038. AccountView accountView = new AccountView();
  1039. //奈飞超过3帐车票不给看
  1040. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  1041. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1042. .field(RenewalView::getGoodsId, 1)
  1043. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1044. .build());
  1045. if (number.intValue() > 2) {
  1046. return accountView;
  1047. }
  1048. NetflixTempAccountUser netflixTempAccountUser = netflixTempAccountUserMapper.selectOne(Wrappers.lambdaQuery(NetflixTempAccountUser.class)
  1049. .eq(NetflixTempAccountUser::getRelationId, relationId)
  1050. .in(NetflixTempAccountUser::getUserId, userIdList)
  1051. .last("limit 1"));
  1052. Account account;
  1053. if (netflixTempAccountUser == null) {
  1054. account = accountMapper.selectNetflixTempAccount();
  1055. if (account != null) {
  1056. netflixTempAccountUser = new NetflixTempAccountUser();
  1057. netflixTempAccountUser.setAccountId(account.getId());
  1058. netflixTempAccountUser.setRelationId(relationId);
  1059. netflixTempAccountUser.setUserId(renewalView.getUserId());
  1060. netflixTempAccountUserMapper.insert(netflixTempAccountUser);
  1061. }
  1062. } else {
  1063. account = accountMapper.selectById(netflixTempAccountUser.getAccountId());
  1064. }
  1065. if (account != null) {
  1066. accountView.setAccount(account.getAccount());
  1067. accountView.setPassword(account.getPassword());
  1068. }
  1069. return accountView;
  1070. }
  1071. @Override
  1072. public void nfErrorAccountSubmit(long userId, Long relationId) {
  1073. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1074. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  1075. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1076. .field(RenewalView::getRelationId, relationId)
  1077. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan).build());
  1078. if (renewalView == null) {
  1079. throw BusinessRuntimeException.getInstance("车票不存在");
  1080. }
  1081. if (renewalView.getGoodsId() != 1) {
  1082. throw BusinessRuntimeException.getInstance("只支持奈飞车票");
  1083. }
  1084. String account = renewalView.getAccount();
  1085. String password = renewalView.getPassword();
  1086. Integer selectCount = netflixUserAccountStatusRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1087. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1088. .eq(NetflixUserAccountStatusRecord::getUserId, userId)
  1089. .eq(NetflixUserAccountStatusRecord::getAccount, account));
  1090. if (selectCount > 0) {
  1091. throw BusinessRuntimeException.getInstance("该账号正在检测中");
  1092. }
  1093. AccountNetflixState accountNetflixState = accountNetflixStateMapper.selectOne(Wrappers.lambdaQuery(AccountNetflixState.class)
  1094. .eq(AccountNetflixState::getAccount, account)
  1095. .last("limit 1"));
  1096. Integer state = 0;
  1097. if (accountNetflixState != null && accountNetflixState.getState() == 3) {
  1098. state = accountNetflixState.getState();
  1099. }
  1100. NetflixUserAccountStatusRecord netflixUserAccountStatusRecord = new NetflixUserAccountStatusRecord();
  1101. netflixUserAccountStatusRecord.setAccount(account);
  1102. netflixUserAccountStatusRecord.setRelationId(relationId);
  1103. netflixUserAccountStatusRecord.setPassword(password);
  1104. netflixUserAccountStatusRecord.setUserId(renewalView.getUserId());
  1105. netflixUserAccountStatusRecord.setState(state);
  1106. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1107. .eq(OrderDon::getRelationId, renewalView.getRelationId())
  1108. .eq(OrderDon::getUserId, renewalView.getUserId())
  1109. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1110. .orderByDesc(OrderDon::getId)
  1111. .last("limit 1"));
  1112. if (orderDon != null) {
  1113. netflixUserAccountStatusRecord.setOrderId(orderDon.getId());
  1114. }
  1115. netflixUserAccountStatusRecordMapper.insert(netflixUserAccountStatusRecord);
  1116. }
  1117. @Override
  1118. public Integer getNetflixErrorAccountStatus(long userId, Long relationId) {
  1119. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1120. NetflixUserAccountStatusRecord netflixUseAccountStatusRecord = netflixUserAccountStatusRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1121. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1122. .eq(NetflixUserAccountStatusRecord::getDeleted, 1)
  1123. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1124. .last("limit 1"));
  1125. if (netflixUseAccountStatusRecord == null) {
  1126. throw BusinessRuntimeException.getInstance("未有提交记录");
  1127. }
  1128. Integer state = netflixUseAccountStatusRecord.getState();
  1129. //2是登录失败 3是被封号
  1130. if (state == 3) {
  1131. if (netflixUseAccountStatusRecord.getCreatedTime().compareTo(DateUtil.offsetMinute(DateTime.now(), -10)) > 0) {
  1132. state = 0;
  1133. }
  1134. }
  1135. //登录失败不算异常
  1136. if (state == 2) {
  1137. state = 1;
  1138. }
  1139. return state;
  1140. }
  1141. @Override
  1142. public List<NetflixUserAccountStatusRecord> getUserNetflixSubmitRecord(long userId) {
  1143. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1144. List<NetflixUserAccountStatusRecord> netflixUseAccountStatusRecords = netflixUserAccountStatusRecordMapper.selectList(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1145. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1146. .eq(NetflixUserAccountStatusRecord::getDeleted, 1)
  1147. .select(NetflixUserAccountStatusRecord::getOrderId, NetflixUserAccountStatusRecord::getRelationId, NetflixUserAccountStatusRecord::getState, NetflixUserAccountStatusRecord::getCreatedTime));
  1148. return netflixUseAccountStatusRecords;
  1149. }
  1150. @Override
  1151. public Long getTrialTicketByUserIdAndGoodsId(Long userId, Long trialSkuId, Integer ticketType) {
  1152. Retryer<Long> build = RetryerBuilder.<Long>newBuilder()
  1153. .retryIfException()
  1154. //运行时异常重试
  1155. .retryIfRuntimeException()
  1156. //false重试
  1157. .retryIfResult(res -> res == null)
  1158. //1s 间隔
  1159. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  1160. //停止策略 : 尝试请求3次
  1161. .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
  1162. try {
  1163. return build.call(() -> {
  1164. //体验规格
  1165. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(trialSkuId);
  1166. GroupsRelation relation = null;
  1167. if (groups != null) {
  1168. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  1169. }
  1170. if (relation == null) {
  1171. //生成空车队
  1172. GoodsDonSku sku = goodsDonSkuMapper.selectById(trialSkuId);
  1173. relation = groupsFuncService.createNewGroupsTrips(sku);
  1174. }
  1175. DateTime startTime = DateTime.now();
  1176. DateTime expiryTime = DateUtil.offsetDay(startTime, 1);
  1177. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1178. .set(GroupsRelation::getUserId, userId)
  1179. .set(GroupsRelation::getStartTime, startTime)
  1180. .set(GroupsRelation::getExpiryTime, expiryTime)
  1181. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  1182. .set(GroupsRelation::getAqType, ticketType)
  1183. .eq(GroupsRelation::getId, relation.getId())
  1184. .eq(GroupsRelation::getUserId, 0));
  1185. if (update > 0) {
  1186. groupsMapper.decrAvailableNum(groups.getId());
  1187. return relation.getId();
  1188. }
  1189. log.error("发送用户:{} GPT镜像车票体验失败,进行重试", userId);
  1190. return null;
  1191. });
  1192. } catch (ExecutionException | RetryException e) {
  1193. log.error("发送用户GPT镜像体验失败:{}", StringUtil.getErrorText(e));
  1194. return null;
  1195. }
  1196. }
  1197. @Override
  1198. public Boolean getMirrorPopups(long userId) {
  1199. //是否弹窗 默认否
  1200. Boolean flag = false;
  1201. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1202. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  1203. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1204. .field(RenewalView::getStatus, GroupsRelation.Status.validity.name())
  1205. .field(RenewalView::getIsMirror, true)
  1206. .build());
  1207. if (number.intValue() == 0) {
  1208. flag = true;
  1209. }
  1210. if (!flag) {
  1211. String thisWeekBegin = DateUtil.beginOfWeek(DateTime.now()).toDateStr();
  1212. Integer selectCount = mirrorTicketPopupsRecordMapper.selectCount(Wrappers.lambdaQuery(MirrorTicketPopupsRecord.class)
  1213. .in(MirrorTicketPopupsRecord::getUserId, userIdList)
  1214. .eq(MirrorTicketPopupsRecord::getThisWeek, thisWeekBegin));
  1215. if (selectCount == 0) {
  1216. MirrorTicketPopupsRecord mirrorTicketPopupsRecord = new MirrorTicketPopupsRecord();
  1217. mirrorTicketPopupsRecord.setThisWeek(thisWeekBegin);
  1218. mirrorTicketPopupsRecord.setUserId(userId);
  1219. mirrorTicketPopupsRecordMapper.insert(mirrorTicketPopupsRecord);
  1220. } else {
  1221. flag = true;
  1222. }
  1223. }
  1224. return flag;
  1225. }
  1226. @Override
  1227. public Long getTicket(Long userId, Long skuId, Boolean isVip) {
  1228. Retryer<Long> build = RetryerBuilder.<Long>newBuilder()
  1229. .retryIfException()
  1230. //运行时异常重试
  1231. .retryIfRuntimeException()
  1232. //false重试
  1233. .retryIfResult(res -> res == null)
  1234. //1s 间隔
  1235. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  1236. //停止策略 : 尝试请求1次
  1237. .withStopStrategy(StopStrategies.stopAfterAttempt(1)).build();
  1238. try {
  1239. return build.call(() -> {
  1240. //体验规格
  1241. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(skuId);
  1242. GroupsRelation relation = null;
  1243. if (groups != null) {
  1244. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  1245. }
  1246. //生成空车队
  1247. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1248. if (relation == null) {
  1249. relation = groupsFuncService.createNewGroupsTrips(sku);
  1250. }
  1251. DateTime startTime = DateTime.now();
  1252. DateTime expiryTime;
  1253. if (sku.getDays() != null) {
  1254. expiryTime = DateUtil.offsetDay(startTime, sku.getDays());
  1255. } else {
  1256. expiryTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  1257. }
  1258. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1259. .set(GroupsRelation::getUserId, userId)
  1260. .set(GroupsRelation::getStartTime, startTime)
  1261. .set(GroupsRelation::getExpiryTime, expiryTime)
  1262. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  1263. .set(GroupsRelation::getIsVip, isVip)
  1264. .eq(GroupsRelation::getId, relation.getId())
  1265. .eq(GroupsRelation::getUserId, 0));
  1266. if (update > 0) {
  1267. groupsMapper.decrAvailableNum(groups.getId());
  1268. return relation.getId();
  1269. }
  1270. log.error("发送用户:{} GPT镜像车票失败,进行重试", userId);
  1271. return null;
  1272. });
  1273. } catch (ExecutionException | RetryException e) {
  1274. log.error("发送用户GPT镜像失败:{}", StringUtil.getErrorText(e));
  1275. return null;
  1276. }
  1277. }
  1278. @Override
  1279. public Boolean getVipMirrorTicketIfEmpty(long userId, Long skuId) {
  1280. Integer selectCount = vipGoodsSkuMapper.selectCount(Wrappers.lambdaQuery(VipGoodsSku.class)
  1281. .eq(VipGoodsSku::getSkuId, skuId));
  1282. if (selectCount == 0) {
  1283. return false;
  1284. }
  1285. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1286. VipUser vipUser = vipUserMapper.selectOne(Wrappers.lambdaQuery(VipUser.class)
  1287. .in(VipUser::getUserId, userIdList)
  1288. .gt(VipUser::getExpiryTime, DateTime.now())
  1289. .last("limit 1"));
  1290. //不是会员 或已到期
  1291. if (vipUser == null) {
  1292. return false;
  1293. }
  1294. Number number = beanSearcher.searchCount(GroupsRelationView.class, MapUtils.builder()
  1295. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  1296. .field(GroupsRelationView::getSkuId, skuId)
  1297. .field(GroupsRelationView::getIsVip, Boolean.TRUE)
  1298. .build());
  1299. if (number.intValue() == 0) {
  1300. Long relationId = getTicket(vipUser.getUserId(), skuId, Boolean.TRUE);
  1301. //同步时间
  1302. groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1303. .set(GroupsRelation::getExpiryTime, vipUser.getExpiryTime())
  1304. .eq(GroupsRelation::getUserId, vipUser.getUserId())
  1305. .eq(GroupsRelation::getId, relationId));
  1306. return true;
  1307. }
  1308. return false;
  1309. }
  1310. private DistributePosterGoodsDetailView setGoodsPoster(RenewalView ticket, User user, List<Long> userIds) {
  1311. DistributePosterGoodsDetailView distributePosterGoodsDetailView = beanSearcher.searchFirst(DistributePosterGoodsDetailView.class, MapUtils.flatBuilder(request.getParameterMap())
  1312. .field(DistributePosterGoodsFrontView::getGoodsId, ticket.getGoodsId()).build());
  1313. if (distributePosterGoodsDetailView == null) {
  1314. return null;
  1315. }
  1316. distributePosterGoodsDetailView.setNickname(user.getNickname());
  1317. UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
  1318. .eq(UserDistribute::getUserId, user.getId())
  1319. .eq(UserDistribute::getDeleted, 1)
  1320. .last("limit 1"));
  1321. if (userDistribute != null) {
  1322. UserPlatDistributeRate userPlatDistributeRate = userPlatDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatDistributeRate.class)
  1323. .eq(UserPlatDistributeRate::getDistributeId, userDistribute.getId())
  1324. .eq(UserPlatDistributeRate::getGoodsId, ticket.getGoodsId())
  1325. .last("limit 1"));
  1326. if (userPlatDistributeRate != null) {
  1327. distributePosterGoodsDetailView.setRate(userPlatDistributeRate.getRate());
  1328. }
  1329. }
  1330. GoodsDon goodsDon = goodsDonMapper.selectById(ticket.getGoodsId());
  1331. if (goodsDon.getIsSkuDistribute()) {
  1332. if (userDistribute != null) {
  1333. UserPlatSkuDistributeRate userPlatSkuDistributeRate = userPlatSkuDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatSkuDistributeRate.class)
  1334. .eq(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId())
  1335. .eq(UserPlatSkuDistributeRate::getSkuId, ticket.getSkuId())
  1336. .last("limit 1"));
  1337. if (userPlatSkuDistributeRate != null) {
  1338. distributePosterGoodsDetailView.setRate(userPlatSkuDistributeRate.getRate());
  1339. }
  1340. } else {
  1341. DistributeGeneralSkuRate distributeGeneralSkuRate = distributeGeneralSkuRateMapper.selectOne(Wrappers.lambdaQuery(DistributeGeneralSkuRate.class)
  1342. .eq(DistributeGeneralSkuRate::getSkuId, ticket.getSkuId())
  1343. .last("limit 1"));
  1344. if (distributeGeneralSkuRate != null) {
  1345. distributePosterGoodsDetailView.setRate(distributeGeneralSkuRate.getRate());
  1346. }
  1347. }
  1348. }
  1349. //用户推广海报记录id
  1350. Optional.ofNullable(userDistributePosterRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributePosterRecord.class)
  1351. .eq(UserDistributePosterRecord::getPosterId, distributePosterGoodsDetailView.getId())
  1352. .in(UserDistributePosterRecord::getUserId, userIds)
  1353. .last("limit 1"))).ifPresent(re -> distributePosterGoodsDetailView.setRid(re.getId()));
  1354. return distributePosterGoodsDetailView;
  1355. }
  1356. private void setRenewDiscount(RenewalView ticket) {
  1357. //镜像或者独立规格
  1358. if (ticket.getIsMirror() || (ticket.getSkuNum() != null && ticket.getSkuNum() == 1)) {
  1359. RenewUpgradePackage renewUpgradePackage = renewUpgradePackageMapper.selectOne(Wrappers.lambdaQuery(RenewUpgradePackage.class)
  1360. .eq(RenewUpgradePackage::getGoodsId, ticket.getGoodsId())
  1361. .eq(RenewUpgradePackage::getStatus, 1)
  1362. .eq(RenewUpgradePackage::getDeleted, 1)
  1363. .eq(RenewUpgradePackage::getSkuId, ticket.getSkuId())
  1364. .orderByAsc(RenewUpgradePackage::getDiscount)
  1365. .last("limit 1")
  1366. .select(RenewUpgradePackage::getId, RenewUpgradePackage::getDiscount));
  1367. if (renewUpgradePackage != null) {
  1368. ticket.setDiscount(renewUpgradePackage.getDiscount());
  1369. }
  1370. }
  1371. }
  1372. private void setMirrorTicketInfo(RenewalView ticket) {
  1373. //设置MJ镜像信息
  1374. setMjMirrorInfo(ticket);
  1375. //设置GPT镜像信息
  1376. setGptMirrorInfo(ticket);
  1377. //clause pro
  1378. setClaudeProInfo(ticket);
  1379. //luma
  1380. setLumaInfo(ticket);
  1381. }
  1382. private void setMjMirrorInfo(RenewalView ticket) {
  1383. if (ticket.getGoodsId() == 26 && ticket.getIsMirror()) {
  1384. 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));
  1385. if (CollectionUtil.isNotEmpty(upgradePackages)) {
  1386. upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(ticket::setMjPackagePrice);
  1387. }
  1388. try {
  1389. MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  1390. .field(MidjourneyUserView::getUserId, ticket.getUserId()).field(MidjourneyUserView::getRelationId, ticket.getRelationId())
  1391. .onlySelect(MidjourneyUserView::getMjUserRelaxNum, MidjourneyUserView::getMjUserFastNum, MidjourneyUserView::getIsCar)
  1392. .build());
  1393. if (search == null) {
  1394. MidjourneyUser midjourneyUser = midjourneyAccountService.getMidjourneyUserToken(ticket.getUserId(), ticket.getRelationId());
  1395. ticket.setMjUserFastNum(midjourneyUser.getMjFastNum());
  1396. ticket.setMjUserRelaxNum(midjourneyUser.getMjRelaxNum());
  1397. ticket.setIsCar(false);
  1398. } else {
  1399. ticket.setIsCar(search.getIsCar());
  1400. ticket.setMjUserFastNum(search.getMjUserFastNum());
  1401. ticket.setMjUserRelaxNum(search.getMjUserRelaxNum());
  1402. }
  1403. } catch (Exception e) {
  1404. }
  1405. }
  1406. }
  1407. public void setGptMirrorInfo(RenewalView ticket) {
  1408. if (ticket.getGoodsId() == 18 && ticket.getIsCar() && ticket.getExpiryTime() != null) {
  1409. try {
  1410. //gpt用户镜像
  1411. ChatGptUserView userInfo = chatGptAccountService.getUserInfo(ticket.getUserId(), ticket.getRelationId());
  1412. ticket.setGptUserLimitNum(userInfo.getLimitNum());
  1413. ticket.setGptUserLimitTime(userInfo.getLimitTime());
  1414. ticket.setUserDsLimitNum(userInfo.getDsLimitNum());
  1415. ticket.setUserDsLimitTime(userInfo.getDsLimitTime());
  1416. ticket.setUserOtherLimitNum(userInfo.getOtherLimitNum());
  1417. ticket.setUserOtherLimitTime(userInfo.getOtherLimitTime());
  1418. ticket.setUse(userInfo.getUse());
  1419. ticket.setModel(userInfo.getModel());
  1420. Integer count = upgradePackageMapper.selectCount(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + ticket.getSkuId() + "\"')")
  1421. .gt(UpgradePackage::getNum, userInfo.getLimitNum())
  1422. .eq(UpgradePackage::getStatus, Boolean.TRUE)
  1423. .eq(UpgradePackage::getGptType, 0)
  1424. .eq(UpgradePackage::getDeleted, Boolean.TRUE));
  1425. ticket.setUpgrade(count > 0 ? true : false);
  1426. ticket.setPackageId(userInfo.getPackageId());
  1427. if (userInfo.getPackageId() != 0) {
  1428. UpgradePackage upgradePackage = upgradePackageMapper.selectById(userInfo.getPackageId());
  1429. ticket.setPackagePrice(upgradePackage.getPrice());
  1430. Long upgradeOrderDonSkuId = upgradePackage.getUpgradeSkuId();
  1431. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, upgradeOrderDonSkuId).build());
  1432. renewSku.setPackageId(userInfo.getPackageId());
  1433. ticket.setRenewSku(renewSku);
  1434. }
  1435. ticket.setIsRenewPackage(userInfo.getIsRenewPackage());
  1436. Long renewSkuId = userInfo.getRenewSkuId();
  1437. if (renewSkuId != null) {
  1438. GoodsDonSkuRenewView upgradeSkuRenewView = ticket.getRenewSku();
  1439. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  1440. //续费升级是更高级规格
  1441. if (upgradeSkuRenewView == null || (renewSku.getGptUserLimitNum() >= upgradeSkuRenewView.getGptUserLimitNum() && renewSku.getMonths() >= userInfo.getMonths())) {
  1442. Optional.ofNullable(orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  1443. .eq(OrderDonRenewRecord::getOrderId, userInfo.getRenewOrderId())
  1444. .last("limit 1"))).ifPresent(e -> renewSku.setOriginalOrderId(e.getOrderId()));
  1445. ticket.setRenewSku(renewSku);
  1446. }
  1447. }
  1448. } catch (Exception e) {
  1449. }
  1450. }
  1451. }
  1452. public void setClaudeProInfo(RenewalView ticket) {
  1453. //clause pro
  1454. if (ticket.getGoodsId() == 75l && ticket.getExpiryTime() != null) {
  1455. try {
  1456. ClaudeUserView userInfo = claudeService.getUserInfo(ticket.getUserId(), ticket.getRelationId());
  1457. ticket.setGptUserLimitNum(userInfo.getLimitNum());
  1458. ticket.setGptUserLimitTime(userInfo.getLimitTime());
  1459. ticket.setUse(userInfo.getUse());
  1460. Long renewSkuId = userInfo.getRenewSkuId();
  1461. if (renewSkuId != null) {
  1462. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  1463. ticket.setRenewSku(renewSku);
  1464. }
  1465. } catch (Exception e) {
  1466. }
  1467. }
  1468. }
  1469. public void setLumaInfo(RenewalView ticket) {
  1470. if (ticket.getGoodsId() == Constant.LUMA_GOODS_ID && ticket.getExpiryTime() != null) {
  1471. try {
  1472. 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));
  1473. if (CollectionUtil.isNotEmpty(upgradePackages)){
  1474. upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(ticket::setLumaPackagePrice);
  1475. }
  1476. LumaUser lumaUser = lumaService.getLumaUser(ticket.getUserId(), ticket.getRelationId());
  1477. ticket.setLumaUserNum(lumaUser.getNum());
  1478. } catch (Exception e) {
  1479. }
  1480. }
  1481. }
  1482. /**
  1483. * 获取gpt镜像天卡活动参与平台ids
  1484. * @return
  1485. */
  1486. private List<Long> getGptMirrorGiveawayBuyGids() {
  1487. GptMirrorDayCardGiveawayActivity gptMirrorDayCardGiveawayActivity = beanSearcher.searchFirst(GptMirrorDayCardGiveawayActivity.class, MapUtils.builder().build());
  1488. if (gptMirrorDayCardGiveawayActivity != null) {
  1489. String buyGoodsIds = gptMirrorDayCardGiveawayActivity.getBuyGoodsIds();
  1490. try {
  1491. return Jsons.parseList(buyGoodsIds, Long.class);
  1492. } catch (Exception e) {
  1493. }
  1494. }
  1495. return null;
  1496. }
  1497. }