OrderService.java 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.fastjson.serializer.SerializerFeature;
  5. import com.alipay.api.AlipayClient;
  6. import com.alipay.api.request.AlipayTradeWapPayRequest;
  7. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  8. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  9. import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
  10. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
  11. import com.github.binarywang.wxpay.constant.WxPayConstants;
  12. import com.github.binarywang.wxpay.exception.WxPayException;
  13. import com.github.binarywang.wxpay.service.WxPayService;
  14. import com.huifu.adapay.core.exception.BaseAdaPayException;
  15. import com.huifu.adapay.model.AdapayCommon;
  16. import com.huifu.adapay.model.Payment;
  17. import com.huifu.adapay.model.Refund;
  18. import com.izouma.nineth.config.AdapayProperties;
  19. import com.izouma.nineth.config.AlipayProperties;
  20. import com.izouma.nineth.config.GeneralProperties;
  21. import com.izouma.nineth.config.WxPayProperties;
  22. import com.izouma.nineth.domain.Collection;
  23. import com.izouma.nineth.domain.*;
  24. import com.izouma.nineth.dto.PageQuery;
  25. import com.izouma.nineth.enums.*;
  26. import com.izouma.nineth.event.CreateAssetEvent;
  27. import com.izouma.nineth.event.CreateOrderEvent;
  28. import com.izouma.nineth.event.TransferAssetEvent;
  29. import com.izouma.nineth.exception.BusinessException;
  30. import com.izouma.nineth.repo.*;
  31. import com.izouma.nineth.security.Authority;
  32. import com.izouma.nineth.service.sms.SmsService;
  33. import com.izouma.nineth.utils.JpaUtils;
  34. import com.izouma.nineth.utils.SnowflakeIdWorker;
  35. import lombok.AllArgsConstructor;
  36. import lombok.extern.slf4j.Slf4j;
  37. import org.apache.commons.codec.EncoderException;
  38. import org.apache.commons.codec.net.URLCodec;
  39. import org.apache.commons.collections.MapUtils;
  40. import org.apache.commons.lang3.StringUtils;
  41. import org.apache.rocketmq.client.producer.SendResult;
  42. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  43. import org.springframework.context.event.EventListener;
  44. import org.springframework.core.env.Environment;
  45. import org.springframework.data.domain.Page;
  46. import org.springframework.data.redis.core.RedisTemplate;
  47. import org.springframework.scheduling.annotation.Scheduled;
  48. import org.springframework.stereotype.Service;
  49. import org.springframework.ui.Model;
  50. import javax.transaction.Transactional;
  51. import java.math.BigDecimal;
  52. import java.math.RoundingMode;
  53. import java.time.LocalDateTime;
  54. import java.time.format.DateTimeFormatter;
  55. import java.util.*;
  56. @Service
  57. @AllArgsConstructor
  58. @Slf4j
  59. public class OrderService {
  60. private OrderRepo orderRepo;
  61. private CollectionRepo collectionRepo;
  62. private UserAddressRepo userAddressRepo;
  63. private UserRepo userRepo;
  64. private Environment env;
  65. private AlipayClient alipayClient;
  66. private AlipayProperties alipayProperties;
  67. private WxPayService wxPayService;
  68. private WxPayProperties wxPayProperties;
  69. private AssetService assetService;
  70. private SysConfigService sysConfigService;
  71. private BlindBoxItemRepo blindBoxItemRepo;
  72. private AssetRepo assetRepo;
  73. private UserCouponRepo userCouponRepo;
  74. private CollectionService collectionService;
  75. private CommissionRecordRepo commissionRecordRepo;
  76. private AdapayProperties adapayProperties;
  77. private GeneralProperties generalProperties;
  78. private RocketMQTemplate rocketMQTemplate;
  79. private RedisTemplate<String, Object> redisTemplate;
  80. private SnowflakeIdWorker snowflakeIdWorker;
  81. private SmsService smsService;
  82. public Page<Order> all(PageQuery pageQuery) {
  83. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  84. }
  85. public String mqCreate(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor) {
  86. Long id = snowflakeIdWorker.nextId();
  87. SendResult result = rocketMQTemplate.syncSend(generalProperties.getCreateOrderTopic(),
  88. new CreateOrderEvent(id, userId, collectionId, qty, addressId, userCouponId, invitor), 100000);
  89. log.info("发送订单到队列: {}, result={}", id, result);
  90. return String.valueOf(id);
  91. }
  92. @Transactional
  93. public Order create(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor, Long id) {
  94. long t = System.currentTimeMillis();
  95. qty = 1;
  96. int stock = Optional.ofNullable(collectionService.decreaseStock(collectionId, qty))
  97. .map(Math::toIntExact)
  98. .orElseThrow(new BusinessException("很遗憾,藏品已售罄"));
  99. try {
  100. if (stock < 0) {
  101. throw new BusinessException("很遗憾,藏品已售罄");
  102. }
  103. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  104. if (collection.getAssetId() != null && collection.getAssetId().equals(778359L)) {
  105. throw new BusinessException("很遗憾,藏品已售罄");
  106. }
  107. if (collection.getAssetId() != null) {
  108. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("藏品不存在"));
  109. if (asset.getStatus() != AssetStatus.NORMAL) {
  110. throw new BusinessException("藏品已下架");
  111. }
  112. }
  113. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  114. UserCoupon coupon = null;
  115. if (userCouponId != null) {
  116. coupon = userCouponRepo.findById(userCouponId).orElseThrow(new BusinessException("兑换券不存在"));
  117. if (coupon.isUsed()) {
  118. throw new BusinessException("该兑换券已使用");
  119. }
  120. if (coupon.isLimited() && !coupon.getCollectionIds().contains(collectionId)) {
  121. throw new BusinessException("该兑换券不可用");
  122. }
  123. }
  124. if (collection.isScheduleSale()) {
  125. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  126. throw new BusinessException("当前还未开售");
  127. }
  128. }
  129. if (!collection.isOnShelf()) {
  130. if (!collection.isScanCode()) {
  131. throw new BusinessException("藏品已下架");
  132. }
  133. }
  134. if (!collection.isSalable()) {
  135. throw new BusinessException("该藏品当前不可购买");
  136. }
  137. if (collection.getMaxCount() > 0) {
  138. int count;
  139. if (StringUtils.isNotBlank(collection.getCountId())) {
  140. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(), Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  141. } else {
  142. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId, Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  143. }
  144. if (count >= collection.getMaxCount()) {
  145. throw new BusinessException("限购" + collection.getMaxCount() + "件");
  146. }
  147. }
  148. UserAddress userAddress = null;
  149. if (addressId != null) {
  150. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  151. }
  152. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  153. Order order = Order.builder()
  154. .id(Optional.ofNullable(id).orElse(snowflakeIdWorker.nextId()))
  155. .userId(userId)
  156. .collectionId(collectionId)
  157. .name(collection.getName())
  158. .pic(collection.getPic())
  159. .detail(collection.getDetail())
  160. .properties(collection.getProperties())
  161. .category(collection.getCategory())
  162. .canResale(collection.isCanResale())
  163. .royalties(collection.getRoyalties())
  164. .serviceCharge(collection.getServiceCharge())
  165. .type(collection.getType())
  166. .source(collection.getSource())
  167. .minterId(collection.getMinterId())
  168. .minter(minter.getNickname())
  169. .minterAvatar(minter.getAvatar())
  170. .qty(qty)
  171. .price(collection.getPrice())
  172. .gasPrice(gasFee)
  173. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  174. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  175. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  176. .address(Optional.ofNullable(userAddress).map(u ->
  177. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  178. .orElse(null))
  179. .status(OrderStatus.NOT_PAID)
  180. .assetId(collection.getAssetId())
  181. .couponId(userCouponId)
  182. .invitor(invitor)
  183. .countId(collection.getCountId())
  184. .build();
  185. if (coupon != null) {
  186. coupon.setUsed(true);
  187. coupon.setUseTime(LocalDateTime.now());
  188. if (coupon.isNeedGas()) {
  189. order.setTotalPrice(order.getGasPrice());
  190. } else {
  191. order.setTotalPrice(BigDecimal.ZERO);
  192. }
  193. }
  194. if (collection.getSource() == CollectionSource.TRANSFER) {
  195. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  196. asset.setStatus(AssetStatus.TRADING);
  197. assetRepo.save(asset);
  198. collectionRepo.setOnShelf(collectionId, false);
  199. }
  200. order = orderRepo.save(order);
  201. if (order.getTotalPrice().equals(BigDecimal.ZERO)) {
  202. notifyOrder(order.getId(), PayMethod.WEIXIN, null);
  203. }
  204. rocketMQTemplate.syncSend(generalProperties.getUpdateStockTopic(), collectionId, 10000);
  205. log.info("订单创建完成, id={}, {}ms", order.getId(), System.currentTimeMillis() - t);
  206. return order;
  207. } catch (Exception e) {
  208. collectionService.increaseStock(collectionId, qty);
  209. throw e;
  210. }
  211. }
  212. public Object checkLimit(Long collectionId, Long userId) {
  213. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  214. int limit = collection.getMaxCount();
  215. int count = 0;
  216. if (collection.getMaxCount() > 0) {
  217. if (StringUtils.isNotBlank(collection.getCountId())) {
  218. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(),
  219. Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  220. } else {
  221. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId,
  222. Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  223. }
  224. }
  225. Map<String, Object> map = new HashMap<>();
  226. map.put("limit", limit);
  227. map.put("count", count);
  228. return map;
  229. }
  230. public void payOrderAlipay(Long id, Model model) {
  231. try {
  232. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  233. if (order.getStatus() != OrderStatus.NOT_PAID) {
  234. throw new BusinessException("订单状态错误");
  235. }
  236. JSONObject bizContent = new JSONObject();
  237. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  238. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  239. bizContent.put("out_trade_no", String.valueOf(snowflakeIdWorker.nextId()));
  240. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  241. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  242. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  243. // 测试环境设为1分
  244. bizContent.put("total_amount", "0.01");
  245. }
  246. bizContent.put("subject", order.getName());
  247. bizContent.put("product_code", "QUICK_WAP_PAY");
  248. JSONObject body = new JSONObject();
  249. body.put("action", "payOrder");
  250. body.put("userId", order.getUserId());
  251. body.put("orderId", order.getId());
  252. bizContent.put("body", body.toJSONString());
  253. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  254. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  255. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  256. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  257. String form = alipayClient.pageExecute(alipayRequest).getBody();
  258. model.addAttribute("form", form);
  259. } catch (BusinessException err) {
  260. model.addAttribute("errMsg", err.getError());
  261. } catch (Exception e) {
  262. model.addAttribute("errMsg", e.getMessage());
  263. }
  264. }
  265. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  266. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  267. if (order.getStatus() != OrderStatus.NOT_PAID) {
  268. throw new BusinessException("订单状态错误");
  269. }
  270. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  271. request.setBody(order.getName());
  272. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  273. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  274. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  275. // 测试环境设为1分
  276. // request.setTotalFee(1);
  277. }
  278. request.setSpbillCreateIp("180.102.110.170");
  279. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  280. request.setTradeType(tradeType);
  281. request.setOpenid(openId);
  282. request.setSignType("MD5");
  283. JSONObject body = new JSONObject();
  284. body.put("action", "payOrder");
  285. body.put("userId", order.getUserId());
  286. body.put("orderId", order.getId());
  287. request.setAttach(body.toJSONString());
  288. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  289. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  290. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  291. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  292. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  293. }
  294. throw new BusinessException("不支持此付款方式");
  295. }
  296. public Object payAdapay(Long id, String payChannel, String openId) throws BaseAdaPayException {
  297. List<String> aliChannels = Arrays.asList("alipay", "alipay_qr", "alipay_wap");
  298. List<String> wxChannels = Arrays.asList("wx_pub", "wx_lite");
  299. if (!aliChannels.contains(payChannel) && !wxChannels.contains(payChannel)) {
  300. throw new BusinessException("不支持此渠道");
  301. }
  302. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  303. Collection collection = collectionRepo.findById(order.getCollectionId())
  304. .orElseThrow(new BusinessException("藏品不存在"));
  305. User invitor = null;
  306. if (order.getInvitor() != null) {
  307. invitor = userRepo.findById(order.getInvitor()).orElse(null);
  308. }
  309. if (invitor != null && StringUtils.isBlank(invitor.getSettleAccountId())) {
  310. invitor = null;
  311. }
  312. if (order.getStatus() != OrderStatus.NOT_PAID) {
  313. throw new BusinessException("订单状态错误");
  314. }
  315. Map<String, Object> paymentParams = new HashMap<>();
  316. paymentParams.put("order_no", String.valueOf(snowflakeIdWorker.nextId()));
  317. paymentParams.put("pay_amt", order.getTotalPrice().setScale(2, RoundingMode.HALF_UP).toPlainString());
  318. paymentParams.put("app_id", adapayProperties.getAppId());
  319. paymentParams.put("pay_channel", payChannel);
  320. paymentParams.put("goods_title", collection.getName());
  321. paymentParams.put("goods_desc", collection.getName());
  322. paymentParams.put("time_expire", DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
  323. .format(LocalDateTime.now().plusMinutes(3)));
  324. paymentParams.put("notify_url", adapayProperties.getNotifyUrl() + "/order/" + order.getId());
  325. List<Map<String, Object>> divMembers = new ArrayList<>();
  326. BigDecimal totalAmount = order.getTotalPrice().subtract(order.getGasPrice());
  327. BigDecimal restAmount = order.getTotalPrice().multiply(BigDecimal.valueOf(1));
  328. if (collection.getSource().equals(CollectionSource.TRANSFER)) {
  329. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("无记录"));
  330. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("拥有者用户不存在"));
  331. if (collection.getServiceCharge() + collection.getRoyalties() > 0) {
  332. // 扣除手续费、服务费、GAS费
  333. restAmount = divMoney(totalAmount, restAmount, divMembers, owner.getMemberId(),
  334. 100 - (collection.getServiceCharge() + collection.getRoyalties()), true);
  335. }
  336. restAmount = divMoney(restAmount, divMembers, "0", restAmount, false);
  337. } else {
  338. if (invitor != null && invitor.getShareRatio() != null
  339. && invitor.getShareRatio().compareTo(BigDecimal.ZERO) > 0) {
  340. restAmount = divMoney(totalAmount, restAmount, divMembers, invitor.getMemberId(),
  341. invitor.getShareRatio().intValue(), false);
  342. }
  343. restAmount = divMoney(restAmount, divMembers, "0", restAmount, true);
  344. }
  345. if (restAmount.compareTo(BigDecimal.ZERO) != 0) {
  346. log.error("分账出错 {}", JSON.toJSONString(divMembers, SerializerFeature.PrettyFormat));
  347. throw new BusinessException("分账出错");
  348. }
  349. if (divMembers.size() > 1) {
  350. paymentParams.put("div_members", divMembers);
  351. }
  352. Map<String, Object> expend = new HashMap<>();
  353. paymentParams.put("expend", expend);
  354. if ("wx_pub".equals(payChannel)) {
  355. if (StringUtils.isBlank(openId)) {
  356. throw new BusinessException("缺少openId");
  357. }
  358. expend.put("open_id", openId);
  359. expend.put("limit_pay", "1");
  360. }
  361. Map<String, Object> response;
  362. if ("wx_lite".equals(payChannel)) {
  363. paymentParams.put("adapay_func_code", "wxpay.createOrder");
  364. paymentParams.put("callback_url", generalProperties.getHost() + "/9th/orders");
  365. response = AdapayCommon.requestAdapayUits(paymentParams);
  366. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  367. } else {
  368. response = Payment.create(paymentParams);
  369. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  370. AdapayService.checkSuccess(response);
  371. }
  372. switch (payChannel) {
  373. case "alipay_wap":
  374. case "alipay":
  375. return MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info");
  376. case "alipay_qr":
  377. return MapUtils.getString(MapUtils.getMap(response, "expend"), "qrcode_url");
  378. case "wx_pub":
  379. JSONObject payParams = JSON.parseObject(MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info"));
  380. payParams.put("timestamp", payParams.get("timeStamp"));
  381. payParams.remove("timeStamp");
  382. return payParams;
  383. default:
  384. return MapUtils.getMap(response, "expend");
  385. }
  386. }
  387. public static BigDecimal divMoney(BigDecimal totalAmount, BigDecimal restAmount, List<Map<String, Object>> divMembers,
  388. String memberId, int ratio, boolean feeFlag) {
  389. if (ratio == -1 || (ratio > 0 && ratio < 100)) {
  390. BigDecimal divAmount = ratio == -1 ? restAmount :
  391. totalAmount.multiply(BigDecimal.valueOf(ratio))
  392. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
  393. Map<String, Object> divMem = new HashMap<>();
  394. divMem.put("member_id", memberId);
  395. divMem.put("amount", divAmount.toPlainString());
  396. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  397. divMembers.add(divMem);
  398. return restAmount.subtract(divAmount);
  399. } else {
  400. throw new BusinessException("分账比例错误");
  401. }
  402. }
  403. public static BigDecimal divMoney(BigDecimal restAmount, List<Map<String, Object>> divMembers,
  404. String memberId, BigDecimal divAmount, boolean feeFlag) {
  405. if (divAmount.compareTo(BigDecimal.ZERO) > 0) {
  406. Map<String, Object> divMem = new HashMap<>();
  407. divMem.put("member_id", memberId);
  408. divMem.put("amount", divAmount.toPlainString());
  409. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  410. divMembers.add(divMem);
  411. }
  412. return restAmount.subtract(divAmount);
  413. }
  414. @Transactional
  415. public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
  416. log.info("订单回调 orderId: {}, payMethod: {}, transactionId: {}", orderId, payMethod, transactionId);
  417. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  418. Collection collection = collectionRepo.findById(order.getCollectionId())
  419. .orElseThrow(new BusinessException("藏品不存在"));
  420. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  421. if (order.getStatus() == OrderStatus.NOT_PAID) {
  422. order.setStatus(OrderStatus.PROCESSING);
  423. order.setPayTime(LocalDateTime.now());
  424. order.setTransactionId(transactionId);
  425. order.setPayMethod(payMethod);
  426. if (order.getType() == CollectionType.BLIND_BOX) {
  427. log.info("开始盲盒抽卡 orderId: {}, collectionId: {}", orderId, collection.getId());
  428. BlindBoxItem winItem = null;
  429. try {
  430. winItem = collectionService.draw(collection.getId());
  431. } catch (BusinessException e) {
  432. }
  433. if (winItem == null) {
  434. log.info("抽卡失败退款 orderId: {}", orderId);
  435. order.setStatus(OrderStatus.CANCELLED);
  436. order.setCancelTime(LocalDateTime.now());
  437. Map<String, Object> refundParams = new HashMap<>();
  438. refundParams.put("refund_amt", order.getTotalPrice().setScale(2, RoundingMode.HALF_UP)
  439. .toPlainString());
  440. refundParams.put("refund_order_no", String.valueOf(snowflakeIdWorker.nextId()));
  441. try {
  442. Map<String, Object> response = Refund.create(transactionId, refundParams);
  443. } catch (BaseAdaPayException e) {
  444. e.printStackTrace();
  445. }
  446. orderRepo.save(order);
  447. return;
  448. }
  449. log.info("抽卡成功 orderId: {}, collectionId: {}, winCollectionId: {}", orderId, collection.getId(), winItem.getCollectionId());
  450. order.setWinCollectionId(winItem.getCollectionId());
  451. orderRepo.save(order);
  452. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售",
  453. winItem.getTotal() > 1 ? collectionService.getNextNumber(winItem.getCollectionId()) : null);
  454. } else {
  455. if (collection.getSource() == CollectionSource.TRANSFER) {
  456. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  457. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  458. collectionRepo.delete(collection);
  459. // 发送短信提醒用户转让成功
  460. if (asset != null && asset.getUserId() != null) {
  461. smsService.sellOut(userRepo.findPhoneById(asset.getUserId()));
  462. }
  463. } else {
  464. orderRepo.save(order);
  465. assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售",
  466. collection.getTotal() > 1 ? collectionService.getNextNumber(order.getCollectionId()) : null);
  467. }
  468. }
  469. commission(order);
  470. if (collection.getAssetId() == null) {
  471. collectionService.increaseSale(order.getCollectionId(), order.getQty());
  472. }
  473. } else {
  474. log.info("订单回调状态错误 {} {}", orderId, order.getStatus());
  475. }
  476. }
  477. @EventListener
  478. public void onCreateAsset(CreateAssetEvent event) {
  479. Asset asset = event.getAsset();
  480. if (asset.getOrderId() != null) {
  481. Order order = orderRepo.findById(asset.getOrderId()).orElse(null);
  482. if (event.isSuccess() && order != null) {
  483. order.setTxHash(asset.getTxHash());
  484. order.setGasUsed(asset.getGasUsed());
  485. order.setBlockNumber(asset.getBlockNumber());
  486. order.setStatus(OrderStatus.FINISH);
  487. orderRepo.save(order);
  488. }
  489. }
  490. }
  491. @EventListener
  492. public void onTransferAsset(TransferAssetEvent event) {
  493. Asset asset = event.getAsset();
  494. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  495. if (event.isSuccess()) {
  496. order.setTxHash(asset.getTxHash());
  497. order.setGasUsed(asset.getGasUsed());
  498. order.setBlockNumber(asset.getBlockNumber());
  499. order.setStatus(OrderStatus.FINISH);
  500. orderRepo.save(order);
  501. } else {
  502. log.error("创建asset失败");
  503. }
  504. }
  505. public void cancel(Long id) {
  506. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  507. cancel(order);
  508. }
  509. public void cancel(Order order) {
  510. if (order.getStatus() != OrderStatus.NOT_PAID) {
  511. throw new BusinessException("已支付订单无法取消");
  512. }
  513. CollectionSource source = Optional.ofNullable(order.getSource()).orElseGet(() ->
  514. collectionRepo.findById(order.getCollectionId()).map(Collection::getSource).orElse(null));
  515. if (source == CollectionSource.TRANSFER) {
  516. Asset asset = assetRepo.findById(order.getAssetId()).orElse(null);
  517. if (asset != null) {
  518. log.info("set normal cancelOrder {}", order.getId());
  519. asset.setStatus(AssetStatus.NORMAL);
  520. assetRepo.save(asset);
  521. }
  522. collectionRepo.setOnShelf(order.getCollectionId(), true);
  523. }
  524. collectionService.increaseStock(order.getCollectionId(), order.getQty());
  525. order.setStatus(OrderStatus.CANCELLED);
  526. order.setCancelTime(LocalDateTime.now());
  527. orderRepo.save(order);
  528. if (order.getCouponId() != null) {
  529. userCouponRepo.findById(order.getCouponId()).ifPresent(coupon -> {
  530. coupon.setUsed(false);
  531. coupon.setUseTime(null);
  532. userCouponRepo.save(coupon);
  533. });
  534. }
  535. rocketMQTemplate.syncSend(generalProperties.getUpdateStockTopic(), order.getCollectionId(), 10000);
  536. log.info("取消订单{}", order.getId());
  537. }
  538. @Scheduled(fixedRate = 30000)
  539. public void batchCancel() {
  540. if (generalProperties.isNotifyServer()) {
  541. return;
  542. }
  543. if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
  544. return;
  545. }
  546. List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  547. LocalDateTime.now().minusSeconds(210));
  548. orders.parallelStream().forEach(o -> {
  549. try {
  550. cancel(o);
  551. } catch (Exception e) {
  552. log.error("取消订单错误 " + o.getId(), e);
  553. }
  554. });
  555. }
  556. public void refundCancelled(Order order) {
  557. }
  558. public void setNumber() {
  559. for (Collection collection : collectionRepo.findAll()) {
  560. if (collection.getSource() != CollectionSource.OFFICIAL) continue;
  561. collection.setCurrentNumber(0);
  562. collectionRepo.save(collection);
  563. for (Asset asset : assetRepo.findByCollectionId(collection.getId())) {
  564. if (asset.getStatus() == AssetStatus.GIFTED || asset.getStatus() == AssetStatus.TRANSFERRED) {
  565. } else {
  566. asset.setNumber(collectionService.getNextNumber(collection.getId()));
  567. assetRepo.save(asset);
  568. }
  569. }
  570. }
  571. }
  572. public void setNumberRecursive(Asset asset) {
  573. }
  574. @Scheduled(fixedRate = 120000)
  575. public void setSales() {
  576. if (generalProperties.isNotifyServer()) {
  577. return;
  578. }
  579. List<User> minters = userRepo.findByAuthoritiesContains(Authority.get(AuthorityName.ROLE_MINTER));
  580. for (User minter : minters) {
  581. userRepo.setSales(minter.getId(), (int) orderRepo.countSales(minter.getId()));
  582. }
  583. }
  584. public void commission(Order order) {
  585. if (order.getInvitor() != null) {
  586. userRepo.findById(order.getInvitor()).ifPresent(user -> {
  587. BigDecimal shareRatio = user.getShareRatio();
  588. if (StringUtils.isNotBlank(user.getSettleAccountId()) &&
  589. shareRatio != null && shareRatio.compareTo(BigDecimal.ZERO) > 0) {
  590. BigDecimal totalPrice = order.getTotalPrice().subtract(order.getGasPrice());
  591. commissionRecordRepo.save(CommissionRecord.builder()
  592. .orderId(order.getId())
  593. .collectionId(order.getCollectionId())
  594. .name(order.getName())
  595. .totalPrice(totalPrice)
  596. .nickname(user.getNickname())
  597. .userId(user.getId())
  598. .shareRatio(user.getShareRatio())
  599. .phone(user.getPhone())
  600. .shareAmount(totalPrice.multiply(shareRatio)
  601. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP))
  602. .build());
  603. }
  604. });
  605. }
  606. }
  607. public void refund(Long id) throws WxPayException {
  608. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  609. if (order.getStatus() != OrderStatus.FINISH) {
  610. throw new BusinessException("订单未付款");
  611. }
  612. WxPayRefundRequest request = new WxPayRefundRequest();
  613. request.setTransactionId(order.getTransactionId());
  614. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  615. request.setRefundFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  616. request.setOutRefundNo(String.valueOf(snowflakeIdWorker.nextId()));
  617. wxPayService.refund(request);
  618. }
  619. public Object queryCreateOrder(String id) {
  620. return redisTemplate.opsForValue().get("createOrder::" + id);
  621. }
  622. }