GroupRelationFrontServiceImpl.java 30 KB

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