OrderService.java 27 KB

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