无关风月
2024-07-19 6fc1cceb61be8e8f6378c0ab7f9e5bf12f9393d1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package com.ruoyi.goods.service.impl;
 
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.RedisConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.goods.domain.Recipient;
import com.ruoyi.goods.domain.TGoods;
import com.ruoyi.goods.domain.TOrder;
import com.ruoyi.goods.dto.GoodExchangeDTO;
import com.ruoyi.goods.mapper.TGoodsMapper;
import com.ruoyi.goods.service.ITGoodsService;
import com.ruoyi.goods.service.ITOrderService;
import com.ruoyi.goods.vo.GoodDetailVO;
import com.ruoyi.goods.vo.TGoodsVO;
import com.ruoyi.study.api.domain.TUser;
import com.ruoyi.study.api.feignClient.StudyClient;
import com.ruoyi.study.api.vo.UserPersonalCenterVO;
import com.ruoyi.system.api.model.LoginUserParent;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 无关风月
 * @since 2024-04-26
 */
@Service
public class TGoodsServiceImpl extends ServiceImpl<TGoodsMapper, TGoods> implements ITGoodsService {
 
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private StudyClient studyClient;
    @Resource
    private ITOrderService orderService;
    @Resource
    private TokenService tokenService;
 
    @Override
    public List<TGoodsVO> goodRecommend(Integer userId) {
        return baseMapper.goodRecommend(userId);
    }
 
    @Override
    public TGoods getById1(Integer goodsId) {
        return this.baseMapper.getById1(goodsId);
    }
 
    @Override
    public GoodDetailVO redeemNow(String goodId, Recipient recipient) {
        // 商品详情
        TGoods goods = lambdaQuery().eq(TGoods::getId, goodId).one();
        if (null == goods) {
            throw new GlobalException("商品不存在!");
        }
        // 商品总数量为 null,可无限兑换,不需要分布式锁进行控制
        if (null != goods.getTotal()) {
            // 库存预热,redisson分布式锁
            String key = String.format(RedisConstants.GOOD_STOCK, goods.getId());
            List<TOrder> orderList = orderService.lambdaQuery()
                    .eq(TOrder::getGoodsId, goodId)
                    .eq(TOrder::getDisabled, 0).list();
            int sum = 0;
            if (!orderList.isEmpty()) {
                sum = orderList.stream().map(TOrder::getCount).mapToInt(Integer::intValue).sum();
            }
            // 计算商品剩余可兑换数量
            int number = goods.getTotal() - sum;
            if (number <= 0) {
                throw new GlobalException("商品可兑换数量不足!");
            }
            // redisson分布式锁
            RSemaphore semaphore = redissonClient.getSemaphore(key);
            semaphore.trySetPermits(number);
            semaphore.expire(Constants.SIXTY, TimeUnit.MINUTES);
        }
        return new GoodDetailVO(goods, recipient);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> goodExchange(GoodExchangeDTO goodExchange, Recipient recipient) {
        // 用户本次兑换数量
        Integer number = goodExchange.getNumber();
        Integer goodId = goodExchange.getGoodId();
        TGoods good = lambdaQuery().eq(TGoods::getId, goodId).one();
        if (null == good) {
            return R.exchangeError("商品不存在,请稍后重试!");
        }
        // 校验用户积分是否足够兑换
        UserPersonalCenterVO userPersonalCenter = studyClient.userInfo().getData();
        if (null == userPersonalCenter) {
            throw new GlobalException("用户信息获取失败!");
        }
        TUser user = userPersonalCenter.getUser();
        int needIntegral = good.getIntegral() * number;
        if (user.getIntegral() < needIntegral) {
            return R.exchangeError("兑换失败,当前剩余积分不足!");
        }
        if (null != good.getTotal()) {
            // 检查库存总数是否足够
            List<TOrder> order = orderService.lambdaQuery().eq(TOrder::getGoodsId, goodId)
                    .eq(TOrder::getDisabled, 0).list();
            int item;
            if (!order.isEmpty()) {
                item = order.stream().map(TOrder::getCount).collect(Collectors.toList())
                        .stream().mapToInt(Integer::intValue).sum();
            } else {
                item = 0;
            }
            boolean canBuy = good.getTotal() - item >= number;
            if (!canBuy) {
                throw new GlobalException("商品库存不足,兑换失败!");
            }
            // 检查用户兑换数量是否超过单用户最大兑换数量
            List<TOrder> orderList = orderService.lambdaQuery().eq(TOrder::getUserId, user.getId())
                    .eq(TOrder::getGoodsId, goodId).list();
            // 用户已兑换数量
            int totalNumber;
            if (orderList.isEmpty()) {
                totalNumber = 0;
            } else {
                // 该商品订单为空、订单数量未超过商品的单个用户兑换上限数量时,可以进行兑换
                totalNumber = orderList.stream().map(TOrder::getCount).collect(Collectors.toList())
                        .stream().mapToInt(Integer::intValue).sum();
            }
            boolean canExchange = true;
            if (null != good.getUserCount()) {
                if (number > good.getUserCount()) {
                    canExchange = false;
                } else {
                    canExchange = (totalNumber + number) <= good.getUserCount();
                }
            }
            if (!canExchange) {
                return R.exchangeError("兑换失败,当前兑换数量已超过最大兑换数量,剩余兑换数量为: " +
                        (good.getUserCount() - totalNumber) + "!");
            }
            // redisson分布式锁,防止超卖
            String key = String.format(RedisConstants.GOOD_STOCK, good.getId());
            RSemaphore semaphore = redissonClient.getSemaphore(key);
            // 请求超时时间 单位:毫秒
            semaphore.trySetPermits(1000);
            boolean tried = semaphore.tryAcquire(number);
            // 兑换失败,库存不足
            if (!tried) {
                semaphore.release(number);
                return R.exchangeError("当前商品库存不足");
            }
            // 兑换成功,生成订单信息、生成积分明细(积分明细需要远程调用rouyi-study服务)
            boolean result = exchangeGood(goodExchange, recipient, number, goodId, needIntegral);
            if (!result) {
                semaphore.release(number);
                return R.exchangeError("商品兑换失败!");
            }
        } else {
            if (null != good.getUserCount()) {
                // 检查用户兑换数量是否超过单用户最大兑换数量
                List<TOrder> orderList = orderService.lambdaQuery().eq(TOrder::getUserId, user.getId())
                        .eq(TOrder::getGoodsId, goodId).list();
                int totalNumber;
                if (orderList.isEmpty()) {
                    totalNumber = 0;
                } else {
                    // 该商品订单为空、订单数量未超过商品的单个用户兑换上限数量时,可以进行兑换
                    totalNumber = orderList.stream().map(TOrder::getCount).collect(Collectors.toList())
                            .stream().mapToInt(Integer::intValue).sum();
                }
                Integer userCount = good.getUserCount();
                if (userCount > totalNumber) {
                    int i = userCount - totalNumber;
                    if (number > i) {
                        return R.exchangeError("兑换失败,当前兑换数量已超过最大兑换数量,剩余兑换数量为: " +
                                i + "!");
                    }
                } else {
                    return R.exchangeError("兑换失败,当前兑换数量已超过最大兑换数量!");
                }
            }
            boolean result = exchangeGood(goodExchange, recipient, number, goodId, needIntegral);
            if (!result) {
                return R.exchangeError("商品兑换失败!");
            }
        }
        return R.ok();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R goodExchange1(GoodExchangeDTO goodExchange, Recipient recipient) {
        // 用户本次兑换数量
        Integer number = goodExchange.getNumber();
        Integer goodId = goodExchange.getGoodId();
        TGoods good = lambdaQuery().eq(TGoods::getId, goodId).one();
        if (null == good) {
            return R.exchangeError("商品不存在,请稍后重试!");
        }
        LoginUserParent loginUser1 = tokenService.getLoginUser1();
        if (null == loginUser1) {
            return R.tokenError("登录失效");
        }
        // 校验用户积分是否足够兑换
        TUser user = studyClient.userInfoParent().getData();
        if (null == user) {
            throw new GlobalException("用户信息获取失败!");
        }
        int needIntegral = good.getIntegral() * number;
        if (user.getIntegral() < needIntegral) {
            return R.exchangeError("兑换失败,当前剩余积分不足!");
        }
        if (null != good.getTotal()) {
            // 检查库存总数是否足够
            List<TOrder> order = orderService.lambdaQuery().eq(TOrder::getGoodsId, goodId)
                    .eq(TOrder::getDisabled, 0).list();
            int item;
            if (!order.isEmpty()) {
                item = order.stream().map(TOrder::getCount).collect(Collectors.toList())
                        .stream().mapToInt(Integer::intValue).sum();
            } else {
                item = 0;
            }
            boolean canBuy = good.getTotal() - item >= number;
            if (!canBuy) {
                return R.exchangeError("商品库存不足,兑换失败!");
//                throw new GlobalException("商品库存不足,兑换失败!");
            }
            // 检查用户兑换数量是否超过单用户最大兑换数量
            List<TOrder> orderList = orderService.lambdaQuery().eq(TOrder::getUserId, user.getId())
                    .eq(TOrder::getGoodsId, goodId).list();
            // 用户已兑换数量
            int totalNumber;
            if (orderList.isEmpty()) {
                totalNumber = 0;
            } else {
                // 该商品订单为空、订单数量未超过商品的单个用户兑换上限数量时,可以进行兑换
                totalNumber = orderList.stream().map(TOrder::getCount).collect(Collectors.toList())
                        .stream().mapToInt(Integer::intValue).sum();
            }
            boolean canExchange = true;
            if (null != good.getUserCount()) {
                if (number > good.getUserCount()) {
                    canExchange = false;
                } else {
                    canExchange = (totalNumber + number) <= good.getUserCount();
                }
            }
            if (!canExchange) {
                return R.exchangeError("兑换失败,当前兑换数量已超过最大兑换数量,剩余兑换数量为: " +
                        (good.getUserCount() - totalNumber) + "!");
            }
            // redisson分布式锁,防止超卖
            String key = String.format(RedisConstants.GOOD_STOCK, good.getId());
            RSemaphore semaphore = redissonClient.getSemaphore(key);
            // 请求超时时间 单位:毫秒
            semaphore.trySetPermits(1000);
            boolean tried = semaphore.tryAcquire(number);
            // 兑换失败,库存不足
            if (!tried) {
                semaphore.release(number);
                return R.exchangeError("当前商品库存不足");
            }
            // 兑换成功,生成订单信息、生成积分明细(积分明细需要远程调用rouyi-study服务)
            boolean result = exchangeGoodParent(goodExchange, recipient, number, goodId, needIntegral);
            if (!result) {
                semaphore.release(number);
                return R.exchangeError("商品兑换失败!");
            }
        } else {
            if (null != good.getUserCount()) {
                // 检查用户兑换数量是否超过单用户最大兑换数量
                List<TOrder> orderList = orderService.lambdaQuery().eq(TOrder::getUserId, user.getId())
                        .eq(TOrder::getGoodsId, goodId).list();
                int totalNumber;
                if (orderList.isEmpty()) {
                    totalNumber = 0;
                } else {
                    // 该商品订单为空、订单数量未超过商品的单个用户兑换上限数量时,可以进行兑换
                    totalNumber = orderList.stream().map(TOrder::getCount).collect(Collectors.toList())
                            .stream().mapToInt(Integer::intValue).sum();
                }
                Integer userCount = good.getUserCount();
                if (userCount > totalNumber) {
                    int i = userCount - totalNumber;
                    if (number > i) {
                        return R.exchangeError("兑换失败,当前兑换数量已超过最大兑换数量,剩余兑换数量为: " +
                                i + "!");
                    }
                } else {
                    return R.exchangeError("兑换失败,当前兑换数量已超过最大兑换数量!");
                }
            }
            boolean result = exchangeGoodParent(goodExchange, recipient, number, goodId, needIntegral);
            if (!result) {
                return R.exchangeError("商品兑换失败!");
            }
        }
        return R.ok();
    }
    private Boolean exchangeGood(GoodExchangeDTO goodExchange, Recipient recipient, Integer number,
                                 Integer goodId, int needIntegral) {
        // 兑换成功,生成订单信息、生成积分明细(积分明细需要远程调用rouyi-study服务)
        TOrder order = orderInfo(goodExchange, recipient, number, goodId, needIntegral);
        order.setProvince(recipient.getProvince());
        order.setCity(recipient.getCity());
        boolean result = orderService.save(order);
        // 远程调用,生成积分明细
        result = result && studyClient.addIntegralDetail(Constants.BURDEN + needIntegral, Constants.SHOPPING_CONSUME).getData();
        // 扣除用户积分
        result = result && studyClient.exchangeIntegral(needIntegral, Constants.BURDEN).getData();
        return result;
    }
 
    private Boolean exchangeGoodParent(GoodExchangeDTO goodExchange, Recipient recipient, Integer number,
                                       Integer goodId, int needIntegral) {
        // 兑换成功,生成订单信息、生成积分明细(积分明细需要远程调用rouyi-study服务)
        TOrder order = orderInfoParent(goodExchange, recipient, number, goodId, needIntegral);
        order.setProvince(recipient.getProvince());
        order.setCity(recipient.getCity());
        boolean result = orderService.save(order);
        // 远程调用,生成积分明细
        result = result && studyClient.addIntegralDetailParent(Constants.BURDEN + needIntegral, Constants.SHOPPING_CONSUME).getData();
        // 扣除用户积分
        result = result && studyClient.exchangeIntegralParent(needIntegral, Constants.BURDEN).getData();
        return result;
    }
 
 
 
    @Override
    public void updateOne(TGoods dto) {
        this.baseMapper.updateOne(dto);
    }
 
    private TOrder orderInfo(GoodExchangeDTO goodExchange, Recipient recipient, Integer number, Integer goodId, int needIntegral) {
        TOrder order = new TOrder();
        order.setOrderNumber(goodExchange.getOrderNumber());
        order.setUserId(tokenService.getLoginUserStudy().getUserid());
        order.setInsertTime(new Date());
        order.setGoodsId(goodId);
        order.setCount(number);
        order.setState(1);
        order.setRemark(goodExchange.getRemark());
        order.setIntegral(needIntegral);
        order.setConsigneeName(recipient.getRecipient());
        order.setConsigneePhone(recipient.getRecipientPhone());
        order.setConsigneeAddress(recipient.getProvince() + recipient.getCity() + recipient.getAddress());
        order.setDisabled(Boolean.FALSE);
        return order;
    }
 
    private TOrder orderInfoParent(GoodExchangeDTO goodExchange, Recipient recipient, Integer number, Integer goodId, int needIntegral) {
        TOrder order = new TOrder();
        order.setOrderNumber(goodExchange.getOrderNumber());
        order.setUserId(tokenService.getLoginUser1().getUserid());
        order.setInsertTime(new Date());
        order.setGoodsId(goodId);
        order.setCount(number);
        order.setState(1);
        order.setRemark(goodExchange.getRemark());
        order.setIntegral(needIntegral);
        order.setConsigneeName(recipient.getRecipient());
        order.setConsigneePhone(recipient.getRecipientPhone());
        order.setConsigneeAddress(recipient.getProvince() + recipient.getCity() + recipient.getAddress());
        order.setDisabled(Boolean.FALSE);
        return order;
    }
 
    private TOrder orderInfo1(GoodExchangeDTO goodExchange, Recipient recipient, Integer number, Integer goodId, int needIntegral) {
        TOrder order = new TOrder();
        order.setOrderNumber(goodExchange.getOrderNumber());
        order.setUserId(tokenService.getLoginUser1().getUserid());
        order.setInsertTime(new Date());
        order.setGoodsId(goodId);
        order.setCount(number);
        order.setState(1);
        order.setIntegral(needIntegral);
        order.setConsigneeName(recipient.getRecipient());
        order.setConsigneePhone(recipient.getRecipientPhone());
        order.setConsigneeAddress(recipient.getAddress());
        order.setDisabled(Boolean.FALSE);
        return order;
    }
}