GroupRelationFrontServiceImpl.java 141 KB

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