GroupRelationFrontServiceImpl.java 83 KB

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