1. 数据库设计 ```sql CREATE TABLE coupon_template ( id VARCHAR(32) PRIMARY KEY, name VARCHAR(64) NOT NULL, type TINYINT NOT NULL COMMENT 1-满减 2-折扣 3-无门槛, discount_amount DECIMAL(10,2), discount_rate DECIMAL(5,2), min_order_amount DECIMAL(10,2), start_time DATETIME NOT NULL, end_time DATETIME NOT NULL, total_count INT NOT NULL, remaining_count INT NOT NULL, applicable_scope VARCHAR(255) COMMENT JSON格式存储适用品类ID, user_level_limit VARCHAR(64) COMMENT 用户等级限制, status TINYINT NOT NULL COMMENT 0-未开始 1-进行中 2-已结束, create_time DATETIME NOT NULL, update_time DATETIME NOT NULL );
CREATE TABLE user_coupon ( id VARCHAR(32) PRIMARY KEY, user_id VARCHAR(32) NOT NULL, coupon_template_id VARCHAR(32) NOT NULL, status TINYINT NOT NULL COMMENT 0-未使用 1-已使用 2-已过期 3-已作废 4-已冻结, get_time DATETIME NOT NULL, use_time DATETIME, order_id VARCHAR(32), FOREIGN KEY (coupon_template_id) REFERENCES coupon_template(id) ); ```
2. 核心服务实现
优惠券领取服务 ```java @Service public class CouponReceiveService {
@Transactional public Result receiveCoupon(String userId, String templateId) { // 1. 校验优惠券模板是否存在且可领取 CouponTemplate template = couponTemplateRepository.findById(templateId) .orElseThrow(() -> new BusinessException("优惠券不存在"));
if (template.getRemainingCount() <= 0) { throw new BusinessException("优惠券已领完"); }
if (LocalDateTime.now().isBefore(template.getStartTime().toInstant() .atZone(ZoneId.systemDefault()).toLocalDateTime())) { throw new BusinessException("优惠券尚未开始发放"); }
if (LocalDateTime.now().isAfter(template.getEndTime().toInstant() .atZone(ZoneId.systemDefault()).toLocalDateTime())) { throw new BusinessException("优惠券已结束发放"); }
@Transactional public Result useCoupon(String userId, String couponId, String orderId) { // 1. 校验订单和用户关系 Order order = orderRepository.findById(orderId) .orElseThrow(() -> new BusinessException("订单不存在"));
if (!order.getUserId().equals(userId)) { throw new BusinessException("订单与用户不匹配"); }
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8192 bytes) in /www/wwwroot/www.sjwxsc.com/config/function.php on line 274