OrderService.java 19 KB

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