OrderService.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.fastjson.serializer.SerializerFeature;
  5. import com.alipay.api.AlipayClient;
  6. import com.alipay.api.request.AlipayTradeWapPayRequest;
  7. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  8. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  9. import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
  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.huifu.adapay.core.exception.BaseAdaPayException;
  15. import com.huifu.adapay.model.AdapayCommon;
  16. import com.huifu.adapay.model.Payment;
  17. import com.izouma.nineth.config.AdapayProperties;
  18. import com.izouma.nineth.config.AlipayProperties;
  19. import com.izouma.nineth.config.GeneralProperties;
  20. import com.izouma.nineth.config.WxPayProperties;
  21. import com.izouma.nineth.domain.Collection;
  22. import com.izouma.nineth.domain.*;
  23. import com.izouma.nineth.dto.PageQuery;
  24. import com.izouma.nineth.enums.*;
  25. import com.izouma.nineth.event.CreateAssetEvent;
  26. import com.izouma.nineth.event.CreateOrderEvent;
  27. import com.izouma.nineth.event.TransferAssetEvent;
  28. import com.izouma.nineth.exception.BusinessException;
  29. import com.izouma.nineth.repo.*;
  30. import com.izouma.nineth.security.Authority;
  31. import com.izouma.nineth.utils.JpaUtils;
  32. import com.izouma.nineth.utils.SnowflakeIdWorker;
  33. import lombok.AllArgsConstructor;
  34. import lombok.extern.slf4j.Slf4j;
  35. import org.apache.commons.codec.EncoderException;
  36. import org.apache.commons.codec.net.URLCodec;
  37. import org.apache.commons.collections.MapUtils;
  38. import org.apache.commons.lang3.StringUtils;
  39. import org.apache.rocketmq.client.producer.SendResult;
  40. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  41. import org.springframework.context.event.EventListener;
  42. import org.springframework.core.env.Environment;
  43. import org.springframework.data.domain.Page;
  44. import org.springframework.data.redis.core.RedisTemplate;
  45. import org.springframework.scheduling.annotation.Scheduled;
  46. import org.springframework.stereotype.Service;
  47. import org.springframework.ui.Model;
  48. import javax.transaction.Transactional;
  49. import java.math.BigDecimal;
  50. import java.math.RoundingMode;
  51. import java.time.LocalDateTime;
  52. import java.time.format.DateTimeFormatter;
  53. import java.util.*;
  54. @Service
  55. @AllArgsConstructor
  56. @Slf4j
  57. public class OrderService {
  58. private OrderRepo orderRepo;
  59. private CollectionRepo collectionRepo;
  60. private UserAddressRepo userAddressRepo;
  61. private UserRepo userRepo;
  62. private Environment env;
  63. private AlipayClient alipayClient;
  64. private AlipayProperties alipayProperties;
  65. private WxPayService wxPayService;
  66. private WxPayProperties wxPayProperties;
  67. private AssetService assetService;
  68. private SysConfigService sysConfigService;
  69. private BlindBoxItemRepo blindBoxItemRepo;
  70. private AssetRepo assetRepo;
  71. private UserCouponRepo userCouponRepo;
  72. private CollectionService collectionService;
  73. private CommissionRecordRepo commissionRecordRepo;
  74. private AdapayProperties adapayProperties;
  75. private GeneralProperties generalProperties;
  76. private RocketMQTemplate rocketMQTemplate;
  77. private RedisTemplate<String, Object> redisTemplate;
  78. private SnowflakeIdWorker snowflakeIdWorker;
  79. public Page<Order> all(PageQuery pageQuery) {
  80. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  81. }
  82. public String mqCreate(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor) {
  83. Long id = snowflakeIdWorker.nextId();
  84. SendResult result = rocketMQTemplate.syncSend(generalProperties.getCreateOrderTopic(),
  85. new CreateOrderEvent(id, userId, collectionId, qty, addressId, userCouponId, invitor), 100000);
  86. log.info("发送订单到队列: {}, result={}", id, result);
  87. return String.valueOf(id);
  88. }
  89. @Transactional
  90. public Order create(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor, Long id) {
  91. long t = System.currentTimeMillis();
  92. qty = 1;
  93. int stock = Optional.ofNullable(collectionService.decreaseStock(collectionId, qty))
  94. .map(Math::toIntExact)
  95. .orElseThrow(new BusinessException("很遗憾,藏品已售罄"));
  96. try {
  97. if (stock < 0) {
  98. throw new BusinessException("很遗憾,藏品已售罄");
  99. }
  100. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  101. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  102. UserCoupon coupon = null;
  103. if (userCouponId != null) {
  104. coupon = userCouponRepo.findById(userCouponId).orElseThrow(new BusinessException("兑换券不存在"));
  105. if (coupon.isUsed()) {
  106. throw new BusinessException("该兑换券已使用");
  107. }
  108. if (coupon.isLimited() && !coupon.getCollectionIds().contains(collectionId)) {
  109. throw new BusinessException("该兑换券不可用");
  110. }
  111. }
  112. if (collection.isScheduleSale()) {
  113. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  114. throw new BusinessException("当前还未开售");
  115. }
  116. }
  117. if (!collection.isOnShelf()) {
  118. if (!collection.isScanCode()) {
  119. throw new BusinessException("藏品已下架");
  120. }
  121. }
  122. if (!collection.isSalable()) {
  123. throw new BusinessException("该藏品当前不可购买");
  124. }
  125. if (collection.getMaxCount() > 0) {
  126. int count;
  127. if (StringUtils.isNotBlank(collection.getCountId())) {
  128. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(), Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  129. } else {
  130. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId, Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  131. }
  132. if (count >= collection.getMaxCount()) {
  133. throw new BusinessException("限购" + collection.getMaxCount() + "件");
  134. }
  135. }
  136. UserAddress userAddress = null;
  137. if (addressId != null) {
  138. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  139. }
  140. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  141. Order order = Order.builder()
  142. .id(Optional.ofNullable(id).orElse(snowflakeIdWorker.nextId()))
  143. .userId(userId)
  144. .collectionId(collectionId)
  145. .name(collection.getName())
  146. .pic(collection.getPic())
  147. .detail(collection.getDetail())
  148. .properties(collection.getProperties())
  149. .category(collection.getCategory())
  150. .canResale(collection.isCanResale())
  151. .royalties(collection.getRoyalties())
  152. .serviceCharge(collection.getServiceCharge())
  153. .type(collection.getType())
  154. .source(collection.getSource())
  155. .minterId(collection.getMinterId())
  156. .minter(minter.getNickname())
  157. .minterAvatar(minter.getAvatar())
  158. .qty(qty)
  159. .price(collection.getPrice())
  160. .gasPrice(gasFee)
  161. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  162. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  163. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  164. .address(Optional.ofNullable(userAddress).map(u ->
  165. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  166. .orElse(null))
  167. .status(OrderStatus.NOT_PAID)
  168. .assetId(collection.getAssetId())
  169. .couponId(userCouponId)
  170. .invitor(invitor)
  171. .countId(collection.getCountId())
  172. .build();
  173. if (coupon != null) {
  174. coupon.setUsed(true);
  175. coupon.setUseTime(LocalDateTime.now());
  176. if (coupon.isNeedGas()) {
  177. order.setTotalPrice(order.getGasPrice());
  178. } else {
  179. order.setTotalPrice(BigDecimal.ZERO);
  180. }
  181. }
  182. if (collection.getSource() == CollectionSource.TRANSFER) {
  183. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  184. asset.setStatus(AssetStatus.TRADING);
  185. assetRepo.save(asset);
  186. collectionRepo.setOnShelf(collectionId, false);
  187. }
  188. order = orderRepo.save(order);
  189. if (order.getTotalPrice().equals(BigDecimal.ZERO)) {
  190. notifyOrder(order.getId(), PayMethod.WEIXIN, null);
  191. }
  192. rocketMQTemplate.syncSend(generalProperties.getUpdateStockTopic(), collectionId, 10000);
  193. log.info("订单创建完成, id={}, {}ms", order.getId(), System.currentTimeMillis() - t);
  194. return order;
  195. } catch (Exception e) {
  196. collectionService.increaseStock(collectionId, qty);
  197. throw e;
  198. }
  199. }
  200. public void payOrderAlipay(Long id, Model model) {
  201. try {
  202. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  203. if (order.getStatus() != OrderStatus.NOT_PAID) {
  204. throw new BusinessException("订单状态错误");
  205. }
  206. JSONObject bizContent = new JSONObject();
  207. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  208. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  209. bizContent.put("out_trade_no", String.valueOf(snowflakeIdWorker.nextId()));
  210. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  211. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  212. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  213. // 测试环境设为1分
  214. bizContent.put("total_amount", "0.01");
  215. }
  216. bizContent.put("subject", order.getName());
  217. bizContent.put("product_code", "QUICK_WAP_PAY");
  218. JSONObject body = new JSONObject();
  219. body.put("action", "payOrder");
  220. body.put("userId", order.getUserId());
  221. body.put("orderId", order.getId());
  222. bizContent.put("body", body.toJSONString());
  223. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  224. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  225. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  226. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  227. String form = alipayClient.pageExecute(alipayRequest).getBody();
  228. model.addAttribute("form", form);
  229. } catch (BusinessException err) {
  230. model.addAttribute("errMsg", err.getError());
  231. } catch (Exception e) {
  232. model.addAttribute("errMsg", e.getMessage());
  233. }
  234. }
  235. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  236. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  237. if (order.getStatus() != OrderStatus.NOT_PAID) {
  238. throw new BusinessException("订单状态错误");
  239. }
  240. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  241. request.setBody(order.getName());
  242. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  243. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  244. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  245. // 测试环境设为1分
  246. // request.setTotalFee(1);
  247. }
  248. request.setSpbillCreateIp("180.102.110.170");
  249. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  250. request.setTradeType(tradeType);
  251. request.setOpenid(openId);
  252. request.setSignType("MD5");
  253. JSONObject body = new JSONObject();
  254. body.put("action", "payOrder");
  255. body.put("userId", order.getUserId());
  256. body.put("orderId", order.getId());
  257. request.setAttach(body.toJSONString());
  258. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  259. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  260. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  261. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  262. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  263. }
  264. throw new BusinessException("不支持此付款方式");
  265. }
  266. public Object payAdapay(Long id, String payChannel, String openId) throws BaseAdaPayException {
  267. List<String> aliChannels = Arrays.asList("alipay", "alipay_qr", "alipay_wap");
  268. List<String> wxChannels = Arrays.asList("wx_pub", "wx_lite");
  269. if (!aliChannels.contains(payChannel) && !wxChannels.contains(payChannel)) {
  270. throw new BusinessException("不支持此渠道");
  271. }
  272. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  273. Collection collection = collectionRepo.findById(order.getCollectionId())
  274. .orElseThrow(new BusinessException("藏品不存在"));
  275. User invitor = null;
  276. if (order.getInvitor() != null) {
  277. invitor = userRepo.findById(order.getInvitor()).orElse(null);
  278. }
  279. if (invitor != null && StringUtils.isBlank(invitor.getSettleAccountId())) {
  280. invitor = null;
  281. }
  282. if (order.getStatus() != OrderStatus.NOT_PAID) {
  283. throw new BusinessException("订单状态错误");
  284. }
  285. Map<String, Object> paymentParams = new HashMap<>();
  286. paymentParams.put("order_no", String.valueOf(snowflakeIdWorker.nextId()));
  287. paymentParams.put("pay_amt", order.getTotalPrice().setScale(2, RoundingMode.HALF_UP).toPlainString());
  288. paymentParams.put("app_id", adapayProperties.getAppId());
  289. paymentParams.put("pay_channel", payChannel);
  290. paymentParams.put("goods_title", collection.getName());
  291. paymentParams.put("goods_desc", collection.getName());
  292. paymentParams.put("time_expire", DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
  293. .format(LocalDateTime.now().plusMinutes(3)));
  294. paymentParams.put("notify_url", adapayProperties.getNotifyUrl() + "/order/" + order.getId());
  295. List<Map<String, Object>> divMembers = new ArrayList<>();
  296. BigDecimal totalAmount = order.getTotalPrice().subtract(order.getGasPrice());
  297. BigDecimal restAmount = order.getTotalPrice().multiply(BigDecimal.valueOf(1));
  298. if (collection.getSource().equals(CollectionSource.TRANSFER)) {
  299. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("无记录"));
  300. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("拥有者用户不存在"));
  301. if (collection.getServiceCharge() + collection.getRoyalties() > 0) {
  302. restAmount = divMoney(totalAmount, restAmount, divMembers, "0",
  303. collection.getServiceCharge() + collection.getRoyalties(), true);
  304. }
  305. restAmount = divMoney(restAmount, divMembers, owner.getMemberId(), restAmount, false);
  306. } else {
  307. if (invitor != null && invitor.getShareRatio() != null
  308. && invitor.getShareRatio().compareTo(BigDecimal.ZERO) > 0) {
  309. restAmount = divMoney(totalAmount, restAmount, divMembers, invitor.getMemberId(),
  310. invitor.getShareRatio().intValue(), false);
  311. }
  312. restAmount = divMoney(restAmount, divMembers, "0", restAmount, true);
  313. }
  314. if (restAmount.compareTo(BigDecimal.ZERO) != 0) {
  315. log.error("分账出错 {}", JSON.toJSONString(divMembers, SerializerFeature.PrettyFormat));
  316. throw new BusinessException("分账出错");
  317. }
  318. if (divMembers.size() > 1) {
  319. paymentParams.put("div_members", divMembers);
  320. }
  321. Map<String, Object> expend = new HashMap<>();
  322. paymentParams.put("expend", expend);
  323. if ("wx_pub".equals(payChannel)) {
  324. if (StringUtils.isBlank(openId)) {
  325. throw new BusinessException("缺少openId");
  326. }
  327. expend.put("open_id", openId);
  328. expend.put("limit_pay", "1");
  329. }
  330. Map<String, Object> response;
  331. if ("wx_lite".equals(payChannel)) {
  332. paymentParams.put("adapay_func_code", "wxpay.createOrder");
  333. paymentParams.put("callback_url", generalProperties.getHost() + "/9th/orders");
  334. response = AdapayCommon.requestAdapayUits(paymentParams);
  335. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  336. } else {
  337. response = Payment.create(paymentParams);
  338. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  339. AdapayService.checkSuccess(response);
  340. }
  341. switch (payChannel) {
  342. case "alipay_wap":
  343. case "alipay":
  344. return MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info");
  345. case "alipay_qr":
  346. return MapUtils.getString(MapUtils.getMap(response, "expend"), "qrcode_url");
  347. case "wx_pub":
  348. JSONObject payParams = JSON.parseObject(MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info"));
  349. payParams.put("timestamp", payParams.get("timeStamp"));
  350. payParams.remove("timeStamp");
  351. return payParams;
  352. default:
  353. return MapUtils.getMap(response, "expend");
  354. }
  355. }
  356. public static BigDecimal divMoney(BigDecimal totalAmount, BigDecimal restAmount, List<Map<String, Object>> divMembers,
  357. String memberId, int ratio, boolean feeFlag) {
  358. if (ratio == -1 || (ratio > 0 && ratio < 100)) {
  359. BigDecimal divAmount = ratio == -1 ? restAmount :
  360. totalAmount.multiply(BigDecimal.valueOf(ratio))
  361. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
  362. Map<String, Object> divMem = new HashMap<>();
  363. divMem.put("member_id", memberId);
  364. divMem.put("amount", divAmount.toPlainString());
  365. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  366. divMembers.add(divMem);
  367. return restAmount.subtract(divAmount);
  368. } else {
  369. throw new BusinessException("分账比例错误");
  370. }
  371. }
  372. public static BigDecimal divMoney(BigDecimal restAmount, List<Map<String, Object>> divMembers,
  373. String memberId, BigDecimal divAmount, boolean feeFlag) {
  374. if (divAmount.compareTo(BigDecimal.ZERO) > 0) {
  375. Map<String, Object> divMem = new HashMap<>();
  376. divMem.put("member_id", memberId);
  377. divMem.put("amount", divAmount.toPlainString());
  378. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  379. divMembers.add(divMem);
  380. }
  381. return restAmount.subtract(divAmount);
  382. }
  383. @Transactional
  384. public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
  385. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  386. Collection collection = collectionRepo.findById(order.getCollectionId())
  387. .orElseThrow(new BusinessException("藏品不存在"));
  388. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  389. if (order.getStatus() == OrderStatus.NOT_PAID) {
  390. order.setStatus(OrderStatus.PROCESSING);
  391. order.setPayTime(LocalDateTime.now());
  392. order.setTransactionId(transactionId);
  393. order.setPayMethod(payMethod);
  394. if (order.getType() == CollectionType.BLIND_BOX) {
  395. BlindBoxItem winItem = collectionService.draw(collection.getId());
  396. order.setWinCollectionId(winItem.getCollectionId());
  397. orderRepo.save(order);
  398. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售",
  399. winItem.getTotal() > 1 ? collectionService.getNextNumber(winItem.getCollectionId()) : null);
  400. } else {
  401. if (collection.getSource() == CollectionSource.TRANSFER) {
  402. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  403. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  404. collectionRepo.delete(collection);
  405. } else {
  406. orderRepo.save(order);
  407. assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售",
  408. collection.getTotal() > 1 ? collectionService.getNextNumber(order.getCollectionId()) : null);
  409. }
  410. }
  411. commission(order);
  412. collectionService.increaseSale(order.getCollectionId(), order.getQty());
  413. } else if (order.getStatus() == OrderStatus.CANCELLED) {
  414. }
  415. }
  416. @EventListener
  417. public void onCreateAsset(CreateAssetEvent event) {
  418. Asset asset = event.getAsset();
  419. if (asset.getOrderId() != null) {
  420. Order order = orderRepo.findById(asset.getOrderId()).orElse(null);
  421. if (event.isSuccess() && order != null) {
  422. order.setTxHash(asset.getTxHash());
  423. order.setGasUsed(asset.getGasUsed());
  424. order.setBlockNumber(asset.getBlockNumber());
  425. order.setStatus(OrderStatus.FINISH);
  426. orderRepo.save(order);
  427. }
  428. }
  429. }
  430. @EventListener
  431. public void onTransferAsset(TransferAssetEvent event) {
  432. Asset asset = event.getAsset();
  433. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  434. if (event.isSuccess()) {
  435. order.setTxHash(asset.getTxHash());
  436. order.setGasUsed(asset.getGasUsed());
  437. order.setBlockNumber(asset.getBlockNumber());
  438. order.setStatus(OrderStatus.FINISH);
  439. orderRepo.save(order);
  440. } else {
  441. log.error("创建asset失败");
  442. }
  443. }
  444. public void cancel(Long id) {
  445. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  446. cancel(order);
  447. }
  448. public void cancel(Order order) {
  449. if (order.getStatus() != OrderStatus.NOT_PAID) {
  450. throw new BusinessException("已支付订单无法取消");
  451. }
  452. CollectionSource source = Optional.ofNullable(order.getSource()).orElseGet(() ->
  453. collectionRepo.findById(order.getCollectionId()).map(Collection::getSource).orElse(null));
  454. if (source == CollectionSource.TRANSFER) {
  455. Asset asset = assetRepo.findById(order.getAssetId()).orElse(null);
  456. if (asset != null) {
  457. asset.setStatus(AssetStatus.NORMAL);
  458. assetRepo.save(asset);
  459. }
  460. collectionRepo.setOnShelf(order.getCollectionId(), true);
  461. }
  462. collectionService.increaseStock(order.getCollectionId(), order.getQty());
  463. order.setStatus(OrderStatus.CANCELLED);
  464. order.setCancelTime(LocalDateTime.now());
  465. orderRepo.save(order);
  466. if (order.getCouponId() != null) {
  467. userCouponRepo.findById(order.getCouponId()).ifPresent(coupon -> {
  468. coupon.setUsed(false);
  469. coupon.setUseTime(null);
  470. userCouponRepo.save(coupon);
  471. });
  472. }
  473. rocketMQTemplate.syncSend(generalProperties.getUpdateStockTopic(), order.getCollectionId(), 10000);
  474. log.info("取消订单{}", order.getId());
  475. }
  476. @Scheduled(fixedRate = 30000)
  477. public void batchCancel() {
  478. if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
  479. return;
  480. }
  481. List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  482. LocalDateTime.now().minusSeconds(210));
  483. orders.parallelStream().forEach(o -> {
  484. try {
  485. cancel(o);
  486. } catch (Exception ignored) {
  487. }
  488. });
  489. }
  490. public void refundCancelled(Order order) {
  491. }
  492. public void setNumber() {
  493. for (Collection collection : collectionRepo.findAll()) {
  494. if (collection.getSource() != CollectionSource.OFFICIAL) continue;
  495. collection.setCurrentNumber(0);
  496. collectionRepo.save(collection);
  497. for (Asset asset : assetRepo.findByCollectionId(collection.getId())) {
  498. if (asset.getStatus() == AssetStatus.GIFTED || asset.getStatus() == AssetStatus.TRANSFERRED) {
  499. } else {
  500. asset.setNumber(collectionService.getNextNumber(collection.getId()));
  501. assetRepo.save(asset);
  502. }
  503. }
  504. }
  505. }
  506. public void setNumberRecursive(Asset asset) {
  507. }
  508. @Scheduled(fixedRate = 120000)
  509. public void setSales() {
  510. List<User> minters = userRepo.findByAuthoritiesContains(Authority.get(AuthorityName.ROLE_MINTER));
  511. for (User minter : minters) {
  512. userRepo.setSales(minter.getId(), (int) orderRepo.countSales(minter.getId()));
  513. }
  514. }
  515. public void commission(Order order) {
  516. if (order.getInvitor() != null) {
  517. userRepo.findById(order.getInvitor()).ifPresent(user -> {
  518. BigDecimal shareRatio = user.getShareRatio();
  519. if (StringUtils.isNotBlank(user.getSettleAccountId()) &&
  520. shareRatio != null && shareRatio.compareTo(BigDecimal.ZERO) > 0) {
  521. BigDecimal totalPrice = order.getTotalPrice().subtract(order.getGasPrice());
  522. commissionRecordRepo.save(CommissionRecord.builder()
  523. .orderId(order.getId())
  524. .totalPrice(totalPrice)
  525. .nickname(user.getNickname())
  526. .userId(user.getId())
  527. .shareRatio(user.getShareRatio())
  528. .phone(user.getPhone())
  529. .shareAmount(totalPrice.multiply(shareRatio)
  530. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP))
  531. .build());
  532. }
  533. });
  534. }
  535. }
  536. public void refund(Long id) throws WxPayException {
  537. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  538. if (order.getStatus() != OrderStatus.FINISH) {
  539. throw new BusinessException("订单未付款");
  540. }
  541. WxPayRefundRequest request = new WxPayRefundRequest();
  542. request.setTransactionId(order.getTransactionId());
  543. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  544. request.setRefundFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  545. request.setOutRefundNo(String.valueOf(snowflakeIdWorker.nextId()));
  546. wxPayService.refund(request);
  547. }
  548. public Object queryCreateOrder(String id) {
  549. return redisTemplate.opsForValue().get("createOrder::" + id);
  550. }
  551. }