OrderService.java 27 KB

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