GroupRelationFrontServiceImpl.java 69 KB

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