GroupRelationController.java 40 KB

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