OrderService.java 33 KB

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