peng
1 天以前 14b3dd223d4a148a4ca681a5c542901dfe74f029
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
package cn.lili.modules.lmk.service.impl;
 
import cn.lili.common.exception.ServiceException;
import cn.lili.modules.lmk.domain.entity.CouponVirtual;
import cn.lili.modules.lmk.domain.entity.StoreCouponSingle;
import cn.lili.modules.lmk.enums.general.GenerateCouponStausEnum;
import cn.lili.modules.lmk.enums.general.StoreCouponStausEnum;
import cn.lili.modules.lmk.service.StoreCouponSingleService;
import cn.lili.modules.order.order.entity.enums.ClaimStatusEnum;
import cn.lili.modules.promotion.entity.dos.Coupon;
import cn.lili.modules.promotion.service.CouponService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.lili.modules.lmk.domain.entity.StoreCoupon;
import cn.lili.modules.lmk.mapper.StoreCouponMapper;
import cn.lili.modules.lmk.service.StoreCouponService;
import cn.lili.base.Result;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lili.modules.lmk.domain.form.StoreCouponForm;
import cn.lili.modules.lmk.domain.vo.StoreCouponVO;
import cn.lili.modules.lmk.domain.query.StoreCouponQuery;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import cn.lili.utils.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
 
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * 店铺优惠卷对应关系 服务实现类
 *
 * @author peng
 * @since 2025-09-25
 */
@Service
@RequiredArgsConstructor
public class StoreCouponServiceImpl extends ServiceImpl<StoreCouponMapper, StoreCoupon> implements StoreCouponService {
 
    private final StoreCouponMapper storeCouponMapper;
    private final RedissonClient redissonClient;
    private static final String STORE_COUPON_GENERATE = "store_coupon_generate:";
    private final CouponService couponService;
    private final StoreCouponSingleService storeCouponSingleService;
 
    /**
     * 添加
     * @param form
     * @return
     */
    @Override
    public Result add(StoreCouponForm form) {
        StoreCoupon entity = StoreCouponForm.getEntityByForm(form, null);
        baseMapper.insert(entity);
        return Result.ok("添加成功");
    }
 
    /**
     * 修改
     * @param form
     * @return
     */
    @Override
    public Result update(StoreCouponForm form) {
        StoreCoupon entity = baseMapper.selectById(form.getId());
 
        // 为空抛IllegalArgumentException,做全局异常处理
        Assert.notNull(entity, "记录不存在");
        BeanUtils.copyProperties(form, entity);
        baseMapper.updateById(entity);
        return Result.ok("修改成功");
    }
 
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public Result remove(List<String> ids) {
        baseMapper.deleteBatchIds(ids);
        return Result.ok("删除成功");
    }
 
    /**
     * id删除
     * @param id
     * @return
     */
    @Override
    public Result removeById(String id) {
        baseMapper.deleteById(id);
        return Result.ok("删除成功");
    }
 
    /**
     * 分页查询
     * @param query
     * @return
     */
    @Override
    public Result page(StoreCouponQuery query) {
        IPage<StoreCouponVO> page = PageUtil.getPage(query, StoreCouponVO.class);
        baseMapper.getPage(page, query);
        return Result.ok().data(page.getRecords()).total(page.getTotal());
    }
 
    /**
     * 根据id查找
     * @param id
     * @return
     */
    @Override
    public Result detail(String id) {
        StoreCouponVO vo = baseMapper.getById(id);
        Assert.notNull(vo, "记录不存在");
        return Result.ok().data(vo);
    }
 
    /**
     * 列表
     * @return
     */
    @Override
    public Result all() {
        List<StoreCoupon> entities = baseMapper.selectList(null);
        List<StoreCouponVO> vos = entities.stream()
                .map(entity -> StoreCouponVO.getVoByEntity(entity, null))
                .collect(Collectors.toList());
        return Result.ok().data(vos);
    }
 
    @Override
    public Result getCoupon(String id) {
        StoreCouponSingle storeCouponSingle = storeCouponSingleService.getById(id);
        StoreCoupon storeCoupon = this.getById(storeCouponSingle.getStoreCoupRef());
        if (storeCoupon == null) {
            throw new ServiceException("店铺礼品卡包不存在");
        }
        if (!StoreCouponStausEnum.ENABLE.name().equals(storeCoupon.getStatus())) {
            throw new ServiceException("店铺礼品卡包没有启用无法领取");
        }
        if (ClaimStatusEnum.CLAIM.name().equals(storeCouponSingle.getClaimStatus())) {
            throw new ServiceException("当前礼品卡包已被领取");
        }
        return Result.ok().data(storeCouponSingle);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addStoreCoupon(StoreCouponForm storeCoupon) {
        StoreCoupon entity = StoreCouponForm.getEntityByForm(storeCoupon, null);
        entity.setStatus(StoreCouponStausEnum.ENABLE.name());
        entity.setCouponClaimNum(0);
        entity.setGenerateStatus(GenerateCouponStausEnum.NOT_GENERATE.name());
        Coupon coupon = couponService.getById(entity.getCouponId());
        Integer publishNum = coupon.getPublishNum();
        //表示不限制领取数量
        if (!Integer.valueOf(0).equals(publishNum)) {
            if (publishNum < storeCoupon.getCouponNum()) {
                throw new ServiceException("优惠卷发行数量小于生成二维码数量");
            }
        }
        this.save(entity);
        return Result.ok();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result generateStoreCoupon(String id) {
        RLock redissonLock = redissonClient.getLock(STORE_COUPON_GENERATE + id);
        try {
            redissonLock.lock();
            LambdaQueryWrapper<StoreCoupon> forUpdate = Wrappers.<StoreCoupon>lambdaQuery().eq(StoreCoupon::getId, id).last("FOR UPDATE");
            StoreCoupon storeCoupon = this.getOne(forUpdate);
            if (storeCoupon == null) {
                throw new ServiceException("当前店铺优惠卷不存在无法生成");
            }
            if (!GenerateCouponStausEnum.NOT_GENERATE.name().equals(  storeCoupon.getGenerateStatus())) {
                throw new ServiceException("当前店铺优惠卷状态异常无法生成");
            }
            //生成优惠卷
            Integer couponNum = storeCoupon.getCouponNum();
            if (couponNum == null) {
                throw new ServiceException("发行数量为空不能生成");
            }
            List<StoreCouponSingle> storeCouponSingles = new ArrayList<>();
            for (int i = 1; i <= couponNum; i++) {
                StoreCouponSingle storeCouponSingle = getStoreCouponSingle(storeCoupon, i);
                storeCouponSingles.add(storeCouponSingle);
            }
            if (!storeCouponSingles.isEmpty()) {
                storeCouponSingleService.saveBatch(storeCouponSingles);
            }
            //更新状态生成状态
            storeCoupon.setGenerateStatus(GenerateCouponStausEnum.GENERATE.name());
            this.updateById(storeCoupon);
            return Result.ok();
        }finally {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    if (redissonLock.isHeldByCurrentThread()) {
                        redissonLock.unlock();
                    }
                }
                @Override
                public void afterCompletion(int status) {
                    // 确保即使在事务回滚的情况下也能释放锁
                    if (redissonLock.isHeldByCurrentThread()) {
                        redissonLock.unlock();
                    }
                }
            });
        }
    }
 
    private static StoreCouponSingle getStoreCouponSingle(StoreCoupon storeCoupon, int i) {
        StoreCouponSingle storeCouponSingle = new StoreCouponSingle();
        storeCouponSingle.setStoreCoupRef(storeCoupon.getId());
        storeCouponSingle.setStoreId(storeCoupon.getStoreId());
        storeCouponSingle.setStoreName(storeCoupon.getStoreName());
        storeCouponSingle.setCouponName(storeCoupon.getCouponName());
        storeCouponSingle.setCouponId(storeCoupon.getCouponId());
        storeCouponSingle.setClaimStatus(ClaimStatusEnum.NOT_CLAIM.name());
        storeCouponSingle.setCouponNo(String.format("%08d", i));
        return storeCouponSingle;
    }
}