GroupRelationFrontServiceImpl.java 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122
  1. package com.cyksj.service.relation.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.collection.CollectionUtil;
  4. import cn.hutool.core.date.BetweenFormater;
  5. import cn.hutool.core.date.DateTime;
  6. import cn.hutool.core.date.DateUtil;
  7. import cn.hutool.core.lang.Assert;
  8. import cn.hutool.core.lang.Validator;
  9. import cn.hutool.core.util.ObjectUtil;
  10. import cn.hutool.core.util.StrUtil;
  11. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  12. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  13. import com.cyksj.common.constant.Constant;
  14. import com.cyksj.common.exception.BusinessRuntimeException;
  15. import com.cyksj.common.snowflake.Sequence;
  16. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  17. import com.cyksj.common.util.Jsons;
  18. import com.cyksj.common.util.StringUtil;
  19. import com.cyksj.enums.GatewayApiCode;
  20. import com.cyksj.mapper.*;
  21. import com.cyksj.mapper.codex.CodexUserRenewExpiryRecordMapper;
  22. import com.cyksj.mapper.manage.distribute.DistributeGeneralSkuRateMapper;
  23. import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
  24. import com.cyksj.mapper.manage.distribute.UserPlatDistributeRateMapper;
  25. import com.cyksj.mapper.manage.distribute.UserPlatSkuDistributeRateMapper;
  26. import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
  27. import com.cyksj.mapper.renew.RenewUpgradePackageMapper;
  28. import com.cyksj.mapper.sys.SysConfigMapper;
  29. import com.cyksj.mapper.sys.SysEmailMapper;
  30. import com.cyksj.mapper.vip.VipGoodsSkuMapper;
  31. import com.cyksj.mapper.vip.VipUserMapper;
  32. import com.cyksj.model.dto.ErrorNetflixChangeOtherSkuTicketDto;
  33. import com.cyksj.model.dto.NetflixRecoverReceivedGptConditionDto;
  34. import com.cyksj.model.dto.OrderRefundDto;
  35. import com.cyksj.model.dto.TicketChangeDto;
  36. import com.cyksj.model.entity.*;
  37. import com.cyksj.model.manage.views.AccountView;
  38. import com.cyksj.model.manage.views.GroupsRelationView;
  39. import com.cyksj.model.request.ErrorNetflixChangeReq;
  40. import com.cyksj.model.request.OrderRefundReq;
  41. import com.cyksj.model.request.SpecialGoodsTicketReq;
  42. import com.cyksj.model.request.TicketLoginReq;
  43. import com.cyksj.model.response.NetflixErrorAccountStatus;
  44. import com.cyksj.model.response.NetflixRecoverResp;
  45. import com.cyksj.model.response.NetflixRefundInfoResp;
  46. import com.cyksj.model.views.*;
  47. import com.cyksj.redis.RedisService;
  48. import com.cyksj.service.chatgpt.ChatGptAccountService;
  49. import com.cyksj.service.chatgpt.ChatGptAuthService;
  50. import com.cyksj.service.claude.ClaudeCodeService;
  51. import com.cyksj.service.claude.ClaudeService;
  52. import com.cyksj.service.codex.CodexService;
  53. import com.cyksj.service.groups.GroupsFuncService;
  54. import com.cyksj.service.luma.LumaService;
  55. import com.cyksj.service.mail.CommonMailService;
  56. import com.cyksj.service.mail.MailService;
  57. import com.cyksj.service.mange.coupon.CouponCommonService;
  58. import com.cyksj.service.midjourney.MidjourneyAccountService;
  59. import com.cyksj.service.order.OrderRefundService;
  60. import com.cyksj.service.relation.GroupRelationClearService;
  61. import com.cyksj.service.relation.GroupRelationFrontService;
  62. import com.cyksj.service.relation.GroupsRelationChangeService;
  63. import com.cyksj.service.sora.SoraCodeFrontService;
  64. import com.cyksj.service.translations.BackInfoTranslationsFrontService;
  65. import com.cyksj.service.user.UserBenefitsService;
  66. import com.cyksj.service.user.UserBindRelationService;
  67. import com.cyksj.service.user.UserLoginRecordService;
  68. import com.ejlchina.searcher.BeanSearcher;
  69. import com.ejlchina.searcher.SearchResult;
  70. import com.ejlchina.searcher.param.Operator;
  71. import com.ejlchina.searcher.util.MapBuilder;
  72. import com.ejlchina.searcher.util.MapUtils;
  73. import com.github.rholder.retry.*;
  74. import lombok.RequiredArgsConstructor;
  75. import lombok.extern.slf4j.Slf4j;
  76. import org.springframework.dao.DuplicateKeyException;
  77. import org.springframework.stereotype.Service;
  78. import org.springframework.transaction.annotation.Transactional;
  79. import javax.servlet.http.HttpServletRequest;
  80. import java.math.BigDecimal;
  81. import java.math.RoundingMode;
  82. import java.util.*;
  83. import java.util.concurrent.ExecutionException;
  84. import java.util.concurrent.TimeUnit;
  85. import java.util.concurrent.atomic.AtomicInteger;
  86. import java.util.stream.Collectors;
  87. import static com.cyksj.enums.GatewayApiCode.GROUP_INDEX_ALREADY_BE_USER;
  88. import static com.cyksj.enums.GatewayApiCode.GROUP_INDEX_NOT_FIND;
  89. /*
  90. *项目名: netflix
  91. *文件名: GroupRelationFrontServiceImpl
  92. *创建者: JavaZou
  93. *创建时间:2022/12/29 15:42
  94. */
  95. @Service
  96. @RequiredArgsConstructor
  97. @Slf4j
  98. public class GroupRelationFrontServiceImpl implements GroupRelationFrontService {
  99. private final UserBindRelationService userBindRelationService;
  100. private final UserMapper userMapper;
  101. private final BeanSearcher beanSearcher;
  102. private final CouponCommonService couponCommonService;
  103. private final GroupsRelationMapper groupsRelationMapper;
  104. private final GroupsMapper groupsMapper;
  105. private final ChatGptAuthService chatGptAuthService;
  106. private final RedisService redisService;
  107. private final MailService mailService;
  108. private final OrderDonMapper orderDonMapper;
  109. private final GroupsRelationExpiryNotifyRecordMapper groupsRelationExpiryNotifyRecordMapper;
  110. private final HttpServletRequest request;
  111. private final GroupsFuncService groupsFuncService;
  112. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  113. private final GroupsRelationLoginCodeRecordMapper groupsRelationLoginCodeRecordMapper;
  114. private final SysEmailMapper sysEmailMapper;
  115. private final GoodsDonSkuMapper goodsDonSkuMapper;
  116. private final UserFuncPropertyMapper userFuncPropertyMapper;
  117. private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
  118. private final UserLoginRecordService userLoginRecordService;
  119. private final UserCertRecordMapper userCertRecordMapper;
  120. private final MidjourneyAccountService midjourneyAccountService;
  121. private final ChatGptAccountService chatGptAccountService;
  122. private final UpgradePackageMapper upgradePackageMapper;
  123. private final LumaService lumaService;
  124. private final BackInfoTranslationsFrontService backInfoTranslationsFrontService;
  125. private final UserDistributeMapper userDistributeMapper;
  126. private final UserPlatDistributeRateMapper userPlatDistributeRateMapper;
  127. private final GoodsDonMapper goodsDonMapper;
  128. private final UserPlatSkuDistributeRateMapper userPlatSkuDistributeRateMapper;
  129. private final DistributeGeneralSkuRateMapper distributeGeneralSkuRateMapper;
  130. private final RenewUpgradePackageMapper renewUpgradePackageMapper;
  131. private final ClaudeService claudeService;
  132. private final UserDistributePosterRecordMapper userDistributePosterRecordMapper;
  133. private final OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  134. private final AccountMapper accountMapper;
  135. private final UserBenefitsMapper userBenefitsMapper;
  136. private final GroupsRelationChangeService changeTickerRelation;
  137. private final NetflixTempAccountUserMapper netflixTempAccountUserMapper;
  138. private final NetflixUserAccountStatusRecordMapper netflixUserAccountStatusRecordMapper;
  139. private final AccountNetflixStateMapper accountNetflixStateMapper;
  140. private final UserMirrorShopMapper userMirrorShopMapper;
  141. private final CommonMailService commonMailService;
  142. private final SysConfigMapper sysConfigMapper;
  143. private final GptMirrorDayCardGiveawayActivityMapper gptMirrorDayCardGiveawayActivityMapper;
  144. private final MirrorTicketPopupsRecordMapper mirrorTicketPopupsRecordMapper;
  145. private final VipUserMapper vipUserMapper;
  146. private final VipGoodsSkuMapper vipGoodsSkuMapper;
  147. private static final Sequence SEQUENCE = new Sequence(0);
  148. private final NetflixUserChangeOtherTicketRecordMapper netflixUserChangeOtherTicketRecordMapper;
  149. private final NetflixUserAccountSubmitRecoverRecordMapper netflixUserAccountSubmitRecoverRecordMapper;
  150. private final OrderRefundService orderRefundService;
  151. private final GroupRelationClearService clearService;
  152. private final UserBenefitsService userBenefitsService;
  153. private final ChatgptUserMapper chatgptUserMapper;
  154. private final ClaudeCodeUserRenewExpiryRecordMapper claudeCodeUserRenewExpiryRecordMapper;
  155. private final GoodsDonCategoryRelateMapper goodsDonCategoryRelateMapper;
  156. private final ClaudeCodeService claudeCodeService;
  157. private final NanoUserQuotaMapper nanoUserQuotaMapper;
  158. private final CodexService codexService;
  159. private final CodexUserRenewExpiryRecordMapper codexUserRenewExpiryRecordMapper;
  160. private final CodexUserMapper codexUserMapper;
  161. private final AccountNetflixFrozenTicketReceivedRecordMapper accountNetflixFrozenTicketReceivedRecordMapper;
  162. private final SoraCodeMapper soraCodeMapper;
  163. private final SoraCodeFrontService soraCodeFrontService;
  164. private final ClaudeUserMapper claudeUserMapper;
  165. private final UserRenewChangeTicketRecordMapper userRenewChangeTicketRecordMapper;
  166. private final NetflixCompensateReceivedRecordMapper netflixCompensateReceivedRecordMapper;
  167. @Override
  168. public SearchResult<RenewalView> getMyTicket(long userId, Boolean isLoginPopularize, String customId, String account, String orderNo, Integer cmt) {
  169. User u = userMapper.selectById(userId);
  170. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  171. if (u.getIsBlack()) {
  172. return new SearchResult<>();
  173. }
  174. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  175. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  176. if (cmt != null && cmt == 2 && StrUtil.isNotBlank(customId)) {
  177. UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
  178. .eq(UserMirrorShop::getCustomId, customId)
  179. .last("limit 1"));
  180. if (userMirrorShop != null) {
  181. builder.field(RenewalView::getCmt, cmt).field(RenewalView::getYhsId, userMirrorShop.getId());
  182. }
  183. }
  184. if (cmt == null || cmt != 2) {
  185. builder.field(RenewalView::getCmt, 2).op(Operator.NotEqual);
  186. }
  187. // Long yhsId = yhShopFrontService.getYhsIdByCustomId(customId);
  188. DateTime now = DateTime.now();
  189. if (StrUtil.isNotBlank(account)) {
  190. builder.field(RenewalView::getAccount, account).op(Operator.Contain);
  191. }
  192. //代充剩余次数大于0/未发车/过期时间/冻结时/恢复中
  193. String conditionSql = String.format("(gr.recharge_remain_num > 0 or gr.expiry_time is null or gr.expiry_time > '%s' or gr.is_frozen = true or gr.is_recover = true", now);
  194. //镜像车票 过期7天后清除
  195. //个人店铺和AI店铺 暂不支持过期续费
  196. if (cmt == null && StrUtil.isEmpty(customId)) {
  197. conditionSql += String.format(" or (sku.is_mirror and gr.expiry_time > '%s')", DateUtil.offsetDay(now, -7));
  198. }
  199. conditionSql += ")";
  200. if (StrUtil.isNotEmpty(orderNo)) {
  201. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  202. .eq(OrderDon::getOrderNo, orderNo)
  203. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  204. .last("limit 1"));
  205. Long orderId = orderDon != null ? orderDon.getId() : 0l;
  206. conditionSql += String.format(" and exists(select 1 from order_don o where o.relation_id = gr.id and o.user_id = gr.user_id and o.id = %s)", orderId);
  207. }
  208. SearchResult<RenewalView> list = beanSearcher.search(RenewalView.class, builder
  209. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  210. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  211. .put("condition", conditionSql)
  212. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  213. .orderBy(RenewalView::getExpiryTime).asc()
  214. .build());
  215. if (list.getDataList().size() > 0) {
  216. String lang = request.getHeader("lang");
  217. //过滤邀请制、已失效的车位
  218. Integer size = list.getTotalCount().intValue();
  219. //赠送GPT日卡 参与平台ids
  220. List<Long> renewReduceSkuIds = userBenefitsMapper.selectList(Wrappers.lambdaQuery(UserBenefits.class)
  221. .eq(UserBenefits::getType, UserBenefits.Type.RENEW).eq(UserBenefits::getStatus, 1).select(UserBenefits::getSkuId)).stream().map(UserBenefits::getSkuId).collect(Collectors.toList());
  222. List<Long> gptBuyGids = getGptMirrorGiveawayBuyGids();
  223. //gpt日卡活动
  224. GptMirrorDayCardGiveawayActivity gptMirrorDayCardGiveawayActivity = gptMirrorDayCardGiveawayActivityMapper.selectOne(Wrappers.lambdaQuery(GptMirrorDayCardGiveawayActivity.class)
  225. .last("limit 1"));
  226. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  227. .eq(SysConfig::getSysKey, Constant.EMAIL_PWD_SHOW_GID_KEY)
  228. .last("limit 1"));
  229. List<Long> showEmailPwdGids = new ArrayList<>();
  230. if (sysConfig != null && StrUtil.isNotBlank(sysConfig.getSysValue())) {
  231. try {
  232. showEmailPwdGids.addAll(Jsons.parseList(sysConfig.getSysValue(), Long.class));
  233. } catch (Exception e) {
  234. }
  235. }
  236. List<Long> vipSkuIds = vipGoodsSkuMapper.selectUpSkus().stream().map(VipGoodsSku::getSkuId).collect(Collectors.toList());
  237. Set<Long> vipGoodsIds = goodsDonSkuMapper.selectList(Wrappers.lambdaQuery(GoodsDonSku.class)
  238. .in(GoodsDonSku::getId, vipSkuIds)).stream().map(GoodsDonSku::getGoodsId).collect(Collectors.toSet());
  239. Integer vipUserCount = vipUserMapper.selectCount(Wrappers.lambdaQuery(VipUser.class)
  240. .in(VipUser::getUserId, userIds)
  241. .gt(VipUser::getExpiryTime, now));
  242. list.getDataList().forEach(ticket -> {
  243. if (ticket.getSkuId() == null || ticket.getGoodsId() == null) {
  244. return;
  245. }
  246. if (ticket.getGoodsId() == 18 && ticket.getSkuNum() > 1) {
  247. ticket.setPassword(null);
  248. }
  249. ticket.setIsMulti(false);
  250. if (ticket.getSkuNum() > 1) {
  251. ticket.setIsMulti(true);
  252. }
  253. //分类ids
  254. ticket.setCategoryIdList(goodsDonCategoryRelateMapper.selectCategoryIdsByGid(ticket.getGoodsId()));
  255. //chatGPT直连
  256. if (ticket.getGoodsId().equals(42l)) {
  257. if (StrUtil.isNotBlank(ticket.getAccount())) {
  258. String accessToken;
  259. try {
  260. accessToken = chatGptAuthService.getAccessToken(ticket.getAccount());
  261. ticket.setGptRefreshToken(accessToken);
  262. } catch (Exception e) {
  263. redisService.set(RedisService.key.CHAT_GPT_TOKEN_EXCEPTION_KEY.getName() + ticket.getAccount(), ticket.getAccount());
  264. }
  265. }
  266. ticket.setAccount(null);
  267. ticket.setPassword(null);
  268. } else {
  269. ticket.setGptRefreshToken(null);
  270. }
  271. if (ticket.getSecondType() == 1) {
  272. ticket.setAccount(null);
  273. ticket.setPassword(null);
  274. }
  275. //gpt 2月的独立账号可看到邮箱密码
  276. if (ticket.getGoodsId() == 18l && ticket.getSkuNum() == 1 && ticket.getAccount() != null && ticket.getCreatedTime().compareTo(DateUtil.parse("2025-02-01")) > 0) {
  277. } else {
  278. if (!showEmailPwdGids.contains(ticket.getGoodsId())) {
  279. ticket.setGptEmailPwd(null);
  280. }
  281. }
  282. if (isLoginPopularize != null && isLoginPopularize) {
  283. GoodsDonViews views = beanSearcher.searchFirst(GoodsDonViews.class, MapUtils.builder().field(GoodsDonViews::getId, ticket.getGoodsId()).build());
  284. views.setSpecs(beanSearcher.searchFirst(GoodsDonSpecFrontView.class, MapUtils.builder().field(GoodsDonSpecFrontView::getGoodsId, views.getId()).build()));
  285. views.setSkuList(beanSearcher.searchAll(GoodsDonSkuFrontView.class, MapUtils.builder().field(GoodsDonSkuFrontView::getGoodsId, views.getId()).field(GoodsDonSkuFrontView::getStatus, true).build()));
  286. ticket.setGoodsDonViews(views);
  287. }
  288. if (ticket.getMonths() != null && ticket.getMonths() >= 300) {
  289. ticket.setExpiryTime(null);
  290. }
  291. if (ticket.getExpiryTime() != null && ticket.getGoodsType() == 1) {
  292. String remainDays = DateUtil.formatBetween(now, ticket.getExpiryTime(), BetweenFormater.Level.DAY);
  293. if ("0天".equals(remainDays)) {
  294. remainDays = "小于1天";
  295. } else {
  296. //当天也算
  297. int days = Integer.parseInt(remainDays.substring(0, remainDays.indexOf("天")));
  298. remainDays = days + 1 + "天";
  299. }
  300. ticket.setRemainDays(remainDays);
  301. ticket.setTotal(DateUtil.betweenDay(ticket.getStartTime(), ticket.getExpiryTime(), false) + 1);
  302. }
  303. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  304. .eq(OrderDon::getRelationId, ticket.getRelationId())
  305. .in(OrderDon::getUserId, userIds)
  306. .eq(OrderDon::getOrderType, 1)
  307. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  308. .orderByDesc(OrderDon::getId)
  309. .last("limit 1"));
  310. Long zhSkuId = ticket.getSkuId();
  311. if (orderDon == null) {
  312. if (ticket.getGoodsId() == Constant.NETFLIX_GID) {
  313. //续费更换过车票
  314. UserRenewChangeTicketRecord record = userRenewChangeTicketRecordMapper.selectOne(Wrappers.lambdaQuery(UserRenewChangeTicketRecord.class)
  315. .in(UserRenewChangeTicketRecord::getUserId, userIds)
  316. .eq(UserRenewChangeTicketRecord::getAfterRelationId, ticket.getRelationId())
  317. .orderByDesc(UserRenewChangeTicketRecord::getId).last("limit 1"));
  318. if (record != null) {
  319. Long preRelationId = record.getPreRelationId();
  320. orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  321. .eq(OrderDon::getRelationId, preRelationId)
  322. .in(OrderDon::getUserId, userIds)
  323. .eq(OrderDon::getOrderType, 1)
  324. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  325. .orderByDesc(OrderDon::getId)
  326. .last("limit 1"));
  327. if (orderDon != null) {
  328. zhSkuId = orderDon.getSkuId();
  329. GoodsDonSku sku = goodsDonSkuMapper.selectById(zhSkuId);
  330. ticket.setSpecVal(sku.getSpecVal());
  331. }
  332. }
  333. }
  334. }
  335. if (orderDon != null) {
  336. ticket.setOrderNo(orderDon.getOrderNo());
  337. ticket.setOrderId(orderDon.getId());
  338. ticket.setTransactionId(orderDon.getTransactionId());
  339. ticket.setOrderCreatedTime(orderDon.getCreatedTime());
  340. if (ticket.getSecondType() == 1) {
  341. //是否完成邀请 根据订单状态
  342. ticket.setIsComplete(orderDon.getStatus() == OrderDon.Status.complete ? true : false);
  343. }
  344. }
  345. if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
  346. String languageSpecVal = backInfoTranslationsFrontService.getLanguageSpecVal(zhSkuId, lang);
  347. if (StrUtil.isNotBlank(languageSpecVal)) {
  348. ticket.setSpecVal(languageSpecVal);
  349. }
  350. }
  351. if (size > 1 && ticket.getGoodsId() != 18) {
  352. Date payTime = null;
  353. if (orderDon != null) {
  354. payTime = Optional.ofNullable(orderDon.getPayTime()).orElse(orderDon.getCreatedTime());
  355. }
  356. //加购订单
  357. if (orderDon == null) {
  358. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(ticket.getRelationId(), ticket.getUserId());
  359. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  360. String relationIds = data.getRelationIds();
  361. if (StrUtil.isEmpty(relationIds)) {
  362. return;
  363. }
  364. try {
  365. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  366. if (relationList.contains(ticket.getRelationId())) {
  367. OrderDon plusOrder = orderDonMapper.selectById(data.getOrderId());
  368. if (plusOrder != null) {
  369. payTime = Optional.ofNullable(plusOrder.getPayTime()).orElse(plusOrder.getCreatedTime());
  370. }
  371. break;
  372. }
  373. } catch (Exception e) {
  374. }
  375. }
  376. }
  377. ticket.setPayTime(payTime);
  378. }
  379. if (ticket.getSkuNum() != null && ticket.getSkuNum() == 1) {
  380. }
  381. //奈飞、gpt
  382. if (ticket.getGoodsId() == 1 || ticket.getGoodsId() == 18 || ticket.getGoodsId() == 33l) {
  383. ticket.setEmail(null);
  384. }
  385. //设置镜像车票信息
  386. // setMirrorTicketInfo(ticket);
  387. // List<GroupsRelationUserView> relationUserViews = groupsRelationMapper.getUserRelationUserViews(ticket.getGroupId(), ticket.getRelationId(), ticket.getUserId(), List.of(GroupsRelation.Status.validity, GroupsRelation.Status.outside));
  388. // ticket.setRelationViews(relationUserViews);
  389. if (ticket.getExpiryTime() != null) {
  390. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  391. }
  392. //查看双重验证码
  393. if (StrUtil.isNotEmpty(ticket.getApiSecret())) {
  394. Boolean isHasVerifyCode = StrUtil.isNotBlank(ticket.getVerifyCode()) ? true : false;
  395. Integer codeNum = getUserCodeNumBySkuId(ticket.getUserId(), ticket.getSkuId(), isHasVerifyCode);
  396. ticket.setCodeNum(codeNum);
  397. }
  398. Long qaId = groupsRelationMapper.selectGoodsDonQaByGoodsId(ticket.getGoodsId());
  399. ticket.setQa(qaId > 0 ? true : false);
  400. //是否存在海报
  401. ticket.setPosterInfo(setGoodsPoster(ticket, u, userIds));
  402. //续费升级折扣
  403. BigDecimal renewDiscount = getRenewDiscount(ticket.getGoodsId(), ticket.getSkuId(), ticket.getIsMirror(), ticket.getSkuNum());
  404. ticket.setDiscount(renewDiscount);
  405. if (CollUtil.isNotEmpty(renewReduceSkuIds) && renewReduceSkuIds.contains(ticket.getSkuId())) {
  406. ticket.setIsRenewReduce(true);
  407. }
  408. if (CollUtil.isNotEmpty(gptBuyGids) && gptBuyGids.contains(ticket.getGoodsId())) {
  409. if (gptMirrorDayCardGiveawayActivity != null && orderDon != null && orderDon.getCreatedTime().compareTo(gptMirrorDayCardGiveawayActivity.getCreatedTime()) > 0) {
  410. //是否领取过GPT日卡
  411. Long orderId = orderDon.getId();
  412. Number count = beanSearcher.searchCount(GptMirrorDayCardActivityRecord.class, MapUtils.builder().field(GptMirrorDayCardActivityRecord::getOrderId, orderId).build());
  413. ticket.setReceivedGptGift(count.intValue() > 0);
  414. }
  415. }
  416. markVipDeductTicket(userIds, ticket, vipGoodsIds, vipUserCount > 0);
  417. if (ticket.getIsVipDeduct() != null && ticket.getIsVipDeduct()) {
  418. //订单不存在
  419. if (orderDon == null) {
  420. ticket.setIsVipDeduct(Boolean.FALSE);
  421. }
  422. }
  423. //codex
  424. if (ticket.getGoodsId() == Constant.CODEX_GOODS_ID) {
  425. CodexUser codexUser = codexUserMapper.selectOne(Wrappers.lambdaQuery(CodexUser.class).eq(CodexUser::getRelationId, ticket.getRelationId()).last("limit 1"));
  426. if (codexUser != null) {
  427. ticket.setIsPay(codexUser.getIsPay());
  428. }
  429. }
  430. });
  431. }
  432. userLoginRecordService.saveUserLoginDayRecord(userId);
  433. return list;
  434. }
  435. @Override
  436. public Boolean isJoinCorpWx(Long userId, Boolean isJoin, Boolean noCoupon) {
  437. if (!isJoin) {
  438. User user = userMapper.selectById(userId);
  439. if (user == null || StrUtil.isEmpty(user.getUnionid())) {
  440. return true;
  441. }
  442. // CorpUser corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class)
  443. // .ne(CorpUser::getUnionid, "")
  444. // .eq(CorpUser::getUnionid, user.getUnionid())
  445. // .last("limit 1")
  446. // .select(CorpUser::getId)
  447. // );
  448. CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
  449. .field(CorpUserFollowView::getUnionId, user.getUnionid())
  450. .field(CorpUserFollowView::getStatus, 1).build());
  451. if (corpUserFollowView == null) {
  452. return false;
  453. }
  454. }
  455. //用户是否买了奈飞车票
  456. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  457. .field(RenewalView::getUserId, userId)
  458. .field(RenewalView::getGoodsId, 1)
  459. .field(RenewalView::getStatus, List.of("validity", "overdue")).op(Operator.InList)
  460. .build());
  461. if (number.intValue() > 0 && !noCoupon) {
  462. couponCommonService.sendCouponToUser(userId, 34l, 0l, 0l, 0l, CouponUser.Channel.wxCorp);
  463. }
  464. return true;
  465. }
  466. @Override
  467. public GroupsRelation getSimilarExpiredGroupRelation(GoodsDonSku sku, List<Long> errorsRelationIds, String ip) {
  468. Long skuId = sku.getId();
  469. Integer days = sku.getDays();
  470. Integer months = sku.getMonths();
  471. Integer maxNum = sku.getNum();
  472. DateTime expiryTime = null;
  473. if (days != null && days > 0) {
  474. expiryTime = DateUtil.offsetDay(DateTime.now(), days);
  475. } else {
  476. expiryTime = DateUtil.offsetMonth(DateTime.now(), months);
  477. }
  478. Integer extraNum = 5;
  479. if (sku.getId() == 178l) {
  480. extraNum = 2;
  481. }
  482. maxNum += extraNum;
  483. DateTime minExpiryTime = DateUtil.offsetDay(expiryTime, -5);
  484. Long groupsId = groupsRelationMapper.selectSimilarExpiredRelation(skuId, minExpiryTime, maxNum, ip);
  485. if (groupsId == null) {
  486. log.info("暂无相似过期时间车队");
  487. return null;
  488. }
  489. GroupsRelation relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  490. .notIn(errorsRelationIds != null && errorsRelationIds.size() > 0, GroupsRelation::getId, errorsRelationIds)
  491. .eq(GroupsRelation::getGroupsId, groupsId)
  492. .eq(GroupsRelation::getStatus, GroupsRelation.Status.none)
  493. .eq(GroupsRelation::getUserId, 0)
  494. .orderByAsc(GroupsRelation::getNum)
  495. .last("limit 1"));
  496. if (relation != null) {
  497. log.info("用户userId:{},获取相似车队的车位relationId:{}", relation.getId());
  498. }
  499. return relation;
  500. }
  501. @Override
  502. public Page<UserRecommendGoodsFrontView> getRecommendGoodsViews(List<Long> yhShopGoodsIds, Boolean isPayNf, List<Long> filter_goods_id, Boolean filterCourseGoods, Integer start, Integer limit) {
  503. return groupsRelationMapper.getRecommendGoodsViews(new Page<>(start, limit), filter_goods_id, isPayNf, filterCourseGoods, yhShopGoodsIds);
  504. }
  505. @Override
  506. @Transactional(rollbackFor = Throwable.class)
  507. public void sendCourseWare(SpecialGoodsTicketReq request) throws Exception {
  508. Long userId = request.getUserId();
  509. Long relationId = request.getRelationId();
  510. String email = request.getEmail();
  511. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  512. RenewalView relation = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getRelationId, relationId).build());
  513. Assert.notNull(relation, "您的车票不存在");
  514. Long relationUserId = relation.getUserId();
  515. if (!userIdList.contains(relationUserId)) {
  516. throw BusinessRuntimeException.getInstance("您的车票不存在");
  517. }
  518. if (relation.getSpecialType() != GoodsDon.SpecialType.courseware) {
  519. throw BusinessRuntimeException.getInstance("");
  520. }
  521. //是否已发送
  522. if (StrUtil.isNotBlank(relation.getGrAccount())) {
  523. throw BusinessRuntimeException.getInstance("已领取课件,请前往邮箱查看");
  524. }
  525. if (!Validator.isEmail(email)) {
  526. throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
  527. }
  528. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  529. .set(GroupsRelation::getAccount, email)
  530. .and(qr -> qr.isNull(GroupsRelation::getAccount).or().eq(GroupsRelation::getAccount, StrUtil.EMPTY))
  531. .eq(GroupsRelation::getId, relationId));
  532. if (update > 0) {
  533. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  534. .set(OrderDon::getStatus, OrderDon.Status.complete)
  535. .eq(OrderDon::getRelationId, relationId)
  536. .eq(OrderDon::getUserId, userId)
  537. .eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  538. mailService.sendCoursewareByGoodsId(relation.getGoodsId(), relation.getRelationId(), relation.getUserId(), relation.getTitle(), email);
  539. }
  540. }
  541. @Override
  542. public GroupsRelation getRelation(Long payRelationId, Long userId, GoodsDonSku sku, String ip) {
  543. GroupsRelation relation = null;
  544. Integer maxNum = sku.getNum();
  545. if (payRelationId != null && payRelationId > 0) {
  546. relation = groupsRelationMapper.selectById(payRelationId);
  547. if (relation == null) {
  548. throw new BusinessRuntimeException(GROUP_INDEX_NOT_FIND.getCode(), GROUP_INDEX_NOT_FIND.getMsg());
  549. }
  550. if (relation.getUserId() != null && relation.getUserId() > 0L) {
  551. throw new BusinessRuntimeException(GROUP_INDEX_ALREADY_BE_USER.getCode(), GROUP_INDEX_ALREADY_BE_USER.getMsg());
  552. }
  553. } else {
  554. GroupsTrips groups = null;
  555. //ChatGpt Plus、Midjourney非独立规格 上车先获取硬塞座位 硬塞5个座位
  556. //主账号过期时间25天以外
  557. //23-12-06 MidJourney 不硬塞
  558. if (sku.getNum() > 1 && Constant.AI_goodsIds.get(0) == sku.getGoodsId()) {
  559. Integer extraNum = 5;
  560. if (sku.getId() == 178l || sku.getId() == 423l) {
  561. extraNum = 2;
  562. }
  563. maxNum += extraNum;
  564. DateTime time = DateUtil.offsetDay(DateUtil.beginOfDay(DateTime.now()), 25);
  565. //不塞存在该用户的车队
  566. Long groupsId = groupsRelationMapper.getOutSideGroupsTripsRelationByGoodsId(sku.getId(), time, extraNum, userId, sku.getNum(), maxNum);
  567. if (groupsId != null) {
  568. relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  569. .eq(GroupsRelation::getGroupsId, groupsId)
  570. .eq(GroupsRelation::getUserId, 0)
  571. .eq(GroupsRelation::getStatus, GroupsRelation.Status.outside)
  572. .last("limit 1"));
  573. if (relation == null) {
  574. relation = new GroupsRelation();
  575. relation.setStatus(GroupsRelation.Status.outside);
  576. relation.setGroupsId(groupsId);
  577. GroupsRelation maxNumRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  578. Integer nextNum = maxNumRelation.getNum() + 1;
  579. if (redisService.setNx(RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getNameFormat(groupsId, nextNum), nextNum, RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getTimeout())) {
  580. relation.setNum(nextNum);
  581. groupsRelationMapper.insert(relation);
  582. } else {
  583. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  584. }
  585. }
  586. groups = groupsMapper.selectById(groupsId);
  587. }
  588. }
  589. if (groups == null) {
  590. //寻找差不多过期时间规格的车位
  591. relation = getSimilarExpiredGroupRelation(sku, null, ip);
  592. if (relation == null) {
  593. //TODO 如果没指定座位,等待逻辑确认
  594. DateTime filterAccountTime = null;
  595. // //奈飞过滤6月23号之前的车队
  596. // if (sku.getGoodsId() == Constant.NETFLIX_GID) {
  597. // filterAccountTime = DateUtil.parse("2025-06-23");
  598. // }
  599. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.validity, maxNum, ip, filterAccountTime);
  600. if (groups == null) {
  601. //待发车
  602. groups = groupsMapper.selectTicketGroups(sku.getId(), GroupsTrips.Status.waiting, maxNum, ip, null);
  603. }
  604. //新增空车队
  605. if (groups == null) {
  606. relation = groupsFuncService.createNewGroupsTrips(sku);
  607. }
  608. //获取车位
  609. if (relation == null) {
  610. //寻找快满编车队进行占座
  611. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  612. if (relation == null) {
  613. Long groupsId = groups.getId();
  614. TASK_EXECUTOR.execute(() -> groupsMapper.updateAvailableNum(groupsId));
  615. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  616. }
  617. }
  618. }
  619. }
  620. if (groups == null) {
  621. groups = groupsMapper.selectById(relation.getGroupsId());
  622. }
  623. //车队目前可用停车数
  624. relation.setGroupsAvailParkingNum(groups.getAvailableParkingNum());
  625. relation.setMaxNum(maxNum);
  626. }
  627. return relation;
  628. }
  629. @Override
  630. public String getAiVerifyCode(TicketLoginReq loginReq) throws Exception {
  631. Integer type = loginReq.getType();
  632. RenewalView renewalView;
  633. String account;
  634. Long userId = 0l;
  635. Long relationId = 0l;
  636. if (loginReq.getMerchants()) {
  637. renewalView = new RenewalView();
  638. renewalView.setGoodsId(loginReq.getGoodsId());
  639. renewalView.setAccount(loginReq.getAccount());
  640. if (loginReq.getAccountId() != null && loginReq.getAccountId() != 0l) {
  641. GroupsTrips groupsTrips = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  642. .eq(GroupsTrips::getAccountId, loginReq.getAccountId())
  643. .last("limit 1"));
  644. if (groupsTrips != null) {
  645. renewalView.setSkuId(groupsTrips.getSkuId());
  646. }
  647. }
  648. renewalView.setUserId(userId);
  649. account = loginReq.getAccount();
  650. } else {
  651. userId = loginReq.getUserId();
  652. relationId = loginReq.getRelationId();
  653. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  654. renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  655. .field(RenewalView::getRelationId, relationId).build());
  656. if (renewalView == null) {
  657. throw BusinessRuntimeException.getInstance("您的车票不存在...");
  658. }
  659. if (StrUtil.isEmpty(renewalView.getAccount())) {
  660. throw BusinessRuntimeException.getInstance("车票未配置账号");
  661. }
  662. account = renewalView.getAccount();
  663. String password = renewalView.getPassword();
  664. if (StrUtil.hasEmpty(account, password)) {
  665. throw BusinessRuntimeException.getInstance("您的车票账号密码异常,请联系客服...");
  666. }
  667. }
  668. if (renewalView.getGoodsId() == 1l) {
  669. Integer linkType = loginReq.getLinkType();
  670. if (type == null && linkType == null) {
  671. throw BusinessRuntimeException.getInstance("系统异常");
  672. }
  673. if (linkType != null) {
  674. String key = RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getNameFormat(DateUtil.hour(DateTime.now(), true), linkType, renewalView.getUserId());
  675. if (!redisService.hasKey(key)) {
  676. redisService.set(key, 0l, RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getTimeout());
  677. } else {
  678. Integer value = (Integer) redisService.get(key);
  679. if (value >= 5) {
  680. throw BusinessRuntimeException.getInstance("获取奈飞同步更新装置过于频繁");
  681. }
  682. }
  683. }
  684. }
  685. String code = commonMailService.getTicketMailCode(renewalView.getGoodsId(), account, renewalView.getRelateEmail(), renewalView.getGptEmailPwd(), renewalView.getCreatedTime(), type, loginReq.getLinkType(), false);
  686. GroupsRelationLoginCodeRecord record = new GroupsRelationLoginCodeRecord();
  687. record.setUserId(userId);
  688. record.setRelationId(relationId);
  689. record.setAccount(renewalView.getAccount());
  690. record.setGoodsId(renewalView.getGoodsId());
  691. record.setSkuId(renewalView.getSkuId());
  692. groupsRelationLoginCodeRecordMapper.insert(record);
  693. //奈飞同步装置
  694. if (renewalView.getGoodsId() == 1l && loginReq.getLinkType() != null) {
  695. String key = RedisService.key.NF_UPGRAD_USER_LIMIT_KEY.getNameFormat(DateUtil.hour(DateTime.now(), true), loginReq.getLinkType(), renewalView.getUserId());
  696. redisService.incr(key, 1L);
  697. }
  698. return code;
  699. }
  700. @Override
  701. public void checkGroupsAvailParkingNum(Long skuId, Long groupsId, Integer availableParkingNum, Integer maxNum) {
  702. //GPT10人月付、4人月付
  703. if (skuId == 161l || skuId == 178l) {
  704. //为0时,不参与限制
  705. if (availableParkingNum == 0) {
  706. return;
  707. }
  708. //目前车队可用停车数
  709. //目前上车人数
  710. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  711. .eq(GroupsRelation::getGroupsId, groupsId)
  712. .ne(GroupsRelation::getUserId, 0)
  713. .le(GroupsRelation::getNum, maxNum));
  714. if (currentParkingNum > availableParkingNum) {
  715. throw BusinessRuntimeException.getInstance("系统繁忙,请重试...");
  716. }
  717. }
  718. }
  719. @Override
  720. public void adjustGroupsParkingTime(Long relationId, GoodsDonSku sku) {
  721. if (sku == null) {
  722. return;
  723. }
  724. Long skuId = sku.getId();
  725. //更新GPT Plus10人、4人月付车队状态 待优化
  726. if (skuId == 161l || skuId == 178l || skuId == 422l || skuId == 423l) {
  727. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  728. Long groupsId = relation.getGroupsId();
  729. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  730. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  731. //为0时 不参与限制
  732. if (availableParkingNum == 0) {
  733. return;
  734. }
  735. Integer extraNum = 5;
  736. if (skuId == 178l || skuId == 423l) {
  737. extraNum = 2;
  738. }
  739. Integer maxNum = sku.getNum() + extraNum;
  740. if (availableParkingNum >= maxNum) {
  741. return;
  742. }
  743. //目前上车人数
  744. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  745. .eq(GroupsRelation::getGroupsId, groupsId)
  746. .ne(GroupsRelation::getUserId, 0)
  747. .le(GroupsRelation::getNum, maxNum));
  748. if (currentParkingNum >= availableParkingNum) {
  749. //锁住
  750. DateTime parkingTime = DateUtil.offsetDay(DateTime.now(), 1);
  751. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  752. .eq(GroupsTrips::getId, groupsTrips.getId())
  753. .set(GroupsTrips::getParkingTime, parkingTime)
  754. .isNull(GroupsTrips::getParkingTime));
  755. }
  756. }
  757. }
  758. @Override
  759. public void setGroupsTripsParkingTimeEmpty(GoodsDonSku sku, Long relationId) {
  760. if (sku == null) {
  761. return;
  762. }
  763. Long skuId = sku.getId();
  764. if (skuId == 161l || skuId == 178l) {
  765. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  766. Long groupsId = relation.getGroupsId();
  767. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  768. Integer availableParkingNum = groupsTrips.getAvailableParkingNum();
  769. if (groupsTrips.getParkingTime() == null || availableParkingNum == 0) {
  770. return;
  771. }
  772. Integer extraNum = 5;
  773. if (skuId == 178l) {
  774. extraNum = 2;
  775. }
  776. Integer skuNum = sku.getNum();
  777. if (availableParkingNum >= skuNum + extraNum) {
  778. return;
  779. }
  780. //目前上车人数
  781. Integer currentParkingNum = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class)
  782. .eq(GroupsRelation::getGroupsId, groupsId)
  783. .ne(GroupsRelation::getUserId, 0));
  784. if (currentParkingNum < availableParkingNum) {
  785. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  786. .eq(GroupsTrips::getId, groupsTrips.getId())
  787. .set(GroupsTrips::getParkingTime, null)
  788. .isNotNull(GroupsTrips::getParkingTime));
  789. }
  790. }
  791. }
  792. @Override
  793. public Integer getUserCodeNumBySkuId(Long userId, Long skuId, Boolean isHasVerifyCode) {
  794. //查看双重验证码
  795. UserFuncProperty userFuncProperty = userFuncPropertyMapper.selectOne(Wrappers.lambdaQuery(UserFuncProperty.class).eq(UserFuncProperty::getUserId, userId).last("limit 1"));
  796. //默认2次
  797. int num = 2;
  798. //有安全码查看次数 置为0
  799. if (isHasVerifyCode) {
  800. num = 0;
  801. //存在身份实名认证有两次机会
  802. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  803. Integer selectCount = userCertRecordMapper.selectCount(Wrappers.lambdaQuery(UserCertRecord.class)
  804. .in(UserCertRecord::getUserId, userIdList));
  805. if (selectCount > 0) {
  806. num = 2;
  807. }
  808. return num;
  809. }
  810. //查看双重验证码次数
  811. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  812. if (sku.getCodeNum() > 0) {
  813. num = sku.getCodeNum();
  814. }
  815. if (userFuncProperty != null) num = userFuncProperty.getVerifyCheckNum();
  816. return num;
  817. }
  818. @Override
  819. public List<RenewalView> getHasPayGoods(long userId) {
  820. User user = userMapper.selectById(userId);
  821. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, user);
  822. DateTime now = DateTime.now();
  823. List<RenewalView> list = groupsRelationMapper.getUserHasPayGoods(userIds, now);
  824. return list;
  825. }
  826. @Override
  827. public List<RenewalView> getExpiryRenewalNotify(Long userId) {
  828. DateTime now = DateTime.now();
  829. DateTime thisZero = DateUtil.beginOfDay(now);
  830. String thisDate = thisZero.toDateStr();
  831. Object exists = redisService.get(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId));
  832. if (exists != null) {
  833. return null;
  834. }
  835. User u = userMapper.selectById(userId);
  836. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  837. if (u.getIsBlack()) {
  838. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  839. return null;
  840. }
  841. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  842. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  843. List<RenewalView> list = beanSearcher.searchAll(RenewalView.class, builder
  844. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  845. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  846. .field(RenewalView::getExpiryTime, now).op(Operator.GreaterThan)
  847. .field(RenewalView::getStatus, List.of("validity", "overdue", "outside")).op(Operator.InList)
  848. .field(RenewalView::getAqType, 1)
  849. .field(RenewalView::getIsVip, Boolean.TRUE)
  850. .field(RenewalView::getMonths, 300).op(Operator.LessThan)
  851. .orderBy(RenewalView::getExpiryTime).asc()
  852. .build());
  853. if (list.size() > 5) {
  854. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  855. return null;
  856. }
  857. List<Long> renewReduceSkuIds = userBenefitsMapper.selectList(Wrappers.lambdaQuery(UserBenefits.class)
  858. .eq(UserBenefits::getType, UserBenefits.Type.RENEW).eq(UserBenefits::getStatus, 1).select(UserBenefits::getSkuId)).stream().map(UserBenefits::getSkuId).collect(Collectors.toList());
  859. //提前7天
  860. AtomicInteger day = new AtomicInteger(7);
  861. List<RenewalView> expiryTickets = list.stream().filter(ticket -> {
  862. //下架
  863. if (ticket.getGoodsStatus() == null || ticket.getSkuStatus() == null || !ticket.getGoodsStatus() || !ticket.getSkuStatus()) {
  864. return false;
  865. }
  866. Integer skuMonths = ticket.getMonths();
  867. if (skuMonths == null) {
  868. return false;
  869. }
  870. Date expiryTime = ticket.getExpiryTime();
  871. //年付 提前一个月
  872. if (skuMonths >= 12) {
  873. day.set(30);
  874. } else {
  875. day.set(7);
  876. }
  877. if (DateUtil.beginOfDay(expiryTime).compareTo(DateUtil.offsetDay(thisZero, day.get())) <= 0) {
  878. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  879. //GPT镜像信息
  880. setGptMirrorInfo(ticket);
  881. ticket.setExpiryTime(null);
  882. if (CollUtil.isNotEmpty(renewReduceSkuIds) && renewReduceSkuIds.contains(ticket.getSkuId())) {
  883. ticket.setIsRenewReduce(true);
  884. }
  885. return true;
  886. }
  887. return false;
  888. }).collect(Collectors.toList());
  889. redisService.setNx(RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getNameFormat(thisDate, userId), userId, RedisService.key.TICKET_EXPIRY_NOTIFY_DAY.getTimeout());
  890. if (CollUtil.isNotEmpty(expiryTickets)) {
  891. groupsRelationExpiryNotifyRecordMapper.batchInsert(userId, expiryTickets);
  892. }
  893. return expiryTickets;
  894. }
  895. @Override
  896. public void getCollegeStudentUserGptTicket(Long userId) {
  897. Retryer<Boolean> build = RetryerBuilder.<Boolean>newBuilder()
  898. .retryIfException()
  899. //运行时异常重试
  900. .retryIfRuntimeException()
  901. //false重试
  902. .retryIfResult(res -> Objects.equals(res, false))
  903. //1s 间隔
  904. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  905. //停止策略 : 尝试请求3次
  906. .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
  907. try {
  908. build.call(() -> {
  909. //体验规格
  910. Long gptMirrorSkuId = Constant.GPT_MIRROR_SKU_ID;
  911. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(gptMirrorSkuId);
  912. if (groups == null) {
  913. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  914. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  915. .eq(GroupsTrips::getSkuId, gptMirrorSkuId)
  916. .last("limit 1"));
  917. }
  918. GroupsRelation relation = null;
  919. if (groups != null) {
  920. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  921. }
  922. if (relation == null) {
  923. //生成空车队
  924. GoodsDonSku sku = goodsDonSkuMapper.selectById(gptMirrorSkuId);
  925. relation = groupsFuncService.createNewGroupsTrips(sku);
  926. }
  927. DateTime startTime = DateTime.now();
  928. DateTime expiryTime = DateUtil.offsetDay(startTime, 1);
  929. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  930. .set(GroupsRelation::getUserId, userId)
  931. .set(GroupsRelation::getStartTime, startTime)
  932. .set(GroupsRelation::getExpiryTime, expiryTime)
  933. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  934. .set(GroupsRelation::getAqType, 2)
  935. .eq(GroupsRelation::getId, relation.getId())
  936. .eq(GroupsRelation::getUserId, 0));
  937. if (update > 0) {
  938. groupsMapper.decrAvailableNum(relation.getGroupsId());
  939. return true;
  940. }
  941. log.error("发送用户:{} GPT镜像车票体验失败,进行重试", userId);
  942. return false;
  943. });
  944. } catch (ExecutionException | RetryException e) {
  945. log.error("发送用户GPT镜像体验失败:{}", StringUtil.getErrorText(e));
  946. }
  947. }
  948. @Override
  949. public RenewalView getTicketDetail(long userId, Long relationId) {
  950. User u = userMapper.selectById(userId);
  951. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  952. MapBuilder builder = MapUtils.builder();
  953. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, builder
  954. .field(RenewalView::getRelationId, relationId)
  955. .field(RenewalView::getUserId, 0).op(Operator.GreaterThan)
  956. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  957. .field("condition", String.format("(gr.expiry_time is null or gr.expiry_time > '%s')", DateTime.now()))
  958. .field(RenewalView::getStatus, List.of("validity", "outside")).op(Operator.InList)
  959. .orderBy(RenewalView::getExpiryTime).asc()
  960. .onlySelect(RenewalView::getRelationId, RenewalView::getExpiryTime, RenewalView::getTitle, RenewalView::getSpecVal, RenewalView::getGoodsId, RenewalView::getSkuId, RenewalView::getSkuNum, RenewalView::getSkuStatus, RenewalView::getGoodsStatus)
  961. .build());
  962. if (renewalView != null) {
  963. renewalView.setExpiryTimeStr(DateUtil.format(renewalView.getExpiryTime(), "yyyy-MM-dd"));
  964. }
  965. return renewalView;
  966. }
  967. @Override
  968. public GroupsRelation ticketLogin(TicketLoginReq loginReq) {
  969. String account = loginReq.getAccount();
  970. if (StrUtil.isEmpty(account)) {
  971. throw BusinessRuntimeException.getInstance("请输入对应账号");
  972. }
  973. if (loginReq.getMerchants()) {
  974. if (account.contains(Constant.YH_EMAIL_DOMAIN_SUFFIX)) {
  975. SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
  976. .eq(SysEmail::getEmail, account)
  977. .last("limit 1"));
  978. if (sysEmail == null) {
  979. throw BusinessRuntimeException.getInstance("账号错误,请联系客服");
  980. }
  981. }
  982. GroupsRelation relation = new GroupsRelation();
  983. relation.setId(0l);
  984. return relation;
  985. }
  986. String password = loginReq.getPassword();
  987. Integer num = loginReq.getNum();
  988. if (ObjectUtil.hasEmpty(password, num)) {
  989. throw BusinessRuntimeException.getInstance("参数错误");
  990. }
  991. Long goodsId = Optional.ofNullable(loginReq.getGoodsId()).orElse(1l);
  992. GroupsRelation relation = groupsRelationMapper.selectRelationByAccountAndNum(account, password, goodsId, num);
  993. if (relation == null) {
  994. log.info("外部入口使用账号account:{},pwd:{},座位num:{}登录失败...", account, password, num);
  995. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  996. throw BusinessRuntimeException.getInstance("Please enter the correct account information");
  997. }
  998. throw BusinessRuntimeException.getInstance("请输入正确的账号信息");
  999. }
  1000. return relation;
  1001. }
  1002. @Override
  1003. public String outsideTicketVerify(TicketLoginReq loginReq) {
  1004. String account = loginReq.getAccount();
  1005. if (StrUtil.isEmpty(account)) {
  1006. throw BusinessRuntimeException.getInstance("账号错误");
  1007. }
  1008. if (loginReq.getMerchants()) {
  1009. if (account.contains(Constant.YH_EMAIL_DOMAIN_SUFFIX)) {
  1010. SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
  1011. .eq(SysEmail::getEmail, account)
  1012. .last("limit 1"));
  1013. if (sysEmail == null) {
  1014. throw BusinessRuntimeException.getInstance("账号错误,请联系客服");
  1015. }
  1016. }
  1017. loginReq.setGoodsId(1l);
  1018. loginReq.setAccountId(0l);
  1019. } else {
  1020. String password = loginReq.getPassword();
  1021. Integer num = loginReq.getNum();
  1022. if (ObjectUtil.hasEmpty(password, num)) {
  1023. throw BusinessRuntimeException.getInstance("参数错误");
  1024. }
  1025. Long goodsId = Optional.ofNullable(loginReq.getGoodsId()).orElse(1l);
  1026. GroupsRelation relation = groupsRelationMapper.selectRelationByAccountAndNum(account, password, goodsId, num);
  1027. if (relation == null) {
  1028. log.info("外部入口使用账号account:{},pwd:{},座位num:{}同步验证链接失败...", account, password, num);
  1029. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  1030. throw BusinessRuntimeException.getInstance("This account is no longer valid");
  1031. }
  1032. throw BusinessRuntimeException.getInstance("该账号已失效");
  1033. }
  1034. loginReq.setUserId(relation.getUserId());
  1035. loginReq.setRelationId(relation.getId());
  1036. loginReq.setGoodsId(goodsId);
  1037. }
  1038. try {
  1039. String aiVerifyCode = getAiVerifyCode(loginReq);
  1040. if (StrUtil.isEmpty(aiVerifyCode)) {
  1041. throw BusinessRuntimeException.getInstance("");
  1042. }
  1043. return aiVerifyCode;
  1044. } catch (Exception e) {
  1045. if (StrUtil.equals(loginReq.getLang(), Constant.EN_US)) {
  1046. throw BusinessRuntimeException.getInstance("Please verify that the link was sent");
  1047. }
  1048. throw BusinessRuntimeException.getInstance("请校验链接是否已发送");
  1049. }
  1050. }
  1051. @Override
  1052. public String getNfHouseholdDevice(long userId, Long relationId) throws Exception {
  1053. List<Long> relationUserIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1054. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder().field(RenewalView::getUserId, relationUserIdList).op(Operator.InList)
  1055. .field(RenewalView::getRelationId, relationId).build());
  1056. if (renewalView == null) {
  1057. throw BusinessRuntimeException.getInstance("您的车票不存在...");
  1058. }
  1059. if (StrUtil.isEmpty(renewalView.getAccount())) {
  1060. throw BusinessRuntimeException.getInstance("车票未配置账号");
  1061. }
  1062. String account = renewalView.getAccount();
  1063. String password = renewalView.getPassword();
  1064. if (StrUtil.hasEmpty(account, password)) {
  1065. throw BusinessRuntimeException.getInstance("您的车票账号密码异常,请联系客服...");
  1066. }
  1067. String code = commonMailService.getTicketMailCode(renewalView.getGoodsId(), account, renewalView.getRelateEmail(), renewalView.getGptEmailPwd(), renewalView.getCreatedTime(), null, 1, true);
  1068. return code;
  1069. }
  1070. @Override
  1071. public String getVerifyCode(String account) throws Exception {
  1072. Account at = accountMapper.selectOne(Wrappers.lambdaQuery(Account.class)
  1073. .eq(Account::getAccount, account)
  1074. .eq(Account::getGoodsId, 18));
  1075. if (at == null) {
  1076. return null;
  1077. }
  1078. String password = at.getPassword();
  1079. if (StrUtil.hasEmpty(account, password)) {
  1080. throw BusinessRuntimeException.getInstance("账号异常");
  1081. }
  1082. String code = commonMailService.getTicketMailCode(at.getGoodsId(), account, at.getRelateEmail(), at.getGptEmailPwd(), at.getCreatedTime(), null, null, false);
  1083. return code;
  1084. }
  1085. @Override
  1086. public void changeTicket(long userId, Long relationId) {
  1087. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1088. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  1089. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1090. .field(RenewalView::getRelationId, relationId)
  1091. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1092. .build());
  1093. if (renewalView == null) {
  1094. throw BusinessRuntimeException.getInstance("车票不存在");
  1095. }
  1096. if (renewalView.getGoodsId() != 1) {
  1097. throw BusinessRuntimeException.getInstance("只针对奈飞车票");
  1098. }
  1099. AccountNetflixState accountNetflixState = accountNetflixStateMapper.selectOne(Wrappers.lambdaQuery(AccountNetflixState.class)
  1100. .eq(AccountNetflixState::getAccount, renewalView.getAccount())
  1101. .orderByDesc(AccountNetflixState::getId)
  1102. .last("limit 1"));
  1103. if (accountNetflixState == null || accountNetflixState.getState() != 3) {
  1104. throw BusinessRuntimeException.getInstance("只支持异常账号更换车票");
  1105. }
  1106. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  1107. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  1108. throw BusinessRuntimeException.getInstance("正在更换车票中..");
  1109. }
  1110. Long groupId = renewalView.getGroupId();
  1111. Long skuId = renewalView.getSkuId();
  1112. Date expiryTime = renewalView.getExpiryTime();
  1113. //随机选择同规格得车票
  1114. Long item_groupsId = groupsMapper.selectRandomGroupsTripsBySkuId(groupId, skuId, expiryTime);
  1115. GroupsRelation newRelation = null;
  1116. if (item_groupsId != null) {
  1117. //存在就随机分配一个,没有就不做处理
  1118. newRelation = changeTickerRelation.changeTicket(renewalView.getUserId(), relationId, item_groupsId, renewalView.getSkuId());
  1119. }
  1120. //若无移至空车队
  1121. if (newRelation == null) {
  1122. newRelation = changeTickerRelation.getEmptyGroupsRelation(renewalView.getUserId(), renewalView.getRelationId(), renewalView.getSkuId());
  1123. }
  1124. if (newRelation == null) {
  1125. throw BusinessRuntimeException.getInstance("更换异常,请重新提交");
  1126. }
  1127. NetflixUserAccountStatusRecord netflixUserAccountStatusRecord = netflixUserAccountStatusRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1128. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1129. .last("limit 1"));
  1130. if (netflixUserAccountStatusRecord != null) {
  1131. netflixUserAccountStatusRecord.setDeleted(false);
  1132. netflixUserAccountStatusRecordMapper.updateById(netflixUserAccountStatusRecord);
  1133. }
  1134. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1135. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  1136. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1137. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1138. .last("limit 1"));
  1139. if (recoverRecord != null) {
  1140. recoverRecord.setStatus(3);
  1141. netflixUserAccountSubmitRecoverRecordMapper.updateById(recoverRecord);
  1142. }
  1143. redisService.del(key);
  1144. }
  1145. @Override
  1146. public AccountView getTempAccount(long userId, Long relationId) {
  1147. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1148. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  1149. .field(RenewalView::getRelationId, relationId)
  1150. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1151. .field(RenewalView::getGroupsStatus, GroupsTrips.Status.waiting.name())
  1152. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1153. .build());
  1154. if (renewalView == null) {
  1155. throw BusinessRuntimeException.getInstance("车票不存在");
  1156. }
  1157. AccountView accountView = new AccountView();
  1158. //奈飞超过3帐车票不给看
  1159. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  1160. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1161. .field(RenewalView::getGoodsId, 1)
  1162. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  1163. .build());
  1164. if (number.intValue() > 2) {
  1165. return accountView;
  1166. }
  1167. NetflixTempAccountUser netflixTempAccountUser = netflixTempAccountUserMapper.selectOne(Wrappers.lambdaQuery(NetflixTempAccountUser.class)
  1168. .eq(NetflixTempAccountUser::getRelationId, relationId)
  1169. .in(NetflixTempAccountUser::getUserId, userIdList)
  1170. .last("limit 1"));
  1171. Account account;
  1172. if (netflixTempAccountUser == null) {
  1173. account = accountMapper.selectNetflixTempAccount();
  1174. if (account != null) {
  1175. netflixTempAccountUser = new NetflixTempAccountUser();
  1176. netflixTempAccountUser.setAccountId(account.getId());
  1177. netflixTempAccountUser.setRelationId(relationId);
  1178. netflixTempAccountUser.setUserId(renewalView.getUserId());
  1179. netflixTempAccountUserMapper.insert(netflixTempAccountUser);
  1180. }
  1181. } else {
  1182. account = accountMapper.selectById(netflixTempAccountUser.getAccountId());
  1183. }
  1184. if (account != null) {
  1185. accountView.setAccount(account.getAccount());
  1186. accountView.setPassword(account.getPassword());
  1187. }
  1188. return accountView;
  1189. }
  1190. @Override
  1191. public void nfErrorAccountSubmit(long userId, Long relationId) {
  1192. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1193. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  1194. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1195. .field(RenewalView::getRelationId, relationId)
  1196. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan).build());
  1197. if (renewalView == null) {
  1198. throw BusinessRuntimeException.getInstance("车票不存在");
  1199. }
  1200. if (renewalView.getGoodsId() != 1) {
  1201. throw BusinessRuntimeException.getInstance("只支持奈飞车票");
  1202. }
  1203. if (renewalView.getIsBannedCheck()) {
  1204. throw BusinessRuntimeException.getInstance("该规格不支持检测");
  1205. }
  1206. String account = renewalView.getAccount();
  1207. String password = renewalView.getPassword();
  1208. Integer selectCount = netflixUserAccountStatusRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1209. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1210. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1211. .eq(NetflixUserAccountStatusRecord::getAccount, account)
  1212. .eq(NetflixUserAccountStatusRecord::getState, 0)
  1213. .eq(NetflixUserAccountStatusRecord::getDeleted, 1));
  1214. if (selectCount > 0) {
  1215. throw BusinessRuntimeException.getInstance("该账号正在检测中");
  1216. }
  1217. Integer state = 0;
  1218. //非正常状态
  1219. if (state != 1) {
  1220. //20号之前得校验 直接失败
  1221. // if (renewalView.getCreatedTime().compareTo(DateUtil.parse("2025-06-20")) < 0) {
  1222. // state = 3;
  1223. // }
  1224. //如果账号下架了 直接失败
  1225. if (renewalView.getDays() == null && StrUtil.equals(GroupsTrips.Status.down.name(), renewalView.getGroupsStatus()) && renewalView.getSkuNum() > 1) {
  1226. state = 3;
  1227. }
  1228. }
  1229. NetflixUserAccountStatusRecord netflixUserAccountStatusRecord = new NetflixUserAccountStatusRecord();
  1230. netflixUserAccountStatusRecord.setAccount(account);
  1231. netflixUserAccountStatusRecord.setRelationId(relationId);
  1232. netflixUserAccountStatusRecord.setPassword(password);
  1233. netflixUserAccountStatusRecord.setUserId(renewalView.getUserId());
  1234. netflixUserAccountStatusRecord.setState(state);
  1235. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1236. .eq(OrderDon::getRelationId, renewalView.getRelationId())
  1237. .in(OrderDon::getUserId, userIdList)
  1238. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1239. .orderByDesc(OrderDon::getId)
  1240. .last("limit 1"));
  1241. if (orderDon != null) {
  1242. netflixUserAccountStatusRecord.setOrderId(orderDon.getId());
  1243. }
  1244. netflixUserAccountStatusRecordMapper.insert(netflixUserAccountStatusRecord);
  1245. }
  1246. @Override
  1247. public NetflixErrorAccountStatus getNetflixErrorAccountStatus(long userId, Long relationId) {
  1248. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1249. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  1250. NetflixUserAccountStatusRecord netflixUseAccountStatusRecord = netflixUserAccountStatusRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1251. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  1252. .eq(NetflixUserAccountStatusRecord::getDeleted, 1)
  1253. .gt(NetflixUserAccountStatusRecord::getCreatedTime, relation.getStartTime())
  1254. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1255. .orderByDesc(NetflixUserAccountStatusRecord::getId)
  1256. .last("limit 1"));
  1257. NetflixErrorAccountStatus status = new NetflixErrorAccountStatus();
  1258. if (netflixUseAccountStatusRecord == null) {
  1259. //是否已经更换
  1260. NetflixUserAccountSubmitRecoverRecord replaceRecover = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1261. .eq(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1262. .eq(NetflixUserAccountSubmitRecoverRecord::getReplaceRelationId, relationId)
  1263. .last("limit 1"));
  1264. if (replaceRecover != null) {
  1265. status.setRecoverStatus(replaceRecover.getStatus());
  1266. }
  1267. return status;
  1268. }
  1269. Integer state = netflixUseAccountStatusRecord.getState();
  1270. //2是登录失败 3是被封号
  1271. // if (state == 3) {
  1272. // if (netflixUseAccountStatusRecord.getCreatedTime().compareTo(DateUtil.offsetMinute(DateTime.now(), -10)) > 0) {
  1273. // state = 0;
  1274. // }
  1275. // }
  1276. //登录失败 可继续申请检测
  1277. if (state == 2) {
  1278. return status;
  1279. }
  1280. //未异常
  1281. if (state != 3) {
  1282. //车队是否已下架
  1283. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  1284. GoodsDonSku sku = goodsDonSkuMapper.selectById(groupsTrips.getSkuId());
  1285. if (groupsTrips != null && sku.getDays() == null && groupsTrips.getStatus() == GroupsTrips.Status.down) {
  1286. state = 3;
  1287. //下架 异常
  1288. if (netflixUseAccountStatusRecord != null) {
  1289. netflixUseAccountStatusRecord.setState(state);
  1290. netflixUserAccountStatusRecordMapper.updateById(netflixUseAccountStatusRecord);
  1291. }
  1292. }
  1293. }
  1294. //账号检测状态
  1295. status.setNfStatus(state);
  1296. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1297. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1298. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  1299. .last("limit 1"));
  1300. if (recoverRecord != null) {
  1301. //申请恢复状态
  1302. status.setRecoverStatus(recoverRecord.getStatus());
  1303. status.setSubmitTime(recoverRecord.getCreatedTime());
  1304. status.setRemainDays(recoverRecord.getRemainDays());
  1305. }
  1306. return status;
  1307. }
  1308. @Override
  1309. public List<NetflixUserAccountStatusRecord> getUserNetflixSubmitRecord(long userId) {
  1310. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1311. List<NetflixUserAccountStatusRecord> netflixUseAccountStatusRecords = netflixUserAccountStatusRecordMapper.selectList(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  1312. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  1313. .eq(NetflixUserAccountStatusRecord::getDeleted, 1)
  1314. .select(NetflixUserAccountStatusRecord::getOrderId, NetflixUserAccountStatusRecord::getRelationId, NetflixUserAccountStatusRecord::getState, NetflixUserAccountStatusRecord::getCreatedTime));
  1315. return netflixUseAccountStatusRecords;
  1316. }
  1317. @Override
  1318. public Long getTrialTicketByUserIdAndGoodsId(Long userId, Long trialSkuId, Integer ticketType) {
  1319. Retryer<Long> build = RetryerBuilder.<Long>newBuilder()
  1320. .retryIfException()
  1321. //运行时异常重试
  1322. .retryIfRuntimeException()
  1323. //false重试
  1324. .retryIfResult(res -> res == null)
  1325. //1s 间隔
  1326. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  1327. //停止策略 : 尝试请求3次
  1328. .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
  1329. try {
  1330. return build.call(() -> {
  1331. //体验规格
  1332. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(trialSkuId);
  1333. GroupsRelation relation = null;
  1334. if (groups == null) {
  1335. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  1336. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  1337. .eq(GroupsTrips::getSkuId, trialSkuId)
  1338. .last("limit 1"));
  1339. }
  1340. if (groups != null) {
  1341. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  1342. }
  1343. if (relation == null) {
  1344. //生成空车队
  1345. GoodsDonSku sku = goodsDonSkuMapper.selectById(trialSkuId);
  1346. relation = groupsFuncService.createNewGroupsTrips(sku);
  1347. }
  1348. DateTime startTime = DateTime.now();
  1349. DateTime expiryTime = DateUtil.offsetDay(startTime, 1);
  1350. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1351. .set(GroupsRelation::getUserId, userId)
  1352. .set(GroupsRelation::getStartTime, startTime)
  1353. .set(GroupsRelation::getExpiryTime, expiryTime)
  1354. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  1355. .set(GroupsRelation::getAqType, ticketType)
  1356. .eq(GroupsRelation::getId, relation.getId())
  1357. .eq(GroupsRelation::getUserId, 0));
  1358. if (update > 0) {
  1359. groupsMapper.decrAvailableNum(relation.getGroupsId());
  1360. return relation.getId();
  1361. }
  1362. log.error("发送用户:{} GPT镜像车票体验失败,进行重试", userId);
  1363. return null;
  1364. });
  1365. } catch (ExecutionException | RetryException e) {
  1366. log.error("发送用户GPT镜像体验失败:{}", StringUtil.getErrorText(e));
  1367. return null;
  1368. }
  1369. }
  1370. @Override
  1371. public Boolean getMirrorPopups(long userId) {
  1372. //是否弹窗 默认否
  1373. Boolean flag = false;
  1374. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1375. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  1376. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  1377. .field(RenewalView::getStatus, GroupsRelation.Status.validity.name())
  1378. .field(RenewalView::getIsMirror, true)
  1379. .build());
  1380. if (number.intValue() == 0) {
  1381. flag = true;
  1382. }
  1383. if (!flag) {
  1384. String thisWeekBegin = DateUtil.beginOfWeek(DateTime.now()).toDateStr();
  1385. Integer selectCount = mirrorTicketPopupsRecordMapper.selectCount(Wrappers.lambdaQuery(MirrorTicketPopupsRecord.class)
  1386. .in(MirrorTicketPopupsRecord::getUserId, userIdList)
  1387. .eq(MirrorTicketPopupsRecord::getThisWeek, thisWeekBegin));
  1388. if (selectCount == 0) {
  1389. MirrorTicketPopupsRecord mirrorTicketPopupsRecord = new MirrorTicketPopupsRecord();
  1390. mirrorTicketPopupsRecord.setThisWeek(thisWeekBegin);
  1391. mirrorTicketPopupsRecord.setUserId(userId);
  1392. mirrorTicketPopupsRecordMapper.insert(mirrorTicketPopupsRecord);
  1393. } else {
  1394. flag = true;
  1395. }
  1396. }
  1397. return flag;
  1398. }
  1399. @Override
  1400. public Long getTicket(Long userId, Long skuId, Boolean isVip) {
  1401. Retryer<Long> build = RetryerBuilder.<Long>newBuilder()
  1402. .retryIfException()
  1403. //运行时异常重试
  1404. .retryIfRuntimeException()
  1405. //false重试
  1406. .retryIfResult(res -> res == null)
  1407. //1s 间隔
  1408. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  1409. //停止策略 : 尝试请求1次
  1410. .withStopStrategy(StopStrategies.stopAfterAttempt(1)).build();
  1411. try {
  1412. return build.call(() -> {
  1413. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(skuId);
  1414. GroupsRelation relation = null;
  1415. if (groups == null) {
  1416. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  1417. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  1418. .eq(GroupsTrips::getSkuId, skuId)
  1419. .last("limit 1"));
  1420. }
  1421. if (groups != null) {
  1422. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  1423. }
  1424. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1425. //生成空车队
  1426. if (relation == null) {
  1427. relation = groupsFuncService.createNewGroupsTrips(sku);
  1428. }
  1429. DateTime startTime = DateTime.now();
  1430. DateTime expiryTime;
  1431. if (sku.getDays() != null) {
  1432. expiryTime = DateUtil.offsetDay(startTime, sku.getDays());
  1433. } else {
  1434. expiryTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  1435. }
  1436. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1437. .set(GroupsRelation::getUserId, userId)
  1438. .set(GroupsRelation::getStartTime, startTime)
  1439. .set(GroupsRelation::getExpiryTime, expiryTime)
  1440. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  1441. .set(GroupsRelation::getIsVip, isVip)
  1442. .eq(GroupsRelation::getId, relation.getId())
  1443. .eq(GroupsRelation::getUserId, 0));
  1444. if (update > 0) {
  1445. groupsMapper.decrAvailableNum(relation.getGroupsId());
  1446. return relation.getId();
  1447. }
  1448. log.error("发送用户:{} GPT镜像车票失败,进行重试", userId);
  1449. return null;
  1450. });
  1451. } catch (ExecutionException | RetryException e) {
  1452. log.error("发送用户GPT镜像失败:{}", StringUtil.getErrorText(e));
  1453. return null;
  1454. }
  1455. }
  1456. @Override
  1457. public Boolean getVipMirrorTicketIfEmpty(long userId, Long skuId) {
  1458. Integer selectCount = vipGoodsSkuMapper.selectCount(Wrappers.lambdaQuery(VipGoodsSku.class)
  1459. .eq(VipGoodsSku::getSkuId, skuId));
  1460. if (selectCount == 0) {
  1461. return false;
  1462. }
  1463. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1464. VipUser vipUser = vipUserMapper.selectOne(Wrappers.lambdaQuery(VipUser.class)
  1465. .in(VipUser::getUserId, userIdList)
  1466. .gt(VipUser::getExpiryTime, DateTime.now())
  1467. .last("limit 1"));
  1468. //不是会员 或已到期
  1469. if (vipUser == null) {
  1470. return false;
  1471. }
  1472. Number number = beanSearcher.searchCount(GroupsRelationView.class, MapUtils.builder()
  1473. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  1474. .field(GroupsRelationView::getSkuId, skuId)
  1475. .field(GroupsRelationView::getIsVip, Boolean.TRUE)
  1476. .build());
  1477. if (number.intValue() == 0) {
  1478. Long relationId = getTicket(vipUser.getUserId(), skuId, Boolean.TRUE);
  1479. //同步时间
  1480. groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1481. .set(GroupsRelation::getExpiryTime, vipUser.getExpiryTime())
  1482. .eq(GroupsRelation::getUserId, vipUser.getUserId())
  1483. .eq(GroupsRelation::getId, relationId));
  1484. return true;
  1485. }
  1486. return false;
  1487. }
  1488. @Override
  1489. @Transactional(rollbackFor = Throwable.class)
  1490. public NetflixRecoverResp netflixSubmitRecover(ErrorNetflixChangeReq req) {
  1491. NetflixRecoverResp recoverResp = new NetflixRecoverResp();
  1492. Long relationId = req.getRelationId();
  1493. Long userId = req.getUserId();
  1494. //校验奈飞账号状态
  1495. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1496. if (netflixRelationView.getIsFrozen()) {
  1497. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1498. .set(GroupsRelation::getIsFrozen, Boolean.FALSE)
  1499. .eq(GroupsRelation::getId, netflixRelationView.getId())
  1500. .eq(GroupsRelation::getIsFrozen, Boolean.TRUE));
  1501. if (update == 0) {
  1502. throw BusinessRuntimeException.getInstance("申请恢复账号失败,请重试");
  1503. }
  1504. try {
  1505. //获取同规格的车票
  1506. Long skuId = netflixRelationView.getSkuId();
  1507. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1508. GroupsRelation relation = getRelation(null, userId, sku, null);
  1509. if (relation != null) {
  1510. Long groupsId = relation.getGroupsId();
  1511. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  1512. //已发车
  1513. if (groupsTrips.getStatus() == GroupsTrips.Status.validity) {
  1514. resetUserTicket(netflixRelationView, relation);
  1515. recoverResp.setIsReset(Boolean.TRUE);
  1516. return recoverResp;
  1517. }
  1518. }
  1519. } catch (Exception e) {
  1520. throw BusinessRuntimeException.getInstance("申请恢复账号失败,请重试");
  1521. }
  1522. }
  1523. Date expiryTime = netflixRelationView.getExpiryTime();
  1524. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1525. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1526. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  1527. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1528. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1529. .last("limit 1"));
  1530. if (recoverRecord == null) {
  1531. recoverRecord = new NetflixUserAccountSubmitRecoverRecord();
  1532. recoverRecord.setRelationId(relationId);
  1533. recoverRecord.setUserId(netflixRelationView.getUserId());
  1534. recoverRecord.setSkuId(netflixRelationView.getSkuId());
  1535. recoverRecord.setAccount(netflixRelationView.getAccount());
  1536. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1537. recoverRecord.setRemainDays(betweenDay);
  1538. recoverRecord.setAccount(netflixRelationView.getTripsAccount());
  1539. try {
  1540. netflixUserAccountSubmitRecoverRecordMapper.insert(recoverRecord);
  1541. } catch (DuplicateKeyException e) {
  1542. throw BusinessRuntimeException.getInstance("您已申请恢复");
  1543. }
  1544. }
  1545. //等待位数
  1546. Integer selectCount = netflixUserAccountSubmitRecoverRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1547. .lt(NetflixUserAccountSubmitRecoverRecord::getCreatedTime, recoverRecord.getCreatedTime())
  1548. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0));
  1549. //往前加100位
  1550. recoverResp.setIndex(100 + selectCount + 1);
  1551. recoverResp.setRemainDays(recoverRecord.getRemainDays());
  1552. //更新车票恢复状态
  1553. groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class).set(GroupsRelation::getIsRecover, Boolean.TRUE).eq(GroupsRelation::getId, recoverRecord.getRelationId()));
  1554. return recoverResp;
  1555. }
  1556. private void resetUserTicket(GroupsRelationView oldRelation, GroupsRelation newRelation) {
  1557. Long userId = oldRelation.getUserId();
  1558. Long oldRelationId = oldRelation.getId();
  1559. //清除车票
  1560. List<Long> userIdList;
  1561. try {
  1562. userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1563. } catch (Exception e) {
  1564. userIdList = List.of(userId);
  1565. }
  1566. GroupsRelation clearRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  1567. .eq(GroupsRelation::getId, oldRelationId)
  1568. .in(GroupsRelation::getUserId, userIdList)
  1569. .last("limit 1"));
  1570. if (clearRelation != null) {
  1571. clearRelation.setNewRelationId(newRelation.getId());
  1572. clearService.clearTicket(clearRelation, UserTicketClearedRecord.Source.ticket_replace);
  1573. }
  1574. newRelation.setUserId(userId);
  1575. //校验座位
  1576. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1577. .set(GroupsRelation::getUserId, userId)
  1578. .eq(GroupsRelation::getUserId, 0)
  1579. .eq(GroupsRelation::getId, newRelation.getId()));
  1580. if (update == 0) {
  1581. throw BusinessRuntimeException.getInstance("申请恢复账号失败,请重试");
  1582. }
  1583. //恢复状态
  1584. newRelation.setStartTime(oldRelation.getStartTime());
  1585. newRelation.setExpiryTime(DateUtil.offsetDay(DateTime.now(), oldRelation.getReservedDays()));
  1586. newRelation.setStatus(GroupsRelation.Status.validity);
  1587. groupsRelationMapper.updateById(newRelation);
  1588. //原订单座位id更新
  1589. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1590. .in(OrderDon::getUserId, userIdList)
  1591. .eq(OrderDon::getRelationId, oldRelationId)
  1592. .notIn(OrderDon::getStatus, Constant.noOrderStatus)
  1593. .orderByDesc(OrderDon::getId)
  1594. .last("limit 1"));
  1595. if (orderDon != null) {
  1596. orderDon.setRelationId(newRelation.getId());
  1597. orderDonMapper.updateById(orderDon);
  1598. }
  1599. }
  1600. @Override
  1601. @Transactional(rollbackFor = Throwable.class)
  1602. public void errorNetflixSubmitChangeOtherTicket(ErrorNetflixChangeReq req) throws Exception {
  1603. Long relationId = req.getRelationId();
  1604. Long userId = req.getUserId();
  1605. //校验奈飞账号状态
  1606. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1607. Date expiryTime = netflixRelationView.getExpiryTime();
  1608. //小于15 不可替换其他车票
  1609. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1610. if (betweenDay <= 30) {
  1611. throw BusinessRuntimeException.getInstance("您的车票有效期未超过30天");
  1612. }
  1613. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1614. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1615. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  1616. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1617. .orderByDesc(NetflixUserAccountSubmitRecoverRecord::getId).last("limit 1"));
  1618. if (recoverRecord != null) {
  1619. if (recoverRecord.getCreatedTime().after(DateUtil.offsetDay(DateTime.now(), -1))) {
  1620. throw BusinessRuntimeException.getInstance("您的车票申请恢复中...");
  1621. }
  1622. recoverRecord.setStatus(2);
  1623. int update = netflixUserAccountSubmitRecoverRecordMapper.update(recoverRecord, Wrappers.lambdaUpdate(NetflixUserAccountSubmitRecoverRecord.class)
  1624. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1625. .eq(NetflixUserAccountSubmitRecoverRecord::getId, recoverRecord.getId()));
  1626. if (update == 0) {
  1627. throw BusinessRuntimeException.getInstance("系统异常,请重试");
  1628. }
  1629. }
  1630. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  1631. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  1632. throw BusinessRuntimeException.getInstance("正在更换其他车票中..");
  1633. }
  1634. try {
  1635. Long skuId = req.getSkuId();
  1636. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  1637. .eq(SysConfig::getSysKey, Constant.ERROR_NETFLIX_CHANGE_OTHER_SKU_KEY)
  1638. .last("limit 1"));
  1639. List<ErrorNetflixChangeOtherSkuTicketDto> errorNetflixChangeOtherSkuTicketDtos = Jsons.parseList(sysConfig.getSysValue(), ErrorNetflixChangeOtherSkuTicketDto.class);
  1640. ErrorNetflixChangeOtherSkuTicketDto errorNetflixChangeOtherSkuTicketDto;
  1641. //自定义顺序 直接获取
  1642. if (betweenDay <= 60) {
  1643. //检验规格
  1644. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(0);
  1645. } else if (betweenDay <= 120) {
  1646. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(1);
  1647. } else {
  1648. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(2);
  1649. }
  1650. List<Long> availableSkuIds = errorNetflixChangeOtherSkuTicketDto.getSkuIds();
  1651. if (!availableSkuIds.contains(skuId)) {
  1652. throw BusinessRuntimeException.getInstance("不支持更换该类型车票");
  1653. }
  1654. //替换车票
  1655. TicketChangeDto changeDto = getTicketAndGenerateOrder(userId, skuId, null, null);
  1656. if (changeDto == null) {
  1657. throw BusinessRuntimeException.getInstance("系统繁忙,请重试");
  1658. }
  1659. //替换记录
  1660. NetflixUserChangeOtherTicketRecord changeOtherTicketRecord = new NetflixUserChangeOtherTicketRecord();
  1661. changeOtherTicketRecord.setUserId(userId);
  1662. changeOtherTicketRecord.setRelationId(relationId);
  1663. changeOtherTicketRecord.setOtherRelationId(changeDto.getOtherRelationId());
  1664. changeOtherTicketRecord.setRelateOrderId(changeDto.getOtherOrderId());
  1665. //该车票订单id
  1666. changeOtherTicketRecord.setOrderId(netflixRelationView.getNfOriOrderId());
  1667. changeOtherTicketRecord.setStartTime(netflixRelationView.getStartTime());
  1668. changeOtherTicketRecord.setExpiryTime(expiryTime);
  1669. netflixUserChangeOtherTicketRecordMapper.insert(changeOtherTicketRecord);
  1670. if (netflixRelationView.getNfCheckId() != null) {
  1671. netflixUserAccountStatusRecordMapper.update(null, Wrappers.lambdaUpdate(NetflixUserAccountStatusRecord.class)
  1672. .set(NetflixUserAccountStatusRecord::getDeleted, false)
  1673. .eq(NetflixUserAccountStatusRecord::getId, netflixRelationView.getNfCheckId()));
  1674. }
  1675. Long ticketUserId = null;
  1676. //清除车票
  1677. GroupsRelation clearRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  1678. .eq(GroupsRelation::getId, relationId)
  1679. .in(GroupsRelation::getUserId, userIdList)
  1680. .last("limit 1"));
  1681. if (clearRelation != null) {
  1682. ticketUserId = clearRelation.getUserId();
  1683. clearService.clearTicket(clearRelation, UserTicketClearedRecord.Source.ticket_replace);
  1684. }
  1685. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1686. .eq(OrderDon::getRelationId, relationId)
  1687. .in(OrderDon::getUserId, userIdList)
  1688. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1689. .orderByDesc(OrderDon::getId)
  1690. .last("limit 1"));
  1691. if (orderDon != null) {
  1692. if (ticketUserId == null) {
  1693. ticketUserId = orderDon.getUserId();
  1694. }
  1695. //替换sku
  1696. GoodsDonSku replaceSku = goodsDonSkuMapper.selectById(skuId);
  1697. GoodsDonSku oriTicketSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  1698. //每天单价
  1699. BigDecimal dayPrice = oriTicketSku.getPrice().divide(BigDecimal.valueOf(oriTicketSku.getMonths() * 30), RoundingMode.DOWN);
  1700. //需要退款金额
  1701. BigDecimal refundMoney = dayPrice.multiply(BigDecimal.valueOf(betweenDay));
  1702. BigDecimal balance = Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO);
  1703. BigDecimal finalOrderMoney = orderDon.getMoney().add(balance);
  1704. if (refundMoney.compareTo(finalOrderMoney) > 0) {
  1705. refundMoney = finalOrderMoney;
  1706. }
  1707. //车票价格高于替换的规格价格 退余额
  1708. if (refundMoney.compareTo(replaceSku.getPrice()) > 0) {
  1709. BigDecimal refundBalance = refundMoney.subtract(replaceSku.getPrice());
  1710. if (refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  1711. userBenefitsService.addUserBalance(ticketUserId, refundBalance, UserBalanceSourceRecord.Source.TICKET_REPLACE, 0L, orderDon.getId(), UserBalanceSourceRecord.Source.TICKET_REPLACE.getDesc(), true);
  1712. }
  1713. }
  1714. }
  1715. } finally {
  1716. redisService.del(key);
  1717. }
  1718. }
  1719. @Override
  1720. public List<GoodsCategorySkuView> getNetflixReplaceOtherSkus(long userId, Long relationId) throws Exception {
  1721. //校验奈飞账号状态
  1722. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1723. Date expiryTime = netflixRelationView.getExpiryTime();
  1724. //小于15 不可替换其他车票
  1725. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1726. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  1727. .eq(SysConfig::getSysKey, Constant.ERROR_NETFLIX_CHANGE_OTHER_SKU_KEY)
  1728. .last("limit 1"));
  1729. List<ErrorNetflixChangeOtherSkuTicketDto> errorNetflixChangeOtherSkuTicketDtos = Jsons.parseList(sysConfig.getSysValue(), ErrorNetflixChangeOtherSkuTicketDto.class);
  1730. ErrorNetflixChangeOtherSkuTicketDto errorNetflixChangeOtherSkuTicketDto;
  1731. if (betweenDay <= 30) {
  1732. return null;
  1733. }
  1734. //自定义顺序 直接获取
  1735. if (betweenDay <= 60) {
  1736. //检验规格
  1737. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(0);
  1738. } else if (betweenDay <= 120) {
  1739. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(1);
  1740. } else {
  1741. errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(2);
  1742. }
  1743. List<GoodsCategorySkuView> goodsCategorySkuViews = beanSearcher.searchAll(GoodsCategorySkuView.class, MapUtils.builder()
  1744. .field(GoodsCategorySkuView::getSkuId, errorNetflixChangeOtherSkuTicketDto.getSkuIds()).op(Operator.InList)
  1745. .orderBy(GoodsCategorySkuView::getPrice).desc()
  1746. .build());
  1747. return goodsCategorySkuViews;
  1748. }
  1749. @Override
  1750. public NetflixRefundInfoResp refundNetflixInfo(Long userId, Long relationId) {
  1751. //校验奈飞账号状态
  1752. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1753. Date expiryTime = netflixRelationView.getExpiryTime();
  1754. //小于15
  1755. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1756. NetflixRefundInfoResp refundInfoResp = new NetflixRefundInfoResp();
  1757. refundInfoResp.setIsRefund(true);
  1758. if (betweenDay > 30) {
  1759. refundInfoResp.setIsRefund(false);
  1760. }
  1761. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1762. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1763. .eq(OrderDon::getRelationId, relationId)
  1764. .in(OrderDon::getUserId, userIdList)
  1765. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1766. .orderByDesc(OrderDon::getId)
  1767. .last("limit 1"));
  1768. if (orderDon == null) {
  1769. refundInfoResp.setIsRefund(false);
  1770. }
  1771. Long skuId = netflixRelationView.getSkuId();
  1772. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1773. BigDecimal orderMoney = orderDon == null ? BigDecimal.ZERO : orderDon.getMoney();
  1774. BigDecimal balance = orderDon == null ? BigDecimal.ZERO : Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO);
  1775. if (orderMoney.add(balance).compareTo(BigDecimal.ZERO) == 0) {
  1776. refundInfoResp.setIsRefund(false);
  1777. }
  1778. //每天单价
  1779. BigDecimal dayPrice;
  1780. if (sku.getDays() != null) {
  1781. dayPrice = orderMoney.add(balance).divide(BigDecimal.valueOf(sku.getDays()), RoundingMode.DOWN);
  1782. } else {
  1783. dayPrice = sku.getPrice().divide(BigDecimal.valueOf(sku.getMonths() * 30), RoundingMode.DOWN);
  1784. }
  1785. //需要退款金额
  1786. BigDecimal refundMoney = dayPrice.multiply(BigDecimal.valueOf(betweenDay));
  1787. refundInfoResp.setPrice(refundMoney);
  1788. // //超过本身订单金额 不允许退款
  1789. // if (refundMoney.compareTo(orderMoney) > 0) {
  1790. // refundInfoResp.setIsRefund(false);
  1791. // }
  1792. if (refundMoney.compareTo(orderMoney.add(balance)) > 0) {
  1793. refundInfoResp.setPrice(orderMoney.add(balance));
  1794. }
  1795. refundInfoResp.setRemainDays(betweenDay);
  1796. return refundInfoResp;
  1797. }
  1798. @Override
  1799. public Boolean refundNetflix(ErrorNetflixChangeReq req) throws Exception {
  1800. Long relationId = req.getRelationId();
  1801. Long userId = req.getUserId();
  1802. //校验奈飞账号状态
  1803. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  1804. Date expiryTime = netflixRelationView.getExpiryTime();
  1805. //小于15
  1806. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  1807. if (betweenDay > 30) {
  1808. throw BusinessRuntimeException.getInstance("车票有效期不超过30天可退款");
  1809. }
  1810. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1811. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1812. .eq(OrderDon::getRelationId, relationId)
  1813. .in(OrderDon::getUserId, userIdList)
  1814. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1815. .orderByDesc(OrderDon::getId)
  1816. .last("limit 1"));
  1817. if (orderDon == null) {
  1818. throw BusinessRuntimeException.getInstance("对应车票订单不存在,请联系客服");
  1819. }
  1820. Long skuId = netflixRelationView.getSkuId();
  1821. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  1822. BigDecimal orderMoney = orderDon.getMoney();
  1823. BigDecimal balance = orderDon == null ? BigDecimal.ZERO : Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO);
  1824. if (orderMoney.add(balance).compareTo(BigDecimal.ZERO) == 0) {
  1825. throw BusinessRuntimeException.getInstance("不符合退款条件");
  1826. }
  1827. //每天单价
  1828. BigDecimal dayPrice;
  1829. if (sku.getDays() != null) {
  1830. dayPrice = orderMoney.add(balance).divide(BigDecimal.valueOf(sku.getDays()), RoundingMode.DOWN);
  1831. } else {
  1832. dayPrice = sku.getPrice().divide(BigDecimal.valueOf(sku.getMonths() * 30), RoundingMode.DOWN);
  1833. }
  1834. //需要退款金额
  1835. BigDecimal totalRefundMoney = dayPrice.multiply(BigDecimal.valueOf(betweenDay));
  1836. BigDecimal refundMoney = totalRefundMoney;
  1837. BigDecimal refundBalance = BigDecimal.ZERO;
  1838. if (totalRefundMoney.compareTo(orderMoney) > 0) {
  1839. refundMoney = orderMoney;
  1840. refundBalance = totalRefundMoney.subtract(orderMoney);
  1841. }
  1842. String outNo = StrUtil.EMPTY;
  1843. if (refundMoney.compareTo(BigDecimal.ZERO) > 0) {
  1844. //调用第三方接口退款
  1845. OrderRefundReq refundReq = new OrderRefundReq();
  1846. refundReq.setRefundMoney(refundMoney);
  1847. refundReq.setRefundType("money");
  1848. outNo = orderRefundService.centerRefund(refundReq, orderDon);
  1849. orderDon.setRefundMoney(refundMoney);
  1850. }
  1851. orderDon.setStatus(OrderDon.Status.refund);
  1852. if (refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  1853. orderDon.setRefundBalance(refundBalance);
  1854. }
  1855. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  1856. orderDonMapper.updateById(orderDon);
  1857. if (refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  1858. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, null, orderDon.getId(), goodsDon.getTitle() + sku.getSpecVal() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1859. }
  1860. String refundType;
  1861. if (refundMoney.compareTo(BigDecimal.ZERO) > 0 && refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  1862. refundType = "bxj";
  1863. } else if (refundMoney.compareTo(BigDecimal.ZERO) == 0 && refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  1864. refundType = "balance";
  1865. } else {
  1866. refundType = orderDon.getType().name();
  1867. }
  1868. orderRefundService.refundRecord(orderDon, refundMoney, refundBalance, "系统", goodsDon, sku, outNo, refundType, null);
  1869. //清除车票
  1870. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  1871. clearService.clearTicket(relation, UserTicketClearedRecord.Source.refund);
  1872. if (netflixRelationView.getNfCheckId() != null) {
  1873. netflixUserAccountStatusRecordMapper.update(null, Wrappers.lambdaUpdate(NetflixUserAccountStatusRecord.class)
  1874. .set(NetflixUserAccountStatusRecord::getDeleted, false)
  1875. .eq(NetflixUserAccountStatusRecord::getId, netflixRelationView.getNfCheckId()));
  1876. }
  1877. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1878. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, orderDon.getRelationId())
  1879. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1880. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1881. .last("limit 1"));
  1882. if (recoverRecord != null) {
  1883. recoverRecord.setStatus(3);
  1884. netflixUserAccountSubmitRecoverRecordMapper.updateById(recoverRecord);
  1885. }
  1886. return true;
  1887. }
  1888. @Override
  1889. public List<UserMirrorTicketView> getMirrorTicket(long userId) {
  1890. User u = userMapper.selectById(userId);
  1891. if (u == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  1892. if (u.getIsBlack()) {
  1893. return null;
  1894. }
  1895. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, u);
  1896. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  1897. DateTime now = DateTime.now();
  1898. String lang = request.getHeader("lang");
  1899. List<UserMirrorTicketView> list = beanSearcher.searchAll(UserMirrorTicketView.class, builder
  1900. .field(UserMirrorTicketView::getUserId, userIds).op(Operator.InList)
  1901. .field(UserMirrorTicketView::getIsMirror, Boolean.TRUE)
  1902. //过期7天内的镜像车票都展示
  1903. .field(UserMirrorTicketView::getExpiryTime, DateUtil.offsetDay(now, -7)).op(Operator.GreaterThan)
  1904. .orderBy(RenewalView::getExpiryTime).asc()
  1905. .build());
  1906. list.forEach(ticket -> {
  1907. if (ticket.getExpiryTime() != null) {
  1908. String remainDays = DateUtil.formatBetween(now, ticket.getExpiryTime(), BetweenFormater.Level.DAY);
  1909. if ("0天".equals(remainDays)) {
  1910. remainDays = "小于1天";
  1911. } else {
  1912. //当天也算
  1913. int days = Integer.parseInt(remainDays.substring(0, remainDays.indexOf("天")));
  1914. remainDays = days + 1 + "天";
  1915. }
  1916. ticket.setRemainDays(remainDays);
  1917. ticket.setTotal(DateUtil.betweenDay(ticket.getStartTime(), ticket.getExpiryTime(), false) + 1);
  1918. }
  1919. if (ticket.getExpiryTime() != null) {
  1920. ticket.setExpiryTimeStr(DateUtil.format(ticket.getExpiryTime(), "yyyy-MM-dd"));
  1921. }
  1922. //续费升级折扣
  1923. BigDecimal renewDiscount = getRenewDiscount(ticket.getGoodsId(), ticket.getSkuId(), ticket.getIsMirror(), ticket.getSkuNum());
  1924. ticket.setDiscount(renewDiscount);
  1925. setAIZoneMirrorTicketInfo(ticket);
  1926. if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
  1927. String languageSpecVal = backInfoTranslationsFrontService.getLanguageSpecVal(ticket.getSkuId(), lang);
  1928. if (StrUtil.isNotBlank(languageSpecVal)) {
  1929. ticket.setSpecVal(languageSpecVal);
  1930. }
  1931. }
  1932. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1933. .eq(OrderDon::getRelationId, ticket.getRelationId())
  1934. .eq(OrderDon::getUserId, ticket.getUserId())
  1935. .eq(OrderDon::getOrderType, 1)
  1936. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1937. .orderByDesc(OrderDon::getId)
  1938. .last("limit 1"));
  1939. if (orderDon != null) {
  1940. ticket.setOrderId(orderDon.getId());
  1941. }
  1942. });
  1943. userLoginRecordService.saveUserLoginDayRecord(userId);
  1944. return list;
  1945. }
  1946. @Override
  1947. public TicketRenewUpgradeView getRenewUpgradeInfo(long userId, Long relationId) {
  1948. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1949. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  1950. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  1951. .field(GroupsRelationView::getId, relationId)
  1952. .build());
  1953. TicketRenewUpgradeView ticketRenewUpgradeView = new TicketRenewUpgradeView();
  1954. if (groupsRelationView != null) {
  1955. String lang = request.getHeader("lang");
  1956. //clause pro
  1957. if (groupsRelationView.getGoodsId() == Constant.CLAUDE_PRO_GID) {
  1958. try {
  1959. ClaudeUserView userInfo = claudeService.getUserInfo(groupsRelationView.getUserId(), groupsRelationView.getId());
  1960. Long renewSkuId = userInfo.getRenewSkuId();
  1961. if (renewSkuId != null) {
  1962. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  1963. ticketRenewUpgradeView.setRenewSku(renewSku);
  1964. }
  1965. ticketRenewUpgradeView.setGptUserLimitNum(userInfo.getLimitNum());
  1966. ticketRenewUpgradeView.setGptUserLimitTime(userInfo.getLimitTime());
  1967. } catch (Exception e) {
  1968. }
  1969. }
  1970. if (groupsRelationView.getGoodsId() == Constant.GPT_PLUS_GID) {
  1971. try {
  1972. //gpt用户镜像
  1973. ChatGptUserView userInfo = chatGptAccountService.getUserInfo(groupsRelationView.getUserId(), groupsRelationView.getId());
  1974. Integer count = upgradePackageMapper.selectCount(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + groupsRelationView.getSkuId() + "\"')")
  1975. .gt(UpgradePackage::getNum, userInfo.getLimitNum())
  1976. .eq(UpgradePackage::getStatus, Boolean.TRUE)
  1977. .eq(UpgradePackage::getGptType, 0)
  1978. .eq(UpgradePackage::getDeleted, Boolean.TRUE));
  1979. ticketRenewUpgradeView.setUpgrade(count > 0 ? true : false);
  1980. ticketRenewUpgradeView.setPackageId(userInfo.getPackageId());
  1981. ticketRenewUpgradeView.setGptUserLimitNum(userInfo.getLimitNum());
  1982. ticketRenewUpgradeView.setGptUserLimitTime(userInfo.getLimitTime());
  1983. ticketRenewUpgradeView.setUserDsLimitNum(userInfo.getDsLimitNum());
  1984. ticketRenewUpgradeView.setUserDsLimitTime(userInfo.getDsLimitTime());
  1985. ticketRenewUpgradeView.setUserOtherLimitNum(userInfo.getOtherLimitNum());
  1986. ticketRenewUpgradeView.setUserOtherLimitTime(userInfo.getOtherLimitTime());
  1987. ticketRenewUpgradeView.setGptThink(userInfo.getGptThink());
  1988. ticketRenewUpgradeView.setGptThinkLimitTime(userInfo.getGptThinkLimitTime());
  1989. ticketRenewUpgradeView.setGptDeepStyleLimit(userInfo.getGptDeepStyleLimit());
  1990. ticketRenewUpgradeView.setGptDeepStyleLimitTime(userInfo.getGptDeepStyleLimitTime());
  1991. if (userInfo.getPackageId() != 0) {
  1992. UpgradePackage upgradePackage = upgradePackageMapper.selectById(userInfo.getPackageId());
  1993. ticketRenewUpgradeView.setPackagePrice(upgradePackage.getPrice());
  1994. Long upgradeOrderDonSkuId = upgradePackage.getUpgradeSkuId();
  1995. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, upgradeOrderDonSkuId).build());
  1996. renewSku.setPackageId(userInfo.getPackageId());
  1997. ticketRenewUpgradeView.setRenewSku(renewSku);
  1998. }
  1999. ticketRenewUpgradeView.setIsRenewPackage(userInfo.getIsRenewPackage());
  2000. Long renewSkuId = userInfo.getRenewSkuId();
  2001. if (renewSkuId != null) {
  2002. GoodsDonSkuRenewView upgradeSkuRenewView = ticketRenewUpgradeView.getRenewSku();
  2003. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  2004. //续费升级是更高级规格
  2005. if (upgradeSkuRenewView == null || (renewSku.getGptUserLimitNum() >= upgradeSkuRenewView.getGptUserLimitNum() && renewSku.getMonths() >= userInfo.getMonths())) {
  2006. Optional.ofNullable(orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  2007. .eq(OrderDonRenewRecord::getOrderId, userInfo.getRenewOrderId())
  2008. .last("limit 1"))).ifPresent(e -> renewSku.setOriginalOrderId(e.getOrderId()));
  2009. if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
  2010. String languageSpecVal = backInfoTranslationsFrontService.getLanguageSpecVal(renewSku.getSkuId(), lang);
  2011. if (StrUtil.isNotBlank(languageSpecVal)) {
  2012. renewSku.setSpecVal(languageSpecVal);
  2013. }
  2014. }
  2015. ticketRenewUpgradeView.setRenewSku(renewSku);
  2016. }
  2017. }
  2018. } catch (Exception e) {
  2019. }
  2020. }
  2021. //claude code
  2022. if (groupsRelationView.getGoodsId() == Constant.CLAUDE_CODE_GOODS_ID) {
  2023. try {
  2024. //cc用户镜像
  2025. ClaudeCodeUserInfoView userInfo = claudeCodeService.getClaudeCodeUserSubsInfo(userId);
  2026. ticketRenewUpgradeView.setClaudeDailyLimit(userInfo.getClaudeDailyLimit());
  2027. ticketRenewUpgradeView.setClaudeQuota(userInfo.getClaudeQuota());
  2028. ticketRenewUpgradeView.setIsRenewPackage(userInfo.getRenewSkuId() != null ? true : false);
  2029. ticketRenewUpgradeView.setHighestUsage(userInfo.getHighestUsage());
  2030. Long renewSkuId = userInfo.getRenewSkuId();
  2031. if (renewSkuId != null) {
  2032. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  2033. Optional.ofNullable(claudeCodeUserRenewExpiryRecordMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUserRenewExpiryRecord.class)
  2034. .eq(ClaudeCodeUserRenewExpiryRecord::getOrderId, userInfo.getRenewOrderId())
  2035. .last("limit 1"))).ifPresent(e -> renewSku.setOriginalOrderId(e.getOrderId()));
  2036. if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
  2037. String languageSpecVal = backInfoTranslationsFrontService.getLanguageSpecVal(renewSku.getSkuId(), lang);
  2038. if (StrUtil.isNotBlank(languageSpecVal)) {
  2039. renewSku.setSpecVal(languageSpecVal);
  2040. }
  2041. }
  2042. ticketRenewUpgradeView.setRenewSku(renewSku);
  2043. }
  2044. } catch (Exception e) {
  2045. }
  2046. }
  2047. //codex
  2048. if (groupsRelationView.getGoodsId() == Constant.CODEX_GOODS_ID) {
  2049. try {
  2050. //codex用户镜像
  2051. CodexUserInfoView userInfo = codexService.getUserSubsInfo(userId);
  2052. ticketRenewUpgradeView.setOpenaiDailyLimit(userInfo.getOpenaiDailyLimit());
  2053. ticketRenewUpgradeView.setOpenaiQuota(userInfo.getOpenaiQuota());
  2054. ticketRenewUpgradeView.setIsRenewPackage(userInfo.getRenewSkuId() != null ? true : false);
  2055. Long renewSkuId = userInfo.getRenewSkuId();
  2056. if (renewSkuId != null) {
  2057. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  2058. Optional.ofNullable(codexUserRenewExpiryRecordMapper.selectOne(Wrappers.lambdaQuery(CodexUserRenewExpiryRecord.class)
  2059. .eq(CodexUserRenewExpiryRecord::getOrderId, userInfo.getRenewOrderId())
  2060. .last("limit 1"))).ifPresent(e -> renewSku.setOriginalOrderId(e.getOrderId()));
  2061. if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
  2062. String languageSpecVal = backInfoTranslationsFrontService.getLanguageSpecVal(renewSku.getSkuId(), lang);
  2063. if (StrUtil.isNotBlank(languageSpecVal)) {
  2064. renewSku.setSpecVal(languageSpecVal);
  2065. }
  2066. }
  2067. ticketRenewUpgradeView.setRenewSku(renewSku);
  2068. }
  2069. } catch (Exception e) {
  2070. }
  2071. }
  2072. }
  2073. return ticketRenewUpgradeView;
  2074. }
  2075. @Override
  2076. public void netflixSubmitFrozen(ErrorNetflixChangeReq req) {
  2077. Long relationId = req.getRelationId();
  2078. Long userId = req.getUserId();
  2079. //校验奈飞账号状态
  2080. GroupsRelationView netflixRelationView = checkNetflixErrorStatus(relationId, userId);
  2081. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  2082. Integer recoverCount = netflixUserAccountSubmitRecoverRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  2083. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  2084. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  2085. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0));
  2086. if (recoverCount > 0) {
  2087. throw BusinessRuntimeException.getInstance("你已申请恢复账号,无法再申请冻结");
  2088. }
  2089. if (netflixRelationView.getIsFrozen()) {
  2090. throw BusinessRuntimeException.getInstance("你已申请冻结,无法再申请冻结");
  2091. }
  2092. Date expiryTime = netflixRelationView.getExpiryTime();
  2093. //保留天数
  2094. Long betweenDay = DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  2095. groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  2096. .set(GroupsRelation::getIsFrozen, Boolean.TRUE)
  2097. //冻结2个月
  2098. .set(GroupsRelation::getUnfrozenTime, DateUtil.offsetMonth(DateTime.now(), 2))
  2099. .set(GroupsRelation::getReservedDays, betweenDay)
  2100. .eq(GroupsRelation::getId, netflixRelationView.getId())
  2101. .eq(GroupsRelation::getUserId, netflixRelationView.getUserId()));
  2102. //送一个月GPT基础月付
  2103. Long sendRelationId = getTicket(userId, Constant.GPT_MIRROR_COMMON_SKU_ID, Boolean.FALSE);
  2104. if (sendRelationId != null) {
  2105. AccountNetflixFrozenTicketReceivedRecord receivedRecord = new AccountNetflixFrozenTicketReceivedRecord();
  2106. receivedRecord.setUserId(userId);
  2107. receivedRecord.setRelationId(relationId);
  2108. receivedRecord.setSendRelationId(sendRelationId);
  2109. accountNetflixFrozenTicketReceivedRecordMapper.insert(receivedRecord);
  2110. }
  2111. }
  2112. @Override
  2113. public String getSoraCode(Long userId, Long relationId) {
  2114. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  2115. GroupsRelation relation = groupsRelationMapper.selectById(relationId);
  2116. if (relation == null) {
  2117. throw BusinessRuntimeException.getInstance("车票不存在");
  2118. }
  2119. if (!userIdList.contains(relation.getUserId())) {
  2120. throw BusinessRuntimeException.getInstance("车票不存在");
  2121. }
  2122. if (relation.getStatus() != GroupsRelation.Status.validity) {
  2123. throw BusinessRuntimeException.getInstance("车票不存在");
  2124. }
  2125. if (relation.getExpiryTime() != null && relation.getExpiryTime().before(DateTime.now())) {
  2126. throw BusinessRuntimeException.getInstance("车票已过期");
  2127. }
  2128. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  2129. GoodsDonSku sku = goodsDonSkuMapper.selectById(groupsTrips.getSkuId());
  2130. //非GPT独立
  2131. if (sku.getGoodsId() != Constant.GPT_PLUS_GID || sku.getNum() != 1) {
  2132. throw BusinessRuntimeException.getInstance("非GPT独立会员车票");
  2133. }
  2134. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).in(OrderDon::getUserId, userIdList).eq(OrderDon::getRelationId, relationId).notIn(OrderDon::getStatus, Constant.noOrderAllStatus).orderByDesc(OrderDon::getId).last("limit 1"));
  2135. SoraCode soraCode = soraCodeMapper.selectOne(Wrappers.lambdaQuery(SoraCode.class).eq(SoraCode::getOrderId, orderDon.getId()).last("limit 1"));
  2136. if (soraCode == null) {
  2137. try {
  2138. if (orderDon.getCreatedTime().before(DateUtil.parse("2025-10-14 17:30:00"))) {
  2139. throw BusinessRuntimeException.getInstance("系统异常");
  2140. }
  2141. soraCodeFrontService.grantSoraCodeForGptMember(relation.getUserId(), orderDon.getId());
  2142. soraCode = soraCodeMapper.selectOne(Wrappers.lambdaQuery(SoraCode.class).eq(SoraCode::getOrderId, orderDon.getId()).last("limit 1"));
  2143. } catch (Exception e) {
  2144. }
  2145. }
  2146. if (soraCode == null) {
  2147. throw BusinessRuntimeException.getInstance("暂无可用sora邀请码,请联系客服");
  2148. }
  2149. return soraCode.getCode();
  2150. }
  2151. @Override
  2152. public NetflixRecoverReceivedGptConditionDto netflixGptMirrorCondition(long userId) {
  2153. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  2154. //是否申请过奈飞恢复
  2155. NetflixUserAccountSubmitRecoverRecord last = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class).in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList).orderByDesc(NetflixUserAccountSubmitRecoverRecord::getId).last("limit 1"));
  2156. NetflixRecoverReceivedGptConditionDto receivedGptConditionDto = new NetflixRecoverReceivedGptConditionDto();
  2157. if (last == null) {
  2158. receivedGptConditionDto.setStatus(Boolean.FALSE);
  2159. return receivedGptConditionDto;
  2160. }
  2161. //是否存在奈飞车票
  2162. List<RenewalView> tickets = beanSearcher.searchAll(RenewalView.class, MapUtils.builder()
  2163. .field(RenewalView::getUserId, userIdList).op(Operator.InList)
  2164. .field(RenewalView::getGoodsId, Constant.NETFLIX_GID)
  2165. .field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  2166. .onlySelect(RenewalView::getRelationId)
  2167. .build());
  2168. if (CollUtil.isEmpty(tickets)) {
  2169. receivedGptConditionDto.setStatus(Boolean.FALSE);
  2170. return receivedGptConditionDto;
  2171. }
  2172. //多张奈飞车票 不给领取
  2173. if (tickets.size() > 1) {
  2174. receivedGptConditionDto.setStatus(Boolean.FALSE);
  2175. return receivedGptConditionDto;
  2176. }
  2177. Long submitRelationId = last.getRelationId();
  2178. receivedGptConditionDto.setNfRelationId(submitRelationId);
  2179. RenewalView renewalView = tickets.get(0);
  2180. //冻结过的车票不补偿
  2181. if (renewalView.getUnfrozenTime() != null) {
  2182. receivedGptConditionDto.setStatus(Boolean.FALSE);
  2183. return receivedGptConditionDto;
  2184. }
  2185. Long presentRelationId = renewalView.getRelationId();
  2186. //是否领取过 并且现在是否有效
  2187. NetflixCompensateReceivedRecord netflixCompensateReceivedRecord = netflixCompensateReceivedRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixCompensateReceivedRecord.class).in(NetflixCompensateReceivedRecord::getUserId, userIdList).orderByDesc(NetflixCompensateReceivedRecord::getId).last("limit 1"));
  2188. if (netflixCompensateReceivedRecord != null) {
  2189. //是否 有效
  2190. Long gptRelationId = netflixCompensateReceivedRecord.getRelationId();
  2191. Integer expiryCount = groupsRelationMapper.selectCount(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getId, gptRelationId).in(GroupsRelation::getUserId, userIdList).gt(GroupsRelation::getExpiryTime, DateTime.now()));
  2192. if (expiryCount > 0) {
  2193. receivedGptConditionDto.setStatus(Boolean.FALSE);
  2194. return receivedGptConditionDto;
  2195. }
  2196. //领取后已过期
  2197. Long compensateReceivedRecordNfRelationId = netflixCompensateReceivedRecord.getNfRelationId();
  2198. //是否通过当前车票已经获取过 镜像车票
  2199. if (compensateReceivedRecordNfRelationId.equals(presentRelationId)) {
  2200. receivedGptConditionDto.setStatus(Boolean.FALSE);
  2201. return receivedGptConditionDto;
  2202. }
  2203. //恢复中 可获取
  2204. if (last.getStatus() == 0) {
  2205. receivedGptConditionDto.setStatus(Boolean.TRUE);
  2206. return receivedGptConditionDto;
  2207. }
  2208. //不是正常恢复 不可获取
  2209. if (last.getStatus() != 1) {
  2210. receivedGptConditionDto.setStatus(Boolean.FALSE);
  2211. return receivedGptConditionDto;
  2212. }
  2213. Long replaceRelationId = last.getReplaceRelationId();
  2214. //非同一张车票 存在更换过
  2215. if (!presentRelationId.equals(replaceRelationId)) {
  2216. receivedGptConditionDto.setStatus(Boolean.FALSE);
  2217. return receivedGptConditionDto;
  2218. }
  2219. }
  2220. receivedGptConditionDto.setStatus(Boolean.TRUE);
  2221. return receivedGptConditionDto;
  2222. }
  2223. @Override
  2224. @Transactional(rollbackFor = Throwable.class)
  2225. public void netflixRecoverGetGptMirror(long userId) {
  2226. NetflixRecoverReceivedGptConditionDto receivedGptConditionDto = netflixGptMirrorCondition(userId);
  2227. if (receivedGptConditionDto.getStatus()) {
  2228. try {
  2229. NetflixCompensateReceivedRecord netflixCompensateReceivedRecord = new NetflixCompensateReceivedRecord();
  2230. netflixCompensateReceivedRecord.setUserId(userId);
  2231. netflixCompensateReceivedRecord.setNfRelationId(receivedGptConditionDto.getNfRelationId());
  2232. netflixCompensateReceivedRecord.setGoodsId(Constant.GPT_PLUS_GID);
  2233. netflixCompensateReceivedRecord.setSkuId(Constant.GPT_MIRROR_SKU_ID);
  2234. netflixCompensateReceivedRecordMapper.insert(netflixCompensateReceivedRecord);
  2235. Long relationId = this.getTicket(userId, Constant.GPT_MIRROR_SKU_ID, Boolean.FALSE);
  2236. if (relationId == null) {
  2237. throw BusinessRuntimeException.getInstance("获取车票失败,请重新领取");
  2238. }
  2239. netflixCompensateReceivedRecord.setRelationId(relationId);
  2240. netflixCompensateReceivedRecordMapper.updateById(netflixCompensateReceivedRecord);
  2241. } catch (DuplicateKeyException e) {
  2242. }
  2243. }
  2244. }
  2245. @Override
  2246. public void youtubeSubmitFrozen(ErrorNetflixChangeReq req) {
  2247. Long relationId = req.getRelationId();
  2248. Long userId = req.getUserId();
  2249. //校验账号
  2250. GroupsRelationView netflixRelationView = checkYoutubeTime(relationId, userId);
  2251. if (netflixRelationView.getIsFrozen()) {
  2252. throw BusinessRuntimeException.getInstance("您的车票已冻结");
  2253. }
  2254. Date expiryTime = netflixRelationView.getExpiryTime();
  2255. OrderDon orderDon = orderDonMapper.selectById(netflixRelationView.getNfOriOrderId());
  2256. Long betweenDay;
  2257. if (expiryTime == null) {
  2258. //用订单时间
  2259. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  2260. if (expiryTime == null) {
  2261. if (sku.getDays() != null) {
  2262. expiryTime = DateUtil.offsetDay(orderDon.getCreatedTime(), sku.getDays());
  2263. } else {
  2264. expiryTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), sku.getMonths());
  2265. }
  2266. }
  2267. }
  2268. betweenDay= DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  2269. groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  2270. .set(GroupsRelation::getIsFrozen, Boolean.TRUE)
  2271. //冻结12个月
  2272. .set(GroupsRelation::getUnfrozenTime, DateUtil.offsetMonth(DateTime.now(), 12))
  2273. .set(betweenDay != null, GroupsRelation::getReservedDays, betweenDay)
  2274. .eq(GroupsRelation::getId, netflixRelationView.getId())
  2275. .eq(GroupsRelation::getUserId, netflixRelationView.getUserId()));
  2276. }
  2277. @Override
  2278. @Transactional(rollbackFor = Throwable.class)
  2279. public void errorYoutubeChangeOtherTicket(ErrorNetflixChangeReq req) throws Exception {
  2280. Long relationId = req.getRelationId();
  2281. Long userId = req.getUserId();
  2282. //校验账号
  2283. GroupsRelationView relationView = checkYoutubeTime(relationId, userId);
  2284. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  2285. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  2286. throw BusinessRuntimeException.getInstance("正在更换其他车票中..");
  2287. }
  2288. Long chooseSkuId = req.getSkuId();
  2289. Date expiryTime = relationView.getExpiryTime();
  2290. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  2291. .eq(SysConfig::getSysKey, Constant.ERROR_YOUTUBE_CHANGE_OTHER_SKU_KEY)
  2292. .last("limit 1"));
  2293. List<ErrorNetflixChangeOtherSkuTicketDto> errorNetflixChangeOtherSkuTicketDtos = Jsons.parseList(sysConfig.getSysValue(), ErrorNetflixChangeOtherSkuTicketDto.class);
  2294. //替换车票
  2295. ErrorNetflixChangeOtherSkuTicketDto errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(0);
  2296. List<Long> skuIds = errorNetflixChangeOtherSkuTicketDto.getSkuIds();
  2297. if (!skuIds.contains(chooseSkuId)) {
  2298. throw BusinessRuntimeException.getInstance("选择要替换的规格错误");
  2299. }
  2300. try {
  2301. TicketChangeDto changeDto = getTicketAndGenerateOrder(userId, chooseSkuId, null, null);
  2302. if (changeDto == null) {
  2303. throw BusinessRuntimeException.getInstance("系统繁忙,请重试");
  2304. }
  2305. //替换记录
  2306. NetflixUserChangeOtherTicketRecord changeOtherTicketRecord = new NetflixUserChangeOtherTicketRecord();
  2307. changeOtherTicketRecord.setUserId(userId);
  2308. changeOtherTicketRecord.setRelationId(relationId);
  2309. changeOtherTicketRecord.setOtherRelationId(changeDto.getOtherRelationId());
  2310. changeOtherTicketRecord.setRelateOrderId(changeDto.getOtherOrderId());
  2311. //该车票订单id
  2312. changeOtherTicketRecord.setOrderId(relationView.getNfOriOrderId());
  2313. changeOtherTicketRecord.setStartTime(relationView.getStartTime());
  2314. changeOtherTicketRecord.setExpiryTime(expiryTime);
  2315. netflixUserChangeOtherTicketRecordMapper.insert(changeOtherTicketRecord);
  2316. //清除车票
  2317. GroupsRelation clearRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  2318. .eq(GroupsRelation::getId, relationId)
  2319. .eq(GroupsRelation::getUserId, relationView.getUserId())
  2320. .last("limit 1"));
  2321. if (clearRelation != null) {
  2322. clearService.clearTicket(clearRelation, UserTicketClearedRecord.Source.ticket_replace);
  2323. }
  2324. } finally {
  2325. redisService.del(key);
  2326. }
  2327. }
  2328. @Override
  2329. public void errorYoutubeRefund(ErrorNetflixChangeReq req) throws Exception {
  2330. Long relationId = req.getRelationId();
  2331. Long userId = req.getUserId();
  2332. //校验状态
  2333. GroupsRelationView relationView = checkYoutubeTime(relationId, userId);
  2334. Long ticketUserId = relationView.getUserId();
  2335. OrderDon orderDon = orderDonMapper.selectById(relationView.getNfOriOrderId());
  2336. if (orderDon != null) {
  2337. //paypal 或者超过一年 联系客服退款
  2338. if (orderDon.getType() == OrderDon.Type.PAYPAL) {
  2339. throw BusinessRuntimeException.getInstance("请联系客服退款");
  2340. }
  2341. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  2342. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  2343. OrderRefundDto orderRefundDto = getYoutubeRefundInfo(relationView, orderDon, sku);
  2344. BigDecimal refundBalance = orderRefundDto.getRefundBalance();
  2345. BigDecimal refundMoney = orderRefundDto.getRefundMoney();
  2346. //超过订单金额 让联系客服退款
  2347. if (refundMoney.compareTo(orderDon.getMoney()) > 0) {
  2348. throw BusinessRuntimeException.getInstance("请联系客服退款");
  2349. }
  2350. String outNo = StrUtil.EMPTY;
  2351. //金额退款
  2352. if (refundMoney.compareTo(BigDecimal.ZERO) > 0) {
  2353. //调用第三方接口退款
  2354. OrderRefundReq refundReq = new OrderRefundReq();
  2355. refundReq.setRefundMoney(refundMoney);
  2356. refundReq.setRefundType("money");
  2357. try {
  2358. outNo = orderRefundService.centerRefund(refundReq, orderDon);
  2359. } catch (Exception e) {
  2360. throw BusinessRuntimeException.getInstance("请联系客服退款");
  2361. }
  2362. orderDon.setRefundMoney(refundMoney);
  2363. }
  2364. //余额退款
  2365. if (refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  2366. userBenefitsService.addUserBalance(ticketUserId, refundBalance, UserBalanceSourceRecord.Source.yt_refund, 0L, orderDon.getId(), UserBalanceSourceRecord.Source.yt_refund.getDesc(), true);
  2367. }
  2368. orderDon.setStatus(OrderDon.Status.refund);
  2369. if (refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  2370. orderDon.setRefundBalance(refundBalance);
  2371. }
  2372. orderDon.setRefundDesc("油管掉会员退款");
  2373. orderDonMapper.updateById(orderDon);
  2374. //记录退款类型
  2375. String refundType = getRefundType(refundMoney, refundBalance, orderDon);
  2376. orderRefundService.refundRecord(orderDon, refundMoney, refundBalance, "系统", goodsDon, sku, outNo, refundType, null);
  2377. //清除车票
  2378. GroupsRelation clearRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  2379. .eq(GroupsRelation::getId, relationId)
  2380. .eq(GroupsRelation::getUserId, relationView.getUserId())
  2381. .last("limit 1"));
  2382. if (clearRelation != null) {
  2383. clearService.clearTicket(clearRelation, UserTicketClearedRecord.Source.yt_refund);
  2384. }
  2385. }
  2386. }
  2387. private OrderRefundDto getYoutubeRefundInfo(GroupsRelationView relationView, OrderDon orderDon, GoodsDonSku sku) {
  2388. OrderRefundDto orderRefundDto = new OrderRefundDto();
  2389. Date expiryTime = relationView.getExpiryTime();
  2390. DateTime now = DateTime.now();
  2391. if (relationView.getIsFrozen()) {
  2392. Integer reservedDays = relationView.getReservedDays();
  2393. //处理边界
  2394. if (relationView.getReservedDays() == 365) {
  2395. reservedDays = 364;
  2396. }
  2397. expiryTime = DateUtil.offsetDay(now, reservedDays);
  2398. }
  2399. if (expiryTime == null) {
  2400. if (sku.getDays() != null) {
  2401. expiryTime = DateUtil.offsetDay(orderDon.getCreatedTime(), sku.getDays());
  2402. } else {
  2403. expiryTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), sku.getMonths());
  2404. }
  2405. }
  2406. //剩余几个月
  2407. Long remainMonths = DateUtil.betweenMonth(now, expiryTime, false) + 1;
  2408. BigDecimal refundBalance = BigDecimal.ZERO;
  2409. BigDecimal refundMoney = BigDecimal.ZERO;
  2410. //订单金额
  2411. BigDecimal money = orderDon.getMoney();
  2412. BigDecimal balance = Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO);
  2413. BigDecimal orderTotalMoney = money.add(balance);
  2414. //2年
  2415. if ((sku.getDays() != null && sku.getDays() == 730) || (sku.getMonths() != null && sku.getMonths() == 24)) {
  2416. if (remainMonths > 12) {
  2417. //兑换码订单
  2418. if (orderTotalMoney.compareTo(BigDecimal.ZERO) == 0) {
  2419. orderTotalMoney = sku.getPrice();
  2420. }
  2421. BigDecimal totalRefundMoney = orderTotalMoney.divide(BigDecimal.valueOf(2), RoundingMode.DOWN);
  2422. if (money.compareTo(BigDecimal.ZERO) == 0) {
  2423. refundBalance = refundBalance.add(totalRefundMoney);
  2424. } else {
  2425. refundMoney = totalRefundMoney;
  2426. if (totalRefundMoney.compareTo(money) > 0) {
  2427. refundMoney = money;
  2428. refundBalance = totalRefundMoney.subtract(money);
  2429. }
  2430. }
  2431. remainMonths = remainMonths - 12;
  2432. }
  2433. }
  2434. if (remainMonths >= 1 && remainMonths <= 6) {
  2435. //1-6月买的 退100余额
  2436. refundBalance = refundBalance.add(BigDecimal.valueOf(10000));
  2437. } else if (remainMonths >= 7 && remainMonths <= 11) {
  2438. //7-11月买的 退150余额
  2439. refundBalance = refundBalance.add(BigDecimal.valueOf(15000));
  2440. } else {
  2441. //12月买的 退200余额
  2442. refundBalance = refundBalance.add(BigDecimal.valueOf(20000));
  2443. }
  2444. //超过订单金额 计算剩余的余额 排除兑换码
  2445. if (orderTotalMoney.compareTo(BigDecimal.ZERO) > 0 && refundMoney.add(refundBalance).compareTo(orderTotalMoney) > 0) {
  2446. refundBalance = orderTotalMoney.subtract(refundMoney);
  2447. }
  2448. orderRefundDto.setRefundMoney(refundMoney);
  2449. orderRefundDto.setRefundBalance(refundBalance);
  2450. return orderRefundDto;
  2451. }
  2452. @Override
  2453. public List<GoodsCategorySkuView> getYoutubeReplaceOtherSkus() throws Exception {
  2454. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
  2455. .eq(SysConfig::getSysKey, Constant.ERROR_YOUTUBE_CHANGE_OTHER_SKU_KEY)
  2456. .last("limit 1"));
  2457. List<ErrorNetflixChangeOtherSkuTicketDto> errorNetflixChangeOtherSkuTicketDtos = Jsons.parseList(sysConfig.getSysValue(), ErrorNetflixChangeOtherSkuTicketDto.class);
  2458. ErrorNetflixChangeOtherSkuTicketDto errorNetflixChangeOtherSkuTicketDto = errorNetflixChangeOtherSkuTicketDtos.get(0);
  2459. List<GoodsCategorySkuView> goodsCategorySkuViews = beanSearcher.searchAll(GoodsCategorySkuView.class, MapUtils.builder()
  2460. .field(GoodsCategorySkuView::getSkuId, errorNetflixChangeOtherSkuTicketDto.getSkuIds()).op(Operator.InList)
  2461. .orderBy(GoodsCategorySkuView::getPrice).desc()
  2462. .build());
  2463. return goodsCategorySkuViews;
  2464. }
  2465. @Override
  2466. public OrderRefundDto getYoutubeRefundInfo(long userId, Long relationId) {
  2467. //校验状态
  2468. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  2469. GroupsRelationView relationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  2470. .field(GroupsRelationView::getId, relationId)
  2471. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  2472. .field(GroupsRelationView::getGoodsId, Constant.YOUTUBE_GOODS_ID)
  2473. .build());
  2474. if (relationView != null) {
  2475. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).in(OrderDon::getUserId, userIdList).eq(OrderDon::getRelationId, relationId).notIn(OrderDon::getStatus, Constant.noOrderAllStatus).orderByDesc(OrderDon::getId).last("limit 1"));
  2476. if (orderDon != null) {
  2477. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  2478. OrderRefundDto orderRefundDto = getYoutubeRefundInfo(relationView, orderDon, sku);
  2479. return orderRefundDto;
  2480. }
  2481. }
  2482. return null;
  2483. }
  2484. private GroupsRelationView checkYoutubeTime(Long relationId, Long userId) {
  2485. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  2486. GroupsRelationView relationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  2487. .field(GroupsRelationView::getId, relationId)
  2488. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  2489. .field(GroupsRelationView::getGoodsId, Constant.YOUTUBE_GOODS_ID)
  2490. .build());
  2491. if (relationView == null) {
  2492. throw BusinessRuntimeException.getInstance("车票不存在");
  2493. }
  2494. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).in(OrderDon::getUserId, userIdList).eq(OrderDon::getRelationId, relationId).notIn(OrderDon::getStatus, Constant.noOrderAllStatus).orderByDesc(OrderDon::getId).last("limit 1"));
  2495. if (orderDon == null) {
  2496. throw BusinessRuntimeException.getInstance("订单不存在");
  2497. }
  2498. SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey, Constant.YOUTUBE_AFTER_SALES_TIME_KEY).last("limit 1"));
  2499. DateTime availableHandleTime = DateUtil.parse(sysConfig.getSysValue());
  2500. if (orderDon.getCreatedTime().after(availableHandleTime)) {
  2501. throw BusinessRuntimeException.getInstance("不可进行售后,请联系客服");
  2502. }
  2503. relationView.setNfOriOrderId(orderDon.getId());
  2504. return relationView;
  2505. }
  2506. private DistributePosterGoodsDetailView setGoodsPoster(RenewalView ticket, User user, List<Long> userIds) {
  2507. DistributePosterGoodsDetailView distributePosterGoodsDetailView = beanSearcher.searchFirst(DistributePosterGoodsDetailView.class, MapUtils.flatBuilder(request.getParameterMap())
  2508. .field(DistributePosterGoodsFrontView::getGoodsId, ticket.getGoodsId()).build());
  2509. if (distributePosterGoodsDetailView == null) {
  2510. return null;
  2511. }
  2512. distributePosterGoodsDetailView.setNickname(user.getNickname());
  2513. UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
  2514. .eq(UserDistribute::getUserId, user.getId())
  2515. .eq(UserDistribute::getDeleted, 1)
  2516. .last("limit 1"));
  2517. if (userDistribute != null) {
  2518. UserPlatDistributeRate userPlatDistributeRate = userPlatDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatDistributeRate.class)
  2519. .eq(UserPlatDistributeRate::getDistributeId, userDistribute.getId())
  2520. .eq(UserPlatDistributeRate::getGoodsId, ticket.getGoodsId())
  2521. .last("limit 1"));
  2522. if (userPlatDistributeRate != null) {
  2523. distributePosterGoodsDetailView.setRate(userPlatDistributeRate.getRate());
  2524. }
  2525. }
  2526. GoodsDon goodsDon = goodsDonMapper.selectById(ticket.getGoodsId());
  2527. if (goodsDon.getIsSkuDistribute()) {
  2528. if (userDistribute != null) {
  2529. UserPlatSkuDistributeRate userPlatSkuDistributeRate = userPlatSkuDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatSkuDistributeRate.class)
  2530. .eq(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId())
  2531. .eq(UserPlatSkuDistributeRate::getSkuId, ticket.getSkuId())
  2532. .last("limit 1"));
  2533. if (userPlatSkuDistributeRate != null) {
  2534. distributePosterGoodsDetailView.setRate(userPlatSkuDistributeRate.getRate());
  2535. }
  2536. } else {
  2537. DistributeGeneralSkuRate distributeGeneralSkuRate = distributeGeneralSkuRateMapper.selectOne(Wrappers.lambdaQuery(DistributeGeneralSkuRate.class)
  2538. .eq(DistributeGeneralSkuRate::getSkuId, ticket.getSkuId())
  2539. .last("limit 1"));
  2540. if (distributeGeneralSkuRate != null) {
  2541. distributePosterGoodsDetailView.setRate(distributeGeneralSkuRate.getRate());
  2542. }
  2543. }
  2544. }
  2545. //用户推广海报记录id
  2546. Optional.ofNullable(userDistributePosterRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributePosterRecord.class)
  2547. .eq(UserDistributePosterRecord::getPosterId, distributePosterGoodsDetailView.getId())
  2548. .in(UserDistributePosterRecord::getUserId, userIds)
  2549. .last("limit 1"))).ifPresent(re -> distributePosterGoodsDetailView.setRid(re.getId()));
  2550. return distributePosterGoodsDetailView;
  2551. }
  2552. private BigDecimal getRenewDiscount(Long goodsId, Long skuId, Boolean isMirror, Integer skuNum) {
  2553. //镜像或者独立规格
  2554. if (goodsId == Constant.CODEX_GOODS_ID || goodsId == Constant.CLAUDE_CODE_GOODS_ID || isMirror || (skuNum != null && skuNum == 1)) {
  2555. RenewUpgradePackage renewUpgradePackage = renewUpgradePackageMapper.selectOne(Wrappers.lambdaQuery(RenewUpgradePackage.class)
  2556. .eq(RenewUpgradePackage::getGoodsId, goodsId)
  2557. .eq(RenewUpgradePackage::getStatus, 1)
  2558. .eq(RenewUpgradePackage::getDeleted, 1)
  2559. .eq(RenewUpgradePackage::getSkuId, skuId)
  2560. .orderByAsc(RenewUpgradePackage::getDiscount)
  2561. .last("limit 1")
  2562. .select(RenewUpgradePackage::getId, RenewUpgradePackage::getDiscount));
  2563. if (renewUpgradePackage != null) {
  2564. return renewUpgradePackage.getDiscount();
  2565. }
  2566. }
  2567. return null;
  2568. }
  2569. private void setMirrorTicketInfo(RenewalView ticket) {
  2570. //// //设置MJ镜像信息
  2571. // setMjMirrorInfo(ticket);
  2572. //设置GPT镜像信息
  2573. setGptMirrorInfo(ticket);
  2574. //// //clause pro
  2575. // setClaudeProInfo(ticket);
  2576. //// //luma
  2577. // setLumaInfo(ticket);
  2578. }
  2579. private void setMjMirrorInfo(RenewalView ticket) {
  2580. if (ticket.getGoodsId() == 26 && ticket.getIsMirror()) {
  2581. List<UpgradePackage> upgradePackages = upgradePackageMapper.selectList(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + ticket.getSkuId() + "\"')").eq(UpgradePackage::getStatus, Boolean.TRUE).eq(UpgradePackage::getDeleted, Boolean.TRUE));
  2582. if (CollectionUtil.isNotEmpty(upgradePackages)) {
  2583. upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(ticket::setMjPackagePrice);
  2584. }
  2585. try {
  2586. MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  2587. .field(MidjourneyUserView::getUserId, ticket.getUserId()).field(MidjourneyUserView::getRelationId, ticket.getRelationId())
  2588. .onlySelect(MidjourneyUserView::getMjUserRelaxNum, MidjourneyUserView::getMjUserFastNum,MidjourneyUserView::getMjUserUpgradeNum, MidjourneyUserView::getIsCar)
  2589. .build());
  2590. if (search == null) {
  2591. MidjourneyUser midjourneyUser = midjourneyAccountService.getMidjourneyUserToken(ticket.getUserId(), ticket.getRelationId());
  2592. ticket.setMjUserFastNum(midjourneyUser.getMjFastNum());
  2593. ticket.setMjUserUpgradeNum(midjourneyUser.getMjUpgradeNum());
  2594. ticket.setMjUserRelaxNum(midjourneyUser.getMjRelaxNum());
  2595. ticket.setIsCar(false);
  2596. } else {
  2597. ticket.setIsCar(search.getIsCar());
  2598. ticket.setMjUserFastNum(search.getMjUserFastNum());
  2599. ticket.setMjUserUpgradeNum(search.getMjUserUpgradeNum());
  2600. ticket.setMjUserRelaxNum(search.getMjUserRelaxNum());
  2601. }
  2602. midjourneyAccountService.updateUserExpiryTime(ticket.getRelationId(), ticket.getExpiryTime());
  2603. } catch (Exception e) {
  2604. }
  2605. }
  2606. }
  2607. public void setGptMirrorInfo(RenewalView ticket) {
  2608. if (ticket.getGoodsId() == 18 && ticket.getIsCar() && ticket.getExpiryTime() != null) {
  2609. try {
  2610. //gpt用户镜像
  2611. ChatGptUserView userInfo = chatGptAccountService.getUserInfo(ticket.getUserId(), ticket.getRelationId());
  2612. ticket.setGptUserLimitNum(userInfo.getLimitNum());
  2613. ticket.setGptUserLimitTime(userInfo.getLimitTime());
  2614. ticket.setUserDsLimitNum(userInfo.getDsLimitNum());
  2615. ticket.setUserDsLimitTime(userInfo.getDsLimitTime());
  2616. ticket.setUserOtherLimitNum(userInfo.getOtherLimitNum());
  2617. ticket.setUserOtherLimitTime(userInfo.getOtherLimitTime());
  2618. ticket.setGptThink(userInfo.getGptThink());
  2619. ticket.setGptThinkLimitTime(userInfo.getGptThinkLimitTime());
  2620. ticket.setGptDeepStyleLimit(userInfo.getGptDeepStyleLimit());
  2621. ticket.setGptDeepStyleLimitTime(userInfo.getGptDeepStyleLimitTime());
  2622. ticket.setUserToken(userInfo.getUserToken());
  2623. ticket.setUse(userInfo.getUse());
  2624. ticket.setModel(userInfo.getModel());
  2625. // Integer count = upgradePackageMapper.selectCount(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + ticket.getSkuId() + "\"')")
  2626. // .gt(UpgradePackage::getNum, userInfo.getLimitNum())
  2627. // .eq(UpgradePackage::getStatus, Boolean.TRUE)
  2628. // .eq(UpgradePackage::getGptType, 0)
  2629. // .eq(UpgradePackage::getDeleted, Boolean.TRUE));
  2630. // ticket.setUpgrade(count > 0 ? true : false);
  2631. // ticket.setPackageId(userInfo.getPackageId());
  2632. // if (userInfo.getPackageId() != 0) {
  2633. // UpgradePackage upgradePackage = upgradePackageMapper.selectById(userInfo.getPackageId());
  2634. // ticket.setPackagePrice(upgradePackage.getPrice());
  2635. // Long upgradeOrderDonSkuId = upgradePackage.getUpgradeSkuId();
  2636. // GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, upgradeOrderDonSkuId).build());
  2637. // renewSku.setPackageId(userInfo.getPackageId());
  2638. // ticket.setRenewSku(renewSku);
  2639. // }
  2640. // ticket.setIsRenewPackage(userInfo.getIsRenewPackage());
  2641. // Long renewSkuId = userInfo.getRenewSkuId();
  2642. // if (renewSkuId != null) {
  2643. // GoodsDonSkuRenewView upgradeSkuRenewView = ticket.getRenewSku();
  2644. // GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  2645. // //续费升级是更高级规格
  2646. // if (upgradeSkuRenewView == null || (renewSku.getGptUserLimitNum() >= upgradeSkuRenewView.getGptUserLimitNum() && renewSku.getMonths() >= userInfo.getMonths())) {
  2647. // Optional.ofNullable(orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  2648. // .eq(OrderDonRenewRecord::getOrderId, userInfo.getRenewOrderId())
  2649. // .last("limit 1"))).ifPresent(e -> renewSku.setOriginalOrderId(e.getOrderId()));
  2650. // ticket.setRenewSku(renewSku);
  2651. // }
  2652. // }
  2653. } catch (Exception e) {
  2654. }
  2655. }
  2656. }
  2657. public void setClaudeProInfo(RenewalView ticket) {
  2658. //clause pro
  2659. if (ticket.getGoodsId() == 75l && ticket.getExpiryTime() != null) {
  2660. try {
  2661. ClaudeUserView userInfo = claudeService.getUserInfo(ticket.getUserId(), ticket.getRelationId());
  2662. ticket.setGptUserLimitNum(userInfo.getLimitNum());
  2663. ticket.setGptUserLimitTime(userInfo.getLimitTime());
  2664. ticket.setUse(userInfo.getUse());
  2665. Long renewSkuId = userInfo.getRenewSkuId();
  2666. if (renewSkuId != null) {
  2667. GoodsDonSkuRenewView renewSku = beanSearcher.searchFirst(GoodsDonSkuRenewView.class, MapUtils.builder().field(GoodsDonSkuRenewView::getSkuId, renewSkuId).build());
  2668. ticket.setRenewSku(renewSku);
  2669. }
  2670. } catch (Exception e) {
  2671. }
  2672. }
  2673. }
  2674. public void setLumaInfo(RenewalView ticket) {
  2675. if (ticket.getGoodsId() == Constant.LUMA_GOODS_ID && ticket.getExpiryTime() != null) {
  2676. try {
  2677. List<UpgradePackage> upgradePackages = upgradePackageMapper.selectList(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + ticket.getSkuId() + "\"')").eq(UpgradePackage::getStatus, Boolean.TRUE).eq(UpgradePackage::getDeleted, Boolean.TRUE));
  2678. if (CollectionUtil.isNotEmpty(upgradePackages)){
  2679. upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(ticket::setLumaPackagePrice);
  2680. }
  2681. LumaUser lumaUser = lumaService.getLumaUser(ticket.getUserId(), ticket.getRelationId());
  2682. ticket.setLumaUserNum(lumaUser.getNum());
  2683. } catch (Exception e) {
  2684. }
  2685. }
  2686. }
  2687. /**
  2688. * 获取gpt镜像天卡活动参与平台ids
  2689. * @return
  2690. */
  2691. private List<Long> getGptMirrorGiveawayBuyGids() {
  2692. GptMirrorDayCardGiveawayActivity gptMirrorDayCardGiveawayActivity = beanSearcher.searchFirst(GptMirrorDayCardGiveawayActivity.class, MapUtils.builder().build());
  2693. if (gptMirrorDayCardGiveawayActivity != null) {
  2694. String buyGoodsIds = gptMirrorDayCardGiveawayActivity.getBuyGoodsIds();
  2695. try {
  2696. return Jsons.parseList(buyGoodsIds, Long.class);
  2697. } catch (Exception e) {
  2698. }
  2699. }
  2700. return null;
  2701. }
  2702. /**
  2703. * 标记是否可抵扣会员车票
  2704. */
  2705. private void markVipDeductTicket(List<Long> userIds, RenewalView ticket, Set<Long> vipGoodsIds, Boolean isVip) {
  2706. if (CollUtil.isNotEmpty(vipGoodsIds) && ticket.getIsMirror() != null && ticket.getIsMirror() && !isVip) {
  2707. Long goodsId = ticket.getGoodsId();
  2708. //只购买
  2709. if (ticket.getAqType() != 1) {
  2710. return;
  2711. }
  2712. if (vipGoodsIds.contains(goodsId)) {
  2713. if (goodsId == Constant.NANO_GOODS_ID) {
  2714. NanoUserQuota nanoUserQuota = nanoUserQuotaMapper.selectOne(Wrappers.lambdaQuery(NanoUserQuota.class).in(NanoUserQuota::getUid, userIds).orderByDesc(NanoUserQuota::getRemainingQuota).last("limit 1"));
  2715. if (nanoUserQuota != null) {
  2716. if (ObjectUtil.equal(nanoUserQuota.getRelationId(), ticket.getRelationId())) {
  2717. ticket.setIsVipDeduct(true);
  2718. }
  2719. return;
  2720. }
  2721. RenewalView renewalView = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
  2722. .field(RenewalView::getGoodsId, goodsId)
  2723. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  2724. .orderBy(RenewalView::getSkuNanoQuota).desc()
  2725. .onlySelect(RenewalView::getRelationId)
  2726. .build());
  2727. if (renewalView != null && ObjectUtil.equal(renewalView.getRelationId(), ticket.getRelationId())) {
  2728. ticket.setIsVipDeduct(true);
  2729. }
  2730. return;
  2731. }
  2732. //是否时长最长
  2733. Number number = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
  2734. .field(RenewalView::getRelationId, ticket.getRelationId()).op(Operator.NotEqual)
  2735. .field(RenewalView::getGoodsId, goodsId)
  2736. .field(RenewalView::getUserId, userIds).op(Operator.InList)
  2737. .field(RenewalView::getExpiryTime, ticket.getExpiryTime()).op(Operator.GreaterThan)
  2738. .build());
  2739. if (number.intValue() == 0) {
  2740. ticket.setIsVipDeduct(true);
  2741. }
  2742. }
  2743. }
  2744. }
  2745. /**
  2746. * 检验奈飞账号状态
  2747. */
  2748. public GroupsRelationView checkNetflixErrorStatus(Long relationId, Long userId) {
  2749. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  2750. GroupsRelationView netflixRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  2751. .field(GroupsRelationView::getId, relationId)
  2752. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  2753. .field(GroupsRelationView::getGoodsId, Constant.NETFLIX_GID)
  2754. .build());
  2755. if (netflixRelationView == null) {
  2756. throw BusinessRuntimeException.getInstance("奈飞车票已过期");
  2757. }
  2758. NetflixUserAccountStatusRecord netflixUseAccountStatusRecord = netflixUserAccountStatusRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountStatusRecord.class)
  2759. .eq(NetflixUserAccountStatusRecord::getRelationId, relationId)
  2760. .eq(NetflixUserAccountStatusRecord::getDeleted, 1)
  2761. .gt(NetflixUserAccountStatusRecord::getCreatedTime, netflixRelationView.getStartTime())
  2762. .in(NetflixUserAccountStatusRecord::getUserId, userIdList)
  2763. .orderByDesc(NetflixUserAccountStatusRecord::getId)
  2764. .last("limit 1"));
  2765. if (netflixUseAccountStatusRecord == null) {
  2766. throw BusinessRuntimeException.getInstance("请先提交账号检测");
  2767. }
  2768. Integer state = netflixUseAccountStatusRecord.getState();
  2769. if (state == 0) {
  2770. throw BusinessRuntimeException.getInstance("您的账号检测中");
  2771. }
  2772. //2是登录失败 3是被封号
  2773. if (state != 3) {
  2774. throw BusinessRuntimeException.getInstance("您的账号未封禁");
  2775. }
  2776. if (netflixRelationView != null) {
  2777. if (netflixRelationView.getIsFrozen() && netflixRelationView.getUnfrozenTime().after(DateTime.now())) {
  2778. throw BusinessRuntimeException.getInstance("冻结未结束");
  2779. }
  2780. if (netflixRelationView.getIsFrozen()) {
  2781. //重新设置车票时长
  2782. netflixRelationView.setExpiryTime(DateUtil.offsetDay(DateTime.now(), netflixRelationView.getReservedDays()));
  2783. }
  2784. if (!netflixRelationView.getIsRecover() && netflixRelationView.getExpiryTime().before(DateTime.now())) {
  2785. throw BusinessRuntimeException.getInstance("奈飞车票已过期");
  2786. }
  2787. }
  2788. netflixRelationView.setNfCheckId(netflixUseAccountStatusRecord.getId());
  2789. netflixRelationView.setNfOriOrderId(netflixUseAccountStatusRecord.getOrderId());
  2790. return netflixRelationView;
  2791. }
  2792. /**
  2793. * 获取车票 并生成订单
  2794. */
  2795. public TicketChangeDto getTicketAndGenerateOrder(Long userId, Long skuId, Date startTime, Date expiryTime) {
  2796. Retryer<TicketChangeDto> build = RetryerBuilder.<TicketChangeDto>newBuilder()
  2797. .retryIfException()
  2798. //运行时异常重试
  2799. .retryIfRuntimeException()
  2800. //false重试
  2801. .retryIfResult(res -> res == null)
  2802. //1s 间隔
  2803. .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
  2804. //停止策略 : 尝试请求1次
  2805. .withStopStrategy(StopStrategies.stopAfterAttempt(1)).build();
  2806. if (startTime == null) {
  2807. startTime = DateTime.now();
  2808. }
  2809. GoodsDonSku sku = goodsDonSkuMapper.selectById(skuId);
  2810. if (expiryTime == null) {
  2811. if (sku.getDays() != null) {
  2812. expiryTime = DateUtil.offsetDay(startTime, sku.getDays());
  2813. } else {
  2814. expiryTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  2815. }
  2816. }
  2817. Date finalStartTime = startTime;
  2818. Date finalExpiryTime = expiryTime;
  2819. try {
  2820. return build.call(() -> {
  2821. GroupsTrips groups = groupsMapper.selectCollegeStudentUserGptTicket(skuId);
  2822. if (groups == null) {
  2823. groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class)
  2824. .eq(GroupsTrips::getStatus, GroupsTrips.Status.waiting)
  2825. .eq(GroupsTrips::getSkuId, skuId)
  2826. .last("limit 1"));
  2827. }
  2828. GroupsRelation relation = null;
  2829. if (groups != null) {
  2830. relation = groupsRelationMapper.selectRandomOneRelationByGroupsId(groups.getId());
  2831. }
  2832. //生成空车队
  2833. if (relation == null) {
  2834. relation = groupsFuncService.createNewGroupsTrips(sku);
  2835. }
  2836. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  2837. .set(GroupsRelation::getUserId, userId)
  2838. .set(GroupsRelation::getStartTime, finalStartTime)
  2839. .set(GroupsRelation::getExpiryTime, finalExpiryTime)
  2840. .set(GroupsRelation::getStatus, GroupsRelation.Status.validity)
  2841. .eq(GroupsRelation::getId, relation.getId())
  2842. .eq(GroupsRelation::getUserId, 0));
  2843. if (update > 0) {
  2844. groupsMapper.decrAvailableNum(relation.getGroupsId());
  2845. Long relationId = relation.getId();
  2846. //生成新的订单
  2847. OrderDon otherOrderDon = generateNewTicketOrder(relationId, userId, sku);
  2848. TicketChangeDto ticketChangeDto = new TicketChangeDto();
  2849. ticketChangeDto.setOtherRelationId(relationId);
  2850. ticketChangeDto.setOtherOrderId(otherOrderDon.getId());
  2851. return ticketChangeDto;
  2852. }
  2853. log.error("发送用户:{} GPT镜像车票失败,进行重试", userId);
  2854. return null;
  2855. });
  2856. } catch (ExecutionException | RetryException e) {
  2857. log.error("发送用户GPT镜像失败:{}", StringUtil.getErrorText(e));
  2858. return null;
  2859. }
  2860. }
  2861. private OrderDon generateNewTicketOrder(Long relationId, Long userId, GoodsDonSku sku) {
  2862. OrderDon orderDon = new OrderDon();
  2863. orderDon.setUserId(userId);
  2864. orderDon.setOrderNo(SEQUENCE.nextId().toString());
  2865. orderDon.setMoney(BigDecimal.ZERO);
  2866. orderDon.setRelationId(relationId);
  2867. orderDon.setGoodsId(sku.getGoodsId());
  2868. orderDon.setSkuId(sku.getId());
  2869. orderDon.setType(OrderDon.Type.TICKET_REPLACE);
  2870. orderDon.setStatus(OrderDon.Status.complete);
  2871. orderDonMapper.insert(orderDon);
  2872. return orderDon;
  2873. }
  2874. private void setAIZoneMirrorTicketInfo(UserMirrorTicketView ticket) {
  2875. setAIZoneGptMirrorInfo(ticket);
  2876. }
  2877. private void setAIZoneGptMirrorInfo(UserMirrorTicketView ticket) {
  2878. if (ticket.getGoodsId() != null && ticket.getGoodsId() == Constant.GPT_PLUS_GID) {
  2879. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
  2880. .eq(ChatgptUser::getRelationId, ticket.getRelationId())
  2881. .last("limit 1"));
  2882. if (chatgptUser != null) {
  2883. ticket.setModel(chatgptUser.getModel());
  2884. if (chatgptUser.getRenewSkuId() != null) {
  2885. Optional.ofNullable(goodsDonSkuMapper.selectById(chatgptUser.getRenewSkuId())).ifPresent(renewSku -> ticket.setRenewSpecVal(renewSku.getSpecVal()));
  2886. }
  2887. }
  2888. }
  2889. if (ticket.getGoodsId() != null && ticket.getGoodsId() == Constant.CLAUDE_PRO_GID) {
  2890. ClaudeUser claudeUser = claudeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeUser.class)
  2891. .eq(ClaudeUser::getRelationId, ticket.getRelationId())
  2892. .last("limit 1"));
  2893. if (claudeUser != null) {
  2894. if (claudeUser.getRenewSkuId() != null) {
  2895. Optional.ofNullable(goodsDonSkuMapper.selectById(claudeUser.getRenewSkuId())).ifPresent(renewSku -> ticket.setRenewSpecVal(renewSku.getSpecVal()));
  2896. }
  2897. }
  2898. }
  2899. }
  2900. public OrderRefundDto getRefundInfo(GroupsRelationView netflixRelationView) {
  2901. OrderDon orderDon = orderDonMapper.selectById(netflixRelationView.getNfOriOrderId());
  2902. Long betweenDay = Long.valueOf(netflixRelationView.getReservedDays());
  2903. //未冻结时,使用车票时长
  2904. if (!netflixRelationView.getIsFrozen()) {
  2905. Date expiryTime = netflixRelationView.getExpiryTime();
  2906. if (expiryTime == null) {
  2907. //用订单时间
  2908. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  2909. expiryTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), sku.getMonths());
  2910. }
  2911. betweenDay= DateUtil.betweenDay(DateTime.now(), expiryTime, false) + 1;
  2912. }
  2913. GoodsDonSku oriTicketSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  2914. //每天单价
  2915. BigDecimal dayPrice = oriTicketSku.getPrice().divide(BigDecimal.valueOf(oriTicketSku.getMonths() * 30), RoundingMode.DOWN);
  2916. //需要退款金额
  2917. BigDecimal totalRefundMoney = dayPrice.multiply(BigDecimal.valueOf(betweenDay));
  2918. BigDecimal refundBalance = BigDecimal.ZERO;
  2919. BigDecimal refundMoney = BigDecimal.ZERO;
  2920. String outNo = StrUtil.EMPTY;
  2921. //订单金额为0 直接退款余额
  2922. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  2923. refundBalance = totalRefundMoney;
  2924. } else {
  2925. BigDecimal remainRefundBalanceMoney = null;
  2926. if (orderDon.getMoney().compareTo(totalRefundMoney) < 0) {
  2927. remainRefundBalanceMoney = totalRefundMoney.subtract(orderDon.getMoney());
  2928. refundMoney = orderDon.getMoney();
  2929. }
  2930. if (remainRefundBalanceMoney != null) {
  2931. refundBalance = refundBalance.add(remainRefundBalanceMoney);
  2932. }
  2933. }
  2934. OrderRefundDto orderRefundDto = new OrderRefundDto();
  2935. orderRefundDto.setRefundBalance(refundBalance);
  2936. orderRefundDto.setRefundMoney(refundMoney);
  2937. return orderRefundDto;
  2938. }
  2939. private String getRefundType(BigDecimal refundMoney, BigDecimal refundBalance, OrderDon orderDon) {
  2940. String refundType;
  2941. if (refundMoney.compareTo(BigDecimal.ZERO) > 0 && refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  2942. refundType = "bxj";
  2943. } else if (refundMoney.compareTo(BigDecimal.ZERO) == 0 && refundBalance.compareTo(BigDecimal.ZERO) > 0) {
  2944. refundType = "balance";
  2945. } else {
  2946. refundType = orderDon.getType().name();
  2947. }
  2948. return refundType;
  2949. }
  2950. }