GroupRelationFrontServiceImpl.java 158 KB

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