GroupRelationFrontServiceImpl.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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.StrUtil;
  10. import cn.hutool.http.HttpRequest;
  11. import cn.hutool.http.HttpStatus;
  12. import cn.hutool.http.HttpUtil;
  13. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  14. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  15. import com.cyksj.common.constant.Constant;
  16. import com.cyksj.common.exception.BusinessRuntimeException;
  17. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  18. import com.cyksj.common.util.Jsons;
  19. import com.cyksj.common.util.StringUtil;
  20. import com.cyksj.common.util.TicketCodeCommonUtil;
  21. import com.cyksj.enums.GatewayApiCode;
  22. import com.cyksj.mapper.*;
  23. import com.cyksj.mapper.sys.SysEmailMapper;
  24. import com.cyksj.model.entity.*;
  25. import com.cyksj.model.request.SpecialGoodsTicketReq;
  26. import com.cyksj.model.views.*;
  27. import com.cyksj.redis.RedisService;
  28. import com.cyksj.service.chatgpt.ChatGptAccountService;
  29. import com.cyksj.service.chatgpt.ChatGptAuthService;
  30. import com.cyksj.service.groups.GroupsFuncService;
  31. import com.cyksj.service.mail.CuiQiuMailService;
  32. import com.cyksj.service.mail.MailService;
  33. import com.cyksj.service.mange.coupon.CouponCommonService;
  34. import com.cyksj.service.midjourney.MidjourneyAccountService;
  35. import com.cyksj.service.relation.GroupRelationFrontService;
  36. import com.cyksj.service.relation.GroupsRelationNetflixService;
  37. import com.cyksj.service.user.UserBindRelationService;
  38. import com.cyksj.service.user.UserLoginRecordService;
  39. import com.ejlchina.searcher.BeanSearcher;
  40. import com.ejlchina.searcher.SearchResult;
  41. import com.ejlchina.searcher.param.Operator;
  42. import com.ejlchina.searcher.util.MapBuilder;
  43. import com.ejlchina.searcher.util.MapUtils;
  44. import com.github.rholder.retry.*;
  45. import lombok.RequiredArgsConstructor;
  46. import lombok.extern.slf4j.Slf4j;
  47. import org.springframework.stereotype.Service;
  48. import org.springframework.transaction.annotation.Transactional;
  49. import javax.servlet.http.HttpServletRequest;
  50. import java.math.BigDecimal;
  51. import java.math.RoundingMode;
  52. import java.util.*;
  53. import java.util.concurrent.ExecutionException;
  54. import java.util.concurrent.TimeUnit;
  55. import java.util.concurrent.atomic.AtomicInteger;
  56. import java.util.stream.Collectors;
  57. import static com.cyksj.enums.GatewayApiCode.GROUP_INDEX_ALREADY_BE_USER;
  58. import static com.cyksj.enums.GatewayApiCode.GROUP_INDEX_NOT_FIND;
  59. /*
  60. *项目名: netflix
  61. *文件名: GroupRelationFrontServiceImpl
  62. *创建者: JavaZou
  63. *创建时间:2022/12/29 15:42
  64. */
  65. @Service
  66. @RequiredArgsConstructor
  67. @Slf4j
  68. public class GroupRelationFrontServiceImpl implements GroupRelationFrontService {
  69. private final UserBindRelationService userBindRelationService;
  70. private final UserMapper userMapper;
  71. private final BeanSearcher beanSearcher;
  72. private final CouponCommonService couponCommonService;
  73. private final GroupsRelationMapper groupsRelationMapper;
  74. private final GroupsMapper groupsMapper;
  75. private final ChatGptAuthService chatGptAuthService;
  76. private final RedisService redisService;
  77. private final MailService mailService;
  78. private final OrderDonMapper orderDonMapper;
  79. private final GroupsRelationExpiryNotifyRecordMapper groupsRelationExpiryNotifyRecordMapper;
  80. private final HttpServletRequest request;
  81. private final GroupsFuncService groupsFuncService;
  82. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  83. private final GroupsRelationLoginCodeRecordMapper groupsRelationLoginCodeRecordMapper;
  84. private final SysEmailMapper sysEmailMapper;
  85. private final GoodsDonSkuMapper goodsDonSkuMapper;
  86. private final UserFuncPropertyMapper userFuncPropertyMapper;
  87. private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
  88. private final UserLoginRecordService userLoginRecordService;
  89. private final CuiQiuMailService cuiQiuMailService;
  90. private final UserCertRecordMapper userCertRecordMapper;
  91. private final MidjourneyAccountService midjourneyAccountService;
  92. private final ChatGptAccountService chatGptAccountService;
  93. //脆球邮箱后缀
  94. private final static String CUI_QIU_EMAIL_SUFFIX = "@kindvd.com";
  95. private final UpgradePackageMapper upgradePackageMapper;
  96. private final GoodsDonQaRelateMapper goodsDonQaRelateMapper;
  97. private final GroupsRelationNetflixService groupsRelationNetflixService;
  98. @Override
  99. public SearchResult<RenewalView> getMyTicket(long userId, Boolean isLoginPopularize, String customId, String account) {
  100. User u = userMapper.selectById(userId);
  101. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  102. if (u.getIsBlack()) {
  103. return new SearchResult<>();
  104. }
  105. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  106. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  107. //Long yhsId = yhShopFrontService.getYhsIdByCustomId(customId);
  108. DateTime now = DateTime.now();
  109. if (StrUtil.isNotBlank(account)) {
  110. builder.field(RenewalView::getAccount, account).op(Operator.Contain);
  111. }
  112. SearchResult<RenewalView> list = beanSearcher.search(RenewalView.class, builder
  113. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  114. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  115. //.field(RenewalView::getYhsId, yhsId)
  116. .put("condition", String.format("(gr.expiry_time is null or gr.expiry_time > '%s')", now))
  117. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  118. .orderBy(RenewalView::getExpiryTime).asc()
  119. .build());
  120. //过滤邀请制、已失效的车位
  121. Integer size = list.getTotalCount().intValue();
  122. list.getDataList().forEach(ticket -> {
  123. if (ticket.getSkuId() == null || ticket.getGoodsId() == null) {
  124. return;
  125. }
  126. if (ticket.getGoodsId() == 18 && ticket.getSkuNum() > 1) {
  127. ticket.setPassword(null);
  128. }
  129. ticket.setIsMulti(false);
  130. if (ticket.getSkuNum() > 1) {
  131. ticket.setIsMulti(true);
  132. }
  133. //chatGPT直连
  134. if (ticket.getGoodsId().equals(42l)) {
  135. if (StrUtil.isNotBlank(ticket.getAccount())) {
  136. String accessToken;
  137. try {
  138. accessToken = chatGptAuthService.getAccessToken(ticket.getAccount());
  139. ticket.setGptRefreshToken(accessToken);
  140. } catch (Exception e) {
  141. redisService.set(RedisService.key.CHAT_GPT_TOKEN_EXCEPTION_KEY.getName() + ticket.getAccount(), ticket.getAccount());
  142. }
  143. }
  144. ticket.setAccount(null);
  145. ticket.setPassword(null);
  146. } else {
  147. ticket.setGptRefreshToken(null);
  148. }
  149. if (ticket.getSecondType() == 1) {
  150. ticket.setAccount(null);
  151. ticket.setPassword(null);
  152. }
  153. if (isLoginPopularize != null && isLoginPopularize) {
  154. GoodsDonViews views = beanSearcher.searchFirst(GoodsDonViews.class, MapUtils.builder().field(GoodsDonViews::getId, ticket.getGoodsId()).build());
  155. views.setSpecs(beanSearcher.searchFirst(GoodsDonSpecFrontView.class, MapUtils.builder().field(GoodsDonSpecFrontView::getGoodsId, views.getId()).build()));
  156. views.setSkuList(beanSearcher.searchAll(GoodsDonSkuFrontView.class, MapUtils.builder().field(GoodsDonSkuFrontView::getGoodsId, views.getId()).field(GoodsDonSkuFrontView::getStatus, true).build()));
  157. ticket.setGoodsDonViews(views);
  158. }
  159. if (ticket.getMonths() != null && ticket.getMonths() >= 300) {
  160. ticket.setExpiryTime(null);
  161. }
  162. if (ticket.getExpiryTime() != null && ticket.getGoodsType() == 1 && ticket.getSecondType() == 2) {
  163. String remainDays = DateUtil.formatBetween(now, ticket.getExpiryTime(), BetweenFormater.Level.DAY);
  164. if ("0天".equals(remainDays)) {
  165. remainDays = "小于1天";
  166. } else {
  167. //当天也算
  168. int days = Integer.parseInt(remainDays.substring(0, remainDays.indexOf("天")));
  169. remainDays = days + 1 + "天";
  170. }
  171. ticket.setRemainDays(remainDays);
  172. }
  173. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  174. .eq(OrderDon::getRelationId, ticket.getRelationId())
  175. .eq(OrderDon::getUserId, ticket.getUserId())
  176. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  177. .orderByDesc(OrderDon::getId)
  178. .last("limit 1"));
  179. if (orderDon != null) {
  180. ticket.setOrderNo(orderDon.getOrderNo());
  181. ticket.setOrderId(orderDon.getId());
  182. ticket.setTransactionId(orderDon.getTransactionId());
  183. }
  184. if (size > 1 && ticket.getGoodsId() != 18) {
  185. Date payTime = null;
  186. if (orderDon != null) {
  187. payTime = Optional.ofNullable(orderDon.getPayTime()).orElse(orderDon.getCreatedTime());
  188. }
  189. //加购订单
  190. if (orderDon == null) {
  191. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(ticket.getRelationId(), ticket.getUserId());
  192. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  193. String relationIds = data.getRelationIds();
  194. if (StrUtil.isEmpty(relationIds)) {
  195. return;
  196. }
  197. try {
  198. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  199. if (relationList.contains(ticket.getRelationId())) {
  200. OrderDon plusOrder = orderDonMapper.selectById(data.getOrderId());
  201. if (plusOrder != null) {
  202. payTime = Optional.ofNullable(plusOrder.getPayTime()).orElse(plusOrder.getCreatedTime());
  203. }
  204. break;
  205. }
  206. } catch (Exception e) {
  207. }
  208. }
  209. }
  210. ticket.setPayTime(payTime);
  211. }
  212. if (ticket.getGoodsId() == 26 && ticket.getIsMirror()){
  213. 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));
  214. if (CollectionUtil.isNotEmpty(upgradePackages)){
  215. upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(ticket::setMjPackagePrice);
  216. }
  217. try {
  218. MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  219. .field(MidjourneyUserView::getUserId, ticket.getUserId()).field(MidjourneyUserView::getRelationId, ticket.getRelationId())
  220. .onlySelect(MidjourneyUserView::getMjFastNum, MidjourneyUserView::getMjRelaxNum)
  221. .build());
  222. if (search == null) {
  223. MidjourneyUser midjourneyUser = midjourneyAccountService.getMidjourneyUserToken(ticket.getUserId(), ticket.getRelationId());
  224. ticket.setMjUserFastNum(midjourneyUser.getMjFastNum());
  225. ticket.setMjUserRelaxNum(midjourneyUser.getMjRelaxNum());
  226. } else {
  227. ticket.setMjUserFastNum(search.getMjFastNum());
  228. ticket.setMjUserRelaxNum(search.getMjRelaxNum());
  229. }
  230. } catch (Exception e) {
  231. }
  232. }
  233. if (ticket.getGoodsId() == 18 && ticket.getIsCar() && ticket.getExpiryTime() != null) {
  234. //gpt用户镜像
  235. ChatGptUserView userInfo = chatGptAccountService.getUserInfo(userId, ticket.getRelationId());
  236. ticket.setGptUserLimitNum(userInfo.getLimitNum());
  237. ticket.setGptUserLimitTime(userInfo.getLimitTime());
  238. ticket.setUse(userInfo.getUse());
  239. Integer count = upgradePackageMapper.selectCount(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + ticket.getSkuId() + "\"')")
  240. .gt(UpgradePackage::getNum, userInfo.getLimitNum())
  241. .eq(UpgradePackage::getStatus, Boolean.TRUE)
  242. .eq(UpgradePackage::getGptType, 0)
  243. .eq(UpgradePackage::getDeleted, Boolean.TRUE));
  244. ticket.setUpgrade(count > 0 ? true : false);
  245. ticket.setPackageId(userInfo.getPackageId());
  246. if (userInfo.getPackageId() != 0) {
  247. UpgradePackage upgradePackage = upgradePackageMapper.selectById(userInfo.getPackageId());
  248. ticket.setPackagePrice(upgradePackage.getPrice());
  249. }
  250. }
  251. List<GroupsRelationUserView> relationUserViews = groupsRelationMapper.getUserRelationUserViews(ticket.getGroupId(), ticket.getRelationId(), ticket.getUserId(), List.of(GroupsRelation.Status.validity, GroupsRelation.Status.outside));
  252. ticket.setRelationViews(relationUserViews);
  253. if (ticket.getExpiryTime() != null) {
  254. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  255. }
  256. //查看双重验证码
  257. if (StrUtil.isNotEmpty(ticket.getApiSecret())) {
  258. Boolean isHasVerifyCode = StrUtil.isNotBlank(ticket.getVerifyCode()) ? true : false;
  259. Integer codeNum = getUserCodeNumBySkuId(ticket.getUserId(), ticket.getSkuId(), isHasVerifyCode);
  260. ticket.setCodeNum(codeNum);
  261. }
  262. Long qaId = groupsRelationMapper.selectGoodsDonQaByGoodsId(ticket.getGoodsId());
  263. ticket.setQa(qaId > 0 ? true : false);
  264. });
  265. userLoginRecordService.saveUserLoginDayRecord(userId);
  266. return list;
  267. }
  268. @Override
  269. public Boolean isJoinCorpWx(Long userId, Boolean isJoin, Boolean noCoupon) {
  270. if (!isJoin) {
  271. User user = userMapper.selectById(userId);
  272. if (user == null || StrUtil.isEmpty(user.getUnionid())) {
  273. return true;
  274. }
  275. // CorpUser corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class)
  276. // .ne(CorpUser::getUnionid, "")
  277. // .eq(CorpUser::getUnionid, user.getUnionid())
  278. // .last("limit 1")
  279. // .select(CorpUser::getId)
  280. // );
  281. CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
  282. .field(CorpUserFollowView::getUnionId, user.getUnionid())
  283. .field(CorpUserFollowView::getStatus, 1).build());
  284. if (corpUserFollowView == null) {
  285. return false;
  286. }
  287. }
  288. //用户是否买了奈飞车票
  289. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  290. .field(RenewalView::getUserId, userId)
  291. .field(RenewalView::getGoodsId, 1)
  292. .field(RenewalView::getStatus, List.of("validity", "overdue")).op(Operator.InList)
  293. .build());
  294. if (number.intValue() > 0 && !noCoupon) {
  295. couponCommonService.sendCouponToUser(userId, 34l, 0l, 0l, 0l, CouponUser.Channel.wxCorp);
  296. }
  297. return true;
  298. }
  299. @Override
  300. public GroupsRelation getSimilarExpiredGroupRelation(GoodsDonSku sku, List<Long> errorsRelationIds, String ip) {
  301. Long skuId = sku.getId();
  302. Integer days = sku.getDays();
  303. Integer months = sku.getMonths();
  304. Integer maxNum = sku.getNum();
  305. DateTime expiryTime = null;
  306. if (days != null && days > 0) {
  307. expiryTime = DateUtil.offsetDay(DateTime.now(), days);
  308. } else {
  309. expiryTime = DateUtil.offsetMonth(DateTime.now(), months);
  310. }
  311. Integer extraNum = 5;
  312. if (sku.getId() == 178l) {
  313. extraNum = 2;
  314. }
  315. maxNum += extraNum;
  316. DateTime minExpiryTime = DateUtil.offsetDay(expiryTime, -5);
  317. Long groupsId = groupsRelationMapper.selectSimilarExpiredRelation(skuId, minExpiryTime, maxNum, ip);
  318. if (groupsId == null) {
  319. log.info("暂无相似过期时间车队");
  320. return null;
  321. }
  322. GroupsRelation relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  323. .notIn(errorsRelationIds != null && errorsRelationIds.size() > 0, GroupsRelation::getId, errorsRelationIds)
  324. .eq(GroupsRelation::getGroupsId, groupsId)
  325. .eq(GroupsRelation::getStatus, GroupsRelation.Status.none)
  326. .eq(GroupsRelation::getUserId, 0)
  327. .orderByAsc(GroupsRelation::getNum)
  328. .last("limit 1"));
  329. if (relation != null) {
  330. log.info("用户userId:{},获取相似车队的车位relationId:{}", relation.getId());
  331. }
  332. return relation;
  333. }
  334. @Override
  335. public Page<UserRecommendGoodsFrontView> getRecommendGoodsViews(Boolean isPayNf, List<Long> filter_goods_id, Boolean filterCourseGoods, Integer start, Integer limit) {
  336. return groupsRelationMapper.getRecommendGoodsViews(new Page<>(start, limit), filter_goods_id, isPayNf, filterCourseGoods);
  337. }
  338. @Override
  339. @Transactional(rollbackFor = Throwable.class)
  340. public void sendCourseWare(SpecialGoodsTicketReq request) throws Exception {
  341. Long userId = request.getUserId();
  342. Long relationId = request.getRelationId();
  343. String email = request.getEmail();
  344. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  345. RenewalView relation = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getRelationId, relationId).build());
  346. Assert.notNull(relation, "您的车票不存在");
  347. Long relationUserId = relation.getUserId();
  348. if (!userIdList.contains(relationUserId)) {
  349. throw BusinessRuntimeException.getInstance("您的车票不存在");
  350. }
  351. if (relation.getSpecialType() != GoodsDon.SpecialType.courseware) {
  352. throw BusinessRuntimeException.getInstance("");
  353. }
  354. //是否已发送
  355. if (StrUtil.isNotBlank(relation.getGrAccount())) {
  356. throw BusinessRuntimeException.getInstance("已领取课件,请前往邮箱查看");
  357. }
  358. if (!Validator.isEmail(email)) {
  359. throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
  360. }
  361. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  362. .set(GroupsRelation::getAccount, email)
  363. .and(qr -> qr.isNull(GroupsRelation::getAccount).or().eq(GroupsRelation::getAccount, StrUtil.EMPTY))
  364. .eq(GroupsRelation::getId, relationId));
  365. if (update > 0) {
  366. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  367. .set(OrderDon::getStatus, OrderDon.Status.complete)
  368. .eq(OrderDon::getRelationId, relationId)
  369. .eq(OrderDon::getUserId, userId)
  370. .eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  371. mailService.sendCoursewareByGoodsId(relation.getGoodsId(), relation.getRelationId(), relation.getUserId(), relation.getTitle(), email);
  372. }
  373. }
  374. @Override
  375. public GroupsRelation getRelation(Long payRelationId, Long userId, GoodsDonSku sku, String ip) {
  376. GroupsRelation relation = null;
  377. Integer maxNum = sku.getNum();
  378. if (payRelationId != null && payRelationId > 0) {
  379. relation = groupsRelationMapper.selectById(payRelationId);
  380. if (relation == null) {
  381. throw new BusinessRuntimeException(GROUP_INDEX_NOT_FIND.getCode(), GROUP_INDEX_NOT_FIND.getMsg());
  382. }
  383. if (relation.getUserId() != null && relation.getUserId() > 0L) {
  384. throw new BusinessRuntimeException(GROUP_INDEX_ALREADY_BE_USER.getCode(), GROUP_INDEX_ALREADY_BE_USER.getMsg());
  385. }
  386. } else {
  387. GroupsTrips groups = null;
  388. //ChatGpt Plus、Midjourney非独立规格 上车先获取硬塞座位 硬塞5个座位
  389. //主账号过期时间25天以外
  390. //23-12-06 MidJourney 不硬塞
  391. if (sku.getNum() > 1 && Constant.AI_goodsIds.get(0) == sku.getGoodsId()) {
  392. Integer extraNum = 5;
  393. if (sku.getId() == 178l || sku.getId() == 423l) {
  394. extraNum = 2;
  395. }
  396. maxNum += extraNum;
  397. DateTime time = DateUtil.offsetDay(DateUtil.beginOfDay(DateTime.now()), 25);
  398. //不塞存在该用户的车队
  399. Long groupsId = groupsRelationMapper.getOutSideGroupsTripsRelationByGoodsId(sku.getId(), time, extraNum, userId, sku.getNum(), maxNum);
  400. if (groupsId != null) {
  401. relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  402. .eq(GroupsRelation::getGroupsId, groupsId)
  403. .eq(GroupsRelation::getUserId, 0)
  404. .eq(GroupsRelation::getStatus, GroupsRelation.Status.outside)
  405. .last("limit 1"));
  406. if (relation == null) {
  407. relation = new GroupsRelation();
  408. relation.setStatus(GroupsRelation.Status.outside);
  409. relation.setUserId(userId);
  410. relation.setGroupsId(groupsId);
  411. GroupsRelation maxNumRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  412. Integer nextNum = maxNumRelation.getNum() + 1;
  413. if (redisService.setNx(RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getNameFormat(groupsId, nextNum), nextNum, RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getTimeout())) {
  414. relation.setNum(nextNum);
  415. groupsRelationMapper.insert(relation);
  416. } else {
  417. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  418. }
  419. }
  420. groups = groupsMapper.selectById(groupsId);
  421. }
  422. }
  423. if (groups == null) {
  424. //寻找差不多过期时间规格的车位
  425. relation = getSimilarExpiredGroupRelation(sku, null, ip);
  426. if (relation == null) {
  427. //TODO 如果没指定座位,等待逻辑确认
  428. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.validity, maxNum, ip);
  429. if (groups == null) {
  430. //待发车
  431. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.waiting, maxNum, ip);
  432. }
  433. //新增空车队
  434. if (groups == null) {
  435. relation = groupsFuncService.createNewGroupsTrips(sku);
  436. }
  437. //获取车位
  438. if (relation == null) {
  439. //寻找快满编车队进行占座
  440. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  441. if (relation == null) {
  442. Long groupsId = groups.getId();
  443. TASK_EXECUTOR.execute(() -> groupsMapper.updateAvailableNum(groupsId));
  444. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  445. }
  446. }
  447. }
  448. }
  449. if (groups == null) {
  450. groups = groupsMapper.selectById(relation.getGroupsId());
  451. }
  452. //车队目前可用停车数
  453. relation.setGroupsAvailParkingNum(groups.getAvailableParkingNum());
  454. relation.setMaxNum(maxNum);
  455. }
  456. return relation;
  457. }
  458. @Override
  459. public String getAiVerifyCode(Long userId, Long relationId, Integer type, Boolean sync) throws Exception {
  460. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  461. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  462. .field(RenewalView::getRelationId, relationId).build());
  463. if (renewalView == null) {
  464. throw BusinessRuntimeException.getInstance("您的车票不存在...");
  465. }
  466. if (StrUtil.isEmpty(renewalView.getAccount())) {
  467. throw BusinessRuntimeException.getInstance("车票未配置账号");
  468. }
  469. String account = renewalView.getAccount();
  470. String password = renewalView.getPassword();
  471. if (StrUtil.hasEmpty(account, password)) {
  472. throw BusinessRuntimeException.getInstance("您的车票账号密码异常,请联系客服...");
  473. }
  474. if (renewalView.getAccount().contains(CUI_QIU_EMAIL_SUFFIX)) {
  475. return cuiQiuMailService.getVerifyCode(renewalView.getAccount(), renewalView.getGoodsId(), type, sync);
  476. }
  477. //获取邮箱密码
  478. SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
  479. .eq(SysEmail::getEmail, account)
  480. .last("limit 1"));
  481. if (sysEmail == null) {
  482. log.info("获取账号:{}验证码异常,未配置对应系统邮箱", account);
  483. throw BusinessRuntimeException.getInstance("获取账号验证码异常,请联系客服...");
  484. }
  485. String url = "http://yinhelx.com/api/controller.php";
  486. Map<String, Object> params = new HashMap<>();
  487. params.put("imap_key", "imap_56568niua@@");
  488. params.put("fun", "imap_read");
  489. params.put("imap_ip", "yinhelx.com");
  490. params.put("port", "143");
  491. params.put("username", account);
  492. params.put("password", sysEmail.getPassword());
  493. params.put("mbox_id", "0");
  494. params.put("delete", "0");
  495. HttpRequest post = HttpUtil.createPost(url);
  496. post.form(params);
  497. cn.hutool.http.HttpResponse execute = post.execute();
  498. if (execute.getStatus() != HttpStatus.HTTP_OK) {
  499. throw BusinessRuntimeException.getInstance("获取验证码异常,请联系客服...");
  500. }
  501. String code = getDifferentGoodsCode(renewalView.getGoodsId(), execute.body(), type, sync);
  502. GroupsRelationLoginCodeRecord record = new GroupsRelationLoginCodeRecord();
  503. record.setUserId(userId);
  504. record.setRelationId(relationId);
  505. record.setAccount(renewalView.getAccount());
  506. record.setGoodsId(renewalView.getGoodsId());
  507. record.setSkuId(renewalView.getSkuId());
  508. groupsRelationLoginCodeRecordMapper.insert(record);
  509. return code;
  510. }
  511. @Override
  512. public void checkGroupsAvailParkingNum(Long skuId, Long groupsId, Integer availableParkingNum, Integer maxNum) {
  513. //GPT10人月付、4人月付
  514. if (skuId == 161l || skuId == 178l) {
  515. //为0时,不参与限制
  516. if (availableParkingNum == 0) {
  517. return;
  518. }
  519. //目前车队可用停车数
  520. //目前上车人数
  521. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  522. .eq(GroupsRelation::getGroupsId, groupsId)
  523. .ne(GroupsRelation::getUserId, 0)
  524. .le(GroupsRelation::getNum, maxNum));
  525. if (currentParkingNum > availableParkingNum) {
  526. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  527. }
  528. }
  529. }
  530. @Override
  531. public void adjustGroupsParkingTime(Long relationId, GoodsDonSku sku) {
  532. Long skuId = sku.getId();
  533. //更新GPT Plus10人、4人月付车队状态 待优化
  534. if (skuId == 161l || skuId == 178l || skuId == 422l || skuId == 423l) {
  535. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  536. Long groupsId = relation.getGroupsId();
  537. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  538. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  539. //为0时 不参与限制
  540. if (availableParkingNum == 0) {
  541. return;
  542. }
  543. Integer extraNum = 5;
  544. if (skuId == 178l || skuId == 423l) {
  545. extraNum = 2;
  546. }
  547. Integer maxNum = sku.getNum() + extraNum;
  548. if (availableParkingNum >= maxNum) {
  549. return;
  550. }
  551. //目前上车人数
  552. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  553. .eq(GroupsRelation::getGroupsId, groupsId)
  554. .ne(GroupsRelation::getUserId, 0)
  555. .le(GroupsRelation::getNum, maxNum));
  556. if (currentParkingNum >= availableParkingNum) {
  557. //锁住
  558. DateTime parkingTime = DateUtil.offsetDay(DateTime.now(), 1);
  559. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  560. .eq(GroupsTrips::getId, groupsTrips.getId())
  561. .set(GroupsTrips::getParkingTime, parkingTime)
  562. .isNull(GroupsTrips::getParkingTime));
  563. }
  564. }
  565. }
  566. @Override
  567. public void setGroupsTripsParkingTimeEmpty(GoodsDonSku sku, Long relationId) {
  568. Long skuId = sku.getId();
  569. if (skuId == 161l || skuId == 178l) {
  570. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  571. Long groupsId = relation.getGroupsId();
  572. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  573. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  574. if (groupsTrips.getParkingTime() == null || availableParkingNum == 0) {
  575. return;
  576. }
  577. Integer extraNum = 5;
  578. if (skuId == 178l) {
  579. extraNum = 2;
  580. }
  581. Integer skuNum = sku.getNum();
  582. if (availableParkingNum >= skuNum + extraNum) {
  583. return;
  584. }
  585. //目前上车人数
  586. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  587. .eq(GroupsRelation::getGroupsId, groupsId)
  588. .ne(GroupsRelation::getUserId, 0));
  589. if (currentParkingNum < availableParkingNum) {
  590. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  591. .eq(GroupsTrips::getId, groupsTrips.getId())
  592. .set(GroupsTrips::getParkingTime, null)
  593. .isNotNull(GroupsTrips::getParkingTime));
  594. }
  595. }
  596. }
  597. @Override
  598. public Integer getUserCodeNumBySkuId(Long userId, Long skuId, Boolean isHasVerifyCode) {
  599. //查看双重验证码
  600. UserFuncProperty userFuncProperty = userFuncPropertyMapper.selectOne(Wrappers.lambdaQuery(UserFuncProperty.class).eq(UserFuncProperty::getUserId, userId).last("limit 1"));
  601. //默认2次
  602. int num = 2;
  603. //有安全码查看次数 置为0
  604. if (isHasVerifyCode) {
  605. num = 0;
  606. //存在身份实名认证有两次机会
  607. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  608. Integer selectCount = userCertRecordMapper.selectCount(Wrappers.lambdaQuery(UserCertRecord.class)
  609. .in(UserCertRecord::getUserId, userIdList));
  610. if (selectCount > 0) {
  611. num = 2;
  612. }
  613. return num;
  614. }
  615. //查看双重验证码次数
  616. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  617. if (sku.getCodeNum() > 0) {
  618. num = sku.getCodeNum();
  619. }
  620. if (userFuncProperty != null) num = userFuncProperty.getVerifyCheckNum();
  621. return num;
  622. }
  623. @Override
  624. public List<RenewalView> getHasPayGoods(long userId) {
  625. User user = userMapper.selectById(userId);
  626. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, user);
  627. DateTime now = DateTime.now();
  628. List<RenewalView> list = groupsRelationMapper.getUserHasPayGoods(userIds, now);
  629. return list;
  630. }
  631. @Override
  632. public List<RenewalView> getExpiryRenewalNotify(Long userId) {
  633. DateTime now = DateTime.now();
  634. DateTime thisZero = DateUtil.beginOfDay(now);
  635. String thisDate = thisZero.toDateStr();
  636. Object exists = redisService.get(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId));
  637. if (exists != null) {
  638. return null;
  639. }
  640. User u = userMapper.selectById(userId);
  641. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  642. if (u.getIsBlack()) {
  643. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  644. return null;
  645. }
  646. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  647. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  648. List<RenewalView> list = beanSearcher.searchAll(RenewalView.class, builder
  649. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  650. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  651. .field(RenewalView::getExpiryTime, now).op(Operator.GreaterThan)
  652. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  653. .field(RenewalView::getAqType, 1)
  654. .orderBy(RenewalView::getExpiryTime).asc()
  655. .onlySelect(RenewalView::getMonths, RenewalView::getExpiryTime, RenewalView::getRelationId, RenewalView::getAccount, RenewalView::getGoodsId, RenewalView::getTitle, RenewalView::getLogo, RenewalView::getImg, RenewalView::getGroupId, RenewalView::getSkuId, RenewalView::getSpecVal, RenewalView::getGoodsStatus, RenewalView::getSkuStatus)
  656. .build());
  657. if (list.size() > 5) {
  658. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  659. return null;
  660. }
  661. //提前7天
  662. AtomicInteger day = new AtomicInteger(7);
  663. List<RenewalView> expiryTickets = list.stream().filter(ticket -> {
  664. //下架
  665. if (ticket.getGoodsStatus() == null || ticket.getSkuStatus() == null || !ticket.getGoodsStatus() || !ticket.getSkuStatus()) {
  666. return false;
  667. }
  668. Integer skuMonths = ticket.getMonths();
  669. Date expiryTime = ticket.getExpiryTime();
  670. //年付 提前一个月
  671. if (skuMonths >= 12) {
  672. day.set(30);
  673. } else {
  674. day.set(7);
  675. }
  676. if (DateUtil.beginOfDay(expiryTime).compareTo(DateUtil.offsetDay(thisZero, day.get())) <= 0) {
  677. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  678. ticket.setExpiryTime(null);
  679. return true;
  680. }
  681. return false;
  682. }).collect(Collectors.toList());
  683. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  684. if (CollUtil.isNotEmpty(expiryTickets)) {
  685. groupsRelationExpiryNotifyRecordMapper.batchInsert(userId, expiryTickets);
  686. }
  687. return expiryTickets;
  688. }
  689. public String getDifferentGoodsCode(Long goodsId, String body, Integer type, Boolean sync) {
  690. String code = null;
  691. //奈飞
  692. if (goodsId == 1) {
  693. if (type != null && type == 1) {
  694. if (body.contains("輸入此代碼登入") || body.contains("输入此代码登录")) {
  695. code = StrUtil.subBetween(body, "輸入此代碼登入", "請在裝置上輸入上");
  696. if (StrUtil.isEmpty(code)) {
  697. code = StrUtil.subAfter(body, "输入此代码登录", true);
  698. }
  699. }
  700. if (StrUtil.isEmpty(code)) {
  701. throw BusinessRuntimeException.getInstance("查询失败,请检查是否发送了登陆码..");
  702. }
  703. } else {
  704. String urlPref = "https://www.netflix.com/account/update-primary-location";
  705. code = StrUtil.subBetween(body, "[" + urlPref, "]");
  706. if (StrUtil.isEmpty(code)) {
  707. urlPref = "https://www.netflix.com/account/travel/verify";
  708. code = StrUtil.subBetween(body, "[" + urlPref, "]");
  709. if (StrUtil.isEmpty(code)) {
  710. throw BusinessRuntimeException.getInstance("获取认证链接失败,请重新获取");
  711. }
  712. }
  713. String url = urlPref + code;
  714. //非点击装置同步更新按钮 直接返回链接
  715. if (!sync) return url;
  716. //失败返回验证链接
  717. if (!groupsRelationNetflixService.confirmUpdate(url)) {
  718. return url;
  719. }
  720. return StrUtil.EMPTY;
  721. }
  722. }
  723. //除奈飞
  724. if (StrUtil.isEmpty(code)) {
  725. code = TicketCodeCommonUtil.getTicketCodeStr(body, goodsId);
  726. }
  727. int length = 4;
  728. if (goodsId == 33l) {
  729. length = 6;
  730. }
  731. code = StringUtil.getVerifyCodePattern(code, length);
  732. if (!Validator.isNumber(code)) {
  733. log.error("获取账号验证码失败:{}", StrUtil.subSufByLength(code, 512));
  734. throw BusinessRuntimeException.getInstance("获取验证码失败,请重新获取..");
  735. }
  736. return code.trim();
  737. }
  738. @Override
  739. public void getCollegeStudentUserGptTicket(Long userId) {
  740. Retryer<Boolean> build = RetryerBuilder.<Boolean>newBuilder()
  741. .retryIfException()
  742. //运行时异常重试
  743. .retryIfRuntimeException()
  744. //false重试
  745. .retryIfResult(res -> Objects.equals(res, false))
  746. //1s 间隔
  747. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  748. //停止策略 : 尝试请求3次
  749. .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
  750. try {
  751. build.call(() -> {
  752. //体验规格
  753. Long gptMirrorSkuId = Constant.GPT_MIRROR_SKU_ID;
  754. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(gptMirrorSkuId);
  755. GroupsRelation relation = null;
  756. if (groups != null) {
  757. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  758. }
  759. if (relation == null) {
  760. //生成空车队
  761. GoodsDonSku sku = goodsDonSkuMapper.selectById(gptMirrorSkuId);
  762. relation = groupsFuncService.createNewGroupsTrips(sku);
  763. }
  764. DateTime startTime = DateTime.now();
  765. DateTime expiryTime = DateUtil.offsetDay(startTime, 1);
  766. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  767. .set(GroupsRelation::getUserId, userId)
  768. .set(GroupsRelation::getStartTime, startTime)
  769. .set(GroupsRelation::getExpiryTime, expiryTime)
  770. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  771. .set(GroupsRelation::getAqType, 2)
  772. .eq(GroupsRelation::getId, relation.getId())
  773. .eq(GroupsRelation::getUserId, 0));
  774. if (update > 0) {
  775. groupsMapper.decrAvailableNum(groups.getId());
  776. return true;
  777. }
  778. log.error("发送用户:{} GPT镜像车票体验失败,进行重试", userId);
  779. return false;
  780. });
  781. } catch (ExecutionException | RetryException e) {
  782. log.error("发送用户GPT镜像体验失败:{}", StringUtil.getErrorText(e));
  783. }
  784. }
  785. @Override
  786. public RenewalView getTicketDetail(long userId, Long relationId) {
  787. User u = userMapper.selectById(userId);
  788. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  789. MapBuilder builder = MapUtils.builder();
  790. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, builder
  791. .field(RenewalView::getRelationId, relationId)
  792. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  793. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  794. .field("condition", String.format("(gr.expiry_time is null or gr.expiry_time > '%s')", DateTime.now()))
  795. .field(RenewalView::getStatus, List.of("validity", "outside")).op(Operator.InList)
  796. .orderBy(RenewalView::getExpiryTime).asc()
  797. .onlySelect(RenewalView::getRelationId, RenewalView::getExpiryTime, RenewalView::getTitle, RenewalView::getSpecVal, RenewalView::getGoodsId, RenewalView::getSkuId, RenewalView::getSkuNum, RenewalView::getSkuStatus, RenewalView::getGoodsStatus)
  798. .build());
  799. if (renewalView != null) {
  800. renewalView.setExpiryTimeStr(DateUtil.format(renewalView.getExpiryTime(), "yyyy-MM-dd"));
  801. }
  802. return renewalView;
  803. }
  804. }