Skip to content

优惠券系统

MineShop 的优惠券系统支持多种优惠类型,包括满减券、折扣券、无门槛券等,并提供完善的发放、核销和统计功能。

🎯 系统架构

┌─────────────────────────────────────────────────────────────┐
│                      优惠券模板 (Coupon)                      │
│              • 优惠类型、面额、使用条件                         │
│              • 有效期、发放数量、使用限制                        │
├─────────────────────────────────────────────────────────────┤
│                      用户优惠券 (CouponUser)                   │
│              • 领取记录、使用状态、过期时间                      │
└─────────────────────────────────────────────────────────────┘

✨ 核心特性

1. 优惠券类型

类型说明示例
满减券满足金额条件减免固定金额满 100 减 20
折扣券按比例折扣8 折券
无门槛券无使用条件立减 10 元
运费券抵扣运费免运费券

2. 使用条件

php
// CouponEntity.php
public function canUse(float $orderAmount, array $productIds): bool
{
    // 检查最低消费
    if ($orderAmount < $this->minAmount) {
        return false;
    }
    
    // 检查适用商品
    if (!empty($this->applicableProducts)) {
        $matched = array_intersect($productIds, $this->applicableProducts);
        if (empty($matched)) {
            return false;
        }
    }
    
    return true;
}

3. 发放控制

  • 每人限领数量
  • 总发放数量限制
  • 发放时间范围
  • 指定用户群体

🔄 状态流转

┌──────────┐    用户领取    ┌──────────┐    订单使用    ┌──────────┐
│  未领取   │ ───────────→ │  已领取   │ ───────────→ │  已使用   │
│ available│              │  claimed │              │   used   │
└──────────┘              └──────────┘              └──────────┘

                                │ 超过有效期

                          ┌──────────┐
                          │  已过期   │
                          │ expired  │
                          └──────────┘

📦 核心服务

php
// DomainCouponService.php
final class DomainCouponService extends IService
{
    /**
     * 创建优惠券
     */
    public function create(CouponEntity $entity): Coupon
    {
        return $this->repository->createFromEntity($entity);
    }

    /**
     * 删除优惠券(有发放记录时禁止删除)
     */
    public function deleteById(mixed $id): int
    {
        $issued = $this->couponUserRepository->countByCouponId($id);
        if ($issued > 0) {
            throw new \RuntimeException('已有发放记录,无法删除');
        }
        return $this->repository->deleteById($id);
    }

    /**
     * 同步使用统计
     */
    public function syncUsage(int $couponId): void
    {
        $this->repository->syncUsageStatistics($couponId);
    }
}

💻 API 接口

后台管理

接口方法说明
/admin/couponGET优惠券列表
/admin/couponPOST创建优惠券
/admin/coupon/{id}PUT更新优惠券
/admin/coupon/{id}DELETE删除优惠券
/admin/coupon/{id}/togglePOST切换状态
/admin/coupon/statsGET统计数据

前端 API

接口方法说明
/api/coupon/availableGET可领取优惠券
/api/coupon/claim/{id}POST领取优惠券
/api/coupon/myGET我的优惠券
/api/coupon/usableGET可用优惠券(下单时)

📊 数据统计

  • 发放数量统计
  • 使用率分析
  • 核销金额统计
  • 用户领取排行

⚠️ 注意事项

  1. 并发领取: 使用 Redis 原子操作防止超发
  2. 有效期: 支持固定日期和领取后 N 天两种模式
  3. 叠加规则: 可配置是否与其他优惠叠加
  4. 退款处理: 订单退款时自动返还优惠券

📚 相关文档

基于 Apache-2.0 许可发布 | 感谢 MineAdmin 提供的优秀基础框架