ClaudeCodeServiceImpl.java 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  1. package com.cyksj.service.claude.impl;
  2. import cn.hutool.core.date.DateTime;
  3. import cn.hutool.core.date.DateUtil;
  4. import cn.hutool.core.lang.Assert;
  5. import cn.hutool.core.util.ObjectUtil;
  6. import cn.hutool.http.HttpException;
  7. import cn.hutool.http.HttpResponse;
  8. import cn.hutool.http.HttpUtil;
  9. import cn.hutool.http.Method;
  10. import cn.hutool.json.JSONObject;
  11. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  12. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  13. import com.cyksj.common.constant.Constant;
  14. import com.cyksj.common.exception.BusinessRuntimeException;
  15. import com.cyksj.common.util.Jsons;
  16. import com.cyksj.common.util.StringUtil;
  17. import com.cyksj.mapper.*;
  18. import com.cyksj.mapper.claudecode.*;
  19. import com.cyksj.mapper.manage.distribute.DistributePointsExchangeMoneyMapper;
  20. import com.cyksj.mapper.manage.distribute.DistributeWaitingSendPointsMapper;
  21. import com.cyksj.model.dto.ClaudeCodeDeductDto;
  22. import com.cyksj.model.entity.*;
  23. import com.cyksj.model.manage.views.GroupsRelationView;
  24. import com.cyksj.model.request.ClaudeCodeApiKeysReq;
  25. import com.cyksj.model.request.ClaudeCodeCreditCardUseReq;
  26. import com.cyksj.model.request.ClaudeCodeDelReq;
  27. import com.cyksj.model.request.CreditResetReq;
  28. import com.cyksj.model.request.codex.CodexUserPackageReq;
  29. import com.cyksj.model.response.ClaudeCodeRewardDetailsResp;
  30. import com.cyksj.model.response.CreditResetResp;
  31. import com.cyksj.model.response.TimeRateConfigsResp;
  32. import com.cyksj.model.response.claudecode.ClaudeCodeResp;
  33. import com.cyksj.model.views.*;
  34. import com.cyksj.redis.RedisService;
  35. import com.cyksj.service.api.ClaudeCodexApiService;
  36. import com.cyksj.service.claude.ClaudeCodeService;
  37. import com.cyksj.service.codex.CodexService;
  38. import com.cyksj.service.user.UserBindRelationService;
  39. import com.ejlchina.searcher.BeanSearcher;
  40. import com.ejlchina.searcher.SearchResult;
  41. import com.ejlchina.searcher.param.Operator;
  42. import com.ejlchina.searcher.util.MapUtils;
  43. import com.github.rholder.retry.*;
  44. import lombok.RequiredArgsConstructor;
  45. import lombok.extern.slf4j.Slf4j;
  46. import org.springframework.dao.DuplicateKeyException;
  47. import org.springframework.stereotype.Service;
  48. import org.springframework.transaction.annotation.Transactional;
  49. import java.math.BigDecimal;
  50. import java.math.RoundingMode;
  51. import java.util.*;
  52. import java.util.concurrent.ExecutionException;
  53. import java.util.concurrent.TimeUnit;
  54. /**
  55. * 项目名: yhlxj11111111
  56. * 文件名: ClaudeCodeServiceImpl
  57. * 创建者: JavaZou
  58. * 创建时间:2025/8/8 10:55
  59. */
  60. @Service
  61. @RequiredArgsConstructor
  62. @Slf4j
  63. public class ClaudeCodeServiceImpl implements ClaudeCodeService {
  64. private final UserBindRelationService userBindRelationService;
  65. private final GroupsRelationMapper relationMapper;
  66. private final BeanSearcher beanSearcher;
  67. private final ClaudeCodeUserRenewExpiryRecordMapper claudeCodeUserRenewExpiryRecordMapper;
  68. private final ClaudeCodeUserMapper claudeCodeUserMapper;
  69. private final GoodsDonSkuMapper skuMapper;
  70. private final GroupsMapper groupsMapper;
  71. private final OrderDonMapper orderDonMapper;
  72. private final OrderDonGalaxyCoinRecordMapper orderDonGalaxyCoinRecordMapper;
  73. private final ClaudeCodeUserResetRecordMapper claudeCodeUserResetRecordMapper;
  74. private final ClaudeCodeUserCreditCardRecordMapper claudeCodeUserCreditCardRecordMapper;
  75. private final ClaudeCodeCreditCardMapper claudeCodeCreditCardMapper;
  76. private final UserMapper userMapper;
  77. private final DistributeWaitingSendPointsMapper distributeWaitingSendPointsMapper;
  78. private final DistributePointsExchangeMoneyMapper distributePointsExchangeMoneyMapper;
  79. private final GoodsDonMapper goodsDonMapper;
  80. private final ClaudeCodeDayResetRecordMapper claudeCodeDayResetRecordMapper;
  81. private final RedisService redisService;
  82. private final CodexService codexService;
  83. private final CodexUserMapper codexUserMapper;
  84. private final ClaudeCodexApiService claudeCodexApiService;
  85. private final ClaudeCodeDeductOrderRelateMapper claudeCodeDeductOrderRelateMapper;
  86. @Override
  87. public void generateOrUpdateClaudeCodeUserInfo(Long orderId, Long relationId, Long userId, GoodsDonSku sku, Integer orderType) {
  88. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  89. GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getId, relationId).in(GroupsRelation::getUserId, userIdList));
  90. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  91. GoodsDonSku relationSku = skuMapper.selectById(groupsTrips.getSkuId());
  92. Long thisCodeOriSkuId = relationSku.getId();
  93. Long relationUserId = relation.getUserId();
  94. //此时车票的套餐规格积分
  95. Integer thisRelationCodeDayilyLimit = null;
  96. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).eq(ClaudeCodeUser::getRelationId, relationId).last("limit 1"));
  97. if (claudeCodeUser != null) {
  98. thisRelationCodeDayilyLimit = claudeCodeUser.getClaudeDailyLimit();
  99. }
  100. Date expiryTime = relation.getExpiryTime();
  101. Integer claudeDailyLimit = sku.getClaudeDailyLimit();
  102. Integer claudePermanentBalance = sku.getClaudePermanentBalance();
  103. Long skuId = sku.getId();
  104. Boolean isUpgrade = false;
  105. Date renewExpiryTime = null;
  106. //若是续费升级 记录此时续费升级的过期时间
  107. if (!ObjectUtil.equal(thisCodeOriSkuId, skuId)) {
  108. //非车票原规格id 续费升级记录
  109. saveClaudeCodeRenewExpiryRecord(orderId, relationUserId, relationId, skuId);
  110. //是否需要修改当前claude code user 套餐等级
  111. if (thisRelationCodeDayilyLimit != null && thisRelationCodeDayilyLimit <= claudeDailyLimit) {
  112. if (sku.getDays() != null) {
  113. renewExpiryTime = DateUtil.offsetDay(DateTime.now(), sku.getDays());
  114. } else {
  115. renewExpiryTime = DateUtil.offsetMonth(DateTime.now(), sku.getMonths());
  116. }
  117. isUpgrade = true;
  118. }
  119. }
  120. generateOrUpdateClaudeCodeUser(relationUserId, relationId, claudeDailyLimit, claudePermanentBalance, expiryTime, isUpgrade, orderId, skuId, renewExpiryTime, sku.getSpecVal(), userIdList);
  121. try {
  122. //获取最新的claude code user
  123. claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).eq(ClaudeCodeUser::getRelationId, relationId).last("limit 1"));
  124. //生成claude code或更新用户套餐
  125. ClaudeCodeResp codeUserPackage = createOrUpdateClaudeCodeUserPackage(relation.getUserId(), claudeCodeUser.getPlanName(), claudeCodeUser.getClaudeDailyLimit(), claudeCodeUser.getClaudePermanentBalance(), claudeCodeUser.getExpiryTime(), claudeCodeUser.getRelationId(), sku);
  126. if (!Constant.SUCCESS.equals(codeUserPackage.getMessage())) {
  127. //重试更新code userInfo数据
  128. setClaudeCodeUserRetryUpdateInfo(relationId);
  129. return;
  130. }
  131. //清缓存
  132. if (orderType != null && orderType == 2) {
  133. invalidateUserCache(relationUserId);
  134. }
  135. } catch (Exception e) {
  136. log.error("生成或更新claude code用户:{}套餐skuId:{} 失败,error_info:{}", userId, skuId, StringUtil.getErrorText(e));
  137. //重试更新code userInfo数据
  138. setClaudeCodeUserRetryUpdateInfo(relationId);
  139. }
  140. }
  141. private void generateOrUpdateClaudeCodeUser(Long relationUserId, Long relationId, Integer claudeDailyLimit, Integer claudePermanentBalance, Date expiryTime, Boolean isUpgrade, Long orderId, Long renewSkuId, Date renewExpiryTime, String planName, List<Long> userIdList) {
  142. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).eq(ClaudeCodeUser::getRelationId, relationId).last("limit 1"));
  143. if (claudeCodeUser == null) {
  144. claudeCodeUser = new ClaudeCodeUser();
  145. }
  146. if (isUpgrade) {
  147. claudeCodeUser.setRenewOrderId(orderId);
  148. claudeCodeUser.setRenewSkuId(renewSkuId);
  149. claudeCodeUser.setRenewExpiryTime(renewExpiryTime);
  150. claudeCodeUser.setPlanName(planName);
  151. claudeCodeUser.setClaudeDailyLimit(claudeDailyLimit);
  152. claudeCodeUser.setClaudePermanentBalance(claudePermanentBalance);
  153. }
  154. claudeCodeUser.setUserId(relationUserId);
  155. claudeCodeUser.setRelationId(relationId);
  156. claudeCodeUser.setExpiryTime(expiryTime);
  157. if (claudeCodeUser.getId() == null) {
  158. claudeCodeUser.setPlanName(planName);
  159. claudeCodeUser.setClaudeDailyLimit(claudeDailyLimit);
  160. claudeCodeUser.setClaudePermanentBalance(claudePermanentBalance);
  161. //可重置次数
  162. Integer resetCount = claudeCodeUserResetRecordMapper.getUserResetCountByUserIds(userIdList);
  163. if (resetCount != null && resetCount > 0) {
  164. claudeCodeUser.setResetCount(resetCount);
  165. }
  166. }
  167. if (claudeCodeUser.getId() == null) {
  168. try {
  169. claudeCodeUserMapper.insert(claudeCodeUser);
  170. } catch (DuplicateKeyException e) {
  171. log.info("插入claude code user 重复");
  172. }
  173. } else claudeCodeUserMapper.updateById(claudeCodeUser);
  174. }
  175. @Override
  176. public ClaudeCodeResp createApiKeys(ClaudeCodeApiKeysReq req) throws Exception {
  177. Long userId = req.getUserId();
  178. if (checkClaudeCodeUser(userId)) {
  179. Long claudeCodeUserId = getClaudeCodeUserId(userId);
  180. Assert.notNull(claudeCodeUserId, "您的claude code账号已过期");
  181. req.setUserId(claudeCodeUserId);
  182. return claudeCodexApiService.createApiKeys(req);
  183. }
  184. throw new BusinessRuntimeException("您还没有claudecode账号");
  185. }
  186. @Override
  187. public void deleteApiKeysById(ClaudeCodeDelReq delReq) throws Exception {
  188. Long userId = delReq.getUserId();
  189. Long keyId = delReq.getKeyId();
  190. if (checkClaudeCodeUser(userId)) {
  191. Long claudeCodeUserId = getClaudeCodeUserId(userId);
  192. claudeCodexApiService.deleteApiKeysById(claudeCodeUserId, keyId);
  193. }
  194. }
  195. @Override
  196. public List<ClaudeCodeUserApiKeysView> getUserApiKeys(long userId) throws Exception {
  197. Long claudeCodeUserId = getClaudeCodeUserId(userId);
  198. if (claudeCodeUserId != null) {
  199. return claudeCodexApiService.getUserApiKeys(claudeCodeUserId);
  200. }
  201. return null;
  202. }
  203. @Override
  204. public ClaudeCodeResp getUserDashboard(Long userId) throws Exception {
  205. Long claudeCodeUserId = getClaudeCodeUserId(userId);
  206. if (claudeCodeUserId != null) {
  207. String url = String.format(Constant.CLAUDE_CODE_API_PREFIX + "api/claude/users/%s/dashboard", claudeCodeUserId);
  208. ClaudeCodeResp claudeCodeResp = executeClaudeCodeGetApi(url);
  209. return claudeCodeResp;
  210. }
  211. return null;
  212. }
  213. @Override
  214. public ClaudeCodeResp getUserBalance(Long userId) throws Exception {
  215. Long claudeCodeUserId = getClaudeCodeUserId(userId);
  216. if (claudeCodeUserId != null) {
  217. String url = String.format(Constant.CLAUDE_CODE_API_PREFIX + "api/users/%s/balance", claudeCodeUserId);
  218. ClaudeCodeResp claudeCodeResp = executeClaudeCodeGetApi(url);
  219. return claudeCodeResp;
  220. }
  221. return null;
  222. }
  223. @Override
  224. public ClaudeCodeResp getCreditsAnalytics(Long userId, String start, String end, String tz, Integer page, Integer limit, String order, String type) throws Exception {
  225. Long claudeCodeUserId = getClaudeCodeUserId(userId);
  226. if (start == null) {
  227. DateTime now = DateTime.now();
  228. start = DateUtil.offsetDay(now, -1).toString();
  229. end = now.toString();
  230. }
  231. if (claudeCodeUserId != null) {
  232. String url = String.format(Constant.CLAUDE_CODE_API_PREFIX + "api/claude/users/%s/analytics?start=%s&end=%s&tz=%s&page=%s&limit=%s&order=%s&type=%s", claudeCodeUserId, start, end, tz, page, limit, order, type);
  233. ClaudeCodeResp claudeCodeResp = executeClaudeCodeGetApi(url);
  234. return claudeCodeResp;
  235. }
  236. return null;
  237. }
  238. /**
  239. * 用户缓存失效
  240. */
  241. @Override
  242. public void invalidateUserCache(Long userId) {
  243. String url = String.format(Constant.CLAUDE_CODE_API_PREFIX + "api/cache/invalidate/user/%s", userId);
  244. try {
  245. executeClaudeCodePostApi(url, null);
  246. } catch (Exception e) {
  247. }
  248. }
  249. @Override
  250. public ClaudeCodeUserInfoView getClaudeCodeUserSubsInfo(Long userId) {
  251. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  252. //是否有该车票
  253. GroupsRelationMirrorView groupsRelationMirrorView = beanSearcher.searchFirst(GroupsRelationMirrorView.class, MapUtils.builder()
  254. .field(GroupsRelationMirrorView::getUserId, userIdList).op(Operator.InList)
  255. .field(GroupsRelationMirrorView::getGoodsId, Constant.CLAUDE_CODE_GOODS_ID)
  256. .field(GroupsRelationMirrorView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  257. .build());
  258. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).in(ClaudeCodeUser::getUserId, userIdList).last("limit 1"));
  259. CodexUser codexUser = null;
  260. CodexUserInfoView codexUserInfoView = null;
  261. //车票不存在
  262. if (groupsRelationMirrorView == null) {
  263. //套餐是否存在
  264. if (claudeCodeUser != null) {
  265. //清除用户套餐
  266. if (delUserPackages(claudeCodeUser.getUserId())) {
  267. claudeCodeUserMapper.deleteById(claudeCodeUser.getId());
  268. //codex
  269. codexUserMapper.delete(Wrappers.lambdaQuery(CodexUser.class).eq(CodexUser::getRelationId, claudeCodeUser.getRelationId()).in(CodexUser::getUserId, userIdList));
  270. }
  271. }
  272. return null;
  273. }
  274. GoodsDonSku sku = null;
  275. if (claudeCodeUser == null) {
  276. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  277. .eq(OrderDon::getGoodsId, Constant.CLAUDE_CODE_GOODS_ID)
  278. .eq(OrderDon::getRelationId, groupsRelationMirrorView.getId())
  279. .in(OrderDon::getUserId, userIdList)
  280. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  281. .orderByDesc(OrderDon::getId)
  282. .last("limit 1"));
  283. if (orderDon != null) {
  284. sku = skuMapper.selectById(orderDon.getSkuId());
  285. generateOrUpdateClaudeCodeUserInfo(orderDon.getId(), orderDon.getRelationId(), orderDon.getUserId(), sku, orderDon.getOrderType());
  286. claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).in(ClaudeCodeUser::getUserId, userIdList).last("limit 1"));
  287. } else {
  288. //试用车票
  289. Long skuId = groupsRelationMirrorView.getSkuId();
  290. sku = skuMapper.selectById(skuId);
  291. generateOrUpdateClaudeCodeUserInfo(null, groupsRelationMirrorView.getId(), groupsRelationMirrorView.getUserId(), sku, null);
  292. claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).in(ClaudeCodeUser::getUserId, userIdList).last("limit 1"));
  293. }
  294. }
  295. //续费升级
  296. if (claudeCodeUser.getRenewSkuId() != null) {
  297. sku = skuMapper.selectById(claudeCodeUser.getRenewSkuId());
  298. }
  299. if (sku == null) {
  300. sku = skuMapper.selectById(groupsRelationMirrorView.getSkuId());
  301. }
  302. if (claudeCodeUser != null) {
  303. claudeCodeUser.setPlanName(sku.getSpecVal());
  304. claudeCodeUser.setExpiryTime(groupsRelationMirrorView.getExpiryTime());
  305. claudeCodeUserMapper.updateById(claudeCodeUser);
  306. }
  307. //是否需要重试更新 cladueCode userInfo信息
  308. if (claudeCodeUser.getIsRetry()) {
  309. try {
  310. ClaudeCodeResp codeUserPackage = createOrUpdateClaudeCodeUserPackage(claudeCodeUser.getUserId(), claudeCodeUser.getPlanName(), claudeCodeUser.getClaudeDailyLimit(), claudeCodeUser.getClaudePermanentBalance(), claudeCodeUser.getExpiryTime(), claudeCodeUser.getRelationId(), sku);
  311. if (!Constant.SUCCESS.equals(codeUserPackage.getMessage())) {
  312. claudeCodeUser.setIsRetry(Boolean.TRUE);
  313. claudeCodeUserMapper.updateById(claudeCodeUser);
  314. } else {
  315. claudeCodeUser.setIsRetry(Boolean.FALSE);
  316. claudeCodeUserMapper.updateById(claudeCodeUser);
  317. }
  318. } catch (Exception e) {
  319. }
  320. }
  321. codexUser = codexUserMapper.selectOne(Wrappers.lambdaQuery(CodexUser.class).eq(CodexUser::getRelationId, claudeCodeUser.getRelationId()).in(CodexUser::getUserId, userIdList).last("limit 1"));
  322. if (codexUser == null) {
  323. //是否赠送codex
  324. if (sku.getIsCodex()) {
  325. CodexUserPackageReq codexPackageReq = CodexUserPackageReq.builder()
  326. .userId(claudeCodeUser.getUserId())
  327. .relationId(claudeCodeUser.getRelationId())
  328. .planName(sku.getCodexPlanName())
  329. .openaiDailyLimit(sku.getOpenaiDailyLimit())
  330. .openaiPermanentBalance(sku.getOpenaiPermanentBalance())
  331. .expiryTime(claudeCodeUser.getExpiryTime()).build();
  332. codexService.createOrUpdateUserPackage(codexPackageReq);
  333. }
  334. }
  335. return ClaudeCodeUserInfoView.builder()
  336. .planName(claudeCodeUser.getPlanName())
  337. .relationId(claudeCodeUser.getRelationId())
  338. .claudeDailyLimit(claudeCodeUser.getClaudeDailyLimit())
  339. .claudePermanentBalance(claudeCodeUser.getClaudePermanentBalance())
  340. .expiryTime(claudeCodeUser.getExpiryTime())
  341. .skuId(groupsRelationMirrorView.getSkuId())
  342. .renewSkuId(claudeCodeUser.getRenewSkuId())
  343. .renewOrderId(claudeCodeUser.getRenewOrderId())
  344. .renewExpiryTime(claudeCodeUser.getRenewExpiryTime())
  345. .highestUsage(sku.getHighestUsage())
  346. .build();
  347. }
  348. public ClaudeCodeResp createOrUpdateClaudeCodeUserPackage(Long userId, String planName, Integer claudeDailyLimit, Integer claudePermanentBalance, Date expiryTime, Long relationId, GoodsDonSku sku) throws Exception {
  349. Map<String, Object> parmas = new HashMap<>();
  350. parmas.put("plan_name", planName.replaceAll(";", ""));
  351. parmas.put("claude_daily_limit", claudeDailyLimit);
  352. parmas.put("claude_quota", claudePermanentBalance);
  353. //服务类型
  354. parmas.put("service_type", "claude");
  355. if (sku != null && sku.getIsCodex()) {
  356. parmas.put("openai_daily_limit", sku.getOpenaiDailyLimit());
  357. parmas.put("openai_quota", sku.getOpenaiPermanentBalance());
  358. //组合
  359. parmas.put("service_type", "combined");
  360. } else {
  361. parmas.put("openai_daily_limit", 0);
  362. parmas.put("openai_quota", 0);
  363. //单独 claude类型
  364. parmas.put("service_type", "claude");
  365. }
  366. parmas.put("expire_time", DateUtil.format(expiryTime, "yyyy-MM-dd HH:mm:ss"));
  367. String planUrl = String.format(Constant.CLAUDE_CODE_API_PREFIX + "api/users/%s/plan", userId);
  368. ClaudeCodeResp claudeCodeResp = executeClaudeCodePostApi(planUrl, Jsons.toJson(parmas));
  369. if (!Constant.SUCCESS.equals(claudeCodeResp.getMessage())) {
  370. log.info("用户claude code用户:{}套餐:{}创建或更新失败,info:{}", userId, planName, claudeCodeResp.getMessage());
  371. } else {
  372. //是否赠送codex
  373. if (sku != null && sku.getIsCodex()) {
  374. CodexUserPackageReq codexPackageReq = CodexUserPackageReq.builder()
  375. .userId(userId)
  376. .relationId(relationId)
  377. .planName(sku.getCodexPlanName())
  378. .openaiDailyLimit(sku.getOpenaiDailyLimit())
  379. .openaiPermanentBalance(sku.getOpenaiPermanentBalance())
  380. .expiryTime(expiryTime).build();
  381. codexService.createOrUpdateUserPackage(codexPackageReq);
  382. } else {
  383. codexService.delCodexUser(userId, relationId);
  384. }
  385. }
  386. return claudeCodeResp;
  387. }
  388. /**
  389. * 校验是否是claude code用户
  390. * @param userId
  391. * @return
  392. */
  393. @Override
  394. public Boolean checkClaudeCodeUser(Long userId) {
  395. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  396. Integer count = relationMapper.selectCountByGoodsId(userIdList, Constant.CLAUDE_CODE_GOODS_ID, DateTime.now());
  397. return count > 0;
  398. }
  399. @Override
  400. public void updateClaudeCodeUserPackageInfo(ClaudeCodeUser claudeCodeUser, Date expiryTime, GoodsDonSku sku) {
  401. try {
  402. ClaudeCodeResp codeUserPackage = createOrUpdateClaudeCodeUserPackage(claudeCodeUser.getUserId(), claudeCodeUser.getPlanName(), claudeCodeUser.getClaudeDailyLimit(), claudeCodeUser.getClaudePermanentBalance(), expiryTime, claudeCodeUser.getRelationId(), sku);
  403. if (!Constant.SUCCESS.equals(codeUserPackage.getMessage())) {
  404. //重试标记
  405. claudeCodeUser.setIsRetry(Boolean.TRUE);
  406. claudeCodeUserMapper.updateById(claudeCodeUser);
  407. return;
  408. }
  409. //刷新缓存
  410. invalidateUserCache(claudeCodeUser.getUserId());
  411. } catch (Exception e) {
  412. claudeCodeUser.setIsRetry(Boolean.TRUE);
  413. claudeCodeUserMapper.updateById(claudeCodeUser);
  414. }
  415. }
  416. @Override
  417. public Boolean delUserPackages(Long userId) {
  418. String url = String.format(Constant.CLAUDE_CODE_API_PREFIX + "api/users/%s/plan?service_type=claude", userId);
  419. try {
  420. ClaudeCodeResp claudeCodeResp = executeClaudeCodeDeletedApi(url);
  421. if (!Constant.SUCCESS.equals(claudeCodeResp.getMessage())) {
  422. log.error("删除用户:{} claude code套餐失败:{}", userId, claudeCodeResp.getMessage());
  423. return Boolean.FALSE;
  424. }
  425. return Boolean.TRUE;
  426. } catch (Exception e) {
  427. log.error("删除用户:{} claude code套餐报错:{}", userId, StringUtil.getErrorText(e));
  428. }
  429. return Boolean.FALSE;
  430. }
  431. @Override
  432. public void handleClaudeCodeUserPackageSku(GroupsRelation relation, GoodsDonSku sku, Long orderId) {
  433. generateOrUpdateClaudeCodeUserInfo(orderId, relation.getId(), relation.getUserId(), sku, 2);
  434. }
  435. @Override
  436. public TimeRateConfigsResp getAllConfigs() {
  437. try {
  438. String url = Constant.CLAUDE_CODE_API_PREFIX + "api/time-multiplier/configs";
  439. ClaudeCodeResp claudeCodeResp = executeClaudeCodeGetApi(url);
  440. return Jsons.parseObject(claudeCodeResp.getData(), TimeRateConfigsResp.class);
  441. } catch (Exception e) {
  442. log.error("获取时间倍率配置列表失败", e);
  443. throw BusinessRuntimeException.getInstance("获取时间倍率配置列表失败");
  444. }
  445. }
  446. @Override
  447. public CreditResetResp resetUserCredits(Long userId, CreditResetReq req) throws Exception {
  448. if (userId <= 0) {
  449. throw BusinessRuntimeException.getInstance("用户ID无效");
  450. }
  451. String url = Constant.CLAUDE_CODE_API_PREFIX + "api/users/" + userId + "/credits/reset";
  452. String body = req != null ? Jsons.toJson(req) : "{}";
  453. ClaudeCodeResp claudeCodeResp = executeClaudeCodePostApi(url, body);
  454. if (!Constant.SUCCESS.equals(claudeCodeResp.getMessage())) {
  455. throw BusinessRuntimeException.getInstance("重置次数失败");
  456. }
  457. return Jsons.parseObject(claudeCodeResp.getData(), CreditResetResp.class);
  458. }
  459. /**
  460. * 验证时间范围
  461. */
  462. private void validateTimeRange(Integer startHour, Integer endHour) {
  463. if (startHour == null || endHour == null) {
  464. throw BusinessRuntimeException.getInstance("开始和结束小时不能为空");
  465. }
  466. if (startHour < 0 || startHour > 23) {
  467. throw BusinessRuntimeException.getInstance("开始小时必须在0-23之间");
  468. }
  469. if (endHour < 0 || endHour > 23) {
  470. throw BusinessRuntimeException.getInstance("结束小时必须在0-23之间");
  471. }
  472. }
  473. /**
  474. * 获取claude code用户id
  475. */
  476. public Long getClaudeCodeUserId(Long userId) {
  477. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  478. GroupsRelationMirrorView groupsRelationMirrorView = beanSearcher.searchFirst(GroupsRelationMirrorView.class, MapUtils.builder()
  479. .field(GroupsRelationMirrorView::getUserId, userIdList).op(Operator.InList)
  480. .field(GroupsRelationMirrorView::getGoodsId, Constant.CLAUDE_CODE_GOODS_ID)
  481. .field(GroupsRelationMirrorView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  482. .build());
  483. if (groupsRelationMirrorView != null) {
  484. return groupsRelationMirrorView.getUserId();
  485. }
  486. return null;
  487. }
  488. /**
  489. * claude code GET请求
  490. */
  491. public ClaudeCodeResp executeClaudeCodeGetApi(String url) {
  492. Retryer<ClaudeCodeResp> build = getApiRetryer(1, 3);
  493. try {
  494. return build.call(() -> {
  495. try {
  496. HttpResponse execute = HttpUtil.createGet(url)
  497. .header(Constant.CLAUDE_CODE_HEARD_KEY, Constant.CLAUDE_CODE_API_ADMIN_KEY)
  498. .setConnectionTimeout(Constant.CONNECT_MILLISECONDS)
  499. .execute();
  500. ClaudeCodeResp resp = Jsons.parseObject(execute.body(), ClaudeCodeResp.class);
  501. if (!Constant.SUCCESS.equals(resp.getMessage())) {
  502. log.error("claude code GET URL:{}接口返回msg:{}", url, resp.getMessage());
  503. }
  504. return resp;
  505. } catch (HttpException e) {
  506. return null;
  507. }
  508. });
  509. } catch (ExecutionException | RetryException e) {
  510. log.error("重试调用claude code GET请求url->{}失败,msg->{}", url, StringUtil.getErrorText(e));
  511. throw BusinessRuntimeException.getInstance("接口请求失败");
  512. }
  513. }
  514. /**
  515. * claude code Post请求
  516. */
  517. public ClaudeCodeResp executeClaudeCodePostApi(String url, String body) {
  518. Retryer<ClaudeCodeResp> build = getApiRetryer(1, 3);
  519. try {
  520. return build.call(() -> {
  521. try {
  522. HttpResponse execute = HttpUtil.createPost(url)
  523. .header(Constant.CLAUDE_CODE_HEARD_KEY, Constant.CLAUDE_CODE_API_ADMIN_KEY)
  524. .setConnectionTimeout(Constant.CONNECT_MILLISECONDS)
  525. .body(body)
  526. .execute();
  527. ClaudeCodeResp resp = Jsons.parseObject(execute.body(), ClaudeCodeResp.class);
  528. if (!Constant.SUCCESS.equals(resp.getMessage())) {
  529. log.error("claude code POST URL:{}接口返回msg:{}", url, resp.getMessage());
  530. }
  531. return resp;
  532. } catch (Exception e) {
  533. return null;
  534. }
  535. });
  536. } catch (ExecutionException | RetryException e) {
  537. log.info("重试调用claude code POST请求 url->{}失败,msg->{}", url, StringUtil.getErrorText(e));
  538. throw BusinessRuntimeException.getInstance("接口请求失败");
  539. }
  540. }
  541. /**
  542. * claude code DELETE请求
  543. */
  544. public ClaudeCodeResp executeClaudeCodeDeletedApi(String url) {
  545. Retryer<ClaudeCodeResp> build = getApiRetryer(1, 3);
  546. try {
  547. return build.call(() -> {
  548. try {
  549. HttpResponse execute = HttpUtil.createRequest(Method.DELETE, url).header(Constant.CLAUDE_CODE_HEARD_KEY, Constant.CLAUDE_CODE_API_ADMIN_KEY).setConnectionTimeout(Constant.CONNECT_MILLISECONDS).execute();
  550. ClaudeCodeResp resp = Jsons.parseObject(execute.body(), ClaudeCodeResp.class);
  551. if (!Constant.SUCCESS.equals(resp.getMessage())) {
  552. log.error("claude code DELETE URL:{}接口返回msg:{}", url, resp.getMessage());
  553. }
  554. return resp;
  555. } catch (HttpException e) {
  556. return null;
  557. }
  558. });
  559. } catch (ExecutionException | RetryException e) {
  560. log.error("重试调用claude code DELETE请求url->{}失败,msg->{}", url, StringUtil.getErrorText(e));
  561. throw BusinessRuntimeException.getInstance("接口请求失败");
  562. }
  563. }
  564. /**
  565. * 记录claude code 续费升级的过期时间
  566. */
  567. private void saveClaudeCodeRenewExpiryRecord(Long orderId, Long relationUserId, Long relationId, Long skuId) {
  568. ClaudeCodeUserRenewExpiryRecord renewExpiryRecord = new ClaudeCodeUserRenewExpiryRecord();
  569. renewExpiryRecord.setOrderId(orderId);
  570. renewExpiryRecord.setUserId(relationUserId);
  571. renewExpiryRecord.setRelationId(relationId);
  572. renewExpiryRecord.setRenewSkuId(skuId);
  573. claudeCodeUserRenewExpiryRecordMapper.insert(renewExpiryRecord);
  574. }
  575. /**
  576. * claude code、codex user用户信息重试更新信息
  577. */
  578. public void setClaudeCodeUserRetryUpdateInfo(Long relationId) {
  579. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).eq(ClaudeCodeUser::getRelationId, relationId).last("limit 1"));
  580. if (claudeCodeUser != null) {
  581. claudeCodeUser.setIsRetry(Boolean.TRUE);
  582. claudeCodeUserMapper.updateById(claudeCodeUser);
  583. }
  584. CodexUser codexUser = codexUserMapper.selectOne(Wrappers.lambdaQuery(CodexUser.class).eq(CodexUser::getRelationId, relationId).last("limit 1"));
  585. if (codexUser != null) {
  586. codexUser.setIsRetry(Boolean.TRUE);
  587. codexUserMapper.updateById(codexUser);
  588. }
  589. }
  590. public Retryer getApiRetryer(Integer sleepSecond, Integer attemptNum) {
  591. Retryer build = RetryerBuilder.newBuilder()
  592. .retryIfException()
  593. //运行时异常重试
  594. .retryIfRuntimeException()
  595. //false重试
  596. .retryIfResult(res -> res == null)
  597. //1s 间隔
  598. .withWaitStrategy(WaitStrategies.fixedWait(sleepSecond, TimeUnit.SECONDS))
  599. //停止策略 : 尝试请求3次
  600. .withStopStrategy(StopStrategies.stopAfterAttempt(attemptNum)).build();
  601. return build;
  602. }
  603. @Override
  604. @Transactional(rollbackFor = Throwable.class)
  605. public void useResetCount(Long userId) throws Exception {
  606. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  607. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(
  608. Wrappers.lambdaQuery(ClaudeCodeUser.class)
  609. .in(ClaudeCodeUser::getUserId, userIdList)
  610. .last("limit 1")
  611. );
  612. if (claudeCodeUser == null) {
  613. throw new BusinessRuntimeException("用户未开通Claude Code服务");
  614. }
  615. Integer currentResetCount = claudeCodeUser.getResetCount();
  616. if (currentResetCount == null || currentResetCount <= 0) {
  617. throw BusinessRuntimeException.getInstance("可用重置次数为0");
  618. }
  619. claudeCodeUser.setResetCount(currentResetCount - 1);
  620. int updateResult = claudeCodeUserMapper.update(claudeCodeUser,
  621. Wrappers.lambdaUpdate(ClaudeCodeUser.class)
  622. .eq(ClaudeCodeUser::getId, claudeCodeUser.getId())
  623. .eq(ClaudeCodeUser::getResetCount, currentResetCount)
  624. );
  625. if (updateResult > 0) {
  626. log.info("用户{}成功使用重置次数,剩余次数:{}", userId, currentResetCount - 1);
  627. //重置用户次数
  628. CreditResetReq creditResetReq = new CreditResetReq();
  629. creditResetReq.setDescription("用户使用重置次数");
  630. //调用API重置用户次数
  631. resetUserCredits(claudeCodeUser.getUserId(), creditResetReq);
  632. ClaudeCodeUserResetRecord resetRecord = new ClaudeCodeUserResetRecord();
  633. resetRecord.setUserId(userId);
  634. resetRecord.setNum(-1);
  635. resetRecord.setResetReason("使用重置次数");
  636. claudeCodeUserResetRecordMapper.insert(resetRecord);
  637. } else {
  638. throw BusinessRuntimeException.getInstance("使用重置次数失败");
  639. }
  640. }
  641. @Override
  642. @Transactional(rollbackFor = Throwable.class)
  643. public void useCreditCard(ClaudeCodeCreditCardUseReq req) throws Exception {
  644. Long userId = req.getUserId();
  645. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  646. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(
  647. Wrappers.lambdaQuery(ClaudeCodeUser.class)
  648. .in(ClaudeCodeUser::getUserId, userIdList)
  649. .last("limit 1")
  650. );
  651. if (claudeCodeUser == null) {
  652. throw new BusinessRuntimeException("用户未开通Claude Code服务");
  653. }
  654. ClaudeCodeCreditCard creditCard = claudeCodeCreditCardMapper.selectOne(
  655. Wrappers.lambdaQuery(ClaudeCodeCreditCard.class)
  656. .eq(ClaudeCodeCreditCard::getStatus, 0)
  657. .in(ClaudeCodeCreditCard::getUserId, userIdList)
  658. .last("limit 1")
  659. );
  660. if (creditCard == null) {
  661. throw new BusinessRuntimeException("无可用补充卡");
  662. }
  663. if (creditCard.getStatus() != 0) {
  664. if (creditCard.getStatus() == 1) {
  665. throw new BusinessRuntimeException("补充卡已被使用");
  666. } else if (creditCard.getStatus() == 2) {
  667. throw new BusinessRuntimeException("补充卡已过期");
  668. } else {
  669. throw new BusinessRuntimeException("补充卡状态异常");
  670. }
  671. }
  672. String cardNumber = creditCard.getCardNumber();
  673. if (creditCard.getExpiryTime() != null && creditCard.getExpiryTime().before(new Date())) {
  674. creditCard.setStatus(2);
  675. claudeCodeCreditCardMapper.updateById(creditCard);
  676. throw new BusinessRuntimeException("补充卡已过期");
  677. }
  678. ClaudeCodeResp dashboard = getUserDashboard(userId);
  679. JSONObject data = Jsons.parseObject(dashboard.getData(), JSONObject.class);
  680. BigDecimal daily_remaining = data.getBigDecimal("daily_remaining");
  681. BigDecimal daily_total = BigDecimal.valueOf(claudeCodeUser.getClaudeDailyLimit());
  682. //超出积分 异常
  683. if (daily_remaining.add(BigDecimal.valueOf(creditCard.getCreditAmount())).compareTo(daily_total) > 0) {
  684. throw BusinessRuntimeException.getInstance("目前使用只能补充到{0},建议您消耗更多额度后再补充使用", daily_total);
  685. }
  686. BigDecimal beforeCodePoints = daily_remaining;
  687. BigDecimal addCodePoints = BigDecimal.valueOf(creditCard.getCreditAmount());
  688. BigDecimal afterCodePoints = beforeCodePoints.add(addCodePoints);
  689. creditCard.setStatus(1);
  690. creditCard.setUsedUserId(userId);
  691. creditCard.setUsedTime(new Date());
  692. int cardUpdateResult = claudeCodeCreditCardMapper.update(creditCard,
  693. Wrappers.lambdaUpdate(ClaudeCodeCreditCard.class)
  694. .eq(ClaudeCodeCreditCard::getId, creditCard.getId())
  695. .eq(ClaudeCodeCreditCard::getStatus, 0)
  696. );
  697. if (cardUpdateResult > 0) {
  698. ClaudeCodeUserCreditCardRecord creditCardRecord = new ClaudeCodeUserCreditCardRecord();
  699. creditCardRecord.setUserId(userId);
  700. creditCardRecord.setBeforeCodePoints(beforeCodePoints);
  701. creditCardRecord.setAddCodePoints(addCodePoints);
  702. creditCardRecord.setAfterCodePoints(afterCodePoints);
  703. creditCardRecord.setCardNumber(cardNumber);
  704. //使用一次
  705. creditCardRecord.setNum(-1);
  706. creditCardRecord.setUseReason("使用补充卡");
  707. claudeCodeUserCreditCardRecordMapper.insert(creditCardRecord);
  708. log.info("用户{}成功使用补充卡{},增加{}预算", userId, cardNumber, addCodePoints);
  709. //调用API调整用户积分
  710. adjClaudeCodeUserPoints(claudeCodeUser.getUserId(), creditCard.getCreditAmount(), "adjustment", "用户使用补充卡");
  711. } else {
  712. throw new BusinessRuntimeException("补充卡使用失败,请重试");
  713. }
  714. }
  715. @Override
  716. public SearchResult<ClaudeCodeUserResetRecordView> getUserResetRecords(Long userId, Integer page, Integer limit) {
  717. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  718. return beanSearcher.search(ClaudeCodeUserResetRecordView.class, MapUtils.builder()
  719. .field(ClaudeCodeUserResetRecordView::getUserId, userIdList).op(Operator.InList)
  720. .page(page, limit)
  721. .orderBy(ClaudeCodeUserResetRecordView::getCreatedTime).desc()
  722. .build());
  723. }
  724. @Override
  725. public SearchResult<ClaudeCodeUserCreditCardRecordView> getUserCreditCardRecords(Long userId, Integer page, Integer limit) {
  726. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  727. return beanSearcher.search(ClaudeCodeUserCreditCardRecordView.class, MapUtils.builder()
  728. .field(ClaudeCodeUserCreditCardRecordView::getUserId, userIdList).op(Operator.InList)
  729. .page(page, limit)
  730. .orderBy(ClaudeCodeUserCreditCardRecordView::getCreatedTime).desc()
  731. .build());
  732. }
  733. @Override
  734. public ClaudeCodeRewardDetailsResp getUserRewardDetails(Long userId, Boolean general) {
  735. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  736. ClaudeCodeRewardDetailsResp response = new ClaudeCodeRewardDetailsResp();
  737. // 获取用户Claude Code信息
  738. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(
  739. Wrappers.lambdaQuery(ClaudeCodeUser.class)
  740. .in(ClaudeCodeUser::getUserId, userIdList)
  741. .last("limit 1")
  742. );
  743. // 设置可重置次数
  744. if (claudeCodeUser != null) {
  745. Integer resetCount = claudeCodeUser.getResetCount();
  746. response.setResetCount(resetCount != null ? resetCount : 0);
  747. } else {
  748. response.setResetCount(0);
  749. }
  750. // 获取可用补充卡数量
  751. Integer availableCreditCards = claudeCodeCreditCardMapper.selectCount(
  752. Wrappers.lambdaQuery(ClaudeCodeCreditCard.class)
  753. .eq(ClaudeCodeCreditCard::getStatus, 0)
  754. .in(ClaudeCodeCreditCard::getUserId, userIdList)
  755. .isNull(ClaudeCodeCreditCard::getUsedUserId)
  756. );
  757. response.setAvailableCreditCards(availableCreditCards != null ? availableCreditCards : 0);
  758. //是否是普通推广
  759. if (general != null && general) {
  760. //提现门槛
  761. DistributePointsExchangeMoney distributePointsExchangeMoney = distributePointsExchangeMoneyMapper.selectOne(Wrappers.lambdaQuery(DistributePointsExchangeMoney.class).last("limit 1"));
  762. response.setThresholdMoney(BigDecimal.valueOf(distributePointsExchangeMoney.getMinPoints()).divide(BigDecimal.valueOf(distributePointsExchangeMoney.getPoints())).multiply(distributePointsExchangeMoney.getMoney()));
  763. // 获取分销相关数据
  764. try {
  765. User user = userMapper.selectById(userId);
  766. List<DistributeWaitingSendPoints> distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectList(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getSendStatus, DistributeWaitingSendPoints.Status.waiting).eq(DistributeWaitingSendPoints::getSharedId, userId).select(DistributeWaitingSendPoints::getPoints));
  767. BigDecimal waitingPoints = BigDecimal.ZERO;
  768. if (!distributeWaitingSendPoints.isEmpty()) {
  769. Optional<BigDecimal> points = distributeWaitingSendPoints.stream().map(DistributeWaitingSendPoints::getPoints).reduce(BigDecimal::add);
  770. if (points.isPresent()) {
  771. waitingPoints = points.get();
  772. }
  773. }
  774. GoodsDon goodsDon = goodsDonMapper.selectById(Constant.CLAUDE_CODE_GOODS_ID);
  775. //cc 分销平台比例
  776. if (goodsDon != null) {
  777. response.setRate(goodsDon.getRate());
  778. }
  779. if (user.getPoints().compareTo(BigDecimal.ZERO) <= 0 && waitingPoints.compareTo(BigDecimal.ZERO) <= 0) {
  780. response.setGotMoney(BigDecimal.ZERO);
  781. response.setWaitingMoney(BigDecimal.ZERO);
  782. } else {
  783. BigDecimal points = BigDecimal.valueOf(distributePointsExchangeMoney.getPoints());
  784. BigDecimal money = distributePointsExchangeMoney.getMoney();
  785. BigDecimal oneHundred = BigDecimal.valueOf(100);
  786. if (user.getPoints().compareTo(BigDecimal.ZERO) >= 0) {
  787. response.setGotMoney(user.getPoints().divide(points).multiply(money).divide(oneHundred, 2, RoundingMode.HALF_DOWN));
  788. }
  789. if (user.getPoints().compareTo(BigDecimal.ZERO) >= 0) {
  790. response.setWaitingMoney(waitingPoints.divide(points).multiply(money).divide(oneHundred, 2, RoundingMode.DOWN));
  791. }
  792. }
  793. } catch (Exception e) {
  794. log.warn("获取用户{}分销数据异常", userId, e);
  795. // 设置默认值
  796. response.setGotMoney(BigDecimal.ZERO);
  797. response.setWaitingMoney(BigDecimal.ZERO);
  798. }
  799. }
  800. return response;
  801. }
  802. @Override
  803. public void sendCreditCard(Long orderId, Long userId, Integer points, String cardNumber, String remark) {
  804. //暂时不送积分卡
  805. if (true) {
  806. return;
  807. }
  808. ClaudeCodeCreditCard creditCard = new ClaudeCodeCreditCard();
  809. creditCard.setUserId(userId);
  810. creditCard.setOrderId(orderId);
  811. creditCard.setCardNumber(cardNumber);
  812. creditCard.setCreditAmount(points);
  813. creditCard.setRemark(remark);
  814. claudeCodeCreditCardMapper.insert(creditCard);
  815. //补充卡明细
  816. ClaudeCodeUserCreditCardRecord creditCardRecord = new ClaudeCodeUserCreditCardRecord();
  817. creditCardRecord.setUserId(userId);
  818. creditCardRecord.setCardNumber(cardNumber);
  819. creditCardRecord.setUseReason(remark);
  820. creditCardRecord.setNum(1);
  821. creditCardRecord.setAddCodePoints(BigDecimal.valueOf(points));
  822. claudeCodeUserCreditCardRecordMapper.insert(creditCardRecord);
  823. }
  824. @Override
  825. public void adjUserRestNum(Long orderId, Long userId, Integer num, String remark) {
  826. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  827. // 获取用户Claude Code信息
  828. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(
  829. Wrappers.lambdaQuery(ClaudeCodeUser.class)
  830. .in(ClaudeCodeUser::getUserId, userIdList)
  831. .last("limit 1")
  832. );
  833. if (claudeCodeUser == null) {
  834. log.info("claude code user不存在");
  835. return;
  836. }
  837. Integer resetCount = claudeCodeUser.getResetCount();
  838. claudeCodeUser.setResetCount(resetCount + num);
  839. if (claudeCodeUser.getResetCount() < 0) {
  840. return;
  841. }
  842. int update = 0;
  843. while (update == 0) {
  844. update = claudeCodeUserMapper.update(claudeCodeUser, Wrappers.lambdaUpdate(ClaudeCodeUser.class).eq(ClaudeCodeUser::getUserId, claudeCodeUser.getUserId()).eq(ClaudeCodeUser::getResetCount, resetCount));
  845. if (update == 0) {
  846. claudeCodeUser = claudeCodeUserMapper.selectOne(
  847. Wrappers.lambdaQuery(ClaudeCodeUser.class)
  848. .in(ClaudeCodeUser::getUserId, userIdList)
  849. .last("limit 1")
  850. );
  851. if (claudeCodeUser == null) {
  852. break;
  853. }
  854. resetCount = claudeCodeUser.getResetCount();
  855. claudeCodeUser.setResetCount(resetCount + num);
  856. if (claudeCodeUser.getResetCount() < 0) {
  857. break;
  858. }
  859. }
  860. //记录获取重置次数记录
  861. ClaudeCodeUserResetRecord resetRecord = new ClaudeCodeUserResetRecord();
  862. resetRecord.setOrderId(orderId);
  863. resetRecord.setUserId(userId);
  864. resetRecord.setResetReason(remark);
  865. resetRecord.setNum(num);
  866. claudeCodeUserResetRecordMapper.insert(resetRecord);
  867. }
  868. }
  869. @Override
  870. @Transactional(rollbackFor = Throwable.class)
  871. public void useDayResetCount(Long userId) throws Exception {
  872. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  873. // 获取用户Claude Code信息
  874. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(
  875. Wrappers.lambdaQuery(ClaudeCodeUser.class)
  876. .in(ClaudeCodeUser::getUserId, userIdList)
  877. .last("limit 1")
  878. );
  879. if (claudeCodeUser == null) {
  880. log.info("claude code user不存在");
  881. return;
  882. }
  883. //非标准版、专业版 不给使用
  884. if (claudeCodeUser.getClaudeDailyLimit() < 5000) {
  885. return;
  886. }
  887. Integer selectCount = claudeCodeDayResetRecordMapper.selectCount(Wrappers.lambdaQuery(ClaudeCodeDayResetRecord.class).in(ClaudeCodeDayResetRecord::getUserId, userIdList).gt(ClaudeCodeDayResetRecord::getCreatedTime, DateUtil.beginOfDay(DateTime.now())));
  888. //今日使用为0
  889. if (selectCount == 0) {
  890. String idxKey = "cc:uid:" + userId;
  891. try {
  892. if (redisService.setNx(idxKey, userId, 5l)) {
  893. //重置用户次数
  894. CreditResetReq creditResetReq = new CreditResetReq();
  895. creditResetReq.setDescription("用户使用每日重置");
  896. //调用API重置用户次数
  897. resetUserCredits(claudeCodeUser.getUserId(), creditResetReq);
  898. ClaudeCodeDayResetRecord claudeCodeDayResetRecord = new ClaudeCodeDayResetRecord();
  899. claudeCodeDayResetRecord.setUserId(userId);
  900. claudeCodeDayResetRecord.setRelationId(claudeCodeUser.getRelationId());
  901. claudeCodeDayResetRecordMapper.insert(claudeCodeDayResetRecord);
  902. }
  903. } finally {
  904. if (redisService.hasKey(idxKey)) {
  905. redisService.del(idxKey);
  906. }
  907. }
  908. }
  909. }
  910. @Override
  911. public Boolean getUserSubs(long userId) {
  912. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  913. //是否有该车票
  914. GroupsRelationMirrorView groupsRelationMirrorView = beanSearcher.searchFirst(GroupsRelationMirrorView.class, MapUtils.builder()
  915. .field(GroupsRelationMirrorView::getUserId, userIdList).op(Operator.InList)
  916. .field(GroupsRelationMirrorView::getGoodsId, Constant.CLAUDE_CODE_GOODS_ID)
  917. .field(GroupsRelationMirrorView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  918. .build());
  919. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).in(ClaudeCodeUser::getUserId, userIdList).last("limit 1"));
  920. //车票不存在
  921. if (groupsRelationMirrorView == null) {
  922. //套餐是否存在
  923. if (claudeCodeUser != null) {
  924. //清除用户套餐
  925. if (delUserPackages(claudeCodeUser.getUserId())) {
  926. claudeCodeUserMapper.deleteById(claudeCodeUser.getId());
  927. }
  928. }
  929. return false;
  930. }
  931. return true;
  932. }
  933. @Override
  934. public ClaudeCodeDeductDto getDeductSkuMoney(Long userId, Long relationId, Long skuId) {
  935. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  936. GroupsRelationView relationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
  937. .field(GroupsRelationView::getGoodsId, Constant.CLAUDE_CODE_GOODS_ID)
  938. .field(GroupsRelationView::getId, relationId)
  939. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  940. .field(GroupsRelationView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
  941. .build());
  942. ClaudeCodeDeductDto claudeCodeDeductDto = new ClaudeCodeDeductDto();
  943. if (relationView == null) {
  944. claudeCodeDeductDto.setDeductMoney(BigDecimal.ZERO);
  945. return claudeCodeDeductDto;
  946. }
  947. ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class).eq(ClaudeCodeUser::getRelationId, relationId).last("limit 1"));
  948. GoodsDonSku upgradeSku = skuMapper.selectById(skuId);
  949. if (upgradeSku.getGoodsId() != Constant.CLAUDE_CODE_GOODS_ID) {
  950. claudeCodeDeductDto.setDeductMoney(BigDecimal.ZERO);
  951. return claudeCodeDeductDto;
  952. }
  953. GoodsDonSku relationPresentSku = null;
  954. Long renewSkuId = claudeCodeUser.getRenewSkuId();
  955. if (renewSkuId != null) {
  956. relationPresentSku = skuMapper.selectById(renewSkuId);
  957. }
  958. if (relationPresentSku == null) {
  959. relationPresentSku = skuMapper.selectById(relationView.getSkuId());
  960. }
  961. if (upgradeSku.getClaudePermanentBalance().intValue() < relationPresentSku.getClaudePermanentBalance().intValue()) {
  962. claudeCodeDeductDto.setDeductMoney(BigDecimal.ZERO);
  963. return claudeCodeDeductDto;
  964. }
  965. claudeCodeDeductDto = getDeductMoney(relationId, relationView.getSkuId(), claudeCodeUser.getRenewSkuId(), claudeCodeUser.getRenewOrderId(), claudeCodeUser.getRenewExpiryTime(), relationView.getStartTime(), relationView.getExpiryTime(), DateTime.now(), userIdList, upgradeSku);
  966. return claudeCodeDeductDto;
  967. }
  968. @Override
  969. public ClaudeCodeDeductDto getDeductMoney(Long relationId, Long relationSkuId, Long renewSkuId, Long renewOrderId, Date renewExpiryTime, Date relationStartTime, Date relationExpiryTime, DateTime now, List<Long> userIdList, GoodsDonSku upgradeSku) {
  970. BigDecimal deductMoney = BigDecimal.ZERO;
  971. //一个月当30天算单价 往上取整
  972. //续费规格
  973. ClaudeCodeDeductDto claudeCodeDeductDto = new ClaudeCodeDeductDto();
  974. if (renewSkuId != null && renewExpiryTime.compareTo(now) > 0) {
  975. OrderDon renewOrderDon = orderDonMapper.selectById(renewOrderId);
  976. BigDecimal orderMoney = renewOrderDon.getMoney().add(Optional.ofNullable(renewOrderDon.getBalance()).orElse(BigDecimal.ZERO)).add(Optional.ofNullable(renewOrderDon.getCouponMoney()).orElse(BigDecimal.ZERO));
  977. OrderDonGalaxyCoinRecord orderDonGalaxyCoinRecord = orderDonGalaxyCoinRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class).eq(OrderDonGalaxyCoinRecord::getOrderId, renewOrderDon.getId()).last("limit 1"));
  978. if (orderDonGalaxyCoinRecord != null) {
  979. orderMoney = orderMoney.add(orderDonGalaxyCoinRecord.getDeductMoney());
  980. }
  981. GoodsDonSku presentSku = skuMapper.selectById(renewSkuId);
  982. if (orderMoney.compareTo(BigDecimal.ZERO) == 0) {
  983. //存在升级后的0元订单 即兑换码订单 不让抵扣
  984. claudeCodeDeductDto.setDeductMoney(BigDecimal.ZERO);
  985. return claudeCodeDeductDto;
  986. } else {
  987. Long betweenDay = DateUtil.betweenDay(now, renewExpiryTime, false) + 1;
  988. //当天购买的按规格原价抵扣
  989. BigDecimal renewDeductMoney;
  990. if (now.toDateStr().equals(DateUtil.format(renewOrderDon.getCreatedTime(), "yyyy-MM-dd"))) {
  991. renewDeductMoney = orderMoney;
  992. deductMoney = deductMoney.add(renewDeductMoney);
  993. if (presentSku.getDays() != null) {
  994. relationExpiryTime = DateUtil.offsetDay(relationExpiryTime, -presentSku.getDays());
  995. } else {
  996. relationExpiryTime = DateUtil.offsetMonth(relationExpiryTime, -presentSku.getMonths());
  997. }
  998. } else {
  999. //此次续费规格单价
  1000. BigDecimal single = getPayOrderSingle(orderMoney, presentSku);
  1001. //该车票抵扣金额
  1002. renewDeductMoney = single.multiply(BigDecimal.valueOf(betweenDay));
  1003. log.info("车票id:{}目前续费升级规格可抵扣的金额为:{}", relationId, renewDeductMoney);
  1004. deductMoney = deductMoney.add(renewDeductMoney);
  1005. relationExpiryTime = DateUtil.offsetDay(relationExpiryTime, -betweenDay.intValue());
  1006. }
  1007. }
  1008. //上一个续费升级规格
  1009. List<OrderDon> orderDOns = claudeCodeUserRenewExpiryRecordMapper.getOtherRenewSkuOrders(renewOrderId, relationId, userIdList);
  1010. OrderDon presentRenewOrderDon = renewOrderDon;
  1011. for (OrderDon thisRenewOrderDon : orderDOns) {
  1012. Long skuId = thisRenewOrderDon.getSkuId();
  1013. GoodsDonSku thisRenewSku = skuMapper.selectById(skuId);
  1014. BigDecimal thisOrderMoney = thisRenewOrderDon.getMoney().add(Optional.ofNullable(thisRenewOrderDon.getBalance()).orElse(BigDecimal.ZERO));
  1015. if (thisOrderMoney.compareTo(BigDecimal.ZERO) == 0) {
  1016. //存在升级后的0元订单 即兑换码订单 不让抵扣
  1017. claudeCodeDeductDto.setDeductMoney(BigDecimal.ZERO);
  1018. return claudeCodeDeductDto;
  1019. }
  1020. //当天购买的按规格原价抵扣
  1021. BigDecimal thisRenewDeductMoney = BigDecimal.ZERO;
  1022. if (now.toDateStr().equals(DateUtil.format(thisRenewOrderDon.getCreatedTime(), "yyyy-MM-dd"))) {
  1023. thisRenewDeductMoney = thisOrderMoney;
  1024. deductMoney = deductMoney.add(thisRenewDeductMoney);
  1025. if (thisRenewSku.getDays() != null) {
  1026. relationExpiryTime = DateUtil.offsetDay(relationExpiryTime, -thisRenewSku.getDays());
  1027. } else {
  1028. relationExpiryTime = DateUtil.offsetMonth(relationExpiryTime, -thisRenewSku.getMonths());
  1029. }
  1030. } else {
  1031. //此次续费订单过期时间
  1032. Date thisOrderExpiryTime;
  1033. if (thisRenewSku.getDays() != null) {
  1034. thisOrderExpiryTime = DateUtil.offsetDay(thisRenewOrderDon.getCreatedTime(), thisRenewSku.getDays());
  1035. } else {
  1036. thisOrderExpiryTime = DateUtil.offsetMonth(thisRenewOrderDon.getCreatedTime(), thisRenewSku.getMonths());
  1037. }
  1038. //续费同规格不处理
  1039. if (!ObjectUtil.equal(thisRenewOrderDon.getSkuId(), presentRenewOrderDon.getSkuId())) {
  1040. //先扣除已使用的天数
  1041. //相差多少天
  1042. Long thisRenewBetDay = DateUtil.betweenDay(thisRenewOrderDon.getCreatedTime(), presentRenewOrderDon.getCreatedTime(), false);
  1043. //扣除已使用的
  1044. thisOrderExpiryTime = DateUtil.offsetDay(thisOrderExpiryTime, -thisRenewBetDay.intValue());
  1045. }
  1046. //此订单过期时间
  1047. if (thisOrderExpiryTime.compareTo(now) > 0) {
  1048. //距离过期还剩多少天
  1049. Long thisDeductBetweenDay = DateUtil.betweenDay(now, thisOrderExpiryTime, false) + 1;
  1050. if (thisDeductBetweenDay != 0) {
  1051. //此次续费规格单价
  1052. BigDecimal single = getPayOrderSingle(thisOrderMoney, thisRenewSku);
  1053. //该车票抵扣金额
  1054. thisRenewDeductMoney = single.multiply(BigDecimal.valueOf(thisDeductBetweenDay));
  1055. deductMoney = deductMoney.add(thisRenewDeductMoney);
  1056. }
  1057. //目前级别续费订单
  1058. presentRenewOrderDon = thisRenewOrderDon;
  1059. relationExpiryTime = DateUtil.offsetDay(relationExpiryTime, -thisDeductBetweenDay.intValue());
  1060. }
  1061. }
  1062. log.info("车票id:{}目前次一级规格:{}可抵扣的金额为:{}", relationId, thisRenewSku.getSpecVal(), thisRenewDeductMoney);
  1063. }
  1064. }
  1065. if (relationExpiryTime.after(now)) {
  1066. //该车票抵扣金额
  1067. BigDecimal deductMoneyFromTicket = getDeductMoneyFromTicket(relationId, userIdList, relationSkuId, now, relationStartTime, relationExpiryTime);
  1068. deductMoney = deductMoney.add(deductMoneyFromTicket);
  1069. }
  1070. log.info("车票id:{}最终到期时间为:{}车票可返回 抵扣金额:{}", relationId, DateUtil.format(relationExpiryTime, "yyyy-MM-dd HH:mm:ss"), deductMoney);
  1071. //超出可抵扣的金额 直接返回
  1072. if (deductMoney.compareTo(upgradeSku.getPrice()) >= 0) {
  1073. BigDecimal overMoney = deductMoney.subtract(upgradeSku.getPrice());
  1074. //超过抵扣金额可换延长会员多少天
  1075. //每天单价
  1076. BigDecimal daySingle = upgradeSku.getPrice().divide(BigDecimal.valueOf(upgradeSku.getMonths())).divide(BigDecimal.valueOf(30), 0, RoundingMode.DOWN);
  1077. //超出部分可换取多少天 低于每天单价为0天
  1078. BigDecimal extendsDays = overMoney.divide(daySingle, 0, RoundingMode.UP);
  1079. claudeCodeDeductDto.setExtendsDays(extendsDays.intValue());
  1080. }
  1081. claudeCodeDeductDto.setDeductMoney(deductMoney);
  1082. return claudeCodeDeductDto;
  1083. }
  1084. private void adjClaudeCodeUserPoints(Long userId, Integer points, String type, String description) throws Exception {
  1085. String apiKeyUrl = String.format(Constant.CLAUDE_CODE_API_PREFIX + "api/claude/users/%s/limit", userId);
  1086. Map<String, Object> parmas = new HashMap<>();
  1087. parmas.put("amount", points);
  1088. parmas.put("type", type);
  1089. parmas.put("description", description);
  1090. ClaudeCodeResp claudeCodeResp = executeClaudeCodePostApi(apiKeyUrl, Jsons.toJson(parmas));
  1091. if (!Constant.SUCCESS.equals(claudeCodeResp.getMessage())) {
  1092. throw BusinessRuntimeException.getInstance("使用补充卡失败");
  1093. }
  1094. }
  1095. /**
  1096. * 获取订单单价
  1097. */
  1098. public BigDecimal getPayOrderSingle(BigDecimal orderMoney, GoodsDonSku sku) {
  1099. //此次续费规格单价
  1100. BigDecimal single;
  1101. //区分天/月
  1102. if (sku.getDays() != null) {
  1103. single = orderMoney.divide(BigDecimal.valueOf(sku.getDays()), 0, RoundingMode.HALF_UP);
  1104. } else {
  1105. single = orderMoney.divide(BigDecimal.valueOf(sku.getMonths()).multiply(BigDecimal.valueOf(30)), 0, RoundingMode.HALF_UP);
  1106. }
  1107. return single;
  1108. }
  1109. /**
  1110. * 获取车票可抵扣金额
  1111. */
  1112. public BigDecimal getDeductMoneyFromTicket(Long relationId, List<Long> userIdList, Long skuId, DateTime now, Date relationStartTime, Date relationExpiryTime) {
  1113. OrderDon oriOrderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getRelationId, relationId).in(OrderDon::getUserId, userIdList).notIn(OrderDon::getStatus, Constant.noOrderAllStatus).eq(OrderDon::getOrderType, 1).orderByDesc(OrderDon::getId).last("limit 1"));
  1114. LambdaQueryWrapper<OrderDon> queryWrapper = Wrappers.lambdaQuery(OrderDon.class);
  1115. if (oriOrderDon != null) {
  1116. queryWrapper.ge(OrderDon::getCreatedTime, oriOrderDon.getCreatedTime());
  1117. }
  1118. List<OrderDon> orderDonList = orderDonMapper.selectList(queryWrapper
  1119. .eq(OrderDon::getRelationId, relationId)
  1120. .in(OrderDon::getUserId, userIdList)
  1121. .eq(OrderDon::getSkuId, skuId)
  1122. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1123. .orderByDesc(OrderDon::getId));
  1124. //部分退款
  1125. if (orderDonList.isEmpty()) {
  1126. orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  1127. .eq(OrderDon::getRelationId, relationId)
  1128. .in(OrderDon::getUserId, userIdList)
  1129. .eq(OrderDon::getSkuId, skuId)
  1130. .notIn(OrderDon::getStatus, Constant.noOrderStatus)
  1131. .orderByDesc(OrderDon::getId));
  1132. }
  1133. //未有订单 返回抵扣金额0
  1134. if (orderDonList.isEmpty()) {
  1135. return BigDecimal.ZERO;
  1136. }
  1137. //原车票订单总实付金额
  1138. BigDecimal totalOrderMoney = BigDecimal.ZERO;
  1139. //原车票订单总天数
  1140. Integer totalDays = 0;
  1141. for (OrderDon orderDon : orderDonList) {
  1142. GoodsDonSku sku = skuMapper.selectById(skuId);
  1143. BigDecimal thisOrderMoney = orderDon.getMoney().add(Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO)).subtract(Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO)).add(Optional.ofNullable(orderDon.getCouponMoney()).orElse(BigDecimal.ZERO));
  1144. OrderDonGalaxyCoinRecord orderDonGalaxyCoinRecord = orderDonGalaxyCoinRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class).eq(OrderDonGalaxyCoinRecord::getOrderId, orderDon.getId()).last("limit 1"));
  1145. if (orderDonGalaxyCoinRecord != null) {
  1146. thisOrderMoney = thisOrderMoney.add(orderDonGalaxyCoinRecord.getDeductMoney());
  1147. }
  1148. if (thisOrderMoney.compareTo(BigDecimal.ZERO) == 0) {
  1149. if (sku.getDays() != null) {
  1150. relationExpiryTime = DateUtil.offsetDay(relationExpiryTime, -sku.getDays());
  1151. } else {
  1152. relationExpiryTime = DateUtil.offsetMonth(relationExpiryTime, -sku.getMonths());
  1153. }
  1154. continue;
  1155. }
  1156. totalOrderMoney = totalOrderMoney.add(thisOrderMoney);
  1157. //总时间
  1158. if (sku.getDays() != null) {
  1159. totalDays += sku.getDays();
  1160. } else {
  1161. totalDays += sku.getMonths() * 30;
  1162. }
  1163. ClaudeCodeDeductOrderRelate claudeCodeDeductOrderRelate = claudeCodeDeductOrderRelateMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeDeductOrderRelate.class).eq(ClaudeCodeDeductOrderRelate::getOrderId, orderDon.getId()).last("limit 1"));
  1164. if (claudeCodeDeductOrderRelate != null) {
  1165. totalOrderMoney = totalOrderMoney.add(claudeCodeDeductOrderRelate.getDeductMoney());
  1166. }
  1167. //原订单数
  1168. if (orderDonList.size() == 1) {
  1169. //此次订单过期时间
  1170. Date thisOrderExpiryTime;
  1171. if (sku.getDays() != null) {
  1172. thisOrderExpiryTime = DateUtil.offsetDay(orderDon.getCreatedTime(), sku.getDays());
  1173. } else {
  1174. thisOrderExpiryTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), sku.getMonths());
  1175. }
  1176. //当天购买的按规格原价抵扣
  1177. if (now.toDateStr().equals(DateUtil.format(relationStartTime, "yyyy-MM-dd")) && (DateUtil.betweenDay(thisOrderExpiryTime, relationExpiryTime, true) == 0)) {
  1178. return totalOrderMoney;
  1179. }
  1180. }
  1181. }
  1182. //总天数为0 不抵扣
  1183. if (totalDays == 0) {
  1184. return BigDecimal.ZERO;
  1185. }
  1186. Long thisDeductBetweenDay = DateUtil.betweenDay(now, relationExpiryTime, false) + 1;
  1187. BigDecimal single = totalOrderMoney.divide(BigDecimal.valueOf(totalDays), 0, RoundingMode.HALF_UP);
  1188. //该车票抵扣金额
  1189. BigDecimal deductMoney = single.multiply(BigDecimal.valueOf(thisDeductBetweenDay));
  1190. if (deductMoney.compareTo(totalOrderMoney) > 0) {
  1191. deductMoney = totalOrderMoney;
  1192. }
  1193. return deductMoney;
  1194. }
  1195. }