OrderService.java 17 KB

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