GroupRelationFrontServiceImpl.java 161 KB

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