Bläddra i källkod

增加优惠券领取接口

林海涛 1 år sedan
förälder
incheckning
e2200734a8

+ 2 - 2
app/adminapi/lists/coupon/CouponRulesLists.php

@@ -40,8 +40,8 @@ class CouponRulesLists extends BaseAdminDataLists implements ListsSearchInterfac
     public function setSearch(): array
     {
         return [
-            '=' => ['amount', 'amount_require', 'begin_use', 'discount_ratio', 'event_name', 'expire_time', 'max_deductible_price', 'mold_type', 'server_category_name', 'voucher_status', 'voucher_count'],
-
+            '=' => ['amount', 'amount_require',  'max_deductible_price', 'mold_type', 'server_category_name', 'coupon_type','voucher_status', 'voucher_count'],
+            '%like%' => ['event_name'],
         ];
     }
 

+ 27 - 0
app/api/controller/UserCouponController.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace app\api\controller;
+
+use app\api\lists\UserCouponLists;
+use app\api\logic\UserCouponLogic;
+use app\api\validate\UserCouponValidate;
+
+class UserCouponController extends BaseApiController
+{
+    public function lists()
+    {
+        return $this->dataLists(new UserCouponLists());
+    }
+
+    public function add()
+    {
+        $params = (new UserCouponValidate())->post()->goCheck('add',[
+            'user_id'=>$this->userId
+        ]);
+        $result = UserCouponLogic::add($params);
+        if (false !== $result) {
+            return $this->success('领取成功'.implode('\n',$result), [], 1, 1);
+        }
+        return $this->fail(UserCouponLogic::getError());
+    }
+}

+ 62 - 0
app/api/lists/UserCouponLists.php

@@ -0,0 +1,62 @@
+<?php
+namespace app\api\lists;
+
+use app\common\lists\ListsSearchInterface;
+use app\common\model\coupon\UserCoupon;
+use think\db\Query;
+
+class UserCouponLists extends  BaseApiDataLists implements ListsSearchInterface
+{
+    public function setSearch(): array
+    {
+        return [
+            '=' => ['user_id'],
+        ];
+    }
+    public function queryWhere(){
+        $where = [];
+        if(isset($this->params['voucher_status']) && is_array($this->params['voucher_status'])){
+            $where[] = ['voucher_status','IN',$this->params['voucher_status']];
+        }
+        $where[] = ['user_id','=',$this->userId];
+        return $where;
+    }
+    public function lists(): array
+    {
+        $data = UserCoupon::with(['couponRules'=>function(Query $query){
+                $query->withoutField(['voucher_status','voucher_count']);
+                $query->with(['couponWithCategory'=>function(Query $query){
+                        $query->field('id,name');
+                }]);
+            }])
+            ->where($this->searchWhere)
+            ->where($this->queryWhere())
+            ->field(['id', 'user_id', 'coupon_id', 'voucher_status','voucher_count'])
+            ->limit($this->limitOffset, $this->limitLength)
+            ->order(['id' => 'desc'])
+            ->select()
+            ->toArray();
+        $couponIds = [];
+        foreach($data as $k => $v){
+            if($v['couponRules']){
+                if($v['voucher_status'] !=2 &&($v['couponRules']['begin_use'] <time() || $data['couponRules']['expire_time'] > time())){
+                    $couponIds[] = $v['coupon_id'];
+                    $v['voucher_status'] = 2;
+                }
+                $v['couponRules']['begin_use'] = date("Y-m-d H:i:s",$v['couponRules']['begin_use'] );
+                $v['couponRules']['expire_time'] = date("Y-m-d H:i:s",$v['couponRules']['expire_time'] );
+                $v['couponRules']['goods_category_ids'] = array_column($v['couponRules']['couponWithCategory'],'id');
+                $data[$k] = $v;
+            }
+        }
+        if(!empty($couponIds)){
+            UserCoupon::whereIn('coupon_id',$couponIds)->update(['voucher_status'=>2]);
+        }
+        return $data;
+    }
+
+    public function count(): int
+    {
+        return UserCoupon::where($this->searchWhere)->count();
+    }
+}

+ 55 - 0
app/api/logic/UserCouponLogic.php

@@ -0,0 +1,55 @@
+<?php
+namespace app\api\logic;
+use app\common\logic\BaseLogic;
+use app\common\model\coupon\CouponRules;
+use app\common\model\coupon\UserCoupon;
+use think\facade\Db;
+
+/**
+ * @author 林海涛
+ * @date 2024/7/18 下午4:49
+ */
+class UserCouponLogic extends BaseLogic
+{
+    public static function add($params)
+    {
+        Db::startTrans();
+        try{
+            $errMsgArr = [];
+            $rules = CouponRules::whereIn('id',$params['coupon_ids'])->lock(true)->select();
+            $userCoupon = UserCoupon::where('user_id',$params['user_id'])
+                ->whereIn('coupon_id',$params['coupon_ids'])
+                ->where('voucher_count','>',0)
+                ->select();
+            $updateData = [];
+            $createData = [];
+            foreach($rules as $v) {
+                if ($v->expire_time < time()) {
+                    $errMsgArr[]  = $v->event_name .'已过期';
+                    continue;
+                }
+                if($v->voucher_status == 2){
+                    $errMsgArr[] = $v->event_name .'已设置为过期';
+                    continue;
+                }
+                if($userCoupon->where('coupon_id',$v->id)->count()){
+                    $errMsgArr[] = $v->event_name . '已领取';
+                    continue;
+                }
+                $updateData[$v->id] = ['voucher_count' => --$v->voucher_count];
+                $createData[] = ['user_id'=>$params['user_id'],'coupon_id' => $v->id,'voucher_count' =>1];
+            }
+            CouponRules::updateWhenCase($updateData);
+            if(!empty($createData)){
+                (new UserCoupon())->saveAll($createData);
+            }
+            Db::commit();
+            return $errMsgArr;
+        }catch(\Exception $e){
+            Db::rollback();
+            self::setError($e->getMessage());
+            return false;
+        }
+
+    }
+}

+ 20 - 0
app/api/validate/UserCouponValidate.php

@@ -0,0 +1,20 @@
+<?php
+namespace app\api\validate;
+use app\common\validate\BaseValidate;
+
+/**
+ * @author 林海涛
+ * @date 2024/7/18 下午4:39
+ */
+class UserCouponValidate extends BaseValidate {
+    protected $rule = [
+        'coupon_ids' => 'require',
+    ];
+    protected $field = [
+        'coupon_ids' => '优惠券ID组',
+    ];
+    public function sceneAdd()
+    {
+        return $this->only(['coupon_ids']);
+    }
+}

+ 41 - 0
app/common/model/BaseModel.php

@@ -15,6 +15,7 @@
 namespace app\common\model;
 
 use app\common\service\FileService;
+use think\facade\Db;
 use think\Model;
 
 /**
@@ -47,4 +48,44 @@ class BaseModel extends Model
     {
         return trim($value) ? FileService::setFileUrl($value) : '';
     }
+
+    public static function getDb(){
+        $model = new static();
+        return $model->db()->getTable();
+    }
+
+    /**
+     * 批量更新字段
+     * 获取DB 对象并赋予 模型本身的 connection 连接
+     * @return mixed
+     */
+
+    public static function updateWhenCase($datas)
+    {
+        if(is_array($datas) && count($datas) > 0 ){
+            $ids = array_keys($datas);
+            if(is_array(reset($datas))){
+                $fields = array_keys(reset($datas));
+                $sql= " update ". self::getDb() ." set ";
+                foreach($fields as $field ){
+                    $sql.= " `$field` = ( case id";
+                    foreach($datas as $id => $data ){
+                        $sql.= " when $id then ".self::stringFilter($data[$field])." ";
+                    }
+                    $sql.= " end ),";
+                }
+                $sql = substr($sql,0,-1);
+                $sql.= " where id in (".implode(",",$ids).")";
+                Db::execute($sql);
+            }
+        }
+    }
+
+    public static function stringFilter($string)
+    {
+        if(is_null($string)) {
+            return 'null';
+        }
+        return "'" . str_replace("'","\'",$string) . "'";
+    }
 }

+ 21 - 0
app/common/model/coupon/UserCoupon.php

@@ -0,0 +1,21 @@
+<?php
+
+namespace app\common\model\coupon;
+use app\common\model\BaseModel;
+
+/**
+ * @author 林海涛
+ * @date 2024/7/18 下午3:42
+ */
+
+class UserCoupon extends BaseModel
+{
+
+    protected $name = 'user_coupon';
+
+    public function couponRules()
+    {
+        return $this->hasOne(CouponRules::class,'id','coupon_id');
+    }
+
+}