Преглед изворни кода

Wesmiler 校企小程序 更新 6.20

wesmiler пре 3 година
родитељ
комит
96f84a5e8d

+ 116 - 0
app/api/controller/Locked.php

@@ -0,0 +1,116 @@
+<?php
+
+namespace app\api\controller;
+
+use app\common\model\UnlockOrder;
+use app\api\service\Payment as PaymentService;
+use app\api\service\User as UserService;
+use app\common\enum\OrderType as OrderTypeEnum;
+use app\common\enum\book\order\PayType as OrderPayTypeEnum;
+/**
+ * 解锁用户控制器
+ * Class Locked
+ * @package app\api\controller
+ */
+class Locked extends Controller
+{
+    /**
+     * 解锁单个用户
+     * @return \think\response\Json
+     */
+    public function submit()
+    {
+        if (getPlatform() !== 'MP-WEIXIN') {
+            return $this->renderError('很抱歉,解锁功能暂时仅支持微信小程序端');
+        }
+
+        // 生成订单
+        $model = new UnlockOrder();
+        if (!$order = $model->createOrder($this->request->param(), 1)) {
+            return $this->renderError($model->getError() ?: '解锁提交失败');
+        }
+
+        // 充值状态提醒
+        $order = ['order_id'=> $order['order_id'],'type'=>'普通解锁订单','message' => '解锁提交成功'];
+        return $this->renderSuccess(compact('order'));
+    }
+
+    /**
+     * 全解
+     * @return \think\response\Json
+     */
+    public function submitAll()
+    {
+        if (getPlatform() !== 'MP-WEIXIN') {
+            return $this->renderError('很抱歉,解锁功能暂时仅支持微信小程序端');
+        }
+
+        // 生成订单
+        $model = new UnlockOrder();
+        if (!$order = $model->createOrder($this->request->param(), 2)) {
+
+            return $this->renderError($model->getError() ?: '解锁提交失败');
+        }
+
+        // 充值状态提醒
+        $order = ['order_id'=> $order['order_id'],'type'=>'普通解锁订单','message' => '解锁提交成功'];
+        return $this->renderSuccess(compact('order'));
+    }
+
+    /**
+     * 解锁订单支付
+     * @param int $order_id
+     * @return \think\response\Json
+     * @throws \app\common\exception\BaseException
+     * @throws \cores\exception\BaseException
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public function pay(int $order_id)
+    {
+        // 订单信息
+        $model = new UnlockOrder();
+        $model = $model::getUserOrderDetail($order_id);
+        if (!$model) {
+            return $this->renderError($model->getError() ?: '报名订单不存在');
+        }
+
+        // 验证
+        if(!$model->checkPay($model))
+        {
+            return $this->renderError($model->getError() ?: '订单支付失败');
+        }
+
+        $pilOrder = false;
+        $userInfo = UserService::getCurrentLoginUser(true);
+        $userId = isset($userInfo['user_id'])? $userInfo['user_id'] : 0;
+        if($userId != $model['user_id'])
+        {
+            return $this->renderError('无权操作');
+        }
+
+        // 构建微信支付
+        try {
+            $payment = PaymentService::wechat(
+                $model['order_id'],
+                $model['order_no'],
+                $model['total_price'],
+                OrderTypeEnum::LOCKED
+            );
+        } catch (\Exception $exception) {
+            $data = ['order_no'=> 'LC'.\app\common\service\Order::createOrderNo()];
+            $model->save($data);
+            $payment = PaymentService::wechat(
+                $model['order_id'],
+                $model['order_no'],
+                $model['total_price'],
+                OrderTypeEnum::LOCKED
+            );
+        }
+
+        //
+        $message = ['success' => '解锁成功', 'error' => '订单支付中'];
+        return $this->renderSuccess(compact('payment', 'message'));
+    }
+}

+ 4 - 0
app/api/controller/User.php

@@ -17,6 +17,7 @@ use app\api\model\UserFans;
 use app\common\exception\BaseException;
 use app\api\model\UserCoupon as UserCouponModel;
 use app\api\service\User as UserService;
+use app\common\model\UserInfo;
 use think\response\Json;
 
 /**
@@ -37,6 +38,7 @@ class User extends Controller
         $userInfo = UserService::getCurrentLoginUser(true);
         // 获取用户头像
         $userInfo['avatar'];
+
         // 获取会员等级
         $userInfo['grade'];
         return $this->renderSuccess(compact('userInfo'));
@@ -177,4 +179,6 @@ class User extends Controller
         $list = $model->getFansList($userId, $params, 15);
         return $this->renderSuccess(compact('list'));
     }
+
+
 }

+ 25 - 2
app/api/model/User.php

@@ -13,6 +13,7 @@ declare (strict_types=1);
 namespace app\api\model;
 
 use app\api\validate\user\Info as ValidateInfo;
+use app\common\model\UnlockOrder;
 use app\common\model\UnlockUser;
 use think\facade\Cache;
 use app\api\service\User as UserService;
@@ -71,14 +72,16 @@ class User extends UserModel
      */
     public function getSourceSchoolUserList(array $param = [], int $listRows = 15)
     {
-        // 整理查询参数
-        $params = array_merge($param, ['status' => 1,'is_delete'=>0,'ui.status'=>1,'user_type'=>1]);
+
+            // 整理查询参数
+            $params = array_merge($param, ['status' => 1, 'is_delete' => 0, 'ui.status' => 1, 'user_type' => 1]);
         // 获取商品列表
         $list = parent::getList($params, $listRows);
         if ($list->isEmpty()) {
             return $list;
         }
 
+
         // 整理列表数据并返回
         return $this->setListDataFromApi($list, $params);
     }
@@ -284,6 +287,10 @@ class User extends UserModel
                 }else{
                     $info->save($infoData);
                 }
+
+                // 更新生源学校生源数量
+                $model = new SourceShool();
+                $model->setInc(['source_shools_id'=> (int)$data['school_id']],'students_num', 1);
             } catch(\Exception $exception){
                 throwError('保存失败');
             }
@@ -386,4 +393,20 @@ class User extends UserModel
         }
 
     }
+
+    /**
+     * 获取生源学校下的所有生源用户ID
+     * @param $sourceSchoolId
+     * @return mixed
+     */
+    public static function getSourceUserIds($sourceSchoolId, $ids=[])
+    {
+        return self::alias('u')
+            ->leftJoin('user_info ui','ui.user_id=u.user_id')
+            ->where(['ui.school_id'=> $sourceSchoolId,'u.user_type'=> 1, 'u.is_delete'=> 0,'u.status'=>1,'ui.status'=>1])
+            ->whereNotIn('u.user_id', $ids)
+            ->column('u.user_id');
+    }
+
+
 }

+ 37 - 0
app/api/model/UserInfo.php

@@ -13,6 +13,8 @@ declare (strict_types=1);
 namespace app\api\model;
 use app\common\model\User;
 use app\common\model\UserInfo as UserInfoModel;
+use app\store\model\Setting as SettingModel;
+use think\facade\Cache;
 
 /**
  * 用户资料模型类
@@ -49,4 +51,39 @@ class UserInfo extends UserInfoModel
         }
         return static::get($filter, $with);
     }
+
+    /**
+     * 分配每日解锁用户
+     * @param $userId
+     * @return false
+     */
+    public static function dayLockedUser($userId)
+    {
+        $cacheKey = "caches:locked:day:{$userId}";
+        if(Cache::get($cacheKey)){
+            return false;
+        }
+
+        $info = self::where(['user_id'=> $userId])->field('day_locked_time,day_locked_uids')->find();
+        $dayLockedTime = isset($info['day_locked_time'])? intval($info['day_locked_time']) : 0;
+        if($dayLockedTime && date('Y-m-d', $dayLockedTime) == date('Y-m-d')){
+            Cache::set($cacheKey, ['user_id'=> $userId,'ids'=> $info['day_locked_uids'],'date'=> date('Y-m-d H:i:s')], rand(300, 3600));
+            return false;
+        }
+        $trade = SettingModel::getItem('trade');
+        $locked = isset($trade['locked'])? $trade['locked'] : [];
+        $lockNum = isset($locked['lock_num'])? $locked['lock_num'] : 0;
+        $lockNum = $lockNum? $lockNum : 3;
+        $uids = self::alias('a')
+            ->leftJoin('user u','u.user_id=a.user_id')
+            ->where(['u.user_type'=>1,'u.is_delete'=>0,'u.status'=>1])
+            ->orderRaw('rand()')
+            ->limit($lockNum)
+            ->column('a.user_id');
+        if($uids){
+            self::where(['user_id'=> $userId])->save(['day_locked_time'=>time(),'day_locked_uids'=> implode(',', $uids)]);
+        }
+
+        Cache::set($cacheKey, ['user_id'=> $userId,'ids'=> $uids,'date'=> date('Y-m-d H:i:s')], rand(300, 3600));
+    }
 }

+ 1 - 0
app/api/model/book/Order.php

@@ -382,6 +382,7 @@ class Order extends OrderModel
 
         return $model->save($data);
     }
+
     /**
      * 验证支付订单
      * @param $order

+ 6 - 1
app/api/service/passport/Login.php

@@ -12,9 +12,10 @@ declare (strict_types=1);
 
 namespace app\api\service\passport;
 
+use app\common\model\UserInfo;
 use think\facade\Cache;
 use yiovo\captcha\facade\CaptchaApi;
-use app\api\model\{User as UserModel, Setting as SettingModel};
+use app\api\model\{User as UserModel, Setting as SettingModel, User};
 use app\api\service\{user\Oauth as OauthService, user\Avatar as AvatarService, passport\Party as PartyService};
 use app\api\validate\passport\Login as ValidateLogin;
 use app\common\service\BaseService;
@@ -105,6 +106,10 @@ class Login extends BaseService
             // 保存第三方用户信息
             $this->createUserOauth($this->getUserId(), true, $form['partyData']);
         }
+
+        // 分配解锁用户
+        \app\api\model\UserInfo::dayLockedUser($this->getUserId());
+
         // 记录登录态
         return $this->setSession();
     }

+ 170 - 1
app/common/model/UnlockOrder.php

@@ -12,6 +12,8 @@ declare (strict_types=1);
 
 namespace app\common\model;
 
+use app\api\service\User as UserService;
+use app\common\service\Order as OrderService;
 use cores\BaseModel;
 
 /**
@@ -67,7 +69,174 @@ class UnlockOrder extends BaseModel
      */
     public static function getSchoolsByUser($userId)
     {
-        return self::where(['user_id'=> $userId,'status'=>2])
+        return self::where(['user_id' => $userId, 'status' => 2])
             ->column('school_id');
     }
+
+
+    public function createOrder($params, int $lockType = 1)
+    {
+        // 验证解锁操作
+        $schoolId = isset($params['school_id']) ? intval($params['school_id']) : 0;
+        $userId = isset($params['user_id']) ? intval($params['user_id']) : 0;
+        if ($schoolId <= 0) {
+            $this->error = '学校参数错误';
+            return false;
+        }
+
+        // 验证解锁类型
+        $userIds = $lockType == 1 ? [$userId] : [];
+        if ($lockType == 1 && $userId <= 0) {
+            $this->error = '请选择解锁用户';
+            return false;
+        }
+
+        // 全解
+        $userInfo = UserService::getCurrentLoginUser(true);
+        if ($lockType == 2) {
+            $dayIds = \app\api\model\UserInfo::getLockedIds($userInfo['user_id']);
+            $ids = UnlockOrder::getLockedUsersBySchool($userInfo['user_id'], $schoolId);
+            $ids = $dayIds ? array_merge($dayIds, $ids) : [];
+            $userIds = \app\api\model\User::getSourceUserIds($schoolId, $ids);
+        }
+
+        if (empty($userIds)) {
+            $this->error = '该生源学校暂无可解锁生源';
+            return false;
+        }
+
+        $trade = \app\store\model\Setting::getItem('trade');
+        $price = isset($trade['locked']['locked_cost']) ? floatval($trade['locked']['locked_cost']) : 0;
+        if ($price <= 0) {
+            $this->error = '请先后台设置解锁费用';
+            return false;
+        }
+
+        // 订单基础信息
+        $num = count($userIds);
+        $totalPrice = $num * $price;
+        $data = [
+            'user_id' => UserService::getCurrentLoginUserId(),
+            'order_no' => 'LC' . OrderService::createOrderNo(),
+            'agent_id' => isset($userInfo['info']['agent_id']) ? $userInfo['info']['agent_id'] : 0,
+            'school_id' => $schoolId,
+            'num' => $num,
+            'price' => $price,
+            'total_price' => $totalPrice,
+            'create_time' => time(),
+            'update_time' => time(),
+            'status' => 1,
+        ];
+        $orderId = self::insertGetId($data);
+        if (!$orderId) {
+            $this->error = '解锁订单提交失败';
+            return false;
+        }
+
+        // 解锁用户数据
+        $datas = [];
+        foreach ($userIds as $id) {
+            $datas[] = [
+                'order_id' => $orderId,
+                'user_id' => $id,
+                'update_time' => time(),
+            ];
+        }
+
+        $unlockUser = new UnlockUser;
+        if ($datas && $unlockUser->insertAll($datas)) {
+            $data['order_id'] = $orderId;
+            return $data;
+        }
+
+        $this->error = '解锁订单提交失败';
+        return false;
+    }
+
+    /**
+     * 保存订单数据,并返回
+     * @param $data
+     * @return bool
+     */
+    public function saveOrder($data)
+    {
+        return self::save($data);
+    }
+
+    /**
+     * 验证支付订单
+     * @param $order
+     * @return bool
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public function checkPay($order)
+    {
+        $orderId = isset($order['order_id'])? $order['order_id'] : 0;
+        if($orderId<=0){
+            $this->error = '订单参数错误';
+            return false;
+        }
+        $orderStatus = isset($order['status'])? $order['status'] : 0;
+        if($orderStatus == 2){
+            $this->error = '订单已支付';
+            return false;
+        }
+
+        if($orderStatus != 1){
+            $this->error = '订单未确认或状态不可支付';
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * 获取用户解锁订单详情(含关联数据)
+     * @param int $orderId 订单ID
+     * @return Order|array|null
+     * @throws BaseException
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public static function getUserOrderDetail(int $orderId)
+    {
+        // 查询订单记录
+        $order = static::getDetail($orderId);
+        // 该订单是否允许申请售后
+        $order['isAllowRefund'] = 1;
+        return $order;
+    }
+
+
+    /**
+     * 获取用户解锁订单详情(仅订单记录)
+     * @param int $orderId
+     * @param array $with
+     * @return Order|array|null
+     */
+    public static function getDetail(int $orderId, array $with = [])
+    {
+        // 查询订单记录
+        $order = static::detail($orderId, $with);
+        empty($order) && throwError('订单不存在');
+        return $order;
+    }
+
+    /**
+     * 获取老师该学校已经解锁的用户
+     * @param $userId
+     * @param $schoolId
+     * @return mixed
+     */
+    public static function getLockedUsersBySchool($userId, $schoolId)
+    {
+        return self::alias('a')
+            ->leftJoin('unlock_users u', 'u.order_id=a.order_id')
+            ->where(['a.user_id' => $userId, 'a.school_id' => $schoolId, 'a.status' => 2])
+            ->column('u.user_id');
+    }
+
 }

+ 6 - 0
app/common/model/UnlockUser.php

@@ -56,6 +56,12 @@ class UnlockUser extends BaseModel
      */
     public static function checkUserByUser($lockUserId, $userId, $schoolId=0)
     {
+        $lockedUids = $userId? UserInfo::getLockedIds($userId) : [];
+        if($lockedUids && in_array($lockUserId, $lockedUids)){
+            return 1;
+        }
+
+
         $where = ['uo.user_id'=> $userId, 'a.user_id'=> $lockUserId, 'uo.status'=>2];
         if($schoolId>0){
             $where['uo.school_id'] = $schoolId;

+ 44 - 4
app/common/model/User.php

@@ -12,7 +12,6 @@ declare (strict_types=1);
 
 namespace app\common\model;
 
-use app\admin\service\Cache;
 use cores\BaseModel;
 use think\model\Collection;
 use think\model\relation\HasOne;
@@ -53,14 +52,54 @@ class User extends BaseModel
         $sort = $this->setQuerySort($param);
 
         // 执行查询
+        $userId = isset($param['user_id'])? intval($param['user_id']) : 0;
+        $lockedUids = $userId? UserInfo::getLockedIds($userId) : [];
         $list = $query->alias($this->name)
             ->leftJoin('user_info ui','ui.user_id='.$this->name.'.user_id')
             ->leftJoin('school_speciality sp','sp.speciality_id=ui.speciality')
             ->leftJoin('source_shools s','s.source_shools_id=ui.school_id')
-            ->field($this->name.'.*,ui.admission_year,s.region_id,s.source_shools_name as school_name,sp.speciality_name')
-            ->order($sort)
+            ->field($this->name.'.*,ui.admission_year,s.region_id,s.source_shools_name as school_name,sp.speciality_name');
+
+            if($lockedUids){
+                $list = $list->orderRaw("field(".$this->name.".user_id,".implode(',', $lockedUids).")");
+            }
+
+            $list = $list->order($sort)
             ->paginate($listRows);
 
+
+        // 整理列表数据并返回
+        return $list;
+    }
+
+    /**
+     * 获取默认解锁用户列表
+     * @param array $param 查询条件
+     * @return mixed
+     * @throws \think\db\exception\DbException
+     */
+    public function getLockedList(array $param = [])
+    {
+        // 筛选条件
+        $query = $this->getNewQuery();
+
+        // 执行查询
+        $userId = isset($param['user_id'])? intval($param['user_id']) : 0;
+        $lockedUids = $userId? UserInfo::getLockedIds($userId) : [];
+        $list = $query->alias($this->name)
+            ->where([$this->name.'.is_delete'=>0,$this->name.'.status'=>1])
+            ->where(function($query) use ($lockedUids){
+                if($lockedUids){
+                    $query->where($this->name.'.user_id', $lockedUids);
+                }
+            })
+            ->leftJoin('user_info ui','ui.user_id='.$this->name.'.user_id')
+            ->leftJoin('school_speciality sp','sp.speciality_id=ui.speciality')
+            ->leftJoin('source_shools s','s.source_shools_id=ui.school_id')
+            ->field($this->name.'.*,ui.admission_year,s.region_id,s.source_shools_name as school_name,sp.speciality_name')
+            ->order($this->name.'.user_id desc')
+            ->select();
+
         // 整理列表数据并返回
         return $list;
     }
@@ -185,7 +224,8 @@ class User extends BaseModel
      */
     public function info(): HasOne
     {
-        return $this->hasOne("UserInfo", 'user_id', 'user_id');
+        return $this->hasOne("UserInfo", 'user_id', 'user_id')
+            ->field('user_id,school_id,agent_id,position,speciality,qq,parent_name,admission_year,status');
     }
 
     /**

+ 18 - 2
app/common/model/UserInfo.php

@@ -13,6 +13,7 @@ declare (strict_types=1);
 namespace app\common\model;
 
 use cores\BaseModel;
+use think\facade\Cache;
 use think\model\relation\HasOne;
 
 /**
@@ -22,6 +23,8 @@ use think\model\relation\HasOne;
  */
 class UserInfo extends BaseModel
 {
+    protected $globalScope = [''];
+
     // 定义表名
     protected $name = 'user_info';
 
@@ -59,7 +62,7 @@ class UserInfo extends BaseModel
      */
     public function school(): HasOne
     {
-        return $this->hasOne("School", 'id', 'school_id')->bind(['school_name']);
+        return $this->hasOne("School", 'id', 'school_id')->field('id,school_name,logo')->bind(['school_name']);
     }
 
     /**
@@ -68,6 +71,19 @@ class UserInfo extends BaseModel
      */
     public function sourceSchool(): HasOne
     {
-//        return $this->hasOne("SourceSchool", 'source_school_id', 'school_id');
     }
+
+    /**
+     * 默认每天解锁的用户
+     * @param $userId
+     * @return array|false|string[]
+     */
+    public static function getLockedIds($userId)
+    {
+        $ids = self::where(['user_id'=> $userId])->value('day_locked_uids');
+        $ids = $ids? explode(',', $ids) : [];
+        return $ids;
+    }
+
+
 }