萤火科技 4 лет назад
Родитель
Сommit
d05c71bdb2

+ 6 - 10
app/api/controller/MyCoupon.php

@@ -14,7 +14,6 @@ namespace app\api\controller;
 
 use app\api\model\UserCoupon as UserCouponModel;
 use app\api\service\User as UserService;
-use app\common\exception\BaseException;
 
 /**
  * 用户优惠券
@@ -25,13 +24,11 @@ class MyCoupon extends Controller
 {
     /**
      * 用户优惠券列表
-     * @return mixed
-     * @throws BaseException
-     * @throws \think\db\exception\DataNotFoundException
+     * @return \think\response\Json
+     * @throws \cores\exception\BaseException
      * @throws \think\db\exception\DbException
-     * @throws \think\db\exception\ModelNotFoundException
      */
-    public function list()
+    public function list(): \think\response\Json
     {
         $userId = UserService::getCurrentLoginUserId();
         $model = new UserCouponModel;
@@ -42,10 +39,10 @@ class MyCoupon extends Controller
     /**
      * 领取优惠券
      * @param int $couponId
-     * @return array|\think\response\Json
-     * @throws BaseException
+     * @return \think\response\Json
+     * @throws \cores\exception\BaseException
      */
-    public function receive(int $couponId)
+    public function receive(int $couponId): \think\response\Json
     {
         $model = new UserCouponModel;
         if ($model->receive($couponId)) {
@@ -53,5 +50,4 @@ class MyCoupon extends Controller
         }
         return $this->renderError($model->getError() ?: '领取失败');
     }
-
 }

+ 0 - 26
app/api/model/Coupon.php

@@ -83,30 +83,4 @@ class Coupon extends CouponModel
         }
         return $couponList;
     }
-
-    /**
-     * 验证优惠券是否可领取
-     * @return bool
-     */
-    public function checkReceive(): bool
-    {
-        if ($this['total_num'] > -1 && $this['receive_num'] >= $this['total_num']) {
-            $this->error = '优惠券已发完';
-            return false;
-        }
-        if ($this['expire_type'] == 20 && ($this->getData('end_time') + 86400) < time()) {
-            $this->error = '优惠券已过期';
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * 累计已领取数量
-     * @return mixed
-     */
-    public function setIncReceiveNum()
-    {
-        return $this->setInc($this['coupon_id'], 'receive_num', 1);
-    }
 }

+ 18 - 62
app/api/model/UserCoupon.php

@@ -13,9 +13,9 @@ declare (strict_types=1);
 namespace app\api\model;
 
 use app\api\service\User as UserService;
+use app\api\model\Coupon as CouponModel;
 use app\common\model\UserCoupon as UserCouponModel;
 use app\common\enum\coupon\CouponType as CouponTypeEnum;
-use app\common\enum\coupon\ExpireType as ExpireTypeEnum;
 use app\common\enum\coupon\ApplyRange as ApplyRangeEnum;
 use app\common\library\helper;
 use cores\exception\BaseException;
@@ -114,83 +114,39 @@ class UserCoupon extends UserCouponModel
      */
     public function receive(int $couponId): bool
     {
-        // 当前用户信息
-        $userInfo = UserService::getCurrentLoginUser(true);
+        // 当前用户ID
+        $userId = UserService::getCurrentLoginUserId(true);
         // 获取优惠券信息
-        $coupon = Coupon::detail($couponId);
+        $couponInfo = Coupon::detail($couponId);
         // 验证优惠券是否可领取
-        if (!$this->checkReceive($userInfo, $coupon)) {
+        if (!$this->checkReceive($userId, $couponInfo)) {
             return false;
         }
         // 添加领取记录
-        return $this->add($userInfo, $coupon);
-    }
-
-    /**
-     * 添加领取记录
-     * @param $user
-     * @param Coupon $coupon
-     * @return bool
-     */
-    private function add($user, Coupon $coupon): bool
-    {
-        // 计算有效期
-        if ($coupon['expire_type'] == ExpireTypeEnum::RECEIVE) {
-            $startTime = time();
-            $endTime = $startTime + ($coupon['expire_day'] * 86400);
-        } else {
-            $startTime = $coupon->getData('start_time');
-            $endTime = $coupon->getData('end_time');
-        }
-        // 整理领取记录
-        $data = [
-            'coupon_id' => $coupon['coupon_id'],
-            'name' => $coupon['name'],
-            'coupon_type' => $coupon['coupon_type'],
-            'reduce_price' => $coupon['reduce_price'],
-            'discount' => $coupon['discount'],
-            'min_price' => $coupon['min_price'],
-            'expire_type' => $coupon['expire_type'],
-            'expire_day' => $coupon['expire_day'],
-            'start_time' => $startTime,
-            'end_time' => $endTime,
-            'apply_range' => $coupon['apply_range'],
-            'apply_range_config' => $coupon['apply_range_config'],
-            'user_id' => $user['user_id'],
-            'store_id' => self::$storeId
-        ];
-        // 事务处理
-        return $this->transaction(function () use ($data, $coupon) {
-            // 添加领取记录
-            $status = $this->save($data);
-            if ($status) {
-                // 更新优惠券领取数量
-                $coupon->setIncReceiveNum();
-            }
-            return $status;
-        });
+        return $this->add($userId, $couponInfo);
     }
 
     /**
      * 验证优惠券是否可领取
-     * @param mixed $userInfo 当前登录用户信息
-     * @param Coupon $coupon 优惠券详情
+     * @param int $userId 当前用户ID
+     * @param CouponModel $couponInfo 优惠券详情
      * @return bool
      */
-    private function checkReceive($userInfo, Coupon $coupon): bool
+    private function checkReceive(int $userId, CouponModel $couponInfo): bool
     {
-        if (empty($coupon)) {
-            $this->error = '优惠券不存在';
+        if (empty($couponInfo)) {
+            $this->error = '当前优惠券不存在';
             return false;
         }
-        if (!$coupon->checkReceive()) {
-            $this->error = $coupon->getError();
+        // 验证优惠券状态是否可领取
+        $model = new CouponModel;
+        if (!$model->checkReceive($couponInfo)) {
+            $this->error = $model->getError() ?: '优惠券状态不可领取';
             return false;
         }
-        // 验证是否已领取
-        $userCouponIds = $this->getUserCouponIds($userInfo['user_id']);
-        if (in_array($coupon['coupon_id'], $userCouponIds)) {
-            $this->error = '该优惠券已领取';
+        // 验证当前用户是否已领取
+        if (static::checktUserCoupon($couponInfo['coupon_id'], $userId)) {
+            $this->error = '当前用户已领取该优惠券';
             return false;
         }
         return true;

+ 35 - 3
app/common/model/Coupon.php

@@ -117,11 +117,43 @@ class Coupon extends BaseModel
 
     /**
      * 优惠券详情
-     * @param int $couponId
-     * @return null|static
+     * @param int $couponId 优惠券ID
+     * @return static|null
      */
-    public static function detail(int $couponId)
+    public static function detail(int $couponId): ?Coupon
     {
         return self::get($couponId);
     }
+
+    /**
+     * 验证优惠券状态是否可领取
+     * @param $couponInfo
+     * @return bool
+     */
+    public function checkReceive($couponInfo): bool
+    {
+        if (empty($couponInfo)) {
+            $this->error = '当前优惠券不存在';
+            return false;
+        }
+        if ($couponInfo['total_num'] > -1 && $couponInfo['receive_num'] >= $couponInfo['total_num']) {
+            $this->error = '优惠券已发完';
+            return false;
+        }
+        if ($couponInfo['expire_type'] == 20 && ($couponInfo->getData('end_time') + 86400) < time()) {
+            $this->error = '优惠券已过期';
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * 累计优惠券已领取的数量
+     * @param int $couponId
+     * @return mixed
+     */
+    public static function setIncReceiveNum(int $couponId)
+    {
+        return (new static)->setInc($couponId, 'receive_num', 1);
+    }
 }

+ 58 - 1
app/common/model/UserCoupon.php

@@ -13,8 +13,9 @@ declare (strict_types=1);
 namespace app\common\model;
 
 use cores\BaseModel;
-
+use app\common\model\Coupon as CouponModel;
 use app\common\library\helper;
+use app\common\enum\coupon\ExpireType as ExpireTypeEnum;
 use think\model\relation\BelongsTo;
 
 /**
@@ -142,4 +143,60 @@ class UserCoupon extends BaseModel
     {
         return static::updateBase(['is_use' => (int)$isUse], ['user_coupon_id' => $userCouponId]);
     }
+
+    /**
+     * 验证指定用户是否已领取优惠券
+     * @param int $couponId 优惠券ID
+     * @param int $userId 用户ID
+     * @return bool
+     */
+    public static function checktUserCoupon(int $couponId, int $userId): bool
+    {
+        return (bool)(new static)->where('coupon_id', '=', $couponId)
+            ->where('user_id', '=', $userId)
+            ->value('user_coupon_id');
+    }
+
+    /**
+     * 添加领取记录
+     * @param int $userId 用户ID
+     * @param CouponModel $couponInfo
+     * @return bool
+     */
+    public function add(int $userId, CouponModel $couponInfo): bool
+    {
+        // 计算有效期
+        if ($couponInfo['expire_type'] == ExpireTypeEnum::RECEIVE) {
+            $startTime = time();
+            $endTime = $startTime + ($couponInfo['expire_day'] * 86400);
+        } else {
+            $startTime = $couponInfo->getData('start_time');
+            $endTime = $couponInfo->getData('end_time');
+        }
+        // 整理领取记录
+        $data = [
+            'coupon_id' => $couponInfo['coupon_id'],
+            'name' => $couponInfo['name'],
+            'coupon_type' => $couponInfo['coupon_type'],
+            'reduce_price' => $couponInfo['reduce_price'],
+            'discount' => $couponInfo['discount'],
+            'min_price' => $couponInfo['min_price'],
+            'expire_type' => $couponInfo['expire_type'],
+            'expire_day' => $couponInfo['expire_day'],
+            'start_time' => $startTime,
+            'end_time' => $endTime,
+            'apply_range' => $couponInfo['apply_range'],
+            'apply_range_config' => $couponInfo['apply_range_config'],
+            'user_id' => $userId,
+            'store_id' => self::$storeId
+        ];
+        // 事务处理
+        return $this->transaction(function () use ($data, $couponInfo) {
+            // 添加领取记录
+            $this->save($data);
+            // 累计优惠券已领取的数量
+            CouponModel::setIncReceiveNum($couponInfo['coupon_id']);
+            return true;
+        });
+    }
 }