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. if (userInfo.getPackageId() != 0) {
  244. UpgradePackage upgradePackage = upgradePackageMapper.selectById(userInfo.getPackageId());
  245. ticket.setPackagePrice(upgradePackage.getPrice());
  246. }
  247. }
  248. List<GroupsRelationUserView> relationUserViews = groupsRelationMapper.getUserRelationUserViews(ticket.getGroupId(), ticket.getRelationId(), ticket.getUserId(), List.of(GroupsRelation.Status.validity, GroupsRelation.Status.outside));
  249. ticket.setRelationViews(relationUserViews);
  250. if (ticket.getExpiryTime() != null) {
  251. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  252. }
  253. //查看双重验证码
  254. if (StrUtil.isNotEmpty(ticket.getApiSecret())) {
  255. Boolean isHasVerifyCode = StrUtil.isNotBlank(ticket.getVerifyCode()) ? true : false;
  256. Integer codeNum = getUserCodeNumBySkuId(ticket.getUserId(), ticket.getSkuId(), isHasVerifyCode);
  257. ticket.setCodeNum(codeNum);
  258. }
  259. });
  260. userLoginRecordService.saveUserLoginDayRecord(userId);
  261. return list;
  262. }
  263. @Override
  264. public Boolean isJoinCorpWx(Long userId, Boolean isJoin, Boolean noCoupon) {
  265. if (!isJoin) {
  266. User user = userMapper.selectById(userId);
  267. if (user == null || StrUtil.isEmpty(user.getUnionid())) {
  268. return true;
  269. }
  270. // CorpUser corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class)
  271. // .ne(CorpUser::getUnionid, "")
  272. // .eq(CorpUser::getUnionid, user.getUnionid())
  273. // .last("limit 1")
  274. // .select(CorpUser::getId)
  275. // );
  276. CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
  277. .field(CorpUserFollowView::getUnionId, user.getUnionid())
  278. .field(CorpUserFollowView::getStatus, 1).build());
  279. if (corpUserFollowView == null) {
  280. return false;
  281. }
  282. }
  283. //用户是否买了奈飞车票
  284. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  285. .field(RenewalView::getUserId, userId)
  286. .field(RenewalView::getGoodsId, 1)
  287. .field(RenewalView::getStatus, List.of("validity", "overdue")).op(Operator.InList)
  288. .build());
  289. if (number.intValue() > 0 && !noCoupon) {
  290. couponCommonService.sendCouponToUser(userId, 34l, 0l, 0l, 0l, CouponUser.Channel.wxCorp);
  291. }
  292. return true;
  293. }
  294. @Override
  295. public GroupsRelation getSimilarExpiredGroupRelation(GoodsDonSku sku, List<Long> errorsRelationIds, String ip) {
  296. Long skuId = sku.getId();
  297. Integer days = sku.getDays();
  298. Integer months = sku.getMonths();
  299. Integer maxNum = sku.getNum();
  300. DateTime expiryTime = null;
  301. if (days != null && days > 0) {
  302. expiryTime = DateUtil.offsetDay(DateTime.now(), days);
  303. } else {
  304. expiryTime = DateUtil.offsetMonth(DateTime.now(), months);
  305. }
  306. Integer extraNum = 5;
  307. if (sku.getId() == 178l) {
  308. extraNum = 2;
  309. }
  310. maxNum += extraNum;
  311. DateTime minExpiryTime = DateUtil.offsetDay(expiryTime, -5);
  312. Long groupsId = groupsRelationMapper.selectSimilarExpiredRelation(skuId, minExpiryTime, maxNum, ip);
  313. if (groupsId == null) {
  314. log.info("暂无相似过期时间车队");
  315. return null;
  316. }
  317. GroupsRelation relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  318. .notIn(errorsRelationIds != null && errorsRelationIds.size() > 0, GroupsRelation::getId, errorsRelationIds)
  319. .eq(GroupsRelation::getGroupsId, groupsId)
  320. .eq(GroupsRelation::getStatus, GroupsRelation.Status.none)
  321. .eq(GroupsRelation::getUserId, 0)
  322. .orderByAsc(GroupsRelation::getNum)
  323. .last("limit 1"));
  324. if (relation != null) {
  325. log.info("用户userId:{},获取相似车队的车位relationId:{}", relation.getId());
  326. }
  327. return relation;
  328. }
  329. @Override
  330. public Page<UserRecommendGoodsFrontView> getRecommendGoodsViews(Boolean isPayNf, List<Long> filter_goods_id, Boolean filterCourseGoods, Integer start, Integer limit) {
  331. return groupsRelationMapper.getRecommendGoodsViews(new Page<>(start, limit), filter_goods_id, isPayNf, filterCourseGoods);
  332. }
  333. @Override
  334. @Transactional(rollbackFor = Throwable.class)
  335. public void sendCourseWare(SpecialGoodsTicketReq request) throws Exception {
  336. Long userId = request.getUserId();
  337. Long relationId = request.getRelationId();
  338. String email = request.getEmail();
  339. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  340. RenewalView relation = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getRelationId, relationId).build());
  341. Assert.notNull(relation, "您的车票不存在");
  342. Long relationUserId = relation.getUserId();
  343. if (!userIdList.contains(relationUserId)) {
  344. throw BusinessRuntimeException.getInstance("您的车票不存在");
  345. }
  346. if (relation.getSpecialType() != GoodsDon.SpecialType.courseware) {
  347. throw BusinessRuntimeException.getInstance("");
  348. }
  349. //是否已发送
  350. if (StrUtil.isNotBlank(relation.getGrAccount())) {
  351. throw BusinessRuntimeException.getInstance("已领取课件,请前往邮箱查看");
  352. }
  353. if (!Validator.isEmail(email)) {
  354. throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
  355. }
  356. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  357. .set(GroupsRelation::getAccount, email)
  358. .and(qr -> qr.isNull(GroupsRelation::getAccount).or().eq(GroupsRelation::getAccount, StrUtil.EMPTY))
  359. .eq(GroupsRelation::getId, relationId));
  360. if (update > 0) {
  361. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  362. .set(OrderDon::getStatus, OrderDon.Status.complete)
  363. .eq(OrderDon::getRelationId, relationId)
  364. .eq(OrderDon::getUserId, userId)
  365. .eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  366. mailService.sendCoursewareByGoodsId(relation.getGoodsId(), relation.getRelationId(), relation.getUserId(), relation.getTitle(), email);
  367. }
  368. }
  369. @Override
  370. public GroupsRelation getRelation(Long payRelationId, Long userId, GoodsDonSku sku, String ip) {
  371. GroupsRelation relation = null;
  372. Integer maxNum = sku.getNum();
  373. if (payRelationId != null && payRelationId > 0) {
  374. relation = groupsRelationMapper.selectById(payRelationId);
  375. if (relation == null) {
  376. throw new BusinessRuntimeException(GROUP_INDEX_NOT_FIND.getCode(), GROUP_INDEX_NOT_FIND.getMsg());
  377. }
  378. if (relation.getUserId() != null && relation.getUserId() > 0L) {
  379. throw new BusinessRuntimeException(GROUP_INDEX_ALREADY_BE_USER.getCode(), GROUP_INDEX_ALREADY_BE_USER.getMsg());
  380. }
  381. } else {
  382. GroupsTrips groups = null;
  383. //ChatGpt Plus、Midjourney非独立规格 上车先获取硬塞座位 硬塞5个座位
  384. //主账号过期时间25天以外
  385. //23-12-06 MidJourney 不硬塞
  386. if (sku.getNum() > 1 && Constant.AI_goodsIds.get(0) == sku.getGoodsId()) {
  387. Integer extraNum = 5;
  388. if (sku.getId() == 178l || sku.getId() == 423l) {
  389. extraNum = 2;
  390. }
  391. maxNum += extraNum;
  392. DateTime time = DateUtil.offsetDay(DateUtil.beginOfDay(DateTime.now()), 25);
  393. //不塞存在该用户的车队
  394. Long groupsId = groupsRelationMapper.getOutSideGroupsTripsRelationByGoodsId(sku.getId(), time, extraNum, userId, sku.getNum(), maxNum);
  395. if (groupsId != null) {
  396. relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  397. .eq(GroupsRelation::getGroupsId, groupsId)
  398. .eq(GroupsRelation::getUserId, 0)
  399. .eq(GroupsRelation::getStatus, GroupsRelation.Status.outside)
  400. .last("limit 1"));
  401. if (relation == null) {
  402. relation = new GroupsRelation();
  403. relation.setStatus(GroupsRelation.Status.outside);
  404. relation.setUserId(userId);
  405. relation.setGroupsId(groupsId);
  406. GroupsRelation maxNumRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  407. Integer nextNum = maxNumRelation.getNum() + 1;
  408. if (redisService.setNx(RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getNameFormat(groupsId, nextNum), nextNum, RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getTimeout())) {
  409. relation.setNum(nextNum);
  410. groupsRelationMapper.insert(relation);
  411. } else {
  412. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  413. }
  414. }
  415. groups = groupsMapper.selectById(groupsId);
  416. }
  417. }
  418. if (groups == null) {
  419. //寻找差不多过期时间规格的车位
  420. relation = getSimilarExpiredGroupRelation(sku, null, ip);
  421. if (relation == null) {
  422. //TODO 如果没指定座位,等待逻辑确认
  423. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.validity, maxNum, ip);
  424. if (groups == null) {
  425. //待发车
  426. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.waiting, maxNum, ip);
  427. }
  428. //新增空车队
  429. if (groups == null) {
  430. relation = groupsFuncService.createNewGroupsTrips(sku);
  431. }
  432. //获取车位
  433. if (relation == null) {
  434. //寻找快满编车队进行占座
  435. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  436. if (relation == null) {
  437. Long groupsId = groups.getId();
  438. TASK_EXECUTOR.execute(() -> groupsMapper.updateAvailableNum(groupsId));
  439. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  440. }
  441. }
  442. }
  443. }
  444. if (groups == null) {
  445. groups = groupsMapper.selectById(relation.getGroupsId());
  446. }
  447. //车队目前可用停车数
  448. relation.setGroupsAvailParkingNum(groups.getAvailableParkingNum());
  449. relation.setMaxNum(maxNum);
  450. }
  451. return relation;
  452. }
  453. @Override
  454. public String getAiVerifyCode(Long userId, Long relationId, Integer type) throws Exception {
  455. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  456. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  457. .field(RenewalView::getRelationId, relationId).build());
  458. if (renewalView == null) {
  459. throw BusinessRuntimeException.getInstance("您的车票不存在...");
  460. }
  461. if (StrUtil.isEmpty(renewalView.getAccount())) {
  462. throw BusinessRuntimeException.getInstance("车票未配置账号");
  463. }
  464. String account = renewalView.getAccount();
  465. String password = renewalView.getPassword();
  466. if (StrUtil.hasEmpty(account, password)) {
  467. throw BusinessRuntimeException.getInstance("您的车票账号密码异常,请联系客服...");
  468. }
  469. if (renewalView.getAccount().contains(CUI_QIU_EMAIL_SUFFIX)) {
  470. return cuiQiuMailService.getVerifyCode(renewalView.getAccount(), renewalView.getGoodsId());
  471. }
  472. //获取邮箱密码
  473. SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
  474. .eq(SysEmail::getEmail, account)
  475. .last("limit 1"));
  476. if (sysEmail == null) {
  477. log.info("获取账号:{}验证码异常,未配置对应系统邮箱", account);
  478. throw BusinessRuntimeException.getInstance("获取账号验证码异常,请联系客服...");
  479. }
  480. String url = "http://yinhelx.com/api/controller.php";
  481. Map<String, Object> params = new HashMap<>();
  482. params.put("imap_key", "imap_56568niua@@");
  483. params.put("fun", "imap_read");
  484. params.put("imap_ip", "yinhelx.com");
  485. params.put("port", "143");
  486. params.put("username", account);
  487. params.put("password", sysEmail.getPassword());
  488. params.put("mbox_id", "0");
  489. params.put("delete", "0");
  490. HttpRequest post = HttpUtil.createPost(url);
  491. post.form(params);
  492. cn.hutool.http.HttpResponse execute = post.execute();
  493. if (execute.getStatus() != HttpStatus.HTTP_OK) {
  494. throw BusinessRuntimeException.getInstance("获取验证码异常,请联系客服...");
  495. }
  496. String code = getDifferentGoodsCode(renewalView.getGoodsId(), execute.body(), type);
  497. GroupsRelationLoginCodeRecord record = new GroupsRelationLoginCodeRecord();
  498. record.setUserId(userId);
  499. record.setRelationId(relationId);
  500. record.setAccount(renewalView.getAccount());
  501. record.setGoodsId(renewalView.getGoodsId());
  502. record.setSkuId(renewalView.getSkuId());
  503. groupsRelationLoginCodeRecordMapper.insert(record);
  504. return code;
  505. }
  506. @Override
  507. public void checkGroupsAvailParkingNum(Long skuId, Long groupsId, Integer availableParkingNum, Integer maxNum) {
  508. //GPT10人月付、4人月付
  509. if (skuId == 161l || skuId == 178l) {
  510. //为0时,不参与限制
  511. if (availableParkingNum == 0) {
  512. return;
  513. }
  514. //目前车队可用停车数
  515. //目前上车人数
  516. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  517. .eq(GroupsRelation::getGroupsId, groupsId)
  518. .ne(GroupsRelation::getUserId, 0)
  519. .le(GroupsRelation::getNum, maxNum));
  520. if (currentParkingNum > availableParkingNum) {
  521. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  522. }
  523. }
  524. }
  525. @Override
  526. public void adjustGroupsParkingTime(Long relationId, GoodsDonSku sku) {
  527. Long skuId = sku.getId();
  528. //更新GPT Plus10人、4人月付车队状态 待优化
  529. if (skuId == 161l || skuId == 178l || skuId == 422l || skuId == 423l) {
  530. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  531. Long groupsId = relation.getGroupsId();
  532. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  533. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  534. //为0时 不参与限制
  535. if (availableParkingNum == 0) {
  536. return;
  537. }
  538. Integer extraNum = 5;
  539. if (skuId == 178l || skuId == 423l) {
  540. extraNum = 2;
  541. }
  542. Integer maxNum = sku.getNum() + extraNum;
  543. if (availableParkingNum >= maxNum) {
  544. return;
  545. }
  546. //目前上车人数
  547. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  548. .eq(GroupsRelation::getGroupsId, groupsId)
  549. .ne(GroupsRelation::getUserId, 0)
  550. .le(GroupsRelation::getNum, maxNum));
  551. if (currentParkingNum >= availableParkingNum) {
  552. //锁住
  553. DateTime parkingTime = DateUtil.offsetDay(DateTime.now(), 1);
  554. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  555. .eq(GroupsTrips::getId, groupsTrips.getId())
  556. .set(GroupsTrips::getParkingTime, parkingTime)
  557. .isNull(GroupsTrips::getParkingTime));
  558. }
  559. }
  560. }
  561. @Override
  562. public void setGroupsTripsParkingTimeEmpty(GoodsDonSku sku, Long relationId) {
  563. Long skuId = sku.getId();
  564. if (skuId == 161l || skuId == 178l) {
  565. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  566. Long groupsId = relation.getGroupsId();
  567. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  568. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  569. if (groupsTrips.getParkingTime() == null || availableParkingNum == 0) {
  570. return;
  571. }
  572. Integer extraNum = 5;
  573. if (skuId == 178l) {
  574. extraNum = 2;
  575. }
  576. Integer skuNum = sku.getNum();
  577. if (availableParkingNum >= skuNum + extraNum) {
  578. return;
  579. }
  580. //目前上车人数
  581. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  582. .eq(GroupsRelation::getGroupsId, groupsId)
  583. .ne(GroupsRelation::getUserId, 0));
  584. if (currentParkingNum < availableParkingNum) {
  585. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  586. .eq(GroupsTrips::getId, groupsTrips.getId())
  587. .set(GroupsTrips::getParkingTime, null)
  588. .isNotNull(GroupsTrips::getParkingTime));
  589. }
  590. }
  591. }
  592. @Override
  593. public Integer getUserCodeNumBySkuId(Long userId, Long skuId, Boolean isHasVerifyCode) {
  594. //查看双重验证码
  595. UserFuncProperty userFuncProperty = userFuncPropertyMapper.selectOne(Wrappers.lambdaQuery(UserFuncProperty.class).eq(UserFuncProperty::getUserId, userId).last("limit 1"));
  596. //默认2次
  597. int num = 2;
  598. //有安全码查看次数 置为0
  599. if (isHasVerifyCode) {
  600. num = 0;
  601. //存在身份实名认证有两次机会
  602. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  603. Integer selectCount = userCertRecordMapper.selectCount(Wrappers.lambdaQuery(UserCertRecord.class)
  604. .in(UserCertRecord::getUserId, userIdList));
  605. if (selectCount > 0) {
  606. num = 2;
  607. }
  608. return num;
  609. }
  610. //查看双重验证码次数
  611. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  612. if (sku.getCodeNum() > 0) {
  613. num = sku.getCodeNum();
  614. }
  615. if (userFuncProperty != null) num = userFuncProperty.getVerifyCheckNum();
  616. return num;
  617. }
  618. @Override
  619. public List<RenewalView> getHasPayGoods(long userId) {
  620. User user = userMapper.selectById(userId);
  621. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, user);
  622. DateTime now = DateTime.now();
  623. List<RenewalView> list = groupsRelationMapper.getUserHasPayGoods(userIds, now);
  624. return list;
  625. }
  626. @Override
  627. public List<RenewalView> getExpiryRenewalNotify(Long userId) {
  628. DateTime now = DateTime.now();
  629. DateTime thisZero = DateUtil.beginOfDay(now);
  630. String thisDate = thisZero.toDateStr();
  631. Object exists = redisService.get(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId));
  632. if (exists != null) {
  633. return null;
  634. }
  635. User u = userMapper.selectById(userId);
  636. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  637. if (u.getIsBlack()) {
  638. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  639. return null;
  640. }
  641. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  642. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  643. List<RenewalView> list = beanSearcher.searchAll(RenewalView.class, builder
  644. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  645. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  646. .field(RenewalView::getExpiryTime, now).op(Operator.GreaterThan)
  647. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  648. .orderBy(RenewalView::getExpiryTime).asc()
  649. .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)
  650. .build());
  651. if (list.size() > 5) {
  652. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  653. return null;
  654. }
  655. //提前7天
  656. AtomicInteger day = new AtomicInteger(7);
  657. List<RenewalView> expiryTickets = list.stream().filter(ticket -> {
  658. //下架
  659. if (ticket.getGoodsStatus() == null || ticket.getSkuStatus() == null || !ticket.getGoodsStatus() || !ticket.getSkuStatus()) {
  660. return false;
  661. }
  662. Integer skuMonths = ticket.getMonths();
  663. Date expiryTime = ticket.getExpiryTime();
  664. //年付 提前一个月
  665. if (skuMonths >= 12) {
  666. day.set(30);
  667. } else {
  668. day.set(7);
  669. }
  670. if (DateUtil.beginOfDay(expiryTime).compareTo(DateUtil.offsetDay(thisZero, day.get())) <= 0) {
  671. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  672. ticket.setExpiryTime(null);
  673. return true;
  674. }
  675. return false;
  676. }).collect(Collectors.toList());
  677. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  678. if (CollUtil.isNotEmpty(expiryTickets)) {
  679. groupsRelationExpiryNotifyRecordMapper.batchInsert(userId, expiryTickets);
  680. }
  681. return expiryTickets;
  682. }
  683. public String getDifferentGoodsCode(Long goodsId, String body, Integer type) {
  684. String code = null;
  685. //奈飞
  686. if (goodsId == 1) {
  687. if (body.contains("輸入此代碼登入")) {
  688. code = StrUtil.subBetween(body, "輸入此代碼登入", "請在裝置上輸入上");
  689. } else {
  690. String urlPref = "https://www.netflix.com/account/update-primary-location";
  691. code = StrUtil.subBetween(body, "[" + urlPref, "]");
  692. if (StrUtil.isEmpty(code)) {
  693. urlPref = "https://www.netflix.com/account/travel/verify";
  694. code = StrUtil.subBetween(body, "[" + urlPref, "]");
  695. if (StrUtil.isEmpty(code) && type == null) {
  696. throw BusinessRuntimeException.getInstance("获取认证链接失败,请重新获取");
  697. }
  698. }
  699. if (StrUtil.isNotBlank(code)) {
  700. return urlPref + code;
  701. }
  702. }
  703. if (type != null && type == 1) {
  704. throw BusinessRuntimeException.getInstance("查询失败,请检查是否发送了登陆码..");
  705. }
  706. }
  707. if (StrUtil.isEmpty(code)) {
  708. code = TicketCodeCommonUtil.getTicketCodeStr(body, goodsId);
  709. }
  710. int length = 4;
  711. if (goodsId == 33l) {
  712. length = 6;
  713. }
  714. code = StringUtil.getVerifyCodePattern(code, length);
  715. if (!Validator.isNumber(code)) {
  716. log.error("获取账号验证码失败:{}", StrUtil.subSufByLength(code, 512));
  717. throw BusinessRuntimeException.getInstance("获取验证码失败,请重新获取..");
  718. }
  719. return code.trim();
  720. }
  721. @Override
  722. public void getCollegeStudentUserGptTicket(Long userId) {
  723. Retryer<Boolean> build = RetryerBuilder.<Boolean>newBuilder()
  724. .retryIfException()
  725. //运行时异常重试
  726. .retryIfRuntimeException()
  727. //false重试
  728. .retryIfResult(res -> Objects.equals(res, false))
  729. //1s 间隔
  730. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  731. //停止策略 : 尝试请求3次
  732. .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
  733. try {
  734. build.call(() -> {
  735. //体验规格
  736. Long gptMirrorSkuId = Constant.GPT_MIRROR_SKU_ID;
  737. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(gptMirrorSkuId);
  738. GroupsRelation relation = null;
  739. if (groups != null) {
  740. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  741. }
  742. if (relation == null) {
  743. //生成空车队
  744. GoodsDonSku sku = goodsDonSkuMapper.selectById(gptMirrorSkuId);
  745. relation = groupsFuncService.createNewGroupsTrips(sku);
  746. }
  747. DateTime startTime = DateTime.now();
  748. DateTime expiryTime = DateUtil.offsetDay(startTime, 1);
  749. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  750. .set(GroupsRelation::getUserId, userId)
  751. .set(GroupsRelation::getStartTime, startTime)
  752. .set(GroupsRelation::getExpiryTime, expiryTime)
  753. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  754. //车票获取类型
  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. }