OrderService.java 19 KB

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