OrderService.java 30 KB

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