OrderService.java 36 KB

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