Appearance
优惠券系统
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/coupon | GET | 优惠券列表 |
/admin/coupon | POST | 创建优惠券 |
/admin/coupon/{id} | PUT | 更新优惠券 |
/admin/coupon/{id} | DELETE | 删除优惠券 |
/admin/coupon/{id}/toggle | POST | 切换状态 |
/admin/coupon/stats | GET | 统计数据 |
前端 API
| 接口 | 方法 | 说明 |
|---|---|---|
/api/coupon/available | GET | 可领取优惠券 |
/api/coupon/claim/{id} | POST | 领取优惠券 |
/api/coupon/my | GET | 我的优惠券 |
/api/coupon/usable | GET | 可用优惠券(下单时) |
📊 数据统计
- 发放数量统计
- 使用率分析
- 核销金额统计
- 用户领取排行
⚠️ 注意事项
- 并发领取: 使用 Redis 原子操作防止超发
- 有效期: 支持固定日期和领取后 N 天两种模式
- 叠加规则: 可配置是否与其他优惠叠加
- 退款处理: 订单退款时自动返还优惠券