OrderService.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alipay.api.AlipayClient;
  5. import com.alipay.api.request.AlipayTradeWapPayRequest;
  6. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  7. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  8. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
  9. import com.github.binarywang.wxpay.constant.WxPayConstants;
  10. import com.github.binarywang.wxpay.exception.WxPayException;
  11. import com.github.binarywang.wxpay.service.WxPayService;
  12. import com.izouma.nineth.config.AlipayProperties;
  13. import com.izouma.nineth.config.WxPayProperties;
  14. import com.izouma.nineth.domain.Collection;
  15. import com.izouma.nineth.domain.*;
  16. import com.izouma.nineth.dto.PageQuery;
  17. import com.izouma.nineth.enums.*;
  18. import com.izouma.nineth.event.CreateAssetEvent;
  19. import com.izouma.nineth.event.TransferAssetEvent;
  20. import com.izouma.nineth.exception.BusinessException;
  21. import com.izouma.nineth.repo.*;
  22. import com.izouma.nineth.utils.JpaUtils;
  23. import com.izouma.nineth.utils.SnowflakeIdWorker;
  24. import lombok.AllArgsConstructor;
  25. import lombok.extern.slf4j.Slf4j;
  26. import org.apache.commons.codec.EncoderException;
  27. import org.apache.commons.codec.net.URLCodec;
  28. import org.apache.commons.lang3.RandomUtils;
  29. import org.apache.commons.lang3.Range;
  30. import org.springframework.context.event.EventListener;
  31. import org.springframework.core.env.Environment;
  32. import org.springframework.data.domain.Page;
  33. import org.springframework.scheduling.annotation.Scheduled;
  34. import org.springframework.stereotype.Service;
  35. import org.springframework.ui.Model;
  36. import javax.transaction.Transactional;
  37. import java.math.BigDecimal;
  38. import java.time.LocalDateTime;
  39. import java.util.*;
  40. @Service
  41. @AllArgsConstructor
  42. @Slf4j
  43. public class OrderService {
  44. private OrderRepo orderRepo;
  45. private CollectionRepo collectionRepo;
  46. private UserAddressRepo userAddressRepo;
  47. private UserRepo userRepo;
  48. private Environment env;
  49. private AlipayClient alipayClient;
  50. private AlipayProperties alipayProperties;
  51. private WxPayService wxPayService;
  52. private WxPayProperties wxPayProperties;
  53. private AssetService assetService;
  54. private SysConfigService sysConfigService;
  55. private BlindBoxItemRepo blindBoxItemRepo;
  56. private AssetRepo assetRepo;
  57. private UserCouponRepo userCouponRepo;
  58. private CollectionService collectionService;
  59. public Page<Order> all(PageQuery pageQuery) {
  60. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  61. }
  62. @Transactional
  63. public Order create(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId) {
  64. if (qty <= 0) throw new BusinessException("数量必须大于0");
  65. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  66. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  67. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  68. UserCoupon coupon = null;
  69. if (userCouponId != null) {
  70. coupon = userCouponRepo.findById(userCouponId).orElseThrow(new BusinessException("兑换券不存在"));
  71. if (coupon.isUsed()) {
  72. throw new BusinessException("该兑换券已使用");
  73. }
  74. if (coupon.isLimited() && !coupon.getCollectionIds().contains(collectionId)) {
  75. throw new BusinessException("该兑换券不可用");
  76. }
  77. }
  78. if (!collection.isOnShelf()) {
  79. throw new BusinessException("藏品已下架");
  80. }
  81. if (qty > collection.getStock()) {
  82. throw new BusinessException("库存不足");
  83. }
  84. if (!collection.isSalable()) {
  85. throw new BusinessException("该藏品当前不可购买");
  86. }
  87. if (collection.getType() == CollectionType.BLIND_BOX) {
  88. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  89. throw new BusinessException("盲盒未开售");
  90. }
  91. }
  92. UserAddress userAddress = null;
  93. if (addressId != null) {
  94. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  95. }
  96. collection.setStock(collection.getStock() - qty);
  97. collection.setSale(collection.getSale() + qty);
  98. collectionRepo.save(collection);
  99. minter.setSales(minter.getSales() + 1);
  100. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  101. Order order = Order.builder()
  102. .userId(userId)
  103. .collectionId(collectionId)
  104. .name(collection.getName())
  105. .pic(collection.getPic())
  106. .detail(collection.getDetail())
  107. .properties(collection.getProperties())
  108. .category(collection.getCategory())
  109. .canResale(collection.isCanResale())
  110. .royalties(collection.getRoyalties())
  111. .serviceCharge(collection.getServiceCharge())
  112. .type(collection.getType())
  113. .minterId(collection.getMinterId())
  114. .minter(minter.getNickname())
  115. .minterAvatar(minter.getAvatar())
  116. .qty(qty)
  117. .price(collection.getPrice())
  118. .gasPrice(gasFee)
  119. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  120. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  121. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  122. .address(Optional.ofNullable(userAddress).map(u ->
  123. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  124. .orElse(null))
  125. .status(OrderStatus.NOT_PAID)
  126. .assetId(collection.getAssetId())
  127. .couponId(userCouponId)
  128. .build();
  129. if (coupon != null) {
  130. coupon.setUsed(true);
  131. coupon.setUseTime(LocalDateTime.now());
  132. if (coupon.isNeedGas()) {
  133. order.setTotalPrice(order.getGasPrice());
  134. } else {
  135. order.setTotalPrice(BigDecimal.ZERO);
  136. }
  137. }
  138. if (collection.getSource() == CollectionSource.TRANSFER) {
  139. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  140. asset.setStatus(AssetStatus.TRADING);
  141. assetRepo.save(asset);
  142. collection.setOnShelf(false);
  143. collectionRepo.save(collection);
  144. }
  145. order = orderRepo.save(order);
  146. if (order.getTotalPrice().equals(BigDecimal.ZERO)) {
  147. notifyOrder(order.getId(), PayMethod.WEIXIN, null);
  148. }
  149. return order;
  150. }
  151. public void payOrderAlipay(Long id, Model model) {
  152. try {
  153. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  154. if (order.getStatus() != OrderStatus.NOT_PAID) {
  155. throw new BusinessException("订单状态错误");
  156. }
  157. JSONObject bizContent = new JSONObject();
  158. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  159. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  160. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  161. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  162. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  163. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  164. // 测试环境设为1分
  165. bizContent.put("total_amount", "0.01");
  166. }
  167. bizContent.put("subject", order.getName());
  168. bizContent.put("product_code", "QUICK_WAP_PAY");
  169. JSONObject body = new JSONObject();
  170. body.put("action", "payOrder");
  171. body.put("userId", order.getUserId());
  172. body.put("orderId", order.getId());
  173. bizContent.put("body", body.toJSONString());
  174. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  175. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  176. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  177. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  178. String form = alipayClient.pageExecute(alipayRequest).getBody();
  179. model.addAttribute("form", form);
  180. } catch (BusinessException err) {
  181. model.addAttribute("errMsg", err.getError());
  182. } catch (Exception e) {
  183. model.addAttribute("errMsg", e.getMessage());
  184. }
  185. }
  186. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  187. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  188. if (order.getStatus() != OrderStatus.NOT_PAID) {
  189. throw new BusinessException("订单状态错误");
  190. }
  191. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  192. request.setBody(order.getName());
  193. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  194. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  195. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  196. // 测试环境设为1分
  197. // request.setTotalFee(1);
  198. }
  199. request.setSpbillCreateIp("180.102.110.170");
  200. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  201. request.setTradeType(tradeType);
  202. request.setOpenid(openId);
  203. request.setSignType("MD5");
  204. JSONObject body = new JSONObject();
  205. body.put("action", "payOrder");
  206. body.put("userId", order.getUserId());
  207. body.put("orderId", order.getId());
  208. request.setAttach(body.toJSONString());
  209. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  210. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  211. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  212. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  213. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  214. }
  215. throw new BusinessException("不支持此付款方式");
  216. }
  217. public void notifyOrder1(Long orderId, PayMethod payMethod, String transactionId) {
  218. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  219. Collection collection = collectionRepo.findById(order.getCollectionId())
  220. .orElseThrow(new BusinessException("藏品不存在"));
  221. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  222. if (order.getStatus() == OrderStatus.NOT_PAID) {
  223. if (order.getType() == CollectionType.BLIND_BOX) {
  224. List<BlindBoxItem> items = blindBoxItemRepo.findByBlindBoxId(order.getCollectionId());
  225. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  226. int c = 0, sum = 0;
  227. for (BlindBoxItem item : items) {
  228. randomRange.put(item, Range.between(c, c + item.getStock()));
  229. c += item.getStock();
  230. sum += item.getStock();
  231. }
  232. int retry = 0;
  233. BlindBoxItem winItem = null;
  234. while (winItem == null) {
  235. retry++;
  236. int rand = RandomUtils.nextInt(0, sum + 1);
  237. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  238. BlindBoxItem item = entry.getKey();
  239. Range<Integer> range = entry.getValue();
  240. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  241. int total = items.stream().filter(i -> !i.isRare())
  242. .mapToInt(BlindBoxItem::getTotal).sum();
  243. int stock = items.stream().filter(i -> !i.isRare())
  244. .mapToInt(BlindBoxItem::getStock).sum();
  245. if (item.isRare()) {
  246. double nRate = stock / (double) total;
  247. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  248. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  249. if (!(nRate > 0.1 && item.getStock() == 1)) {
  250. winItem = item;
  251. }
  252. }
  253. } else {
  254. double nRate = (stock - 1) / (double) total;
  255. double rRate = item.getStock() / (double) item.getTotal();
  256. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  257. winItem = item;
  258. }
  259. }
  260. }
  261. }
  262. if (retry > 100 && winItem == null) {
  263. throw new BusinessException("盲盒抽卡失败");
  264. }
  265. }
  266. winItem.setStock(winItem.getStock() - 1);
  267. winItem.setSale(winItem.getSale() + 1);
  268. order.setStatus(OrderStatus.PROCESSING);
  269. order.setPayTime(LocalDateTime.now());
  270. order.setTransactionId(transactionId);
  271. order.setPayMethod(payMethod);
  272. orderRepo.save(order);
  273. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售");
  274. } else {
  275. if (collection.getSource() == CollectionSource.TRANSFER) {
  276. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  277. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  278. collectionRepo.delete(collection);
  279. } else {
  280. order.setStatus(OrderStatus.PROCESSING);
  281. order.setPayTime(LocalDateTime.now());
  282. order.setTransactionId(transactionId);
  283. order.setPayMethod(payMethod);
  284. orderRepo.save(order);
  285. assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售");
  286. }
  287. }
  288. } else if (order.getStatus() == OrderStatus.CANCELLED) {
  289. }
  290. }
  291. @Transactional
  292. public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
  293. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  294. Collection collection = collectionRepo.findById(order.getCollectionId())
  295. .orElseThrow(new BusinessException("藏品不存在"));
  296. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  297. if (order.getStatus() == OrderStatus.NOT_PAID) {
  298. order.setStatus(OrderStatus.PROCESSING);
  299. order.setPayTime(LocalDateTime.now());
  300. order.setTransactionId(transactionId);
  301. order.setPayMethod(payMethod);
  302. if (order.getType() == CollectionType.BLIND_BOX) {
  303. BlindBoxItem winItem = collectionService.draw(collection.getId());
  304. orderRepo.save(order);
  305. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售");
  306. } else {
  307. if (collection.getSource() == CollectionSource.TRANSFER) {
  308. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  309. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  310. collectionRepo.delete(collection);
  311. } else {
  312. orderRepo.save(order);
  313. assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售");
  314. }
  315. }
  316. } else if (order.getStatus() == OrderStatus.CANCELLED) {
  317. }
  318. }
  319. @EventListener
  320. public void onCreateAsset(CreateAssetEvent event) {
  321. Asset asset = event.getAsset();
  322. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  323. if (event.isSuccess()) {
  324. order.setTxHash(asset.getTxHash());
  325. order.setGasUsed(asset.getGasUsed());
  326. order.setBlockNumber(asset.getBlockNumber());
  327. order.setStatus(OrderStatus.FINISH);
  328. orderRepo.save(order);
  329. } else {
  330. log.error("创建asset失败");
  331. }
  332. }
  333. @EventListener
  334. public void onTransferAsset(TransferAssetEvent event) {
  335. Asset asset = event.getAsset();
  336. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  337. if (event.isSuccess()) {
  338. order.setTxHash(asset.getTxHash());
  339. order.setGasUsed(asset.getGasUsed());
  340. order.setBlockNumber(asset.getBlockNumber());
  341. order.setStatus(OrderStatus.FINISH);
  342. orderRepo.save(order);
  343. } else {
  344. log.error("创建asset失败");
  345. }
  346. }
  347. public void cancel(Long id) {
  348. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  349. cancel(order);
  350. }
  351. public void cancel(Order order) {
  352. if (order.getStatus() != OrderStatus.NOT_PAID) {
  353. throw new BusinessException("已支付订单无法取消");
  354. }
  355. Collection collection = collectionRepo.findById(order.getCollectionId())
  356. .orElseThrow(new BusinessException("藏品不存在"));
  357. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  358. if (collection.getSource() == CollectionSource.TRANSFER) {
  359. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  360. if (asset != null) {
  361. asset.setStatus(AssetStatus.NORMAL);
  362. }
  363. collection.setOnShelf(true);
  364. }
  365. collection.setSale(collection.getSale() - 1);
  366. collection.setStock(collection.getStock() + 1);
  367. collectionRepo.save(collection);
  368. minter.setSales(minter.getSales() - 1);
  369. userRepo.save(minter);
  370. order.setStatus(OrderStatus.CANCELLED);
  371. order.setCancelTime(LocalDateTime.now());
  372. orderRepo.save(order);
  373. if (order.getCouponId() != null) {
  374. userCouponRepo.findById(order.getCouponId()).ifPresent(coupon -> {
  375. coupon.setUsed(false);
  376. coupon.setUseTime(null);
  377. userCouponRepo.save(coupon);
  378. });
  379. }
  380. }
  381. @Scheduled(fixedRate = 60000)
  382. public void batchCancel() {
  383. List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  384. LocalDateTime.now().minusMinutes(5));
  385. orders.forEach(this::cancel);
  386. }
  387. public void refundCancelled(Order order) {
  388. }
  389. }