wesmiler 3 лет назад
Родитель
Сommit
1b4872523d

+ 154 - 0
source/application/api/service/User.php

@@ -2,7 +2,11 @@
 
 namespace app\api\service;
 
+use app\api\model\user\Grade;
+use app\api\model\user\GradeLog;
+use app\common\model\dealer\Setting;
 use think\Cache;
+use think\Db;
 use think\Exception;
 use app\api\model\User as UserModel;
 class User
@@ -58,4 +62,154 @@ class User
         return UserModel::where('user_id', $userId)->update(['pay_password'=>$payPassword,'update_time'=>time()]);
     }
 
+    /**
+     * 用户升级
+     * @param $user_id
+     * @param int $wxapp_id
+     * @return bool
+     * @throws Exception
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function upgrade($user_id, $wxapp_id=0)
+    {
+        $info = UserModel::alias('a')
+            ->leftJoin('user_grade ug', 'ug.grade_id=a.grade_id')
+            ->where('user_id', $user_id)
+            ->field('a.user_id,a.grade_id,ug.name,a.expend_upgrade_money')
+            ->find();
+        if(empty($info)){
+            return false;
+        }
+
+        $gradeId = isset($info['grade_id'])? intval($info['grade_id']) : 0;
+        $upgradeMoney = isset($info['expend_upgrade_money'])? floatval($info['expend_upgrade_money']) : 0;
+        if($upgradeMoney>0){
+            $gradeList = Grade::where(['status'=> 1, 'is_delete'=> 0,'wxapp_id'=>$wxapp_id])
+                ->where('grade_id','>', $gradeId)
+                ->field('grade_id,name,upgrade')
+                ->order('weight asc')
+                ->select();
+            $gradeList = $gradeList? $gradeList->toArray() : [];
+            if($gradeList){
+                $log = [];
+                $newGradeId = 0;
+                foreach ($gradeList as $v){
+                    $id = isset($v['grade_id'])? $v['grade_id'] : 0;
+                    $upgrade = isset($v['upgrade']) && $v['upgrade']? json_decode($v['upgrade'], true) : [];
+                    $upgradeGradeMoney = isset($upgrade['expend_money'])? floatval($upgrade['expend_money']) : 0;
+                    if($id>$gradeId && $upgradeGradeMoney<=$upgradeMoney){
+                        $newGradeId = $id;
+                    }
+                }
+
+                // 处理
+                if($newGradeId>0){
+                    Db::startTrans();
+                    if(!UserModel::where(['user_id'=>$user_id])->update(['grade_id'=> $newGradeId,'update_time'=> time()])){
+                        Db::rollback();
+                        throw new Exception('升级处理失败');
+                    }
+
+                    $log = [
+                        'user_id'=> $user_id,
+                        'old_grade_id'=> $gradeId,
+                        'new_grade_id'=> $newGradeId,
+                        'change_type'=> 20,
+                        'wxapp_id'=> $wxapp_id,
+                        'remark'=> "升级成功",
+                        'create_time'=> time()
+                    ];
+                    if(!GradeLog::insertgetId($log)){
+                        Db::rollback();
+                        throw new Exception('升级处理失败');
+                    }
+
+
+                    // 推荐奖金
+                    self::settleAward($user_id, $wxapp_id);
+
+                    Db::commit();
+                    return true;
+                }
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * 获取用户信息
+     * @param $userId
+     * @param $wxapp_id
+     * @return mixed
+     */
+    public static function getUserInfo($userId, $wxapp_id)
+    {
+        if(empty($userId)){
+            return false;
+        }
+
+        $model = new \app\common\model\dealer\User();
+        return $dealerUserInfo = $model::alias('a')
+            ->leftJoin('user u','u.user_id=a.user_id')
+            ->leftJoin('user_grade ug','ug.grade_id=u.grade_id')
+            ->where(['a.user_id'=>$userId,'a.wxapp_id'=>$wxapp_id,'a.is_delete'=>0])
+            ->field('a.user_id,a.money,a.referee_id,u.grade_id,ug.weight as level,ug.name as grade_name')
+            ->find();
+    }
+    /**
+     * 结算推荐佣金
+     */
+    public static  function settleAward($userId, $wxapp_id)
+    {
+        // 奖金配置参数
+        $config = Setting::getItem('commission', $wxapp_id);
+        if(empty($config)){
+            return false;
+        }
+
+        $dealerUserInfo = self::getUserInfo($userId, $wxapp_id);
+        $userLevel = isset($dealerUserInfo['level'])? $dealerUserInfo['level'] : 0;
+        $firstId = isset($dealerUserInfo['referee_id'])? $dealerUserInfo['referee_id'] : 0;
+        if(empty($dealerUserInfo) || $firstId<=0){
+            return false;
+        }
+
+        $firstInfo = self::getUserInfo($firstId, $wxapp_id);
+        $firstLevel = isset($firstInfo['level'])? $firstInfo['level'] : 0;
+        $firstLevelName = isset($firstInfo['grade_name'])? $firstInfo['grade_name'] : '';
+        $secondId = isset($firstInfo['referee_id'])? $firstInfo['referee_id'] : 0;
+
+        $secondInfo = self::getUserInfo($secondId, $wxapp_id);
+        $secondLevel = isset($secondInfo['level'])? $secondInfo['level'] : 0;
+        $secondLevelName = isset($secondInfo['grade_name'])? $secondInfo['grade_name'] : '';
+
+
+        // 平级奖 (vip以及以上等级)
+        $model = new \app\common\model\dealer\User();
+        if($firstInfo && $userLevel>=1){
+            // 直推平级奖
+            $equalScore1 = isset($config['equal_score_1'])? floatval($config['equal_score_1']) : 0;
+            if($userLevel==$firstLevel && $equalScore1>0){
+                $model->grantMoney($firstId, $equalScore1, 2, "来自用户[{$userId}]直推[{$firstLevelName}]平级奖");
+            }
+
+            // 间推平级奖
+            $equalScore2 = isset($config['equal_score_2'])? floatval($config['equal_score_2']) : 0;
+            if($secondInfo && $userLevel==$secondLevel && $equalScore2>0){
+                $model->grantMoney($secondId, $equalScore2, 2, "来自用户[{$userId}]间推[{$secondLevelName}]平级奖");
+            }
+        }
+
+
+        // 反推奖(上级的级别大于当前用户)
+        $reverseScore = isset($config['reverse_score_'.$firstLevel])? floatval($config['reverse_score_'.$firstLevel]) : 0;
+        if($firstLevel>$userLevel && $reverseScore>0){
+            $model->grantMoney($firstId, $reverseScore, 2, "来自用户[{$userId}]反推[{$firstLevelName}]奖");
+        }
+
+        return true;
+    }
 }

+ 20 - 0
source/application/api/service/order/Checkout.php

@@ -4,6 +4,7 @@ namespace app\api\service\order;
 
 use app\api\model\Order as OrderModel;
 
+use app\api\model\User;
 use app\api\model\User as UserModel;
 use app\api\model\Goods as GoodsModel;
 use app\api\model\Setting as SettingModel;
@@ -588,6 +589,25 @@ class Checkout
         });
         // 余额支付标记订单已支付
         if ($status && $order['pay_type'] == PayTypeEnum::BALANCE) {
+            // 验证密码
+            $payPassword = input('pay_password','');
+            if(empty($payPassword)){
+                $this->error = '请填写支付密码';
+                return false;
+            }
+
+            $userPayPassword = User::where(['user_id'=> $this->model['user_id'],'wxapp_id'=>$this->model['wxapp_id']])
+                ->value('pay_password');
+            if(empty($userPayPassword)){
+                $this->error = '请先设置支付密码';
+                return false;
+            }
+
+            if(makePassword($payPassword) != $userPayPassword){
+                $this->error = '支付密码错误';
+                return false;
+            }
+
             return $this->model->onPaymentByBalance($this->model['order_no']);
         }
         return $status;

+ 3 - 0
source/application/common/model/User.php

@@ -179,6 +179,8 @@ class User extends BaseModel
         return true;
     }
 
+
+
     /**
      * 累积用户的可用积分数量 (批量)
      * @param $data
@@ -212,4 +214,5 @@ class User extends BaseModel
         return $this->setInc('points', $points);
     }
 
+
 }

+ 113 - 1
source/application/common/model/dealer/Order.php

@@ -97,7 +97,7 @@ class Order extends BaseModel
     }
 
     /**
-     * 发放分销订单佣金
+     * 发放分销订单佣金(分销订单)
      * @param array|\think\Model $order 订单详情
      * @param int $orderType 订单类型
      * @return bool|false|int
@@ -122,6 +122,118 @@ class Order extends BaseModel
         if (!$model || $model['is_settled'] == 1) {
             return false;
         }
+
+        // 重新计算分销佣金
+        $capital = $model->getCapitalByOrder($order);
+        // 发放一级分销商佣金
+        $model['first_user_id'] > 0 && User::grantMoney($model['first_user_id'], $capital['first_money']);
+        // 发放二级分销商佣金
+        $model['second_user_id'] > 0 && User::grantMoney($model['second_user_id'], $capital['second_money']);
+        // 发放三级分销商佣金
+        $model['third_user_id'] > 0 && User::grantMoney($model['third_user_id'], $capital['third_money']);
+        // 更新分销订单记录
+        return $model->save([
+            'order_price' => $capital['orderPrice'],
+            'first_money' => $capital['first_money'],
+            'second_money' => $capital['second_money'],
+            'third_money' => $capital['third_money'],
+            'is_settled' => 1,
+            'settle_time' => time()
+        ]);
+    }
+
+    /**
+     * 发放分销订单佣金 (直接购买订单)
+     * @param array|\think\Model $order 订单详情
+     * @param int $orderType 订单类型
+     * @return bool|false|int
+     * @throws \think\Exception
+     * @throws \think\exception\DbException
+     */
+    public static function grantOrderMoney($order, $orderType = OrderTypeEnum::MASTER)
+    {
+        // 订单是否已完成
+        if ($order['order_status']['value'] != 30) {
+            return false;
+        }
+        // 佣金结算天数
+        $settleDays = Setting::getItem('settlement', $order['wxapp_id'])['settle_days'];
+        // 判断该订单是否满足结算时间 (订单完成时间 + 佣金结算时间) ≤ 当前时间
+        $deadlineTime = $order['receipt_time'] + ((int)$settleDays * 86400);
+        if ($settleDays > 0 && $deadlineTime > time()) {
+            return false;
+        }
+        // 分销订单详情
+        $model = \app\common\model\Order::detail(['order_id'=>$order['order_id']]);
+        if (!$model || $model['is_settled'] == 1) {
+            return false;
+        }
+
+        $userInfo = User::where(['user_id'=> $order['user_id'],'wxapp_id'=>$order['wxapp_id']])
+            ->field('user_id,referee_id')
+            ->find();
+        $firstId = isset($userInfo['referee_id'])? $userInfo['referee_id'] : 0;
+        if($userInfo && $firstId>0){
+            $firstInfo = User::where(['user_id'=> $firstId,'wxapp_id'=>$order['wxapp_id']])
+                ->field('user_id,referee_id')
+                ->find();
+            $secondId = isset($firstInfo['referee_id'])? $firstInfo['referee_id'] : 0;
+            $payMoney = isset($model['total_price'])? floatval($model['total_price']) : 0;
+            $config = Setting::getItem('commission', $order['wxapp_id']);
+            $awardScoreRate1 = isset($config['award_score_1'])? floatval($config['award_score_1']) : 0;
+            $awardScoreRate2 = isset($config['award_score_2'])? floatval($config['award_score_2']) : 0;
+            // 一级佣金
+            $awardScore1 = floatval($payMoney * $awardScoreRate1/100);
+            $awardScore2 = floatval($payMoney * $awardScoreRate2/100);
+            if($firstId && $firstInfo && $awardScore1>0){
+                User::grantMoney($firstId, $awardScore1);
+            }
+
+            //二级佣金
+            $secondInfo = User::where(['user_id'=> $secondId,'wxapp_id'=>$order['wxapp_id']])
+                ->field('user_id,referee_id')
+                ->find();
+            if($firstId && $secondInfo && $awardScore2>0){
+                User::grantMoney($secondInfo, $awardScore2);
+            }
+        }
+
+        // 更新订单结算数据
+        return $model->save([
+            'first_money' => $awardScore1,
+            'second_money' => $awardScore2,
+            'is_settled' => 1,
+            'settle_time' => time()
+        ]);
+    }
+
+    /**
+     * 发放分销订单佣金(备份旧的结算)
+     * @param array|\think\Model $order 订单详情
+     * @param int $orderType 订单类型
+     * @return bool|false|int
+     * @throws \think\Exception
+     * @throws \think\exception\DbException
+     */
+    public static function grantMoneyBack($order, $orderType = OrderTypeEnum::MASTER)
+    {
+        // 订单是否已完成
+        if ($order['order_status']['value'] != 30) {
+            return false;
+        }
+        // 佣金结算天数
+        $settleDays = Setting::getItem('settlement', $order['wxapp_id'])['settle_days'];
+        // 判断该订单是否满足结算时间 (订单完成时间 + 佣金结算时间) ≤ 当前时间
+        $deadlineTime = $order['receipt_time'] + ((int)$settleDays * 86400);
+        if ($settleDays > 0 && $deadlineTime > time()) {
+            return false;
+        }
+        // 分销订单详情
+        $model = self::getDetailByOrderId($order['order_id'], $orderType);
+        if (!$model || $model['is_settled'] == 1) {
+            return false;
+        }
+
         // 重新计算分销佣金
         $capital = $model->getCapitalByOrder($order);
         // 发放一级分销商佣金

+ 3 - 2
source/application/common/model/dealer/User.php

@@ -80,7 +80,7 @@ class User extends BaseModel
      * @throws \think\Exception
      * @throws \think\exception\DbException
      */
-    public static function grantMoney($user_id, $money)
+    public static function grantMoney($user_id, $money, $type=4, $remark='')
     {
         // 分销商详情
         $model = static::detail($user_id);
@@ -92,9 +92,10 @@ class User extends BaseModel
         // 记录分销商资金明细
         Capital::add([
             'user_id' => $user_id,
+            'type' => $type,
             'flow_type' => 10,
             'money' => $money,
-            'describe' => '订单佣金结算',
+            'describe' => $remark? $remark : '订单佣金结算',
             'wxapp_id' => $model['wxapp_id'],
         ]);
         return true;

+ 7 - 2
source/application/common/service/order/Complete.php

@@ -6,7 +6,7 @@ use app\common\library\helper;
 use app\common\model\User as UserModel;
 use app\common\model\Setting as SettingModel;
 use app\common\model\dealer\Order as DealerOrderModel;
-use app\common\model\user\Grade;
+use app\api\service\user as UserService;
 use app\common\model\user\PointsLog as PointsLogModel;
 use app\common\service\wechat\wow\Order as WowService;
 use app\common\enum\OrderType as OrderTypeEnum;
@@ -78,7 +78,12 @@ class Complete
 
         // 发放分销商佣金
         foreach ($orderList as $order) {
-            DealerOrderModel::grantMoney($order, $this->orderType);
+
+            // 结算分销佣金
+            DealerOrderModel::grantOrderMoney($order, $this->orderType);
+
+            // 用户升级
+            UserService::upgrade($order['user_id'], $order['wxapp_id']);
         }
 
         // 更新好物圈订单状态

+ 4 - 4
source/application/store/view/apps/dealer/setting/index.php

@@ -184,10 +184,10 @@
                                             一级佣金
                                         </label>
                                         <div class="am-u-sm-9">
-                                            <input type="number" min="0" max="10000" class="tpl-form-input"
+                                            <input type="number" min="0" max="100" class="tpl-form-input"
                                                    name="setting[commission][award_score_1]"
                                                    value="<?= isset($data['commission']['values']['award_score_1'])? $data['commission']['values']['award_score_1']:0 ?>" required>
-                                            <small>一级反佣积分数量</small>
+                                            <small>一级反佣积分比例%</small>
                                         </div>
                                     </div>
                                     <div class="am-form-group">
@@ -195,11 +195,11 @@
                                             二级佣金
                                         </label>
                                         <div class="am-u-sm-9">
-                                            <input type="number" min="0" max="10000" class="tpl-form-input"
+                                            <input type="number" min="0" max="100" class="tpl-form-input"
                                                    name="setting[commission][award_score_2]"
                                                    value="<?= isset($data['commission']['values']['award_score_2'])? $data['commission']['values']['award_score_2']:0 ?>"
                                                    required>
-                                            <small>二级级反佣积分数量</small>
+                                            <small>二级级反佣积分比例%</small>
                                         </div>
                                     </div>
                                     <!--<div class="am-form-group">