GroupRelationController.java 59 KB

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