GroupRelationFrontServiceImpl.java 35 KB

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