GroupRelationController.java 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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.AccountView;
  31. import com.cyksj.model.manage.views.GroupsRelationView;
  32. import com.cyksj.model.request.*;
  33. import com.cyksj.model.response.GptStandbyResp;
  34. import com.cyksj.model.views.*;
  35. import com.cyksj.redis.RedisService;
  36. import com.cyksj.service.chatgpt.ChatGptAuthService;
  37. import com.cyksj.service.mange.CmsOrderDonService;
  38. import com.cyksj.service.mange.coupon.CouponCommonService;
  39. import com.cyksj.service.mange.ticket.TicketAdvertiseConfigClickRecordService;
  40. import com.cyksj.service.order.OrderDonService;
  41. import com.cyksj.service.relation.GroupRelationFrontService;
  42. import com.cyksj.service.relation.GroupsRelationNetflixService;
  43. import com.cyksj.service.user.UserBindRelationService;
  44. import com.cyksj.service.user.UserService;
  45. import com.cyksj.web.util.StpUserUtil;
  46. import com.ejlchina.searcher.BeanSearcher;
  47. import com.ejlchina.searcher.SearchResult;
  48. import com.ejlchina.searcher.operator.LessEqual;
  49. import com.ejlchina.searcher.param.Operator;
  50. import com.ejlchina.searcher.util.MapBuilder;
  51. import com.ejlchina.searcher.util.MapUtils;
  52. import lombok.RequiredArgsConstructor;
  53. import lombok.extern.slf4j.Slf4j;
  54. import org.springframework.transaction.annotation.Transactional;
  55. import org.springframework.validation.annotation.Validated;
  56. import org.springframework.web.bind.annotation.*;
  57. import javax.servlet.http.HttpServletRequest;
  58. import javax.validation.constraints.NotEmpty;
  59. import javax.validation.constraints.NotNull;
  60. import java.math.BigDecimal;
  61. import java.math.RoundingMode;
  62. import java.util.*;
  63. import java.util.concurrent.TimeUnit;
  64. import java.util.concurrent.atomic.AtomicInteger;
  65. import java.util.concurrent.atomic.AtomicLong;
  66. import java.util.stream.Collectors;
  67. /**
  68. * @author chan
  69. * @date 2022/9/27 11:48 AM
  70. */
  71. @Slf4j
  72. @RequiredArgsConstructor
  73. @RestController
  74. @RequestMapping("/applets/group/relation")
  75. public class GroupRelationController {
  76. private final BeanSearcher beanSearcher;
  77. private final OrderDonService orderDonService;
  78. private final GroupsRelationMapper relationMapper;
  79. private final GroupRelationFrontService groupRelationFrontService;
  80. private final UserService userService;
  81. private final UserBindRelationService userBindRelationService;
  82. private final TicketPwdViewRecordMapper ticketPwdViewRecordMapper;
  83. private final HttpServletRequest request;
  84. private final AccountDoubleVerifyRecordMapper accountDoubleVerifyRecordMapper;
  85. private final DoubleVerifyClickRecordMapper doubleVerifyRecordMapper;
  86. private final RedisService redisService;
  87. private final DoubleVerifyClickRefreshRecordMapper refreshRecordMapper;
  88. private final QuestionResponseRecordMapper questionResponseRecordMapper;
  89. private final CouponCommonService couponCommonService;
  90. private final FormFieldsDataMapper formFieldsDataMapper;
  91. private final QuestionnairePromotionMapper questionnairePromotionMapper;
  92. private final TicketAdvertiseConfigClickRecordService ticketAdvertiseConfigClickRecordService;
  93. private final GlobalThreadPoolTaskExecutor THREAD_POOL;
  94. private final ChatGptAuthService chatGptAuthService;
  95. private final GoodsCoursewareFileMapper goodsCoursewareFileMapper;
  96. private final GptTicketStandbyMapper gptTicketStandbyMapper;
  97. private final CmsOrderDonService cmsOrderDonService;
  98. private final GoodsDonSkuMapper goodsDonSkuMapper;
  99. private final AccountBlockedReplaceRecordMapper accountBlockedReplaceRecordMapper;
  100. private final OrderDonMapper orderDonMapper;
  101. private final UserGoodsNewbieGuideRecordMapper userGoodsNewbieGuideRecordMapper;
  102. private final GroupsRelationNetflixService groupsRelationNetflixService;
  103. private final ChatgptUserMapper chatgptUserMapper;
  104. private final UpgradeOrderDonMapper upgradeOrderDonMapper;
  105. private final UserBenefitsOrderRecordMapper userBenefitsOrderRecordMapper;
  106. private final ClaudeUserMapper claudeUserMapper;
  107. private final static Sequence SEQUENCE = new Sequence(0);
  108. @RequestMapping("/get/renewal")
  109. public Result<SearchResult<RenewalView>> get(Boolean isLoginPopularize, String customId, String account, String orderNo, Integer cmt) {
  110. long userId = StpUserUtil.getLoginIdAsLong();
  111. SearchResult<RenewalView> list = groupRelationFrontService.getMyTicket(userId, isLoginPopularize, customId, account, orderNo, cmt);
  112. return GatewayResponse.SUCCESS.newBuilder().toResult(list);
  113. }
  114. @GetMapping("/get/pay/goods")
  115. public Result<List<RenewalView>> getHasPayGoods() {
  116. long userId = StpUserUtil.getLoginIdAsLong();
  117. List<RenewalView> hasPayGoods = groupRelationFrontService.getHasPayGoods(userId);
  118. return GatewayResponse.SUCCESS.newBuilder().toResult(hasPayGoods);
  119. }
  120. @PostMapping("/post/renewal")
  121. public Result<OrderDon> renewal(@RequestBody OrderPayRequest payRequest) throws Exception {
  122. long userId = StpUserUtil.getLoginIdAsLong();
  123. payRequest.setUserId(userId);
  124. String ip = ServletUtil.getClientIP(request);
  125. payRequest.setIp(ip);
  126. OrderDon orderDon = orderDonService.renewal(payRequest);
  127. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  128. }
  129. @PutMapping("/update/set/account")
  130. public Result<String> setAccount(@RequestBody GroupsRelation relation) {
  131. long userId = StpUserUtil.getLoginIdAsLong();
  132. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  133. GroupsRelation re = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  134. .eq(GroupsRelation::getId, relation.getId())
  135. .in(GroupsRelation::getUserId, userIds)
  136. .last(" limit 1"));
  137. if (re == null) {
  138. throw new BusinessRuntimeException("该车票不存在,请联系客服.");
  139. }
  140. LambdaUpdateWrapper<GroupsRelation> updateWrapper = Wrappers.lambdaUpdate(GroupsRelation.class)
  141. .set(GroupsRelation::getAccount, relation.getAccount())
  142. .set(GroupsRelation::getPassword, relation.getPassword())
  143. .eq(GroupsRelation::getId, relation.getId());
  144. if (re.getRechargeStatus() != null) {
  145. if (re.getRechargeStatus() == GroupsRelation.RechargeStatus.complete) {
  146. throw BusinessRuntimeException.getInstance("代充账号已充值");
  147. }
  148. if (StrUtil.isEmpty(relation.getAccount()) || StrUtil.isEmpty(relation.getPassword())) {
  149. throw BusinessRuntimeException.getInstance("请输入正确的账号密码信息");
  150. }
  151. if (re.getRechargeStatus() == GroupsRelation.RechargeStatus.error) {
  152. updateWrapper.set(GroupsRelation::getRechargeStatus, GroupsRelation.RechargeStatus.waiting);
  153. }
  154. }
  155. relationMapper.update(relation, updateWrapper);
  156. return GatewayResponse.SUCCESS.newBuilder().toResult();
  157. }
  158. /**
  159. * 查询是否加入了企业微信
  160. */
  161. @GetMapping("/check/joinCorpWx")
  162. public Result<Boolean> isJoinCorpWx() {
  163. long userId = StpUserUtil.getLoginIdAsLong();
  164. Boolean flag = groupRelationFrontService.isJoinCorpWx(userId, false, false);
  165. return GatewayResponse.SUCCESS.newBuilder().toResult(flag);
  166. }
  167. /**
  168. * 获取全部车票
  169. */
  170. @GetMapping("/get")
  171. public Result<List<UserTicketView>> getUserTicketView(Long goodsId, Long skuId) {
  172. long userId = StpUserUtil.getLoginIdAsLong();
  173. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  174. List<UserTicketView> tickets = relationMapper.selectUserTickets(userIds, goodsId, skuId);
  175. return GatewayResponse.SUCCESS.newBuilder().toResult(tickets);
  176. }
  177. /**
  178. * 记录查看ChatGPT车票密码
  179. */
  180. @GetMapping("/recordView/{relationId}")
  181. public Result<String> recordGPTPwdView(@PathVariable Long relationId) {
  182. long userId = StpUserUtil.getLoginIdAsLong();
  183. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  184. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  185. .field(GroupsRelationView::getUserId, userIds).op(Operator.InList)
  186. .field(GroupsRelationView::getId, relationId).build());
  187. if (groupsRelationView == null) {
  188. log.info("userId:{}查看relationId:{}车票不存在", userId, relationId);
  189. throw BusinessRuntimeException.getInstance("该车票已不存在");
  190. }
  191. if (groupsRelationView.getAccountId() == null) throw BusinessRuntimeException.getInstance("该车队未配置账号");
  192. if (groupRelationFrontService == null) throw BusinessRuntimeException.getInstance("车票已不存在");
  193. TicketPwdViewRecord viewRecord = new TicketPwdViewRecord();
  194. viewRecord.setUserId(userId);
  195. viewRecord.setRelationId(relationId);
  196. viewRecord.setSkuId(groupsRelationView.getSkuId());
  197. viewRecord.setOperateLocation(ServletUtil.getClientIP(request));
  198. viewRecord.setAccount(groupsRelationView.getTripsAccount());
  199. viewRecord.setPassword(groupsRelationView.getTripsPassword());
  200. ticketPwdViewRecordMapper.insert(viewRecord);
  201. if (groupsRelationView.getGoodsId() == 18 && StrUtil.isEmpty(groupsRelationView.getApiSecret())) {
  202. THREAD_POOL.execute(() -> {
  203. //车队所有人查看密码
  204. Integer num = groupsRelationView.getGtNum();
  205. Integer viewNum = relationMapper.selectViewPwdCount(groupsRelationView.getGroupsId());
  206. if (num <= viewNum) {
  207. AccountDoubleVerifyRecord exist = accountDoubleVerifyRecordMapper.selectOne(Wrappers.lambdaQuery(AccountDoubleVerifyRecord.class)
  208. .eq(AccountDoubleVerifyRecord::getAccountId, groupsRelationView.getAccountId())
  209. .eq(AccountDoubleVerifyRecord::getDeleted, true).last("limit 1"));
  210. if (exist == null) {
  211. if (redisService.setNx(String.format("%s-%s", groupsRelationView.getAccountId(), groupsRelationView.getId()), groupsRelationView.getId(), 60l)) {
  212. //记录
  213. AccountDoubleVerifyRecord accountDoubleVerifyRecord = new AccountDoubleVerifyRecord();
  214. accountDoubleVerifyRecord.setAccountId(groupsRelationView.getAccountId());
  215. accountDoubleVerifyRecord.setAccount(groupsRelationView.getTripsAccount());
  216. accountDoubleVerifyRecord.setGroupsId(groupsRelationView.getGroupsId());
  217. accountDoubleVerifyRecord.setSkuId(groupsRelationView.getSkuId());
  218. accountDoubleVerifyRecord.setRemark("车队所有人看过密码");
  219. accountDoubleVerifyRecordMapper.insert(accountDoubleVerifyRecord);
  220. }
  221. }
  222. }
  223. });
  224. }
  225. return GatewayResponse.SUCCESS.newBuilder().toResult(groupsRelationView.getTripsPassword());
  226. }
  227. /**
  228. * 获取AI类 ChatGPT产品谷歌验证码
  229. */
  230. @GetMapping("/get/authCode")
  231. public Result<String> getAuthCode(Long relationId) {
  232. long userId = StpUserUtil.getLoginIdAsLong();
  233. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  234. if (relationId == null) throw BusinessRuntimeException.getInstance("车票不存在");
  235. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  236. .field(GroupsRelationView::getId, relationId)
  237. .field(GroupsRelationView::getUserId, userIds).op(Operator.InList).build());
  238. if (groupsRelationView == null) throw BusinessRuntimeException.getInstance("车票不存在");
  239. if (StrUtil.isEmpty(groupsRelationView.getApiSecret())) throw BusinessRuntimeException.getInstance("未开启验证");
  240. DateTime now = DateTime.now();
  241. Integer count = doubleVerifyRecordMapper.selectCount(Wrappers.lambdaQuery(DoubleVerifyClickRecord.class)
  242. .in(DoubleVerifyClickRecord::getUserId, userIds)
  243. .eq(DoubleVerifyClickRecord::getRelationId, relationId)
  244. .eq(DoubleVerifyClickRecord::getAccountId, groupsRelationView.getAccountId())
  245. .between(DoubleVerifyClickRecord::getCreatedTime, DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now)));
  246. //获取双重验证码
  247. Boolean isHasVerifyCode = StrUtil.isNotBlank(groupsRelationView.getVerifyCode()) ? true : false;
  248. //出去亚马逊 获取限制
  249. if (groupsRelationView.getGoodsId() != 6) {
  250. Integer num = groupRelationFrontService.getUserCodeNumBySkuId(userId, groupsRelationView.getSkuId(), isHasVerifyCode);
  251. if (count >= num) throw BusinessRuntimeException.getInstance("获取双重验证码次数上限");
  252. }
  253. //一分钟内 只能一人获取
  254. boolean b = redisService.setNx(RedisService.key.DOUBLE_VERIFY_CODE_VIEW_MINUTES_KEY.getName() + groupsRelationView.getTripsAccount(), relationId, RedisService.key.DOUBLE_VERIFY_CODE_VIEW_MINUTES_KEY.getTimeout());
  255. if (!b) {
  256. throw BusinessRuntimeException.getInstance("一分钟内已有人获取该账号验证码,请稍后获取..");
  257. }
  258. int second = now.second();
  259. if (second < 30 && 30 - second < 3) {
  260. ThreadUtil.sleep(30 - second + 1, TimeUnit.SECONDS);
  261. } else if (second > 30 && 60 - second < 3) {
  262. ThreadUtil.sleep(60 - second + 1, TimeUnit.SECONDS);
  263. }
  264. StringBuilder sb = new StringBuilder();
  265. JSONObject re = new JSONObject();
  266. try {
  267. long code = GoogleGenerator.getCode(groupsRelationView.getApiSecret(), now.getTime());
  268. sb.append(code);
  269. while (sb.length() < 6) {
  270. sb.insert(0, 0);
  271. }
  272. re.putOpt("code", sb.toString());
  273. int nowSecond = DateTime.now().second();
  274. int time = 0;
  275. if (nowSecond < 30) {
  276. time = 30 - nowSecond;
  277. } else {
  278. time = 60 - nowSecond;
  279. }
  280. re.putOpt("time", time);
  281. DoubleVerifyClickRecord doubleVerifyClickRecord = new DoubleVerifyClickRecord();
  282. doubleVerifyClickRecord.setRelationId(relationId);
  283. doubleVerifyClickRecord.setUserId(userId);
  284. doubleVerifyClickRecord.setAccountId(groupsRelationView.getAccountId());
  285. doubleVerifyClickRecord.setAccount(groupsRelationView.getTripsAccount());
  286. doubleVerifyClickRecord.setSkuId(groupsRelationView.getSkuId());
  287. doubleVerifyClickRecord.setCode(sb.toString());
  288. doubleVerifyClickRecord.setRemainTime(time);
  289. doubleVerifyRecordMapper.insert(doubleVerifyClickRecord);
  290. DoubleVerifyDto doubleVerifyDto = new DoubleVerifyDto();
  291. doubleVerifyDto.setClickId(doubleVerifyClickRecord.getId());
  292. doubleVerifyDto.setApiSecret(groupsRelationView.getApiSecret());
  293. redisService.set(String.format("%s-%s", userId, sb.toString()), 0, 60 * 10l);
  294. redisService.set(String.format("%s/%s", userId, sb.toString()), Jsons.toJson(doubleVerifyDto), 60 * 10l);
  295. } catch (Exception e) {
  296. throw BusinessRuntimeException.getInstance("获取双重验证码错误,请联系客服");
  297. }
  298. return GatewayResponse.SUCCESS.newBuilder().toResult(re.toString());
  299. }
  300. /**
  301. * 刷新验证码
  302. */
  303. @GetMapping("/refresh/code")
  304. public Result<String> refreshCode(String code) {
  305. long userId = StpUserUtil.getLoginIdAsLong();
  306. String numKey = String.format("%s-%s", userId, code);
  307. Object num = redisService.get(numKey);
  308. String objKey = String.format("%s/%s", userId, code);
  309. Object objValue = redisService.get(objKey);
  310. if (objValue == null || num == null) {
  311. throw BusinessRuntimeException.getInstance("请重新获取双重验证码");
  312. }
  313. Integer refreshNum = Integer.parseInt(num.toString());
  314. String apiSecret = null;
  315. Long clickId = 0l;
  316. try {
  317. DoubleVerifyDto dto = Jsons.parseObject(objValue.toString(), DoubleVerifyDto.class);
  318. apiSecret = dto.getApiSecret();
  319. clickId = dto.getClickId();
  320. } catch (Exception e) {
  321. apiSecret = objValue.toString();
  322. }
  323. if (refreshNum >= 3) {
  324. redisService.del(numKey);
  325. redisService.del(objKey);
  326. throw BusinessRuntimeException.getInstance("刷新次数已达到3次,请重新获取验证码");
  327. }
  328. if (apiSecret == null) {
  329. throw BusinessRuntimeException.getInstance("请重新获取双重验证码");
  330. }
  331. StringBuilder sb = new StringBuilder();
  332. try {
  333. long c = GoogleGenerator.getCode(apiSecret, DateTime.now().getTime());
  334. sb.append(c);
  335. while (sb.length() < 6) {
  336. sb.insert(0, 0);
  337. }
  338. redisService.incr(numKey, 1l);
  339. } catch (Exception e) {
  340. throw BusinessRuntimeException.getInstance("刷新双重验证码错误,请联系客服");
  341. }
  342. if (clickId != 0) {
  343. int nowSecond = DateTime.now().second();
  344. int time = 0;
  345. if (nowSecond < 30) {
  346. time = 30 - nowSecond;
  347. } else {
  348. time = 60 - nowSecond;
  349. }
  350. //刷新双重验证码记录
  351. DoubleVerifyClickRefreshRecord refreshRecord = new DoubleVerifyClickRefreshRecord();
  352. refreshRecord.setClickId(clickId);
  353. refreshRecord.setUserId(userId);
  354. refreshRecord.setCode(sb.toString());
  355. refreshRecord.setRemainTime(time);
  356. refreshRecordMapper.insert(refreshRecord);
  357. }
  358. return GatewayResponse.SUCCESS.newBuilder().toResult(sb.toString());
  359. }
  360. /**
  361. * 获取双重验证码记录
  362. */
  363. @GetMapping("/get/doubleVerify/codeList")
  364. public Result<List<DoubleVerifyCodeView>> getDoubleVerifyCodeList(Long relationId) {
  365. long userId = StpUserUtil.getLoginIdAsLong();
  366. List<DoubleVerifyCodeView> views = doubleVerifyRecordMapper.getDoubleVerifyCodeList(userId, relationId);
  367. return GatewayResponse.SUCCESS.newBuilder().toResult(views);
  368. }
  369. /**
  370. * 用户是不是自然流量渠道
  371. * 且未回答答题
  372. */
  373. @GetMapping("/natural/channel")
  374. public Result<Boolean> isNaturalChannel() {
  375. long userId = StpUserUtil.getLoginIdAsLong();
  376. String question_key = RedisService.key.QUESTION_RESPONSE_KEY.getNameFormat(userId);
  377. if (redisService.get(question_key) != null) {
  378. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  379. }
  380. User user = userService.getById(userId);
  381. if (user.getPopularizeId() != 0) {
  382. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  383. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  384. }
  385. if (user.getPopularizeId() == 0) {
  386. QuestionResponseRecord record = questionResponseRecordMapper.selectOne(Wrappers.lambdaQuery(QuestionResponseRecord.class)
  387. .eq(QuestionResponseRecord::getUserId, userId).select(QuestionResponseRecord::getId).last("limit 1"));
  388. if (record != null) {
  389. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  390. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  391. }
  392. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  393. }
  394. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  395. }
  396. /**
  397. * 问卷记录
  398. */
  399. @PostMapping("/record/replyQuestion")
  400. public Result<String> recordReplyQuestion(@RequestBody @Validated QuestionResponseRecord record) {
  401. long userId = StpUserUtil.getLoginIdAsLong();
  402. User user = userService.getById(userId);
  403. String nickname = user.getNickname();
  404. String question_key = RedisService.key.QUESTION_RESPONSE_KEY.getNameFormat(userId);
  405. QuestionResponseRecord dbRecord = questionResponseRecordMapper.selectOne(Wrappers.lambdaQuery(QuestionResponseRecord.class)
  406. .eq(QuestionResponseRecord::getUserId, userId).select(QuestionResponseRecord::getId).last("limit 1"));
  407. if (dbRecord == null) {
  408. if (redisService.setNx(String.format("%s-%s", userId, nickname), userId, 10l)) {
  409. record.setUserId(userId);
  410. record.setNickname(nickname);
  411. questionResponseRecordMapper.insert(record);
  412. //发放优惠券
  413. couponCommonService.sendCouponToUser(userId, 100l, 0l, 0l, 0l, CouponUser.Channel.ques_response);
  414. redisService.set(question_key, userId, RedisService.key.QUESTION_RESPONSE_KEY.getTimeout());
  415. }
  416. }
  417. return GatewayResponse.SUCCESS.newBuilder().toResult();
  418. }
  419. /**
  420. * 获取对应的动态问卷
  421. */
  422. @GetMapping("/get/questionnaire")
  423. public Result<List<QuestionnaireView>> getQuestionnaireView(Long promotionId) {
  424. QuestionnairePromotion promotion = questionnairePromotionMapper.selectById(promotionId);
  425. if (promotion == null || !promotion.getDeleted()) throw BusinessRuntimeException.getInstance("问卷不存在");
  426. Long templateId = promotion.getTemplateId();
  427. List<QuestionnaireView> questionnaireViews = beanSearcher.searchAll(QuestionnaireView.class, MapUtils.builder()
  428. .field(QuestionnaireView::getPromotionId, promotionId)
  429. .orderBy(QuestionnaireView::getSorted).asc()
  430. .orderBy(QuestionnaireView::getFieldsId).asc()
  431. .build());
  432. return GatewayResponse.SUCCESS.newBuilder().toResult(questionnaireViews);
  433. }
  434. /**
  435. * 记录问卷
  436. */
  437. @PostMapping("/record/questionnaire/{promotionId}")
  438. @Transactional(rollbackFor = Exception.class)
  439. @NoSubmit
  440. public Result<String> recordQuestionnaire(@PathVariable Long promotionId, String showId, @RequestBody List<FormFieldsData> answers) {
  441. Long userId = StpUserUtil.getUserIdAfterLogin();
  442. Long groupsId = SEQUENCE.nextId();
  443. List<QuestionnairePromotionFieldsListView> promotionFieldsListViews = beanSearcher.searchAll(QuestionnairePromotionFieldsListView.class, MapUtils.builder().field(QuestionnairePromotionFieldsListView::getPromotionId, promotionId).build());
  444. if (CollUtil.isEmpty(promotionFieldsListViews)) throw BusinessRuntimeException.getInstance("问卷已结束");
  445. if (promotionFieldsListViews.size() != answers.size()) throw BusinessRuntimeException.getInstance("请完成所有问题");
  446. log.info("开始记录问卷:{}", promotionId);
  447. answers.forEach(answer -> {
  448. // if (StringUtil.isNotBlank(showId)) {
  449. // answer.setUserId(userService.getUserIdByShowId(showId));
  450. // }
  451. answer.setUserId(userId);
  452. Long fieldsId = answer.getFieldsId();
  453. String content = answer.getContent();
  454. if (fieldsId == null || StrUtil.isBlank(content)) {
  455. throw BusinessRuntimeException.getInstance("必填项为空");
  456. }
  457. answer.setPromotionId(promotionId);
  458. answer.setGroupsId(groupsId);
  459. formFieldsDataMapper.insert(answer);
  460. });
  461. return GatewayResponse.SUCCESS.newBuilder().toResult();
  462. }
  463. /**
  464. * 查询用户是否填写问卷
  465. */
  466. @GetMapping("/check/questionnaire/{promotionId}")
  467. public Result<Boolean> checkQuestionnaire(@PathVariable Long promotionId) {
  468. long userId = StpUserUtil.getLoginIdAsLong();
  469. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  470. Integer count = formFieldsDataMapper.selectCount(Wrappers.lambdaQuery(FormFieldsData.class).in(FormFieldsData::getUserId, userIdList).eq(FormFieldsData::getPromotionId, promotionId));
  471. return GatewayResponse.SUCCESS.newBuilder().toResult(count > 0);
  472. }
  473. /**
  474. * 对应平台车票 广告配置列表
  475. */
  476. @GetMapping("/get/advertise/{goodsId}")
  477. public Result<List<TicketAdvertiseConfigFrontView>> getTicketAdvertiseConfig(@PathVariable Long goodsId) {
  478. long userId = StpUserUtil.getLoginIdAsLong();
  479. log.info("userId:{}获取广告位配置", userId);
  480. List<TicketAdvertiseConfigFrontView> views = beanSearcher.searchAll(TicketAdvertiseConfigFrontView.class, MapUtils.flatBuilder(request.getParameterMap())
  481. .field(TicketAdvertiseConfig::getGoodsId, goodsId)
  482. .orderBy(TicketAdvertiseConfig::getSorted).desc()
  483. .orderBy(TicketAdvertiseConfig::getId).desc()
  484. .build());
  485. return GatewayResponse.SUCCESS.newBuilder().toResult(views);
  486. }
  487. /**
  488. * 记录用户点击车票广告
  489. */
  490. @PostMapping("/click/ticket/advertise/record/{configId}")
  491. public Result<String> recordClickTicketAdvertise(@PathVariable Long configId) {
  492. long userId = StpUserUtil.getLoginIdAsLong();
  493. ticketAdvertiseConfigClickRecordService.recordUserClickTicketAdvertise(userId, configId);
  494. return GatewayResponse.SUCCESS.newBuilder().toResult();
  495. }
  496. /**
  497. * 推荐平台
  498. */
  499. @GetMapping("/get/recommend/goods")
  500. public Result<Page<UserRecommendGoodsFrontView>> getRecommendGoodsViews(@RequestParam(defaultValue = "0") Integer start, @RequestParam(defaultValue = "5") Integer limit) {
  501. //推荐用户未购买的车票平台 优先展示ai类平台 然后是影视流媒体
  502. long userId = StpUserUtil.getLoginIdAsLong();
  503. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  504. List<Long> filter_goods_id = relationMapper.getTicketGoodsId(userIds, List.of("validity", "overdue", "outside"));
  505. //用户是否购买过奈飞产品
  506. Boolean isPayNf = false;
  507. if (filter_goods_id.contains(1l)) {
  508. isPayNf = true;
  509. } else {
  510. int count = orderDonService.count(Wrappers.lambdaQuery(OrderDon.class)
  511. .eq(OrderDon::getGoodsId, 1)
  512. .eq(OrderDon::getUserId, userId)
  513. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
  514. if (count > 0) {
  515. //优先展示路由器、ai、流媒体
  516. isPayNf = true;
  517. }
  518. }
  519. Boolean filterCourseGoods = false;
  520. //GPT Plus基础2月 课程不展示
  521. Integer orders = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
  522. .in(OrderDon::getUserId, userIds)
  523. .eq(OrderDon::getSkuId, 444)
  524. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  525. if (orders > 0) {
  526. filterCourseGoods = true;
  527. }
  528. Page<UserRecommendGoodsFrontView> page = groupRelationFrontService.getRecommendGoodsViews(isPayNf, filter_goods_id, filterCourseGoods, start, limit);
  529. return GatewayResponse.SUCCESS.newBuilder().toResult(page);
  530. }
  531. /**
  532. * 查看GPT token
  533. */
  534. @GetMapping("/get/gptAccessToken")
  535. public Result<String> getGptAccessToken(Long relationId) throws Exception {
  536. long userId = StpUserUtil.getLoginIdAsLong();
  537. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  538. //存在该车票
  539. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  540. .field(RenewalView::getRelationId, relationId)
  541. .field(RenewalView::getUserId, userIds).op(Operator.InList).build());
  542. Assert.notNull(renewalView, "您的车票不存在");
  543. if (renewalView.getGoodsId() != 42) {
  544. throw BusinessRuntimeException.getInstance("该平台类型车票无法获取GPT直连token");
  545. }
  546. String account = renewalView.getAccount();
  547. String accessToken = chatGptAuthService.getAccessToken(account);
  548. return GatewayResponse.SUCCESS.newBuilder().toResult(accessToken);
  549. }
  550. /**
  551. * 获取特殊类型课程 通过邮件发送课程
  552. * 领取课件
  553. */
  554. @PostMapping("/courseware")
  555. public Result<String> getCourseWare(@RequestBody SpecialGoodsTicketReq request) throws Exception {
  556. long userId = StpUserUtil.getLoginIdAsLong();
  557. request.setUserId(userId);
  558. groupRelationFrontService.sendCourseWare(request);
  559. return GatewayResponse.SUCCESS.newBuilder().toResult();
  560. }
  561. //获取课程云盘链接
  562. @GetMapping("/get/courseware")
  563. public Result<GoodsCoursewareFile> getGoodsCourseware(Long relationId) {
  564. long userId = StpUserUtil.getLoginIdAsLong();
  565. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  566. RenewalView relationView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  567. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  568. .field(RenewalView::getRelationId, relationId).build());
  569. if (relationView == null) {
  570. throw BusinessRuntimeException.getInstance("您的车票不存在");
  571. }
  572. GoodsCoursewareFile goodsCoursewareFile = goodsCoursewareFileMapper.selectOne(Wrappers.lambdaQuery(GoodsCoursewareFile.class)
  573. .eq(GoodsCoursewareFile::getGoodsId, relationView.getGoodsId())
  574. .eq(GoodsCoursewareFile::getStatus, true)
  575. .select(GoodsCoursewareFile::getLink, GoodsCoursewareFile::getCode)
  576. .last("limit 1"));
  577. if (goodsCoursewareFile == null) {
  578. throw BusinessRuntimeException.getInstance("暂未配置课件链接地址,请联系客服");
  579. }
  580. return GatewayResponse.SUCCESS.newBuilder().toResult(goodsCoursewareFile);
  581. }
  582. /**
  583. * 读取车票账号登录验证码
  584. */
  585. @PostMapping("/get/verifyCode")
  586. public Result<String> getAiVerifyCode(@RequestBody TicketLoginReq loginReq) throws Exception {
  587. long userId = StpUserUtil.getLoginIdAsLong();
  588. loginReq.setUserId(userId);
  589. return GatewayResponse.SUCCESS.newBuilder().toResult(groupRelationFrontService.getAiVerifyCode(loginReq));
  590. }
  591. /**
  592. * 车票后台登录
  593. */
  594. @PostMapping("/ticket/login")
  595. public Result<GroupsRelation> ticketLogin(@RequestBody TicketLoginReq loginReq) {
  596. GroupsRelation relation = groupRelationFrontService.ticketLogin(loginReq);
  597. return GatewayResponse.SUCCESS.newBuilder().toResult(relation);
  598. }
  599. /**
  600. * 奈飞验证校验
  601. */
  602. @PostMapping("/ticket/verify")
  603. public Result<String> outsideTicketVerify(@RequestBody TicketLoginReq loginReq) {
  604. return GatewayResponse.SUCCESS.newBuilder().toResult(groupRelationFrontService.outsideTicketVerify(loginReq));
  605. }
  606. /**
  607. * 是否有mid车票可候补
  608. */
  609. @GetMapping("/get/standby")
  610. public Result<GptStandbyResp> getGptStandby() {
  611. long userId = StpUserUtil.getLoginIdAsLong();
  612. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  613. 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))";
  614. List<RenewalView> renewalViewList = beanSearcher.searchAll(RenewalView.class, MapUtils.builder()
  615. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  616. .field(RenewalView::getGoodsId, 26)
  617. .put("condition", condition)
  618. .field(RenewalView::getExpiryTime).op(Operator.NotNull)
  619. .onlySelect(RenewalView::getAccount, RenewalView::getExpiryTime)
  620. .build());
  621. GptStandbyResp gptStandbyResp = new GptStandbyResp();
  622. if (renewalViewList.isEmpty()) {
  623. gptStandbyResp.setIsHasAccount(false);
  624. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  625. }
  626. List<RenewalView> overTen = new ArrayList<>();
  627. List<RenewalView> underTen = new ArrayList<>();
  628. DateTime now = DateTime.now();
  629. renewalViewList.forEach(e -> {
  630. if (e.getExpiryTime().compareTo(DateUtil.offsetDay(now, 10)) > 0) {
  631. overTen.add(e);
  632. } else underTen.add(e);
  633. });
  634. Integer accountBlockedCount = 1;
  635. if (overTen.size() > 1) {
  636. List<String> accountList = overTen.stream().map(RenewalView::getAccount).distinct().collect(Collectors.toList());
  637. accountBlockedCount = accountBlockedReplaceRecordMapper.selectCount(Wrappers.lambdaQuery(AccountBlockedReplaceRecord.class)
  638. .eq(AccountBlockedReplaceRecord::getGoodsId, 26)
  639. .in(AccountBlockedReplaceRecord::getAccount, accountList));
  640. }
  641. if (accountBlockedCount > 1) {
  642. gptStandbyResp.setIsHasAccount(false);
  643. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  644. }
  645. gptStandbyResp.setIsHasAccount(true);
  646. gptStandbyResp.setOverTen(overTen);
  647. gptStandbyResp.setUnderTen(underTen);
  648. Integer count = gptTicketStandbyMapper.selectCount(Wrappers.lambdaQuery(GptTicketStandby.class)
  649. .in(GptTicketStandby::getUserId, relationUserIdList));
  650. gptStandbyResp.setIsApply(count > 0 ? true : false);
  651. return GatewayResponse.SUCCESS.newBuilder().toResult(gptStandbyResp);
  652. }
  653. /**
  654. * 申请候补
  655. */
  656. @PostMapping("/apply/standby")
  657. @NoSubmit
  658. public Result<Boolean> applyGptStandby() {
  659. long userId = StpUserUtil.getLoginIdAsLong();
  660. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  661. 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))";
  662. List<RenewalView> renewalViewList = beanSearcher.searchAll(RenewalView.class, MapUtils.builder()
  663. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  664. .field(RenewalView::getGoodsId, 26)
  665. .put("condition", condition)
  666. .field(RenewalView::getExpiryTime, DateUtil.offsetDay(DateTime.now(), 10)).op(Operator.GreaterThan)
  667. .onlySelect(RenewalView::getAccount)
  668. .build());
  669. if (renewalViewList.isEmpty()) {
  670. throw BusinessRuntimeException.getInstance("你未有车票账号");
  671. }
  672. Integer count = gptTicketStandbyMapper.selectCount(Wrappers.lambdaQuery(GptTicketStandby.class)
  673. .in(GptTicketStandby::getUserId, relationUserIdList));
  674. if (count > 0) {
  675. throw BusinessRuntimeException.getInstance("你已申请车票账号候补");
  676. }
  677. if (renewalViewList.size() > 1) {
  678. Set<String> accountSet = renewalViewList.stream().map(RenewalView::getAccount).collect(Collectors.toSet());
  679. Integer accountBlockedCount = accountBlockedReplaceRecordMapper.selectCount(Wrappers.lambdaQuery(AccountBlockedReplaceRecord.class)
  680. .eq(AccountBlockedReplaceRecord::getGoodsId, 26)
  681. .in(AccountBlockedReplaceRecord::getAccount, accountSet));
  682. if (accountBlockedCount > 1) {
  683. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  684. }
  685. }
  686. GptTicketStandby gptTicketStandby = new GptTicketStandby();
  687. gptTicketStandby.setUserId(userId);
  688. gptTicketStandbyMapper.insert(gptTicketStandby);
  689. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  690. }
  691. /**
  692. * midjourney车票退款
  693. */
  694. @PutMapping("/refund/ticketOrder/{relationId}")
  695. @NoSubmit
  696. public Result<String> ticketRefundOrders(@PathVariable Long relationId) throws Exception {
  697. long userId = StpUserUtil.getLoginIdAsLong();
  698. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  699. 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))";
  700. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  701. .field(RenewalView::getRelationId, relationId)
  702. .field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  703. .put("condition", condition)
  704. .field(RenewalView::getGoodsId, 26)
  705. .field(RenewalView::getExpiryTime, DateUtil.offsetDay(DateTime.now(), 10)).op(Operator.LessEqual)
  706. .build());
  707. if (renewalView == null) {
  708. throw BusinessRuntimeException.getInstance("你车票不存在或不符合退款要求");
  709. }
  710. OrderDon orderDon = orderDonService.getOne(Wrappers.lambdaQuery(OrderDon.class)
  711. .in(OrderDon::getUserId, relationUserIdList)
  712. .eq(OrderDon::getRelationId, relationId)
  713. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  714. .orderByDesc(OrderDon::getId)
  715. .last("limit 1"));
  716. if (orderDon == null) {
  717. throw BusinessRuntimeException.getInstance("你对应车票的订单不存在");
  718. }
  719. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  720. if (sku == null) {
  721. throw BusinessRuntimeException.getInstance("该车票规格不存在,请联系客服进行人工退款..");
  722. }
  723. Date expiryTime = renewalView.getExpiryTime();
  724. long remainDay = DateUtil.between(DateTime.now(), expiryTime, DateUnit.DAY) + 1;
  725. BigDecimal money = orderDon.getMoney();
  726. BigDecimal refundMoney = null;
  727. BigDecimal refundBalance= null;
  728. String refundType = null;
  729. if (money.compareTo(BigDecimal.ZERO) > 0) {
  730. BigDecimal dayMoney = money.divide(BigDecimal.valueOf(sku.getMonths()).multiply(BigDecimal.valueOf(30)), 2, RoundingMode.HALF_DOWN);
  731. refundMoney = BigDecimal.valueOf(remainDay).multiply(dayMoney);
  732. refundType = "money";
  733. }
  734. OrderRefundReq refundReq = new OrderRefundReq();
  735. if (orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  736. BigDecimal dayMoney = orderDon.getBalance().divide(BigDecimal.valueOf(sku.getMonths()).multiply(BigDecimal.valueOf(30)), 2, RoundingMode.HALF_DOWN);
  737. refundBalance = BigDecimal.valueOf(remainDay).multiply(dayMoney);
  738. refundReq.setIsOnly(true);
  739. }
  740. refundReq.setOrderId(orderDon.getId());
  741. refundReq.setRefundDesc("失效车票退款");
  742. refundReq.setRefundMoney(Optional.ofNullable(refundMoney).orElse(BigDecimal.ZERO));
  743. refundReq.setRefundBalance(Optional.ofNullable(refundBalance).orElse(BigDecimal.ZERO));
  744. refundReq.setRefundType(Optional.ofNullable(refundType).orElse("balance"));
  745. cmsOrderDonService.unifiedRefund(refundReq);
  746. return GatewayResponse.SUCCESS.newBuilder().toResult();
  747. }
  748. /**
  749. * 每日车票到期弹窗
  750. */
  751. @GetMapping("/get/expiry/notify")
  752. public Result<List<RenewalView>> getExpiryRenewalNotify() {
  753. Long userId = StpUserUtil.getLoginIdAsLong();
  754. List<RenewalView> expiryRenewals = groupRelationFrontService.getExpiryRenewalNotify(userId);
  755. return GatewayResponse.SUCCESS.newBuilder().toResult(expiryRenewals);
  756. }
  757. /**
  758. * 车票详情
  759. */
  760. @GetMapping("/get/detail")
  761. public Result<RenewalView> getTicketDetail(Long relationId) {
  762. if (relationId == null) {
  763. return GatewayResponse.SUCCESS.newBuilder().toResult();
  764. }
  765. long userId = StpUserUtil.getLoginIdAsLong();
  766. RenewalView ticketDetail = groupRelationFrontService.getTicketDetail(userId, relationId);
  767. return GatewayResponse.SUCCESS.newBuilder().toResult(ticketDetail);
  768. }
  769. /**
  770. * 车票售后常见问题
  771. */
  772. @GetMapping("/get/questions/{goodsId}")
  773. public Result<List<GoodsDonQaFrontView>> getTicketQuestions(@PathVariable Long goodsId, @RequestParam(defaultValue = "1") Integer type) {
  774. long userId = StpUserUtil.getLoginIdAsLong();
  775. log.info("userId:{}查看车票:{}售后问题", userId, goodsId);
  776. if (type < 1 || type > 2) {
  777. return GatewayResponse.SUCCESS.newBuilder().toResult();
  778. }
  779. String key = RedisService.key.YH_GOODS_QUESTIONS_DETAIL.getNameFormat(type, goodsId);
  780. Object o = redisService.get(key);
  781. if (o == null) {
  782. List<GoodsDonQaFrontView> donQaFrontViews = beanSearcher.searchAll(GoodsDonQaFrontView.class, MapUtils.builder().field(GoodsDonQaFrontView::getGoodsId, goodsId).field(GoodsDonQaFrontView::getType, type).build());
  783. if (CollUtil.isEmpty(donQaFrontViews)) {
  784. return GatewayResponse.SUCCESS.newBuilder().toResult();
  785. }
  786. redisService.setNx(key, donQaFrontViews, RedisService.key.YH_GOODS_QUESTIONS_DETAIL.getTimeout());
  787. o = redisService.get(key);
  788. }
  789. List<GoodsDonQaFrontView> donQaFrontViews = Jsons.parseList(o, GoodsDonQaFrontView.class);
  790. return GatewayResponse.SUCCESS.newBuilder().toResult(donQaFrontViews);
  791. }
  792. /**
  793. * 是否首次购买车票
  794. */
  795. @GetMapping("/get/first/pay/{goodsId}")
  796. public Result<Boolean> getFirstPay(@PathVariable Long goodsId) {
  797. long userId = StpUserUtil.getLoginIdAsLong();
  798. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  799. Number number = beanSearcher.searchCount(OrderDon.class, MapUtils.builder()
  800. .field(OrderDon::getGoodsId, goodsId)
  801. .field(OrderDon::getCreatedTime, new DateTime().toDateStr()).op(Operator.LessEqual)
  802. .field(OrderDon::getUserId, userIdList).op(Operator.InList)
  803. .field(OrderDon::getStatus, Constant.noOrderStatus).op(Operator.NotIn)
  804. .build());
  805. if (number.intValue() == 0) {
  806. UserGoodsNewbieGuideRecord userGoodsNewbieGuideRecord = new UserGoodsNewbieGuideRecord();
  807. userGoodsNewbieGuideRecord.setGoodsId(goodsId);
  808. userGoodsNewbieGuideRecord.setUserId(userId);
  809. userGoodsNewbieGuideRecordMapper.insert(userGoodsNewbieGuideRecord);
  810. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  811. }
  812. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  813. }
  814. /**
  815. * 设置pin码
  816. */
  817. @PutMapping("/set/pin/{relationId}")
  818. public Result<String> setPin(@PathVariable Long relationId, String code) {
  819. long userId = StpUserUtil.getLoginIdAsLong();
  820. JSONObject data = groupsRelationNetflixService.setNetflixPin(relationId, userId, code);
  821. return GatewayResponse.SUCCESS.newBuilder().toResult(data.toString());
  822. }
  823. /**
  824. * 查询是否设置成功
  825. */
  826. @GetMapping("/get/pin/status/{taskId}")
  827. public Result<Integer> getPinStatus(@PathVariable String taskId) throws Exception {
  828. long userId = StpUserUtil.getLoginIdAsLong();
  829. log.info("userId:{}查看设置pin码状态", userId);
  830. return GatewayResponse.SUCCESS.newBuilder().toResult(groupsRelationNetflixService.getPinStatus(taskId));
  831. }
  832. /**
  833. * 踢出奈飞设备
  834. */
  835. @PostMapping("/kickOut/nf/{relationId}")
  836. public Result<String> nfKickOut(@PathVariable Long relationId) {
  837. long userId = StpUserUtil.getLoginIdAsLong();
  838. JSONObject data = groupsRelationNetflixService.nfKickOut(userId, relationId);
  839. return GatewayResponse.SUCCESS.newBuilder().toResult(data.toString());
  840. }
  841. /**
  842. * 奈飞同户装置链接
  843. */
  844. @GetMapping("/get/nf/household/device")
  845. public Result<String> getNfHouseholdDevice(@NotNull Long relationId) throws Exception {
  846. long userId = StpUserUtil.getLoginIdAsLong();
  847. String url = groupRelationFrontService.getNfHouseholdDevice(userId, relationId);
  848. return GatewayResponse.SUCCESS.newBuilder().toResult(url);
  849. }
  850. /**
  851. * 代点奈飞同户装置
  852. */
  853. @PostMapping("/click/nf/household/device")
  854. public void clickNfHouseholdDevice(@RequestBody NfDeviceReq nfDeviceReq) {
  855. groupsRelationNetflixService.clickNfHouseholdDevice(nfDeviceReq);
  856. }
  857. /**
  858. * 可选 续费升级车票
  859. */
  860. @GetMapping("/get/renew/skus/{relationId}/{skuId}")
  861. public Result<List<RenewUpgradePackageFrontView>> getRenewSkus(@PathVariable Long relationId, @PathVariable Long skuId) {
  862. long userId = StpUserUtil.getLoginIdAsLong();
  863. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  864. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
  865. .eq(ChatgptUser::getRelationId, relationId)
  866. .last("limit 1"));
  867. if (chatgptUser == null) return GatewayResponse.SUCCESS.newBuilder().toResult();
  868. //目前续费升级的规格
  869. Long renewSkuId = chatgptUser.getRenewSkuId();
  870. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  871. AtomicInteger minMonths = new AtomicInteger(sku.getMonths());
  872. AtomicInteger minNum = new AtomicInteger(chatgptUser.getLimitNum());
  873. AtomicLong minTime = new AtomicLong(chatgptUser.getLimitTime());
  874. if (renewSkuId != null) {
  875. GoodsDonSku presentRenew = goodsDonSkuMapper.selectById(renewSkuId);
  876. minMonths.set(presentRenew.getMonths());
  877. }
  878. if (chatgptUser.getPackageId() != 0) {
  879. Long packageId = chatgptUser.getPackageId();
  880. UpgradeOrderDon upgradeOrderDon = upgradeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UpgradeOrderDon.class)
  881. .eq(UpgradeOrderDon::getPackageId, packageId)
  882. .eq(UpgradeOrderDon::getRelationId, relationId)
  883. .in(UpgradeOrderDon::getUserId, userIdList)
  884. .last("limit 1"));
  885. Long upgradeOrderDonSkuId = upgradeOrderDon.getSkuId();
  886. GoodsDonSku upgradeSku = goodsDonSkuMapper.selectById(upgradeOrderDonSkuId);
  887. if (upgradeSku != null) {
  888. if (upgradeSku.getMonths() > minMonths.get()) {
  889. minMonths.set(upgradeSku.getMonths());
  890. }
  891. }
  892. }
  893. List<RenewUpgradePackageFrontView> renewUpgradePackageFrontViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.class, MapUtils.builder().field(RenewUpgradePackageFrontView::getSkuId, skuId).build());
  894. renewUpgradePackageFrontViews.forEach(renew -> {
  895. try {
  896. List<Long> upgradeSkuIds = Jsons.parseList(renew.getUpgradeSkuIds(), Long.class);
  897. //年付展示
  898. MapBuilder builder = MapUtils.builder();
  899. // if (minMonths.get() == 12) {
  900. // builder.field(RenewUpgradePackageFrontView.RenewSkuView::getMonths, minMonths.get()).op(Operator.GreaterEqual);
  901. // if (renewSkuId != null) {
  902. // upgradeSkuIds.remove(renewSkuId);
  903. // }
  904. // } else {
  905. // builder.field(RenewUpgradePackageFrontView.RenewSkuView::getMonths, minMonths.get()).op(Operator.GreaterEqual);
  906. // }
  907. //GPT镜像2月规格 特殊处理
  908. if (sku.getGoodsId() == 18 && sku.getMonths() == 2) {
  909. } else {
  910. //同续费时间规格
  911. builder.field(RenewUpgradePackageFrontView.RenewSkuView::getMonths, minMonths.get()).op(Operator.GreaterEqual);
  912. }
  913. if (renewSkuId != null) {
  914. upgradeSkuIds.remove(renewSkuId);
  915. }
  916. List<RenewUpgradePackageFrontView.RenewSkuView> renewSkuViews = new ArrayList<>();
  917. if (CollUtil.isNotEmpty(upgradeSkuIds)) {
  918. renewSkuViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.RenewSkuView.class, builder
  919. .field(RenewUpgradePackageFrontView.RenewSkuView::getGptLimitNum, minNum.get()).op(Operator.GreaterEqual)
  920. .field(RenewUpgradePackageFrontView.RenewSkuView::getGptLimitTime, minTime.get()).op(LessEqual.class)
  921. .field(RenewUpgradePackageFrontView.RenewSkuView::getSkuId, upgradeSkuIds).op(Operator.InList)
  922. .build());
  923. }
  924. renew.setRenewSkus(renewSkuViews);
  925. } catch (Exception e) {
  926. }
  927. });
  928. return GatewayResponse.SUCCESS.newBuilder().toResult(renewUpgradePackageFrontViews);
  929. }
  930. /**
  931. * 独立规格续费套餐列表
  932. */
  933. @GetMapping("/get/independent/renew/skus/{skuId}")
  934. public Result<List<RenewUpgradePackageFrontView>> getRenewSkus(@PathVariable Long skuId) {
  935. long userId = StpUserUtil.getLoginIdAsLong();
  936. List<RenewUpgradePackageFrontView> renewUpgradePackageFrontViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.class, MapUtils.builder().field(RenewUpgradePackageFrontView::getSkuId, skuId).build());
  937. renewUpgradePackageFrontViews.forEach(renew -> {
  938. try {
  939. List<Long> upgradeSkuIds = Jsons.parseList(renew.getUpgradeSkuIds(), Long.class);
  940. MapBuilder builder = MapUtils.builder();
  941. List<RenewUpgradePackageFrontView.RenewSkuView> renewSkuViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.RenewSkuView.class, builder
  942. .field(RenewUpgradePackageFrontView.RenewSkuView::getSkuId, upgradeSkuIds).op(Operator.InList)
  943. .build());
  944. renew.setRenewSkus(renewSkuViews);
  945. } catch (Exception e) {
  946. }
  947. });
  948. return GatewayResponse.SUCCESS.newBuilder().toResult(renewUpgradePackageFrontViews);
  949. }
  950. /**
  951. * claude pro续费升级
  952. */
  953. @GetMapping("/get/claude/renew/skus/{relationId}/{skuId}")
  954. public Result<List<RenewUpgradePackageFrontView> > getClaudeRenewSkus(@PathVariable Long relationId, @PathVariable Long skuId) {
  955. long userId = StpUserUtil.getLoginIdAsLong();
  956. ClaudeUser claudeUser = claudeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeUser.class)
  957. .eq(ClaudeUser::getRelationId, relationId)
  958. .last("limit 1"));
  959. if (claudeUser == null) return GatewayResponse.SUCCESS.newBuilder().toResult();
  960. List<RenewUpgradePackageFrontView> renewUpgradePackageFrontViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.class, MapUtils.builder().field(RenewUpgradePackageFrontView::getSkuId, skuId).build());
  961. renewUpgradePackageFrontViews.forEach(renew -> {
  962. try {
  963. List<Long> upgradeSkuIds = Jsons.parseList(renew.getUpgradeSkuIds(), Long.class);
  964. MapBuilder builder = MapUtils.builder();
  965. List<RenewUpgradePackageFrontView.RenewSkuView> renewSkuViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.RenewSkuView.class, builder
  966. .field(RenewUpgradePackageFrontView.RenewSkuView::getSkuId, upgradeSkuIds).op(Operator.InList)
  967. .field(RenewUpgradePackageFrontView.RenewSkuView::getGptLimitNum, claudeUser.getLimitNum()).op(Operator.GreaterEqual)
  968. .build());
  969. renew.setRenewSkus(renewSkuViews);
  970. } catch (Exception e) {
  971. }
  972. });
  973. return GatewayResponse.SUCCESS.newBuilder().toResult(renewUpgradePackageFrontViews);
  974. }
  975. /**
  976. * 已配置的续费升级规格ids
  977. */
  978. @GetMapping("/get/renew/skus/configured")
  979. public Result<List<Long> > getClaudeRenewSkus() {
  980. long userId = StpUserUtil.getLoginIdAsLong();
  981. List<RenewUpgradePackageFrontView> renewUpgradePackageFrontViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.class, MapUtils.builder().onlySelect(RenewUpgradePackageFrontView::getSkuId).build());
  982. List<Long> collect = renewUpgradePackageFrontViews.stream().map(RenewUpgradePackageFrontView::getSkuId).collect(Collectors.toList());
  983. return GatewayResponse.SUCCESS.newBuilder().toResult(collect);
  984. }
  985. /**
  986. * 获取GPT PLUS登录验证码
  987. */
  988. @GetMapping("/get/verify/code")
  989. public Result<String> getVerifyCode(@NotEmpty String account) throws Exception {
  990. String code = groupRelationFrontService.getVerifyCode(account);
  991. if (StrUtil.isEmpty(code)) {
  992. throw BusinessRuntimeException.getInstance("请重新发送验证码");
  993. }
  994. return GatewayResponse.SUCCESS.newBuilder().toResult(code);
  995. }
  996. /**
  997. * 独立规格续费减免
  998. */
  999. @GetMapping("/get/renew/reduce")
  1000. public Result<UserBenefitsFrontView> getRenewReduce(Long skuId, Long relationId) {
  1001. long userId = StpUserUtil.getLoginIdAsLong();
  1002. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1003. UserBenefitsFrontView data = beanSearcher.searchFirst(UserBenefitsFrontView.class, MapUtils.builder().field(UserBenefitsFrontView::getSkuId, skuId).field(UserBenefitsFrontView::getType, UserBenefits.Type.RENEW.name()).build());
  1004. if (data == null) {
  1005. return GatewayResponse.SUCCESS.newBuilder().toResult();
  1006. }
  1007. Date startTime = null;
  1008. if (relationId != null) {
  1009. GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  1010. .eq(GroupsRelation::getId, relationId)
  1011. .in(GroupsRelation::getUserId, userIdList));
  1012. if (relation == null) {
  1013. throw BusinessRuntimeException.getInstance("车票不存在");
  1014. }
  1015. startTime = relation.getStartTime();
  1016. }
  1017. Integer renewCount = userBenefitsOrderRecordMapper.selectUseComboRecordByUid(userIdList, data.getType(), data.getGoodsId(), data.getSkuId(), Constant.noOrderAllStatus, null, startTime, relationId);
  1018. data.setRenewCount(renewCount);
  1019. return GatewayResponse.SUCCESS.newBuilder().toResult(data);
  1020. }
  1021. /**
  1022. * 申请更换车票
  1023. */
  1024. @PostMapping("/change/ticket")
  1025. public Result<String> changeTicket(@RequestBody ChangeTicketReq changeTicketReq) {
  1026. long userId = StpUserUtil.getLoginIdAsLong();
  1027. List<Long> relationIds = changeTicketReq.getRelationIds();
  1028. if (CollUtil.isEmpty(relationIds)) {
  1029. return GatewayResponse.SUCCESS.newBuilder().toResult();
  1030. }
  1031. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1032. //奈飞超过3帐车票不给看
  1033. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  1034. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1035. .field(RenewalView::getGoodsId, 1)
  1036. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1037. .build());
  1038. if (number.intValue() > 2) {
  1039. return GatewayResponse.SUCCESS.newBuilder().toResult();
  1040. }
  1041. relationIds.forEach(relationId -> {
  1042. try {
  1043. groupRelationFrontService.changeTicket(userId, relationId);
  1044. } catch (Exception e) {
  1045. log.error("更换车票失败:{}", StringUtil.getErrorText(e));
  1046. if (relationIds.size() == 1) {
  1047. throw BusinessRuntimeException.getInstance(e.getMessage());
  1048. }
  1049. }
  1050. });
  1051. return GatewayResponse.SUCCESS.newBuilder().toResult();
  1052. }
  1053. /**
  1054. * 查看临时账号
  1055. */
  1056. @GetMapping("/get/temp/account/{relationId}")
  1057. public Result<AccountView> getTempAccount(@PathVariable Long relationId) {
  1058. long userId = StpUserUtil.getLoginIdAsLong();
  1059. AccountView accountView = groupRelationFrontService.getTempAccount(userId, relationId);
  1060. return GatewayResponse.SUCCESS.newBuilder().toResult(accountView);
  1061. }
  1062. /**
  1063. * 申请提交记录
  1064. */
  1065. @GetMapping("/get/netflix/get/error/submit/record")
  1066. public Result<List<NetflixUserAccountStatusRecord>> getUserNetflixSubmitRecord() {
  1067. long userId = StpUserUtil.getLoginIdAsLong();
  1068. List<NetflixUserAccountStatusRecord> netflixUserAccountStatusRecords = groupRelationFrontService.getUserNetflixSubmitRecord(userId);
  1069. return GatewayResponse.SUCCESS.newBuilder().toResult(netflixUserAccountStatusRecords);
  1070. }
  1071. /**
  1072. * 奈飞账号异常检测提交
  1073. */
  1074. @PostMapping("/netflix/error/account/submit/{relationId}")
  1075. public Result<String> nfErrorAccountSubmit(@PathVariable Long relationId) {
  1076. long userId = StpUserUtil.getLoginIdAsLong();
  1077. groupRelationFrontService.nfErrorAccountSubmit(userId, relationId);
  1078. return GatewayResponse.SUCCESS.newBuilder().toResult();
  1079. }
  1080. /**
  1081. * 奈飞账号检测结果
  1082. */
  1083. @GetMapping("/get/netflix/error/account/status/{relationId}")
  1084. public Result<Integer> getNetflixErrorAccountStatus(@PathVariable Long relationId) {
  1085. long userId = StpUserUtil.getLoginIdAsLong();
  1086. Integer state = groupRelationFrontService.getNetflixErrorAccountStatus(userId, relationId);
  1087. return GatewayResponse.SUCCESS.newBuilder().toResult(state);
  1088. }
  1089. }