GroupRelationController.java 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. //出去亚马逊 获取限制
  239. if (groupsRelationView.getGoodsId() != 6) {
  240. Integer num = groupRelationFrontService.getUserCodeNumBySkuId(userId, groupsRelationView.getSkuId(), isHasVerifyCode);
  241. if (count >= num) throw BusinessRuntimeException.getInstance("获取双重验证码次数上限");
  242. }
  243. //一分钟内 只能一人获取
  244. 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());
  245. if (!b) {
  246. throw BusinessRuntimeException.getInstance("一分钟内已有人获取该账号验证码,请稍后获取..");
  247. }
  248. int second = now.second();
  249. if (second < 30 && 30 - second < 3) {
  250. ThreadUtil.sleep(30 - second + 1, TimeUnit.SECONDS);
  251. } else if (second > 30 && 60 - second < 3) {
  252. ThreadUtil.sleep(60 - second + 1, TimeUnit.SECONDS);
  253. }
  254. StringBuilder sb = new StringBuilder();
  255. JSONObject re = new JSONObject();
  256. try {
  257. long code = GoogleGenerator.getCode(groupsRelationView.getApiSecret(), now.getTime());
  258. sb.append(code);
  259. while (sb.length() < 6) {
  260. sb.insert(0, 0);
  261. }
  262. re.putOpt("code", sb.toString());
  263. int nowSecond = DateTime.now().second();
  264. int time = 0;
  265. if (nowSecond < 30) {
  266. time = 30 - nowSecond;
  267. } else {
  268. time = 60 - nowSecond;
  269. }
  270. re.putOpt("time", time);
  271. DoubleVerifyClickRecord doubleVerifyClickRecord = new DoubleVerifyClickRecord();
  272. doubleVerifyClickRecord.setRelationId(relationId);
  273. doubleVerifyClickRecord.setUserId(userId);
  274. doubleVerifyClickRecord.setAccountId(groupsRelationView.getAccountId());
  275. doubleVerifyClickRecord.setAccount(groupsRelationView.getTripsAccount());
  276. doubleVerifyClickRecord.setSkuId(groupsRelationView.getSkuId());
  277. doubleVerifyClickRecord.setCode(sb.toString());
  278. doubleVerifyClickRecord.setRemainTime(time);
  279. doubleVerifyRecordMapper.insert(doubleVerifyClickRecord);
  280. DoubleVerifyDto doubleVerifyDto = new DoubleVerifyDto();
  281. doubleVerifyDto.setClickId(doubleVerifyClickRecord.getId());
  282. doubleVerifyDto.setApiSecret(groupsRelationView.getApiSecret());
  283. redisService.set(String.format("%s-%s", userId, sb.toString()), 0, 60 * 10l);
  284. redisService.set(String.format("%s/%s", userId, sb.toString()), Jsons.toJson(doubleVerifyDto), 60 * 10l);
  285. } catch (Exception e) {
  286. throw BusinessRuntimeException.getInstance("获取双重验证码错误,请联系客服");
  287. }
  288. return GatewayResponse.SUCCESS.newBuilder().toResult(re.toString());
  289. }
  290. /**
  291. * 刷新验证码
  292. */
  293. @GetMapping("/refresh/code")
  294. public Result<String> refreshCode(String code) {
  295. long userId = StpUserUtil.getLoginIdAsLong();
  296. String numKey = String.format("%s-%s", userId, code);
  297. Object num = redisService.get(numKey);
  298. String objKey = String.format("%s/%s", userId, code);
  299. Object objValue = redisService.get(objKey);
  300. if (objValue == null || num == null) {
  301. throw BusinessRuntimeException.getInstance("请重新获取双重验证码");
  302. }
  303. Integer refreshNum = Integer.parseInt(num.toString());
  304. String apiSecret = null;
  305. Long clickId = 0l;
  306. try {
  307. DoubleVerifyDto dto = Jsons.parseObject(objValue.toString(), DoubleVerifyDto.class);
  308. apiSecret = dto.getApiSecret();
  309. clickId = dto.getClickId();
  310. } catch (Exception e) {
  311. apiSecret = objValue.toString();
  312. }
  313. if (refreshNum >= 3) {
  314. redisService.del(numKey);
  315. redisService.del(objKey);
  316. throw BusinessRuntimeException.getInstance("刷新次数已达到3次,请重新获取验证码");
  317. }
  318. if (apiSecret == null) {
  319. throw BusinessRuntimeException.getInstance("请重新获取双重验证码");
  320. }
  321. StringBuilder sb = new StringBuilder();
  322. try {
  323. long c = GoogleGenerator.getCode(apiSecret, DateTime.now().getTime());
  324. sb.append(c);
  325. while (sb.length() < 6) {
  326. sb.insert(0, 0);
  327. }
  328. redisService.incr(numKey, 1l);
  329. } catch (Exception e) {
  330. throw BusinessRuntimeException.getInstance("刷新双重验证码错误,请联系客服");
  331. }
  332. if (clickId != 0) {
  333. int nowSecond = DateTime.now().second();
  334. int time = 0;
  335. if (nowSecond < 30) {
  336. time = 30 - nowSecond;
  337. } else {
  338. time = 60 - nowSecond;
  339. }
  340. //刷新双重验证码记录
  341. DoubleVerifyClickRefreshRecord refreshRecord = new DoubleVerifyClickRefreshRecord();
  342. refreshRecord.setClickId(clickId);
  343. refreshRecord.setUserId(userId);
  344. refreshRecord.setCode(sb.toString());
  345. refreshRecord.setRemainTime(time);
  346. refreshRecordMapper.insert(refreshRecord);
  347. }
  348. return GatewayResponse.SUCCESS.newBuilder().toResult(sb.toString());
  349. }
  350. /**
  351. * 获取双重验证码记录
  352. */
  353. @GetMapping("/get/doubleVerify/codeList")
  354. public Result<List<DoubleVerifyCodeView>> getDoubleVerifyCodeList(Long relationId) {
  355. long userId = StpUserUtil.getLoginIdAsLong();
  356. List<DoubleVerifyCodeView> views = doubleVerifyRecordMapper.getDoubleVerifyCodeList(userId, relationId);
  357. return GatewayResponse.SUCCESS.newBuilder().toResult(views);
  358. }
  359. /**
  360. * 用户是不是自然流量渠道
  361. * 且未回答答题
  362. */
  363. @GetMapping("/natural/channel")
  364. public Result<Boolean> isNaturalChannel() {
  365. long userId = StpUserUtil.getLoginIdAsLong();
  366. String question_key = RedisService.key.QUESTION_RESPONSE_KEY.getNameFormat(userId);
  367. if (redisService.get(question_key) != null) {
  368. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  369. }
  370. User user = userService.getById(userId);
  371. if (user.getPopularizeId() != 0) {
  372. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  373. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  374. }
  375. if (user.getPopularizeId() == 0) {
  376. QuestionResponseRecord record = questionResponseRecordMapper.selectOne(Wrappers.lambdaQuery(QuestionResponseRecord.class)
  377. .eq(QuestionResponseRecord::getUserId, userId).select(QuestionResponseRecord::getId).last("limit 1"));
  378. if (record != null) {
  379. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  380. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  381. }
  382. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  383. }
  384. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  385. }
  386. /**
  387. * 问卷记录
  388. */
  389. @PostMapping("/record/replyQuestion")
  390. public Result<String> recordReplyQuestion(@RequestBody @Validated QuestionResponseRecord record) {
  391. long userId = StpUserUtil.getLoginIdAsLong();
  392. User user = userService.getById(userId);
  393. String nickname = user.getNickname();
  394. String question_key = RedisService.key.QUESTION_RESPONSE_KEY.getNameFormat(userId);
  395. QuestionResponseRecord dbRecord = questionResponseRecordMapper.selectOne(Wrappers.lambdaQuery(QuestionResponseRecord.class)
  396. .eq(QuestionResponseRecord::getUserId, userId).select(QuestionResponseRecord::getId).last("limit 1"));
  397. if (dbRecord == null) {
  398. if (redisService.setNx(String.format("%s-%s", userId, nickname), userId, 10l)) {
  399. record.setUserId(userId);
  400. record.setNickname(nickname);
  401. questionResponseRecordMapper.insert(record);
  402. //发放优惠券
  403. couponCommonService.sendCouponToUser(userId, 100l, 0l, 0l, 0l, CouponUser.Channel.ques_response);
  404. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  405. }
  406. }
  407. return GatewayResponse.SUCCESS.newBuilder().toResult();
  408. }
  409. /**
  410. * 获取对应的动态问卷
  411. */
  412. @GetMapping("/get/questionnaire")
  413. public Result<List<QuestionnaireView>> getQuestionnaireView(Long promotionId) {
  414. QuestionnairePromotion promotion = questionnairePromotionMapper.selectById(promotionId);
  415. if (promotion == null || !promotion.getDeleted()) throw BusinessRuntimeException.getInstance("问卷不存在");
  416. Long templateId = promotion.getTemplateId();
  417. List<QuestionnaireView> questionnaireViews = beanSearcher.searchAll(QuestionnaireView.class, MapUtils.builder()
  418. .field(QuestionnaireView::getPromotionId, promotionId)
  419. .orderBy(QuestionnaireView::getSorted).asc()
  420. .orderBy(QuestionnaireView::getFieldsId).asc()
  421. .build());
  422. return GatewayResponse.SUCCESS.newBuilder().toResult(questionnaireViews);
  423. }
  424. /**
  425. * 记录问卷
  426. */
  427. @PostMapping("/record/questionnaire/{promotionId}")
  428. @Transactional(rollbackFor = Exception.class)
  429. @NoSubmit
  430. public Result<String> recordQuestionnaire(@PathVariable Long promotionId, @RequestBody List<FormFieldsData> answers) {
  431. Long groupsId = SEQUENCE.nextId();
  432. List<QuestionnairePromotionFieldsListView> promotionFieldsListViews = beanSearcher.searchAll(QuestionnairePromotionFieldsListView.class, MapUtils.builder().field(QuestionnairePromotionFieldsListView::getPromotionId, promotionId).build());
  433. if (CollUtil.isEmpty(promotionFieldsListViews)) throw BusinessRuntimeException.getInstance("问卷已结束");
  434. if (promotionFieldsListViews.size() != answers.size()) throw BusinessRuntimeException.getInstance("请完成所有问题");
  435. answers.forEach(answer -> {
  436. Long fieldsId = answer.getFieldsId();
  437. String content = answer.getContent();
  438. if (fieldsId == null || StrUtil.isBlank(content)) {
  439. throw BusinessRuntimeException.getInstance("必填项为空");
  440. }
  441. answer.setPromotionId(promotionId);
  442. answer.setGroupsId(groupsId);
  443. formFieldsDataMapper.insert(answer);
  444. });
  445. return GatewayResponse.SUCCESS.newBuilder().toResult();
  446. }
  447. /**
  448. * 对应平台车票 广告配置列表
  449. */
  450. @GetMapping("/get/advertise/{goodsId}")
  451. public Result<List<TicketAdvertiseConfigFrontView>> getTicketAdvertiseConfig(@PathVariable Long goodsId) {
  452. List<TicketAdvertiseConfigFrontView> views = beanSearcher.searchAll(TicketAdvertiseConfigFrontView.class, MapUtils.flatBuilder(request.getParameterMap())
  453. .field(TicketAdvertiseConfig::getGoodsId, goodsId)
  454. .orderBy(TicketAdvertiseConfig::getSorted).desc()
  455. .orderBy(TicketAdvertiseConfig::getId).desc()
  456. .build());
  457. return GatewayResponse.SUCCESS.newBuilder().toResult(views);
  458. }
  459. /**
  460. * 记录用户点击车票广告
  461. */
  462. @PostMapping("/click/ticket/advertise/record/{configId}")
  463. public Result<String> recordClickTicketAdvertise(@PathVariable Long configId) {
  464. long userId = StpUserUtil.getLoginIdAsLong();
  465. ticketAdvertiseConfigClickRecordService.recordUserClickTicketAdvertise(userId, configId);
  466. return GatewayResponse.SUCCESS.newBuilder().toResult();
  467. }
  468. /**
  469. * 推荐平台
  470. */
  471. @GetMapping("/get/recommend/goods")
  472. public Result<Page<UserRecommendGoodsFrontView>> getRecommendGoodsViews(@RequestParam(defaultValue = "0") Integer start, @RequestParam(defaultValue = "5") Integer limit) {
  473. //推荐用户未购买的车票平台 优先展示ai类平台 然后是影视流媒体
  474. long userId = StpUserUtil.getLoginIdAsLong();
  475. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  476. List<Long> filter_goods_id = relationMapper.getTicketGoodsId(userIds, List.of("validity", "overdue", "outside"));
  477. //用户是否购买过奈飞产品
  478. Boolean isPayNf = false;
  479. if (filter_goods_id.contains(1l)) {
  480. isPayNf = true;
  481. } else {
  482. int count = orderDonService.count(Wrappers.lambdaQuery(OrderDon.class)
  483. .eq(OrderDon::getGoodsId, 1)
  484. .eq(OrderDon::getUserId, userId)
  485. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
  486. if (count > 0) {
  487. //优先展示路由器、ai、流媒体
  488. isPayNf = true;
  489. }
  490. }
  491. Page<UserRecommendGoodsFrontView> page = groupRelationFrontService.getRecommendGoodsViews(isPayNf, filter_goods_id, start, limit);
  492. return GatewayResponse.SUCCESS.newBuilder().toResult(page);
  493. }
  494. /**
  495. * 查看GPT token
  496. */
  497. @GetMapping("/get/gptAccessToken")
  498. public Result<String> getGptAccessToken(Long relationId) throws Exception {
  499. long userId = StpUserUtil.getLoginIdAsLong();
  500. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  501. //存在该车票
  502. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  503. .field(RenewalView::getRelationId, relationId)
  504. .field(RenewalView::getUserId, userIds).op(Operator.InList).build());
  505. Assert.notNull(renewalView, "您的车票不存在");
  506. if (renewalView.getGoodsId() != 42) {
  507. throw BusinessRuntimeException.getInstance("该平台类型车票无法获取GPT直连token");
  508. }
  509. String account = renewalView.getAccount();
  510. String accessToken = chatGptAuthService.getAccessToken(account);
  511. return GatewayResponse.SUCCESS.newBuilder().toResult(accessToken);
  512. }
  513. /**
  514. * 获取特殊类型课程 通过邮件发送课程
  515. * 领取课件
  516. */
  517. @PostMapping("/courseware")
  518. public Result<String> getCourseWare(@RequestBody SpecialGoodsTicketReq request) throws Exception {
  519. long userId = StpUserUtil.getLoginIdAsLong();
  520. request.setUserId(userId);
  521. groupRelationFrontService.sendCourseWare(request);
  522. return GatewayResponse.SUCCESS.newBuilder().toResult();
  523. }
  524. //获取课程云盘链接
  525. @GetMapping("/get/courseware")
  526. public Result<GoodsCoursewareFile> getGoodsCourseware(Long relationId) {
  527. long userId = StpUserUtil.getLoginIdAsLong();
  528. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  529. RenewalView relationView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  530. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  531. .field(RenewalView::getRelationId, relationId).build());
  532. if (relationView == null) {
  533. throw BusinessRuntimeException.getInstance("您的车票不存在");
  534. }
  535. GoodsCoursewareFile goodsCoursewareFile = goodsCoursewareFileMapper.selectOne(Wrappers.lambdaQuery(GoodsCoursewareFile.class)
  536. .eq(GoodsCoursewareFile::getGoodsId, relationView.getGoodsId())
  537. .eq(GoodsCoursewareFile::getStatus, true)
  538. .select(GoodsCoursewareFile::getLink, GoodsCoursewareFile::getCode)
  539. .last("limit 1"));
  540. if (goodsCoursewareFile == null) {
  541. throw BusinessRuntimeException.getInstance("暂未配置课件链接地址,请联系客服");
  542. }
  543. return GatewayResponse.SUCCESS.newBuilder().toResult(goodsCoursewareFile);
  544. }
  545. /**
  546. * 读取车票账号登录验证码
  547. */
  548. @GetMapping("/get/verifyCode/{relationId}")
  549. public Result<String> getAiVerifyCode(@PathVariable Long relationId, Integer type) throws Exception {
  550. long userId = StpUserUtil.getLoginIdAsLong();
  551. return GatewayResponse.SUCCESS.newBuilder().toResult(groupRelationFrontService.getAiVerifyCode(userId, relationId, type));
  552. }
  553. /**
  554. * 是否有mid车票可候补
  555. */
  556. @GetMapping("/get/standby")
  557. public Result<GptStandbyResp> getGptStandby() {
  558. long userId = StpUserUtil.getLoginIdAsLong();
  559. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  560. 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))";
  561. List<RenewalView> renewalViewList = beanSearcher.searchAll(RenewalView.class, MapUtils.builder()
  562. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  563. .field(RenewalView::getGoodsId, 26)
  564. .put("condition", condition)
  565. .field(RenewalView::getExpiryTime).op(Operator.NotNull)
  566. .onlySelect(RenewalView::getAccount, RenewalView::getExpiryTime)
  567. .build());
  568. GptStandbyResp gptStandbyResp = new GptStandbyResp();
  569. if (renewalViewList.isEmpty()) {
  570. gptStandbyResp.setIsHasAccount(false);
  571. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  572. }
  573. List<RenewalView> overTen = new ArrayList<>();
  574. List<RenewalView> underTen = new ArrayList<>();
  575. DateTime now = DateTime.now();
  576. renewalViewList.forEach(e -> {
  577. if (e.getExpiryTime().compareTo(DateUtil.offsetDay(now, 10)) > 0) {
  578. overTen.add(e);
  579. } else underTen.add(e);
  580. });
  581. Integer accountBlockedCount = 1;
  582. if (overTen.size() > 1) {
  583. List<String> accountList = overTen.stream().map(RenewalView::getAccount).distinct().collect(Collectors.toList());
  584. accountBlockedCount = accountBlockedReplaceRecordMapper.selectCount(Wrappers.lambdaQuery(AccountBlockedReplaceRecord.class)
  585. .eq(AccountBlockedReplaceRecord::getGoodsId, 26)
  586. .in(AccountBlockedReplaceRecord::getAccount, accountList));
  587. }
  588. if (accountBlockedCount > 1) {
  589. gptStandbyResp.setIsHasAccount(false);
  590. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  591. }
  592. gptStandbyResp.setIsHasAccount(true);
  593. gptStandbyResp.setOverTen(overTen);
  594. gptStandbyResp.setUnderTen(underTen);
  595. Integer count = gptTicketStandbyMapper.selectCount(Wrappers.lambdaQuery(GptTicketStandby.class)
  596. .in(GptTicketStandby::getUserId, relationUserIdList));
  597. gptStandbyResp.setIsApply(count > 0 ? true : false);
  598. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  599. }
  600. /**
  601. * 申请候补
  602. */
  603. @PostMapping("/apply/standby")
  604. @NoSubmit
  605. public Result<Boolean> applyGptStandby() {
  606. long userId = StpUserUtil.getLoginIdAsLong();
  607. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  608. 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))";
  609. List<RenewalView> renewalViewList = beanSearcher.searchAll(RenewalView.class, MapUtils.builder()
  610. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  611. .field(RenewalView::getGoodsId, 26)
  612. .put("condition", condition)
  613. .field(RenewalView::getExpiryTime, DateUtil.offsetDay(DateTime.now(), 10)).op(Operator.GreaterThan)
  614. .onlySelect(RenewalView::getAccount)
  615. .build());
  616. if (renewalViewList.isEmpty()) {
  617. throw BusinessRuntimeException.getInstance("你未有车票账号");
  618. }
  619. Integer count = gptTicketStandbyMapper.selectCount(Wrappers.lambdaQuery(GptTicketStandby.class)
  620. .in(GptTicketStandby::getUserId, relationUserIdList));
  621. if (count > 0) {
  622. throw BusinessRuntimeException.getInstance("你已申请车票账号候补");
  623. }
  624. if (renewalViewList.size() > 1) {
  625. Set<String> accountSet = renewalViewList.stream().map(RenewalView::getAccount).collect(Collectors.toSet());
  626. Integer accountBlockedCount = accountBlockedReplaceRecordMapper.selectCount(Wrappers.lambdaQuery(AccountBlockedReplaceRecord.class)
  627. .eq(AccountBlockedReplaceRecord::getGoodsId, 26)
  628. .in(AccountBlockedReplaceRecord::getAccount, accountSet));
  629. if (accountBlockedCount > 1) {
  630. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  631. }
  632. }
  633. GptTicketStandby gptTicketStandby = new GptTicketStandby();
  634. gptTicketStandby.setUserId(userId);
  635. gptTicketStandbyMapper.insert(gptTicketStandby);
  636. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  637. }
  638. /**
  639. * midjourney车票退款
  640. */
  641. @PutMapping("/refund/ticketOrder/{relationId}")
  642. @NoSubmit
  643. public Result<String> ticketRefundOrders(@PathVariable Long relationId) throws Exception {
  644. long userId = StpUserUtil.getLoginIdAsLong();
  645. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  646. 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))";
  647. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  648. .field(RenewalView::getRelationId, relationId)
  649. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  650. .put("condition", condition)
  651. .field(RenewalView::getGoodsId, 26)
  652. .field(RenewalView::getExpiryTime, DateUtil.offsetDay(DateTime.now(), 10)).op(Operator.LessEqual)
  653. .build());
  654. if (renewalView == null) {
  655. throw BusinessRuntimeException.getInstance("你车票不存在或不符合退款要求");
  656. }
  657. OrderDon orderDon = orderDonService.getOne(Wrappers.lambdaQuery(OrderDon.class)
  658. .in(OrderDon::getUserId, relationUserIdList)
  659. .eq(OrderDon::getRelationId, relationId)
  660. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  661. .orderByDesc(OrderDon::getId)
  662. .last("limit 1"));
  663. if (orderDon == null) {
  664. throw BusinessRuntimeException.getInstance("你对应车票的订单不存在");
  665. }
  666. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  667. if (sku == null) {
  668. throw BusinessRuntimeException.getInstance("该车票规格不存在,请联系客服进行人工退款..");
  669. }
  670. Date expiryTime = renewalView.getExpiryTime();
  671. long remainDay = DateUtil.between(DateTime.now(), expiryTime, DateUnit.DAY) + 1;
  672. BigDecimal money = orderDon.getMoney();
  673. BigDecimal refundMoney = null;
  674. BigDecimal refundBalance= null;
  675. String refundType = null;
  676. if (money.compareTo(BigDecimal.ZERO) > 0) {
  677. BigDecimal dayMoney = money.divide(BigDecimal.valueOf(sku.getMonths()).multiply(BigDecimal.valueOf(30)), 2, RoundingMode.HALF_DOWN);
  678. refundMoney = BigDecimal.valueOf(remainDay).multiply(dayMoney);
  679. refundType = "money";
  680. }
  681. OrderRefundReq refundReq = new OrderRefundReq();
  682. if (orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  683. BigDecimal dayMoney = orderDon.getBalance().divide(BigDecimal.valueOf(sku.getMonths()).multiply(BigDecimal.valueOf(30)), 2, RoundingMode.HALF_DOWN);
  684. refundBalance = BigDecimal.valueOf(remainDay).multiply(dayMoney);
  685. refundReq.setIsOnly(true);
  686. }
  687. refundReq.setOrderId(orderDon.getId());
  688. refundReq.setRefundDesc("失效车票退款");
  689. refundReq.setRefundMoney(Optional.ofNullable(refundMoney).orElse(BigDecimal.ZERO));
  690. refundReq.setRefundBalance(Optional.ofNullable(refundBalance).orElse(BigDecimal.ZERO));
  691. refundReq.setRefundType(Optional.ofNullable(refundType).orElse("balance"));
  692. cmsOrderDonService.unifiedRefund(refundReq);
  693. return GatewayResponse.SUCCESS.newBuilder().toResult();
  694. }
  695. /**
  696. * 每日车票到期弹窗
  697. */
  698. @GetMapping("/get/expiry/notify")
  699. public Result<List<RenewalView>> getExpiryRenewalNotify() {
  700. Long userId = StpUserUtil.getLoginIdAsLong();
  701. List<RenewalView> expiryRenewals = groupRelationFrontService.getExpiryRenewalNotify(userId);
  702. return GatewayResponse.SUCCESS.newBuilder().toResult(expiryRenewals);
  703. }
  704. }