OrderService.java 19 KB

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