OrderService.java 27 KB

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