GroupRelationFrontServiceImpl.java 145 KB

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