GroupRelationController.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. package com.cyksj.web.controller.group;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.core.date.DateUnit;
  5. import cn.hutool.core.date.DateUtil;
  6. import cn.hutool.core.lang.Assert;
  7. import cn.hutool.core.thread.ThreadUtil;
  8. import cn.hutool.core.util.StrUtil;
  9. import cn.hutool.extra.servlet.ServletUtil;
  10. import cn.hutool.json.JSONObject;
  11. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  12. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  13. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  14. import com.cyksj.common.annotation.NoSubmit;
  15. import com.cyksj.common.constant.Constant;
  16. import com.cyksj.common.exception.BusinessRuntimeException;
  17. import com.cyksj.common.snowflake.Sequence;
  18. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  19. import com.cyksj.common.util.GoogleGenerator;
  20. import com.cyksj.common.util.Jsons;
  21. import com.cyksj.dto.Result;
  22. import com.cyksj.enums.GatewayResponse;
  23. import com.cyksj.mapper.*;
  24. import com.cyksj.mapper.manage.form.FormFieldsDataMapper;
  25. import com.cyksj.mapper.manage.form.QuestionnairePromotionMapper;
  26. import com.cyksj.model.dto.DoubleVerifyDto;
  27. import com.cyksj.model.dto.QuestionnaireView;
  28. import com.cyksj.model.entity.*;
  29. import com.cyksj.model.manage.views.GroupsRelationView;
  30. import com.cyksj.model.request.OrderPayRequest;
  31. import com.cyksj.model.request.OrderRefundReq;
  32. import com.cyksj.model.request.SpecialGoodsTicketReq;
  33. import com.cyksj.model.response.GptStandbyResp;
  34. import com.cyksj.model.views.*;
  35. import com.cyksj.redis.RedisService;
  36. import com.cyksj.service.chatgpt.ChatGptAuthService;
  37. import com.cyksj.service.mange.CmsOrderDonService;
  38. import com.cyksj.service.mange.coupon.CouponCommonService;
  39. import com.cyksj.service.mange.ticket.TicketAdvertiseConfigClickRecordService;
  40. import com.cyksj.service.order.OrderDonService;
  41. import com.cyksj.service.relation.GroupRelationFrontService;
  42. import com.cyksj.service.relation.GroupsRelationNetflixService;
  43. import com.cyksj.service.user.UserBindRelationService;
  44. import com.cyksj.service.user.UserService;
  45. import com.cyksj.web.util.StpUserUtil;
  46. import com.ejlchina.searcher.BeanSearcher;
  47. import com.ejlchina.searcher.SearchResult;
  48. import com.ejlchina.searcher.param.Operator;
  49. import com.ejlchina.searcher.util.MapUtils;
  50. import lombok.RequiredArgsConstructor;
  51. import lombok.extern.slf4j.Slf4j;
  52. import org.springframework.transaction.annotation.Transactional;
  53. import org.springframework.validation.annotation.Validated;
  54. import org.springframework.web.bind.annotation.*;
  55. import javax.servlet.http.HttpServletRequest;
  56. import java.math.BigDecimal;
  57. import java.math.RoundingMode;
  58. import java.util.*;
  59. import java.util.concurrent.TimeUnit;
  60. import java.util.stream.Collectors;
  61. /**
  62. * @author chan
  63. * @date 2022/9/27 11:48 AM
  64. */
  65. @Slf4j
  66. @RequiredArgsConstructor
  67. @RestController
  68. @RequestMapping("/applets/group/relation")
  69. public class GroupRelationController {
  70. private final BeanSearcher beanSearcher;
  71. private final OrderDonService orderDonService;
  72. private final GroupsRelationMapper relationMapper;
  73. private final GroupRelationFrontService groupRelationFrontService;
  74. private final UserService userService;
  75. private final UserBindRelationService userBindRelationService;
  76. private final TicketPwdViewRecordMapper ticketPwdViewRecordMapper;
  77. private final HttpServletRequest request;
  78. private final AccountDoubleVerifyRecordMapper accountDoubleVerifyRecordMapper;
  79. private final DoubleVerifyClickRecordMapper doubleVerifyRecordMapper;
  80. private final RedisService redisService;
  81. private final DoubleVerifyClickRefreshRecordMapper refreshRecordMapper;
  82. private final QuestionResponseRecordMapper questionResponseRecordMapper;
  83. private final CouponCommonService couponCommonService;
  84. private final FormFieldsDataMapper formFieldsDataMapper;
  85. private final QuestionnairePromotionMapper questionnairePromotionMapper;
  86. private final TicketAdvertiseConfigClickRecordService ticketAdvertiseConfigClickRecordService;
  87. private final GlobalThreadPoolTaskExecutor THREAD_POOL;
  88. private final ChatGptAuthService chatGptAuthService;
  89. private final GoodsCoursewareFileMapper goodsCoursewareFileMapper;
  90. private final GptTicketStandbyMapper gptTicketStandbyMapper;
  91. private final CmsOrderDonService cmsOrderDonService;
  92. private final GoodsDonSkuMapper goodsDonSkuMapper;
  93. private final AccountBlockedReplaceRecordMapper accountBlockedReplaceRecordMapper;
  94. private final OrderDonMapper orderDonMapper;
  95. private final UserGoodsNewbieGuideRecordMapper userGoodsNewbieGuideRecordMapper;
  96. private final GroupsRelationNetflixService groupsRelationNetflixService;
  97. private final static Sequence SEQUENCE = new Sequence(0);
  98. @RequestMapping("/get/renewal")
  99. public Result<SearchResult<RenewalView>> get(Boolean isLoginPopularize, String customId, String account) {
  100. long userId = StpUserUtil.getLoginIdAsLong();
  101. SearchResult<RenewalView> list = groupRelationFrontService.getMyTicket(userId, isLoginPopularize, customId, account);
  102. return GatewayResponse.SUCCESS.newBuilder().toResult(list);
  103. }
  104. @GetMapping("/get/pay/goods")
  105. public Result<List<RenewalView>> getHasPayGoods() {
  106. long userId = StpUserUtil.getLoginIdAsLong();
  107. List<RenewalView> hasPayGoods = groupRelationFrontService.getHasPayGoods(userId);
  108. return GatewayResponse.SUCCESS.newBuilder().toResult(hasPayGoods);
  109. }
  110. @PostMapping("/post/renewal")
  111. public Result<OrderDon> renewal(@RequestBody OrderPayRequest payRequest) throws Exception {
  112. long userId = StpUserUtil.getLoginIdAsLong();
  113. payRequest.setUserId(userId);
  114. String ip = ServletUtil.getClientIP(request);
  115. payRequest.setIp(ip);
  116. OrderDon orderDon = orderDonService.renewal(payRequest);
  117. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  118. }
  119. @PutMapping("/update/set/account")
  120. public Result<String> setAccount(@RequestBody GroupsRelation relation) {
  121. long userId = StpUserUtil.getLoginIdAsLong();
  122. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  123. GroupsRelation re = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  124. .eq(GroupsRelation::getId, relation.getId())
  125. .in(GroupsRelation::getUserId, userIds)
  126. .last(" limit 1"));
  127. if (re == null) {
  128. throw new BusinessRuntimeException("该车票不存在,请联系客服.");
  129. }
  130. LambdaUpdateWrapper<GroupsRelation> updateWrapper = Wrappers.lambdaUpdate(GroupsRelation.class)
  131. .set(GroupsRelation::getAccount, relation.getAccount())
  132. .set(GroupsRelation::getPassword, relation.getPassword())
  133. .eq(GroupsRelation::getId, relation.getId());
  134. if (re.getRechargeStatus() != null) {
  135. if (re.getRechargeStatus() == GroupsRelation.RechargeStatus.complete) {
  136. throw BusinessRuntimeException.getInstance("代充账号已充值");
  137. }
  138. if (StrUtil.isEmpty(relation.getAccount()) || StrUtil.isEmpty(relation.getPassword())) {
  139. throw BusinessRuntimeException.getInstance("请输入正确的账号密码信息");
  140. }
  141. if (re.getRechargeStatus() == GroupsRelation.RechargeStatus.error) {
  142. updateWrapper.set(GroupsRelation::getRechargeStatus, GroupsRelation.RechargeStatus.waiting);
  143. }
  144. }
  145. relationMapper.update(relation, updateWrapper);
  146. return GatewayResponse.SUCCESS.newBuilder().toResult();
  147. }
  148. /**
  149. * 查询是否加入了企业微信
  150. */
  151. @GetMapping("/check/joinCorpWx")
  152. public Result<Boolean> isJoinCorpWx() {
  153. long userId = StpUserUtil.getLoginIdAsLong();
  154. Boolean flag = groupRelationFrontService.isJoinCorpWx(userId, false, false);
  155. return GatewayResponse.SUCCESS.newBuilder().toResult(flag);
  156. }
  157. /**
  158. * 获取全部车票
  159. */
  160. @GetMapping("/get")
  161. public Result<List<UserTicketView>> getUserTicketView() {
  162. long userId = StpUserUtil.getLoginIdAsLong();
  163. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  164. List<UserTicketView> ticketViews = beanSearcher.searchAll(UserTicketView.class, MapUtils.flatBuilder(request.getParameterMap())
  165. .field(UserTicketView::getUserId, userIds).op(Operator.InList)
  166. .field(RenewalView::getStatus, List.of("validity", "outside")).op(Operator.InList)
  167. .orderBy(UserTicketView::getRelationId).asc()
  168. .build());
  169. return GatewayResponse.SUCCESS.newBuilder().toResult(ticketViews);
  170. }
  171. /**
  172. * 记录查看ChatGPT车票密码
  173. */
  174. @GetMapping("/recordView/{relationId}")
  175. public Result<String> recordGPTPwdView(@PathVariable Long relationId) {
  176. long userId = StpUserUtil.getLoginIdAsLong();
  177. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  178. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  179. .field(GroupsRelationView::getUserId, userIds).op(Operator.InList)
  180. .field(GroupsRelationView::getId, relationId).build());
  181. if (groupsRelationView == null) {
  182. log.info("userId:{}查看relationId:{}车票不存在", userId, relationId);
  183. throw BusinessRuntimeException.getInstance("该车票已不存在");
  184. }
  185. if (groupsRelationView.getAccountId() == null) throw BusinessRuntimeException.getInstance("该车队未配置账号");
  186. if (groupRelationFrontService == null) throw BusinessRuntimeException.getInstance("车票已不存在");
  187. TicketPwdViewRecord viewRecord = new TicketPwdViewRecord();
  188. viewRecord.setUserId(userId);
  189. viewRecord.setRelationId(relationId);
  190. viewRecord.setSkuId(groupsRelationView.getSkuId());
  191. viewRecord.setOperateLocation(ServletUtil.getClientIP(request));
  192. viewRecord.setAccount(groupsRelationView.getTripsAccount());
  193. viewRecord.setPassword(groupsRelationView.getTripsPassword());
  194. ticketPwdViewRecordMapper.insert(viewRecord);
  195. if (groupsRelationView.getGoodsId() == 18 && StrUtil.isEmpty(groupsRelationView.getApiSecret())) {
  196. THREAD_POOL.execute(() -> {
  197. //车队所有人查看密码
  198. Integer num = groupsRelationView.getGtNum();
  199. Integer viewNum = relationMapper.selectViewPwdCount(groupsRelationView.getGroupsId());
  200. if (num <= viewNum) {
  201. AccountDoubleVerifyRecord exist = accountDoubleVerifyRecordMapper.selectOne(Wrappers.lambdaQuery(AccountDoubleVerifyRecord.class)
  202. .eq(AccountDoubleVerifyRecord::getAccountId, groupsRelationView.getAccountId())
  203. .eq(AccountDoubleVerifyRecord::getDeleted, true).last("limit 1"));
  204. if (exist == null) {
  205. if (redisService.setNx(String.format("%s-%s", groupsRelationView.getAccountId(), groupsRelationView.getId()), groupsRelationView.getId(), 60l)) {
  206. //记录
  207. AccountDoubleVerifyRecord accountDoubleVerifyRecord = new AccountDoubleVerifyRecord();
  208. accountDoubleVerifyRecord.setAccountId(groupsRelationView.getAccountId());
  209. accountDoubleVerifyRecord.setAccount(groupsRelationView.getTripsAccount());
  210. accountDoubleVerifyRecord.setGroupsId(groupsRelationView.getGroupsId());
  211. accountDoubleVerifyRecord.setSkuId(groupsRelationView.getSkuId());
  212. accountDoubleVerifyRecord.setRemark("车队所有人看过密码");
  213. accountDoubleVerifyRecordMapper.insert(accountDoubleVerifyRecord);
  214. }
  215. }
  216. }
  217. });
  218. }
  219. return GatewayResponse.SUCCESS.newBuilder().toResult(groupsRelationView.getTripsPassword());
  220. }
  221. /**
  222. * 获取AI类 ChatGPT产品谷歌验证码
  223. */
  224. @GetMapping("/get/authCode")
  225. public Result<String> getAuthCode(Long relationId) {
  226. long userId = StpUserUtil.getLoginIdAsLong();
  227. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  228. if (relationId == null) throw BusinessRuntimeException.getInstance("车票不存在");
  229. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  230. .field(GroupsRelationView::getId, relationId)
  231. .field(GroupsRelationView::getUserId, userIds).op(Operator.InList).build());
  232. if (groupsRelationView == null) throw BusinessRuntimeException.getInstance("车票不存在");
  233. if (StrUtil.isEmpty(groupsRelationView.getApiSecret())) throw BusinessRuntimeException.getInstance("未开启验证");
  234. DateTime now = DateTime.now();
  235. Integer count = doubleVerifyRecordMapper.selectCount(Wrappers.lambdaQuery(DoubleVerifyClickRecord.class)
  236. .in(DoubleVerifyClickRecord::getUserId, userIds)
  237. .eq(DoubleVerifyClickRecord::getRelationId, relationId)
  238. .eq(DoubleVerifyClickRecord::getAccountId, groupsRelationView.getAccountId())
  239. .between(DoubleVerifyClickRecord::getCreatedTime, DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now)));
  240. //获取双重验证码
  241. Boolean isHasVerifyCode = StrUtil.isNotBlank(groupsRelationView.getVerifyCode()) ? true : false;
  242. //出去亚马逊 获取限制
  243. if (groupsRelationView.getGoodsId() != 6) {
  244. Integer num = groupRelationFrontService.getUserCodeNumBySkuId(userId, groupsRelationView.getSkuId(), isHasVerifyCode);
  245. if (count >= num) throw BusinessRuntimeException.getInstance("获取双重验证码次数上限");
  246. }
  247. //一分钟内 只能一人获取
  248. boolean b = redisService.setNx(RedisService.key.DOUBLE_VERIFY_CODE_VIEW_MINUTES_KEY.getEnvName() + groupsRelationView.getTripsAccount(), relationId, RedisService.key.DOUBLE_VERIFY_CODE_VIEW_MINUTES_KEY.getTimeout());
  249. if (!b) {
  250. throw BusinessRuntimeException.getInstance("一分钟内已有人获取该账号验证码,请稍后获取..");
  251. }
  252. int second = now.second();
  253. if (second < 30 && 30 - second < 3) {
  254. ThreadUtil.sleep(30 - second + 1, TimeUnit.SECONDS);
  255. } else if (second > 30 && 60 - second < 3) {
  256. ThreadUtil.sleep(60 - second + 1, TimeUnit.SECONDS);
  257. }
  258. StringBuilder sb = new StringBuilder();
  259. JSONObject re = new JSONObject();
  260. try {
  261. long code = GoogleGenerator.getCode(groupsRelationView.getApiSecret(), now.getTime());
  262. sb.append(code);
  263. while (sb.length() < 6) {
  264. sb.insert(0, 0);
  265. }
  266. re.putOpt("code", sb.toString());
  267. int nowSecond = DateTime.now().second();
  268. int time = 0;
  269. if (nowSecond < 30) {
  270. time = 30 - nowSecond;
  271. } else {
  272. time = 60 - nowSecond;
  273. }
  274. re.putOpt("time", time);
  275. DoubleVerifyClickRecord doubleVerifyClickRecord = new DoubleVerifyClickRecord();
  276. doubleVerifyClickRecord.setRelationId(relationId);
  277. doubleVerifyClickRecord.setUserId(userId);
  278. doubleVerifyClickRecord.setAccountId(groupsRelationView.getAccountId());
  279. doubleVerifyClickRecord.setAccount(groupsRelationView.getTripsAccount());
  280. doubleVerifyClickRecord.setSkuId(groupsRelationView.getSkuId());
  281. doubleVerifyClickRecord.setCode(sb.toString());
  282. doubleVerifyClickRecord.setRemainTime(time);
  283. doubleVerifyRecordMapper.insert(doubleVerifyClickRecord);
  284. DoubleVerifyDto doubleVerifyDto = new DoubleVerifyDto();
  285. doubleVerifyDto.setClickId(doubleVerifyClickRecord.getId());
  286. doubleVerifyDto.setApiSecret(groupsRelationView.getApiSecret());
  287. redisService.set(String.format("%s-%s", userId, sb.toString()), 0, 60 * 10l);
  288. redisService.set(String.format("%s/%s", userId, sb.toString()), Jsons.toJson(doubleVerifyDto), 60 * 10l);
  289. } catch (Exception e) {
  290. throw BusinessRuntimeException.getInstance("获取双重验证码错误,请联系客服");
  291. }
  292. return GatewayResponse.SUCCESS.newBuilder().toResult(re.toString());
  293. }
  294. /**
  295. * 刷新验证码
  296. */
  297. @GetMapping("/refresh/code")
  298. public Result<String> refreshCode(String code) {
  299. long userId = StpUserUtil.getLoginIdAsLong();
  300. String numKey = String.format("%s-%s", userId, code);
  301. Object num = redisService.get(numKey);
  302. String objKey = String.format("%s/%s", userId, code);
  303. Object objValue = redisService.get(objKey);
  304. if (objValue == null || num == null) {
  305. throw BusinessRuntimeException.getInstance("请重新获取双重验证码");
  306. }
  307. Integer refreshNum = Integer.parseInt(num.toString());
  308. String apiSecret = null;
  309. Long clickId = 0l;
  310. try {
  311. DoubleVerifyDto dto = Jsons.parseObject(objValue.toString(), DoubleVerifyDto.class);
  312. apiSecret = dto.getApiSecret();
  313. clickId = dto.getClickId();
  314. } catch (Exception e) {
  315. apiSecret = objValue.toString();
  316. }
  317. if (refreshNum >= 3) {
  318. redisService.del(numKey);
  319. redisService.del(objKey);
  320. throw BusinessRuntimeException.getInstance("刷新次数已达到3次,请重新获取验证码");
  321. }
  322. if (apiSecret == null) {
  323. throw BusinessRuntimeException.getInstance("请重新获取双重验证码");
  324. }
  325. StringBuilder sb = new StringBuilder();
  326. try {
  327. long c = GoogleGenerator.getCode(apiSecret, DateTime.now().getTime());
  328. sb.append(c);
  329. while (sb.length() < 6) {
  330. sb.insert(0, 0);
  331. }
  332. redisService.incr(numKey, 1l);
  333. } catch (Exception e) {
  334. throw BusinessRuntimeException.getInstance("刷新双重验证码错误,请联系客服");
  335. }
  336. if (clickId != 0) {
  337. int nowSecond = DateTime.now().second();
  338. int time = 0;
  339. if (nowSecond < 30) {
  340. time = 30 - nowSecond;
  341. } else {
  342. time = 60 - nowSecond;
  343. }
  344. //刷新双重验证码记录
  345. DoubleVerifyClickRefreshRecord refreshRecord = new DoubleVerifyClickRefreshRecord();
  346. refreshRecord.setClickId(clickId);
  347. refreshRecord.setUserId(userId);
  348. refreshRecord.setCode(sb.toString());
  349. refreshRecord.setRemainTime(time);
  350. refreshRecordMapper.insert(refreshRecord);
  351. }
  352. return GatewayResponse.SUCCESS.newBuilder().toResult(sb.toString());
  353. }
  354. /**
  355. * 获取双重验证码记录
  356. */
  357. @GetMapping("/get/doubleVerify/codeList")
  358. public Result<List<DoubleVerifyCodeView>> getDoubleVerifyCodeList(Long relationId) {
  359. long userId = StpUserUtil.getLoginIdAsLong();
  360. List<DoubleVerifyCodeView> views = doubleVerifyRecordMapper.getDoubleVerifyCodeList(userId, relationId);
  361. return GatewayResponse.SUCCESS.newBuilder().toResult(views);
  362. }
  363. /**
  364. * 用户是不是自然流量渠道
  365. * 且未回答答题
  366. */
  367. @GetMapping("/natural/channel")
  368. public Result<Boolean> isNaturalChannel() {
  369. long userId = StpUserUtil.getLoginIdAsLong();
  370. String question_key = RedisService.key.QUESTION_RESPONSE_KEY.getNameFormat(userId);
  371. if (redisService.get(question_key) != null) {
  372. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  373. }
  374. User user = userService.getById(userId);
  375. if (user.getPopularizeId() != 0) {
  376. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  377. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  378. }
  379. if (user.getPopularizeId() == 0) {
  380. QuestionResponseRecord record = questionResponseRecordMapper.selectOne(Wrappers.lambdaQuery(QuestionResponseRecord.class)
  381. .eq(QuestionResponseRecord::getUserId, userId).select(QuestionResponseRecord::getId).last("limit 1"));
  382. if (record != null) {
  383. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  384. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  385. }
  386. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  387. }
  388. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  389. }
  390. /**
  391. * 问卷记录
  392. */
  393. @PostMapping("/record/replyQuestion")
  394. public Result<String> recordReplyQuestion(@RequestBody @Validated QuestionResponseRecord record) {
  395. long userId = StpUserUtil.getLoginIdAsLong();
  396. User user = userService.getById(userId);
  397. String nickname = user.getNickname();
  398. String question_key = RedisService.key.QUESTION_RESPONSE_KEY.getNameFormat(userId);
  399. QuestionResponseRecord dbRecord = questionResponseRecordMapper.selectOne(Wrappers.lambdaQuery(QuestionResponseRecord.class)
  400. .eq(QuestionResponseRecord::getUserId, userId).select(QuestionResponseRecord::getId).last("limit 1"));
  401. if (dbRecord == null) {
  402. if (redisService.setNx(String.format("%s-%s", userId, nickname), userId, 10l)) {
  403. record.setUserId(userId);
  404. record.setNickname(nickname);
  405. questionResponseRecordMapper.insert(record);
  406. //发放优惠券
  407. couponCommonService.sendCouponToUser(userId, 100l, 0l, 0l, 0l, CouponUser.Channel.ques_response);
  408. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  409. }
  410. }
  411. return GatewayResponse.SUCCESS.newBuilder().toResult();
  412. }
  413. /**
  414. * 获取对应的动态问卷
  415. */
  416. @GetMapping("/get/questionnaire")
  417. public Result<List<QuestionnaireView>> getQuestionnaireView(Long promotionId) {
  418. QuestionnairePromotion promotion = questionnairePromotionMapper.selectById(promotionId);
  419. if (promotion == null || !promotion.getDeleted()) throw BusinessRuntimeException.getInstance("问卷不存在");
  420. Long templateId = promotion.getTemplateId();
  421. List<QuestionnaireView> questionnaireViews = beanSearcher.searchAll(QuestionnaireView.class, MapUtils.builder()
  422. .field(QuestionnaireView::getPromotionId, promotionId)
  423. .orderBy(QuestionnaireView::getSorted).asc()
  424. .orderBy(QuestionnaireView::getFieldsId).asc()
  425. .build());
  426. return GatewayResponse.SUCCESS.newBuilder().toResult(questionnaireViews);
  427. }
  428. /**
  429. * 记录问卷
  430. */
  431. @PostMapping("/record/questionnaire/{promotionId}")
  432. @Transactional(rollbackFor = Exception.class)
  433. @NoSubmit
  434. public Result<String> recordQuestionnaire(@PathVariable Long promotionId, @RequestBody List<FormFieldsData> answers) {
  435. Long groupsId = SEQUENCE.nextId();
  436. List<QuestionnairePromotionFieldsListView> promotionFieldsListViews = beanSearcher.searchAll(QuestionnairePromotionFieldsListView.class, MapUtils.builder().field(QuestionnairePromotionFieldsListView::getPromotionId, promotionId).build());
  437. if (CollUtil.isEmpty(promotionFieldsListViews)) throw BusinessRuntimeException.getInstance("问卷已结束");
  438. if (promotionFieldsListViews.size() != answers.size()) throw BusinessRuntimeException.getInstance("请完成所有问题");
  439. answers.forEach(answer -> {
  440. Long fieldsId = answer.getFieldsId();
  441. String content = answer.getContent();
  442. if (fieldsId == null || StrUtil.isBlank(content)) {
  443. throw BusinessRuntimeException.getInstance("必填项为空");
  444. }
  445. answer.setPromotionId(promotionId);
  446. answer.setGroupsId(groupsId);
  447. formFieldsDataMapper.insert(answer);
  448. });
  449. return GatewayResponse.SUCCESS.newBuilder().toResult();
  450. }
  451. /**
  452. * 对应平台车票 广告配置列表
  453. */
  454. @GetMapping("/get/advertise/{goodsId}")
  455. public Result<List<TicketAdvertiseConfigFrontView>> getTicketAdvertiseConfig(@PathVariable Long goodsId) {
  456. List<TicketAdvertiseConfigFrontView> views = beanSearcher.searchAll(TicketAdvertiseConfigFrontView.class, MapUtils.flatBuilder(request.getParameterMap())
  457. .field(TicketAdvertiseConfig::getGoodsId, goodsId)
  458. .orderBy(TicketAdvertiseConfig::getSorted).desc()
  459. .orderBy(TicketAdvertiseConfig::getId).desc()
  460. .build());
  461. return GatewayResponse.SUCCESS.newBuilder().toResult(views);
  462. }
  463. /**
  464. * 记录用户点击车票广告
  465. */
  466. @PostMapping("/click/ticket/advertise/record/{configId}")
  467. public Result<String> recordClickTicketAdvertise(@PathVariable Long configId) {
  468. long userId = StpUserUtil.getLoginIdAsLong();
  469. ticketAdvertiseConfigClickRecordService.recordUserClickTicketAdvertise(userId, configId);
  470. return GatewayResponse.SUCCESS.newBuilder().toResult();
  471. }
  472. /**
  473. * 推荐平台
  474. */
  475. @GetMapping("/get/recommend/goods")
  476. public Result<Page<UserRecommendGoodsFrontView>> getRecommendGoodsViews(@RequestParam(defaultValue = "0") Integer start, @RequestParam(defaultValue = "5") Integer limit) {
  477. //推荐用户未购买的车票平台 优先展示ai类平台 然后是影视流媒体
  478. long userId = StpUserUtil.getLoginIdAsLong();
  479. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  480. List<Long> filter_goods_id = relationMapper.getTicketGoodsId(userIds, List.of("validity", "overdue", "outside"));
  481. //用户是否购买过奈飞产品
  482. Boolean isPayNf = false;
  483. if (filter_goods_id.contains(1l)) {
  484. isPayNf = true;
  485. } else {
  486. int count = orderDonService.count(Wrappers.lambdaQuery(OrderDon.class)
  487. .eq(OrderDon::getGoodsId, 1)
  488. .eq(OrderDon::getUserId, userId)
  489. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
  490. if (count > 0) {
  491. //优先展示路由器、ai、流媒体
  492. isPayNf = true;
  493. }
  494. }
  495. Boolean filterCourseGoods = false;
  496. //GPT Plus基础2月 课程不展示
  497. Integer orders = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
  498. .in(OrderDon::getUserId, userIds)
  499. .eq(OrderDon::getSkuId, 444)
  500. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  501. if (orders > 0) {
  502. filterCourseGoods = true;
  503. }
  504. Page<UserRecommendGoodsFrontView> page = groupRelationFrontService.getRecommendGoodsViews(isPayNf, filter_goods_id, filterCourseGoods, start, limit);
  505. return GatewayResponse.SUCCESS.newBuilder().toResult(page);
  506. }
  507. /**
  508. * 查看GPT token
  509. */
  510. @GetMapping("/get/gptAccessToken")
  511. public Result<String> getGptAccessToken(Long relationId) throws Exception {
  512. long userId = StpUserUtil.getLoginIdAsLong();
  513. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  514. //存在该车票
  515. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  516. .field(RenewalView::getRelationId, relationId)
  517. .field(RenewalView::getUserId, userIds).op(Operator.InList).build());
  518. Assert.notNull(renewalView, "您的车票不存在");
  519. if (renewalView.getGoodsId() != 42) {
  520. throw BusinessRuntimeException.getInstance("该平台类型车票无法获取GPT直连token");
  521. }
  522. String account = renewalView.getAccount();
  523. String accessToken = chatGptAuthService.getAccessToken(account);
  524. return GatewayResponse.SUCCESS.newBuilder().toResult(accessToken);
  525. }
  526. /**
  527. * 获取特殊类型课程 通过邮件发送课程
  528. * 领取课件
  529. */
  530. @PostMapping("/courseware")
  531. public Result<String> getCourseWare(@RequestBody SpecialGoodsTicketReq request) throws Exception {
  532. long userId = StpUserUtil.getLoginIdAsLong();
  533. request.setUserId(userId);
  534. groupRelationFrontService.sendCourseWare(request);
  535. return GatewayResponse.SUCCESS.newBuilder().toResult();
  536. }
  537. //获取课程云盘链接
  538. @GetMapping("/get/courseware")
  539. public Result<GoodsCoursewareFile> getGoodsCourseware(Long relationId) {
  540. long userId = StpUserUtil.getLoginIdAsLong();
  541. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  542. RenewalView relationView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  543. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  544. .field(RenewalView::getRelationId, relationId).build());
  545. if (relationView == null) {
  546. throw BusinessRuntimeException.getInstance("您的车票不存在");
  547. }
  548. GoodsCoursewareFile goodsCoursewareFile = goodsCoursewareFileMapper.selectOne(Wrappers.lambdaQuery(GoodsCoursewareFile.class)
  549. .eq(GoodsCoursewareFile::getGoodsId, relationView.getGoodsId())
  550. .eq(GoodsCoursewareFile::getStatus, true)
  551. .select(GoodsCoursewareFile::getLink, GoodsCoursewareFile::getCode)
  552. .last("limit 1"));
  553. if (goodsCoursewareFile == null) {
  554. throw BusinessRuntimeException.getInstance("暂未配置课件链接地址,请联系客服");
  555. }
  556. return GatewayResponse.SUCCESS.newBuilder().toResult(goodsCoursewareFile);
  557. }
  558. /**
  559. * 读取车票账号登录验证码
  560. */
  561. @GetMapping("/get/verifyCode/{relationId}")
  562. public Result<String> getAiVerifyCode(@PathVariable Long relationId, Integer type, @RequestParam(defaultValue = "0") Boolean sync) throws Exception {
  563. long userId = StpUserUtil.getLoginIdAsLong();
  564. return GatewayResponse.SUCCESS.newBuilder().toResult(groupRelationFrontService.getAiVerifyCode(userId, relationId, type, sync));
  565. }
  566. /**
  567. * 是否有mid车票可候补
  568. */
  569. @GetMapping("/get/standby")
  570. public Result<GptStandbyResp> getGptStandby() {
  571. long userId = StpUserUtil.getLoginIdAsLong();
  572. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  573. String condition = "(a.account like '%@yinhe.ac.cn%' or exists (select id from account_blocked_replace_record abrr where abrr.account = a.account and abrr.goods_id = g.id limit 1))";
  574. List<RenewalView> renewalViewList = beanSearcher.searchAll(RenewalView.class, MapUtils.builder()
  575. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  576. .field(RenewalView::getGoodsId, 26)
  577. .put("condition", condition)
  578. .field(RenewalView::getExpiryTime).op(Operator.NotNull)
  579. .onlySelect(RenewalView::getAccount, RenewalView::getExpiryTime)
  580. .build());
  581. GptStandbyResp gptStandbyResp = new GptStandbyResp();
  582. if (renewalViewList.isEmpty()) {
  583. gptStandbyResp.setIsHasAccount(false);
  584. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  585. }
  586. List<RenewalView> overTen = new ArrayList<>();
  587. List<RenewalView> underTen = new ArrayList<>();
  588. DateTime now = DateTime.now();
  589. renewalViewList.forEach(e -> {
  590. if (e.getExpiryTime().compareTo(DateUtil.offsetDay(now, 10)) > 0) {
  591. overTen.add(e);
  592. } else underTen.add(e);
  593. });
  594. Integer accountBlockedCount = 1;
  595. if (overTen.size() > 1) {
  596. List<String> accountList = overTen.stream().map(RenewalView::getAccount).distinct().collect(Collectors.toList());
  597. accountBlockedCount = accountBlockedReplaceRecordMapper.selectCount(Wrappers.lambdaQuery(AccountBlockedReplaceRecord.class)
  598. .eq(AccountBlockedReplaceRecord::getGoodsId, 26)
  599. .in(AccountBlockedReplaceRecord::getAccount, accountList));
  600. }
  601. if (accountBlockedCount > 1) {
  602. gptStandbyResp.setIsHasAccount(false);
  603. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  604. }
  605. gptStandbyResp.setIsHasAccount(true);
  606. gptStandbyResp.setOverTen(overTen);
  607. gptStandbyResp.setUnderTen(underTen);
  608. Integer count = gptTicketStandbyMapper.selectCount(Wrappers.lambdaQuery(GptTicketStandby.class)
  609. .in(GptTicketStandby::getUserId, relationUserIdList));
  610. gptStandbyResp.setIsApply(count > 0 ? true : false);
  611. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  612. }
  613. /**
  614. * 申请候补
  615. */
  616. @PostMapping("/apply/standby")
  617. @NoSubmit
  618. public Result<Boolean> applyGptStandby() {
  619. long userId = StpUserUtil.getLoginIdAsLong();
  620. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  621. String condition = "(a.account like '%@yinhe.ac.cn%' or exists (select id from account_blocked_replace_record abrr where abrr.account = a.account and abrr.goods_id = g.id limit 1))";
  622. List<RenewalView> renewalViewList = beanSearcher.searchAll(RenewalView.class, MapUtils.builder()
  623. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  624. .field(RenewalView::getGoodsId, 26)
  625. .put("condition", condition)
  626. .field(RenewalView::getExpiryTime, DateUtil.offsetDay(DateTime.now(), 10)).op(Operator.GreaterThan)
  627. .onlySelect(RenewalView::getAccount)
  628. .build());
  629. if (renewalViewList.isEmpty()) {
  630. throw BusinessRuntimeException.getInstance("你未有车票账号");
  631. }
  632. Integer count = gptTicketStandbyMapper.selectCount(Wrappers.lambdaQuery(GptTicketStandby.class)
  633. .in(GptTicketStandby::getUserId, relationUserIdList));
  634. if (count > 0) {
  635. throw BusinessRuntimeException.getInstance("你已申请车票账号候补");
  636. }
  637. if (renewalViewList.size() > 1) {
  638. Set<String> accountSet = renewalViewList.stream().map(RenewalView::getAccount).collect(Collectors.toSet());
  639. Integer accountBlockedCount = accountBlockedReplaceRecordMapper.selectCount(Wrappers.lambdaQuery(AccountBlockedReplaceRecord.class)
  640. .eq(AccountBlockedReplaceRecord::getGoodsId, 26)
  641. .in(AccountBlockedReplaceRecord::getAccount, accountSet));
  642. if (accountBlockedCount > 1) {
  643. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  644. }
  645. }
  646. GptTicketStandby gptTicketStandby = new GptTicketStandby();
  647. gptTicketStandby.setUserId(userId);
  648. gptTicketStandbyMapper.insert(gptTicketStandby);
  649. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  650. }
  651. /**
  652. * midjourney车票退款
  653. */
  654. @PutMapping("/refund/ticketOrder/{relationId}")
  655. @NoSubmit
  656. public Result<String> ticketRefundOrders(@PathVariable Long relationId) throws Exception {
  657. long userId = StpUserUtil.getLoginIdAsLong();
  658. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  659. String condition = "(a.account like '%@yinhe.ac.cn%' or exists (select id from account_blocked_replace_record abrr where abrr.account = a.account and abrr.goods_id = g.id limit 1))";
  660. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  661. .field(RenewalView::getRelationId, relationId)
  662. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  663. .put("condition", condition)
  664. .field(RenewalView::getGoodsId, 26)
  665. .field(RenewalView::getExpiryTime, DateUtil.offsetDay(DateTime.now(), 10)).op(Operator.LessEqual)
  666. .build());
  667. if (renewalView == null) {
  668. throw BusinessRuntimeException.getInstance("你车票不存在或不符合退款要求");
  669. }
  670. OrderDon orderDon = orderDonService.getOne(Wrappers.lambdaQuery(OrderDon.class)
  671. .in(OrderDon::getUserId, relationUserIdList)
  672. .eq(OrderDon::getRelationId, relationId)
  673. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  674. .orderByDesc(OrderDon::getId)
  675. .last("limit 1"));
  676. if (orderDon == null) {
  677. throw BusinessRuntimeException.getInstance("你对应车票的订单不存在");
  678. }
  679. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  680. if (sku == null) {
  681. throw BusinessRuntimeException.getInstance("该车票规格不存在,请联系客服进行人工退款..");
  682. }
  683. Date expiryTime = renewalView.getExpiryTime();
  684. long remainDay = DateUtil.between(DateTime.now(), expiryTime, DateUnit.DAY) + 1;
  685. BigDecimal money = orderDon.getMoney();
  686. BigDecimal refundMoney = null;
  687. BigDecimal refundBalance= null;
  688. String refundType = null;
  689. if (money.compareTo(BigDecimal.ZERO) > 0) {
  690. BigDecimal dayMoney = money.divide(BigDecimal.valueOf(sku.getMonths()).multiply(BigDecimal.valueOf(30)), 2, RoundingMode.HALF_DOWN);
  691. refundMoney = BigDecimal.valueOf(remainDay).multiply(dayMoney);
  692. refundType = "money";
  693. }
  694. OrderRefundReq refundReq = new OrderRefundReq();
  695. if (orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  696. BigDecimal dayMoney = orderDon.getBalance().divide(BigDecimal.valueOf(sku.getMonths()).multiply(BigDecimal.valueOf(30)), 2, RoundingMode.HALF_DOWN);
  697. refundBalance = BigDecimal.valueOf(remainDay).multiply(dayMoney);
  698. refundReq.setIsOnly(true);
  699. }
  700. refundReq.setOrderId(orderDon.getId());
  701. refundReq.setRefundDesc("失效车票退款");
  702. refundReq.setRefundMoney(Optional.ofNullable(refundMoney).orElse(BigDecimal.ZERO));
  703. refundReq.setRefundBalance(Optional.ofNullable(refundBalance).orElse(BigDecimal.ZERO));
  704. refundReq.setRefundType(Optional.ofNullable(refundType).orElse("balance"));
  705. cmsOrderDonService.unifiedRefund(refundReq);
  706. return GatewayResponse.SUCCESS.newBuilder().toResult();
  707. }
  708. /**
  709. * 每日车票到期弹窗
  710. */
  711. @GetMapping("/get/expiry/notify")
  712. public Result<List<RenewalView>> getExpiryRenewalNotify() {
  713. Long userId = StpUserUtil.getLoginIdAsLong();
  714. List<RenewalView> expiryRenewals = groupRelationFrontService.getExpiryRenewalNotify(userId);
  715. return GatewayResponse.SUCCESS.newBuilder().toResult(expiryRenewals);
  716. }
  717. /**
  718. * 车票详情
  719. */
  720. @GetMapping("/get/detail")
  721. public Result<RenewalView> getTicketDetail(Long relationId) {
  722. if (relationId == null) {
  723. return GatewayResponse.SUCCESS.newBuilder().toResult();
  724. }
  725. long userId = StpUserUtil.getLoginIdAsLong();
  726. RenewalView ticketDetail = groupRelationFrontService.getTicketDetail(userId, relationId);
  727. return GatewayResponse.SUCCESS.newBuilder().toResult(ticketDetail);
  728. }
  729. /**
  730. * 车票售后常见问题
  731. */
  732. @GetMapping("/get/questions/{goodsId}")
  733. public Result<List<GoodsDonQaFrontView>> getTicketQuestions(@PathVariable Long goodsId, @RequestParam(defaultValue = "1") Integer type) {
  734. if (type < 1 || type > 2) {
  735. return GatewayResponse.SUCCESS.newBuilder().toResult();
  736. }
  737. String key = RedisService.key.YH_GOODS_QUESTIONS_DETAIL.getNameFormat(type, goodsId);
  738. Object o = redisService.get(key);
  739. if (o == null) {
  740. List<GoodsDonQaFrontView> donQaFrontViews = beanSearcher.searchAll(GoodsDonQaFrontView.class, MapUtils.builder().field(GoodsDonQaFrontView::getGoodsId, goodsId).field(GoodsDonQaFrontView::getType, type).build());
  741. if (CollUtil.isEmpty(donQaFrontViews)) {
  742. return GatewayResponse.SUCCESS.newBuilder().toResult();
  743. }
  744. redisService.setNx(key, donQaFrontViews, RedisService.key.YH_GOODS_QUESTIONS_DETAIL.getTimeout());
  745. o = redisService.get(key);
  746. }
  747. List<GoodsDonQaFrontView> donQaFrontViews = Jsons.parseList(o, GoodsDonQaFrontView.class);
  748. return GatewayResponse.SUCCESS.newBuilder().toResult(donQaFrontViews);
  749. }
  750. /**
  751. * 是否首次购买车票
  752. */
  753. @GetMapping("/get/first/pay/{goodsId}")
  754. public Result<Boolean> getFirstPay(@PathVariable Long goodsId) {
  755. long userId = StpUserUtil.getLoginIdAsLong();
  756. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  757. Number number = beanSearcher.searchCount(OrderDon.class, MapUtils.builder()
  758. .field(OrderDon::getGoodsId, goodsId)
  759. .field(OrderDon::getCreatedTime, new DateTime().toDateStr()).op(Operator.LessEqual)
  760. .field(OrderDon::getUserId, userIdList).op(Operator.InList)
  761. .field(OrderDon::getStatus, Constant.noOrderStatus).op(Operator.NotIn)
  762. .build());
  763. if (number.intValue() == 0) {
  764. UserGoodsNewbieGuideRecord userGoodsNewbieGuideRecord = new UserGoodsNewbieGuideRecord();
  765. userGoodsNewbieGuideRecord.setGoodsId(goodsId);
  766. userGoodsNewbieGuideRecord.setUserId(userId);
  767. userGoodsNewbieGuideRecordMapper.insert(userGoodsNewbieGuideRecord);
  768. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  769. }
  770. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  771. }
  772. /**
  773. * 设置pin码
  774. */
  775. @PutMapping("/set/pin/{relationId}")
  776. public Result<String> setPin(@PathVariable Long relationId) {
  777. long userId = StpUserUtil.getLoginIdAsLong();
  778. JSONObject data = groupsRelationNetflixService.setNetflixPin(relationId, userId);
  779. return GatewayResponse.SUCCESS.newBuilder().toResult(data.toString());
  780. }
  781. /**
  782. * 查询是否设置成功
  783. */
  784. @GetMapping("/get/pin/status/{taskId}")
  785. public Result<Integer> getPinStatus(@PathVariable String taskId) throws Exception {
  786. return GatewayResponse.SUCCESS.newBuilder().toResult(groupsRelationNetflixService.getPinStatus(taskId));
  787. }
  788. }