GroupRelationFrontServiceImpl.java 33 KB

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