zxiansheng 4 년 전
부모
커밋
b3fafbb2f8

+ 0 - 15
common/components/ActiveQuery.php

@@ -119,21 +119,6 @@ class ActiveQuery extends \yii\db\ActiveQuery {
      * @return $this
      */
     public function yearMonth($yearMonth, $format='YYYYMM'){
-//        if(!$this->from){
-//            $tableName = $this->modelClass::tableName();
-//        } else {
-//            $tableName = $this->from[0];
-//        }
-//        $alias = '';
-//        $pregResult = null;
-//        if(preg_match('/^\s*(\S+)\s+(AS\s+|as\s+)?(\S+)\s*$/', $tableName, $pregResult)){
-//            $tableName = $pregResult[1];
-//            $alias = ' '.$pregResult[3];
-//        }
-//        if(!$yearMonth){
-//            $yearMonth = '201701';
-//        }
-//        $this->from = [$tableName." PARTITION FOR(TO_DATE('$yearMonth'".','."'$format'))$alias"];
         return $this;
     }
 

+ 8 - 10
common/config/config-devlopment.php

@@ -21,10 +21,10 @@ return [
     ],
     // 日志库
     'dbLog' => [
-        'dsn' => 'mongodb://39.104.27.110:27017/aikang_log_db',
+        'dsn' => 'mongodb://localhost:27017/aikang_log_db',
         'options' => [
-            "username" => "aikang_bonus_log_user",
-            "password" => "mongo@db.useron2020"
+            "username" => "aikang_user",
+            "password" => "mongo@db.localhost"
         ],
     ],
     // 奖金结算专属库(为不占用主库资源,不影响会员正常业务,该库专门用于奖金结算,可单独架设,需与主库做主从同步)
@@ -62,7 +62,7 @@ return [
     // Token专用 Redis 库
     'tokenRedis' => [
         // 服务器
-        'hostname' => '39.104.27.110',
+        'hostname' => 'localhost',
         // 端口
         'port' => 6379,
         // 密码
@@ -72,21 +72,20 @@ return [
     ],
     // 缓存专用 Redis 库
     'cacheRedis' => [
-        'hostname' => '39.104.27.110',
+        'hostname' => 'localhost',
         'port' => 6379,
         'password' => 'hxds_1319',
         'database' => 14,
     ],
     // 其他数据 Redis 库
     'otherRedis' => [
-        'hostname' => '39.104.27.110',
+        'hostname' => 'localhost',
         'port' => 6379,
         'password' => 'hxds_1319',
         'database' => 15,
     ],
-    // 远程静态上传服务器地址 @todo 明哥提供
-    //'remoteUploadHost' => 'http://localhost:9017',
-    'remoteUploadHost' => 'http://localhost:9017',
+    
+    'remoteUploadHost' => '',
     // swoole异步服务器及端口
     'swooleTimerConfig' => [
         'host' => '127.0.0.1',
@@ -96,7 +95,6 @@ return [
         'host' => '127.0.0.1',
         'port' => '9513',
     ],
-    // swoole奖金服务器及端口
     'swooleBonusClientConfig' => [
         'host' => '127.0.0.1',
         'port' => '9513',

+ 0 - 122
common/config/config-example.php

@@ -1,122 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/2/23
- * Time: 下午3:53
- */
-return [
-    // 奖金结算系统主库
-    'db' => [
-        // 数据库连接
-        'dsn' => 'oci:dbname=//192.168.0.253:1522/orclbonus;charset=utf8',
-        // 数据库用户名
-        'username' => 'c##bonusdb',
-        // 数据库密码
-        'password' => '123456',
-        // 数据库字符集
-        'charset' => 'utf8',
-        // 数据表前缀
-        'tablePrefix' => 'AR_',
-    ],
-    // 商城系统主库
-    'dbShop' => [
-        'dsn' => 'oci:dbname=//192.168.0.253:1521/orclshop;charset=utf8',
-        'username' => 'c##shopdb',
-        'password' => '123456',
-        'charset' => 'utf8',
-        'tablePrefix' => 'AR_',
-    ],
-    // 日志库
-    'dbLog' => [
-        'dsn' => 'mongodb://@192.168.0.253:27017/anran_bonus_log',
-        'options' => [
-            "username" => "anran_bonus_log_user",
-            "password" => "123456"
-        ],
-    ],
-    // 奖金结算专属库(为不占用主库资源,不影响会员正常业务,该库专门用于奖金结算,可单独架设,需与主库做主从同步)
-    'dbCalc' => [
-        'dsn' => 'oci:dbname=//192.168.0.253:1522/orclbonus;charset=utf8',
-        'username' => 'c##bonusdb',
-        'password' => '123456',
-        'charset' => 'utf8',
-        'tablePrefix' => 'AR_',
-    ],
-    // 商城用于结算的专属从库(为不占用系统主库资源,不影响会员的正常业务,该库专门用于奖金结算时从商城从库查询报单和订货单,可单独假设,需与商城主库做主从同步)
-    'dbShopCalc' => [
-        'dsn' => 'oci:dbname=//192.168.0.253:1521/orclshop;charset=utf8',
-        'username' => 'c##shopdb',
-        'password' => '123456',
-        'charset' => 'utf8',
-        'tablePrefix' => 'AR_',
-    ],
-    // 移动点位时专用的点位备份库(可用来查看各个时期的会员点位情况)
-    'dbNetPoint' => [
-        'dsn' => 'oci:dbname=//192.168.0.253:1522/orclnet;charset=utf8',
-        'username' => 'c##netdb',
-        'password' => '123456',
-        'charset' => 'utf8',
-        'tablePrefix' => 'AR_',
-    ],
-    // 系统从库
-    'slavesDb' => [
-        'slaveConfig' => [
-            'username' => 'c##bonusslave',
-            'password' => '123456',
-            'charset' => 'utf8',
-            'tablePrefix' => 'AR_',
-            'attributes' => [
-                PDO::ATTR_TIMEOUT => 10,  // 从库超时切换间隔时间
-            ],
-        ],
-        'slaves' => [
-            ['dsn' => 'oci:dbname=//192.168.0.253:1522/orclbonusslave;charset=utf8'],
-            // 其他奖金结算系统的从库从下面继续添加配置
-        ],
-    ],
-    // Token专用 Redis 库
-    'tokenRedis' => [
-        // 服务器
-        'hostname' => 'localhost',
-        // 端口
-        'port' => 6379,
-        // 密码
-        'password' => '123456',
-        // 库索引
-        'database' => 1,
-    ],
-    // 缓存专用 Redis 库
-    'cacheRedis' => [
-        'hostname' => 'localhost',
-        'port' => 6379,
-        'password' => '123456',
-        'database' => 3,
-    ],
-    // 其他数据 Redis 库
-    'otherRedis' => [
-        'hostname' => 'localhost',
-        'port' => 6379,
-        'password' => '123456',
-        'database' => 5,
-    ],
-    // 远程静态上传服务器地址
-    'remoteUploadHost' => 'http://localhost:9017',
-    'idCardVerify' => [
-        'host' => 'http://121.40.238.29:20000',
-        'clientId' => '122371433052508160',
-    ],
-    // swoole异步服务器及端口
-    'swooleTimerConfig' => [
-        'host' => '127.0.0.1',
-        'port' => '9513',
-    ],
-    // swoole的RPC服务器及端口
-    'swooleRPCConfig' => [
-        'host' => '127.0.0.1',
-        'port' => '9515',
-        'ipWhiteList' => [],
-        'username' => 'test',
-        'password' => 'ttt',
-    ],
-];

+ 24 - 25
common/config/config-product.php

@@ -9,11 +9,11 @@ return [
     // 奖金结算系统主库
     'db' => [
         // 数据库连接
-        'dsn' => 'mysql:host=173.1.0.128;port=4000;dbname=aikang_db',
+        'dsn' => 'mysql:host=localhost;port=3306;dbname=aikang_db',
         // 数据库用户名
-        'username' => 'aikang',
+        'username' => 'aaa',
         // 数据库密码
-        'password' => 'xtuNQ7F&p0M&UhcE',
+        'password' => 'vvv&vvv&vv',
         // 数据库字符集
         'charset' => 'utf8',
         // 数据表前缀
@@ -21,33 +21,33 @@ return [
     ],
     // 日志库
     'dbLog' => [
-        'dsn' => 'mongodb://173.1.0.37:27017/aikang_log_db',
+        'dsn' => 'mongodb://localhost/aikang_log_db',
         'options' => [
-            "username" => "aikang_bonus_log_user",
-            "password" => "mongo@db.useron2020"
+            "username" => "aaa",
+            "password" => "mongo@user"
         ],
     ],
-    // 奖金结算专属库(为不占用主库资源,不影响会员正常业务,该库专门用于奖金结算,可单独架设,需与主库做主从同步)
+    //为不占用主库资源,不影响会员正常业务,该库专门用于奖金结算,可单独架设,需与主库做主从同步
     'dbCalc' => [
-        'dsn' => 'mysql:host=173.1.0.128;port=4000;dbname=aikang_db',
-        'username' => 'aikang',
-        'password' => 'xtuNQ7F&p0M&UhcE',
+        'dsn' => 'mysql:host=localhost;port=3306;dbname=aikang_db',
+        'username' => 'aaa',
+        'password' => 'vvv&vvv&vv',
         'charset' => 'utf8',
         'tablePrefix' => 'AR_',
     ],
     // 移动点位时专用的点位备份库(可用来查看各个时期的会员点位情况)
     'dbNetPoint' => [
-        'dsn' => 'mysql:host=173.1.0.128;port=4000;dbname=aikang_db',
-        'username' => 'aikang',
-        'password' => 'xtuNQ7F&p0M&UhcE',
+        'dsn' => 'mysql:host=localhost;port=3306;dbname=aikang_db',
+        'username' => 'aaa',
+        'password' => 'vvv&vvv&vv',
         'charset' => 'utf8',
         'tablePrefix' => 'AR_',
     ],
     // 系统从库
     'slavesDb' => [
         'slaveConfig' => [
-            'username' => 'aikang',
-            'password' => 'xtuNQ7F&p0M&UhcE',
+            'username' => 'aaa',
+            'password' => 'vvv&vvv&vv',
             'charset' => 'utf8',
             'tablePrefix' => 'AR_',
             'attributes' => [
@@ -55,37 +55,37 @@ return [
             ],
         ],
         'slaves' => [
-            ['dsn' => 'mysql:host=173.1.0.128;port=4000;dbname=aikang_db'],
+            ['dsn' => 'mysql:host=localhost;port=3306;dbname=aikang_db'],
             // 其他奖金结算系统的从库从下面继续添加配置
         ],
     ],
     // Token专用 Redis 库
     'tokenRedis' => [
         // 服务器
-        'hostname' => '173.1.0.224',
+        'hostname' => 'localhost',
         // 端口
         'port' => 6379,
         // 密码
-        'password' => 'uGAmdQJt8Z',
+        'password' => 'asaa',
         // 库索引
         'database' => 13,
     ],
     // 缓存专用 Redis 库
     'cacheRedis' => [
-        'hostname' => '173.1.0.224',
+        'hostname' => 'localhost',
         'port' => 6379,
-        'password' => 'uGAmdQJt8Z',
+        'password' => 'asaa',
         'database' => 14,
     ],
     // 其他数据 Redis 库
     'otherRedis' => [
-        'hostname' => '173.1.0.224',
+        'hostname' => 'localhost',
         'port' => 6379,
-        'password' => 'uGAmdQJt8Z',
+        'password' => 'asaa',
         'database' => 15,
     ],
-    // 远程静态上传服务器地址 @todo 明哥提供
-    'remoteUploadHost' => 'http://upload.lxak2020.com',
+    
+    'remoteUploadHost' => 'http://localhost',
     // swoole异步服务器及端口
     'swooleTimerConfig' => [
         'host' => '127.0.0.1',
@@ -95,7 +95,6 @@ return [
         'host' => '127.0.0.1',
         'port' => '9513',
     ],
-    // swoole奖金服务器及端口
     'swooleBonusClientConfig' => [
         'host' => '127.0.0.1',
         'port' => '9513',

+ 0 - 7
common/config/main.php

@@ -7,23 +7,18 @@ return [
     'aliases' => [
         '@bower' => '@vendor/bower-asset',
         '@npm'   => '@vendor/npm-asset',
-//        'anlity/swooleAsyncTimer' => '@backend/runtime/tmp-extensions/yii2-swoole-async-timer',
     ],
     'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
     'components' => [
         'db' => array_merge([
             'class' => 'yii\db\Connection',
             'enableSlaves' => false,
-//            'enableSavepoint' => false,
         ], $mainConfig['db'], $mainConfig['slavesDb']),
-//        'dbShop' => array_merge(['class' => 'yii\db\Connection', 'schemaMap' => ['oci' => 'common\helpers\Schema']], $mainConfig['dbShop']),
         'dbLog' => array_merge(['class' => 'yii\mongodb\Connection',], $mainConfig['dbLog']),
         'dbCalc' => array_merge(['class' => 'yii\db\Connection'], $mainConfig['dbCalc']),
-//        'dbShopCalc' => array_merge(['class' => 'yii\db\Connection', 'schemaMap' => ['oci' => 'common\helpers\Schema'],], $mainConfig['dbShopCalc']),
         'dbNetPoint' => array_merge(['class' => 'yii\db\Connection'], $mainConfig['dbNetPoint']),
         'cache' => [
             'class' => 'yii\redis\Cache',
-            //'redis' => $mainConfig['cacheRedis'],
             'redis' => [
                 'hostname' => '127.0.0.1',
                 'port' => 6379,
@@ -32,8 +27,6 @@ return [
         ],
         'tokenRedis' => array_merge(['class' => 'yii\redis\Connection'], $mainConfig['tokenRedis']),
         'redis' => array_merge(['class' => 'yii\redis\Connection'], $mainConfig['otherRedis']),
-        // 'tokenRedis' => array_merge(['class' => \yii\redis\Cache::class], $mainConfig['tokenRedis']),
-        // 'redis' => array_merge(['class' => \yii\redis\Cache::class], $mainConfig['otherRedis']),
         'mailer' => [
             'class' => 'yii\swiftmailer\Mailer',
             'viewPath' => '@common/mail',

+ 5 - 113
common/config/params.php

@@ -33,12 +33,6 @@ return [
             ],
             'hasIdCardInfoPath' => '/socialwork/v1/external/freedom-emps/has-idcard-info/%s',
         ]
-//        'requestShop' => [
-//            'url' => $mainConfig['requestShopUrl'],
-//            'username' => 'bonus_api',
-//            'password' => 'bonus_api',
-//        ]
-
     ],
     'shopWalletType' => [
         'cash' =>[
@@ -46,117 +40,15 @@ return [
             'title'=>'现金钱包',
         ],
     ],
-    'shopFlowType' => [
-        'remit' => [
-            'value' => 'remit',
-            'label' => '汇款充值',
-        ],
-        'recharge' => [
-            'value' => 'recharge',
-            'label' => '第三方充值',
-        ],
-        'transfer_out' => [
-            'value' => 'transfer_out',
-            'label' => '转出',
-        ],
-        'transfer_in' => [
-            'value' => 'transfer_in',
-            'label' => '转入',
-        ],
-        'pay' => [
-            'value' => 'pay',
-            'label' => '支付',
-        ],
-        'decRecharge' => [
-            'value' => 'decRecharge',
-            'label' => '报单充入',
-        ],
-        'orderRecharge' => [
-            'value' => 'orderRecharge',
-            'label' => '订货充入',
-        ],
-        'freight' => [
-            'value' => 'freight',
-            'label' => '支付运费',
-        ],
-        'adjust_recharge' => [
-            'value' => 'adjust_recharge',
-            'label' => '待调整充入',
-        ],
-        'adjust_deduct' => [
-            'value' => 'adjust_deduct',
-            'label' => '待调整扣除',
-        ],
-        'adjust_transfer_out' => [
-            'value' => 'adjust_transfer_out',
-            'label' => '待调整转出',
-        ],
-        'adjust_transfer_in' => [
-            'value' => 'adjust_transfer_in',
-            'label' => '待调整转入',
-        ],
-        'exchange_recharge' => [
-            'value' => 'exchange_recharge',
-            'label' => '换货充入',
-        ],
-        'exchange_deduct' => [
-            'value' => 'exchange_deduct',
-            'label' => '换货扣除',
-        ],
-        'delete_order_deduct' => [
-            'value' => 'delete_order_deduct',
-            'label' => '删单自动扣除',
-        ],
-        'delete_order_recharge' => [
-            'value' => 'delete_order_recharge',
-            'label' => '删单自动充入',
-        ],
-        'delete_order_return' => [
-            'value' => 'delete_order_return',
-            'label' => '删单扣回',
-        ],
-        'repair_pay' => [
-            'value' => 'repair_pay',
-            'label' => '支付维修费',
-        ],
-        'after_sale_exchange_recharge' => [
-            'value' => 'after_sale_exchange_recharge',
-            'label' => '售后调货充入',
-        ],
-        'after_sale_exchange_deduct' => [
-            'value' => 'after_sale_exchange_deduct',
-            'label' => '售后调货扣费',
-        ],
-        'oms_deduct' => [
-            'value' => 'oms_deduct',
-            'label' => 'OMS扣款',
-        ],
-        'deduct' => [
-            'value' => 'deduct',
-            'label' => '扣除',
-        ],
-        'incr' => [
-            'value' => 'incr',
-            'label' => '增加',
-        ],
-        'other' => [
-            'value' => 'other',
-            'label' => '其它',
-        ],
-        'handle' => [
-            'value' => 'handle',
-            'label' => '管理员手动调整',
-        ],
-    ],
     'enableLog' => true,
-    'isRemoteUpload' => false, // 是否上传至远程
-    'excelLocalDir' => 'excel_export', // 是否上传至远程
+    'isRemoteUpload' => false, 
+    'excelLocalDir' => 'excel_export',
     'superAdminRoleId' => '666A7F102B8D6C66E055736AECE8644D',
     'mainAdminId' => '65F27BCE7FD278FFE055736AECE8644D',
     'mainUserId' => '670B84FD7C216D4EE055736AECE8644D',
-    'hbCouponsProId' => '1000000000', // 货补优惠券
-    'storeDecRoleId' => '8976C62F40064D8AB357BE07C8A3CA8F', // 报单中心里面店铺的ID
-    'countyStoreDecRoleId' => '810916A06B304162902408A6B9E5D177', // 报单中心里面区级店的ID
+    'hbCouponsProId' => '1000000000',
+    'storeDecRoleId' => '8976C62F40064D8AB357BE07C8A3CA8F',
+    'countyStoreDecRoleId' => '810916A06B304162902408A6B9E5D177',
     'daysDiff' => 0,
     'userStatus' => [
         0 => [

+ 0 - 124
common/helpers/bonus/AutoClosePeriod.php

@@ -1,124 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/5/18
- * Time: 下午4:53
- */
-
-namespace common\helpers\bonus;
-
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\models\forms\PeriodForm;
-use common\models\Period;
-use yii\base\BaseObject;
-use yii\base\StaticInstanceTrait;
-
-class AutoClosePeriod extends BaseObject
-{
-    use StaticInstanceTrait;
-
-    const CACHE_PERIOD_NUM_KEY = 'autoClosePeriodNum';
-    const CACHE_PERIOD_CLOSE_STATUS_KEY = 'autoClosePeriodCloseStatus';
-    const CACHE_CLOSE_PERIOD_TIME_KEY = 'autoCloseClosePeriodTime';
-    const CLOSE_PERIOD_STATUS_NORMAL = 1;
-    const CLOSE_PERIOD_STATUS_CLOSING = 2;
-
-    private $_closeInfo;
-
-    public function init()
-    {
-        parent::init();
-    }
-
-    /**
-     * 自动封期
-     * @throws \yii\db\Exception
-     */
-    public function autoClose(){
-        if($this->isAutoClose()){
-            if($this->isToCloseTime()){
-                // 把正在封期状态设置为正在封期
-                $this->setClosingStat();
-                $formModel = new PeriodForm();
-                $formModel->scenario = 'autoClose';
-                $formModel->periodNum = $this->_closeInfo['periodNum'];
-                $formModel->autoClosePeriod();
-                // 更新新的缓存
-                $this->setCloseTimeAndPeriodStat();
-            }
-        }
-    }
-
-    /**
-     * 获取当前系统是否自动封期
-     * @return bool
-     */
-    public function isAutoClose(){
-        $systemConfig = Cache::getSystemConfig();
-        return boolval($systemConfig['autoClosePeriod']['VALUE']);
-    }
-
-    /**
-     * 判断是否到达可以封期
-     * @return bool
-     */
-    public function isToCloseTime(){
-        $closeInfo = $this->_closeInfo = self::getCloseTimeAndPeriodStat();
-        if($closeInfo['periodCloseStatus'] == self::CLOSE_PERIOD_STATUS_CLOSING){
-            return false;
-        }
-        if(Date::nowTime() < $closeInfo['closePeriodTime']){
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * 从缓存中获取封期状态和封期时间
-     * @return array
-     */
-    public function getCloseTimeAndPeriodStat(){
-        $periodNum = \Yii::$app->redis->get(self::CACHE_PERIOD_NUM_KEY);
-        $periodCloseStatus = \Yii::$app->redis->get(self::CACHE_PERIOD_CLOSE_STATUS_KEY);
-        $closePeriodTime = \Yii::$app->redis->get(self::CACHE_CLOSE_PERIOD_TIME_KEY);
-        if((!$periodNum) || (!$periodCloseStatus) || (!$closePeriodTime)){
-            return $this->setCloseTimeAndPeriodStat();
-        }
-        return [
-            'periodNum' => $periodNum,
-            'periodCloseStatus' => $periodCloseStatus,
-            'closePeriodTime' => $closePeriodTime,
-        ];
-    }
-
-    /**
-     * 设置下次封期时间和把本期封期状态设置为正常存入缓存
-     * @return array
-     */
-    public function setCloseTimeAndPeriodStat(){
-        // 先把封期状态设置为正常
-        $periodCloseStatus = self::CLOSE_PERIOD_STATUS_NORMAL;
-        \Yii::$app->redis->set(self::CACHE_PERIOD_CLOSE_STATUS_KEY, $periodCloseStatus);
-        // 找到最近的未封期的期数
-        $periodModel = Period::instance();
-        $periodNum = $periodModel->getNowPeriodNum();
-        \Yii::$app->redis->set(self::CACHE_PERIOD_NUM_KEY, $periodNum);
-        $closePeriodTime = $periodModel->getNowPeriodEnd();
-        \Yii::$app->redis->set(self::CACHE_CLOSE_PERIOD_TIME_KEY, $closePeriodTime);
-        return [
-            'periodNum' => $periodNum,
-            'periodCloseStatus' => $periodCloseStatus,
-            'closePeriodTime' => $closePeriodTime,
-        ];
-    }
-
-    /**
-     * 设置为正在封期
-     */
-    public function setClosingStat(){
-        \Yii::$app->redis->set(self::CACHE_PERIOD_CLOSE_STATUS_KEY, self::CLOSE_PERIOD_STATUS_CLOSING);
-    }
-}

+ 0 - 806
common/helpers/bonus/BonusSend.php

@@ -1,806 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/3/18
- * Time: 上午11:06
- */
-
-namespace common\helpers\bonus;
-
-use common\components\ActiveRecord;
-use common\helpers\DataBak;
-use common\helpers\Form;
-use common\helpers\Tool;
-use common\helpers\user\Balance;
-use common\helpers\user\Info;
-use common\helpers\user\Reconsume;
-use common\helpers\user\Status;
-use common\libs\api\sms\SmsApi;
-use common\libs\swoole\Process;
-use common\models\DealType;
-use common\models\PerfPeriod;
-use common\models\DecOrder;
-use common\models\EmployLevel;
-use common\models\UserBonus;
-use common\models\UserPerfMonthUpdate;
-use common\models\UserPeriodPoints;
-use common\models\UserWallet;
-use common\models\UserInfo;
-use common\models\UserPerf;
-use common\models\UserPerfUpdate;
-use common\models\UserTeamwork;
-use common\models\YearHighestEmpLv;
-use yii\base\BaseObject;
-use yii\base\StaticInstanceTrait;
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\models\CalcBonus;
-use common\models\PerfMonth;
-use common\models\User;
-use Yii;
-use common\models\Period;
-use yii\base\Exception;
-use yii\db\Expression;
-
-class BonusSend extends BaseObject {
-    use StaticInstanceTrait;
-
-    private $_limit = 1000;
-    private $_appUserId = null;
-    private $_sysConfig = [];
-    private $_decLevelConfig = [];
-    private $_empLevelConfig = [];
-    private $_decRoleConfig = [];
-    private $_errors = [];
-    private $_periodNum = 0;
-    private $_periodId;
-    private $_isCalcMonth = 0;
-    private $_isCalcYear = 0;
-    private $_calcYear;
-    private $_calcMonth;
-    private $_calcYearMonth;
-    private $_lastCalcYear;
-    private $_lastCalcMonth;
-    private $_lastCalcYearMonth;
-    private $_workerId;
-    private $_workerNum;
-
-    public function init(int $periodNum = 0, $appUserId = null, $workerId = null, $workerNum = null) {
-        parent::init();
-        $this->_sysConfig = Cache::getSystemConfig();
-        $this->_decLevelConfig = Cache::getDecLevelConfig();
-        $this->_empLevelConfig = Cache::getEmpLevelConfig();
-        $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
-        $this->_periodNum = $periodNum;
-        $this->_appUserId = $appUserId;
-        $this->_workerId = $workerId;
-        $this->_workerNum = $workerNum;
-    }
-
-    /**
-     * 设置期数
-     * @param int $periodNum
-     * @return int
-     */
-    public function setPeriodNum(int $periodNum) {
-        return $this->_periodNum = $periodNum;
-    }
-
-    /**
-     * 获取期数
-     * @return int
-     */
-    public function getPeriodNum() {
-        return $this->_periodNum;
-    }
-
-    /**
-     * 加入错误错误
-     * @param $attr
-     * @param $error
-     */
-    public function addError($attr, $error) {
-        $this->_errors[$attr][] = $error;
-    }
-
-    /**
-     * 获取错误信息
-     * @return array
-     */
-    public function getErrors() {
-        return $this->_errors;
-    }
-
-    /**
-     * 进行奖金发放步骤
-     * @return bool
-     */
-    public function sendStep() {
-        try {
-            $t1 = microtime(true);
-            // 初始化
-            $this->initTask();
-            $t2 = microtime(true);
-            echo('初始化完成,当前期数【' . $this->_periodNum . '】,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            // 改变状态
-            $this->setSendStatus('start');
-            $t3 = microtime(true);
-            echo('改变状态完成,耗时:' . round($t3 - $t2, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(20);
-            //Yii::$app->db->close();
-            //Yii::$app->dbShop->close();
-            // 更新聘级
-            $this->updateEmpLevel();
-            $this->_updatePercent(40);
-            $t4 = microtime(true);
-            echo('更新聘级完成,耗时:' . round($t4 - $t3, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            // 发放奖金
-            $this->sendBonusLoop();
-            $this->_updatePercent(60);
-            $t5 = microtime(true);
-            echo('发放奖金完成,耗时:' . round($t5 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            // 更新会员上次报单级别
-//            $this->updateUserDevLv();
-//            $this->_updatePercent(80);
-            $t6 = microtime(true);
-//            echo('更新会员上次报单级别完成,耗时:' . round($t6 - $t5, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            // 更新会员累计业绩
-            $this->updateUserPerf();
-            $this->_updatePercent(80);
-            $t7 = microtime(true);
-            echo('更新会员累计业绩完成,耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-
-            $this->updateUserPerfMonth();
-            $this->_updatePercent(90);
-            $t8 = microtime(true);
-            echo('更新会员累计月业绩完成,耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-
-            // 开启子进程去完成下面的循环发放和循环改聘级和循环更新累计业绩
-            /*$process = new Process('sendBonus', 3);
-            $process->run(function($workId, $pmid){
-                $this->processStep($workId);
-            });
-            while (true){
-                if($process->isFinish()) break;
-            }
-            unset($process);
-            $this->_updatePercent(90);
-            $t4 = microtime(true);
-            echo('所有子进程的任务完成,耗时:'.round($t4 - $t3, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);*/
-            echo('全部奖金发放完成,耗时:'.round($t7 - $t1, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);
-            $this->_updatePercent(100);
-        } catch (\Exception $e) {
-            $this->addError('sendBonus', $e->getMessage());
-            return false;
-        }
-        if (count($this->_errors) > 0) {
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * 需要多进程执行的任务
-     * @param $workId
-     * @throws \yii\db\Exception
-     */
-    public function processStep($workId = null) {
-        if ($workId == 1 || $workId === null) {
-            // 发放奖金
-            $this->sendBonusLoop();
-        }
-        if ($workId == 2 || $workId === null) {
-            // 更新聘级
-            $this->updateEmpLevel();
-        }
-        if ($workId == 3 || $workId === null) {
-            // 更新会员累计业绩
-            $this->updateUserPerf();
-        }
-        Yii::$app->db->close();
-        Yii::$app->dbShop->close();
-    }
-
-    /**
-     * 初始化发放任务
-     * @throws Exception
-     */
-    public function initTask() {
-        $this->_errors = [];
-        $periodNum = $this->_periodNum;
-        // 获取传入期数的相关信息
-        $periodObj = Period::instance();
-        $periodDataArr = $periodObj->setPeriodNum($periodNum);
-        $this->_periodId = $periodDataArr['ID'];
-        $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
-        $this->_calcYear = $periodObj->getYear($periodNum);
-        $this->_calcMonth = $periodObj->getMonth($periodNum);
-        $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
-        $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
-        $this->_lastCalcYear = $lastYearMonthArr['year'];
-        $this->_lastCalcMonth = $lastYearMonthArr['month'];
-        $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
-    }
-
-    /**
-     * 设置结算状态
-     * @param $type
-     * start|end|fail
-     */
-    public function setSendStatus($type) {
-        Yii::$app->db->close();
-        if ($type == 'start') {
-            Period::updateAll(['IS_SENDING' => 1, 'SEND_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
-        } elseif ($type == 'end') {
-            Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FINISH, 'SENT_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
-        } elseif ($type == 'fail') {
-            Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FAIL, 'SENT_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
-        }
-    }
-
-    /**
-     * 结束计算任务
-     * @throws \yii\db\Exception
-     */
-    public function endTask() {
-        CalcCache::clearAll($this->_periodNum);
-        $this->setSendStatus('end');
-        //@todo 先不备份数据
-//        DataBak::backup($this->_periodNum);
-        //发送复销短信
-//        if ($this->_isCalcMonth && $this->_sysConfig['smsOpen']['VALUE']) {
-//            $this->sendSmsLoop();
-//        }
-    }
-
-    /**
-     * 出现错误
-     */
-    public function errorTask() {
-        $this->setSendStatus('fail');
-    }
-
-    /**
-     * 发放奖金
-     * @param int $page
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function sendBonusLoop($page=1) {
-        echo sprintf("时间:[%s]数据库发奖,当前page为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $page);
-        $periodNum = $this->_periodNum;
-        // 从奖金结算表中获取当期未发放的所有数据
-        $allData = CalcBonus::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('(IS_SENT=0 OR IS_SENT=2) AND CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM', [':CALC_MONTH' => $this->_calcYearMonth, ':PERIOD_NUM' => $periodNum])->limit($this->_limit)->asArray()->all();
-        if ($allData) {
-            $transaction = Yii::$app->db->beginTransaction();
-            try {
-                foreach ($allData as $key => $data) {
-                    // 期奖金
-//                    $periodAmount = $data['BONUS_QY'] + $data['BONUS_YC'] + $data['BONUS_XF'] + $data['BONUS_BD'] + $data['BONUS_TG'] + $data['BONUS_YJ'] + $data['BONUS_GX'] + $data['BONUS_GL'];
-                    $periodAmount = $data['BONUS_REAL'];
-                    // 获取本期结算的管理员
-//                    $period = Period::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
-//                    $updateAminId = $period['CALC_ADMIN_ID'];
-                    if ($periodAmount > 0) {
-                        Balance::changeUserBonus($data['USER_ID'], 'bonus', $periodAmount, [
-                            'CALC_ID' => $data['ID'],
-                            'REMARK' => 'From ' . $periodNum . '期',
-                            'PERIOD_NUM' => $periodNum,
-                            'QY' => $data['BONUS_QY'],
-                            'FW' => $data['BONUS_FW'],
-                            'YC' => $data['BONUS_YC'],
-                            'VIP' => $data['BONUS_VIP'],
-                            'BD' => $data['BONUS_BD'],
-                            'TG' => $data['BONUS_TG'],
-                            'YJ' => $data['BONUS_YJ'],
-                            'GX' => $data['BONUS_GX'],
-                            'GL' => $data['BONUS_GL'],
-
-                            'ORI_QY' => $data['ORI_BONUS_QY'],
-                            'ORI_YC' => $data['ORI_BONUS_YC'],
-                            'ORI_VIP' => $data['ORI_BONUS_VIP'],
-                            'ORI_STANDARD' => $data['ORI_BONUS_STANDARD'],
-                            'ORI_BD' => $data['ORI_BONUS_BD'],
-                            'ORI_TG' => $data['ORI_BONUS_TG'],
-                            'ORI_YJ' => $data['ORI_BONUS_YJ'],
-                            'ORI_GX' => $data['ORI_BONUS_GX'],
-                            'ORI_GL' => $data['ORI_BONUS_GL'],
-
-                            'RECONSUME_POINTS_TOTAL' => $data['RECONSUME_POINTS'],
-                            'MANAGE_TAX' => $data['MANAGE_TAX'],
-
-                            'BONUS_TOTAL' => $data['BONUS_TOTAL'],
-
-                            'DEAL_TYPE_ID' => DealType::BONUS_SEND,
-                            'SORT' => $key * 10,
-                        ]);
-//                        $this->_teamworkBonus($data['USER_ID'], $periodAmount, $key);
-                    }
-
-                    //发放重消积分
-                    if ($data['RECONSUME_POINTS'] > 0) {
-                        Balance::changeUserBonus($data['USER_ID'], 'reconsume_points', $data['RECONSUME_POINTS'], [
-                            'CALC_ID' => $data['ID'],
-                            'REMARK' => 'From ' . $periodNum . '期',
-                            'PERIOD_NUM' => $periodNum,
-                            'RECONSUME_POINTS' => $data['RECONSUME_POINTS'],
-                            'DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_SEND,
-                        ]);
-                    }
-                    // 把记录标记为已发放状态
-                    CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
-
-                    unset($periodAmount, $key, $data);
-                }
-                $transaction->commit();
-            } catch (Exception $e) {
-                $transaction->rollBack();
-                $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getMessage());
-                return false;
-            }
-
-            unset($allData, $transaction);
-            $page++;
-            return $this->sendBonusLoop($page);
-        }
-
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 更新会员聘级
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function updateEmpLevel(int $offset = 0) {
-        if ($this->_isCalcMonth) {
-            $allData = PerfMonth::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->offset($offset)->limit($this->_limit)->all();
-            //@todo 用户级别不变则不更新
-            $defaultEmpLv = EmployLevel::getDefaultLevelId();
-            if ($allData) {
-                $transaction = Yii::$app->db->beginTransaction();
-                try {
-                    foreach ($allData as $data) {
-                        //@todo 用户级别不变则不更新
-                        if( $data['LAST_EMP_LV'] === $defaultEmpLv ) continue;
-
-                        User::updateAll(['EMP_LV' => $data['LAST_EMP_LV']], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
-                        User::deleteBaseInfoFromRedis($data['USER_ID']);
-                        unset($data);
-                    }
-                    $transaction->commit();
-                } catch (Exception $e) {
-                    $transaction->rollBack();
-                    $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
-                    return false;
-                }
-                unset($transaction, $allData, $defaultEmpLv);
-                return $this->updateEmpLevel($offset + $this->_limit);
-            }
-            unset($allData);
-        }
-        return true;
-    }
-
-    /**
-     * 更新会员的累计业绩
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function updateUserPerf(int $offset = 0) {
-        $allData = PerfPeriod::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
-        if ($allData) {
-            $transaction = Yii::$app->db->beginTransaction();
-            try {
-                foreach ($allData as $data) {
-                    $isUpdate = false;
-                    if (UserPerf::findUseDbCalc()->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
-                        // 判断本期是否已经更新过业绩
-                        if (!UserPerfUpdate::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $data['USER_ID'], ':PERIOD_NUM' => $this->_periodNum])->exists()) {
-                            $isUpdate = true;
-                            // 更新业绩
-                            UserPerf::updateAll([
-                                'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
-                                'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
-                                'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
-                                'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
-                                'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
-                                'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
-                                'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
-                                'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
-                                'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
-                                'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
-                                'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
-                                'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
-                                'SURPLUS_1L' => $data['SURPLUS_1L'],
-                                'SURPLUS_2L' => $data['SURPLUS_2L'],
-                                'SURPLUS_3L' => $data['SURPLUS_3L'],
-                                'SURPLUS_4L' => $data['SURPLUS_4L'],
-                                'SURPLUS_5L' => $data['SURPLUS_5L'],
-                                'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
-                                'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
-                                'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
-                                'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
-                                'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
-                                'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
-                                'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
-                                'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
-                                'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
-                                'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
-                            ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
-                        }
-                    } else {
-                        $isUpdate = true;
-                        UserPerf::insertOne([
-                            'USER_ID' => $data['USER_ID'],
-                            'PV_PCS_ZC' => $data['PV_PCS_ZC'],
-                            'PV_PCS_YH' => $data['PV_PCS_YH'],
-                            'PV_PCS_ZG' => $data['PV_PCS_ZG'],
-                            'PV_PCS_LS' => $data['PV_PCS_LS'],
-                            'PV_PCS_FX' => $data['PV_PCS_FX'],
-                            'PV_PSS' => $data['PV_PSS'],
-                            'PV_PSS_TOTAL' => $data['PV_PSS'],
-                            'PV_1L' => $data['PV_1L'],
-                            'PV_2L' => $data['PV_2L'],
-                            'PV_3L' => $data['PV_3L'],
-                            'PV_4L' => $data['PV_4L'],
-                            'PV_5L' => $data['PV_5L'],
-                            'SURPLUS_1L' => $data['SURPLUS_1L'],
-                            'SURPLUS_2L' => $data['SURPLUS_2L'],
-                            'SURPLUS_3L' => $data['SURPLUS_3L'],
-                            'SURPLUS_4L' => $data['SURPLUS_4L'],
-                            'SURPLUS_5L' => $data['SURPLUS_5L'],
-                            'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
-                            'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
-                            'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
-                            'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
-                            'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
-                            'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
-                            'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
-                            'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
-                            'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
-                            'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
-                            'CREATED_AT' => Date::nowTime(),
-                        ]);
-                    }
-                    if ($isUpdate) {
-                        // 变为已更新
-                        UserPerfUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'PERIOD_NUM' => $this->_periodNum, 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH), 'CREATED_AT' => Date::nowTime()]);
-                    }
-
-                    unset($data, $isUpdate);
-                }
-                $transaction->commit();
-            } catch (Exception $e) {
-                $transaction->rollBack();
-                $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
-                return false;
-            }
-            unset($allData, $transaction);
-            return $this->updateUserPerf($offset + $this->_limit);
-
-        }
-        unset($allData);
-        return true;
-    }
-
-
-    /**
-     * 更新会员的月剩余业绩
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function updateUserPerfMonth(int $offset = 0) {
-        // 月结,如果不是月结点,则直接退出
-        if (!$this->_isCalcMonth) {
-            return true;
-        }
-        $allData = PerfMonth::findUseDbCalc()->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
-        if ($allData) {
-            $transaction = Yii::$app->db->beginTransaction();
-            try {
-                foreach ($allData as $data) {
-                    $isUpdate = false;
-                    if (UserPerf::findUseDbCalc()->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
-                        // 判断本期是否已经更新过业绩
-                        if (!UserPerfMonthUpdate::findUseDbCalc()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $data['USER_ID'], ':CALC_MONTH' => $this->_calcYearMonth])->exists()) {
-                            $isUpdate = true;
-                            // 更新业绩
-                            UserPerf::updateAll([
-                                'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
-                                'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
-                                'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
-                                'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
-                                'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC']
-                            ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
-                        }
-                    } else {
-                        $isUpdate = true;
-                        UserPerf::insertOne([
-                            'USER_ID' => $data['USER_ID'],
-                            'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
-                            'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
-                            'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
-                            'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
-                            'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC'],
-                            'CREATED_AT' => Date::nowTime(),
-                        ]);
-                    }
-                    if ($isUpdate) {
-                        // 变为已更新
-                        UserPerfMonthUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'CALC_MONTH' => $this->_calcYearMonth, 'CREATED_AT' => Date::nowTime()]);
-                    }
-
-                    unset($data, $isUpdate);
-                }
-                $transaction->commit();
-            } catch (Exception $e) {
-                $transaction->rollBack();
-                $this->addError('updateUserPerf', '更新会员月业绩失败,原因:' . $e->getMessage());
-                return false;
-            }
-            unset($allData, $transaction);
-            return $this->updateUserPerfMonth($offset + $this->_limit);
-
-        }
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 检测复消积分是否过期
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function checkReconsumePointsExpired(int $offset = 0) {
-        $periodNum = $this->_periodNum;
-        //一期为7天,那么365天为52.14即53期
-        $expiredPeriodNum = $periodNum - 53;
-        if( $expiredPeriodNum <= 0 ) return true;
-
-        //查询需要过期的期数
-        $allData = UserPeriodPoints::find()->select('ID,USER_ID,REMAINDER_POINTS')->where('PERIOD_NUM<=:PERIOD_NUM AND EXPIRED=0', ['PERIOD_NUM'=>$expiredPeriodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->asArray()->all();
-        if( $allData ) {
-            $transaction = Yii::$app->db->beginTransaction();
-            try{
-                //扣除钱包的复消积分
-                foreach ($allData as $everyData) {
-                    //过期
-                    UserPeriodPoints::updateAll([
-                        'REMAINDER_POINTS' => 0,
-                        'EXPIRED' => 1,
-                        'EXPIRED_PERIOD' => $periodNum,
-                        'EXPIRED_AT' => Date::nowTime(),
-                    ], 'ID=:ID', ['ID'=>$everyData['ID']]);
-
-                    if( !isset($everyData['REMAINDER_POINTS']) || !$everyData['REMAINDER_POINTS'] ) continue;
-
-                    UserBonus::updateAllCounters([
-                        'RECONSUME_POINTS' => (-1) * $everyData['REMAINDER_POINTS'],
-                    ], 'USER_ID=:USER_ID', $everyData['USER_ID']);
-
-                    unset($everyData);
-                }
-                unset($periodNum, $expiredPeriodNum, $allData);
-
-                $transaction->commit();
-            }catch (\Exception $e){
-                $transaction->rollBack();
-                $this->addError('checkReconsumePointsExpired', '检测过期在复消积分失败,原因:' . $e->getMessage());
-                return false;
-            }
-
-            return $this->checkReconsumePointsExpired($offset + $this->_limit);
-        }
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 更新会员上次报单级别
-     * @return bool
-     */
-    public function updateUserDevLv() {
-        $transaction = Yii::$app->dbShop->beginTransaction();
-        try {
-            \Yii::$app->dbShop->createCommand()->update(User::tableName(), ['LAST_DEC_LV' => new Expression('DEC_LV'), 'LAST_DEC_LV_UPDATED_AT' => Date::nowTime(), 'LAST_DEC_LV_UPDATED_PERIOD' => $this->_periodNum], 'LAST_DEC_LV!=DEC_LV')->execute();
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('updateUserDevLv', '更新会员上次报单级别失败,原因:' . $e->getMessage());
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * 给商城会员增加货款
-     * @param $userId
-     * @param $amount
-     * @param $remark
-     * @throws Exception
-     */
-    private function _shopAddPaymentForGoods($userId, $amount, $remark) {
-        $db = \Yii::$app->dbShop;
-        $transaction = $db->beginTransaction();
-        try {
-            ActiveRecord::batchUpdate(['PAYMENT_FOR_GOODS' => new Expression('PAYMENT_FOR_GOODS+' . abs($amount))], 'USER_ID=:USER_ID', [':USER_ID' => $userId], '{{%USER_WALLET}}', 'dbShop');
-            // 增加流水
-            $flowInsertData[] = [
-                'USER_ID' => $userId,
-                'USER_NAME' => Cache::getUserBaseInfo($userId)['USER_NAME'],
-                'DEC_LV' => Cache::getUserBaseInfo($userId)['DEC_LV'],
-                'ORDER_SN' => null,
-                'AMOUNT' => $amount,
-                'CREATED_AT' => Date::nowTime(),
-                'PERIOD_AT' => $this->_periodNum,
-                'IS_INCR' => 1,
-                'REMARK' => $remark,
-                'PARTITION_DATE' => Date::ociToDate(),
-                'WALLET_TYPE' => 'payment_for_goods',
-                'FROM_TYPE' => 'incr',
-            ];
-            ActiveRecord::batchInsert($flowInsertData, '{{%FLOW_WALLET}}', 'dbShop');
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            throw new Exception($e->getMessage());
-        }
-    }
-
-    /**
-     * 更新百分比并发送
-     * @param $percent
-     */
-    private function _updatePercent($percent) {
-        // 把数据写入数据库中
-        Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
-        \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'SENT_PERCENT']);
-    }
-
-    /**
-     * 更新最高聘级
-     * @param $user_id
-     * @return bool
-     * @throws Exception
-     */
-    private function _updateHighestEmpLv($user_id) {
-        $empLv = Info::getEmpLv($user_id);
-        $highEmpLv = Info::getHighEmpLv($user_id);
-        $empLvSort = EmployLevel::getSortById($empLv);
-        $empLvHighSort = EmployLevel::getSortById($highEmpLv);
-        if ($empLvHighYear = YearHighestEmpLv::findOneAsArray('USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear], 'HIGHEST_EMP_LV_SORT')) {
-            if ($empLvSort > $empLvHighYear['HIGHEST_EMP_LV_SORT']) {
-                YearHighestEmpLv::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_SORT' => $empLvSort, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum, 'UPDATED_AT' => Date::nowTime()], 'USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear]);
-            }
-        } else {
-            $yearHighest = new YearHighestEmpLv();
-            $yearHighest->USER_ID = $user_id;
-            $yearHighest->YEAR = $this->_calcYear;
-            $yearHighest->HIGHEST_EMP_LV = $empLv;
-            $yearHighest->HIGHEST_EMP_LV_SORT = $empLvSort;
-            $yearHighest->HIGHEST_EMP_LV_PERIOD = $this->_periodNum;
-            $yearHighest->CREATED_AT = Date::nowTime();
-            if (!$yearHighest->save()) {
-                throw new \yii\db\Exception(Form::formatErrorsForApi($yearHighest->getErrors()));
-            }
-        }
-        if ($empLvSort > $empLvHighSort) {
-            UserInfo::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum], 'USER_ID=:USER_ID', [':USER_ID' => $user_id]);
-            //发送历史最高聘级短信
-            if($this->_sysConfig['smsEmpOpen']['VALUE']){
-                if(in_array($empLvSort,explode(",",$this->_sysConfig['smsEmp']['VALUE']))){
-                    $realName = Info::getUserRealNameByUserId($user_id);
-                    $empLvDate = Date::convert();
-                    $empLvName = EmployLevel::getNameById($empLv);
-                    $content = str_replace(['{%REAL_NAME%}', '{%EMP_LV_DATE%}', '{%EMP_LV%}'], [$realName, $empLvDate, $empLvName], $this->_sysConfig['smsContent']['VALUE']);
-                    $params = [
-                        'mobiles' => Info::getUserMobileByUserId($user_id),
-                        'content' => $content,
-                    ];
-                    SmsApi::instance()->clearError();
-                    SmsApi::instance()->goSend($params);
-                }
-            }
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * 点位合作奖金
-     * @param $userId
-     * @param $amount
-     * @param null $type
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    private function _teamworkBonus($userId, $amount, $key) {
-        if (!$teamwork = UserTeamwork::findAllAsArray('USER_ID!=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userId], 'USER_ID,DIVIDE_PERCENT')) return false;
-        $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
-        foreach ($teamwork as $value) {
-            $bonus = Tool::formatPrice($amount * $value['DIVIDE_PERCENT'] * 0.01);
-            if ($bonus <= 0) continue;
-            $toUserInfo = CalcCache::getUserInfo($value['USER_ID'], $this->_periodNum);
-            Balance::changeUserBonus($userId, 'bonus', -abs($bonus), ['SORT' => $key*10+1, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_OUT, 'REMARK' => 'To:' . $toUserInfo['USER_NAME'] . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
-            Balance::changeUserBonus($value['USER_ID'], 'bonus', abs($bonus), ['SORT' => $key*10+2, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_IN, 'REMARK' => 'From: ' . $fromUserInfo['USER_NAME'] . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
-        }
-    }
-
-    /**
-     * 发送短信
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function sendSmsLoop(int $offset = 0) {
-        $allData = UserInfo::findUseDbCalc()->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
-        if ($allData) {
-            $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
-            $smsFee = $this->_sysConfig['smsFee']['VALUE'];
-            //获取剩余月份
-            $period = Period::instance();
-            $year = $period->getYear($this->_periodNum);
-            $monthLeft = Period::getMonthLeft($this->_periodNum);
-            $smsFee = Tool::formatPrice($smsFee * $monthLeft);
-            $to = Date::yearEnd();
-            $transaction = Yii::$app->db->beginTransaction();
-            try {
-                foreach ($allData as $data) {
-                    $userId = $data['USER_ID'];
-                    //过期续费
-                    if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
-                        foreach ($smsWallet as $item) {
-                            //1奖金钱包2现金钱包
-                            if ($item == 1) {
-                                //看余额是否充足
-                                if (Balance::getAvailableBalance($userId) < $smsFee){
-                                    UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-                                    continue;
-                                };
-                                Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
-                                UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-                                $data['ALLOW_RECONSUME_SMS_TO'] = $to;
-                                break;
-                            } elseif ($item == 2) {
-                                throw new Exception('不存在此方式');
-                                break;
-                            }
-                        }
-                    }
-                    if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
-                        $realName = Info::getUserRealNameByUserId($userId);
-                        $reconsumPool = Reconsume::getUserReconsumePool($userId);
-                        $lastRechargeDate = $reconsumPool['toRechargeDate'];
-                        $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
-                        $month = $period->getNowMonth();
-                        $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
-                        //todo 发短信函数 待测试
-                        $params = [
-                            'mobiles' => $mobile,
-                            'content' => $content,
-                        ];
-                        SmsApi::instance()->clearError();
-                        SmsApi::instance()->goSend($params);
-                    }
-                    unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
-                }
-                $transaction->commit();
-            } catch (Exception $e) {
-                $transaction->rollBack();
-                return false;
-            }
-            unset($data);
-            return $this->sendSmsLoop($offset + $this->_limit);
-
-        }
-        unset($allData);
-        return true;
-    }
-}

+ 0 - 1622
common/helpers/bonus/CalcCache.php

@@ -1,1622 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/8/2
- * Time: 上午10:38
- */
-
-namespace common\helpers\bonus;
-
-use common\components\Redis;
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\helpers\user\Info;
-use common\models\CalcBonus;
-use common\models\PerfMonth;
-use common\models\PerfPeriod;
-use common\models\Period;
-use common\models\DeclarationLevel;
-use common\models\DecRole;
-use common\models\EmployLevel;
-use common\models\User;
-use common\models\UserBonus;
-use common\models\UserNetwork;
-use common\models\UserPerf;
-use common\models\UserRelation;
-use Yii;
-use common\models\UserInfo;
-use yii\helpers\Json;
-
-class CalcCache {
-    const LIMIT = 1000;
-
-    const REDIS_KEY_PREFIX_USER = 'calc:user_';
-    const REDIS_KEY_PREFIX_USER_ACTIVE = 'calc:userActive_';
-    const REDIS_KEY_PREFIX_USER_INFO = 'calc:userInfo_';
-    const REDIS_KEY_PREFIX_USER_BONUS = 'calc:userBonus_';
-    const REDIS_KEY_PREFIX_PERIOD_MONTH_CALC_BONUS = 'calc:periodMonthCalcBonus_';
-    const REDIS_KEY_PREFIX_USER_PERF = 'calc:userPerf_';
-    const REDIS_KEY_PREFIX_SURPLUS_PERF = 'calc:spPerf_';
-    const REDIS_KEY_PREFIX_NOW_PERIOD_PERF = 'calc:nowPeriodPerf_';
-    const REDIS_KEY_PREFIX_NOW_STANDARD_MONTH_PERF = 'calc:nowStandardMonthPerf_';
-    const REDIS_KEY_PREFIX_LAST_MONTH_PERF = 'calc:lastMonthPerf_';
-    const REDIS_KEY_PREFIX_NOW_MONTH_PERF = 'calc:nowMonthPerf_';
-    const REDIS_KEY_PREFIX_NOW_MONTH_SCORE = 'calc:nowMonthScore_';
-    const REDIS_KEY_PREFIX_NOW_MONTH_LAST_PERIOD_RECONSUME_POINTS = 'calc:nowMonthLastPeriodReconsumePoints_';
-    const REDIS_KEY_PREFIX_EMP_NUM_PERF = 'calc:empLevelNum_';
-    const REDIS_KEY_PREFIX_BONUS = 'calc:bonus_';
-    const REDIS_KEY_PREFIX_STANDARD_BONUS = 'calc:standard:bonus_';
-    const REDIS_KEY_PREFIX_YC_BONUS = 'calc:yc:bonus_';
-    const REDIS_KEY_PREFIX_FW_BONUS = 'calc:fw:bonus_';
-    const REDIS_KEY_PREFIX_HAS_PERF_USER = 'calc:hasPerfUser_';
-    const REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER = 'calc:hasMonthPerfUser_';
-    const REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER = 'calc:hasStandardMonthPerfUser_';
-    const REDIS_KEY_PREFIX_HAS_BD_USER = 'calc:hasBDUser_';
-    const REDIS_KEY_PREFIX_HAS_INCOME_USER = 'calc:hasIncomeUser_';
-    const REDIS_KEY_PREFIX_HAS_BONUS_USER = 'calc:hasBonusUser_';
-    const REDIS_KEY_PREFIX_HAS_YC_BONUS_USER = 'calc:hasYcBonusUser_';
-    const REDIS_KEY_PREFIX_HAS_FW_BONUS_USER = 'calc:hasFwBonusUser_';
-    const REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER = 'calc:hasMonthBonusUser_';
-    const REDIS_KEY_PREFIX_HAS_PERF_USER_POOL = 'calc:hasPerfUserPool_';
-    const REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER_POOL = 'calc:hasMonthPerfUserPool_';
-    const REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER_POOL = 'calc:hasStandardMonthPerfUserPool_';
-    const REDIS_KEY_PREFIX_HAS_BD_USER_POOL = 'calc:hasBDUserPool_';
-    const REDIS_KEY_PREFIX_HAS_INCOME_USER_POOL = 'calc:hasIncomeUserPool_';
-    const REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL = 'calc:hasBonusUserPool_';
-    const REDIS_KEY_PREFIX_HAS_YC_BONUS_USER_POOL = 'calc:hasYcBonusUserPool_';
-    const REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL = 'calc:hasFwBonusUserPool_';
-    const REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER_POOL = 'calc:hasMonthBonusUserPool_';
-    const REDIS_KEY_PREFIX_HAS_SCORE_USER = 'calc:hasScoreUser_';
-    const REDIS_KEY_PREFIX_HAS_SCORE_USER_POOL = 'calc:hasScoreUserPool_';
-    const REDIS_KEY_PREFIX_HAS_LS_PCS_USER = 'calc:hasLSPCSUser_';
-    const REDIS_KEY_PREFIX_HAS_LS_PCS_USER_POOL = 'calc:hasLSPCSUserPool_';
-    const REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER = 'calc:hasCFPercentPCSUser_';
-    const REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER_POOL = 'calc:hasCFPercentPCSUserPool_';
-    const REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER = 'calc:hasLXPercentPCSUser_';
-    const REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER_POOL = 'calc:hasLXPercentPCSUserPool_';
-    const REDIS_KEY_PREFIX_DEC_ROLE_CONFIG = 'calc:decRoleConfig_';
-    const REDIS_KEY_PREFIX_CF_TOTAL_PERCENT = 'calc:cfTotalPercent_';
-    const REDIS_KEY_PREFIX_LX_TOTAL_PERCENT = 'calc:lxTotalPercent_';
-    const REDIS_KEY_PREFIX_USER_INFO_CHILD_ONE_DEEP = 'calc:userInfo:ChildOneDeep_';
-    const REDIS_KEY_PREFIX_GX_BONUS_DEEP_ONE_LIST_DATA = 'calc:gxBonusDeepOneListData_';
-    const REDIS_KEY_PREFIX_GX_BONUS_DEEP_TWO_LIST_DATA = 'calc:gxBonusDeepTwoListData_';
-    const REDIS_KEY_PREFIX_YC_BONUS_LIST_DATA = 'calc:ycBonusListData_';
-    const REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA = 'calc:fwBonusListData_';
-
-    //@todo
-    const REDIS_KEY_PREFIX_REPAIR_SURPLUS_PERF = 'calc:repairSurplusPerf_';
-    const REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER = 'calc:hasRepairPerfUser_';
-    const REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER_POOL = 'calc:hasRepairPerfPool_';
-
-    //收入的奖金类型
-//    const INCOME_TG_BONUS = 'BONUS_TG';
-//    const INCOME_XF_BONUS = 'BONUS_XF';
-//    const INCOME_YJ_BONUS = 'BONUS_YJ';
-//    const INCOME_QY_BONUS = 'BONUS_QY';
-    const INCOME_QY_BONUS_BD = 'BONUS_QY_BD';
-    const INCOME_QY_BONUS_FX = 'BONUS_QY_FX';
-    const INCOME_BONUS_LIST = [
-//        self::INCOME_TG_BONUS,
-//        self::INCOME_XF_BONUS,
-//        self::INCOME_YJ_BONUS,
-//        self::INCOME_QY_BONUS,
-        self::INCOME_QY_BONUS_BD,
-//        self::INCOME_QY_BONUS_FX,
-    ];
-    const NOT_SEND_BONUS_LIST = [
-        self::INCOME_QY_BONUS_BD,
-        self::INCOME_QY_BONUS_FX,
-    ];
-
-    const FROM_MEANS_BD = 'BD';
-    const FROM_MEANS_FX = 'FX';
-
-    /**
-     * 结算奖金时要清空的缓存
-     * @param $periodNum
-     */
-    public static function clearCalcBonusCache($periodNum) {
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BONUS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_STANDARD_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_YC_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_YC_BONUS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_YC_BONUS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_GX_BONUS_DEEP_ONE_LIST_DATA . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_GX_BONUS_DEEP_TWO_LIST_DATA . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_YC_BONUS_LIST_DATA . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_FW_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum);
-    }
-
-    /**
-     * 清网络缓存
-     */
-    public static function clearNetCache(){
-        \Yii::$app->redis->del(Cache::USER_NETWORK_PARENTS);
-        \Yii::$app->redis->del(Cache::USER_RELATION_PARENTS);
-    }
-
-    /**
-     * 清空所有临时计算用到的缓存
-     * @param $periodNum
-     */
-    public static function clearAll($periodNum) {
-        //Yii::$app->redis->del(Yii::$app->redis->keys('calc*'));
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_ACTIVE . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_INFO . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_PERIOD_MONTH_CALC_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_SURPLUS_PERF . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_PERF . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_NOW_PERIOD_PERF . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_NOW_STANDARD_MONTH_PERF . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_LAST_MONTH_PERF . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_NOW_MONTH_PERF . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_NOW_MONTH_SCORE . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_NOW_MONTH_LAST_PERIOD_RECONSUME_POINTS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_EMP_NUM_PERF . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_STANDARD_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_YC_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_FW_BONUS . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_PERF_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_PERF_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BD_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BD_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_INCOME_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_INCOME_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BONUS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_YC_BONUS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_YC_BONUS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_SCORE_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_SCORE_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_LS_PCS_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_LS_PCS_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER_POOL . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_DEC_ROLE_CONFIG . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_INFO_CHILD_ONE_DEEP . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_GX_BONUS_DEEP_ONE_LIST_DATA . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_GX_BONUS_DEEP_TWO_LIST_DATA . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_YC_BONUS_LIST_DATA . $periodNum);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum);
-    }
-
-    /**
-     * 会员信息加入缓存
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return bool
-     */
-    public static function addUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-//        echo sprintf("时间:[%s]缓存用户,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
-        // 修复USER_INFO表里面已经没有PERIOD_NUM了
-        $allData = UserInfo::findUseDbCalc()->from(UserInfo::tableName(). 'AS UI')->select('UI.USER_ID,U.STATUS')->leftJoin(User::tableName() . 'AS U', 'U.ID=UI.USER_ID')->where('1=1')->orderBy('UI.RELATION_DEEP DESC,UI.ID DESC')->offset($offset)->limit($limit)->asArray()->all();
-        //$allData = User::findUseDbShopCalc()->select('ID AS USER_ID')->where('PERIOD_AT<=:PERIOD_AT AND IS_UNION=0 AND DELETED=0', [':PERIOD_AT' => $periodNum])->offset($offset)->limit($limit)->asArray()->all();
-        if ($allData) {
-            foreach ($allData as $data) {
-//                if(User::find()->where('ID=:ID',[':ID'=>$data['USER_ID']])->exists()) continue;
-                // 会员ID加入缓存
-                $cacheKey = self::REDIS_KEY_PREFIX_USER . $periodNum;
-                $value = $data['USER_ID'];
-                Yii::$app->redis->rpush($cacheKey, $value);
-                if( $data['STATUS'] == 1 ) {
-                    $activeCacheKey = self::REDIS_KEY_PREFIX_USER_ACTIVE . $periodNum;
-                    Yii::$app->redis->rpush($activeCacheKey, $value);
-                    unset($activeCacheKey);
-                }
-                unset($data, $cacheKey, $value);
-            }
-            unset($allData);
-            return self::addUsers($periodNum, $offset + $limit, $limit);
-        }
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 获取会员从缓存中
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 获取激活会员从缓存中
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getActiveUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_USER_ACTIVE . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 加入有业绩的会员
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasPerfUsers($userId, $periodNum) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_PERF_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_PERF_USER_POOL . $periodNum, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_PERF_USER . $periodNum, $userId);
-        }
-        unset($userId, $periodNum, $isset);
-    }
-
-    /**
-     * 获取有业绩的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasPerfUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_PERF_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 加入有月业绩的会员
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasMonthPerfUsers($userId, $periodNum) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER_POOL . $periodNum, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER . $periodNum, $userId);
-        }
-        unset($userId, $periodNum, $isset);
-    }
-
-    /**
-     * 获取有业绩的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasMonthPerfUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 加入有达标业绩的会员
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasStandardMonthPerfUsers($userId, $periodNum) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER_POOL . $periodNum, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER . $periodNum, $userId);
-        }
-        unset($userId, $periodNum, $isset);
-    }
-
-    /**
-     * 获取有达标业绩的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasStandardMonthPerfUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-
-    /**
-     * 加入被报单的会员
-     * @param $userId
-     * @param $periodNum
-     * @param $saveData
-     */
-    public static function addHasBDUsers($userId, $periodNum, $saveData) {
-        // 先从已存在的会员池里面获取
-        $data = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_BD_USER_POOL . $periodNum, $userId);
-        if (!$data) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_BD_USER_POOL . $periodNum, $userId, Json::encode($saveData));
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_BD_USER . $periodNum, $userId);
-        }
-        unset($userId, $periodNum, $saveData, $isset);
-    }
-
-    /**
-     * 获取被报单的会员信息
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     */
-    public static function getBDUsersInfo($userId, $periodNum) {
-        $data = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_BD_USER_POOL . $periodNum, $userId);
-        if( !$data ) return [];
-
-        return Json::decode($data, true);
-    }
-
-    /**
-     * 获取被报单的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasBDUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_BD_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 加入有收入的会员
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasIncomeUsers($userId, $periodNum) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_INCOME_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_INCOME_USER_POOL . $periodNum, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_INCOME_USER . $periodNum, $userId);
-        }
-
-        unset($userId, $periodNum, $isset);
-    }
-
-    /**
-     * 获取有收入的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasIncomeUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_INCOME_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 加入有奖金的会员
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasBonusUsers($userId, $periodNum) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL . $periodNum, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_BONUS_USER . $periodNum, $userId);
-        }
-
-        unset($userId, $periodNum, $isset);
-    }
-
-    /**
-     * 获取有奖金的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasBonusUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_BONUS_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 加入荣衔奖的会员
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasYcBonusUsers($userId, $periodNum) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_YC_BONUS_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_YC_BONUS_USER_POOL . $periodNum, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_YC_BONUS_USER . $periodNum, $userId);
-        }
-
-        unset($userId, $periodNum, $isset);
-    }
-
-    /**
-     * 保存荣衔奖奖金
-     * @param $userId
-     * @param $periodNum
-     * @param $empBonus
-     * @param array $fromData
-     */
-    public static function saveYCBonusList($userId, $periodNum, $empBonus, $fromData=[]) {
-        $userYcBonusData = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_YC_BONUS_LIST_DATA . $periodNum, $userId);
-
-        if( $userYcBonusData ) {
-            $ycBonusData = Json::decode($userYcBonusData, true);
-            $ycBonusData['empBonus'] += $empBonus;
-//            $ycBonusData['fromData'][] = $fromData;
-        }else {
-            $ycBonusData = [
-                'empBonus' => $empBonus,
-//                'fromData' => [
-//                    $fromData
-//                ]
-            ];
-        }
-        unset($userYcBonusData);
-
-        Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_YC_BONUS_LIST_DATA . $periodNum, $userId, Json::encode($ycBonusData));
-        unset($ycBonusData, $userId, $periodNum, $empBonus, $fromData);
-    }
-
-    /**
-     * 返回荣衔奖信息
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     */
-    public static function getYCBonusList($userId, $periodNum) {
-        $userYcBonusData = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_YC_BONUS_LIST_DATA . $periodNum, $userId);
-
-        return $userYcBonusData ? Json::decode($userYcBonusData, true) : [];
-    }
-
-    /**
-     * 获取有荣衔奖的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasYcBonusUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_YC_BONUS_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 获取有服务奖的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasFwBonusUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-
-    /**
-     * 加入服务奖的会员
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasFwBonusUsers($userId, $periodNum) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL . $periodNum, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER . $periodNum, $userId);
-        }
-
-        unset($userId, $periodNum, $isset);
-    }
-
-    /**
-     * 获取有月奖的会员
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasMonthBonusUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-
-    /**
-     * 加入月奖的会员
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasMonthBonusUsers($userId, $periodNum) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER_POOL . $periodNum, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER . $periodNum, $userId);
-        }
-
-        unset($userId, $periodNum, $isset);
-    }
-
-    /**
-     * 保存荣衔奖奖金
-     * @param $userId
-     * @param $periodNum
-     * @param $fwBonus
-     * @param array $fromData
-     */
-    public static function saveFwBonusList($userId, $periodNum, $fwBonus, $fromData=[]) {
-        $userFwBonusData = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum, $userId);
-
-        if( $userFwBonusData ) {
-            $fwBonusData = Json::decode($userFwBonusData, true);
-            $fwBonusData['fwBonus'] += $fwBonus;
-//            $ycBonusData['fromData'][] = $fromData;
-        }else {
-            $fwBonusData = [
-                'fwBonus' => $fwBonus,
-//                'fromData' => [
-//                    $fromData
-//                ]
-            ];
-        }
-        unset($userFwBonusData);
-
-        Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum, $userId, Json::encode($fwBonusData));
-        unset($fwBonusData, $userId, $periodNum, $empBonus, $fromData);
-    }
-
-    /**
-     * 返回服务奖信息
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     */
-    public static function getFwBonusList($userId, $periodNum) {
-        $userYcBonusData = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum, $userId);
-
-        return $userYcBonusData ? Json::decode($userYcBonusData, true) : [];
-    }
-
-    /**
-     * 加入有复销业绩的会员列表
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasScoreUsers($userId, $periodNum) {
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_SCORE_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_SCORE_USER_POOL . $periodNum, $userId, 1);
-            $key = self::REDIS_KEY_PREFIX_HAS_SCORE_USER . $periodNum;
-            Yii::$app->redis->rpush($key, $userId);
-        }
-    }
-
-    /**
-     * 获取有复销业绩的会员列表
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasScoreUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_SCORE_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 加入有零售个人消费的会员列表
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasLSPCSUsers($userId, $periodNum) {
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_LS_PCS_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_LS_PCS_USER_POOL . $periodNum, $userId, 1);
-            $key = self::REDIS_KEY_PREFIX_HAS_LS_PCS_USER . $periodNum;
-            $value = $userId;
-            Yii::$app->redis->rpush($key, $value);
-        }
-    }
-
-    /**
-     * 加入有零售消费的会员列表
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasLSPCSUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_LS_PCS_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 有车房补贴比例的人
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasCFPercentUsers($userId, $periodNum) {
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER_POOL . $periodNum, $userId, 1);
-            $key = self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER . $periodNum;
-            $value = $userId;
-            Yii::$app->redis->rpush($key, $value);
-        }
-    }
-
-    /**
-     * 获取有车房补贴的人
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasCFPercentUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 有领袖分红的人
-     * @param $userId
-     * @param $periodNum
-     */
-    public static function addHasLXPercentUsers($userId, $periodNum) {
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER_POOL . $periodNum, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER_POOL . $periodNum, $userId, 1);
-            $key = self::REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER . $periodNum;
-            $value = $userId;
-            Yii::$app->redis->rpush($key, $value);
-        }
-    }
-
-    /**
-     * 获取有领袖分红的人
-     * @param $periodNum
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasLXPercentUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER . $periodNum, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 通过创建时间获取指定长度的用户列表
-     * @param $userId
-     * @param $limit
-     * @return array|\yii\db\ActiveRecord[]
-     */
-    public static function getUserListByCreatedAtFromDb($userId, $limit)
-    {
-        //查找这个人的CREATED_AT
-        $user = User::findUseDbCalc()->select('ID,CREATED_AT')->where('ID=:ID', ['ID'=>$userId])->asArray()->one();
-        if( !$user ) return [];
-
-        return User::findUseDbCalc()->select('ID,CREATED_AT')->where('ID<:ID AND CREATED_AT<=:CREATED_AT', [
-            'ID'=>$userId,
-            'CREATED_AT' => $user['CREATED_AT']
-        ])->orderBy('CREATED_AT DESC,ID DESC')->limit($limit)->asArray()->all();
-    }
-
-    /**
-     * 通过创建时间获取指定长度的用户列表
-     * @param $userId
-     * @param $limit
-     * @return array|\yii\db\ActiveRecord[]
-     */
-    public static function getAfterUserListByCreatedAtFromDb($userId, $limit)
-    {
-        $cacheKey = Cache::USER_CREATED_AT_LIST . $limit;
-        $value = Yii::$app->redis->hGet($cacheKey, $userId);
-        if( $value ) {
-            unset($cacheKey);
-            return json_decode($value, true);
-        }
-        unset($value);
-
-        $list = UserInfo::findUseDbCalc()->select('USER_ID')->where('USER_ID>:USER_ID', [
-            'USER_ID'=>$userId,
-        ])->orderBy('USER_ID ASC')->limit($limit)->asArray()->all();
-        if ( $limit == count($list) ) {
-            Yii::$app->redis->hSet($cacheKey, $userId, json_encode($list));
-        }
-
-        unset($cacheKey);
-        return $list;
-    }
-
-    /**
-     * 获取会员信息从缓存
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     * @throws \Exception
-     */
-    public static function getUserInfo($userId, $periodNum) {
-        $key = self::REDIS_KEY_PREFIX_USER_INFO . $periodNum;
-        $data = Yii::$app->redis->hget($key, $userId);
-        if (!$data) {
-            $userInfo = UserInfo::findUseDbCalc()->select('USER_ID,USER_NAME,ZC_AMOUNT,ZC_PV,CON_UID,REC_UID,CON_NUM,REC_NUM,NETWORK_DEEP,RELATION_DEEP,STORE_TYPE,UPDATED_AT,SYSTEM_ID')->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-            if( !$userInfo ) {
-                throw new \Exception('用户信息表数据不存在,userId:'.$userId);
-            }
-            // 在获取商城库的会员的级别信息和是否报单中心的会员
-            $userShopInfo = User::find()->select('REAL_NAME,LAST_DEC_LV,DEC_LV,EMP_LV,IS_DEC,DEC_ID,DEC_ROLE_ID,STATUS,PERIOD_AT,MOBILE,CREATED_AT,SUB_COM_ID,PROVINCE,CITY,COUNTY,DEC_PROVINCE,DEC_CITY,DEC_COUNTY,IS_DIRECT_SELLER,SUB_COM_LEADER')->where('ID=:ID', [':ID' => $userId])->asArray()->one();
-            if ( !$userShopInfo ) {
-                throw new \Exception('用户表数据不存在,userId:'.$userId);
-            }
-            $userInfo['REAL_NAME'] = $userShopInfo['REAL_NAME'];
-//            $userInfo['DEC_LV'] = $userShopInfo['DEC_LV'];
-            //先用last_dec_lv
-            $userInfo['DEC_LV'] = $userShopInfo['LAST_DEC_LV'];
-            $userInfo['EMP_LV'] = $userShopInfo['EMP_LV'];
-            $userInfo['IS_DEC'] = $userShopInfo['IS_DEC'];
-            $userInfo['DEC_ID'] = $userShopInfo['DEC_ID'];
-            $userInfo['DEC_ROLE_ID'] = $userShopInfo['DEC_ROLE_ID'];
-            $userInfo['DEC_PROVINCE'] = $userShopInfo['DEC_PROVINCE'];
-            $userInfo['DEC_CITY'] = $userShopInfo['DEC_CITY'];
-            $userInfo['DEC_COUNTY'] = $userShopInfo['DEC_COUNTY'];
-            $userInfo['STATUS'] = $userShopInfo['STATUS'];
-            $userInfo['PERIOD_NUM'] = $userShopInfo['PERIOD_AT'];
-            $userInfo['MOBILE'] = $userShopInfo['MOBILE'];
-            $userInfo['CREATED_AT'] = $userShopInfo['CREATED_AT'];
-            $userInfo['SUB_COM_ID'] = $userShopInfo['SUB_COM_ID'];
-            $userInfo['PROVINCE'] = $userShopInfo['PROVINCE'];
-            $userInfo['CITY'] = $userShopInfo['CITY'];
-            $userInfo['COUNTY'] = $userShopInfo['COUNTY'];
-            $userInfo['IS_DIRECT_SELLER'] = $userShopInfo['IS_DIRECT_SELLER'];
-            $userInfo['SUB_COM_LEADER'] = $userShopInfo['SUB_COM_LEADER'];
-            $userInfo['REC_USER_NAME'] = isset($userInfo['REC_UID']) && $userInfo['REC_UID'] ? Info::getUserNameByUserId($userInfo['REC_UID']) : '';
-            $userInfo['REC_REAL_NAME'] = isset($userInfo['REC_UID']) && $userInfo['REC_UID'] ? Info::getUserRealNameByUserId($userInfo['REC_UID']) : '';
-            $userInfo['CON_USER_NAME'] = isset($userInfo['CON_UID']) && $userInfo['CON_UID'] ? Info::getUserNameByUserId($userInfo['CON_UID']) : '';
-            $userInfo['CON_REAL_NAME'] = isset($userInfo['CON_UID']) && $userInfo['CON_UID'] ? Info::getUserRealNameByUserId($userInfo['CON_UID']) : '';
-//            $userInfo['REC_USER_NAME'] = '';
-//            $userInfo['REC_REAL_NAME'] = '';
-//            $userInfo['CON_USER_NAME'] = '';
-//            $userInfo['CON_REAL_NAME'] = '';
-//            $userInfo['LOCATION'] = 1;
-            unset($userShopInfo);
-//            if( isset($userInfo['CON_UID']) && $userInfo['CON_UID'] ) {
-//                if ($networkParent = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId])) {
-//                    $userInfo['LOCATION'] = $networkParent['RELATIVE_LOCATION'];
-//                }
-//            }
-
-            if (!$userInfo['DEC_LV']) {
-                $userInfo['DEC_LV'] = DeclarationLevel::getDefaultLevelId();
-            }
-            if (!$userInfo['EMP_LV']) {
-                $userInfo['EMP_LV'] = EmployLevel::getDefaultLevelId();
-            }
-            $data = Json::encode($userInfo);
-            Yii::$app->redis->hset($key, $userId, $data);
-            unset($userInfo, $key, $userId, $periodNum);
-        }
-        return $data ? Json::decode($data, true) : [];
-    }
-
-    public static function setUserInfo($userId, $periodNum, $userInfo) {
-        $key = self::REDIS_KEY_PREFIX_USER_INFO . $periodNum;
-        $data = Json::encode($userInfo);
-        Yii::$app->redis->hset($key, $userId, $data);
-        unset($userId, $key, $data, $userInfo, $periodNum);
-        return true;
-    }
-
-    /**
-     * 用户奖金信息
-     * @param $userId
-     * @param $periodNum
-     * @return array|mixed|null|\yii\db\ActiveRecord
-     */
-    public static function LastUserBonus($userId, $periodNum) {
-
-        $cacheKey = self::REDIS_KEY_PREFIX_USER_BONUS . $periodNum;
-        $field = $userId;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue, true);
-        } else {
-            $value = UserBonus::findUseDbCalc()->select('USER_ID,BONUS_TOTAL')->where('USER_ID=:USER_ID', [
-                'USER_ID'=>$userId
-            ])->asArray()->one();
-
-            \Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
-        }
-        return $value;
-    }
-
-    /**
-     * 用户奖金信息
-     * @param $userId
-     * @param $periodNum
-     * @param $yearMonth
-     * @return array|mixed|null|\yii\db\ActiveRecord
-     */
-    public static function lastPeriodMonthCalcBonus($userId, $periodNum, $yearMonth) {
-
-        $cacheKey = self::REDIS_KEY_PREFIX_PERIOD_MONTH_CALC_BONUS . $periodNum;
-        $field = $userId;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue, true);
-        } else {
-            $value = CalcBonus::findUseDbCalc()->select('SUM(ORI_BONUS_QY) AS ORI_BONUS_QY_SUM,SUM(ORI_BONUS_VIP) AS ORI_BONUS_VIP_SUM')->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [
-                'USER_ID'=>$userId,
-                'CALC_MONTH'=>$yearMonth
-            ])->asArray()->one();
-
-            \Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
-        }
-        return $value;
-    }
-
-
-    /**
-     * 本月往期的复消积分的数据
-     * @param $userId
-     * @param $periodNum
-     * @param $calcYearMonth
-     * @return array|mixed|null|\yii\db\ActiveRecord
-     * @throws \yii\db\Exception
-     */
-    public static function monthLastPeriodReconsumePoints($userId, $periodNum, $calcYearMonth) {
-        $cacheKey = self::REDIS_KEY_PREFIX_NOW_MONTH_LAST_PERIOD_RECONSUME_POINTS . $periodNum;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue, true);
-        } else {
-            $value = CalcBonus::findUseDbCalc()->select(["SUM(RECONSUME_POINTS) as RECONSUME_POINTS_SUM"])->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $userId, ':CALC_MONTH'=>$calcYearMonth])->asArray()->one();
-            \Yii::$app->redis->hset($cacheKey, $userId, Json::encode($value));
-        }
-        return $value;
-    }
-
-    /**
-     * 获取结算时这一期的报单中心级别的配置
-     * @param $periodNum
-     * @return array|\yii\db\ActiveRecord[]
-     */
-    public static function getDecRoleConfig($periodNum) {
-        $key = self::REDIS_KEY_PREFIX_DEC_ROLE_CONFIG . $periodNum;
-        Yii::$app->redis->del($key);
-        $data = Yii::$app->redis->get($key);
-        if (!$data) {
-            $data = DecRole::find()->where('1=1')->indexBy('ID')->asArray()->all();
-            $data = Json::encode($data);
-            Yii::$app->redis->set($key, $data);
-        }
-        return $data ? Json::decode($data) : [];
-    }
-
-    /**
-     * 上一期结余业绩
-     * @param $userId
-     * @param $periodNum
-     * @return array|mixed|\yii\db\ActiveRecord|null
-     * @throws \yii\db\Exception
-     */
-    public static function surplusPerf($userId, $periodNum) {
-//        $cacheKey = self::REDIS_KEY_PREFIX_SURPLUS_PERF . $periodNum;
-//        $field = $userId;
-//        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
-//        if ($cacheValue) {
-//            $value = Json::decode($cacheValue);
-//        } else {
-//            $value = UserPerf::getPeriodSurplusPerf($userId);
-//            \Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
-//        }
-//        return $value;
-        $userPerf = self::userPerf($userId, $periodNum);
-        return [
-            'SURPLUS_1L' => $userPerf['SURPLUS_1L'],
-            'SURPLUS_2L' => $userPerf['SURPLUS_2L'],
-            'SURPLUS_3L' => $userPerf['SURPLUS_3L'],
-            'SURPLUS_4L' => $userPerf['SURPLUS_4L'],
-            'SURPLUS_5L' => $userPerf['SURPLUS_5L'],
-            'SURPLUS_1L_ZC' => $userPerf['SURPLUS_1L_ZC'],
-            'SURPLUS_2L_ZC' => $userPerf['SURPLUS_2L_ZC'],
-            'SURPLUS_3L_ZC' => $userPerf['SURPLUS_3L_ZC'],
-            'SURPLUS_4L_ZC' => $userPerf['SURPLUS_4L_ZC'],
-            'SURPLUS_5L_ZC' => $userPerf['SURPLUS_5L_ZC'],
-            'SURPLUS_1L_FX' => $userPerf['SURPLUS_1L_FX'],
-            'SURPLUS_2L_FX' => $userPerf['SURPLUS_2L_FX'],
-            'SURPLUS_3L_FX' => $userPerf['SURPLUS_3L_FX'],
-            'SURPLUS_4L_FX' => $userPerf['SURPLUS_4L_FX'],
-            'SURPLUS_5L_FX' => $userPerf['SURPLUS_5L_FX'],
-            'VIP_SURPLUS_1L_ZC' => $userPerf['VIP_SURPLUS_1L_ZC'],
-            'VIP_SURPLUS_2L_ZC' => $userPerf['VIP_SURPLUS_2L_ZC'],
-            'VIP_SURPLUS_3L_ZC' => $userPerf['VIP_SURPLUS_3L_ZC'],
-            'VIP_SURPLUS_4L_ZC' => $userPerf['VIP_SURPLUS_4L_ZC'],
-            'VIP_SURPLUS_5L_ZC' => $userPerf['VIP_SURPLUS_5L_ZC'],
-            'SURPLUS_LS' => 0,
-        ];
-    }
-
-    /**
-     * 获取repairSurplusPerf
-     * @param $userId
-     * @return int[]|mixed|null
-     */
-    public static function getRepairSurplusPerf($userId) {
-        $cacheKey = self::REDIS_KEY_PREFIX_REPAIR_SURPLUS_PERF;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue);
-        }else {
-            $value = [
-                'SURPLUS_1L' => 0,
-                'SURPLUS_2L' => 0,
-                'SURPLUS_3L' => 0,
-                'SURPLUS_4L' => 0,
-                'SURPLUS_5L' => 0,
-            ];
-        }
-
-        return $value;
-    }
-
-    /**
-     * 累加repairSurplusPerf
-     * @param $userId
-     * @param $surplusPerf
-     * @return int[]|mixed|null
-     */
-    public static function setRepairSurplusPerf($userId, $surplusPerf) {
-        $surplusPerfList = self::getRepairSurplusPerf($userId);
-        foreach ($surplusPerfList as $key => $perf) {
-            $thisPerf = $surplusPerf[$key] ?? 0;
-            $surplusPerfList[$key] = $perf + $thisPerf;
-
-            unset($key, $perf, $thisPerf);
-        }
-
-        $cacheKey = self::REDIS_KEY_PREFIX_REPAIR_SURPLUS_PERF;
-        \Yii::$app->redis->hset($cacheKey, $userId, Json::encode($surplusPerfList));
-        self::addHasRepairPerfUsers($userId);
-
-        unset($userId, $cacheKey, $surplusPerf);
-
-        return $surplusPerfList;
-    }
-
-    /**
-     * 加入有往期结余业绩的会员
-     * @param $userId
-     */
-    public static function addHasRepairPerfUsers($userId) {
-        // 先从已存在的会员池里面获取
-        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER_POOL, $userId);
-        if (!$isset) {
-            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER_POOL, $userId, 1);
-            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER, $userId);
-        }
-        unset($userId, $isset);
-    }
-
-    /**
-     * 获取有往期结余业绩的会员
-     * @param int $offset
-     * @param int $limit
-     * @return mixed
-     */
-    public static function getHasRepairPerfUsers($offset = 0, $limit = self::LIMIT) {
-        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 修正业绩缓存清空
-     */
-    public static function clearRepairAllCache() {
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_REPAIR_SURPLUS_PERF);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER);
-        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER_POOL);
-    }
-
-    /**
-     * 上一期结余业绩
-     * @param $userId
-     * @param $periodNum
-     * @return array|mixed|\yii\db\ActiveRecord|null
-     * @throws \yii\db\Exception
-     */
-    public static function userPerf($userId, $periodNum) {
-        $cacheKey = self::REDIS_KEY_PREFIX_USER_PERF . $periodNum;
-        $field = $userId;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue);
-        } else {
-            $value = UserPerf::getOneUserPerf($userId);
-            \Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
-        }
-        return $value;
-    }
-
-    /**
-     * 当前期数的的业绩
-     * @param $userId
-     * @param $periodNum
-     * @param null $perf
-     * @return array|mixed
-     */
-    public static function nowPeriodPerf($userId, $periodNum, $perf = null) {
-        $cacheKey = self::REDIS_KEY_PREFIX_NOW_PERIOD_PERF . $periodNum;
-        $field = $userId;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue);
-        } else {
-            $value = [
-                'FX_AMOUNT_CASH' => 0,
-                'PV_PCS' => 0,
-                'PV_PSS' => 0,//本期的团队业绩
-                'PV_PCS_ZC' => 0,//注册
-                'PV_PCS_YH' => 0,
-                'PV_PCS_ZG' => 0,//增购
-                'PV_PCS_LS' => 0,
-                'PV_PCS_FX' => 0,
-                'PV_PCS_FX_CASH' => 0,//现金复消
-                'PV_PCS_FX_POINT' => 0,//积分复消
-                'PV_1L' => 0,
-                'PV_1L_TOUCH' => 0,
-                'PV_1L_ZC' => 0,
-                'PV_1L_YH' => 0,
-                'PV_1L_ZG' => 0,
-                'PV_1L_LS' => 0,
-                'PV_1L_FX' => 0,
-                'PV_2L' => 0,
-                'PV_2L_TOUCH' => 0,
-                'PV_2L_ZC' => 0,
-                'PV_2L_YH' => 0,
-                'PV_2L_ZG' => 0,
-                'PV_2L_LS' => 0,
-                'PV_2L_FX' => 0,
-                'PV_3L' => 0,
-                'PV_3L_TOUCH' => 0,
-                'PV_3L_ZC' => 0,
-                'PV_3L_YH' => 0,
-                'PV_3L_ZG' => 0,
-                'PV_3L_LS' => 0,
-                'PV_3L_FX' => 0,
-                'PV_4L' => 0,
-                'PV_4L_TOUCH' => 0,
-                'PV_4L_ZC' => 0,
-                'PV_4L_YH' => 0,
-                'PV_4L_ZG' => 0,
-                'PV_4L_LS' => 0,
-                'PV_4L_FX' => 0,
-                'PV_5L' => 0,
-                'PV_5L_TOUCH' => 0,
-                'PV_5L_ZC' => 0,
-                'PV_5L_YH' => 0,
-                'PV_5L_ZG' => 0,
-                'PV_5L_LS' => 0,
-                'PV_5L_FX' => 0,
-                'PV_LS_TOUCH' => 0,
-                'SURPLUS_1L' => 0,
-                'SURPLUS_2L' => 0,
-                'SURPLUS_3L' => 0,
-                'SURPLUS_4L' => 0,
-                'SURPLUS_5L' => 0,
-                'SURPLUS_1L_ZC' => 0,
-                'SURPLUS_2L_ZC' => 0,
-                'SURPLUS_3L_ZC' => 0,
-                'SURPLUS_4L_ZC' => 0,
-                'SURPLUS_5L_ZC' => 0,
-                'SURPLUS_1L_FX' => 0,
-                'SURPLUS_2L_FX' => 0,
-                'SURPLUS_3L_FX' => 0,
-                'SURPLUS_4L_FX' => 0,
-                'SURPLUS_5L_FX' => 0,
-                'SURPLUS_LS' => 0,
-            ];
-        }
-        if ($perf !== null) {
-            foreach ($perf as $key => $pv) {
-                if (strpos($key, 'SURPLUS') !== false) {
-                    $value[$key] = $pv;
-                } else {
-                    $value[$key] = $pv + $value[$key];
-                }
-            }
-            Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
-        }
-        return $value;
-    }
-
-    /**
-     * 上个月的业绩
-     * @param $userId
-     * @param $periodNum
-     * @return array|mixed|null|\yii\db\ActiveRecord
-     */
-    public static function lastMonthPerf($userId, $periodNum) {
-        $period = Period::instance();
-        $last = $period->getLastMonth($periodNum);
-        $lastYearMonth = $last['yearMonth'];
-        $cacheKey = self::REDIS_KEY_PREFIX_LAST_MONTH_PERF . $periodNum;
-        $field = $userId;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue);
-        } else {
-            $value = PerfMonth::getMonthPerf($lastYearMonth, $userId);
-            \Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
-        }
-        return $value;
-    }
-
-    /**
-     * 当前月的业绩
-     * @param $userId
-     * @param $periodNum
-     * @param $perf
-     * @return array|mixed
-     */
-    public static function nowMonthPerf($userId, $periodNum, $perf = null) {
-        $cacheKey = self::REDIS_KEY_PREFIX_NOW_MONTH_PERF . $periodNum;
-        $field = $userId;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue);
-        } else {
-            $baseInfo = self::getUserInfo($userId, $periodNum);
-            $value = [
-                'USER_ID' => $userId,
-                'FX_AMOUNT_CASH' => 0,
-                'PV_PCS' => 0,
-                'PV_PCS_FX' => 0,
-                'PV_PSS' => 0,
-                'PV_1L' => 0,
-                'PV_2L' => 0,
-                'PV_3L' => 0,
-                'PV_4L' => 0,
-                'PV_5L' => 0,
-                'VIP_PV_1L_ZC' => 0,
-                'VIP_PV_2L_ZC' => 0,
-                'VIP_PV_3L_ZC' => 0,
-                'VIP_PV_4L_ZC' => 0,
-                'VIP_PV_5L_ZC' => 0,
-                'PV_1L_TOTAL' => 0,
-                'PV_2L_TOTAL' => 0,
-                'PV_3L_TOTAL' => 0,
-                'PV_4L_TOTAL' => 0,
-                'PV_5L_TOTAL' => 0,
-                'PV_PSS_TOTAL' => 0,
-                'DEC_LEVEL' => $baseInfo['DEC_LV'],
-                'EMP_LEVEL' => EmployLevel::getDefaultLevelId(),
-                'CF_PERCENT' => 0,
-                'LX_PERCENT' => 0,
-                'FX_STATUS' => PerfMonth::NEXT_MONTH_FX_FALSE,
-            ];
-        }
-        if ($perf !== null) {
-            foreach ($perf as $key => $item) {
-                $value[$key] = $item;
-            }
-        }
-        Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
-        return $value;
-    }
-
-    /**
-     * 当前期数的的业绩
-     * @param $userId
-     * @param $periodNum
-     * @param null $perf
-     * @return array|mixed
-     */
-    public static function nowStandardMonthPerf($userId, $periodNum, $perf = null) {
-        $cacheKey = self::REDIS_KEY_PREFIX_NOW_STANDARD_MONTH_PERF . $periodNum;
-        $field = $userId;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue);
-        } else {
-            $value = [
-                'AMOUNT_PCS' => 0,
-                'AMOUNT_PSS' => 0
-            ];
-        }
-        if ($perf !== null) {
-            foreach ($perf as $key => $pv) {
-                $value[$key] = $pv + $value[$key];
-            }
-            Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
-        }
-        return $value;
-    }
-
-    /**
-     * 当前月的积分
-     * @param $userId
-     * @param $periodNum
-     * @param $perf
-     * @return array|mixed
-     */
-    public static function nowMonthScore($userId, $periodNum, $perf = null) {
-        $cacheKey = self::REDIS_KEY_PREFIX_NOW_MONTH_SCORE . $periodNum;
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue);
-        } else {
-            $value = [
-                'USER_ID' => $userId,
-                'BASE_SCORE' => 0,
-                'LEVEL_SCORE' => 0,
-                'UPGRADE_SCORE' => 0,
-//                'TOTAL_SCORE' => 0,
-            ];
-        }
-        unset($cacheValue);
-        if ($perf !== null) {
-            foreach ($perf as $key => $item) {
-                $value[$key] = $item;
-//                $value['TOTAL_SCORE'] += $item;
-                unset($key, $item);
-            }
-            Yii::$app->redis->hset($cacheKey, $userId, Json::encode($value));
-        }
-
-        unset($userId, $periodNum, $perf, $cacheKey);
-        return $value;
-    }
-
-    /**
-     * 获取直推的所有子会员
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     */
-    public static function getChildrenOneDeepFromRedis($userId, $periodNum){
-        $key = self::REDIS_KEY_PREFIX_USER_INFO_CHILD_ONE_DEEP . $periodNum;
-        $data = Yii::$app->redis->hget($key, $userId);
-        if(!$data){
-            $list = UserInfo::findUseDbCalc()->select('USER_ID')->where('REC_UID=:REC_UID', [
-                'REC_UID' => $userId
-            ])->asArray()->all();
-            $data = Json::encode($list);
-            unset($list);
-            Yii::$app->redis->hset($key, $userId, $data);
-        }
-        unset($key, $userId, $periodNum);
-        return $data ? Json::decode($data, true) : [];
-    }
-
-    /**
-     * 每个区有多少个什么级别的数量
-     * @param $userId
-     * @param $periodNum
-     * @param null $levelNumArr
-     * @return array|mixed
-     */
-    public static function hasEmpLevelNum($userId,  $periodNum, $levelNumArr = null) {
-        $key = self::REDIS_KEY_PREFIX_EMP_NUM_PERF . $periodNum;
-        $field = $userId;
-        $cacheValue = Yii::$app->redis->hget($key, $field);
-
-        if ($cacheValue) {
-            $value = Json::decode($cacheValue);
-        } else {
-            $allEmpLevel = EmployLevel::getFromCache();
-            $value = [];
-            $relationList = self::getChildrenOneDeepFromRedis($userId, $periodNum);
-            foreach ($relationList as $relationData) {
-                foreach ($allEmpLevel as $level) {
-                    // 从月度业绩表中找到所有下级的各个部门的数量
-                    $value[$relationData['USER_ID']][$level['ID']] = 0;
-                }
-            }
-        }
-        if ($levelNumArr != null) {
-            foreach ($levelNumArr as $departUserId => $item) {
-                foreach ($item as $levelID => $num) {
-                    if( isset($value[$departUserId][$levelID]) ) {
-                        $value[$departUserId][$levelID] += $num;
-                    }else {
-                        $value[$departUserId][$levelID] = $num;
-                    }
-                }
-            }
-        }
-        Yii::$app->redis->hset($key, $field, Json::encode($value));
-
-        if ($levelNumArr == null) return $value;
-    }
-
-    /**
-     * 会员是否本月注册
-     * @param $userId
-     * @param $periodNum
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public static function isMonthJoinFromRedis($userId, $periodNum) {
-        $period = Period::instance();
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        $userInfo = self::getUserInfo($userId, $periodNum);
-        $addYearMonth = $period->getYearMonth($userInfo['PERIOD_NUM']);
-        //当月注册
-        if ($addYearMonth == $calcYearMonth) return true;
-        //上月注册
-        $calcLastYearMonth = $period->getLastMonth($periodNum);
-        if ($addYearMonth == $calcLastYearMonth['yearMonth']) return true;
-        // 未来注册
-        if ($addYearMonth > $calcYearMonth) return true;
-        return false;
-    }
-
-    /**
-     * 荣衔奖最大比例
-     * @param $userId
-     * @param $periodNum
-     * @param int $percent
-     * @return float|int
-     */
-    public static function ycMaxBonusPercent($userId, $periodNum, $percent=0) {
-        $cacheKey = self::REDIS_KEY_PREFIX_YC_BONUS . $periodNum;
-        $value = Yii::$app->redis->hget($cacheKey, $userId);
-        $maxPercent = floatval($value)>0 ? floatval($value) : 0;
-        if ( $percent > 0 && $percent > $maxPercent ) {
-            $maxPercent = $percent;
-            unset($periodNum, $percent);
-            Yii::$app->redis->hset($cacheKey, $userId, $maxPercent);
-
-            return $maxPercent;
-        }
-
-        unset($userId, $periodNum, $oriBonus, $cacheKey, $value);
-        return $maxPercent;
-    }
-
-    /**
-     * 服务奖最大比例
-     * @param $userId
-     * @param $periodNum
-     * @param int $percent
-     * @return float|int
-     */
-    public static function fwMaxBonusPercent($userId, $periodNum, $percent=0) {
-        $cacheKey = self::REDIS_KEY_PREFIX_FW_BONUS . $periodNum;
-        $value = Yii::$app->redis->hget($cacheKey, $userId);
-        $maxPercent = floatval($value)>0 ? floatval($value) : 0;
-        if ( $percent > 0 && $percent > $maxPercent ) {
-            $maxPercent = $percent;
-            unset($periodNum, $percent);
-            Yii::$app->redis->hset($cacheKey, $userId, $maxPercent);
-
-            return $maxPercent;
-        }
-
-        unset($userId, $periodNum, $oriBonus, $cacheKey, $value);
-        return $maxPercent;
-    }
-
-    /**
-     * 奖金缓存
-     * @param $userId
-     * @param $periodNum
-     * @param string $bonusType
-     * @param float $oriBonus
-     * @param array $deductData
-     * @return array|mixed
-     */
-    public static function bonus($userId, $periodNum, $bonusType = null, $oriBonus = 0.00, $deductData=[], $fromMeans='') {
-        $cacheKey = self::REDIS_KEY_PREFIX_BONUS . $periodNum;
-        $value = [
-            'BONUS_BD' => 0,
-            'BONUS_TG' => 0,
-            'BONUS_XF' => 0,
-            'BONUS_YJ' => 0,
-            'BONUS_GX' => 0,
-            'BONUS_GL' => 0,
-            'BONUS_QY' => 0,
-            'BONUS_YC' => 0,
-            'BONUS_VIP' => 0,
-            'BONUS_YC_EXTRA' => 0,
-            'ORI_BONUS_BD' => 0,
-            'ORI_BONUS_TG' => 0,
-            'ORI_BONUS_XF' => 0,
-            'ORI_BONUS_YJ' => 0,
-            'ORI_BONUS_YJ_BD' => 0,
-            'ORI_BONUS_YJ_FX' => 0,
-            'ORI_BONUS_GX' => 0,
-            'ORI_BONUS_GL' => 0,
-            'ORI_BONUS_GL_BD' => 0,
-            'ORI_BONUS_GL_FX' => 0,
-            'ORI_BONUS_QY' => 0,
-            'ORI_BONUS_QY_BD' => 0,
-            'ORI_BONUS_QY_FX' => 0,
-            'ORI_BONUS_YC' => 0,
-            'ORI_BONUS_VIP' => 0,
-            'ORI_BONUS_YC_EXTRA' => 0,
-//            'INCOME_TG_TOTAL' => 0,
-//            'INCOME_YJ_TOTAL' => 0,
-//            'INCOME_QY_TOTAL' => 0,
-            'INCOME_TOTAL' => 0,
-            'BONUS_TOTAL' => 0,
-            'RECONSUME_POINTS' => 0,
-            'MANAGE_TAX' => 0,
-
-            //没有用到的
-            'BONUS_FX' => 0,
-            'BONUS_LS' => 0,
-            'BONUS_CF' => 0,
-            'BONUS_LX' => 0,
-            'BONUS_HB' => 0,
-            'BONUS_BT' => 0,
-            'BONUS_BT_PROD' => 0,
-            'BONUS_BT_TOOL' => 0,
-            'DEDUCT_ZR' => 0,
-            'BONUS_FL' => 0,
-        ];
-        // 从 redis 中获取当前的结果
-        $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
-        if ($cacheValue) {
-            $cacheValue = Json::decode($cacheValue);
-            $value = $cacheValue;
-        }
-        unset($cacheValue);
-        if ($oriBonus > 0) {
-            $oriBonusType = sprintf('ORI_%s', $bonusType);
-            $value[$oriBonusType] += $oriBonus;
-            if( $fromMeans !== '' ) {
-                $oriBonusMeansType = sprintf('ORI_%s_%s', $bonusType, $fromMeans);
-                $value[$oriBonusMeansType] += $oriBonus;
-            }
-
-            if( !in_array($bonusType, self::NOT_SEND_BONUS_LIST) ) {
-                if( $deductData ) {
-                    $value[$bonusType] += $deductData['surplus'];
-                    $value['RECONSUME_POINTS'] += $deductData['reConsumePoints'];
-                    $value['MANAGE_TAX'] += $deductData['manageTax'];
-                }else {
-                    $value[$bonusType] += $oriBonus;
-                }
-                $value['BONUS_TOTAL'] += $oriBonus;
-            }
-
-            if( in_array($bonusType, self::INCOME_BONUS_LIST) ) {
-                self::addHasIncomeUsers($userId, $periodNum);
-//                if( !in_array($bonusType, self::NOT_SEND_BONUS_LIST) ) {
-//                    $value['INCOME_TOTAL'] += $oriBonus;
-//                }
-            }
-
-            Yii::$app->redis->hset($cacheKey, $userId, Json::encode($value));
-            unset($oriBonusType);
-            self::addHasBonusUsers($userId, $periodNum);
-        }
-        unset($userId, $periodNum, $bonusType, $oriBonus, $deductData, $cacheKey);
-        return $value;
-    }
-
-    public static function standardBonus($userId, $periodNum, $bonus=0.00) {
-        $cacheKey = self::REDIS_KEY_PREFIX_STANDARD_BONUS . $periodNum;
-
-        $value = 0.00;
-        if( $bonus > 0 ) {
-            Yii::$app->redis->hset($cacheKey, $userId, $bonus);
-            $value = $bonus;
-            //加入有奖金的会员中
-            self::addHasBonusUsers($userId, $periodNum);
-        }else {
-            $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
-            if ($cacheValue) {
-                $value = $cacheValue;
-            }
-            unset($cacheValue);
-        }
-
-        unset($cacheKey, $userId, $periodNum, $bonus);
-        return $value;
-    }
-
-    /**
-     * 设置车房总系数
-     * @param $periodNum
-     * @param $value
-     */
-    public static function setCFTotalPercent($periodNum, $value) {
-        Yii::$app->redis->set(self::REDIS_KEY_PREFIX_CF_TOTAL_PERCENT . $periodNum, $value);
-    }
-
-    /**
-     * 获得车房总系数
-     * @param $periodNum
-     * @return mixed
-     */
-    public static function getCFTotalPercent($periodNum) {
-        return Yii::$app->redis->get(self::REDIS_KEY_PREFIX_CF_TOTAL_PERCENT . $periodNum);
-    }
-
-    /**
-     * 设置领袖总系数
-     * @param $periodNum
-     * @param $value
-     */
-    public static function setLXTotalPercent($periodNum, $value) {
-        Yii::$app->redis->set(self::REDIS_KEY_PREFIX_LX_TOTAL_PERCENT . $periodNum, $value);
-    }
-
-    /**
-     * 获得领袖总系数
-     * @param $periodNum
-     * @return mixed
-     */
-    public static function getLXTotalPercent($periodNum) {
-        return Yii::$app->redis->get(self::REDIS_KEY_PREFIX_LX_TOTAL_PERCENT . $periodNum);
-    }
-
-
-    /**
-     * 添加上2代共享奖关系
-     * @param $bonusUserId
-     * @param $fromUserId
-     * @param $periodNum
-     * @param $validDeep
-     * @return  boolean
-     */
-    public static function addShareBonusOneRelation($bonusUserId, $fromUserId, $periodNum, $validDeep) {
-        if ($validDeep == 1) {
-            $cacheKey = self::REDIS_KEY_PREFIX_GX_BONUS_DEEP_ONE_LIST_DATA . $periodNum;
-        }else {
-            $cacheKey = self::REDIS_KEY_PREFIX_GX_BONUS_DEEP_TWO_LIST_DATA . $periodNum;
-        }
-        $fromUserDataJson = Yii::$app->redis->hget($cacheKey, $fromUserId);
-
-        $fromUserData = [];
-        if( $fromUserDataJson ) {
-            $fromUserData = Json::decode($fromUserDataJson, true);
-        }
-        unset($fromUserDataJson);
-
-        $fromUserData[] = $bonusUserId;
-
-        Yii::$app->redis->hset($cacheKey, $fromUserId, Json::encode($fromUserData));
-
-        unset($fromUserData, $bonusUserId, $fromUserId, $periodNum);
-
-        return true;
-    }
-
-    /**
-     * 获取上2代共享奖关系
-     * @param $fromUserId
-     * @param $periodNum
-     * @param $validDeep
-     * @return array
-     */
-    public static function getShareBonusOneRelation($fromUserId, $periodNum, $validDeep) {
-        if ($validDeep == 1) {
-            $cacheKey = self::REDIS_KEY_PREFIX_GX_BONUS_DEEP_ONE_LIST_DATA . $periodNum;
-        }else {
-            $cacheKey = self::REDIS_KEY_PREFIX_GX_BONUS_DEEP_TWO_LIST_DATA . $periodNum;
-        }
-        $fromUserDataJson = Yii::$app->redis->hget($cacheKey, $fromUserId);
-
-        $bonusUserData = [];
-        if( $fromUserDataJson ) {
-            $bonusUserData = Json::decode($fromUserDataJson, true);
-        }
-        unset($fromUserDataJson);
-
-        return $bonusUserData;
-    }
-}

+ 0 - 1460
common/helpers/bonus/PerfCalc.php

@@ -1,1460 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: liyunlong
- * Date: 2019-01-11
- * Time: 15:27
- */
-
-namespace common\helpers\bonus;
-
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\helpers\Form;
-use common\helpers\snowflake\SnowFake;
-use common\helpers\Tool;
-use common\helpers\user\Info;
-use common\helpers\user\Reconsume;
-use common\models\CalcBonus;
-use common\models\DeclarationLevel;
-use common\models\forms\DeclarationForm;
-use common\models\Order;
-use common\models\OrderDec;
-use common\models\OrderShop;
-use common\models\OrderStandard;
-use common\models\PerfCompany;
-use common\models\PerfMonth;
-use common\models\PerfOrder;
-use common\models\PerfPeriod;
-use common\models\PerfStandard;
-use common\models\Period;
-use common\models\DecOrder;
-use common\models\EmployLevel;
-use common\models\UserRelation;
-use yii\base\Exception;
-use yii\base\StaticInstanceTrait;
-
-class PerfCalc {
-    use StaticInstanceTrait;
-
-    private $_limit = 1000;
-    private $_handleUserId;
-    private $_companyMonthPerf = 0;
-    private $_cfTotalPercent = 0;
-    private $_lxTotalPercent = 0;
-    private $_sysConfig = [];
-    private $_decLevelConfig = [];
-    private $_empLevelConfig = [];
-    private $_decRoleConfig = [];
-    private $_errors = [];
-    private $_periodNum = 0;
-    private $_periodId;
-    private $_isCalcMonth = 0;
-    private $_calcYear;
-    private $_calcMonth;
-    private $_calcYearMonth;
-    private $_lastCalcYear;
-    private $_lastCalcMonth;
-    private $_lastCalcYearMonth;
-    private $_lastPeriodNum;
-    private $_lastPeriodYear;
-    private $_lastPeriodMonth;
-    private $_lastPeriodYearMonth;
-    //pv
-    private $_pvRatio;
-
-    const LOOP_FINISH = 1;
-    const LOOP_CONTINUE = 2;
-
-    const ORDER_PAY_TYPE_CASH = 'cash';
-//    const ORDER_PAY_TYPE_POINT = 'point';
-
-    /**
-     * 设置期数
-     * @param int $periodNum
-     * @return int
-     */
-    public function setPeriodNum(int $periodNum) {
-        return $this->_periodNum = $periodNum;
-    }
-
-    /**
-     * 获取期数
-     * @return int
-     */
-    public function getPeriodNum() {
-        return $this->_periodNum;
-    }
-
-    /**
-     * 加入错误错误
-     * @param string $attr
-     * @param string $error
-     */
-    public function addError(string $attr, string $error) {
-        $this->_errors[$attr][] = $error;
-    }
-
-    /**
-     * 获取错误信息
-     * @return array
-     */
-    public function getErrors() {
-        return $this->_errors;
-    }
-
-    /**
-     * 计算步骤
-     * @param $periodNum
-     * @param null $handleUserId
-     * @return bool
-     */
-    public function calcStep($periodNum, $handleUserId = null) {
-        try {
-            $this->_errors = [];
-            $this->setPeriodNum($periodNum);
-            $this->_handleUserId = $handleUserId;
-            $t1 = microtime(true);
-            // 初始化结算任务
-            $this->initCalcTask();
-            // 设置结算状态
-            $this->setCalcStatus('start');
-            // 清空所有本期结算用到的缓存
-            CalcCache::clearAll($this->_periodNum);
-            // 清空会员推荐和接点关系缓存
-            CalcCache::clearNetCache();
-            // 清空相关表数据
-            $this->clearTableData();
-            $t2 = microtime(true);
-            echo('初始化、清空缓存及相关数据表完成,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(10);
-            // 计算月奖,才需要向缓存中加入按推荐深度的所有用户
-            //修改每一期都缓存所有用户
-            CalcCache::addUsers($this->_periodNum);
-            $t3 = microtime(true);
-            echo('向缓存中加入用户完成,耗时:' . round($t3 - $t2, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(20);
-            // 周结,循环向上级计入业绩并加入业绩单
-            $this->loopCalcPeriodPerfByDecOrder();
-            $this->loopCalcPeriodPerfByOrderDec();
-            $t4 = microtime(true);
-            echo('计算周业绩表中的数据完成,耗时:' . round($t4 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(40);
-            // 从会员的复销订单会员计算复销业绩并加入业绩单
-            $this->loopCalcPerfByFXOrder();
-            $this->loopCalcPerfByShopFXOrder();
-            $t5 = microtime(true);
-            echo('计算复销业绩并写入业绩单完成,耗时:' . round($t5 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(60);
-            //本期业绩入库
-            $this->loopWriteNowPerf();
-            $t6 = microtime(true);
-            echo('本期业绩入库完成,耗时:' . round($t6 - $t5, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(70);
-
-            //计算月业绩表中的数据
-            $this->loopCalcMonthPerfTableData();
-            $t7 = microtime(true);
-            echo('计算月业绩表中的数据完成,耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(80);
-
-            //每月计算聘级
-            $this->loopCalcEmpLevel();
-            $t8 = microtime(true);
-            echo('计算聘级完成,耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(90);
-
-            //本月业绩入库
-            $this->loopWriteMonthPerf();
-            $t7 = microtime(true);
-            echo('本月业绩入库完成,耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(95);
-
-            //达标业绩
-            $this->loopCalcPerfByStandardFXOrder();
-            //达标业绩入库
-            $this->loopWriteStandardPerf();
-            $t8 = microtime(true);
-            echo('本月业绩入库完成,耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-            $this->_updatePercent(100);
-
-
-            echo('结算全部完成,共耗时:' . round($t8 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
-        } catch (\Exception $e) {
-            $this->errorCalcTask();
-            $this->addError('calc', $e->getMessage());
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * 结算完成
-     * @return bool
-     */
-    public function endCalcTask() {
-        // 更新结算状态
-        $this->setCalcStatus('end');
-        //如果自动结算
-        if(boolval($this->_sysConfig['autoCalcPeriod']['VALUE'])){
-            $period = Period::instance();
-            if($period->isLastSent($this->_periodNum)) {
-                $bonusCalc = BonusCalc::instance();
-                $asyncResult = $bonusCalc->calcStep($this->_periodNum);
-                if ($asyncResult) {
-                    $bonusCalc->endCalcTask();
-                } else {
-                    $bonusCalc->errorCalcTask();
-                }
-                return $asyncResult;
-            }
-        }
-    }
-
-    /**
-     * 结算错误
-     */
-    public function errorCalcTask() {
-        // 清空所有本期结算用到的缓存
-        CalcCache::clearAll($this->_periodNum);
-        // 更新结算状态
-        $this->setCalcStatus('fail');
-    }
-
-    /**
-     * 设置生成业绩单状态
-     * @param $type
-     * start|end|fail
-     */
-    public function setCalcStatus($type) {
-        if ($type == 'start') {
-            Period::updateAll(['IS_PERFING' => 1, 'IS_PERFED' => Period::PERF_NONE, 'PERF_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
-        } elseif ($type == 'end') {
-            Period::updateAll(['IS_PERFING' => 0, 'IS_PERFED' => Period::PERF_FINISH, 'PERFED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
-        } elseif ($type == 'fail') {
-            Period::updateAll(['IS_PERFING' => 0, 'IS_PERFED' => Period::PERF_FAIL, 'PERFED_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
-        }
-    }
-
-    /**
-     * 初始化结算任务
-     * @throws \yii\db\Exception
-     */
-    public function initCalcTask() {
-        $this->_sysConfig = Cache::getSystemConfig();
-        $this->_decLevelConfig = Cache::getDecLevelConfig();
-        $this->_empLevelConfig = Cache::getEmpLevelConfig();
-        $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
-        $periodNum = $this->_periodNum;
-        // 获取本年月和上年月
-        $periodObj = Period::instance();
-        $periodDataArr = $periodObj->setPeriodNum($periodNum);
-        $this->_periodId = $periodDataArr['ID'];
-        $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
-        $this->_calcYear = $periodObj->getYear($periodNum);
-        $this->_calcMonth = $periodObj->getMonth($periodNum);
-        $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
-        $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
-        $this->_lastCalcYear = $lastYearMonthArr['year'];
-        $this->_lastCalcMonth = $lastYearMonthArr['month'];
-        $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
-        $this->_lastPeriodNum = $periodNum - 1;
-        if (Period::isExistsPeriodNum($this->_lastPeriodNum)) {
-            $this->_lastPeriodYear = $periodObj->getYear($this->_lastPeriodNum);
-            $this->_lastPeriodMonth = $periodObj->getMonth($this->_lastPeriodNum);
-            $this->_lastPeriodYearMonth = $periodObj->getYearMonth($this->_lastPeriodNum);
-        } else {
-            $this->_lastPeriodYear = 0;
-            $this->_lastPeriodMonth = 0;
-            $this->_lastPeriodYearMonth = 0;
-        }
-        $this->_pvRatio = $this->_sysConfig['pvRatio']['VALUE'];
-    }
-
-    /**
-     * 清空相关表数据
-     */
-    public function clearTableData() {
-        // 周业绩
-        PerfPeriod::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
-        // 业绩单
-        PerfOrder::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
-        // 月结时要清空的数据
-        if ($this->_isCalcMonth) {
-            // 月业绩表
-            PerfMonth::pageDeleteAll("CALC_MONTH='{$this->_calcYearMonth}'");
-            //达标业绩表
-            PerfStandard::pageDeleteAll("CALC_MONTH='{$this->_calcYearMonth}'");
-        }
-    }
-
-    /**
-     * 周结,向上级算业绩,并计入业绩单
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function loopCalcPeriodPerfByDecOrder($offset = 0) {
-        // 循环获取全部报单
-        $allData = DecOrder::findUseDbCalc()->select('ID,DEC_SN,ORDER_SN,USER_ID,TYPE,TO_USER_ID,IS_ADMIN,DEC_AMOUNT,DEC_PV,PERIOD_NUM,CALC_MONTH,IS_DEL,P_CALC_MONTH,CREATED_AT,DEC_ID')->where("PERIOD_NUM=:PERIOD_NUM AND IS_DEL=0 AND TYPE='ZC'", [':PERIOD_NUM' => $this->_periodNum])->orderBy('CREATED_AT DESC,ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
-        if ($allData) {
-            $insertPerfOrderData = [];
-            foreach ($allData as $data) {
-                // 是否关停等状态不能拿业绩
-                if (!$this->isHasPerf($data['TO_USER_ID'])) {
-                    continue;
-                }
-                //零售单不累计业绩,仅存业绩单
-//                if($data['TYPE']!='LS') {
-                    // 给自己增加PCS(个人消费)
-                CalcCache::nowPeriodPerf($data['TO_USER_ID'], $this->_periodNum, [
-                    'PV_PCS' => $data['DEC_PV'],
-                    'PV_PCS_ZC' => $data['DEC_PV'],
-                ]);
-                // 把该会员加入到能拿到业绩的会员缓存中
-                CalcCache::addHasPerfUsers($data['TO_USER_ID'], $this->_periodNum);
-                //加入到报单会员中
-                $toInfo = CalcCache::getUserInfo($data['TO_USER_ID'], $this->_periodNum);
-                CalcCache::addHasBDUsers($data['TO_USER_ID'], $this->_periodNum, [
-                    'TO_USER_ID' => $data['TO_USER_ID'],
-                    'USER_ID' => $data['USER_ID'],
-                    'DEC_ID' => $data['DEC_ID'],
-                    //考虑可能会移网的情况
-                    'REC_USER_ID' => $toInfo['REC_UID'] ?? '',
-                    'CON_USER_ID' => $toInfo['CON_UID'] ?? '',
-                    'DEC_AMOUNT' => $data['DEC_AMOUNT'],
-                    'DEC_PV' => $data['DEC_PV'],
-                ]);
-                // 给上追加业绩
-                $this->loopNetworkParentDo($data['TO_USER_ID'], function ($parent) use (&$data) {
-                    // 给上级会员追加业绩到缓存中
-//                    CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
-//                        'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
-//                    ]);
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'PV_' . $parent['LOCATION'] . 'L' => $data['DEC_PV'],
-                        'PV_' . $parent['LOCATION'] . 'L_TOUCH' => $data['DEC_PV'],
-                        'PV_' . $parent['LOCATION'] . 'L_' . $data['TYPE'] => $data['DEC_PV'],
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-                    unset($parent);
-                });
-                //给推荐关系累计增加业绩
-                $this->loopRelationParentDo($data['TO_USER_ID'], function ($parent) use (&$data) {
-                    // 给上级会员追加业绩到缓存中
-//                    CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
-//                        'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
-//                    ]);
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'PV_PSS' => $data['DEC_PV'],
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-                    unset($parent);
-                });
-
-//                }
-                // 写入业绩单表
-                $decInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
-                $sn = PerfOrder::generateSN();
-                $insertPerfOrderData[] = [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'SN' => $sn,
-                    'DEC_SN' => $data['DEC_SN'],
-                    'DEC_TYPE' => strtoupper($data['TYPE']),
-                    'DEC_STATUS' => PerfOrder::STATUS_NORMAL,
-                    'USER_ID' => $data['TO_USER_ID'],
-                    'LAST_REC_USER_NAME' => $toInfo['REC_USER_NAME'],
-                    'LAST_REC_REAL_NAME' => $toInfo['REC_REAL_NAME'],
-                    'LAST_DEC_LV' => $toInfo['DEC_LV'],
-                    'LAST_EMP_LV' => $toInfo['EMP_LV'],
-                    'LAST_STATUS' => $toInfo['STATUS'],
-                    'PV' => $data['DEC_PV'],
-                    'DEC_AMOUNT' => $data['DEC_AMOUNT'],
-                    'LAST_SUB_COM_ID' => $toInfo['SUB_COM_ID'],
-                    'LAST_PROVINCE' => $toInfo['PROVINCE'],
-                    'LAST_CITY' => $toInfo['CITY'],
-                    'LAST_COUNTY' => $toInfo['COUNTY'],
-                    'DEC_USER_ID' => $data['USER_ID'],
-                    'LAST_DEC_DEC_LV' => $decInfo['DEC_LV'],
-                    'LAST_DEC_SUB_COM_ID' => $decInfo['SUB_COM_ID'],
-                    'LAST_DEC_PROVINCE' => $decInfo['DEC_PROVINCE'],
-                    'LAST_DEC_CITY' => $decInfo['DEC_CITY'],
-                    'LAST_DEC_COUNTY' => $decInfo['DEC_COUNTY'],
-                    'PERIOD_NUM' => $this->_periodNum,
-                    'CALC_MONTH' => $this->_calcYearMonth,
-                    'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-                    'CREATED_AT' => Date::nowTime(),
-                    'CLOSED_AT' => 0,
-                ];
-                unset($data, $decInfo, $sn, $toInfo);
-            }
-            PerfOrder::batchInsert($insertPerfOrderData);
-            unset($insertPerfOrderData, $allData, $snArr);
-            return $this->loopCalcPeriodPerfByDecOrder($offset + $this->_limit);
-        }
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 周结,向上级算业绩,并计入业绩单
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function loopCalcPeriodPerfByOrderDec($offset = 0) {
-        // 循环获取全部报单
-        $allData = OrderDec::findUseDbCalc()->select('ID,SN,USER_ID,ORDER_TYPE,ORDER_AMOUNT,PV,PAY_AMOUNT,PAY_PV,PERIOD_NUM,PAY_TYPE')->where("PERIOD_NUM=:PERIOD_NUM AND IS_DELETE=0 AND ORDER_TYPE=:ORDER_TYPE", [':PERIOD_NUM' => $this->_periodNum, ':ORDER_TYPE'=>'ZC'])->orderBy('ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
-        if ($allData) {
-            $insertPerfOrderData = [];
-            foreach ($allData as $data) {
-                // 是否关停等状态不能拿业绩
-                if (!$this->isHasPerf($data['USER_ID'])) {
-                    continue;
-                }
-                // 给自己增加PCS(个人消费)
-                CalcCache::nowPeriodPerf($data['USER_ID'], $this->_periodNum, [
-                    'PV_PCS' => $data['PAY_PV'],
-                    'PV_PCS_ZC' => $data['PAY_PV'],
-                ]);
-                // 把该会员加入到能拿到业绩的会员缓存中
-                CalcCache::addHasPerfUsers($data['USER_ID'], $this->_periodNum);
-                //加入到报单会员中
-                $toInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
-                CalcCache::addHasBDUsers($data['USER_ID'], $this->_periodNum, [
-                    'TO_USER_ID' => $data['USER_ID'],
-                    'USER_ID' => $toInfo['DEC_ID'],
-                    'DEC_ID' => $toInfo['DEC_ID'],
-                    //考虑可能会移网的情况
-                    'REC_USER_ID' => $toInfo['REC_UID'] ?? '',
-                    'CON_USER_ID' => $toInfo['CON_UID'] ?? '',
-                    'DEC_AMOUNT' => $data['ORDER_AMOUNT'],
-                    'DEC_PV' => $data['PAY_PV'],
-                ]);
-                // 给上追加业绩
-                $this->loopNetworkParentDo($data['USER_ID'], function ($parent) use (&$data) {
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'PV_' . $parent['LOCATION'] . 'L' => $data['PAY_PV'],
-                        'PV_' . $parent['LOCATION'] . 'L_TOUCH' => $data['PAY_PV'],
-                        'PV_' . $parent['LOCATION'] . 'L_' . $data['ORDER_TYPE'] => $data['PAY_PV'],
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-                    unset($parent);
-                });
-                //给推荐关系累计增加业绩
-                $this->loopRelationParentDo($data['USER_ID'], function ($parent) use (&$data) {
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'PV_PSS' => $data['PAY_PV'],
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-                    unset($parent);
-                });
-
-                // 写入业绩单表
-                $decInfo = CalcCache::getUserInfo($toInfo['DEC_ID'], $this->_periodNum);
-                $sn = PerfOrder::generateSN();
-                $insertPerfOrderData[] = [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'SN' => $sn,
-                    'DEC_SN' => $data['SN'],
-                    'DEC_TYPE' => strtoupper($data['ORDER_TYPE']),
-                    'DEC_STATUS' => PerfOrder::STATUS_NORMAL,
-                    'USER_ID' => $data['USER_ID'],
-                    'LAST_REC_USER_NAME' => $toInfo['REC_USER_NAME'],
-                    'LAST_REC_REAL_NAME' => $toInfo['REC_REAL_NAME'],
-                    'LAST_DEC_LV' => $toInfo['DEC_LV'],
-                    'LAST_EMP_LV' => $toInfo['EMP_LV'],
-                    'LAST_STATUS' => $toInfo['STATUS'],
-                    'PV' => $data['PAY_PV'],
-                    'DEC_AMOUNT' => $data['ORDER_AMOUNT'],
-                    'LAST_SUB_COM_ID' => $toInfo['SUB_COM_ID'],
-                    'LAST_PROVINCE' => $toInfo['PROVINCE'],
-                    'LAST_CITY' => $toInfo['CITY'],
-                    'LAST_COUNTY' => $toInfo['COUNTY'],
-                    'DEC_USER_ID' => $toInfo['DEC_ID'],
-                    'LAST_DEC_DEC_LV' => $decInfo['DEC_LV'],
-                    'LAST_DEC_SUB_COM_ID' => $decInfo['SUB_COM_ID'],
-                    'LAST_DEC_PROVINCE' => $decInfo['DEC_PROVINCE'],
-                    'LAST_DEC_CITY' => $decInfo['DEC_CITY'],
-                    'LAST_DEC_COUNTY' => $decInfo['DEC_COUNTY'],
-                    'PERIOD_NUM' => $this->_periodNum,
-                    'CALC_MONTH' => $this->_calcYearMonth,
-                    'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-                    'CREATED_AT' => Date::nowTime(),
-                    'CLOSED_AT' => 0,
-                ];
-                unset($data, $decInfo, $sn, $toInfo);
-            }
-            PerfOrder::batchInsert($insertPerfOrderData);
-            unset($insertPerfOrderData, $allData, $snArr);
-            return $this->loopCalcPeriodPerfByOrderDec($offset + $this->_limit);
-        }
-        unset($allData);
-        return true;
-    }
-
-
-    /**
-     * 从会员的复销订单会员计算复销业绩并加入业绩单
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function loopCalcPerfByFXOrder(int $offset = 0) {
-        // 循环获取全部报单
-        $allData = Order::findUseDbCalc()->select('ID,SN,DEC_SN,USER_ID,ORDER_TYPE,ORDER_AMOUNT,PAY_AMOUNT,PAY_PV,PAY_TYPE,PERIOD_NUM,STATUS,IS_DELETE,P_CALC_MONTH,CREATED_AT')->where("PERIOD_NUM=:PERIOD_NUM AND IS_DELETE=0 AND ORDER_TYPE=:ORDER_TYPE", [':PERIOD_NUM' => $this->_periodNum, ':ORDER_TYPE'=>DeclarationForm::TYPE_FX])->orderBy('CREATED_AT DESC,ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
-        if ($allData) {
-            $insertPerfOrderData = [];
-            foreach ($allData as $data) {
-                // 是否关停等状态不能拿业绩
-                if (!$this->isHasPerf($data['USER_ID'])) {
-                    continue;
-                }
-
-                //如果支付方式是现金,那么实际业绩是支付PV的50%
-                if( $data['PAY_TYPE'] === self::ORDER_PAY_TYPE_CASH ) {
-                    $orderCashAmount = $data['ORDER_AMOUNT'];
-                    //111期开始由50%改为60%-by 2020-04-30修改
-                    $payPv = $data['PAY_PV'] * $this->_sysConfig['cashReconsumeBonusPercent']['VALUE'] / 100;
-                    $cacheDataKey = 'PV_PCS_FX_CASH';
-                }else {
-                    $orderCashAmount = 0;
-                    $payPv = $data['PAY_PV'];
-                    $cacheDataKey = 'PV_PCS_FX_POINT';
-                }
-
-                if( $payPv <= 0 ) continue;
-
-                // 给自己增加PCS(个人消费)
-                CalcCache::nowPeriodPerf($data['USER_ID'], $this->_periodNum, [
-                    'FX_AMOUNT_CASH' => $orderCashAmount,
-                    'PV_PCS' => $payPv,
-                    'PV_PCS_FX' => $payPv,
-                    $cacheDataKey => $payPv,
-                ]);
-                // 把该会员加入到能拿到业绩的会员缓存中
-                CalcCache::addHasPerfUsers($data['USER_ID'], $this->_periodNum);
-                // 给上追加业绩
-                $this->loopNetworkParentDo($data['USER_ID'], function ($parent) use (&$data, $payPv) {
-                    // 给上级会员追加业绩到缓存中
-//                    CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
-//                        'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
-//                    ]);
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'PV_' . $parent['LOCATION'] . 'L' => $payPv,
-                        'PV_' . $parent['LOCATION'] . 'L_TOUCH' => $payPv,
-                        'PV_' . $parent['LOCATION'] . 'L_FX' => $payPv,
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-                });
-                //给推荐关系累计增加业绩
-                $this->loopRelationParentDo($data['USER_ID'], function ($parent) use ($data, $payPv) {
-                    // 给上级会员追加业绩到缓存中
-//                    CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
-//                        'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
-//                    ]);
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'PV_PSS' => $payPv,
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-                });
-
-//                }
-                // 写入业绩单表
-                $baseInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
-                $sn = PerfOrder::generateSN();
-                $insertPerfOrderData[] = [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'SN' => $sn,
-                    'DEC_SN' => null,
-                    'DEC_TYPE' => 'FX',
-                    'DEC_STATUS' => PerfOrder::STATUS_NORMAL,
-                    'USER_ID' => $data['USER_ID'],
-                    'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
-                    'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
-                    'LAST_DEC_LV' => $baseInfo['DEC_LV'],
-                    'LAST_EMP_LV' => $baseInfo['EMP_LV'],
-                    'LAST_STATUS' => $baseInfo['STATUS'],
-                    'PV' => $payPv,
-                    'DEC_AMOUNT' => $data['PAY_AMOUNT'],
-                    'LAST_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
-                    'LAST_PROVINCE' => $baseInfo['PROVINCE'],
-                    'LAST_CITY' => $baseInfo['CITY'],
-                    'LAST_COUNTY' => $baseInfo['COUNTY'],
-                    'DEC_USER_ID' => $data['USER_ID'],
-                    'LAST_DEC_DEC_LV' => $baseInfo['DEC_LV'],
-                    'LAST_DEC_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
-                    'LAST_DEC_PROVINCE' => $baseInfo['PROVINCE'],
-                    'LAST_DEC_CITY' => $baseInfo['CITY'],
-                    'LAST_DEC_COUNTY' => $baseInfo['COUNTY'],
-                    'PERIOD_NUM' => $this->_periodNum,
-                    'CALC_MONTH' => $this->_calcYearMonth,
-                    'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-                    'CREATED_AT' => Date::nowTime(),
-                    'CLOSED_AT' => 0,
-                ];
-                unset($data, $baseInfo, $sn, $orderCashAmount, $payPv, $cacheDataKey);
-            }
-            PerfOrder::batchInsert($insertPerfOrderData);
-
-            unset($insertPerfOrderData, $allData, $snArr);
-            return $this->loopCalcPerfByFXOrder($offset + $this->_limit);
-        }
-
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 从会员的商城复销订单会员计算复销业绩并加入业绩单
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function loopCalcPerfByShopFXOrder(int $offset = 0) {
-        // 循环获取全部报单
-        $allData = OrderShop::findUseDbCalc()->select('ID,SN,DEC_SN,USER_ID,ORDER_TYPE,ORDER_AMOUNT,PAY_AMOUNT,PAY_PV,PAY_TYPE,PERIOD_NUM,STATUS,IS_DELETE,P_CALC_MONTH,CREATED_AT')->where("PERIOD_NUM=:PERIOD_NUM AND IS_DELETE=0 AND ORDER_TYPE=:ORDER_TYPE", [':PERIOD_NUM' => $this->_periodNum, ':ORDER_TYPE'=>DeclarationForm::TYPE_FX])->orderBy('CREATED_AT DESC,ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
-        if ($allData) {
-            $insertPerfOrderData = [];
-            foreach ($allData as $data) {
-                // 是否关停等状态不能拿业绩
-                if (!$this->isHasPerf($data['USER_ID'])) {
-                    continue;
-                }
-
-                //如果支付方式是现金,那么实际业绩是支付PV的50%
-                if( $data['PAY_TYPE'] === self::ORDER_PAY_TYPE_CASH ) {
-                    $orderCashAmount = $data['ORDER_AMOUNT'];
-                    //111期开始由50%改为60%-by 2020-04-30修改
-                    $payPv = $data['PAY_PV'] * $this->_sysConfig['cashReconsumeBonusPercent']['VALUE'] / 100;
-                    $cacheDataKey = 'PV_PCS_FX_CASH';
-                }else {
-                    $orderCashAmount = 0;
-                    $payPv = $data['PAY_PV'];
-                    $cacheDataKey = 'PV_PCS_FX_POINT';
-                }
-
-                if( $payPv <= 0 ) continue;
-
-                // 给自己增加PCS(个人消费)
-                CalcCache::nowPeriodPerf($data['USER_ID'], $this->_periodNum, [
-                    'FX_AMOUNT_CASH' => $orderCashAmount,
-                    'PV_PCS' => $payPv,
-                    'PV_PCS_FX' => $payPv,
-                    $cacheDataKey => $payPv,
-                ]);
-                // 把该会员加入到能拿到业绩的会员缓存中
-                CalcCache::addHasPerfUsers($data['USER_ID'], $this->_periodNum);
-                // 给上追加业绩
-                $this->loopNetworkParentDo($data['USER_ID'], function ($parent) use (&$data, $payPv) {
-                    // 给上级会员追加业绩到缓存中
-//                    CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
-//                        'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
-//                    ]);
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'PV_' . $parent['LOCATION'] . 'L' => $payPv,
-                        'PV_' . $parent['LOCATION'] . 'L_TOUCH' => $payPv,
-                        'PV_' . $parent['LOCATION'] . 'L_FX' => $payPv,
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-                });
-                //给推荐关系累计增加业绩
-                $this->loopRelationParentDo($data['USER_ID'], function ($parent) use ($data, $payPv) {
-                    // 给上级会员追加业绩到缓存中
-//                    CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
-//                        'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
-//                    ]);
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'PV_PSS' => $payPv,
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-                });
-
-//                }
-                // 写入业绩单表
-                $baseInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
-                $sn = PerfOrder::generateSN();
-                $insertPerfOrderData[] = [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'SN' => $sn,
-                    'DEC_SN' => null,
-                    'DEC_TYPE' => 'FX',
-                    'DEC_STATUS' => PerfOrder::STATUS_NORMAL,
-                    'USER_ID' => $data['USER_ID'],
-                    'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
-                    'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
-                    'LAST_DEC_LV' => $baseInfo['DEC_LV'],
-                    'LAST_EMP_LV' => $baseInfo['EMP_LV'],
-                    'LAST_STATUS' => $baseInfo['STATUS'],
-                    'PV' => $payPv,
-                    'DEC_AMOUNT' => $data['PAY_AMOUNT'],
-                    'LAST_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
-                    'LAST_PROVINCE' => $baseInfo['PROVINCE'],
-                    'LAST_CITY' => $baseInfo['CITY'],
-                    'LAST_COUNTY' => $baseInfo['COUNTY'],
-                    'DEC_USER_ID' => $data['USER_ID'],
-                    'LAST_DEC_DEC_LV' => $baseInfo['DEC_LV'],
-                    'LAST_DEC_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
-                    'LAST_DEC_PROVINCE' => $baseInfo['PROVINCE'],
-                    'LAST_DEC_CITY' => $baseInfo['CITY'],
-                    'LAST_DEC_COUNTY' => $baseInfo['COUNTY'],
-                    'PERIOD_NUM' => $this->_periodNum,
-                    'CALC_MONTH' => $this->_calcYearMonth,
-                    'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-                    'CREATED_AT' => Date::nowTime(),
-                    'CLOSED_AT' => 0,
-                ];
-                unset($data, $baseInfo, $sn, $orderCashAmount, $payPv, $cacheDataKey);
-            }
-            PerfOrder::batchInsert($insertPerfOrderData);
-
-            unset($insertPerfOrderData, $allData, $snArr);
-            return $this->loopCalcPerfByShopFXOrder($offset + $this->_limit);
-        }
-
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 达标复销订单
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function loopCalcPerfByStandardFXOrder(int $offset = 0) {
-        if (!$this->_isCalcMonth) {
-            return true;
-        }
-        $allData = OrderStandard::findUseDbCalc()->select('ID,SN,DEC_SN,USER_ID,ORDER_TYPE,ORDER_AMOUNT,PAY_AMOUNT,PAY_PV,PAY_TYPE,PERIOD_NUM,STATUS,IS_DELETE,CREATED_AT')->where("CALC_MONTH=:CALC_MONTH", [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
-        if ($allData) {
-            $insertPerfOrderData = [];
-            foreach ($allData as $data) {
-                // 是否关停等状态不能拿业绩
-                if (!$this->isHasPerf($data['USER_ID'])) {
-                    continue;
-                }
-
-                //如果支付方式是现金,那么实际业绩是支付PV的50%
-                if( $data['PAY_TYPE'] === self::ORDER_PAY_TYPE_CASH ) {
-                    $orderCashAmount = $data['ORDER_AMOUNT'];
-//                    $payPv = $data['PAY_PV'] * $this->_sysConfig['cashReconsumeBonusPercent']['VALUE'] / 100;
-                }else {
-                    $orderCashAmount = 0;
-//                    $payPv = $data['PAY_PV'];
-                }
-
-                if( $orderCashAmount <= 0 ) continue;
-
-
-
-                // 给自己增加个人业绩
-                CalcCache::nowStandardMonthPerf($data['USER_ID'], $this->_periodNum, [
-                    'AMOUNT_PCS' => $orderCashAmount,
-                ]);
-                // 把该会员加入到能拿到业绩的会员缓存中
-                CalcCache::addHasStandardMonthPerfUsers($data['USER_ID'], $this->_periodNum);
-
-                //只有无聘级业绩才向上累加
-                $baseInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
-                if( $baseInfo['EMP_LV'] !=  EmployLevel::NO_LEVEL_ID ) {
-                    continue;
-                }
-                //给推荐团队添加团队业绩 注:如果些订单特别多的情况,可以分2步。先只计算个人业绩、然后根据个人业绩再计算团队业绩。
-                //给推荐关系累计增加业绩
-                $this->loopRelationParentDo($data['USER_ID'], function ($parent) use ($data, $orderCashAmount) {
-                    // 给上级会员追加本期业绩到缓存中
-                    CalcCache::nowStandardMonthPerf($parent['PARENT_UID'], $this->_periodNum, [
-                        'AMOUNT_PSS' => $orderCashAmount,
-                    ]);
-                    // 把该会员加入到能拿到业绩的会员缓存中
-                    CalcCache::addHasStandardMonthPerfUsers($parent['PARENT_UID'], $this->_periodNum);
-
-                    //获取parent聘级
-                    $parentUserInfo = CalcCache::getUserInfo($parent['PARENT_UID'], $this->_periodNum);
-                    if( $parentUserInfo['EMP_LV'] !=  EmployLevel::NO_LEVEL_ID ) {//如果碰到有聘级的业绩就不在向上累加了
-                        return self::LOOP_FINISH;
-                    }
-                });
-
-                unset($data, $baseInfo, $orderCashAmount);
-            }
-
-            unset($insertPerfOrderData, $allData, $snArr);
-            return $this->loopCalcPerfByStandardFXOrder($offset + $this->_limit);
-        }
-
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 计算月业绩表相关的数据并写入数据库
-     * @param int $offset
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public function loopCalcMonthPerfTableData(int $offset = 0) {
-        if (!$this->_isCalcMonth) {
-            return true;
-        }
-        echo sprintf("时间:[%s]月业绩,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
-        // 从缓存列表里面从底层往上倒序获取会员
-
-//        $allData = PerfPeriod::findUseDbCalc()->from(PerfPeriod::tableName()  . ' AS PP')->select('PP.USER_ID AS USER_ID, SUM(PP.PV_PCS) AS PV_PCS_SUM,SUM(PP.PV_PSS) AS PV_PSS_SUM,SUM(PP.PV_1L) AS PV_1L_SUM,SUM(PP.PV_2L) AS PV_2L_SUM,SUM(PP.PV_3L) AS PV_3L_SUM,SUM(PP.PV_4L) AS PV_4L_SUM,SUM(PP.PV_5L) AS PV_5L_SUM, SUM(PM.PV_1L_TOTAL) AS PV_1L_TOTAL, SUM(PM.PV_2L_TOTAL) AS PV_2L_TOTAL, SUM(PM.PV_3L_TOTAL) AS PV_3L_TOTAL, SUM(PM.PV_4L_TOTAL) AS PV_4L_TOTAL,SUM(PM.PV_5L_TOTAL) AS PV_5L_TOTAL, SUM(PM.PV_PSS_TOTAL) AS PV_PSS_TOTAL')->leftJoin(PerfMonth::tableName()  . ' AS PM', 'PM.USER_ID=PP.USER_ID AND PM.CALC_MONTH=:LAST_CALC_MONTH', ['LAST_CALC_MONTH'=>$this->_lastCalcYearMonth])->where('PP.CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->groupBy('PP.USER_ID')->orderBy('PP.USER_ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
-        $allData = PerfPeriod::findUseDbCalc()->select('USER_ID, SUM(FX_AMOUNT_CASH) AS FX_AMOUNT_CASH_SUM,SUM(PV_PCS) AS PV_PCS_SUM,SUM(PV_PCS_FX) AS PV_PCS_FX_SUM,SUM(PV_PSS) AS PV_PSS_SUM,SUM(PV_1L) AS PV_1L_SUM,SUM(PV_2L) AS PV_2L_SUM,SUM(PV_3L) AS PV_3L_SUM,SUM(PV_4L) AS PV_4L_SUM,SUM(PV_5L) AS PV_5L_SUM,SUM(PV_1L_ZC) AS PV_1L_ZC_SUM,SUM(PV_2L_ZC) AS PV_2L_ZC_SUM,SUM(PV_3L_ZC) AS PV_3L_ZC_SUM,SUM(PV_4L_ZC) AS PV_4L_ZC_SUM,SUM(PV_5L_ZC) AS PV_5L_ZC_SUM')->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->groupBy('USER_ID')->orderBy('USER_ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
-        if ($allData) {
-            // 月度业绩表
-            foreach ($allData as $everyData) {
-                $userId = $everyData['USER_ID'];
-//                $lastMonthData = PerfMonth::find()->select('PV_1L_TOTAL, PV_2L_TOTAL, PV_3L_TOTAL, PV_4L_TOTAL, PV_5L_TOTAL, PV_PSS_TOTAL')->where('USER_ID=:USER_ID AND CALC_MONTH=:LAST_CALC_MONTH', [
-//                    'USER_ID'=>$userId,
-//                    'LAST_CALC_MONTH'=>$this->_lastCalcYearMonth,
-//                ])->asArray()->one();
-                //往期业绩
-                $userLastPerf = CalcCache::userPerf($userId, $this->_periodNum);
-                //本期业绩
-                $periodPerf = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
-
-                $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
-                //级别必须为VIP
-                $isVip = false;
-                if( $userBaseInfo['DEC_LV'] === DeclarationLevel::VIP_LEVEL_ID ) {
-                    $isVip= true;
-                }
-                if( $this->_sysConfig['vipBonusGoldDecLevel']['VALUE'] && $userBaseInfo['DEC_LV'] === DeclarationLevel::JIN_ZUAN_LEVEL_ID ) {
-                    $isVip = true;
-                }
-
-
-                $nowMonthPerf = [
-                    'USER_ID' => $userId,
-                    'FX_AMOUNT_CASH' => $everyData['FX_AMOUNT_CASH_SUM'],
-                    'PV_PCS' => $everyData['PV_PCS_SUM'],
-                    'PV_PCS_FX' => $everyData['PV_PCS_FX_SUM'],
-                    'PV_PSS' => $everyData['PV_PSS_SUM'],
-                    'PV_1L' => $everyData['PV_1L_SUM'],
-                    'PV_2L' => $everyData['PV_2L_SUM'],
-                    'PV_3L' => $everyData['PV_3L_SUM'],
-                    'PV_4L' => $everyData['PV_4L_SUM'],
-                    'PV_5L' => $everyData['PV_5L_SUM'],
-
-                    //VIP统计相关业绩
-                    'VIP_PV_1L_ZC' => $isVip ? $everyData['PV_1L_ZC_SUM'] : 0,
-                    'VIP_PV_2L_ZC' => $isVip ? $everyData['PV_2L_ZC_SUM'] : 0,
-                    'VIP_PV_3L_ZC' => $isVip ? $everyData['PV_3L_ZC_SUM'] : 0,
-                    'VIP_PV_4L_ZC' => $isVip ? $everyData['PV_4L_ZC_SUM'] : 0,
-                    'VIP_PV_5L_ZC' => $isVip ? $everyData['PV_5L_ZC_SUM'] : 0,
-
-                    //总数据,历史+本期。不能用上月加本月,因为上月可能没业绩,上上个月有业绩。
-                    'PV_1L_TOTAL' => $periodPerf['PV_1L'] + $userLastPerf['PV_1L'],
-                    'PV_2L_TOTAL' => $periodPerf['PV_2L'] + $userLastPerf['PV_2L'],
-                    'PV_3L_TOTAL' => $periodPerf['PV_3L'] + $userLastPerf['PV_3L'],
-                    'PV_4L_TOTAL' => $periodPerf['PV_4L'] + $userLastPerf['PV_4L'],
-                    'PV_5L_TOTAL' => $periodPerf['PV_5L'] + $userLastPerf['PV_5L'],
-                    'PV_PSS_TOTAL' => $periodPerf['PV_PSS'] + $userLastPerf['PV_PSS_TOTAL'],
-                ];
-
-                // 把会员的月业绩写入缓存中,以便下面的奖金计算从缓冲中获取数据效率高
-                CalcCache::addHasMonthPerfUsers($userId, $this->_periodNum);
-                CalcCache::nowMonthPerf($userId, $this->_periodNum, $nowMonthPerf);
-
-                unset($userId, $everyData, $nowMonthPerf, $lastMonthData, $userBaseInfo, $isVip);
-            }
-            unset($allData);
-            $this->loopCalcMonthPerfTableData($offset + $this->_limit);
-        }
-
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 计算聘级
-     * @param int $offset
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public function loopCalcEmpLevel(int $offset = 0) {
-        if (!$this->_isCalcMonth) {
-            return true;
-        }
-        echo sprintf("时间:[%s]计算聘级,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
-        // 从缓存列表里面从底层往上倒序获取会员
-        $allData = CalcCache::getUsers($this->_periodNum, $offset, $this->_limit);
-        if ($allData) {
-            // 月度业绩表
-            foreach ($allData as $userId) {
-                $userInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
-                $nowMonthPerf = CalcCache::nowMonthPerf($userId, $this->_periodNum);
-                $empLevel = $this->checkEmpLevel($userId, $nowMonthPerf, $userInfo['EMP_LV']);
-
-                //根据用户的级别判断 能否得到级别积分
-                if( $empLevel['LEVEL_SCORE'] > 0 ) {
-                    CalcCache::nowMonthScore($userId, $this->_periodNum, [
-                        'LEVEL_SCORE' => $empLevel['LEVEL_SCORE'],
-                    ]);
-                    CalcCache::addHasScoreUsers($userId, $this->_periodNum);
-                }
-
-
-                //更新月业绩的聘级和用户信息中的聘级
-                CalcCache::nowMonthPerf($userId, $this->_periodNum, [
-                    'EMP_LEVEL' => $empLevel['ID']
-                ]);
-
-                //为业绩单更新结算时聘级
-//                    PerfOrder::updateAll(['LAST_EMP_LV'=>$empLevel['ID']],'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',[':USER_ID'=>$userId,':PERIOD_NUM'=>$this->_periodNum]);
-                $userEmpLevel = $this->_empLevelConfig[$userInfo['EMP_LV']];
-                $userEmpLevelSort = $userEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
-                //不降级
-                if( $empLevel['SORT'] <= $userEmpLevelSort ) continue;
-
-                $userInfo['EMP_LV'] = $empLevel['ID'];
-                CalcCache::setUserInfo($userId, $this->_periodNum, $userInfo);
-
-                //可以判断用户是否升级,能否得到升级积分
-                //因为默认是不降级,直接获得升级积分
-                $upgradeScore = 0;
-                foreach ($this->_empLevelConfig as $everyEmpLevel) {
-                    if( $everyEmpLevel['SORT'] <= $userEmpLevelSort ) continue;
-                    if( $everyEmpLevel['SORT'] > $empLevel['SORT'] ) continue;
-
-                    $upgradeScore += $everyEmpLevel['UPGRADE_SCORE'];
-
-                    unset($everyEmpLevel);
-                }
-
-                if( $upgradeScore > 0 ) {
-                    CalcCache::nowMonthScore($userId, $this->_periodNum, [
-                        'UPGRADE_SCORE' => $upgradeScore
-                    ]);
-                    CalcCache::addHasScoreUsers($userId, $this->_periodNum);
-                }
-
-                unset($userId, $empLevel, $nowMonthPerf, $userInfo, $userEmpLevel, $userEmpLevelSort, $upgradeScore);
-            }
-            unset($allData);
-            $this->loopCalcEmpLevel($offset + $this->_limit);
-        }
-
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 计算公司总业绩
-     * @return bool
-     * @throws Exception
-     */
-    public function calcPerfCompany() {
-        if (!$this->_isCalcMonth) {
-            return true;
-        }
-        $perfCompany = PerfCompany::findOne(['CALC_MONTH' => $this->_calcYearMonth]);
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            if (!$perfCompany) {
-                $perfCompany = new PerfCompany();
-            }
-            $perfCompany->PV = $this->_companyMonthPerf;
-            $perfCompany->CREATED_AT = Date::nowTime();
-            $perfCompany->CALC_YEAR = $this->_calcYear;
-            $perfCompany->CALC_MONTH = $this->_calcYearMonth;
-            if (!$perfCompany->save()) {
-                throw new Exception(Form::formatErrorsForApi($perfCompany->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            throw new Exception($e->getMessage());
-        }
-        unset($perfCompany);
-        return true;
-    }
-
-    /**
-     * 循环有业绩会员,并入库
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function loopWriteNowPerf($offset = 0) {
-        echo sprintf("时间:[%s]缓存本期业绩数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
-        // 从缓存列表里面从底层往上倒序获取会员
-        $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
-        if($allData){
-            $insertDataPeriodPerf = [];
-            foreach($allData as $userId){
-                $insertDataPeriodPerf[] = $this->nowPeriodPerfData($userId);
-                unset($userId);
-            }
-            PerfPeriod::batchInsert($insertDataPeriodPerf);
-
-            unset($insertDataPeriodPerf, $allData);
-            return $this->loopWriteNowPerf($offset + $this->_limit);
-        }
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 循环有月业绩会员,并入库
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function loopWriteMonthPerf($offset = 0) {
-        if(!$this->_isCalcMonth){
-            return true;
-        }
-        echo sprintf("时间:[%s]缓存本月业绩数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
-        // 从缓存列表里面从底层往上倒序获取会员
-        $allData = CalcCache::getHasMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
-        if($allData){
-            $insertDataMonthPerf = [];
-            foreach($allData as $userId){
-                $insertDataMonthPerf[] = $this->nowMonthPerfData($userId);
-                unset($userId);
-            }
-
-            PerfMonth::batchInsert($insertDataMonthPerf);
-            unset($insertDataMonthPerf, $allData);
-            return $this->loopWriteMonthPerf($offset + $this->_limit);
-        }
-        unset($allData);
-        return true;
-    }
-
-
-    /**
-     * 循环达标业绩会员,并入库
-     * @param int $offset
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function loopWriteStandardPerf($offset = 0) {
-        if(!$this->_isCalcMonth){
-            return true;
-        }
-        echo sprintf("时间:[%s]缓存达标业绩数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
-        // 从缓存列表里面从底层往上倒序获取会员
-        $allData = CalcCache::getHasStandardMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
-        if($allData){
-            $insertDataStandardPerf = [];
-            foreach($allData as $userId) {
-                $data = CalcCache::nowStandardMonthPerf($userId, $this->_periodNum);
-                $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
-                $insertDataStandardPerf[] = [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'USER_ID' => $userId,
-                    'LAST_DEC_LV' => $baseInfo['DEC_LV'],
-                    'LAST_EMP_LV' => $baseInfo['EMP_LV'],
-                    'LAST_STATUS' => $baseInfo['STATUS'],
-                    'AMOUNT_PCS' => $data['AMOUNT_PCS'],
-                    'AMOUNT_PSS' => $data['AMOUNT_PSS'],
-                    'CALC_MONTH' => $this->_calcYearMonth,
-                    'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-                    'CREATED_AT' => Date::nowTime(),
-                ];
-                unset($data, $baseInfo, $userId);
-            }
-
-            PerfStandard::batchInsert($insertDataStandardPerf);
-            unset($insertDataStandardPerf, $allData);
-            return $this->loopWriteStandardPerf($offset + $this->_limit);
-        }
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 本期业绩数据
-     * @param $userId
-     * @return array
-     */
-    public function nowPeriodPerfData($userId){
-        $data = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
-        $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
-        $result = [
-            'ID' => SnowFake::instance()->generateId(),
-            'USER_ID' => $userId,
-            'LAST_DEC_LV' => $baseInfo['DEC_LV'],
-            'LAST_EMP_LV' => $baseInfo['EMP_LV'],
-            'LAST_STATUS' => $baseInfo['STATUS'],
-            'FX_AMOUNT_CASH' => $data['FX_AMOUNT_CASH'],
-            'PV_PCS' => $data['PV_PCS'],
-            'PV_PSS' => $data['PV_PSS'],
-            'PV_PCS_ZC' => $data['PV_PCS_ZC'],
-            'PV_PCS_YH' => $data['PV_PCS_YH'],
-            'PV_PCS_ZG' => $data['PV_PCS_ZG'],
-            'PV_PCS_LS' => $data['PV_PCS_LS'],
-            'PV_PCS_FX' => $data['PV_PCS_FX'],
-            'PV_PCS_FX_CASH' => $data['PV_PCS_FX_CASH'],
-            'PV_PCS_FX_POINT' => $data['PV_PCS_FX_POINT'],
-            'PV_1L' => $data['PV_1L'],
-            'PV_1L_TOUCH' => $data['PV_1L_TOUCH'],
-            'PV_1L_ZC' => $data['PV_1L_ZC'],
-            'PV_1L_YH' => $data['PV_1L_YH'],
-            'PV_1L_ZG' => $data['PV_1L_ZG'],
-            'PV_1L_LS' => $data['PV_1L_LS'],
-            'PV_1L_FX' => $data['PV_1L_FX'],
-            'PV_2L' => $data['PV_2L'],
-            'PV_2L_TOUCH' => $data['PV_2L_TOUCH'],
-            'PV_2L_ZC' => $data['PV_2L_ZC'],
-            'PV_2L_YH' => $data['PV_2L_YH'],
-            'PV_2L_ZG' => $data['PV_2L_ZG'],
-            'PV_2L_LS' => $data['PV_2L_LS'],
-            'PV_2L_FX' => $data['PV_2L_FX'],
-            'PV_3L' => $data['PV_3L'],
-            'PV_3L_TOUCH' => $data['PV_3L_TOUCH'],
-            'PV_3L_ZC' => $data['PV_3L_ZC'],
-            'PV_3L_YH' => $data['PV_3L_YH'],
-            'PV_3L_ZG' => $data['PV_3L_ZG'],
-            'PV_3L_LS' => $data['PV_3L_LS'],
-            'PV_3L_FX' => $data['PV_3L_FX'],
-            'PV_4L' => $data['PV_4L'],
-            'PV_4L_TOUCH' => $data['PV_4L_TOUCH'],
-            'PV_4L_ZC' => $data['PV_4L_ZC'],
-            'PV_4L_YH' => $data['PV_4L_YH'],
-            'PV_4L_ZG' => $data['PV_4L_ZG'],
-            'PV_4L_LS' => $data['PV_4L_LS'],
-            'PV_4L_FX' => $data['PV_4L_FX'],
-            'PV_5L' => $data['PV_5L'],
-            'PV_5L_TOUCH' => $data['PV_5L_TOUCH'],
-            'PV_5L_ZC' => $data['PV_5L_ZC'],
-            'PV_5L_YH' => $data['PV_5L_YH'],
-            'PV_5L_ZG' => $data['PV_5L_ZG'],
-            'PV_5L_LS' => $data['PV_5L_LS'],
-            'PV_5L_FX' => $data['PV_5L_FX'],
-            'PV_LS_TOUCH' => $data['PV_LS_TOUCH'],
-            'SURPLUS_1L' => $data['SURPLUS_1L'],
-            'SURPLUS_2L' => $data['SURPLUS_2L'],
-            'SURPLUS_3L' => $data['SURPLUS_3L'],
-            'SURPLUS_4L' => $data['SURPLUS_4L'],
-            'SURPLUS_5L' => $data['SURPLUS_5L'],
-            'SURPLUS_LS' => $data['SURPLUS_LS'],
-            'PERIOD_NUM' => $this->_periodNum,
-            'CALC_MONTH' => $this->_calcYearMonth,
-            'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-            'CREATED_AT' => Date::nowTime(),
-        ];
-        unset($data);
-        return $result;
-    }
-
-
-
-    /**
-     * 本月业绩
-     * @param $userId
-     * @return array
-     */
-    public function nowMonthPerfData($userId){
-        $data = CalcCache::nowMonthPerf($userId, $this->_periodNum);
-        $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
-        $result = [
-            'ID' => SnowFake::instance()->generateId(),
-            'USER_ID' => $userId,
-            'LAST_DEC_LV' => $baseInfo['DEC_LV'],
-            'LAST_EMP_LV' => $data['EMP_LEVEL'],
-            'LAST_STATUS' => $baseInfo['STATUS'],
-            'FX_AMOUNT_CASH' => $data['FX_AMOUNT_CASH'],
-            'PV_PCS' => $data['PV_PCS'],
-            'PV_PCS_FX' => $data['PV_PCS_FX'],
-            'PV_PSS' => $data['PV_PSS'],
-            'PV_1L' => $data['PV_1L'],
-            'PV_2L' => $data['PV_2L'],
-            'PV_3L' => $data['PV_3L'],
-            'PV_4L' => $data['PV_4L'],
-            'PV_5L' => $data['PV_5L'],
-            'VIP_PV_1L_ZC' => $data['VIP_PV_1L_ZC'],
-            'VIP_PV_2L_ZC' => $data['VIP_PV_2L_ZC'],
-            'VIP_PV_3L_ZC' => $data['VIP_PV_3L_ZC'],
-            'VIP_PV_4L_ZC' => $data['VIP_PV_4L_ZC'],
-            'VIP_PV_5L_ZC' => $data['VIP_PV_5L_ZC'],
-            'PV_1L_TOTAL' => $data['PV_1L_TOTAL'],
-            'PV_2L_TOTAL' => $data['PV_2L_TOTAL'],
-            'PV_3L_TOTAL' => $data['PV_3L_TOTAL'],
-            'PV_4L_TOTAL' => $data['PV_4L_TOTAL'],
-            'PV_5L_TOTAL' => $data['PV_5L_TOTAL'],
-            'PV_PSS_TOTAL' => $data['PV_PSS_TOTAL'],
-            'CF_PERCENT' => $data['CF_PERCENT'],
-            'LX_PERCENT' => $data['LX_PERCENT'],
-            'FX_STATUS' => $data['FX_STATUS'],
-            'CALC_MONTH' => $this->_calcYearMonth,
-            'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-            'CREATED_AT' => Date::nowTime(),
-        ];
-        unset($data);
-        return $result;
-    }
-
-    /**
-     * 循环父级并执行回调函数
-     * @param $userId
-     * @param callable $callbackFunc
-     * @param int $offset
-     * @return bool
-     */
-    public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
-        $allParents = Cache::getAllNetworkParents($userId);
-        $allData = array_slice($allParents, $offset, $this->_limit);
-        unset($allParents);
-        if ($allData) {
-            foreach ($allData as $data) {
-                $funcResult = $callbackFunc($data);
-                if ($funcResult === self::LOOP_FINISH) {
-                    return true;
-                } elseif ($funcResult === self::LOOP_CONTINUE) {
-                    continue;
-                }
-                unset($data, $funcResult);
-            }
-            unset($allData);
-            return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
-        }
-        return true;
-    }
-
-    /**
-     * 循环推荐网络的父级
-     * @param $userId
-     * @param callable $callbackFunc
-     * @param int $offset
-     * @return bool
-     */
-    public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
-        $allParents = Cache::getAllRelationParents($userId);
-        $allData = array_slice($allParents, $offset, $this->_limit);
-        unset($allParents);
-        if ($allData) {
-            foreach ($allData as $data) {
-                $funcResult = $callbackFunc($data);
-                if ($funcResult === self::LOOP_FINISH) {
-                    return true;
-                } elseif ($funcResult === self::LOOP_CONTINUE) {
-                    continue;
-                }
-                unset($data, $funcResult);
-            }
-
-            unset($allData);
-            return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
-        }
-        return true;
-    }
-
-    /**
-     * ==== 聘级计算开始 ====
-     */
-
-    /**
-     * 查看会员聘级
-     * @param $userId
-     * @param $nowMonthPerf
-     * @param $userEmpLevelId
-     * @return bool|mixed|\yii\db\ActiveRecord
-     */
-    public function checkEmpLevel($userId, $nowMonthPerf, $userEmpLevelId) {
-        $empLevel = $this->_empLevelConfig;
-        $userEmpLevel = $empLevel[$userEmpLevelId];
-        $userEmpLevelSort = $userEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
-        $childEmpLevelNumArr = CalcCache::hasEmpLevelNum($userId, $this->_periodNum);
-
-        // 判断主任到首席总监
-        $resultLevel = $this->isEmpLevelOther($empLevel, $childEmpLevelNumArr, $userEmpLevelSort);
-        unset($empLevel, $childEmpLevelNumArr);
-
-        if( empty($resultLevel) ) {
-            //不降级
-            if ( $userEmpLevelSort < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {
-                //主任
-                if ($checkLevel = $this->isEmpLevel1($userId, $nowMonthPerf)) {
-                    $resultLevel = $checkLevel;
-                } else {// 无聘级会员
-                    $resultLevel = EmployLevel::getLevelFromSort(EmployLevel::EMP_LEVEL_SORT['NO_LEVEL']);
-                }
-            }else {
-                $resultLevel = $userEmpLevel;
-            }
-        }
-        unset($userEmpLevel, $userEmpLevelSort);
-
-        // 获取到级别以后,给上级的相应人数中追加数量
-        $parentRecUserId = $userId;
-        $this->loopRelationParentDo($userId, function ($parent) use ($resultLevel, &$parentRecUserId) {
-            if( !$parentRecUserId ) return self::LOOP_FINISH;
-            //判断$parentRecUserId是否为$parent['PARENT_UID']的直推
-            $parentUid = $parent['PARENT_UID'];
-            $toInfo = CalcCache::getUserInfo($parentRecUserId, $this->_periodNum);
-            if( !isset($toInfo['REC_UID']) ) {
-                echo $parentRecUserId . PHP_EOL;
-            }
-            if( isset($toInfo['REC_UID']) && $parentUid !== $toInfo['REC_UID'] ) {
-                $parentUid = $toInfo['REC_UID'];
-            }
-            unset($toInfo);
-            if( !$parentUid ) self::LOOP_FINISH;
-
-            CalcCache::hasEmpLevelNum($parentUid, $this->_periodNum, [$parentRecUserId => [$resultLevel['ID'] => 1]]);
-            //每次记录上次的USER_ID
-            $parentRecUserId = $parentUid;
-        });
-        return $resultLevel;
-    }
-
-    /**
-     * 是否达到主任
-     * @param $userId
-     * @param $nowMonthPerf
-     * @return bool|mixed|\yii\db\ActiveRecord
-     * @throws \yii\db\Exception
-     */
-    public function isEmpLevel1($userId, $nowMonthPerf) {
-        $level1Option = EmployLevel::getLevelFromSort(EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL']);
-        //条件去除最大部门,其它部门累计50万
-        if( $nowMonthPerf['PV_PSS_TOTAL'] < $level1Option['OTHER_DEPART_PERF'] ) {//本身业绩就小于50万
-            unset($level1Option);
-            return false;
-        }
-
-        $oneDeepRelation = CalcCache::getChildrenOneDeepFromRedis($userId, $this->_periodNum);
-        if (  count($oneDeepRelation) <= 1 ) {//只有一个区就不判断了
-            unset($oneDeepRelation, $level1Option);
-            return false;
-        }
-        $maxPvPSS = 0;
-        $childPvPssTotalSum = 0;
-        foreach ($oneDeepRelation as $childData) {
-            //往期业绩
-            $userLastPerf = CalcCache::userPerf($childData['USER_ID'], $this->_periodNum);
-            //本期业绩
-            $periodPerf = CalcCache::nowPeriodPerf($childData['USER_ID'], $this->_periodNum);
-            $pvPcsTotal = $userLastPerf['PV_PCS_ZC'] + $userLastPerf['PV_PCS_FX'] + $periodPerf['PV_PCS'];
-
-            $pvPssTotal = $userLastPerf['PV_PSS_TOTAL'] + $periodPerf['PV_PSS'];
-            $childPvPssTotal = $pvPcsTotal + $pvPssTotal;
-            unset($userLastPerf, $periodPerf, $pvPcsTotal, $pvPssTotal);
-
-            $childPvPssTotalSum += $childPvPssTotal;
-            if( $childPvPssTotal >= $maxPvPSS ) {
-                $maxPvPSS = $childPvPssTotal;
-            }
-
-            unset($childData, $childPvPssTotal);
-        }
-        unset($oneDeepRelation);
-
-        if( $childPvPssTotalSum - $maxPvPSS >= $level1Option['OTHER_DEPART_PERF'] ) {
-            unset($maxPvPSS, $childPvPssTotalSum);
-            return $level1Option;
-        }else {
-            unset($maxPvPSS, $childPvPssTotalSum, $level1Option);
-            return false;
-        }
-    }
-
-    /**
-     * 是否达到其他级别
-     * @param $empLevel
-     * @param $childEmpLevelNumArr
-     * @param $userEmpLevelSort
-     * @return bool|mixed|\yii\db\ActiveRecord
-     */
-    public function isEmpLevelOther($empLevel, $childEmpLevelNumArr, $userEmpLevelSort) {
-        $resultLevel = [];
-        foreach ($empLevel as $level) {
-            if ($level['SORT'] < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL']) continue;
-            //不降级
-            if ($level['SORT'] <= $userEmpLevelSort) continue;
-
-            // 级别要求有几个区
-            $locationNum = $level['LOCATION_NUM'];
-            // 级别要求这几个区分别存在级别会员的数量
-            $minEmpNum = $level['MIN_EMPLOY_NUM'];
-            $minEmpLevel = $level['MIN_EMPLOY_LEVEL'];
-            if( !$minEmpLevel || !isset($empLevel[$minEmpLevel]) || $minEmpNum < 1 ) continue;
-            $minEmpLevelSort = $empLevel[$minEmpLevel]['SORT'];
-            $resultEmpLevelNumArr = array_filter($childEmpLevelNumArr, function ($item, $departUserId) use ($empLevel, $minEmpLevelSort, $minEmpNum) {
-
-                $tempEmpLevelNum = 0;
-                foreach ($item as $levelIndex => $levelNum) {
-                    if ($empLevel[$levelIndex]['SORT'] >= $minEmpLevelSort && $levelNum >= $minEmpNum) {
-                        $tempEmpLevelNum += 1;
-                    }
-                }
-                return $tempEmpLevelNum >= 1;
-            }, ARRAY_FILTER_USE_BOTH);
-            if (count($resultEmpLevelNumArr) >= $locationNum) {
-                if( $level['SORT'] == EmployLevel::EMP_LEVEL_SORT['SHX_ZJ_LEVEL'] ) {
-                    //首席总监还要满足一个条件、任意部门1个高级总监
-                    $gjZjLevelNumArr = array_filter($childEmpLevelNumArr, function ($item, $departUserId) use ($empLevel) {
-
-                        $tempEmpLevelNum = 0;
-                        foreach ($item as $levelIndex => $levelNum) {
-                            if ($empLevel[$levelIndex]['SORT'] >= EmployLevel::EMP_LEVEL_SORT['GJ_ZJ_LEVEL'] && $levelNum >= 1) {
-                                $tempEmpLevelNum += 1;
-                            }
-                        }
-                        return $tempEmpLevelNum >= 1;
-                    }, ARRAY_FILTER_USE_BOTH);
-                    if( count($gjZjLevelNumArr) >= 1 ) {
-                        $resultLevel = $level;
-                    }
-                    unset($gjZjLevelNumArr);
-                }else {
-                    $resultLevel = $level;
-                }
-            }
-            unset($level, $minEmpLevel, $minEmpLevelSort, $resultEmpLevelNumArr);
-        }
-        unset($empLevel, $childEmpLevelNumArr, $userEmpLevelSort);
-        return $resultLevel;
-    }
-
-    /**
-     * 是否可拿业绩(即注销、关停、停发状态)
-     * @param $userId
-     * @return bool
-     */
-    public function isHasPerf($userId) {
-        //@todo 所有人都有业绩
-        return true;
-    }
-
-    /**
-     * ==== 聘级计算结束 ====
-     */
-
-    /**
-     * 更新百分比并发送
-     * @param $percent
-     */
-    private function _updatePercent($percent) {
-        // 把数据写入数据库中
-        Period::updateAll(['PERF_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
-        \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'PERF_PERCENT']);
-    }
-
-}

+ 0 - 1
common/helpers/http/BackendToFrontendApi.php

@@ -97,5 +97,4 @@ class BackendToFrontendApi {
         }
         return true;
     }
-
 }

+ 0 - 155
common/helpers/http/LingYunGongApi.php

@@ -1,155 +0,0 @@
-<?php
-namespace common\helpers\http;
-
-use yii\base\BaseObject;
-use yii\httpclient\Client;
-
-class LingYunGongApi {
-
-    const CACHE_TOKEN_KEY = 'cashTokenKey_%s';
-
-    /**
-     * 请求方法
-     */
-    const HTTP_METHOD_POST = 'post';
-    const HTTP_METHOD_GET = 'get';
-
-    /**
-     * http client
-     * @var null
-     */
-    private static $_client = null;
-
-
-    /**
-     * 获取http client 对象
-     * @return null|Client
-     */
-    public static function client(){
-        if(is_null(self::$_client)){
-            self::$_client = new Client();
-        }
-        return self::$_client;
-    }
-
-    /**
-     * request
-     * @return \yii\httpclient\Request
-     */
-    public static function request(){
-        return self::client()->createRequest();
-    }
-
-    /**
-     * POST请求
-     * @param $url
-     * @param $data
-     * @param array $headers
-     * @return mixed
-     */
-    public static function post($url, $data, array $headers=[]){
-        $query = self::request()
-            ->setMethod(self::HTTP_METHOD_POST);
-        if( $headers ) {
-            $query->addHeaders($headers);
-        }
-
-        $query->setFormat(Client::FORMAT_JSON);
-        $query->setUrl($url)
-            ->setData($data);
-        unset($data);
-        return $query->send();
-    }
-
-    /**
-     * GET请求
-     * @param $url
-     * @param array $data
-     * @param array $headers
-     * @return \yii\httpclient\Response
-     */
-    public static function get($url, array $data = [], array $headers=[]){
-        $query = self::request()
-            ->setMethod(self::HTTP_METHOD_GET);
-        if( $headers ) {
-            $query->addHeaders($headers);
-        }
-        $query->setUrl($url);
-        if($data){
-            $query->setData($data);
-        }
-        unset($data);
-        return $query->send();
-    }
-
-    /**
-     * 获取token
-     * @return mixed|string
-     */
-    public static function getAuthToken() {
-        $authTokenClientId = \Yii::$app->params['http']['lingYunGongApi']['authToken']['clientId'];
-        $cacheKey = sprintf(self::CACHE_TOKEN_KEY, $authTokenClientId);
-        $cache = \Yii::$app->cache;
-        $token = $cache->get($cacheKey);
-        if( $token ) return $token;
-
-        $tokenData = self::_apiAuthToken();
-        if ( !$tokenData ) return '';
-
-        $token = $tokenData['access_token'] ?? '';
-        $expiresIn = $tokenData['expires_in'] ?? 0;
-//        $tokenType = $tokenData['token_type'];
-        $cacheTime  = $expiresIn - 60;
-        if( $cacheTime > 0 && $token ) {
-            \Yii::$app->cache->set($cacheKey, $token, $cacheTime);
-        }
-        return $token;
-    }
-
-
-    /**
-     * api接口获取token
-     * @return false
-     */
-    private static function _apiAuthToken() {
-        $host = \Yii::$app->params['http']['lingYunGongApi']['host'];
-        $authTokenPath = \Yii::$app->params['http']['lingYunGongApi']['authToken']['path'];
-        $authTokenClientId = \Yii::$app->params['http']['lingYunGongApi']['authToken']['clientId'];
-        $requestUrl = $host . $authTokenPath;
-
-        $data = [
-            'grant_type' => 'client_credential',
-            'client_secret' => 'secret!',
-            'client_id' => $authTokenClientId,
-        ];
-
-
-        $response = self::post($requestUrl, $data, ['content-type' => 'application/json']);
-        if($response->isOk){
-            return $response->data;
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * 判断是否上传了身份证信息
-     * @param string $idCard
-     */
-    public static function hasIdCardInfo(string $idCard) {
-        $token = self::getAuthToken();
-        if( !$token ) return false;
-
-        $host = \Yii::$app->params['http']['lingYunGongApi']['host'];
-        $authTokenPath = \Yii::$app->params['http']['lingYunGongApi']['hasIdCardInfoPath'];
-        $requestUrl = $host . sprintf($authTokenPath, $idCard);
-        $response = self::get($requestUrl, [], [
-            'Authorization' => sprintf('Bearer %s', $token)
-        ]);
-        if($response->isOk){
-            return $response->data;
-        } else {
-            return false;
-        }
-    }
-}

+ 0 - 152
common/helpers/http/RemoteUploadApi.php

@@ -1,152 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/5/17
- * Time: 下午2:44
- */
-
-namespace common\helpers\http;
-
-use common\models\Uploads;
-use yii\base\BaseObject;
-use yii\base\StaticInstanceTrait;
-use yii\httpclient\Client;
-
-class RemoteUploadApi extends BaseObject
-{
-    use StaticInstanceTrait;
-
-    /**
-     * 通讯密钥
-     */
-    public $authKey;
-
-    /**
-     * 上传地址
-     * @var
-     */
-    public $uploadUrl;
-
-    /**
-     * action地址
-     * @var
-     */
-    public $actionUrl;
-
-    public $filePath;
-
-    /**
-     * 上传的用户ID
-     * @var
-     */
-    public $id;
-
-    const CATEGORY_EXPORT = 'export';
-    const FORBIDDEN_NOTIFY_URL = 'forbidden';
-
-    /**
-     * 初始化
-     * @throws \yii\base\Exception
-     */
-    public function init()
-    {
-        parent::init();
-        $this->authKey = \Yii::$app->params['http']['remoteUploadApi']['authKey'];
-        $this->uploadUrl = \Yii::$app->params['http']['remoteUploadApi']['host'].'/upload';
-        $this->actionUrl = \Yii::$app->params['http']['remoteUploadApi']['host'].'/action';
-        $this->filePath = \Yii::$app->params['http']['remoteUploadApi']['host'].'/files/';
-        $this->id = \Yii::$app->security->generateRandomString(32);
-    }
-
-    /**
-     * @param $uid
-     * @param array $params
-     * @return array
-     */
-    public function generateToken($uid, $params = []){
-        if(!isset($params['date']) || !$params['date']){
-            $params['date'] = date('YmdH');
-        }
-        if(!isset($params['authKey']) || !$params['authKey']){
-            $params['authKey'] = \Yii::$app->params['http']['remoteUploadApi']['authKey'];
-        }
-        $hash = 'uid:'.$uid.'&secretkey:'.(string)$params['authKey'].'&datetime:'.(string)$params['date'];
-        if(!isset($params['notifyUrl']) || !$params['notifyUrl']){
-            $params['notifyUrl'] = \Yii::$app->params['http']['remoteUploadApi']['remoteUploadNotifyUrl'];
-        }elseif($params['notifyUrl'] == self::FORBIDDEN_NOTIFY_URL){
-            $params['notifyUrl'] = '';
-        }
-        $hash .= '&notifyurl:' . (string)$params['notifyUrl'];
-        $md5 = md5($hash);
-        return [
-            'date' => $params['date'],
-            'token' => $md5,
-            'notifyUrl' => $params['notifyUrl'],
-        ];
-    }
-
-    /**
-     * 上传
-     * @param $filePath
-     * @return bool|mixed
-     * @throws \yii\base\InvalidConfigException
-     * @throws \yii\httpclient\Exception
-     */
-    public function upload($filePath){
-        $token = $this->generateToken($this->id);
-        // 上传
-        $client = new Client();
-        $response = $client->createRequest()
-            ->setMethod('POST')
-            ->addHeaders([
-                'UPLOAD-SERVER-TOKEN' => $token['token'],
-                'UPLOAD-SERVER-USER' => $this->id,
-                'UPLOAD-SERVER-NOTIFY-URL'=>$token['notifyUrl'],
-                'UPLOAD-SERVER-DATE'=>$token['date'],
-            ])
-            ->setUrl($this->uploadUrl)
-            ->addFile('ATTACHMENT', $filePath)
-            ->send();
-        if($response->isOk && isset($response->data['url'])){
-            return $response->data;
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * 删除
-     * @param $filePath
-     * @return bool
-     * @throws \yii\base\InvalidConfigException
-     */
-    public function delete($filePath){
-        // 处理$filePath
-        if(strpos($filePath, $this->filePath) !== false){
-            $filePath = str_replace($this->filePath, '', $filePath);
-        }
-        $token = $this->generateToken($this->id);
-        $client = new Client();
-        $response = $client->createRequest()
-            ->setMethod('POST')
-            ->addHeaders([
-                'UPLOAD-SERVER-TOKEN' => $token['token'],
-                'UPLOAD-SERVER-USER' => $this->id,
-                'UPLOAD-SERVER-NOTIFY-URL'=>$token['notifyUrl'],
-                'UPLOAD-SERVER-DATE'=>$token['date'],
-            ])
-            ->setUrl($this->actionUrl)
-            ->setData([
-                'action' => 'delete',
-                'post_data' => $filePath,
-            ])
-            ->send();
-        if($response->isOk && isset($response->data['success']) && $response->data['success'] == 1){
-            return $response->data;
-        } else {
-            return false;
-        }
-    }
-
-}

+ 0 - 208
common/helpers/http/ShopApi.php

@@ -1,208 +0,0 @@
-<?php
-/**
- * 内部API助手类
- * Created by PhpStorm.
- * User: Ming
- * Date: 2018/3/13
- * Time: 10:21
- */
-
-namespace common\helpers\http;
-use Yii;
-use yii\httpclient\Client;
-class ShopApi {
-    /**
-     * 通讯密钥
-     */
-    const AUTH_KEY = '';
-    /**
-     * 允许的时间差(秒)
-     */
-    const TIME_DIFF = '';
-    /**
-     * 请求方法
-     */
-    const HTTP_METHOD_POST = 'post';
-    const HTTP_METHOD_GET = 'get';
-    /**
-     * 返回成功的标记
-     */
-    const RETURN_SUCCESS = 'success';
-    /**
-     * http client
-     * @var null
-     */
-    private static $_client = null;
-    /**
-     * http response
-     * @var null
-     */
-    protected static $response = null;
-    /**
-     * 错误代码
-     * @var int
-     */
-    private static $_errorCode = 0;
-    /**
-     * 错误信息
-     * @var null
-     */
-    private static $_errorMessage = null;
-    /**
-     * 获取密钥
-     * @return string
-     */
-    public static function getAuthKey(){
-        if(self::AUTH_KEY === ''){
-            return Yii::$app->params['http']['shopApi']['authKey'];
-        }
-
-        return self::AUTH_KEY;
-    }
-
-    /**
-     * 获取允许的时间差
-     * @return string
-     */
-    public static function getTimeDiff(){
-        if(self::TIME_DIFF === ''){
-            return Yii::$app->params['http']['shopApi']['timeDiff'];
-        }
-        return self::TIME_DIFF;
-    }
-    /**
-     * 生成签名
-     * @param array $params
-     * @return array
-     */
-    public static function paramsFormat(array $params){
-        if(!isset($params['timestamp'])){
-            $params['timestamp'] = time();
-        }
-        if(isset($params['signature'])){
-            unset($params['signature']);
-        }
-        ksort($params);
-        $string = '';
-        foreach($params as $key=>$value){
-            $string .= $key.'='.$value . '&';
-        }
-        $params['signature'] = sha1(trim($string,'&') . self::getAuthKey());
-        return $params;
-    }
-
-    /**
-     * 验证签名
-     * @param $signature
-     * @param array $params
-     * @return bool
-     */
-    public static function checkSignature($signature, array $params){
-        $params = self::paramsFormat($params);
-        if($params['signature'] !== $signature){
-            return false;
-        }
-        $timeDiff = (int)self::getTimeDiff();
-        if($timeDiff > 0 && (time() -> $params['timestamp']) > $timeDiff){
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * 获取http client 对象
-     * @return null|Client
-     */
-    public static function client(){
-        if(is_null(self::$_client)){
-            self::$_client = new Client();
-        }
-        return self::$_client;
-    }
-
-    /**
-     * request
-     * @return \yii\httpclient\Request
-     */
-    public static function request(){
-        return self::client()->createRequest();
-    }
-
-    /**
-     * POST请求
-     * @param $url
-     * @param $data
-     * @return mixed
-     */
-    public static function post($url, $data){
-        $data = self::paramsFormat($data);
-        static::$response = self::request()
-            ->setMethod(self::HTTP_METHOD_POST)
-            ->setUrl($url)
-            ->setData($data)
-            ->send();
-        unset($data);
-        return static::$response;
-    }
-
-    /**
-     * GET请求
-     * @param $url
-     * @param array $data
-     * @return \yii\httpclient\Response
-     */
-    public static function get($url, $data = []){
-        $data = self::paramsFormat($data);
-        $query = self::request()
-            ->setMethod(self::HTTP_METHOD_GET)
-            ->setUrl($url);
-        if($data){
-            $query->setData($data);
-        }
-        static::$response = $query->send();
-        unset($data, $query);
-        return static::$response;
-    }
-    /**
-     * 输出是否正确
-     * @return mixed
-     */
-    public static function responsed(){
-        return self::$response->isOk && (is_array(self::$response->data) && isset(self::$response->data[self::RETURN_SUCCESS]));
-    }
-
-    /**
-     * 获取报文
-     * @return null
-     */
-    public static function getResponse(){
-        return self::$response;
-    }
-    /**
-     * 获取报文数据
-     * @return mixed
-     */
-    public static function result(){
-        return self::$response->data;
-    }
-
-    /**
-     * 设置错误
-     * @param $message
-     * @param null $code
-     */
-    public static function setError($message, $code = null){
-        if(!is_null($code)){
-            self::$_errorCode = $code;
-        }
-        self::$_errorMessage = $message;
-    }
-
-    /**
-     * 获取错误
-     * @return array
-     */
-    public static function getError(){
-        return [self::$_errorMessage, self::$_errorCode];
-    }
-}