OrderService.java 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. package com.izouma.nineth.service;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.alibaba.fastjson.serializer.SerializerFeature;
  6. import com.alipay.api.AlipayClient;
  7. import com.alipay.api.request.AlipayTradeWapPayRequest;
  8. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  9. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  10. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
  11. import com.github.binarywang.wxpay.constant.WxPayConstants;
  12. import com.github.binarywang.wxpay.exception.WxPayException;
  13. import com.github.binarywang.wxpay.service.WxPayService;
  14. import com.google.common.base.Splitter;
  15. import com.huifu.adapay.Adapay;
  16. import com.huifu.adapay.core.exception.BaseAdaPayException;
  17. import com.huifu.adapay.model.AdapayCommon;
  18. import com.huifu.adapay.model.Payment;
  19. import com.huifu.adapay.model.Refund;
  20. import com.izouma.nineth.config.*;
  21. import com.izouma.nineth.domain.Collection;
  22. import com.izouma.nineth.domain.*;
  23. import com.izouma.nineth.dto.MarketSettlement;
  24. import com.izouma.nineth.dto.PageQuery;
  25. import com.izouma.nineth.dto.UserBankCard;
  26. import com.izouma.nineth.enums.*;
  27. import com.izouma.nineth.event.CreateAssetEvent;
  28. import com.izouma.nineth.event.CreateOrderEvent;
  29. import com.izouma.nineth.event.OrderNotifyEvent;
  30. import com.izouma.nineth.event.TransferAssetEvent;
  31. import com.izouma.nineth.exception.BusinessException;
  32. import com.izouma.nineth.repo.*;
  33. import com.izouma.nineth.security.Authority;
  34. import com.izouma.nineth.service.sms.SmsService;
  35. import com.izouma.nineth.utils.*;
  36. import com.izouma.nineth.utils.excel.ExcelUtils;
  37. import lombok.AllArgsConstructor;
  38. import lombok.extern.slf4j.Slf4j;
  39. import org.apache.commons.codec.EncoderException;
  40. import org.apache.commons.codec.net.URLCodec;
  41. import org.apache.commons.collections.MapUtils;
  42. import org.apache.commons.lang3.ObjectUtils;
  43. import org.apache.commons.lang3.RandomStringUtils;
  44. import org.apache.commons.lang3.RandomUtils;
  45. import org.apache.commons.lang3.StringUtils;
  46. import org.apache.rocketmq.client.producer.SendResult;
  47. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  48. import org.springframework.cache.annotation.Cacheable;
  49. import org.springframework.context.event.EventListener;
  50. import org.springframework.core.env.Environment;
  51. import org.springframework.data.domain.Page;
  52. import org.springframework.data.redis.core.BoundSetOperations;
  53. import org.springframework.data.redis.core.BoundValueOperations;
  54. import org.springframework.data.redis.core.RedisTemplate;
  55. import org.springframework.scheduling.annotation.Scheduled;
  56. import org.springframework.stereotype.Service;
  57. import org.springframework.ui.Model;
  58. import java.io.File;
  59. import java.io.OutputStream;
  60. import java.math.BigDecimal;
  61. import java.math.BigInteger;
  62. import java.math.RoundingMode;
  63. import java.time.Duration;
  64. import java.time.LocalDate;
  65. import java.time.LocalDateTime;
  66. import java.time.LocalTime;
  67. import java.time.format.DateTimeFormatter;
  68. import java.time.temporal.ChronoUnit;
  69. import java.util.*;
  70. import java.util.concurrent.TimeUnit;
  71. import java.util.concurrent.atomic.AtomicInteger;
  72. import java.util.stream.Collectors;
  73. @Service
  74. @AllArgsConstructor
  75. @Slf4j
  76. public class OrderService {
  77. private OrderRepo orderRepo;
  78. private CollectionRepo collectionRepo;
  79. private UserAddressRepo userAddressRepo;
  80. private UserRepo userRepo;
  81. private Environment env;
  82. private AlipayClient alipayClient;
  83. private AlipayProperties alipayProperties;
  84. private WxPayService wxPayService;
  85. private WxPayProperties wxPayProperties;
  86. private AssetService assetService;
  87. private SysConfigService sysConfigService;
  88. private AssetRepo assetRepo;
  89. private UserCouponRepo userCouponRepo;
  90. private CollectionService collectionService;
  91. private CommissionRecordRepo commissionRecordRepo;
  92. private AdapayProperties adapayProperties;
  93. private GeneralProperties generalProperties;
  94. private RocketMQTemplate rocketMQTemplate;
  95. private RedisTemplate<String, Object> redisTemplate;
  96. private SnowflakeIdWorker snowflakeIdWorker;
  97. private SmsService smsService;
  98. private ErrorOrderRepo errorOrderRepo;
  99. private ShowCollectionRepo showCollectionRepo;
  100. private ShowroomService showroomService;
  101. private CollectionPrivilegeRepo collectionPrivilegeRepo;
  102. private UserBankCardRepo userBankCardRepo;
  103. private IdentityAuthRepo identityAuthRepo;
  104. private CacheService cacheService;
  105. public Page<Order> all(PageQuery pageQuery) {
  106. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  107. }
  108. public String mqCreate(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor,
  109. String sign, boolean vip, int vipPurchase, int vipPoint) {
  110. String qs = null;
  111. try {
  112. qs = AESEncryptUtil.decrypt(sign);
  113. } catch (Exception e) {
  114. throw new BusinessException("签名错误");
  115. }
  116. final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(qs);
  117. if (Math.abs(MapUtils.getLong(map, "ts") - System.currentTimeMillis()) > 90000) {
  118. throw new BusinessException("签名已过期");
  119. }
  120. if (redisTemplate.opsForValue().get(RedisKeys.BLACK_LIST + userId) != null) {
  121. throw new BusinessException("频繁操作,请稍后再试");
  122. }
  123. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.LIMIT_USER + userId);
  124. ops.setIfAbsent(0, Duration.ofSeconds(10));
  125. long val = Optional.ofNullable(ops.increment()).orElse(0L);
  126. if (val > 5) {
  127. if (val > 10) {
  128. redisTemplate.opsForValue().set(RedisKeys.BLACK_LIST + userId, 1, Duration.ofSeconds(60 * 10));
  129. }
  130. throw new BusinessException("频繁操作,请稍后再试");
  131. }
  132. limitReq(collectionId);
  133. Integer stock = collectionService.getStock(collectionId);
  134. if (stock == null || stock <= 0) {
  135. throw new BusinessException("藏品已售罄", ErrorCode.SOLD_OUT);
  136. }
  137. Long id = snowflakeIdWorker.nextId();
  138. SendResult result = rocketMQTemplate.syncSend(generalProperties.getCreateOrderTopic(),
  139. new CreateOrderEvent(id, userId, collectionId, qty, addressId, userCouponId, invitor, vip), 100000);
  140. log.info("发送订单到队列: {}, userId={}, result={}", id, userId, result);
  141. return String.valueOf(id);
  142. }
  143. public void limitReq(Long collectionId) {
  144. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.LIMIT_REQ + collectionId);
  145. ops.setIfAbsent(3000, Duration.ofSeconds(30));
  146. Long val = ops.decrement();
  147. if (val == null || val < 0) {
  148. throw new BusinessException("前方拥堵,请稍后再试");
  149. }
  150. }
  151. public Order create(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor,
  152. Long id, boolean vip) {
  153. long t = System.currentTimeMillis();
  154. qty = 1;
  155. int stock = Optional.ofNullable(collectionService.decreaseStock(collectionId, qty))
  156. .map(Math::toIntExact)
  157. .orElseThrow(new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT));
  158. int usePoint = 0;
  159. // 创建订单出错后需要回滚库存,所以需要try-catch
  160. try {
  161. if (stock < 0) {
  162. throw new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT);
  163. }
  164. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  165. if (collection.getAssetId() != null && collection.getAssetId().equals(778359L)) {
  166. throw new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT);
  167. }
  168. if (collection.getAssetId() != null) {
  169. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("藏品不存在"));
  170. if (asset.getStatus() != AssetStatus.NORMAL) {
  171. throw new BusinessException("藏品已下架");
  172. }
  173. }
  174. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  175. UserCoupon coupon = null;
  176. if (collection.isCouponPayment()) {
  177. if (userCouponId == null) {
  178. throw new BusinessException("必须使用优惠券支付");
  179. }
  180. coupon = userCouponRepo.findById(userCouponId).orElseThrow(new BusinessException("兑换券不存在"));
  181. if (coupon.isUsed()) {
  182. throw new BusinessException("该兑换券已使用");
  183. }
  184. if (coupon.isLimited() && !coupon.getCollectionIds().contains(collectionId)) {
  185. throw new BusinessException("该兑换券不可用");
  186. }
  187. }
  188. if (collection.isScheduleSale()) {
  189. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  190. throw new BusinessException("当前还未开售");
  191. }
  192. }
  193. if (!collection.isOnShelf()) {
  194. if (!collection.isScanCode()) {
  195. throw new BusinessException("藏品已下架");
  196. }
  197. }
  198. if (!collection.isSalable()) {
  199. throw new BusinessException("该藏品当前不可购买");
  200. }
  201. if (collection.getMaxCount() > 0) {
  202. int count;
  203. if (StringUtils.isNotBlank(collection.getCountId())) {
  204. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(), Arrays
  205. .asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  206. } else {
  207. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId, Arrays
  208. .asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  209. }
  210. if (count >= collection.getMaxCount()) {
  211. throw new BusinessException("限购" + collection.getMaxCount() + "件");
  212. }
  213. }
  214. User user = null;
  215. if (ObjectUtils.isNotEmpty(collection.getMinimumCharge()) && collection.getMinimumCharge()
  216. .compareTo(BigDecimal.ZERO) > 0) {
  217. user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  218. if (!user.isCanSale()) {
  219. throw new BusinessException("绿洲石不足");
  220. }
  221. }
  222. //查询是否有拉新任务,只算官方购买
  223. if (collection.getSource() != CollectionSource.TRANSFER && collection.getAssignment() > 0) {
  224. //延迟销售
  225. if (!vip && collection.getTimeDelay()) {
  226. if (collection.getSaleTime().isAfter(LocalDateTime.now())) {
  227. throw new BusinessException("当前还未开售");
  228. }
  229. }
  230. if (user == null) {
  231. user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  232. }
  233. if (vip) {
  234. int purchase = orderRepo
  235. .countByUserIdAndCollectionIdAndVipTrueAndStatusIn(userId, collectionId, Arrays
  236. .asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  237. if (user.getVipPurchase() - purchase <= 0) {
  238. throw new BusinessException("vip名额已使用完毕!");
  239. }
  240. // vip扣除额度
  241. if (ObjectUtils.isNotEmpty(collection.getVipQuota())) {
  242. collectionService.decreaseQuota(collectionId, 1);
  243. }
  244. } else {
  245. if (user.getVipPoint() < 1) {
  246. throw new BusinessException("没有购买名额");
  247. }
  248. usePoint = 1;
  249. }
  250. }
  251. UserAddress userAddress = null;
  252. if (addressId != null) {
  253. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  254. }
  255. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  256. Order order = Order.builder()
  257. .id(Optional.ofNullable(id).orElse(snowflakeIdWorker.nextId()))
  258. .userId(userId)
  259. .collectionId(collectionId)
  260. .name(collection.getName())
  261. .pic(collection.getPic())
  262. .detail(collection.getDetail())
  263. .properties(collection.getProperties())
  264. .category(collection.getCategory())
  265. .canResale(collection.isCanResale())
  266. .royalties(collection.getRoyalties())
  267. .serviceCharge(collection.getServiceCharge())
  268. .type(collection.getType())
  269. .source(collection.getSource())
  270. .minterId(collection.getMinterId())
  271. .minter(minter.getNickname())
  272. .minterAvatar(minter.getAvatar())
  273. .qty(qty)
  274. .price(collection.getPrice())
  275. .gasPrice(gasFee)
  276. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  277. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  278. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  279. .address(Optional.ofNullable(userAddress).map(u ->
  280. u.getProvinceName() + " " + u.getCityName() + " " + u.getDistrictName() + " " + u
  281. .getAddress())
  282. .orElse(null))
  283. .status(OrderStatus.NOT_PAID)
  284. .assetId(collection.getAssetId())
  285. .couponId(userCouponId)
  286. .invitor(invitor)
  287. .countId(collection.getCountId())
  288. .vip(vip)
  289. .vipPoint(usePoint)
  290. .build();
  291. if (coupon != null) {
  292. coupon.setUsed(true);
  293. coupon.setUseTime(LocalDateTime.now());
  294. if (coupon.isNeedGas()) {
  295. order.setTotalPrice(order.getGasPrice());
  296. } else {
  297. order.setTotalPrice(BigDecimal.ZERO);
  298. }
  299. userCouponRepo.save(coupon);
  300. }
  301. if (collection.getSource() == CollectionSource.TRANSFER) {
  302. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  303. asset.setStatus(AssetStatus.TRADING);
  304. assetRepo.save(asset);
  305. collectionRepo.setOnShelf(collectionId, false);
  306. }
  307. order = orderRepo.save(order);
  308. if (order.getTotalPrice().equals(BigDecimal.ZERO)) {
  309. notifyOrder(order.getId(), PayMethod.WEIXIN, null);
  310. }
  311. if (usePoint > 0) {
  312. // 扣除积分
  313. userRepo.addVipPoint(userId, -usePoint);
  314. cacheService.clearUserMy(userId);
  315. }
  316. rocketMQTemplate.syncSend(generalProperties.getUpdateStockTopic(), collectionId, 10000);
  317. log.info("订单创建完成, id={}, {}ms", order.getId(), System.currentTimeMillis() - t);
  318. return order;
  319. } catch (Exception e) {
  320. collectionService.increaseStock(collectionId, qty);
  321. if (usePoint > 0) {
  322. // 扣除积分
  323. userRepo.addVipPoint(userId, usePoint);
  324. cacheService.clearUserMy(userId);
  325. log.info("订单失败加积分用户ID:{}, 积分:{}", userId, usePoint);
  326. }
  327. if (vip) {
  328. collectionService.decreaseQuota(collectionId, 1);
  329. log.info("订单失败加藏品额度CollectionId:{}", collectionId);
  330. }
  331. throw e;
  332. }
  333. }
  334. public Object checkLimit(Long collectionId, Long userId) {
  335. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  336. int limit = collection.getMaxCount();
  337. int count = 0;
  338. if (collection.getMaxCount() > 0) {
  339. if (StringUtils.isNotBlank(collection.getCountId())) {
  340. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(),
  341. Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  342. } else {
  343. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId,
  344. Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  345. }
  346. }
  347. Map<String, Object> map = new HashMap<>();
  348. map.put("limit", limit);
  349. map.put("count", count);
  350. return map;
  351. }
  352. public void payOrderAlipay(Long id, Model model) {
  353. try {
  354. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  355. if (order.getStatus() != OrderStatus.NOT_PAID) {
  356. throw new BusinessException("订单状态错误");
  357. }
  358. JSONObject bizContent = new JSONObject();
  359. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  360. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  361. bizContent.put("out_trade_no", String.valueOf(snowflakeIdWorker.nextId()));
  362. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  363. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  364. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  365. // 测试环境设为1分
  366. bizContent.put("total_amount", "0.01");
  367. }
  368. bizContent.put("subject", order.getName());
  369. bizContent.put("product_code", "QUICK_WAP_PAY");
  370. JSONObject body = new JSONObject();
  371. body.put("action", "payOrder");
  372. body.put("userId", order.getUserId());
  373. body.put("orderId", order.getId());
  374. bizContent.put("body", body.toJSONString());
  375. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  376. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  377. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  378. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  379. String form = alipayClient.pageExecute(alipayRequest).getBody();
  380. model.addAttribute("form", form);
  381. } catch (BusinessException err) {
  382. model.addAttribute("errMsg", err.getError());
  383. } catch (Exception e) {
  384. model.addAttribute("errMsg", e.getMessage());
  385. }
  386. }
  387. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  388. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  389. if (order.getStatus() != OrderStatus.NOT_PAID) {
  390. throw new BusinessException("订单状态错误");
  391. }
  392. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  393. request.setBody(order.getName());
  394. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  395. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  396. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  397. // 测试环境设为1分
  398. // request.setTotalFee(1);
  399. }
  400. request.setSpbillCreateIp("180.102.110.170");
  401. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  402. request.setTradeType(tradeType);
  403. request.setOpenid(openId);
  404. request.setSignType("MD5");
  405. JSONObject body = new JSONObject();
  406. body.put("action", "payOrder");
  407. body.put("userId", order.getUserId());
  408. body.put("orderId", order.getId());
  409. request.setAttach(body.toJSONString());
  410. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  411. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  412. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  413. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  414. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  415. }
  416. throw new BusinessException("不支持此付款方式");
  417. }
  418. @Cacheable(value = "adapay", key = "#id+'_'+#payChannel")
  419. public Object payAdapay(Long id, String payChannel, String openId) throws BaseAdaPayException {
  420. List<String> aliChannels = Arrays.asList("alipay", "alipay_qr", "alipay_wap");
  421. List<String> wxChannels = Arrays.asList("wx_pub", "wx_lite");
  422. if (!aliChannels.contains(payChannel) && !wxChannels.contains(payChannel)) {
  423. throw new BusinessException("不支持此渠道");
  424. }
  425. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  426. if (SecurityUtils.getAuthenticatedUser() != null
  427. && !SecurityUtils.getAuthenticatedUser().getId().equals(order.getUserId())) {
  428. log.error("payAdapay userId错误 requestUserId={} orderUserId={}",
  429. SecurityUtils.getAuthenticatedUser().getId(), order.getUserId());
  430. }
  431. Collection collection = collectionRepo.findById(order.getCollectionId())
  432. .orElseThrow(new BusinessException("藏品不存在"));
  433. User invitor = null;
  434. if (order.getInvitor() != null) {
  435. invitor = userRepo.findById(order.getInvitor()).orElse(null);
  436. }
  437. if (invitor != null && StringUtils.isBlank(invitor.getSettleAccountId())) {
  438. invitor = null;
  439. }
  440. if (order.getStatus() != OrderStatus.NOT_PAID) {
  441. throw new BusinessException("订单状态错误");
  442. }
  443. Map<String, Object> paymentParams = new HashMap<>();
  444. paymentParams.put("order_no", String.valueOf(snowflakeIdWorker.nextId()));
  445. paymentParams.put("pay_amt", order.getTotalPrice().setScale(2, RoundingMode.HALF_UP).toPlainString());
  446. paymentParams.put("app_id", adapayProperties.getAppId());
  447. paymentParams.put("pay_channel", payChannel);
  448. paymentParams.put("goods_title", collection.getName());
  449. paymentParams.put("goods_desc", collection.getName());
  450. paymentParams.put("time_expire", DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
  451. .format(LocalDateTime.now().plusMinutes(3)));
  452. paymentParams.put("notify_url", adapayProperties.getNotifyUrl() + "/order/" + adapayProperties
  453. .getMerchant() + "/" + order.getId());
  454. List<Map<String, Object>> divMembers = new ArrayList<>();
  455. BigDecimal totalAmount = order.getTotalPrice().subtract(order.getGasPrice());
  456. BigDecimal restAmount = order.getTotalPrice().multiply(BigDecimal.valueOf(1));
  457. if (collection.getSource().equals(CollectionSource.TRANSFER)) {
  458. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("无记录"));
  459. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("拥有者用户不存在"));
  460. if (collection.getServiceCharge() + collection.getRoyalties() > 0) {
  461. // 扣除手续费、服务费、GAS费
  462. restAmount = divMoney(totalAmount, restAmount, divMembers, owner.getMemberId(),
  463. 100 - (collection.getServiceCharge() + collection.getRoyalties()), false);
  464. }
  465. restAmount = divMoney(restAmount, divMembers, "0", restAmount, true);
  466. } else {
  467. if (invitor != null && invitor.getShareRatio() != null
  468. && invitor.getShareRatio().compareTo(BigDecimal.ZERO) > 0) {
  469. restAmount = divMoney(totalAmount, restAmount, divMembers, invitor.getMemberId(),
  470. invitor.getShareRatio().intValue(), false);
  471. }
  472. restAmount = divMoney(restAmount, divMembers, "0", restAmount, true);
  473. }
  474. if (restAmount.compareTo(BigDecimal.ZERO) != 0) {
  475. log.error("分账出错 {}", JSON.toJSONString(divMembers, SerializerFeature.PrettyFormat));
  476. throw new BusinessException("分账出错");
  477. }
  478. if (divMembers.size() > 1) {
  479. paymentParams.put("div_members", divMembers);
  480. }
  481. Map<String, Object> expend = new HashMap<>();
  482. paymentParams.put("expend", expend);
  483. if ("wx_pub".equals(payChannel)) {
  484. if (StringUtils.isBlank(openId)) {
  485. throw new BusinessException("缺少openId");
  486. }
  487. expend.put("open_id", openId);
  488. expend.put("limit_pay", "1");
  489. }
  490. Map<String, Object> response;
  491. if ("wx_lite".equals(payChannel)) {
  492. paymentParams.put("adapay_func_code", "wxpay.createOrder");
  493. paymentParams.put("callback_url", generalProperties.getHost() + "/9th/orders");
  494. response = AdapayCommon.requestAdapayUits(paymentParams);
  495. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  496. } else {
  497. response = Payment.create(paymentParams);
  498. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  499. AdapayService.checkSuccess(response);
  500. // 保存adapay的订单id,用于后续取消订单时的查询
  501. BoundSetOperations<String, Object> ops = redisTemplate.boundSetOps(RedisKeys.PAY_RECORD + order.getId());
  502. ops.add(adapayProperties.getMerchant() + "#" + MapUtils.getString(response, "id"));
  503. ops.expire(7, TimeUnit.DAYS);
  504. }
  505. switch (payChannel) {
  506. case "alipay_wap":
  507. case "alipay":
  508. return MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info");
  509. case "alipay_qr":
  510. return MapUtils.getString(MapUtils.getMap(response, "expend"), "qrcode_url");
  511. case "wx_pub":
  512. JSONObject payParams = JSON
  513. .parseObject(MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info"));
  514. payParams.put("timestamp", payParams.get("timeStamp"));
  515. payParams.remove("timeStamp");
  516. return payParams;
  517. default:
  518. return MapUtils.getMap(response, "expend");
  519. }
  520. }
  521. public static BigDecimal divMoney(BigDecimal totalAmount, BigDecimal restAmount, List<Map<String, Object>> divMembers,
  522. String memberId, int ratio, boolean feeFlag) {
  523. if (ratio == -1 || (ratio > 0 && ratio < 100)) {
  524. BigDecimal divAmount = ratio == -1 ? restAmount :
  525. totalAmount.multiply(BigDecimal.valueOf(ratio))
  526. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
  527. Map<String, Object> divMem = new HashMap<>();
  528. divMem.put("member_id", memberId);
  529. divMem.put("amount", divAmount.toPlainString());
  530. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  531. divMembers.add(divMem);
  532. return restAmount.subtract(divAmount);
  533. } else {
  534. throw new BusinessException("分账比例错误");
  535. }
  536. }
  537. public static BigDecimal divMoney(BigDecimal restAmount, List<Map<String, Object>> divMembers,
  538. String memberId, BigDecimal divAmount, boolean feeFlag) {
  539. if (divAmount.compareTo(BigDecimal.ZERO) > 0) {
  540. Map<String, Object> divMem = new HashMap<>();
  541. divMem.put("member_id", memberId);
  542. divMem.put("amount", divAmount.toPlainString());
  543. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  544. divMembers.add(divMem);
  545. }
  546. return restAmount.subtract(divAmount);
  547. }
  548. public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
  549. log.info("订单回调 orderId: {}, payMethod: {}, transactionId: {}", orderId, payMethod, transactionId);
  550. // 取消订单与订单回调不能同时进行,需要抢锁
  551. if (!getOrderLock(orderId)) {
  552. log.info("订单回调失败 orderId: {} redis锁定, 重新发送到队列", orderId);
  553. rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  554. new OrderNotifyEvent(orderId, payMethod, transactionId, System.currentTimeMillis()));
  555. return;
  556. }
  557. try {
  558. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  559. Collection collection = collectionRepo.findById(order.getCollectionId())
  560. .orElseThrow(new BusinessException("藏品不存在"));
  561. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  562. if (order.getStatus() == OrderStatus.NOT_PAID) {
  563. order.setStatus(OrderStatus.PROCESSING);
  564. order.setPayTime(LocalDateTime.now());
  565. order.setTransactionId(transactionId);
  566. order.setPayMethod(payMethod);
  567. if (order.getType() == CollectionType.BLIND_BOX) {
  568. log.info("开始盲盒抽卡 orderId: {}, collectionId: {}", orderId, collection.getId());
  569. BlindBoxItem winItem = null;
  570. try {
  571. winItem = collectionService.draw(collection.getId());
  572. } catch (BusinessException ignored) {
  573. }
  574. if (winItem == null) {
  575. log.info("抽卡失败退款 orderId: {}", orderId);
  576. order.setStatus(OrderStatus.CANCELLED);
  577. order.setCancelTime(LocalDateTime.now());
  578. Map<String, Object> refundParams = new HashMap<>();
  579. refundParams.put("refund_amt", order.getTotalPrice().setScale(2, RoundingMode.HALF_UP)
  580. .toPlainString());
  581. refundParams.put("refund_order_no", String.valueOf(snowflakeIdWorker.nextId()));
  582. try {
  583. Map<String, Object> response = Refund.create(transactionId, refundParams);
  584. } catch (BaseAdaPayException e) {
  585. e.printStackTrace();
  586. }
  587. orderRepo.save(order);
  588. throw new BusinessException("抽卡失败, 已退款 " + orderId);
  589. }
  590. log.info("抽卡成功 orderId: {}, collectionId: {}, winCollectionId: {}", orderId, collection
  591. .getId(), winItem.getCollectionId());
  592. order.setWinCollectionId(winItem.getCollectionId());
  593. orderRepo.save(order);
  594. //藏品其他信息/是否vip
  595. CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(order.getCollectionId());
  596. if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
  597. if (collectionPrivilege.isVip()) {
  598. //更新vip信息
  599. userRepo.updateVipPurchase(order.getUserId(), 1);
  600. }
  601. }
  602. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售",
  603. winItem.getTotal() > 1 ? collectionService.getNextNumber(winItem.getCollectionId()) : null,
  604. collection.getHoldDays());
  605. } else {
  606. if (collection.getSource() == CollectionSource.TRANSFER) {
  607. orderRepo.save(order);
  608. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  609. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  610. collectionRepo.delete(collection);
  611. // 如果展厅有此藏品
  612. showCollectionRepo.deleteAllByCollectionId(order.getCollectionId());
  613. // 发送短信提醒用户转让成功
  614. if (asset != null && asset.getUserId() != null) {
  615. smsService.sellOut(userRepo.findPhoneById(asset.getUserId()));
  616. }
  617. } else {
  618. orderRepo.save(order);
  619. //藏品其他信息/是否vip
  620. CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(order.getCollectionId());
  621. if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
  622. if (collectionPrivilege.isVip()) {
  623. //更新vip信息
  624. userRepo.updateVipPurchase(order.getUserId(), 1);
  625. }
  626. }
  627. Asset asset = assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售",
  628. collection.getTotal() > 1 ? collectionService
  629. .getNextNumber(order.getCollectionId()) : null);
  630. if (collection.getType() == CollectionType.SHOWROOM) {
  631. showroomService.save(asset);
  632. }
  633. }
  634. }
  635. commission(order);
  636. if (collection.getAssetId() == null) {
  637. collectionService.increaseSale(order.getCollectionId(), order.getQty());
  638. }
  639. } else {
  640. throw new BusinessException("状态错误 " + order.getStatus());
  641. }
  642. } catch (Exception e) {
  643. ErrorOrder errorOrder = ErrorOrder.builder()
  644. .orderId(orderId)
  645. .transactionId(transactionId)
  646. .payMethod(payMethod)
  647. .build();
  648. if (e instanceof BusinessException) {
  649. log.error("订单回调出错 orderId: {} {}", orderId, e.getMessage());
  650. } else {
  651. log.error("订单回调出错 orderId: " + orderId, e);
  652. }
  653. errorOrder.setErrorMessage(e.getMessage());
  654. errorOrderRepo.save(errorOrder);
  655. }
  656. releaseOrderLock(orderId);
  657. }
  658. @EventListener
  659. public void onCreateAsset(CreateAssetEvent event) {
  660. Asset asset = event.getAsset();
  661. if (asset.getOrderId() != null) {
  662. Order order = orderRepo.findById(asset.getOrderId()).orElse(null);
  663. if (event.isSuccess() && order != null) {
  664. order.setTxHash(asset.getTxHash());
  665. order.setGasUsed(asset.getGasUsed());
  666. order.setBlockNumber(asset.getBlockNumber());
  667. order.setStatus(OrderStatus.FINISH);
  668. orderRepo.save(order);
  669. }
  670. }
  671. }
  672. @EventListener
  673. public void onTransferAsset(TransferAssetEvent event) {
  674. Asset asset = event.getAsset();
  675. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  676. if (event.isSuccess()) {
  677. order.setTxHash(asset.getTxHash());
  678. order.setGasUsed(asset.getGasUsed());
  679. order.setBlockNumber(asset.getBlockNumber());
  680. order.setStatus(OrderStatus.FINISH);
  681. orderRepo.save(order);
  682. } else {
  683. log.error("创建asset失败");
  684. }
  685. }
  686. public void cancel(Long id) {
  687. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  688. cancel(order);
  689. }
  690. public void cancel(Order order) {
  691. // 取消订单与订单回调不能同时进行,需要抢锁
  692. if (!getOrderLock(order.getId())) {
  693. log.error("订单取消失败 {}, redis锁了", order.getId());
  694. return;
  695. }
  696. try {
  697. if (order.getStatus() != OrderStatus.NOT_PAID) {
  698. throw new BusinessException("已支付订单无法取消");
  699. }
  700. // 查询adapay支付记录,如果已经支付,则不能取消
  701. Set<Object> transactionIds = redisTemplate.opsForSet().members(RedisKeys.PAY_RECORD + order.getId());
  702. if (transactionIds != null && transactionIds.size() > 0) {
  703. AtomicInteger succeeded = new AtomicInteger();
  704. AtomicInteger pending = new AtomicInteger();
  705. transactionIds.parallelStream().forEach(s -> {
  706. String transactionIdStr = Optional.ofNullable(s).map(Object::toString).orElse("");
  707. String transactionId = null;
  708. String merchant = null;
  709. if (transactionIdStr.contains("#")) {
  710. String[] arr = transactionIdStr.split("#");
  711. merchant = arr[0];
  712. transactionId = arr[1];
  713. } else {
  714. merchant = Adapay.defaultMerchantKey;
  715. transactionId = transactionIdStr;
  716. }
  717. try {
  718. Map<String, Object> map = Payment.query(transactionId, merchant);
  719. if ("succeeded".equalsIgnoreCase(MapUtils.getString(map, "status"))) {
  720. succeeded.getAndIncrement();
  721. }
  722. if ("pending".equalsIgnoreCase(MapUtils.getString(map, "status"))) {
  723. pending.getAndIncrement();
  724. // 未支付的订单调用关单接口
  725. Map<String, Object> closeParams = new HashMap<>();
  726. closeParams.put("payment_id", transactionId);
  727. Payment.close(closeParams, merchant);
  728. }
  729. } catch (BaseAdaPayException e) {
  730. log.error("adapay error", e);
  731. }
  732. });
  733. // if (succeeded.get() + pending.get() > 0) {
  734. if (succeeded.get() > 0) {
  735. if (ChronoUnit.MINUTES.between(order.getCreatedAt(), LocalDateTime.now()) < 10) {
  736. throw new BusinessException("订单已经支付成功或待支付,不能取消 " + order.getId());
  737. }
  738. }
  739. }
  740. CollectionSource source = Optional.ofNullable(order.getSource()).orElseGet(() ->
  741. collectionRepo.findById(order.getCollectionId()).map(Collection::getSource).orElse(null));
  742. if (source == CollectionSource.TRANSFER) {
  743. Asset asset = assetRepo.findById(order.getAssetId()).orElse(null);
  744. if (asset != null) {
  745. log.info("set normal cancelOrder {}", order.getId());
  746. asset.setStatus(AssetStatus.NORMAL);
  747. assetRepo.save(asset);
  748. }
  749. collectionRepo.setOnShelf(order.getCollectionId(), true);
  750. }
  751. collectionService.increaseStock(order.getCollectionId(), order.getQty());
  752. order.setStatus(OrderStatus.CANCELLED);
  753. order.setCancelTime(LocalDateTime.now());
  754. orderRepo.save(order);
  755. if (order.getCouponId() != null) {
  756. userCouponRepo.findById(order.getCouponId()).ifPresent(coupon -> {
  757. coupon.setUsed(false);
  758. coupon.setUseTime(null);
  759. userCouponRepo.save(coupon);
  760. });
  761. }
  762. //加上积分
  763. if (ObjectUtils.isNotEmpty(order.getVipPoint()) && order.getVipPoint() > 0) {
  764. userRepo.updateVipPoint(order.getUserId(), order.getVipPoint());
  765. cacheService.clearUserMy(order.getUserId());
  766. log.info("取消加积分用户ID:{},订单ID:{},积分:{}", order.getUserId(), order.getId(), order.getVipPoint());
  767. }
  768. if (order.isVip()) {
  769. collectionService.decreaseQuota(order.getCollectionId(), 1);
  770. log.info("取消加藏品额度CollectionId:{}", order.getCollectionId());
  771. }
  772. rocketMQTemplate.syncSend(generalProperties.getUpdateQuotaTopic(), order.getCollectionId(), 10000);
  773. log.info("取消订单{}", order.getId());
  774. } catch (Exception e) {
  775. if (e instanceof BusinessException) {
  776. log.error(e.getMessage());
  777. } else {
  778. log.error("订单取消错误 orderId: " + order.getId(), e);
  779. }
  780. }
  781. releaseOrderLock(order.getId());
  782. }
  783. public void refundCancelled(Order order) {
  784. }
  785. public void setNumber() {
  786. for (Collection collection : collectionRepo.findAll()) {
  787. if (collection.getSource() != CollectionSource.OFFICIAL) continue;
  788. collection.setCurrentNumber(0);
  789. collectionRepo.save(collection);
  790. for (Asset asset : assetRepo.findByCollectionId(collection.getId())) {
  791. if (asset.getStatus() == AssetStatus.GIFTED || asset.getStatus() == AssetStatus.TRANSFERRED) {
  792. } else {
  793. asset.setNumber(collectionService.getNextNumber(collection.getId()));
  794. assetRepo.save(asset);
  795. }
  796. }
  797. }
  798. }
  799. public void setNumberRecursive(Asset asset) {
  800. }
  801. @Scheduled(cron = "0 0 4 * * ?")
  802. public void setSales() {
  803. if (generalProperties.isNotifyServer()) {
  804. return;
  805. }
  806. List<User> minters = userRepo.findByAuthoritiesContains(Authority.get(AuthorityName.ROLE_MINTER));
  807. for (User minter : minters) {
  808. userRepo.setSales(minter.getId(), (int) orderRepo.countSales(minter.getId()));
  809. }
  810. }
  811. public void commission(Order order) {
  812. if (order.getInvitor() != null) {
  813. userRepo.findById(order.getInvitor()).ifPresent(user -> {
  814. BigDecimal shareRatio = user.getShareRatio();
  815. if (StringUtils.isNotBlank(user.getSettleAccountId()) &&
  816. shareRatio != null && shareRatio.compareTo(BigDecimal.ZERO) > 0) {
  817. BigDecimal totalPrice = order.getTotalPrice().subtract(order.getGasPrice());
  818. commissionRecordRepo.save(CommissionRecord.builder()
  819. .orderId(order.getId())
  820. .collectionId(order.getCollectionId())
  821. .name(order.getName())
  822. .totalPrice(totalPrice)
  823. .nickname(user.getNickname())
  824. .userId(user.getId())
  825. .shareRatio(user.getShareRatio())
  826. .phone(user.getPhone())
  827. .shareAmount(totalPrice.multiply(shareRatio)
  828. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP))
  829. .build());
  830. }
  831. });
  832. }
  833. }
  834. public Object queryCreateOrder(String id) {
  835. Object res = redisTemplate.opsForValue().get(RedisKeys.CREATE_ORDER + id);
  836. if (res != null) {
  837. if (res instanceof Map) {
  838. if (MapUtils.getBooleanValue((Map) res, "success", false)) {
  839. Order order = (Order) MapUtils.getObject((Map) res, "data");
  840. if (!SecurityUtils.getAuthenticatedUser().getId().equals(order.getUserId())) {
  841. log.error("queryCreateOrder userId错误 requestUserId={} orderUserId={}",
  842. SecurityUtils.getAuthenticatedUser().getId(), order.getUserId());
  843. return null;
  844. }
  845. }
  846. }
  847. }
  848. return res;
  849. }
  850. // 获取订单锁,有效时间1小时
  851. public boolean getOrderLock(Long orderId) {
  852. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.ORDER_LOCK + orderId);
  853. Boolean flag = ops.setIfAbsent(1, 1, TimeUnit.HOURS);
  854. return Boolean.TRUE.equals(flag);
  855. }
  856. // 释放订单锁
  857. public void releaseOrderLock(Long orderId) {
  858. redisTemplate.delete(RedisKeys.ORDER_LOCK + orderId);
  859. }
  860. public void calcSettle(LocalDateTime start, LocalDateTime end, OutputStream outputStream) {
  861. List<Order> orders = orderRepo
  862. .findByCreatedAtBetweenAndSourceAndStatusIn(start, end, CollectionSource.TRANSFER, Arrays
  863. .asList(OrderStatus.PROCESSING, OrderStatus.FINISH));
  864. List<Asset> assets = assetRepo.findAllById(orders.stream().map(Order::getAssetId).collect(Collectors.toSet()));
  865. List<UserBankCard> bankCards = userBankCardRepo
  866. .findByUserIdIn(assets.stream().map(Asset::getUserId).collect(Collectors.toSet()));
  867. List<MarketSettlement> settlements = new ArrayList<>();
  868. for (Order order : orders) {
  869. BigDecimal amount = order.getTotalPrice()
  870. .subtract(order.getGasPrice())
  871. .multiply(new BigDecimal("100")
  872. .subtract(BigDecimal.valueOf(order.getServiceCharge()))
  873. .subtract(BigDecimal.valueOf(order.getRoyalties()))
  874. .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP))
  875. .setScale(2, RoundingMode.HALF_UP);
  876. Long userId = assets.stream().filter(a -> a.getId().equals(order.getAssetId())).map(Asset::getUserId)
  877. .findAny().orElse(null);
  878. if (userId != null) {
  879. UserBankCard userBankCard = bankCards.stream().filter(b -> b.getUserId().equals(userId)).findAny()
  880. .orElse(null);
  881. MarketSettlement marketSettlement = settlements.stream().filter(s -> s.getUserId().equals(userId))
  882. .findAny().orElse(null);
  883. if (marketSettlement == null) {
  884. marketSettlement = new MarketSettlement(userId,
  885. Optional.ofNullable(userBankCard).map(UserBankCard::getRealName).orElse(null),
  886. Optional.ofNullable(userBankCard).map(UserBankCard::getBankNo).orElse(null),
  887. amount);
  888. settlements.add(marketSettlement);
  889. } else {
  890. marketSettlement.setAmount(marketSettlement.getAmount()
  891. .add(amount));
  892. }
  893. }
  894. }
  895. EasyExcel.write(outputStream, MarketSettlement.class).sheet("sheet").doWrite(settlements);
  896. }
  897. @Scheduled(cron = "0 0/10 * * * ?")
  898. public void setBlackList() {
  899. List<Long> userIds = orderRepo
  900. .checkBlackList(LocalDate.now().atStartOfDay(), LocalDate.now().atTime(LocalTime.MAX));
  901. userIds.forEach(userId -> {
  902. redisTemplate.opsForValue().set(RedisKeys.BLACK_LIST + userId, 1, Duration.ofSeconds(60 * 120));
  903. });
  904. }
  905. public List<Order> addOrder(Long collectionId, List<Long> userIds, LocalDateTime time, boolean notify) {
  906. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  907. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("用户不存在"));
  908. int i = 0;
  909. List<Order> list = new ArrayList<>();
  910. for (Long userId : userIds) {
  911. time = time.plusSeconds(i++);
  912. BigDecimal gasFee = new BigDecimal("1");
  913. Order order = Order.builder()
  914. .id(snowflakeIdWorker.nextId())
  915. .userId(userId)
  916. .collectionId(collectionId)
  917. .name(collection.getName())
  918. .pic(collection.getPic())
  919. .detail(collection.getDetail())
  920. .properties(collection.getProperties())
  921. .category(collection.getCategory())
  922. .canResale(collection.isCanResale())
  923. .royalties(collection.getRoyalties())
  924. .serviceCharge(collection.getServiceCharge())
  925. .type(collection.getType())
  926. .source(collection.getSource())
  927. .minterId(collection.getMinterId())
  928. .minter(minter.getNickname())
  929. .minterAvatar(minter.getAvatar())
  930. .qty(1)
  931. .price(collection.getPrice())
  932. .gasPrice(gasFee)
  933. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(1)).add(gasFee))
  934. .status(notify ? OrderStatus.NOT_PAID : OrderStatus.FINISH)
  935. .assetId(collection.getAssetId())
  936. .countId(collection.getCountId())
  937. .build();
  938. orderRepo.saveAndFlush(order);
  939. String txHash = RandomStringUtils.randomAlphanumeric(64).toLowerCase(Locale.ROOT);
  940. String transactionId = DateTimeUtils.format(LocalDateTime.now(), "yyyyMMdd") +
  941. RandomStringUtils.randomNumeric(24);
  942. BigInteger gas = new BigInteger("157377");
  943. if (notify) {
  944. rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  945. new OrderNotifyEvent(order.getId(), PayMethod.ALIPAY, order.getTransactionId()
  946. , System.currentTimeMillis()));
  947. } else {
  948. order.setCreatedAt(ObjectUtils.clone(time));
  949. order.setPayTime(time.plusSeconds(RandomUtils.nextInt(5, 50)));
  950. order.setTransactionId(transactionId);
  951. order.setTxHash(txHash);
  952. order.setGasUsed(gas);
  953. order.setPayMethod(PayMethod.ALIPAY);
  954. order.setStatus(OrderStatus.FINISH);
  955. order.setModifiedAt(order.getPayTime());
  956. order.setModifiedBy("system");
  957. order.setCreatedBy("system");
  958. orderRepo.save(order);
  959. }
  960. list.add(order);
  961. }
  962. return list;
  963. }
  964. }