OrderService.java 33 KB

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