OrderService.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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) {
  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. .build();
  130. if (coupon != null) {
  131. coupon.setUsed(true);
  132. coupon.setUseTime(LocalDateTime.now());
  133. if (coupon.isNeedGas()) {
  134. order.setTotalPrice(order.getGasPrice());
  135. } else {
  136. order.setTotalPrice(BigDecimal.ZERO);
  137. }
  138. }
  139. if (collection.getSource() == CollectionSource.TRANSFER) {
  140. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  141. asset.setStatus(AssetStatus.TRADING);
  142. assetRepo.save(asset);
  143. collection.setOnShelf(false);
  144. collectionRepo.save(collection);
  145. }
  146. order = orderRepo.save(order);
  147. if (order.getTotalPrice().equals(BigDecimal.ZERO)) {
  148. notifyOrder(order.getId(), PayMethod.WEIXIN, null);
  149. }
  150. return order;
  151. }
  152. public void payOrderAlipay(Long id, Model model) {
  153. try {
  154. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  155. if (order.getStatus() != OrderStatus.NOT_PAID) {
  156. throw new BusinessException("订单状态错误");
  157. }
  158. JSONObject bizContent = new JSONObject();
  159. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  160. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  161. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  162. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  163. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  164. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  165. // 测试环境设为1分
  166. bizContent.put("total_amount", "0.01");
  167. }
  168. bizContent.put("subject", order.getName());
  169. bizContent.put("product_code", "QUICK_WAP_PAY");
  170. JSONObject body = new JSONObject();
  171. body.put("action", "payOrder");
  172. body.put("userId", order.getUserId());
  173. body.put("orderId", order.getId());
  174. bizContent.put("body", body.toJSONString());
  175. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  176. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  177. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  178. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  179. String form = alipayClient.pageExecute(alipayRequest).getBody();
  180. model.addAttribute("form", form);
  181. } catch (BusinessException err) {
  182. model.addAttribute("errMsg", err.getError());
  183. } catch (Exception e) {
  184. model.addAttribute("errMsg", e.getMessage());
  185. }
  186. }
  187. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  188. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  189. if (order.getStatus() != OrderStatus.NOT_PAID) {
  190. throw new BusinessException("订单状态错误");
  191. }
  192. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  193. request.setBody(order.getName());
  194. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  195. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  196. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  197. // 测试环境设为1分
  198. // request.setTotalFee(1);
  199. }
  200. request.setSpbillCreateIp("180.102.110.170");
  201. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  202. request.setTradeType(tradeType);
  203. request.setOpenid(openId);
  204. request.setSignType("MD5");
  205. JSONObject body = new JSONObject();
  206. body.put("action", "payOrder");
  207. body.put("userId", order.getUserId());
  208. body.put("orderId", order.getId());
  209. request.setAttach(body.toJSONString());
  210. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  211. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  212. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  213. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  214. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  215. }
  216. throw new BusinessException("不支持此付款方式");
  217. }
  218. @Transactional
  219. public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
  220. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  221. Collection collection = collectionRepo.findById(order.getCollectionId())
  222. .orElseThrow(new BusinessException("藏品不存在"));
  223. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  224. if (order.getStatus() == OrderStatus.NOT_PAID) {
  225. order.setStatus(OrderStatus.PROCESSING);
  226. order.setPayTime(LocalDateTime.now());
  227. order.setTransactionId(transactionId);
  228. order.setPayMethod(payMethod);
  229. if (order.getType() == CollectionType.BLIND_BOX) {
  230. BlindBoxItem winItem = collectionService.draw(collection.getId());
  231. order.setWinCollectionId(winItem.getCollectionId());
  232. orderRepo.save(order);
  233. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售",
  234. collectionService.getNextNumber(winItem.getCollectionId()));
  235. addSales(winItem.getMinterId());
  236. } else {
  237. if (collection.getSource() == CollectionSource.TRANSFER) {
  238. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  239. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  240. collectionRepo.delete(collection);
  241. } else {
  242. orderRepo.save(order);
  243. assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售",
  244. collectionService.getNextNumber(order.getCollectionId()));
  245. }
  246. addSales(collection.getMinterId());
  247. }
  248. } else if (order.getStatus() == OrderStatus.CANCELLED) {
  249. }
  250. }
  251. @EventListener
  252. public void onCreateAsset(CreateAssetEvent event) {
  253. Asset asset = event.getAsset();
  254. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  255. if (event.isSuccess()) {
  256. order.setTxHash(asset.getTxHash());
  257. order.setGasUsed(asset.getGasUsed());
  258. order.setBlockNumber(asset.getBlockNumber());
  259. order.setStatus(OrderStatus.FINISH);
  260. orderRepo.save(order);
  261. } else {
  262. log.error("创建asset失败");
  263. }
  264. }
  265. @EventListener
  266. public void onTransferAsset(TransferAssetEvent event) {
  267. Asset asset = event.getAsset();
  268. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  269. if (event.isSuccess()) {
  270. order.setTxHash(asset.getTxHash());
  271. order.setGasUsed(asset.getGasUsed());
  272. order.setBlockNumber(asset.getBlockNumber());
  273. order.setStatus(OrderStatus.FINISH);
  274. orderRepo.save(order);
  275. } else {
  276. log.error("创建asset失败");
  277. }
  278. }
  279. public void cancel(Long id) {
  280. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  281. cancel(order);
  282. }
  283. public void cancel(Order order) {
  284. if (order.getStatus() != OrderStatus.NOT_PAID) {
  285. throw new BusinessException("已支付订单无法取消");
  286. }
  287. Collection collection = collectionRepo.findById(order.getCollectionId())
  288. .orElseThrow(new BusinessException("藏品不存在"));
  289. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  290. if (collection.getSource() == CollectionSource.TRANSFER) {
  291. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  292. if (asset != null) {
  293. asset.setStatus(AssetStatus.NORMAL);
  294. assetRepo.save(asset);
  295. }
  296. collection.setOnShelf(true);
  297. }
  298. collection.setSale(collection.getSale() - 1);
  299. collection.setStock(collection.getStock() + 1);
  300. collectionRepo.save(collection);
  301. order.setStatus(OrderStatus.CANCELLED);
  302. order.setCancelTime(LocalDateTime.now());
  303. orderRepo.save(order);
  304. if (order.getCouponId() != null) {
  305. userCouponRepo.findById(order.getCouponId()).ifPresent(coupon -> {
  306. coupon.setUsed(false);
  307. coupon.setUseTime(null);
  308. userCouponRepo.save(coupon);
  309. });
  310. }
  311. }
  312. @Scheduled(fixedRate = 60000)
  313. public void batchCancel() {
  314. List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  315. LocalDateTime.now().minusMinutes(5));
  316. orders.forEach(this::cancel);
  317. }
  318. public void refundCancelled(Order order) {
  319. }
  320. public synchronized void addSales(Long userId) {
  321. if (userId != null) {
  322. userRepo.findById(userId).ifPresent(user -> {
  323. user.setSales(user.getSales() + 1);
  324. userRepo.save(user);
  325. });
  326. }
  327. }
  328. public void setNumber() {
  329. for (Collection collection : collectionRepo.findAll()) {
  330. if (collection.getSource() != CollectionSource.OFFICIAL) continue;
  331. String key = "collectionNumber::" + collection.getId();
  332. redisTemplate.opsForValue().set(key, 0);
  333. for (Asset asset : assetRepo.findByCollectionId(collection.getId())) {
  334. redisTemplate.opsForValue().increment(key);
  335. asset.setNumber((Integer) redisTemplate.opsForValue().get(key));
  336. assetRepo.save(asset);
  337. }
  338. }
  339. }
  340. public void setSales() {
  341. List<Collection> collections = collectionRepo.findAll();
  342. List<User> minters = userRepo.findAllById(collections.stream().map(Collection::getMinterId)
  343. .collect(Collectors.toSet()));
  344. for (User minter : minters) {
  345. List<Collection> list = collections.stream().filter(c -> minter.getId().equals(c.getMinterId()))
  346. .collect(Collectors.toList());
  347. minter.setSales((int) orderRepo.findByCollectionIdIn(list.stream().map(Collection::getId)
  348. .collect(Collectors.toSet())).stream()
  349. .filter(o -> o.getStatus() != OrderStatus.CANCELLED).count());
  350. userRepo.save(minter);
  351. }
  352. }
  353. }