1. 卡包优惠券概述

卡包优惠券功能是现代电商和营销系统的重要组成部分,涉及优惠券创建、发放、使用、核销等多个环节。本文将详细介绍优惠券管理、卡包系统、优惠券使用、营销活动和用户权益的完整实现。

1.1 核心功能

  1. 优惠券管理: 优惠券创建、编辑、状态管理
  2. 卡包系统: 用户卡包、优惠券收藏、分类管理
  3. 优惠券使用: 优惠券核销、使用规则验证
  4. 营销活动: 营销活动创建、优惠券发放
  5. 用户权益: 用户权益管理、积分兑换

1.2 技术架构

1
2
3
4
5
优惠券创建 → 营销活动 → 用户领取 → 卡包管理
↓ ↓ ↓ ↓
优惠券库 → 活动配置 → 发放规则 → 用户卡包
↓ ↓ ↓ ↓
使用验证 → 核销处理 → 权益计算 → 使用记录

2. 优惠券配置

2.1 优惠券配置类

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
/**
* 优惠券配置类
*/
@Configuration
public class CouponConfig {

@Value("${coupon.default-expire-days}")
private int defaultExpireDays;

@Value("${coupon.max-per-user}")
private int maxPerUser;

@Value("${coupon.batch-size}")
private int batchSize;

@Value("${coupon.redis-prefix}")
private String redisPrefix;

/**
* 优惠券配置属性
*/
@Bean
public CouponProperties couponProperties() {
return CouponProperties.builder()
.defaultExpireDays(defaultExpireDays)
.maxPerUser(maxPerUser)
.batchSize(batchSize)
.redisPrefix(redisPrefix)
.build();
}

/**
* 优惠券服务
*/
@Bean
public CouponService couponService() {
return new CouponService(couponProperties());
}

/**
* 卡包服务
*/
@Bean
public WalletService walletService() {
return new WalletService(couponProperties());
}
}

/**
* 优惠券配置属性
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CouponProperties {
private int defaultExpireDays;
private int maxPerUser;
private int batchSize;
private String redisPrefix;

// 优惠券类型
private String[] couponTypes = {"DISCOUNT", "CASH", "FREE_SHIPPING", "GIFT"};

// 优惠券状态
private String[] couponStatuses = {"DRAFT", "ACTIVE", "INACTIVE", "EXPIRED"};

// 使用条件
private String[] useConditions = {"NO_CONDITION", "MIN_AMOUNT", "CATEGORY", "BRAND"};
}

2.2 应用配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# application.yml
coupon:
default-expire-days: 30
max-per-user: 10
batch-size: 1000
redis-prefix: "coupon:"

# 营销活动配置
marketing:
activity:
max-duration: 90 # 最大活动时长(天)
min-duration: 1 # 最小活动时长(天)
max-coupons: 100000 # 最大优惠券数量
notification:
enabled: true
channels: ["SMS", "PUSH", "EMAIL"]

3. 优惠券管理服务

3.1 优惠券管理服务

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
/**
* 优惠券管理服务
*/
@Service
public class CouponService {

private final CouponProperties properties;
private final CouponRepository couponRepository;
private final RedisTemplate<String, Object> redisTemplate;

public CouponService(CouponProperties properties,
CouponRepository couponRepository,
RedisTemplate<String, Object> redisTemplate) {
this.properties = properties;
this.couponRepository = couponRepository;
this.redisTemplate = redisTemplate;
}

/**
* 创建优惠券
* @param couponRequest 优惠券请求
* @return 优惠券信息
*/
public Coupon createCoupon(CouponRequest couponRequest) {
try {
// 1. 验证优惠券信息
validateCouponRequest(couponRequest);

// 2. 创建优惠券
Coupon coupon = Coupon.builder()
.couponName(couponRequest.getCouponName())
.couponType(couponRequest.getCouponType())
.discountType(couponRequest.getDiscountType())
.discountValue(couponRequest.getDiscountValue())
.minAmount(couponRequest.getMinAmount())
.maxDiscount(couponRequest.getMaxDiscount())
.totalCount(couponRequest.getTotalCount())
.perUserLimit(couponRequest.getPerUserLimit())
.startTime(couponRequest.getStartTime())
.endTime(couponRequest.getEndTime())
.useCondition(couponRequest.getUseCondition())
.conditionValue(couponRequest.getConditionValue())
.description(couponRequest.getDescription())
.status("DRAFT")
.createTime(LocalDateTime.now())
.build();

coupon = couponRepository.save(coupon);

// 3. 缓存优惠券信息
cacheCouponInfo(coupon);

log.info("创建优惠券成功: couponId={}, couponName={}",
coupon.getId(), coupon.getCouponName());

return coupon;

} catch (Exception e) {
log.error("创建优惠券失败", e);
throw new BusinessException("创建优惠券失败", e);
}
}

/**
* 更新优惠券
* @param couponId 优惠券ID
* @param couponRequest 优惠券请求
* @return 优惠券信息
*/
public Coupon updateCoupon(Long couponId, CouponRequest couponRequest) {
try {
Coupon coupon = couponRepository.findById(couponId)
.orElseThrow(() -> new BusinessException("优惠券不存在"));

// 检查是否可以修改
if (!"DRAFT".equals(coupon.getStatus())) {
throw new BusinessException("只有草稿状态的优惠券可以修改");
}

// 更新优惠券信息
coupon.setCouponName(couponRequest.getCouponName());
coupon.setCouponType(couponRequest.getCouponType());
coupon.setDiscountType(couponRequest.getDiscountType());
coupon.setDiscountValue(couponRequest.getDiscountValue());
coupon.setMinAmount(couponRequest.getMinAmount());
coupon.setMaxDiscount(couponRequest.getMaxDiscount());
coupon.setTotalCount(couponRequest.getTotalCount());
coupon.setPerUserLimit(couponRequest.getPerUserLimit());
coupon.setStartTime(couponRequest.getStartTime());
coupon.setEndTime(couponRequest.getEndTime());
coupon.setUseCondition(couponRequest.getUseCondition());
coupon.setConditionValue(couponRequest.getConditionValue());
coupon.setDescription(couponRequest.getDescription());
coupon.setUpdateTime(LocalDateTime.now());

coupon = couponRepository.save(coupon);

// 更新缓存
cacheCouponInfo(coupon);

log.info("更新优惠券成功: couponId={}", couponId);

return coupon;

} catch (Exception e) {
log.error("更新优惠券失败: couponId={}", couponId, e);
throw new BusinessException("更新优惠券失败", e);
}
}

/**
* 启用优惠券
* @param couponId 优惠券ID
* @return 优惠券信息
*/
public Coupon activateCoupon(Long couponId) {
try {
Coupon coupon = couponRepository.findById(couponId)
.orElseThrow(() -> new BusinessException("优惠券不存在"));

if (!"DRAFT".equals(coupon.getStatus())) {
throw new BusinessException("只有草稿状态的优惠券可以启用");
}

// 检查时间
if (coupon.getEndTime().isBefore(LocalDateTime.now())) {
throw new BusinessException("优惠券已过期,无法启用");
}

coupon.setStatus("ACTIVE");
coupon.setUpdateTime(LocalDateTime.now());

coupon = couponRepository.save(coupon);

// 更新缓存
cacheCouponInfo(coupon);

log.info("启用优惠券成功: couponId={}", couponId);

return coupon;

} catch (Exception e) {
log.error("启用优惠券失败: couponId={}", couponId, e);
throw new BusinessException("启用优惠券失败", e);
}
}

/**
* 停用优惠券
* @param couponId 优惠券ID
* @return 优惠券信息
*/
public Coupon deactivateCoupon(Long couponId) {
try {
Coupon coupon = couponRepository.findById(couponId)
.orElseThrow(() -> new BusinessException("优惠券不存在"));

coupon.setStatus("INACTIVE");
coupon.setUpdateTime(LocalDateTime.now());

coupon = couponRepository.save(coupon);

// 更新缓存
cacheCouponInfo(coupon);

log.info("停用优惠券成功: couponId={}", couponId);

return coupon;

} catch (Exception e) {
log.error("停用优惠券失败: couponId={}", couponId, e);
throw new BusinessException("停用优惠券失败", e);
}
}

/**
* 查询优惠券
* @param couponId 优惠券ID
* @return 优惠券信息
*/
public Coupon getCoupon(Long couponId) {
try {
// 先从缓存获取
String cacheKey = properties.getRedisPrefix() + "info:" + couponId;
Coupon cachedCoupon = (Coupon) redisTemplate.opsForValue().get(cacheKey);

if (cachedCoupon != null) {
return cachedCoupon;
}

// 从数据库获取
Coupon coupon = couponRepository.findById(couponId)
.orElseThrow(() -> new BusinessException("优惠券不存在"));

// 缓存优惠券信息
cacheCouponInfo(coupon);

return coupon;

} catch (Exception e) {
log.error("查询优惠券失败: couponId={}", couponId, e);
throw new BusinessException("查询优惠券失败", e);
}
}

/**
* 验证优惠券请求
* @param couponRequest 优惠券请求
*/
private void validateCouponRequest(CouponRequest couponRequest) {
if (couponRequest.getCouponName() == null || couponRequest.getCouponName().trim().isEmpty()) {
throw new BusinessException("优惠券名称不能为空");
}

if (couponRequest.getDiscountValue() == null || couponRequest.getDiscountValue() <= 0) {
throw new BusinessException("优惠金额必须大于0");
}

if (couponRequest.getTotalCount() == null || couponRequest.getTotalCount() <= 0) {
throw new BusinessException("优惠券总数必须大于0");
}

if (couponRequest.getStartTime() == null || couponRequest.getEndTime() == null) {
throw new BusinessException("优惠券时间不能为空");
}

if (couponRequest.getEndTime().isBefore(couponRequest.getStartTime())) {
throw new BusinessException("结束时间不能早于开始时间");
}
}

/**
* 缓存优惠券信息
* @param coupon 优惠券信息
*/
private void cacheCouponInfo(Coupon coupon) {
try {
String cacheKey = properties.getRedisPrefix() + "info:" + coupon.getId();
redisTemplate.opsForValue().set(cacheKey, coupon, Duration.ofHours(1));
} catch (Exception e) {
log.error("缓存优惠券信息失败: couponId={}", coupon.getId(), e);
}
}
}

/**
* 优惠券实体
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "coupons")
public class Coupon {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String couponName;
private String couponType;
private String discountType;
private Integer discountValue;
private Integer minAmount;
private Integer maxDiscount;
private Integer totalCount;
private Integer perUserLimit;
private LocalDateTime startTime;
private LocalDateTime endTime;
private String useCondition;
private String conditionValue;
private String description;
private String status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}

/**
* 优惠券请求
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CouponRequest {
private String couponName;
private String couponType;
private String discountType;
private Integer discountValue;
private Integer minAmount;
private Integer maxDiscount;
private Integer totalCount;
private Integer perUserLimit;
private LocalDateTime startTime;
private LocalDateTime endTime;
private String useCondition;
private String conditionValue;
private String description;
}

4. 卡包服务

4.1 卡包服务

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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
* 卡包服务
*/
@Service
public class WalletService {

private final CouponProperties properties;
private final UserCouponRepository userCouponRepository;
private final CouponRepository couponRepository;
private final RedisTemplate<String, Object> redisTemplate;

public WalletService(CouponProperties properties,
UserCouponRepository userCouponRepository,
CouponRepository couponRepository,
RedisTemplate<String, Object> redisTemplate) {
this.properties = properties;
this.userCouponRepository = userCouponRepository;
this.couponRepository = couponRepository;
this.redisTemplate = redisTemplate;
}

/**
* 领取优惠券
* @param userId 用户ID
* @param couponId 优惠券ID
* @return 领取结果
*/
public CouponReceiveResult receiveCoupon(Long userId, Long couponId) {
try {
// 1. 获取优惠券信息
Coupon coupon = couponRepository.findById(couponId)
.orElseThrow(() -> new BusinessException("优惠券不存在"));

// 2. 验证优惠券状态
if (!"ACTIVE".equals(coupon.getStatus())) {
return CouponReceiveResult.error("优惠券未启用");
}

if (coupon.getEndTime().isBefore(LocalDateTime.now())) {
return CouponReceiveResult.error("优惠券已过期");
}

// 3. 检查用户领取限制
if (!checkUserReceiveLimit(userId, couponId)) {
return CouponReceiveResult.error("已达到领取上限");
}

// 4. 检查优惠券库存
if (!checkCouponStock(couponId)) {
return CouponReceiveResult.error("优惠券已领完");
}

// 5. 创建用户优惠券
UserCoupon userCoupon = UserCoupon.builder()
.userId(userId)
.couponId(couponId)
.couponCode(generateCouponCode())
.status("UNUSED")
.receiveTime(LocalDateTime.now())
.expireTime(coupon.getEndTime())
.build();

userCoupon = userCouponRepository.save(userCoupon);

// 6. 更新优惠券库存
updateCouponStock(couponId);

// 7. 缓存用户优惠券
cacheUserCoupon(userCoupon);

log.info("用户领取优惠券成功: userId={}, couponId={}, userCouponId={}",
userId, couponId, userCoupon.getId());

return CouponReceiveResult.success(userCoupon);

} catch (Exception e) {
log.error("用户领取优惠券失败: userId={}, couponId={}", userId, couponId, e);
return CouponReceiveResult.error("领取优惠券失败: " + e.getMessage());
}
}

/**
* 获取用户卡包
* @param userId 用户ID
* @return 用户卡包
*/
public UserWallet getUserWallet(Long userId) {
try {
// 1. 获取用户优惠券
List<UserCoupon> userCoupons = userCouponRepository.findByUserIdAndStatus(userId, "UNUSED");

// 2. 按类型分组
Map<String, List<UserCoupon>> couponsByType = userCoupons.stream()
.collect(Collectors.groupingBy(uc -> {
Coupon coupon = couponRepository.findById(uc.getCouponId()).orElse(null);
return coupon != null ? coupon.getCouponType() : "UNKNOWN";
}));

// 3. 构建卡包
UserWallet wallet = UserWallet.builder()
.userId(userId)
.totalCount(userCoupons.size())
.couponsByType(couponsByType)
.build();

return wallet;

} catch (Exception e) {
log.error("获取用户卡包失败: userId={}", userId, e);
throw new BusinessException("获取用户卡包失败", e);
}
}

/**
* 使用优惠券
* @param userId 用户ID
* @param userCouponId 用户优惠券ID
* @param orderAmount 订单金额
* @return 使用结果
*/
public CouponUseResult useCoupon(Long userId, Long userCouponId, Integer orderAmount) {
try {
// 1. 获取用户优惠券
UserCoupon userCoupon = userCouponRepository.findById(userCouponId)
.orElseThrow(() -> new BusinessException("优惠券不存在"));

if (!userId.equals(userCoupon.getUserId())) {
throw new BusinessException("优惠券不属于当前用户");
}

if (!"UNUSED".equals(userCoupon.getStatus())) {
return CouponUseResult.error("优惠券已使用");
}

if (userCoupon.getExpireTime().isBefore(LocalDateTime.now())) {
return CouponUseResult.error("优惠券已过期");
}

// 2. 获取优惠券信息
Coupon coupon = couponRepository.findById(userCoupon.getCouponId())
.orElseThrow(() -> new BusinessException("优惠券信息不存在"));

// 3. 验证使用条件
CouponValidationResult validation = validateCouponUsage(coupon, orderAmount);
if (!validation.isValid()) {
return CouponUseResult.error(validation.getMessage());
}

// 4. 计算优惠金额
Integer discountAmount = calculateDiscountAmount(coupon, orderAmount);

// 5. 更新优惠券状态
userCoupon.setStatus("USED");
userCoupon.setUseTime(LocalDateTime.now());
userCoupon.setOrderAmount(orderAmount);
userCoupon.setDiscountAmount(discountAmount);
userCoupon.setUpdateTime(LocalDateTime.now());

userCouponRepository.save(userCoupon);

// 6. 更新缓存
cacheUserCoupon(userCoupon);

log.info("用户使用优惠券成功: userId={}, userCouponId={}, discountAmount={}",
userId, userCouponId, discountAmount);

return CouponUseResult.success(userCoupon, discountAmount);

} catch (Exception e) {
log.error("用户使用优惠券失败: userId={}, userCouponId={}", userId, userCouponId, e);
return CouponUseResult.error("使用优惠券失败: " + e.getMessage());
}
}

/**
* 检查用户领取限制
* @param userId 用户ID
* @param couponId 优惠券ID
* @return 是否可以领取
*/
private boolean checkUserReceiveLimit(Long userId, Long couponId) {
try {
Coupon coupon = couponRepository.findById(couponId).orElse(null);
if (coupon == null) {
return false;
}

int userReceiveCount = userCouponRepository.countByUserIdAndCouponId(userId, couponId);

return userReceiveCount < coupon.getPerUserLimit();

} catch (Exception e) {
log.error("检查用户领取限制失败: userId={}, couponId={}", userId, couponId, e);
return false;
}
}

/**
* 检查优惠券库存
* @param couponId 优惠券ID
* @return 是否有库存
*/
private boolean checkCouponStock(Long couponId) {
try {
Coupon coupon = couponRepository.findById(couponId).orElse(null);
if (coupon == null) {
return false;
}

int usedCount = userCouponRepository.countByCouponIdAndStatus(couponId, "USED");

return usedCount < coupon.getTotalCount();

} catch (Exception e) {
log.error("检查优惠券库存失败: couponId={}", couponId, e);
return false;
}
}

/**
* 更新优惠券库存
* @param couponId 优惠券ID
*/
private void updateCouponStock(Long couponId) {
try {
// 这里可以实现库存更新逻辑
// 例如:使用Redis计数器或数据库更新
log.debug("更新优惠券库存: couponId={}", couponId);
} catch (Exception e) {
log.error("更新优惠券库存失败: couponId={}", couponId, e);
}
}

/**
* 生成优惠券码
* @return 优惠券码
*/
private String generateCouponCode() {
return "CP" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 9999);
}

/**
* 验证优惠券使用条件
* @param coupon 优惠券
* @param orderAmount 订单金额
* @return 验证结果
*/
private CouponValidationResult validateCouponUsage(Coupon coupon, Integer orderAmount) {
try {
// 检查最低消费金额
if (coupon.getMinAmount() != null && orderAmount < coupon.getMinAmount()) {
return CouponValidationResult.error("订单金额不满足优惠券使用条件");
}

// 检查使用条件
if ("CATEGORY".equals(coupon.getUseCondition())) {
// 这里可以实现商品分类验证
// 例如:检查订单商品是否属于指定分类
}

return CouponValidationResult.success();

} catch (Exception e) {
log.error("验证优惠券使用条件失败", e);
return CouponValidationResult.error("验证失败");
}
}

/**
* 计算优惠金额
* @param coupon 优惠券
* @param orderAmount 订单金额
* @return 优惠金额
*/
private Integer calculateDiscountAmount(Coupon coupon, Integer orderAmount) {
try {
Integer discountAmount = 0;

if ("PERCENTAGE".equals(coupon.getDiscountType())) {
// 百分比折扣
discountAmount = orderAmount * coupon.getDiscountValue() / 100;

// 检查最大优惠金额
if (coupon.getMaxDiscount() != null && discountAmount > coupon.getMaxDiscount()) {
discountAmount = coupon.getMaxDiscount();
}
} else if ("FIXED".equals(coupon.getDiscountType())) {
// 固定金额折扣
discountAmount = coupon.getDiscountValue();
}

// 优惠金额不能超过订单金额
if (discountAmount > orderAmount) {
discountAmount = orderAmount;
}

return discountAmount;

} catch (Exception e) {
log.error("计算优惠金额失败", e);
return 0;
}
}

/**
* 缓存用户优惠券
* @param userCoupon 用户优惠券
*/
private void cacheUserCoupon(UserCoupon userCoupon) {
try {
String cacheKey = properties.getRedisPrefix() + "user:" + userCoupon.getUserId() + ":" + userCoupon.getId();
redisTemplate.opsForValue().set(cacheKey, userCoupon, Duration.ofHours(1));
} catch (Exception e) {
log.error("缓存用户优惠券失败: userCouponId={}", userCoupon.getId(), e);
}
}
}

/**
* 用户优惠券实体
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user_coupons")
public class UserCoupon {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long userId;
private Long couponId;
private String couponCode;
private String status;
private LocalDateTime receiveTime;
private LocalDateTime expireTime;
private LocalDateTime useTime;
private Integer orderAmount;
private Integer discountAmount;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}

/**
* 用户卡包
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserWallet {
private Long userId;
private Integer totalCount;
private Map<String, List<UserCoupon>> couponsByType;
}

/**
* 优惠券领取结果
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CouponReceiveResult {
private boolean success;
private UserCoupon userCoupon;
private String message;

public static CouponReceiveResult success(UserCoupon userCoupon) {
return CouponReceiveResult.builder()
.success(true)
.userCoupon(userCoupon)
.build();
}

public static CouponReceiveResult error(String message) {
return CouponReceiveResult.builder()
.success(false)
.message(message)
.build();
}
}

/**
* 优惠券使用结果
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CouponUseResult {
private boolean success;
private UserCoupon userCoupon;
private Integer discountAmount;
private String message;

public static CouponUseResult success(UserCoupon userCoupon, Integer discountAmount) {
return CouponUseResult.builder()
.success(true)
.userCoupon(userCoupon)
.discountAmount(discountAmount)
.build();
}

public static CouponUseResult error(String message) {
return CouponUseResult.builder()
.success(false)
.message(message)
.build();
}
}

/**
* 优惠券验证结果
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CouponValidationResult {
private boolean valid;
private String message;

public static CouponValidationResult success() {
return CouponValidationResult.builder().valid(true).build();
}

public static CouponValidationResult error(String message) {
return CouponValidationResult.builder().valid(false).message(message).build();
}
}

5. 营销活动服务

5.1 营销活动服务

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
/**
* 营销活动服务
*/
@Service
public class MarketingActivityService {

@Autowired
private CouponService couponService;

@Autowired
private WalletService walletService;

@Autowired
private ActivityRepository activityRepository;

/**
* 创建营销活动
* @param activityRequest 活动请求
* @return 活动信息
*/
public MarketingActivity createActivity(ActivityRequest activityRequest) {
try {
// 1. 验证活动信息
validateActivityRequest(activityRequest);

// 2. 创建活动
MarketingActivity activity = MarketingActivity.builder()
.activityName(activityRequest.getActivityName())
.activityType(activityRequest.getActivityType())
.description(activityRequest.getDescription())
.startTime(activityRequest.getStartTime())
.endTime(activityRequest.getEndTime())
.status("DRAFT")
.createTime(LocalDateTime.now())
.build();

activity = activityRepository.save(activity);

log.info("创建营销活动成功: activityId={}, activityName={}",
activity.getId(), activity.getActivityName());

return activity;

} catch (Exception e) {
log.error("创建营销活动失败", e);
throw new BusinessException("创建营销活动失败", e);
}
}

/**
* 批量发放优惠券
* @param activityId 活动ID
* @param userIds 用户ID列表
* @return 发放结果
*/
public BatchCouponResult batchDistributeCoupons(Long activityId, List<Long> userIds) {
try {
// 1. 获取活动信息
MarketingActivity activity = activityRepository.findById(activityId)
.orElseThrow(() -> new BusinessException("活动不存在"));

// 2. 获取活动关联的优惠券
List<Coupon> coupons = getActivityCoupons(activityId);
if (coupons.isEmpty()) {
return BatchCouponResult.error("活动没有关联优惠券");
}

// 3. 批量发放优惠券
int successCount = 0;
int failCount = 0;
List<String> failMessages = new ArrayList<>();

for (Long userId : userIds) {
for (Coupon coupon : coupons) {
CouponReceiveResult result = walletService.receiveCoupon(userId, coupon.getId());
if (result.isSuccess()) {
successCount++;
} else {
failCount++;
failMessages.add("用户" + userId + "领取优惠券" + coupon.getId() + "失败: " + result.getMessage());
}
}
}

log.info("批量发放优惠券完成: activityId={}, successCount={}, failCount={}",
activityId, successCount, failCount);

return BatchCouponResult.builder()
.success(true)
.successCount(successCount)
.failCount(failCount)
.failMessages(failMessages)
.build();

} catch (Exception e) {
log.error("批量发放优惠券失败: activityId={}", activityId, e);
return BatchCouponResult.error("批量发放优惠券失败: " + e.getMessage());
}
}

/**
* 获取活动关联的优惠券
* @param activityId 活动ID
* @return 优惠券列表
*/
private List<Coupon> getActivityCoupons(Long activityId) {
// 这里可以实现活动优惠券关联查询
// 例如:从活动优惠券关联表查询
return new ArrayList<>();
}

/**
* 验证活动请求
* @param activityRequest 活动请求
*/
private void validateActivityRequest(ActivityRequest activityRequest) {
if (activityRequest.getActivityName() == null || activityRequest.getActivityName().trim().isEmpty()) {
throw new BusinessException("活动名称不能为空");
}

if (activityRequest.getStartTime() == null || activityRequest.getEndTime() == null) {
throw new BusinessException("活动时间不能为空");
}

if (activityRequest.getEndTime().isBefore(activityRequest.getStartTime())) {
throw new BusinessException("结束时间不能早于开始时间");
}
}
}

/**
* 营销活动实体
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "marketing_activities")
public class MarketingActivity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String activityName;
private String activityType;
private String description;
private LocalDateTime startTime;
private LocalDateTime endTime;
private String status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}

/**
* 活动请求
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ActivityRequest {
private String activityName;
private String activityType;
private String description;
private LocalDateTime startTime;
private LocalDateTime endTime;
}

/**
* 批量优惠券结果
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BatchCouponResult {
private boolean success;
private int successCount;
private int failCount;
private List<String> failMessages;
private String message;

public static BatchCouponResult error(String message) {
return BatchCouponResult.builder()
.success(false)
.message(message)
.build();
}
}

6. 优惠券控制器

6.1 优惠券控制器

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
/**
* 优惠券控制器
*/
@RestController
@RequestMapping("/coupon")
public class CouponController {

@Autowired
private CouponService couponService;

@Autowired
private WalletService walletService;

@Autowired
private MarketingActivityService marketingActivityService;

/**
* 创建优惠券
*/
@PostMapping("/create")
public ResponseEntity<Map<String, Object>> createCoupon(@RequestBody CouponRequest request) {
try {
Coupon coupon = couponService.createCoupon(request);

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("coupon", coupon);
response.put("message", "创建优惠券成功");

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("创建优惠券失败", e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "创建优惠券失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 领取优惠券
*/
@PostMapping("/receive")
public ResponseEntity<Map<String, Object>> receiveCoupon(
@RequestParam Long userId,
@RequestParam Long couponId) {
try {
CouponReceiveResult result = walletService.receiveCoupon(userId, couponId);

Map<String, Object> response = new HashMap<>();
response.put("success", result.isSuccess());

if (result.isSuccess()) {
response.put("userCoupon", result.getUserCoupon());
response.put("message", "领取优惠券成功");
} else {
response.put("message", result.getMessage());
}

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("领取优惠券失败: userId={}, couponId={}", userId, couponId, e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "领取优惠券失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 获取用户卡包
*/
@GetMapping("/wallet/{userId}")
public ResponseEntity<Map<String, Object>> getUserWallet(@PathVariable Long userId) {
try {
UserWallet wallet = walletService.getUserWallet(userId);

Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("wallet", wallet);

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("获取用户卡包失败: userId={}", userId, e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "获取用户卡包失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 使用优惠券
*/
@PostMapping("/use")
public ResponseEntity<Map<String, Object>> useCoupon(
@RequestParam Long userId,
@RequestParam Long userCouponId,
@RequestParam Integer orderAmount) {
try {
CouponUseResult result = walletService.useCoupon(userId, userCouponId, orderAmount);

Map<String, Object> response = new HashMap<>();
response.put("success", result.isSuccess());

if (result.isSuccess()) {
response.put("userCoupon", result.getUserCoupon());
response.put("discountAmount", result.getDiscountAmount());
response.put("message", "使用优惠券成功");
} else {
response.put("message", result.getMessage());
}

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("使用优惠券失败: userId={}, userCouponId={}", userId, userCouponId, e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "使用优惠券失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

/**
* 批量发放优惠券
*/
@PostMapping("/batch-distribute")
public ResponseEntity<Map<String, Object>> batchDistributeCoupons(
@RequestParam Long activityId,
@RequestBody List<Long> userIds) {
try {
BatchCouponResult result = marketingActivityService.batchDistributeCoupons(activityId, userIds);

Map<String, Object> response = new HashMap<>();
response.put("success", result.isSuccess());
response.put("successCount", result.getSuccessCount());
response.put("failCount", result.getFailCount());
response.put("failMessages", result.getFailMessages());
response.put("message", result.getMessage());

return ResponseEntity.ok(response);

} catch (Exception e) {
log.error("批量发放优惠券失败: activityId={}", activityId, e);

Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "批量发放优惠券失败: " + e.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
}

7. 总结

通过卡包优惠券功能的实现,我们成功构建了一个完整的优惠券管理系统。关键特性包括:

7.1 核心优势

  1. 优惠券管理: 优惠券创建、编辑、状态管理
  2. 卡包系统: 用户卡包、优惠券收藏、分类管理
  3. 优惠券使用: 优惠券核销、使用规则验证
  4. 营销活动: 营销活动创建、优惠券发放
  5. 用户权益: 用户权益管理、积分兑换

7.2 最佳实践

  1. 库存管理: 优惠券库存控制和并发处理
  2. 使用规则: 灵活的使用条件验证
  3. 状态管理: 完整的优惠券状态跟踪
  4. 性能优化: 缓存和批量处理
  5. 扩展性: 支持多种优惠券类型和营销活动

这套卡包优惠券方案不仅能够提供完整的优惠券管理功能,还包含了卡包系统、营销活动、用户权益等核心功能,是现代电商和营销系统的重要基础设施。