GroupRelationController.java 37 KB

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