CouponLogic.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Http\logic\api;
  3. use App\Models\UserCoupon;
  4. use App\Services\CouponService;
  5. /**
  6. * 优惠券业务逻辑层
  7. *
  8. * 处理优惠券相关的请求:列表获取、使用前验证
  9. */
  10. class CouponLogic extends BaseApiLogic
  11. {
  12. /** @var CouponService */
  13. protected $couponService;
  14. public function __construct()
  15. {
  16. $this->couponService = new CouponService();
  17. }
  18. /**
  19. * 获取用户优惠券列表(含自动发放)
  20. *
  21. * @param int $userId
  22. * @return array
  23. */
  24. public function getList($userId)
  25. {
  26. $result = $this->couponService->getCouponList($userId);
  27. // 格式化返回给前端
  28. $formattedList = [];
  29. foreach ($result['list'] as $coupon) {
  30. $formattedList[] = $this->formatCoupon($coupon);
  31. }
  32. $formattedNew = [];
  33. foreach ($result['new_issued'] as $coupon) {
  34. $formattedNew[] = $this->formatCoupon((object) $coupon);
  35. }
  36. return [
  37. 'list' => $formattedList,
  38. 'new_issued' => $formattedNew,
  39. ];
  40. }
  41. /**
  42. * 验证优惠券是否可用于充值
  43. *
  44. * @param int $couponId
  45. * @param int $userId
  46. * @param float $payAmt 充值金额(元)
  47. * @return array|false 成功返回优惠券信息,失败返回false
  48. */
  49. public function validateForPayment($couponId, $userId, $payAmt)
  50. {
  51. $validation = $this->couponService->validateCoupon($couponId, $userId, $payAmt);
  52. if (!$validation['valid']) {
  53. $this->error = $validation['error'];
  54. return false;
  55. }
  56. return $validation['coupon'];
  57. }
  58. /**
  59. * 格式化优惠券数据为前端友好格式
  60. *
  61. * @param object $coupon
  62. * @return array
  63. */
  64. protected function formatCoupon($coupon)
  65. {
  66. $typeLabel = $coupon->coupon_type == UserCoupon::TYPE_FIXED ? 'fixed' : 'percent';
  67. // 构建描述文案
  68. if ($coupon->coupon_type == UserCoupon::TYPE_FIXED) {
  69. $desc = "+{$coupon->coupon_value} bonus";
  70. } else {
  71. $desc = "+{$coupon->coupon_value}% bonus";
  72. if ($coupon->max_bonus > 0) {
  73. $desc .= " (max {$coupon->max_bonus})";
  74. }
  75. }
  76. return [
  77. 'id' => (int) $coupon->id,
  78. 'name' => $coupon->coupon_name,
  79. 'type' => $typeLabel,
  80. 'type_id' => (int) $coupon->coupon_type,
  81. 'value' => (float) $coupon->coupon_value,
  82. 'min_recharge' => (float) $coupon->min_recharge,
  83. 'max_bonus' => (float) $coupon->max_bonus,
  84. 'desc' => $desc,
  85. 'status' => (int) $coupon->status,
  86. 'expire_at' => $coupon->expire_at,
  87. 'issued_at' => $coupon->issued_at ?? '',
  88. 'expire_in_seconds' => $coupon->expire_in_seconds ?? 0,
  89. ];
  90. }
  91. }