| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace App\Http\logic\api;
- use App\Models\UserCoupon;
- use App\Services\CouponService;
- /**
- * 优惠券业务逻辑层
- *
- * 处理优惠券相关的请求:列表获取、使用前验证
- */
- class CouponLogic extends BaseApiLogic
- {
- /** @var CouponService */
- protected $couponService;
- public function __construct()
- {
- $this->couponService = new CouponService();
- }
- /**
- * 获取用户优惠券列表(含自动发放)
- *
- * @param int $userId
- * @return array
- */
- public function getList($userId)
- {
- $result = $this->couponService->getCouponList($userId);
- // 格式化返回给前端
- $formattedList = [];
- foreach ($result['list'] as $coupon) {
- $formattedList[] = $this->formatCoupon($coupon);
- }
- $formattedNew = [];
- foreach ($result['new_issued'] as $coupon) {
- $formattedNew[] = $this->formatCoupon((object) $coupon);
- }
- return [
- 'list' => $formattedList,
- 'new_issued' => $formattedNew,
- ];
- }
- /**
- * 验证优惠券是否可用于充值
- *
- * @param int $couponId
- * @param int $userId
- * @param float $payAmt 充值金额(元)
- * @return array|false 成功返回优惠券信息,失败返回false
- */
- public function validateForPayment($couponId, $userId, $payAmt)
- {
- $validation = $this->couponService->validateCoupon($couponId, $userId, $payAmt);
- if (!$validation['valid']) {
- $this->error = $validation['error'];
- return false;
- }
- return $validation['coupon'];
- }
- /**
- * 格式化优惠券数据为前端友好格式
- *
- * @param object $coupon
- * @return array
- */
- protected function formatCoupon($coupon)
- {
- $typeLabel = $coupon->coupon_type == UserCoupon::TYPE_FIXED ? 'fixed' : 'percent';
- // 构建描述文案
- if ($coupon->coupon_type == UserCoupon::TYPE_FIXED) {
- $desc = "+{$coupon->coupon_value} bonus";
- } else {
- $desc = "+{$coupon->coupon_value}% bonus";
- if ($coupon->max_bonus > 0) {
- $desc .= " (max {$coupon->max_bonus})";
- }
- }
- return [
- 'id' => (int) $coupon->id,
- 'name' => $coupon->coupon_name,
- 'type' => $typeLabel,
- 'type_id' => (int) $coupon->coupon_type,
- 'value' => (float) $coupon->coupon_value,
- 'min_recharge' => (float) $coupon->min_recharge,
- 'max_bonus' => (float) $coupon->max_bonus,
- 'desc' => $desc,
- 'status' => (int) $coupon->status,
- 'expire_at' => $coupon->expire_at,
- 'issued_at' => $coupon->issued_at ?? '',
- 'expire_in_seconds' => $coupon->expire_in_seconds ?? 0,
- ];
- }
- }
|