OrderService.java 25 KB

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