GroupRelationController.java 37 KB

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