GroupRelationController.java 40 KB

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