OrderService.java 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. package com.izouma.nineth.service;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.alibaba.fastjson.serializer.SerializerFeature;
  6. import com.alipay.api.AlipayClient;
  7. import com.alipay.api.request.AlipayTradeWapPayRequest;
  8. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  9. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  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.Adapay;
  16. import com.huifu.adapay.core.exception.BaseAdaPayException;
  17. import com.huifu.adapay.model.AdapayCommon;
  18. import com.huifu.adapay.model.Payment;
  19. import com.huifu.adapay.model.Refund;
  20. import com.izouma.nineth.config.*;
  21. import com.izouma.nineth.domain.Collection;
  22. import com.izouma.nineth.domain.*;
  23. import com.izouma.nineth.dto.MarketSettlement;
  24. import com.izouma.nineth.dto.PageQuery;
  25. import com.izouma.nineth.dto.UserBankCard;
  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.*;
  36. import com.izouma.nineth.utils.excel.ExcelUtils;
  37. import lombok.AllArgsConstructor;
  38. import lombok.extern.slf4j.Slf4j;
  39. import org.apache.commons.codec.EncoderException;
  40. import org.apache.commons.codec.net.URLCodec;
  41. import org.apache.commons.collections.MapUtils;
  42. import org.apache.commons.lang3.ObjectUtils;
  43. import org.apache.commons.lang3.RandomStringUtils;
  44. import org.apache.commons.lang3.RandomUtils;
  45. import org.apache.commons.lang3.StringUtils;
  46. import org.apache.rocketmq.client.producer.SendResult;
  47. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  48. import org.springframework.cache.annotation.Cacheable;
  49. import org.springframework.context.event.EventListener;
  50. import org.springframework.core.env.Environment;
  51. import org.springframework.data.domain.Page;
  52. import org.springframework.data.redis.core.BoundSetOperations;
  53. import org.springframework.data.redis.core.BoundValueOperations;
  54. import org.springframework.data.redis.core.RedisTemplate;
  55. import org.springframework.scheduling.annotation.Scheduled;
  56. import org.springframework.stereotype.Service;
  57. import org.springframework.ui.Model;
  58. import java.io.File;
  59. import java.io.OutputStream;
  60. import java.math.BigDecimal;
  61. import java.math.BigInteger;
  62. import java.math.RoundingMode;
  63. import java.time.Duration;
  64. import java.time.LocalDate;
  65. import java.time.LocalDateTime;
  66. import java.time.LocalTime;
  67. import java.time.format.DateTimeFormatter;
  68. import java.time.temporal.ChronoUnit;
  69. import java.util.*;
  70. import java.util.concurrent.TimeUnit;
  71. import java.util.concurrent.atomic.AtomicInteger;
  72. import java.util.stream.Collectors;
  73. @Service
  74. @AllArgsConstructor
  75. @Slf4j
  76. public class OrderService {
  77. private OrderRepo orderRepo;
  78. private CollectionRepo collectionRepo;
  79. private UserAddressRepo userAddressRepo;
  80. private UserRepo userRepo;
  81. private Environment env;
  82. private AlipayClient alipayClient;
  83. private AlipayProperties alipayProperties;
  84. private WxPayService wxPayService;
  85. private WxPayProperties wxPayProperties;
  86. private AssetService assetService;
  87. private SysConfigService sysConfigService;
  88. private AssetRepo assetRepo;
  89. private UserCouponRepo userCouponRepo;
  90. private CollectionService collectionService;
  91. private CommissionRecordRepo commissionRecordRepo;
  92. private AdapayProperties adapayProperties;
  93. private GeneralProperties generalProperties;
  94. private RocketMQTemplate rocketMQTemplate;
  95. private RedisTemplate<String, Object> redisTemplate;
  96. private SnowflakeIdWorker snowflakeIdWorker;
  97. private SmsService smsService;
  98. private ErrorOrderRepo errorOrderRepo;
  99. private ShowCollectionRepo showCollectionRepo;
  100. private ShowroomService showroomService;
  101. private CollectionPrivilegeRepo collectionPrivilegeRepo;
  102. private UserBankCardRepo userBankCardRepo;
  103. private IdentityAuthRepo identityAuthRepo;
  104. private CacheService cacheService;
  105. public Page<Order> all(PageQuery pageQuery) {
  106. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  107. }
  108. public String mqCreate(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor,
  109. String sign, boolean vip, int vipPurchase, int vipPoint) {
  110. String qs = null;
  111. try {
  112. qs = AESEncryptUtil.decrypt(sign);
  113. } catch (Exception e) {
  114. throw new BusinessException("签名错误");
  115. }
  116. final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(qs);
  117. if (Math.abs(MapUtils.getLong(map, "ts") - System.currentTimeMillis()) > 90000) {
  118. throw new BusinessException("签名已过期");
  119. }
  120. if (redisTemplate.opsForValue().get(RedisKeys.BLACK_LIST + userId) != null) {
  121. throw new BusinessException("频繁操作,请稍后再试");
  122. }
  123. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.LIMIT_USER + userId);
  124. ops.setIfAbsent(0, Duration.ofSeconds(10));
  125. long val = Optional.ofNullable(ops.increment()).orElse(0L);
  126. if (val > 5) {
  127. if (val > 10) {
  128. redisTemplate.opsForValue().set(RedisKeys.BLACK_LIST + userId, 1, Duration.ofSeconds(60 * 10));
  129. }
  130. throw new BusinessException("频繁操作,请稍后再试");
  131. }
  132. limitReq(collectionId);
  133. Integer stock = collectionService.getStock(collectionId);
  134. if (stock == null || stock <= 0) {
  135. throw new BusinessException("藏品已售罄", ErrorCode.SOLD_OUT);
  136. }
  137. Long id = snowflakeIdWorker.nextId();
  138. SendResult result = rocketMQTemplate.syncSend(generalProperties.getCreateOrderTopic(),
  139. new CreateOrderEvent(id, userId, collectionId, qty, addressId, userCouponId, invitor, vip), 100000);
  140. log.info("发送订单到队列: {}, userId={}, result={}", id, userId, result);
  141. return String.valueOf(id);
  142. }
  143. public void limitReq(Long collectionId) {
  144. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.LIMIT_REQ + collectionId);
  145. ops.setIfAbsent(3000, Duration.ofSeconds(30));
  146. Long val = ops.decrement();
  147. if (val == null || val < 0) {
  148. throw new BusinessException("前方拥堵,请稍后再试");
  149. }
  150. }
  151. public Order create(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor,
  152. Long id, boolean vip) {
  153. long t = System.currentTimeMillis();
  154. qty = 1;
  155. int stock = Optional.ofNullable(collectionService.decreaseStock(collectionId, qty))
  156. .map(Math::toIntExact)
  157. .orElseThrow(new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT));
  158. int usePoint = 0;
  159. // 创建订单出错后需要回滚库存,所以需要try-catch
  160. try {
  161. if (stock < 0) {
  162. throw new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT);
  163. }
  164. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  165. if (collection.getAssetId() != null && collection.getAssetId().equals(778359L)) {
  166. throw new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT);
  167. }
  168. if (collection.getSource() == CollectionSource.TRANSFER) {
  169. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("藏品不存在"));
  170. if (Objects.equals(asset.getUserId(), userId)) {
  171. throw new BusinessException("不能购买自己的藏品");
  172. }
  173. if (asset.getStatus() != AssetStatus.NORMAL) {
  174. throw new BusinessException("藏品已下架");
  175. }
  176. }
  177. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  178. UserCoupon coupon = null;
  179. if (collection.isCouponPayment()) {
  180. if (userCouponId == null) {
  181. throw new BusinessException("必须使用优惠券支付");
  182. }
  183. coupon = userCouponRepo.findById(userCouponId).orElseThrow(new BusinessException("兑换券不存在"));
  184. if (coupon.isUsed()) {
  185. throw new BusinessException("该兑换券已使用");
  186. }
  187. if (coupon.isLimited() && !coupon.getCollectionIds().contains(collectionId)) {
  188. throw new BusinessException("该兑换券不可用");
  189. }
  190. }
  191. if (collection.isScheduleSale()) {
  192. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  193. throw new BusinessException("当前还未开售");
  194. }
  195. }
  196. if (!collection.isOnShelf()) {
  197. if (!collection.isScanCode()) {
  198. throw new BusinessException("藏品已下架");
  199. }
  200. }
  201. if (!collection.isSalable()) {
  202. throw new BusinessException("该藏品当前不可购买");
  203. }
  204. if (collection.getMaxCount() > 0) {
  205. int count;
  206. if (StringUtils.isNotBlank(collection.getCountId())) {
  207. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(), Arrays
  208. .asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  209. } else {
  210. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId, Arrays
  211. .asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  212. }
  213. if (count >= collection.getMaxCount()) {
  214. throw new BusinessException("限购" + collection.getMaxCount() + "件");
  215. }
  216. }
  217. User user = null;
  218. if (ObjectUtils.isNotEmpty(collection.getMinimumCharge()) && collection.getMinimumCharge()
  219. .compareTo(BigDecimal.ZERO) > 0) {
  220. user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  221. if (!user.isCanSale()) {
  222. throw new BusinessException("绿洲石不足");
  223. }
  224. }
  225. //查询是否有拉新任务,只算官方购买
  226. if (collection.getSource() != CollectionSource.TRANSFER && collection.getAssignment() > 0) {
  227. //延迟销售
  228. if (!vip && collection.getTimeDelay()) {
  229. if (collection.getSaleTime().isAfter(LocalDateTime.now())) {
  230. throw new BusinessException("当前还未开售");
  231. }
  232. }
  233. if (user == null) {
  234. user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  235. }
  236. if (vip) {
  237. int purchase = orderRepo
  238. .countByUserIdAndCollectionIdAndVipTrueAndStatusIn(userId, collectionId, Arrays
  239. .asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  240. if (user.getVipPurchase() - purchase <= 0) {
  241. throw new BusinessException("vip名额已使用完毕!");
  242. }
  243. // vip扣除额度
  244. if (ObjectUtils.isNotEmpty(collection.getVipQuota())) {
  245. collectionService.decreaseQuota(collectionId, 1);
  246. }
  247. } else {
  248. if (user.getVipPoint() < 1) {
  249. throw new BusinessException("没有购买名额");
  250. }
  251. usePoint = 1;
  252. }
  253. }
  254. UserAddress userAddress = null;
  255. if (addressId != null) {
  256. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  257. }
  258. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  259. Order order = Order.builder()
  260. .id(Optional.ofNullable(id).orElse(snowflakeIdWorker.nextId()))
  261. .userId(userId)
  262. .collectionId(collectionId)
  263. .name(collection.getName())
  264. .pic(collection.getPic())
  265. .detail(collection.getDetail())
  266. .properties(collection.getProperties())
  267. .category(collection.getCategory())
  268. .canResale(collection.isCanResale())
  269. .royalties(collection.getRoyalties())
  270. .serviceCharge(collection.getServiceCharge())
  271. .type(collection.getType())
  272. .source(collection.getSource())
  273. .minterId(collection.getMinterId())
  274. .minter(minter.getNickname())
  275. .minterAvatar(minter.getAvatar())
  276. .qty(qty)
  277. .price(collection.getPrice())
  278. .gasPrice(gasFee)
  279. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  280. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  281. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  282. .address(Optional.ofNullable(userAddress).map(u ->
  283. u.getProvinceName() + " " + u.getCityName() + " " + u.getDistrictName() + " " + u
  284. .getAddress())
  285. .orElse(null))
  286. .status(OrderStatus.NOT_PAID)
  287. .assetId(collection.getAssetId())
  288. .couponId(userCouponId)
  289. .invitor(invitor)
  290. .countId(collection.getCountId())
  291. .vip(vip)
  292. .vipPoint(usePoint)
  293. .build();
  294. if (coupon != null) {
  295. coupon.setUsed(true);
  296. coupon.setUseTime(LocalDateTime.now());
  297. if (coupon.isNeedGas()) {
  298. order.setTotalPrice(order.getGasPrice());
  299. } else {
  300. order.setTotalPrice(BigDecimal.ZERO);
  301. }
  302. userCouponRepo.save(coupon);
  303. }
  304. if (collection.getSource() == CollectionSource.TRANSFER) {
  305. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  306. asset.setStatus(AssetStatus.TRADING);
  307. assetRepo.save(asset);
  308. collectionRepo.setOnShelf(collectionId, false);
  309. }
  310. order = orderRepo.save(order);
  311. if (order.getTotalPrice().compareTo(BigDecimal.ZERO) == 0) {
  312. notifyOrder(order.getId(), PayMethod.WEIXIN, null);
  313. }
  314. if (usePoint > 0) {
  315. // 扣除积分
  316. userRepo.addVipPoint(userId, -usePoint);
  317. cacheService.clearUserMy(userId);
  318. }
  319. rocketMQTemplate.syncSend(generalProperties.getUpdateStockTopic(), collectionId, 10000);
  320. log.info("订单创建完成, id={}, {}ms", order.getId(), System.currentTimeMillis() - t);
  321. return order;
  322. } catch (Exception e) {
  323. collectionService.increaseStock(collectionId, qty);
  324. if (usePoint > 0) {
  325. // 扣除积分
  326. userRepo.addVipPoint(userId, usePoint);
  327. cacheService.clearUserMy(userId);
  328. log.info("订单失败加积分用户ID:{}, 积分:{}", userId, usePoint);
  329. }
  330. if (vip) {
  331. collectionService.decreaseQuota(collectionId, 1);
  332. log.info("订单失败加藏品额度CollectionId:{}", collectionId);
  333. }
  334. throw e;
  335. }
  336. }
  337. public Object checkLimit(Long collectionId, Long userId) {
  338. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  339. int limit = collection.getMaxCount();
  340. int count = 0;
  341. if (collection.getMaxCount() > 0) {
  342. if (StringUtils.isNotBlank(collection.getCountId())) {
  343. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(),
  344. Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  345. } else {
  346. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId,
  347. Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  348. }
  349. }
  350. Map<String, Object> map = new HashMap<>();
  351. map.put("limit", limit);
  352. map.put("count", count);
  353. return map;
  354. }
  355. public void payOrderAlipay(Long id, Model model) {
  356. try {
  357. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  358. if (order.getStatus() != OrderStatus.NOT_PAID) {
  359. throw new BusinessException("订单状态错误");
  360. }
  361. JSONObject bizContent = new JSONObject();
  362. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  363. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  364. bizContent.put("out_trade_no", String.valueOf(snowflakeIdWorker.nextId()));
  365. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  366. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  367. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  368. // 测试环境设为1分
  369. bizContent.put("total_amount", "0.01");
  370. }
  371. bizContent.put("subject", order.getName());
  372. bizContent.put("product_code", "QUICK_WAP_PAY");
  373. JSONObject body = new JSONObject();
  374. body.put("action", "payOrder");
  375. body.put("userId", order.getUserId());
  376. body.put("orderId", order.getId());
  377. bizContent.put("body", body.toJSONString());
  378. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  379. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  380. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  381. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  382. String form = alipayClient.pageExecute(alipayRequest).getBody();
  383. model.addAttribute("form", form);
  384. } catch (BusinessException err) {
  385. model.addAttribute("errMsg", err.getError());
  386. } catch (Exception e) {
  387. model.addAttribute("errMsg", e.getMessage());
  388. }
  389. }
  390. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  391. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  392. if (order.getStatus() != OrderStatus.NOT_PAID) {
  393. throw new BusinessException("订单状态错误");
  394. }
  395. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  396. request.setBody(order.getName());
  397. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  398. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  399. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  400. // 测试环境设为1分
  401. // request.setTotalFee(1);
  402. }
  403. request.setSpbillCreateIp("180.102.110.170");
  404. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  405. request.setTradeType(tradeType);
  406. request.setOpenid(openId);
  407. request.setSignType("MD5");
  408. JSONObject body = new JSONObject();
  409. body.put("action", "payOrder");
  410. body.put("userId", order.getUserId());
  411. body.put("orderId", order.getId());
  412. request.setAttach(body.toJSONString());
  413. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  414. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  415. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  416. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  417. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  418. }
  419. throw new BusinessException("不支持此付款方式");
  420. }
  421. @Cacheable(value = "adapay", key = "#id+'_'+#payChannel")
  422. public Object payAdapay(Long id, String payChannel, String openId) throws BaseAdaPayException {
  423. List<String> aliChannels = Arrays.asList("alipay", "alipay_qr", "alipay_wap");
  424. List<String> wxChannels = Arrays.asList("wx_pub", "wx_lite");
  425. if (!aliChannels.contains(payChannel) && !wxChannels.contains(payChannel)) {
  426. throw new BusinessException("不支持此渠道");
  427. }
  428. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  429. if (SecurityUtils.getAuthenticatedUser() != null
  430. && !SecurityUtils.getAuthenticatedUser().getId().equals(order.getUserId())) {
  431. log.error("payAdapay userId错误 requestUserId={} orderUserId={}",
  432. SecurityUtils.getAuthenticatedUser().getId(), order.getUserId());
  433. }
  434. Collection collection = collectionRepo.findById(order.getCollectionId())
  435. .orElseThrow(new BusinessException("藏品不存在"));
  436. User invitor = null;
  437. if (order.getInvitor() != null) {
  438. invitor = userRepo.findById(order.getInvitor()).orElse(null);
  439. }
  440. if (invitor != null && StringUtils.isBlank(invitor.getSettleAccountId())) {
  441. invitor = null;
  442. }
  443. if (order.getStatus() != OrderStatus.NOT_PAID) {
  444. throw new BusinessException("订单状态错误");
  445. }
  446. Map<String, Object> paymentParams = new HashMap<>();
  447. paymentParams.put("order_no", String.valueOf(snowflakeIdWorker.nextId()));
  448. paymentParams.put("pay_amt", order.getTotalPrice().setScale(2, RoundingMode.HALF_UP).toPlainString());
  449. paymentParams.put("app_id", adapayProperties.getAppId());
  450. paymentParams.put("pay_channel", payChannel);
  451. paymentParams.put("goods_title", collection.getName());
  452. paymentParams.put("goods_desc", collection.getName());
  453. paymentParams.put("time_expire", DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
  454. .format(LocalDateTime.now().plusMinutes(3)));
  455. paymentParams.put("notify_url", adapayProperties.getNotifyUrl() + "/order/" + adapayProperties
  456. .getMerchant() + "/" + order.getId());
  457. List<Map<String, Object>> divMembers = new ArrayList<>();
  458. BigDecimal totalAmount = order.getTotalPrice().subtract(order.getGasPrice());
  459. BigDecimal restAmount = order.getTotalPrice().multiply(BigDecimal.valueOf(1));
  460. if (collection.getSource().equals(CollectionSource.TRANSFER)) {
  461. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("无记录"));
  462. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("拥有者用户不存在"));
  463. if (collection.getServiceCharge() + collection.getRoyalties() > 0) {
  464. // 扣除手续费、服务费、GAS费
  465. restAmount = divMoney(totalAmount, restAmount, divMembers, owner.getMemberId(),
  466. 100 - (collection.getServiceCharge() + collection.getRoyalties()), false);
  467. }
  468. restAmount = divMoney(restAmount, divMembers, "0", restAmount, true);
  469. } else {
  470. if (invitor != null && invitor.getShareRatio() != null
  471. && invitor.getShareRatio().compareTo(BigDecimal.ZERO) > 0) {
  472. restAmount = divMoney(totalAmount, restAmount, divMembers, invitor.getMemberId(),
  473. invitor.getShareRatio().intValue(), false);
  474. }
  475. restAmount = divMoney(restAmount, divMembers, "0", restAmount, true);
  476. }
  477. if (restAmount.compareTo(BigDecimal.ZERO) != 0) {
  478. log.error("分账出错 {}", JSON.toJSONString(divMembers, SerializerFeature.PrettyFormat));
  479. throw new BusinessException("分账出错");
  480. }
  481. if (divMembers.size() > 1) {
  482. paymentParams.put("div_members", divMembers);
  483. }
  484. Map<String, Object> expend = new HashMap<>();
  485. paymentParams.put("expend", expend);
  486. if ("wx_pub".equals(payChannel)) {
  487. if (StringUtils.isBlank(openId)) {
  488. throw new BusinessException("缺少openId");
  489. }
  490. expend.put("open_id", openId);
  491. expend.put("limit_pay", "1");
  492. }
  493. Map<String, Object> response;
  494. if ("wx_lite".equals(payChannel)) {
  495. paymentParams.put("adapay_func_code", "wxpay.createOrder");
  496. paymentParams.put("callback_url", generalProperties.getHost() + "/9th/orders");
  497. response = AdapayCommon.requestAdapayUits(paymentParams);
  498. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  499. } else {
  500. response = Payment.create(paymentParams);
  501. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  502. AdapayService.checkSuccess(response);
  503. // 保存adapay的订单id,用于后续取消订单时的查询
  504. BoundSetOperations<String, Object> ops = redisTemplate.boundSetOps(RedisKeys.PAY_RECORD + order.getId());
  505. ops.add(adapayProperties.getMerchant() + "#" + MapUtils.getString(response, "id"));
  506. ops.expire(7, TimeUnit.DAYS);
  507. }
  508. switch (payChannel) {
  509. case "alipay_wap":
  510. case "alipay":
  511. return MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info");
  512. case "alipay_qr":
  513. return MapUtils.getString(MapUtils.getMap(response, "expend"), "qrcode_url");
  514. case "wx_pub":
  515. JSONObject payParams = JSON
  516. .parseObject(MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info"));
  517. payParams.put("timestamp", payParams.get("timeStamp"));
  518. payParams.remove("timeStamp");
  519. return payParams;
  520. default:
  521. return MapUtils.getMap(response, "expend");
  522. }
  523. }
  524. public static BigDecimal divMoney(BigDecimal totalAmount, BigDecimal restAmount, List<Map<String, Object>> divMembers,
  525. String memberId, int ratio, boolean feeFlag) {
  526. if (ratio == -1 || (ratio > 0 && ratio < 100)) {
  527. BigDecimal divAmount = ratio == -1 ? restAmount :
  528. totalAmount.multiply(BigDecimal.valueOf(ratio))
  529. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
  530. Map<String, Object> divMem = new HashMap<>();
  531. divMem.put("member_id", memberId);
  532. divMem.put("amount", divAmount.toPlainString());
  533. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  534. divMembers.add(divMem);
  535. return restAmount.subtract(divAmount);
  536. } else {
  537. throw new BusinessException("分账比例错误");
  538. }
  539. }
  540. public static BigDecimal divMoney(BigDecimal restAmount, List<Map<String, Object>> divMembers,
  541. String memberId, BigDecimal divAmount, boolean feeFlag) {
  542. if (divAmount.compareTo(BigDecimal.ZERO) > 0) {
  543. Map<String, Object> divMem = new HashMap<>();
  544. divMem.put("member_id", memberId);
  545. divMem.put("amount", divAmount.toPlainString());
  546. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  547. divMembers.add(divMem);
  548. }
  549. return restAmount.subtract(divAmount);
  550. }
  551. public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
  552. log.info("订单回调 orderId: {}, payMethod: {}, transactionId: {}", orderId, payMethod, transactionId);
  553. // 取消订单与订单回调不能同时进行,需要抢锁
  554. if (!getOrderLock(orderId)) {
  555. log.info("订单回调失败 orderId: {} redis锁定, 重新发送到队列", orderId);
  556. rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  557. new OrderNotifyEvent(orderId, payMethod, transactionId, System.currentTimeMillis()));
  558. return;
  559. }
  560. try {
  561. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  562. Collection collection = collectionRepo.findDetailById(order.getCollectionId())
  563. .orElseThrow(new BusinessException("藏品不存在"));
  564. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  565. if (order.getStatus() == OrderStatus.NOT_PAID) {
  566. order.setStatus(OrderStatus.PROCESSING);
  567. order.setPayTime(LocalDateTime.now());
  568. order.setTransactionId(transactionId);
  569. order.setPayMethod(payMethod);
  570. if (order.getType() == CollectionType.BLIND_BOX) {
  571. log.info("开始盲盒抽卡 orderId: {}, collectionId: {}", orderId, collection.getId());
  572. BlindBoxItem winItem = collectionService.draw(collection.getId());
  573. log.info("抽卡成功 orderId: {}, collectionId: {}, winCollectionId: {}", orderId, collection
  574. .getId(), winItem.getCollectionId());
  575. order.setWinCollectionId(winItem.getCollectionId());
  576. orderRepo.save(order);
  577. //藏品其他信息/是否vip
  578. CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(order.getCollectionId());
  579. if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
  580. if (collectionPrivilege.isVip()) {
  581. //更新vip信息
  582. userRepo.updateVipPurchase(order.getUserId(), 1);
  583. }
  584. }
  585. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售",
  586. winItem.getTotal() > 1 ? collectionService.getNextNumber(winItem.getCollectionId()) : null,
  587. collection.getHoldDays());
  588. } else {
  589. if (collection.getSource() == CollectionSource.TRANSFER) {
  590. orderRepo.save(order);
  591. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  592. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  593. order.setStatus(OrderStatus.FINISH);
  594. orderRepo.save(order);
  595. collectionRepo.delete(collection);
  596. // 如果展厅有此藏品
  597. showCollectionRepo.deleteAllByCollectionId(order.getCollectionId());
  598. // 发送短信提醒用户转让成功
  599. if (asset != null && asset.getUserId() != null) {
  600. smsService.sellOut(userRepo.findPhoneById(asset.getUserId()));
  601. }
  602. } else {
  603. orderRepo.save(order);
  604. //藏品其他信息/是否vip
  605. CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(order.getCollectionId());
  606. if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
  607. if (collectionPrivilege.isVip()) {
  608. //更新vip信息
  609. userRepo.updateVipPurchase(order.getUserId(), 1);
  610. }
  611. }
  612. Asset asset = assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售",
  613. collection.getTotal() > 1 ? collectionService
  614. .getNextNumber(order.getCollectionId()) : null);
  615. if (collection.getType() == CollectionType.SHOWROOM) {
  616. showroomService.save(asset);
  617. }
  618. }
  619. }
  620. commission(order);
  621. if (collection.getAssetId() == null) {
  622. collectionService.increaseSale(order.getCollectionId(), order.getQty());
  623. }
  624. } else {
  625. throw new BusinessException("状态错误 " + order.getStatus());
  626. }
  627. } catch (Exception e) {
  628. ErrorOrder errorOrder = ErrorOrder.builder()
  629. .orderId(orderId)
  630. .transactionId(transactionId)
  631. .payMethod(payMethod)
  632. .build();
  633. if (e instanceof BusinessException) {
  634. log.error("订单回调出错 orderId: {} {}", orderId, e.getMessage());
  635. } else {
  636. log.error("订单回调出错 orderId: " + orderId, e);
  637. }
  638. errorOrder.setErrorMessage(e.getMessage());
  639. errorOrderRepo.save(errorOrder);
  640. }
  641. releaseOrderLock(orderId);
  642. }
  643. @EventListener
  644. public void onCreateAsset(CreateAssetEvent event) {
  645. Asset asset = event.getAsset();
  646. if (asset.getOrderId() != null) {
  647. Order order = orderRepo.findById(asset.getOrderId()).orElse(null);
  648. if (event.isSuccess() && order != null) {
  649. order.setTxHash(asset.getTxHash());
  650. order.setGasUsed(asset.getGasUsed());
  651. order.setBlockNumber(asset.getBlockNumber());
  652. order.setStatus(OrderStatus.FINISH);
  653. orderRepo.save(order);
  654. }
  655. }
  656. }
  657. @EventListener
  658. public void onTransferAsset(TransferAssetEvent event) {
  659. Asset asset = event.getAsset();
  660. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  661. if (event.isSuccess()) {
  662. order.setTxHash(asset.getTxHash());
  663. order.setGasUsed(asset.getGasUsed());
  664. order.setBlockNumber(asset.getBlockNumber());
  665. order.setStatus(OrderStatus.FINISH);
  666. orderRepo.save(order);
  667. } else {
  668. log.error("创建asset失败");
  669. }
  670. }
  671. public void cancel(Long id) {
  672. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  673. cancel(order);
  674. }
  675. public void cancel(Order order) {
  676. // 取消订单与订单回调不能同时进行,需要抢锁
  677. if (!getOrderLock(order.getId())) {
  678. log.error("订单取消失败 {}, redis锁了", order.getId());
  679. return;
  680. }
  681. try {
  682. if (order.getStatus() != OrderStatus.NOT_PAID) {
  683. throw new BusinessException("已支付订单无法取消");
  684. }
  685. // 查询adapay支付记录,如果已经支付,则不能取消
  686. Set<Object> transactionIds = redisTemplate.opsForSet().members(RedisKeys.PAY_RECORD + order.getId());
  687. if (transactionIds != null && transactionIds.size() > 0) {
  688. AtomicInteger succeeded = new AtomicInteger();
  689. AtomicInteger pending = new AtomicInteger();
  690. transactionIds.parallelStream().forEach(s -> {
  691. String transactionIdStr = Optional.ofNullable(s).map(Object::toString).orElse("");
  692. String transactionId = null;
  693. String merchant = null;
  694. if (transactionIdStr.contains("#")) {
  695. String[] arr = transactionIdStr.split("#");
  696. merchant = arr[0];
  697. transactionId = arr[1];
  698. } else {
  699. merchant = Adapay.defaultMerchantKey;
  700. transactionId = transactionIdStr;
  701. }
  702. try {
  703. Map<String, Object> map = Payment.query(transactionId, merchant);
  704. if ("succeeded".equalsIgnoreCase(MapUtils.getString(map, "status"))) {
  705. succeeded.getAndIncrement();
  706. }
  707. if ("pending".equalsIgnoreCase(MapUtils.getString(map, "status"))) {
  708. pending.getAndIncrement();
  709. // 未支付的订单调用关单接口
  710. Map<String, Object> closeParams = new HashMap<>();
  711. closeParams.put("payment_id", transactionId);
  712. Payment.close(closeParams, merchant);
  713. }
  714. } catch (BaseAdaPayException e) {
  715. log.error("adapay error", e);
  716. }
  717. });
  718. // if (succeeded.get() + pending.get() > 0) {
  719. if (succeeded.get() > 0) {
  720. if (ChronoUnit.MINUTES.between(order.getCreatedAt(), LocalDateTime.now()) < 10) {
  721. throw new BusinessException("订单已经支付成功或待支付,不能取消 " + order.getId());
  722. }
  723. }
  724. }
  725. CollectionSource source = Optional.ofNullable(order.getSource()).orElseGet(() ->
  726. collectionRepo.findById(order.getCollectionId()).map(Collection::getSource).orElse(null));
  727. if (source == CollectionSource.TRANSFER) {
  728. Asset asset = assetRepo.findById(order.getAssetId()).orElse(null);
  729. if (asset != null) {
  730. log.info("set normal cancelOrder {}", order.getId());
  731. asset.setStatus(AssetStatus.NORMAL);
  732. assetRepo.save(asset);
  733. }
  734. collectionRepo.setOnShelf(order.getCollectionId(), true);
  735. }
  736. collectionService.increaseStock(order.getCollectionId(), order.getQty());
  737. order.setStatus(OrderStatus.CANCELLED);
  738. order.setCancelTime(LocalDateTime.now());
  739. orderRepo.save(order);
  740. if (order.getCouponId() != null) {
  741. userCouponRepo.findById(order.getCouponId()).ifPresent(coupon -> {
  742. coupon.setUsed(false);
  743. coupon.setUseTime(null);
  744. userCouponRepo.save(coupon);
  745. });
  746. }
  747. //加上积分
  748. if (ObjectUtils.isNotEmpty(order.getVipPoint()) && order.getVipPoint() > 0) {
  749. userRepo.updateVipPoint(order.getUserId(), order.getVipPoint());
  750. cacheService.clearUserMy(order.getUserId());
  751. log.info("取消加积分用户ID:{},订单ID:{},积分:{}", order.getUserId(), order.getId(), order.getVipPoint());
  752. }
  753. if (order.isVip()) {
  754. collectionService.decreaseQuota(order.getCollectionId(), 1);
  755. log.info("取消加藏品额度CollectionId:{}", order.getCollectionId());
  756. }
  757. rocketMQTemplate.syncSend(generalProperties.getUpdateQuotaTopic(), order.getCollectionId(), 10000);
  758. log.info("取消订单{}", order.getId());
  759. } catch (Exception e) {
  760. if (e instanceof BusinessException) {
  761. log.error(e.getMessage());
  762. } else {
  763. log.error("订单取消错误 orderId: " + order.getId(), e);
  764. }
  765. }
  766. releaseOrderLock(order.getId());
  767. }
  768. public void refundCancelled(Order order) {
  769. }
  770. public void setNumber() {
  771. for (Collection collection : collectionRepo.findAll()) {
  772. if (collection.getSource() != CollectionSource.OFFICIAL) continue;
  773. collection.setCurrentNumber(0);
  774. collectionRepo.save(collection);
  775. for (Asset asset : assetRepo.findByCollectionId(collection.getId())) {
  776. if (asset.getStatus() == AssetStatus.GIFTED || asset.getStatus() == AssetStatus.TRANSFERRED) {
  777. } else {
  778. asset.setNumber(collectionService.getNextNumber(collection.getId()));
  779. assetRepo.save(asset);
  780. }
  781. }
  782. }
  783. }
  784. public void setNumberRecursive(Asset asset) {
  785. }
  786. @Scheduled(cron = "0 0 4 * * ?")
  787. public void setSales() {
  788. if (generalProperties.isNotifyServer()) {
  789. return;
  790. }
  791. List<User> minters = userRepo.findByAuthoritiesContains(Authority.get(AuthorityName.ROLE_MINTER));
  792. for (User minter : minters) {
  793. userRepo.setSales(minter.getId(), (int) orderRepo.countSales(minter.getId()));
  794. }
  795. }
  796. public void commission(Order order) {
  797. if (order.getInvitor() != null) {
  798. userRepo.findById(order.getInvitor()).ifPresent(user -> {
  799. BigDecimal shareRatio = user.getShareRatio();
  800. if (StringUtils.isNotBlank(user.getSettleAccountId()) &&
  801. shareRatio != null && shareRatio.compareTo(BigDecimal.ZERO) > 0) {
  802. BigDecimal totalPrice = order.getTotalPrice().subtract(order.getGasPrice());
  803. commissionRecordRepo.save(CommissionRecord.builder()
  804. .orderId(order.getId())
  805. .collectionId(order.getCollectionId())
  806. .name(order.getName())
  807. .totalPrice(totalPrice)
  808. .nickname(user.getNickname())
  809. .userId(user.getId())
  810. .shareRatio(user.getShareRatio())
  811. .phone(user.getPhone())
  812. .shareAmount(totalPrice.multiply(shareRatio)
  813. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP))
  814. .build());
  815. }
  816. });
  817. }
  818. }
  819. public Object queryCreateOrder(String id) {
  820. Object res = redisTemplate.opsForValue().get(RedisKeys.CREATE_ORDER + id);
  821. if (res != null) {
  822. if (res instanceof Map) {
  823. if (MapUtils.getBooleanValue((Map) res, "success", false)) {
  824. Order order = (Order) MapUtils.getObject((Map) res, "data");
  825. if (!SecurityUtils.getAuthenticatedUser().getId().equals(order.getUserId())) {
  826. log.error("queryCreateOrder userId错误 requestUserId={} orderUserId={}",
  827. SecurityUtils.getAuthenticatedUser().getId(), order.getUserId());
  828. return null;
  829. }
  830. }
  831. }
  832. }
  833. return res;
  834. }
  835. // 获取订单锁,有效时间1小时
  836. public boolean getOrderLock(Long orderId) {
  837. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.ORDER_LOCK + orderId);
  838. Boolean flag = ops.setIfAbsent(1, 1, TimeUnit.HOURS);
  839. return Boolean.TRUE.equals(flag);
  840. }
  841. // 释放订单锁
  842. public void releaseOrderLock(Long orderId) {
  843. redisTemplate.delete(RedisKeys.ORDER_LOCK + orderId);
  844. }
  845. public void calcSettle(LocalDateTime start, LocalDateTime end, OutputStream outputStream) {
  846. List<Order> orders = orderRepo
  847. .findByCreatedAtBetweenAndSourceAndStatusIn(start, end, CollectionSource.TRANSFER, Arrays
  848. .asList(OrderStatus.PROCESSING, OrderStatus.FINISH));
  849. List<Asset> assets = assetRepo.findAllById(orders.stream().map(Order::getAssetId).collect(Collectors.toSet()));
  850. List<UserBankCard> bankCards = userBankCardRepo
  851. .findByUserIdIn(assets.stream().map(Asset::getUserId).collect(Collectors.toSet()));
  852. List<MarketSettlement> settlements = new ArrayList<>();
  853. for (Order order : orders) {
  854. BigDecimal amount = order.getTotalPrice()
  855. .subtract(order.getGasPrice())
  856. .multiply(new BigDecimal("100")
  857. .subtract(BigDecimal.valueOf(order.getServiceCharge()))
  858. .subtract(BigDecimal.valueOf(order.getRoyalties()))
  859. .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP))
  860. .setScale(2, RoundingMode.HALF_UP);
  861. Long userId = assets.stream().filter(a -> a.getId().equals(order.getAssetId())).map(Asset::getUserId)
  862. .findAny().orElse(null);
  863. if (userId != null) {
  864. UserBankCard userBankCard = bankCards.stream().filter(b -> b.getUserId().equals(userId)).findAny()
  865. .orElse(null);
  866. MarketSettlement marketSettlement = settlements.stream().filter(s -> s.getUserId().equals(userId))
  867. .findAny().orElse(null);
  868. if (marketSettlement == null) {
  869. marketSettlement = new MarketSettlement(userId,
  870. Optional.ofNullable(userBankCard).map(UserBankCard::getRealName).orElse(null),
  871. Optional.ofNullable(userBankCard).map(UserBankCard::getBankNo).orElse(null),
  872. amount);
  873. settlements.add(marketSettlement);
  874. } else {
  875. marketSettlement.setAmount(marketSettlement.getAmount()
  876. .add(amount));
  877. }
  878. }
  879. }
  880. EasyExcel.write(outputStream, MarketSettlement.class).sheet("sheet").doWrite(settlements);
  881. }
  882. @Scheduled(cron = "0 0/10 * * * ?")
  883. public void setBlackList() {
  884. List<Long> userIds = orderRepo
  885. .checkBlackList(LocalDate.now().atStartOfDay(), LocalDate.now().atTime(LocalTime.MAX));
  886. userIds.forEach(userId -> {
  887. redisTemplate.opsForValue().set(RedisKeys.BLACK_LIST + userId, 1, Duration.ofSeconds(60 * 120));
  888. });
  889. }
  890. public List<Order> addOrder(Long collectionId, List<Long> userIds, LocalDateTime time, boolean notify) {
  891. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  892. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("用户不存在"));
  893. int i = 0;
  894. List<Order> list = new ArrayList<>();
  895. for (Long userId : userIds) {
  896. time = time.plusSeconds(i++);
  897. BigDecimal gasFee = new BigDecimal("1");
  898. Order order = Order.builder()
  899. .id(snowflakeIdWorker.nextId())
  900. .userId(userId)
  901. .collectionId(collectionId)
  902. .name(collection.getName())
  903. .pic(collection.getPic())
  904. .detail(collection.getDetail())
  905. .properties(collection.getProperties())
  906. .category(collection.getCategory())
  907. .canResale(collection.isCanResale())
  908. .royalties(collection.getRoyalties())
  909. .serviceCharge(collection.getServiceCharge())
  910. .type(collection.getType())
  911. .source(collection.getSource())
  912. .minterId(collection.getMinterId())
  913. .minter(minter.getNickname())
  914. .minterAvatar(minter.getAvatar())
  915. .qty(1)
  916. .price(collection.getPrice())
  917. .gasPrice(gasFee)
  918. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(1)).add(gasFee))
  919. .status(notify ? OrderStatus.NOT_PAID : OrderStatus.FINISH)
  920. .assetId(collection.getAssetId())
  921. .countId(collection.getCountId())
  922. .build();
  923. orderRepo.saveAndFlush(order);
  924. String txHash = RandomStringUtils.randomAlphanumeric(64).toLowerCase(Locale.ROOT);
  925. String transactionId = DateTimeUtils.format(LocalDateTime.now(), "yyyyMMdd") +
  926. RandomStringUtils.randomNumeric(24);
  927. BigInteger gas = new BigInteger("157377");
  928. if (notify) {
  929. rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  930. new OrderNotifyEvent(order.getId(), PayMethod.ALIPAY, order.getTransactionId()
  931. , System.currentTimeMillis()));
  932. } else {
  933. order.setCreatedAt(ObjectUtils.clone(time));
  934. order.setPayTime(time.plusSeconds(RandomUtils.nextInt(5, 50)));
  935. order.setTransactionId(transactionId);
  936. order.setTxHash(txHash);
  937. order.setGasUsed(gas);
  938. order.setPayMethod(PayMethod.ALIPAY);
  939. order.setStatus(OrderStatus.FINISH);
  940. order.setModifiedAt(order.getPayTime());
  941. order.setModifiedBy("system");
  942. order.setCreatedBy("system");
  943. orderRepo.save(order);
  944. }
  945. list.add(order);
  946. }
  947. return list;
  948. }
  949. }