root пре 3 година
родитељ
комит
5ce26b0eef
42 измењених фајлова са 0 додато и 13118 уклоњено
  1. 0 582
      common/helpers/NetPoint.php
  2. 0 976
      common/helpers/user/Balance.php
  3. 0 201
      common/helpers/user/Cash.php
  4. 0 634
      common/helpers/user/Info.php
  5. 0 395
      common/helpers/user/Perf.php
  6. 0 486
      common/helpers/user/Reconsume.php
  7. 0 178
      common/helpers/user/Status.php
  8. 0 107
      common/models/ExcelAddUser.php
  9. 0 75
      common/models/ExcelChangeBalance.php
  10. 0 61
      common/models/ExcelImport.php
  11. 0 58
      common/models/ExcelOrderShop.php
  12. 0 90
      common/models/ExcelRegInfo.php
  13. 0 73
      common/models/ExcelWithdrawPaidFalse.php
  14. 0 356
      common/models/forms/ConfigForm.php
  15. 0 241
      common/models/forms/ExcelOrderDecForm.php
  16. 0 258
      common/models/forms/ExcelOrderShopForm.php
  17. 0 169
      common/models/forms/ExcelOrderStandardForm.php
  18. 0 480
      common/models/forms/OrderDeleteForm.php
  19. 0 1015
      common/models/forms/OrderForm.php
  20. 0 291
      common/models/forms/RechargeForm.php
  21. 0 359
      common/models/forms/SendCFAndLXForm.php
  22. 0 350
      common/models/forms/ShopGoodsForm.php
  23. 0 102
      common/models/forms/TransferBonusForm.php
  24. 0 375
      common/models/forms/TransferForm.php
  25. 0 227
      common/models/forms/UserBasicForm.php
  26. 0 377
      common/models/forms/UserBindForm.php
  27. 0 269
      common/models/forms/UserCloseForm.php
  28. 0 190
      common/models/forms/UserDecForm.php
  29. 0 91
      common/models/forms/UserGroupForm.php
  30. 0 625
      common/models/forms/UserStatusForm.php
  31. 0 246
      common/models/forms/UserSystemForm.php
  32. 0 201
      common/models/forms/UserTeamForm.php
  33. 0 429
      common/models/forms/UserTeamworkForm.php
  34. 0 99
      common/models/forms/UserTransferPropForm.php
  35. 0 706
      common/models/forms/WithdrawForm.php
  36. 0 116
      common/models/forms/WithdrawLevelForm.php
  37. 0 55
      console/controllers/BonusController.php
  38. 0 210
      console/controllers/ChangeNetController.php
  39. 0 1022
      console/controllers/ImportController.php
  40. 0 143
      console/controllers/ImportOrderController.php
  41. 0 67
      console/controllers/ReconsumeController.php
  42. 0 133
      console/controllers/ShopController.php

+ 0 - 582
common/helpers/NetPoint.php

@@ -1,582 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/4/28
- * Time: 下午6:38
- */
-
-namespace common\helpers;
-use common\components\ActiveRecord;
-use common\helpers\user\Info;
-use common\models\PerfMonth;
-use common\models\PerfPeriod;
-use common\models\Period;
-use common\models\DecOrder;
-use common\models\User;
-use common\models\UserInfo;
-use common\models\UserMove;
-use common\models\UserNetwork;
-use common\models\UserPerf;
-use common\models\UserRelation;
-use common\models\UserSystem;
-use yii\base\BaseObject;
-use yii\base\Exception;
-use yii\base\StaticInstanceTrait;
-use yii\db\Expression;
-use yii\helpers\Json;
-
-/**
- * Class NetPoint
- * 网络接点关系调整类
- * 1、点位A从点位B移动到点位C,首先寻找公共接点人,把非公共的点位全部删掉
- * 2、循环把自己和自己的所有下级相对这个公共点位的都修改深度+变化的深度,修改区域为点位A到点位C后相应的区位。
- * 3、循环查找会员移动到点位C后,所有的点位C及C的上级,并会员A及A的下级,都添加这些上级数据。
- * 4、修改user_info表,的接点人
- * @package common\helpers
- */
-class NetPoint extends BaseObject
-{
-    const NET_TYPE_NETWORK = 'network';
-    const NET_TYPE_RELATION = 'relation';
-
-    const REDIS_KEY_PREFIX_CHILD_USER = 'moveNetChildUser:NetType_%s:moveUserId_%s';
-
-    private $_limit = 100;
-    private $_errors = [];
-    private $_moveInfo;
-    public $moveId;
-    private $_moveUserId;
-    private $_moveUserInfo;
-    private $_toConUserId;
-    private $_toConUserInfo;
-    private $_fromConUserId;
-    private $_fromConUserInfo;
-    private $_fromLocation;
-    private $_location;
-    private $_commonParentUserId = null;
-    private $_commonDeepDiff;
-    //private $_commonNewParentLocation;
-    private $_tempCalcDeep = 0;
-    private $_isContinueFindParent = true; // 用于往上找父级,找到公共节点就不在找了
-
-    public static function factory($moveId) {
-        return new self([
-                'moveId' => $moveId
-            ]
-        );
-    }
-
-    public function init()
-    {
-        parent::init();
-    }
-
-    /**
-     * 加入错误错误
-     * @param $attr
-     * @param $error
-     */
-    public function addError($attr, $error){
-        $this->_errors[$attr][] = $error;
-    }
-
-    /**
-     * 获取错误信息
-     * @return array
-     */
-    public function getErrors(){
-        return $this->_errors;
-    }
-
-    /**
-     * 初始化移动
-     * @param $netType
-     * @param $moveUserId
-     * @param $toConUserId
-     * @param int $location
-     * @param int $fromLocation
-     * @throws \Exception
-     */
-    public function initMove($netType, $moveUserId, $toConUserId, $location=0, $fromLocation = 0){
-        $this->_moveInfo = UserMove::findOneAsArray(['ID'=>$this->moveId]);
-        $this->_moveUserId = $moveUserId;
-        $this->_moveUserInfo = Info::baseInfo($moveUserId);
-        if($netType == self::NET_TYPE_NETWORK){
-            $this->_fromConUserId = $this->_moveUserInfo['CON_UID'];
-        } else {
-            $this->_fromConUserId = $this->_moveUserInfo['REC_UID'];
-        }
-//        $this->_fromConUserInfo = UserInfo::findOneAsArray(['USER_ID'=>$this->_fromConUserId]);
-        $this->_toConUserId = $toConUserId;
-//        $this->_toConUserInfo = UserInfo::findOneAsArray(['USER_ID'=>$this->_toConUserId]);
-        $this->_location = $location;
-        $this->_fromLocation = $fromLocation;
-        $this->_errors = [];
-        $this->_clearChildUserFromRedis($netType);
-        $this->allChildUserToRedisList($netType);
-    }
-
-    /**
-     * 移动安置网络节点
-     * @param $moveUserId
-     * @param $toConUserId
-     * @param $location
-     * @param $fromLocation
-     * @return bool
-     * @throws \Exception
-     */
-    public function moveNetworkPoint($moveUserId, $toConUserId, $location, $fromLocation){
-        return $this->movePoint(self::NET_TYPE_NETWORK, $moveUserId, $toConUserId, $location, $fromLocation);
-    }
-
-    /**
-     * 移动开拓网络节点
-     * @param $moveUserId
-     * @param $toConUserId
-     * @return bool
-     * @throws \Exception
-     */
-    public function moveRelationPoint($moveUserId, $toConUserId){
-        return $this->movePoint(self::NET_TYPE_RELATION, $moveUserId, $toConUserId);
-    }
-
-    /**
-     * 移网
-     * @param $netType
-     * @param $moveUserId
-     * @param $toConUserId
-     * @param int $location
-     * @param int $fromLocation
-     * @return bool
-     * @throws \Exception
-     */
-    public function movePoint($netType, $moveUserId, $toConUserId, $location=0, $fromLocation = 0){
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $this->initMove($netType, $moveUserId, $toConUserId, $location, $fromLocation);
-            echo sprintf("时间:[%s],用户ID:[%s]移网,初始化成功".PHP_EOL, date('Y-m-d H:i:s', time()), $moveUserId);
-
-            //修改移动会员以及子会员的深度、父ID、以及网体标记等
-            $this->_moveParentAndChildren($netType);
-            // 把userInfo表的数据也改掉
-            if($netType == self::NET_TYPE_NETWORK){
-                $conNumField = 'CON_NUM';
-            } else {
-                $conNumField = 'REC_NUM';
-            }
-            // 原上级接点数量减少,新上级接点数量增加
-            UserInfo::updateAllCounters([$conNumField => -1], 'USER_ID=:USER_ID', [':USER_ID'=>$this->_fromConUserId]);
-            UserInfo::updateAllCounters([$conNumField =>1], 'USER_ID=:USER_ID', [':USER_ID'=>$this->_toConUserId]);
-            // 清除redis
-            if ($netType == self::NET_TYPE_NETWORK) {
-                \Yii::$app->redis->del(Cache::USER_NETWORK_PARENTS);
-            } else {
-                \Yii::$app->redis->del(Cache::USER_RELATION_PARENTS);
-            }
-
-            $this->_endHandle();
-            $transaction->commit();
-        } catch (\Exception $e){
-            echo $e->getMessage() . PHP_EOL;
-            $transaction->rollBack();
-            $this->_errorHandle();
-            $this->addError($netType, $e->getMessage());
-            $this->_clearChildUserFromRedis($netType);
-            return false;
-        }
-
-        $this->_clearChildUserFromRedis($netType);
-        return true;
-    }
-
-    /**
-     * 删除备份的表
-     */
-    public function dropBakTable(){
-        $oneMove = $this->_moveInfo;
-        $createTableName =  $oneMove['NET_TABLE_NAME'];
-        if(ActiveRecord::isExistsTable('{{%'.$createTableName.'}}', 'dbNetPoint')){
-            ActiveRecord::deleteTable($createTableName, 'dbNetPoint');
-        }
-    }
-
-    /**
-     * 把所有子会员数据存入缓存中
-     * @param $netType
-     * @return bool
-     */
-    public function allChildUserToRedisList($netType){
-        return $this->_getChildUserToRedis($this->_moveUserId, $netType);
-    }
-
-    private function _getChildUserToRedis($parentUid, $netType) {
-        if($netType == self::NET_TYPE_NETWORK){
-            $field = 'CON_UID';
-        } else {
-            $field = 'REC_UID';
-        }
-        $childList = UserInfo::find()->select(['USER_ID'])->where("{$field}=:PARENT_UID", ['PARENT_UID'=>$parentUid])->asArray()->all();
-        if( !$childList ) {
-            unset($childList, $field, $parentUid, $netType);
-            return true;
-        }
-        foreach ($childList as $child) {
-            // 会员ID加入缓存
-            $this->_addChildUserToRedis($netType, $child['USER_ID']);
-
-            $this->_getChildUserToRedis($child['USER_ID'], $netType);
-        }
-
-        unset($childList, $field, $parentUid, $netType, $child);
-        return true;
-    }
-
-    /**
-     * 循环删除子节点对应的非公共节点的数据
-     * @param $netType
-     * @param $parentUserId
-     * @param int $offset
-     */
-    public function _loopChildDelUnCommonParent($netType, $parentUserId, int $offset=0){
-        // 分页从缓存中获取子会员
-        $allData = $this->_getChildUserFromRedis($netType, $offset, $this->_limit);
-        if($allData){
-            foreach($allData as $childUserId){
-                $modelClass = self::getModelClass($netType);
-                $modelClass::deleteAll('PARENT_UID=:PARENT_UID AND USER_ID=:USER_ID', [':PARENT_UID'=>$parentUserId, ':USER_ID'=>$childUserId]);
-            }
-            unset($allData);
-            $this->_loopChildDelUnCommonParent($netType, $parentUserId, $offset + $this->_limit);
-        }
-    }
-
-
-    /**
-     * 把移动的会员及子会员加入到直接新上级的节点数据
-     * @param $netType
-     */
-    private function _moveParentAndChildren($netType){
-        $modelClass = self::getModelClass($netType);
-        // 获取一条新上级的网络数据
-        $fromData = $modelClass::find()->where('USER_ID=:USER_ID', [':USER_ID'=>$this->_moveUserId])->asArray()->one();
-        $toParentData = $modelClass::find()->where('USER_ID=:USER_ID', [':USER_ID'=>$this->_toConUserId])->asArray()->one();
-
-        if( $toParentData['PARENT_UIDS'] ) {
-            $updateParentUids = $toParentData['PARENT_UIDS'] . ',' . $this->_toConUserId;
-        }else {
-            $updateParentUids = $this->_toConUserId;
-        }
-
-        $updateData = [
-            'PARENT_UID' => $this->_toConUserId,
-            'PARENT_UIDS' => $updateParentUids,
-            'TOP_UID' => $toParentData['TOP_UID'],
-            'TOP_DEEP' => $toParentData['TOP_DEEP'] + 1,
-            'UPDATED_AT' => Date::nowTime(),
-        ];
-        if($netType == self::NET_TYPE_NETWORK){
-            $updateData['RELATIVE_LOCATION'] = $this->_location;
-            $updateData['LOCATION_TAG'] = $toParentData['LOCATION_TAG'] . $this->_location;
-        }
-        $modelClass::updateAll($updateData, 'USER_ID=:USER_ID', [
-            'USER_ID' => $this->_moveUserId
-        ]);
-        unset($modelClass, $toParentData, $updateParentUids);
-
-        if($netType == self::NET_TYPE_NETWORK){
-            $conField = 'CON_UID';
-        } else {
-            $conField = 'REC_UID';
-        }
-        UserInfo::updateAll([
-            $conField => $this->_toConUserId,
-            strtoupper($netType).'_DEEP' => $updateData['TOP_DEEP'],
-        ], 'USER_ID=:USER_ID', [':USER_ID'=>$this->_moveUserId]);
-
-        $this->_updatePercent(30);
-
-        // 把子会员也更新、准备公共子会员需要的信息
-        $commonParentData = [
-            'toConUserId' => $this->_toConUserId,
-            'topUserId' => $updateData['TOP_UID'],
-            'commonDiffDeep' => $updateData['TOP_DEEP'] - $fromData['TOP_DEEP'],
-            'oldParentUids' => $fromData['PARENT_UIDS'],
-            'newParentUids' => $updateData['PARENT_UIDS'],
-        ];
-        if($netType == self::NET_TYPE_NETWORK){
-            $commonParentData['oldParentLocationTag'] = $fromData['LOCATION_TAG'];
-            $commonParentData['newParentLocationTag'] = $updateData['LOCATION_TAG'];
-        }
-        unset($fromData, $updateData);
-
-        $this->_updateChildData($netType, $commonParentData);
-
-        $this->_changeNetPerfData($netType, $commonParentData);
-
-        unset($netType, $commonParentData);
-    }
-
-    /**
-     * 分页循环给子会员增加相较于上级的数据
-     * @param $netType
-     * @param $params
-     *       [
-     *       'toConUserId' => $this->_toConUserId,
-     *       'topUserId' => $updateData['TOP_UID'],
-     *       'commonDiffDeep' => $updateData['TOP_DEEP'] - $fromData['TOP_DEEP'],
-     *       'oldParentUids' => $fromData['PARENT_UIDS'],
-     *       'newParentUids' => $updateData['PARENT_UIDS'],
-     *       ]
-     * @param int $offset
-     */
-    private function _updateChildData($netType, $params, int $offset = 0){
-        // 分页获取要移动的会员的子会员
-        $allData = $this->_getChildUserFromRedis($netType, $offset, $this->_limit);
-        if($allData){
-            $modelClass = self::getModelClass($netType);
-            foreach($allData as $childUserId){
-                $childData = $modelClass::find()->where('USER_ID=:USER_ID', [':USER_ID'=>$childUserId])->asArray()->one();
-                //原PARENT_UIDS、新PARENT_UIDS
-                $childParentUids = substr($childData['PARENT_UIDS'], strlen($params['oldParentUids']));
-                $childUpdateData = [
-                    'PARENT_UIDS' => $params['newParentUids'] . $childParentUids,//不变
-                    'TOP_UID' => $params['topUserId'],//和父的保持一致
-                    'TOP_DEEP' => $childData['TOP_DEEP'] + $params['commonDiffDeep'],//所有子会员变化深度一致
-                    'UPDATED_AT' => Date::nowTime(),
-                ];
-                if($netType == self::NET_TYPE_NETWORK){
-                    //RELATIVE_LOCATION不变
-                    //找到moveUser的 原来 locationTag 的length
-                    $childLocationTag = substr($childData['LOCATION_TAG'], strlen($params['oldParentLocationTag']));
-                    $childUpdateData['LOCATION_TAG'] = $params['newParentLocationTag'] . $childLocationTag;
-                    unset($childLocationTag);
-                }
-
-                $modelClass::updateAll($childUpdateData, 'USER_ID=:USER_ID', [
-                    'USER_ID' => $childUserId
-                ]);
-                UserInfo::updateAll([
-                    strtoupper($netType).'_DEEP' => $childUpdateData['TOP_DEEP'],
-                ], 'USER_ID=:USER_ID', [':USER_ID'=>$childUserId]);
-
-                unset($childUserId, $childData, $childParentUids, $childUpdateData);
-            }
-
-            unset($allData, $modelClass);
-            return $this->_updateChildData($netType, $params, $offset + $this->_limit);
-        }
-
-        unset($allData);
-        return true;
-    }
-
-    /**
-     * 移网业绩数据处理
-     * @param $netType
-     * @param $commonData
-     * @return bool
-     */
-    private function _changeNetPerfData($netType, $commonData) {
-        //获取未结算的月份
-        $noSentPeriod = Period::find()->where('IS_SENT=0')->orderBy('PERIOD_NUM ASC')->asArray()->one();
-        if( !$noSentPeriod ) return false;
-
-        $thisYearMonth = $noSentPeriod['CALC_YEAR'].Tool::numFix($noSentPeriod['CALC_MONTH'], 2);
-//        $lastYearMonth = Date::lastMonth($noSentPeriod['CALC_YEAR'].'-'.$noSentPeriod['CALC_MONTH'], 'Ym');
-        $thisYearMonthPerf=[];
-        if( $noSentPeriod['IS_MONTH'] == 1 ) {
-            $thisYearMonthPerf =  PerfMonth::find()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$this->_moveUserId, 'CALC_MONTH'=>$thisYearMonth])->asArray()->one();
-        }
-        unset($noSentPeriod);
-        //查找移动点位这个人的上个月的累计业绩
-//        $lastYearMonthPerf = PerfMonth::find()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$this->_moveUserId, 'CALC_MONTH'=>$lastYearMonth])->asArray()->one();
-        //本月的已结算业绩
-        $thisPerfPeriodList = PerfPeriod::find()->select(['PV_PCS', 'PV_PSS', 'PERIOD_NUM'])->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$this->_moveUserId, 'CALC_MONTH'=>$thisYearMonth])->asArray()->all();
-
-        //总的pss_total
-        $userPerf = UserPerf::find()->where('USER_ID=:USER_ID', ['USER_ID'=>$this->_moveUserId])->asArray()->one();
-
-        $oldParentUids = $commonData['oldParentUids'] ? explode(',', $commonData['oldParentUids']) : [];
-        $newParentUids = $commonData['newParentUids'] ? explode(',', $commonData['newParentUids']) : [];
-        if( $netType === self::NET_TYPE_RELATION ) {
-            //修改上个月的累计业绩
-//            if( $lastYearMonthPerf ) {
-//                $lastYearMonthPssTotal = $lastYearMonthPerf['PV_PCS'] + $lastYearMonthPerf['PV_PSS_TOTAL'];
-//                $lastYearMonthPss = $lastYearMonthPerf['PV_PCS'] + $lastYearMonthPerf['PV_PSS'];
-//                foreach ($oldParentUids as $oldParentUid) {//减
-//                    PerfMonth::updateAllCounters(['PV_PSS'=>(-1)*$lastYearMonthPss, 'PV_PSS_TOTAL'=>(-1)*$lastYearMonthPssTotal], 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$oldParentUid, 'CALC_MONTH'=>$lastYearMonth]);
-//                    unset($oldParentUid);
-//                }
-//                foreach ($newParentUids as $newParentUid) {//加
-//                    PerfMonth::updateAllCounters(['PV_PSS'=>$lastYearMonthPss, 'PV_PSS_TOTAL'=>$lastYearMonthPssTotal], 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$newParentUid, 'CALC_MONTH'=>$lastYearMonth]);
-//                    unset($newParentUid);
-//                }
-//                unset($lastYearMonthPssTotal, $lastYearMonthPss);
-//            }
-//            unset($lastYearMonthPerf, $lastYearMonth);
-
-            //修改本月的累计业绩
-            if( $thisYearMonthPerf ) {
-                $thisYearMonthPssTotal = $thisYearMonthPerf['PV_PCS'] + $thisYearMonthPerf['PV_PSS_TOTAL'];
-                $thisYearMonthPss = $thisYearMonthPerf['PV_PCS'] + $thisYearMonthPerf['PV_PSS'];
-                foreach ($oldParentUids as $oldParentUid) {//减
-                    $parentThisYearMonthPerf =  PerfMonth::find()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$oldParentUid, 'CALC_MONTH'=>$thisYearMonth])->asArray()->one();
-                    if( $parentThisYearMonthPerf ) {
-                        if( $parentThisYearMonthPerf['PV_PSS_TOTAL'] < $thisYearMonthPssTotal ) {
-                            PerfMonth::updateAll(['PV_PSS'=>(-1)*$thisYearMonthPss, 'PV_PSS_TOTAL'=>0], 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$oldParentUid, 'CALC_MONTH'=>$thisYearMonth]);
-                        }else {
-                            PerfMonth::updateAllCounters(['PV_PSS'=>(-1)*$thisYearMonthPss, 'PV_PSS_TOTAL'=>(-1)*$thisYearMonthPssTotal], 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$oldParentUid, 'CALC_MONTH'=>$thisYearMonth]);
-
-                        }
-                    }
-                    unset($oldParentUid, $parentThisYearMonthPerf);
-                }
-                foreach ($newParentUids as $newParentUid) {//加
-                    PerfMonth::updateAllCounters(['PV_PSS'=>$thisYearMonthPss, 'PV_PSS_TOTAL'=>$thisYearMonthPssTotal], 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$newParentUid, 'CALC_MONTH'=>$thisYearMonth]);
-                    unset($newParentUid);
-                }
-                unset($thisYearMonthPssTotal, $thisYearMonthPss);
-            }
-            unset($thisYearMonthPerf);
-
-            //修改本月的已结算业绩
-            foreach ($thisPerfPeriodList as $periodPerf) {
-                $periodPss = $periodPerf['PV_PCS'] + $periodPerf['PV_PSS'];
-                if( $periodPss <= 0 ) continue;
-
-                foreach ($oldParentUids as $oldParentUid) {//减
-                    PerfPeriod::updateAllCounters(['PV_PSS'=>(-1)*$periodPss], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', ['USER_ID'=>$oldParentUid, 'PERIOD_NUM'=>$periodPerf['PERIOD_NUM']]);
-                    unset($oldParentUid);
-                }
-                foreach ($newParentUids as $newParentUid) {//加
-                    PerfPeriod::updateAllCounters(['PV_PSS'=>$periodPss], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', ['USER_ID'=>$newParentUid, 'PERIOD_NUM'=>$periodPerf['PERIOD_NUM']]);
-                    unset($newParentUid);
-                }
-
-                unset($periodPerf, $periodPss);
-            }
-            unset($thisPerfPeriodList, $thisYearMonth);
-
-            if( $userPerf ) {
-                $userPerfPss = $userPerf['PV_PCS_ZC'] + $userPerf['PV_PCS_FX'] + $userPerf['PV_PSS'];
-                $userPerfPssTotal = $userPerf['PV_PCS_ZC'] + $userPerf['PV_PCS_FX'] + $userPerf['PV_PSS_TOTAL'];
-                foreach ($oldParentUids as $oldParentUid) {//减
-                    $parentPerf = UserPerf::find()->where('USER_ID=:USER_ID', ['USER_ID'=>$oldParentUid])->asArray()->one();
-                    if( $parentPerf ) {
-                        if( $parentPerf['PV_PSS_TOTAL'] < $userPerfPssTotal ) {
-                            UserPerf::updateAll(['PV_PSS'=>0, 'PV_PSS_TOTAL'=>0], 'USER_ID=:USER_ID', ['USER_ID'=>$oldParentUid]);
-                        }else {
-                            UserPerf::updateAllCounters(['PV_PSS'=>(-1)*$userPerfPss, 'PV_PSS_TOTAL'=>(-1)*$userPerfPssTotal], 'USER_ID=:USER_ID', ['USER_ID'=>$oldParentUid]);
-                        }
-                    }
-                    unset($oldParentUid, $parentPerf);
-                }
-                foreach ($newParentUids as $newParentUid) {//加
-                    UserPerf::updateAllCounters(['PV_PSS'=>$userPerfPss, 'PV_PSS_TOTAL'=>$userPerfPssTotal], 'USER_ID=:USER_ID', ['USER_ID'=>$newParentUid]);
-                    unset($newParentUid);
-                }
-                unset($userPerfPss, $userPerfPssTotal);
-            }
-            unset($userPerf);
-
-        }
-
-        if( $netType === self::NET_TYPE_NETWORK ) {
-            //@todo 团队奖相关的,对碰往期对碰剩余业绩是否修改
-        }
-
-        unset($oldParentUids, $newParentUids);
-
-    }
-
-    /**
-     * 结束操作
-     * @throws Exception
-     */
-    private function _endHandle(){
-        // 把移网申请记录的正在移网状态修改
-        $oneMove = UserMove::findOne(['ID'=>$this->moveId]);
-        $oneMove->IS_MOVING = 0;
-        $oneMove->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
-        $oneMove->ENDED_AT = Date::nowTime();
-        if(!$oneMove->save()){
-            throw new Exception(Form::formatErrorsForApi($oneMove->getErrors()));
-        }
-        $this->_updatePercent(100);
-    }
-
-    /**
-     * 错误的时候,把移网状态改回原状
-     */
-    private function _errorHandle(){
-        // 把移网的审核状态回归
-        $oneMove = UserMove::findOne(['ID'=>$this->moveId]);
-        $oneMove->IS_MOVING = 0;
-        $oneMove->AUDIT_ADMIN_ID = null;
-        $oneMove->AUDITED_AT = 0;
-        $oneMove->AUDIT_STATUS = \Yii::$app->params['auditStatus']['false']['value'];
-        $oneMove->save();
-        // 删除创建的表
-        $this->dropBakTable();
-        $this->_updatePercent(0);
-    }
-
-    /**
-     * 更新百分比并发送
-     * @param $percent
-     */
-    private function _updatePercent($percent){
-        // 把数据写入数据库中
-        UserMove::updateAll(['MOVE_PERCENT'=>$percent], 'ID=:ID', [':ID'=>$this->moveId]);
-        \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'USER_MOVE' ,'ID' => $this->moveId, 'FIELD' => 'MOVE_PERCENT']);
-    }
-
-    /**
-     * 把子会员存入到缓存中
-     * @param $netType
-     * @param $userId
-     */
-    private function _addChildUserToRedis($netType, $userId){
-        $cacheKey = sprintf(self::REDIS_KEY_PREFIX_CHILD_USER, $netType, $this->_moveUserId);
-        \Yii::$app->redis->rpush($cacheKey, $userId);
-    }
-
-    /**
-     * 从缓存中获取子会员数据
-     * @param $netType
-     * @param $offset
-     * @param $limit
-     * @return mixed
-     */
-    private function _getChildUserFromRedis($netType, $offset, $limit){
-        $cacheKey = sprintf(self::REDIS_KEY_PREFIX_CHILD_USER, $netType, $this->_moveUserId);
-        return \Yii::$app->redis->lrange($cacheKey, $offset, ($offset + $limit - 1));
-    }
-
-    /**
-     * 清空子会员数据从缓存中
-     * @param $netType
-     * @return mixed
-     */
-    private function _clearChildUserFromRedis($netType){
-        $cacheKey = sprintf(self::REDIS_KEY_PREFIX_CHILD_USER, $netType, $this->_moveUserId);
-        return \Yii::$app->redis->del($cacheKey);
-    }
-
-    /**
-     * 获取model类
-     * @param $netType
-     * @return null|string
-     */
-    private static function getModelClass($netType){
-        if($netType == self::NET_TYPE_NETWORK){
-            return UserNetwork::class;
-        } elseif($netType == self::NET_TYPE_RELATION){
-            return UserRelation::class;
-        } else {
-            return null;
-        }
-    }
-
-}

+ 0 - 976
common/helpers/user/Balance.php

@@ -1,976 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/10/30
- * Time: 下午3:19
- */
-
-namespace common\helpers\user;
-
-use common\components\ActiveRecord;
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\helpers\Form;
-use common\libs\lock\RedisLock;
-use common\models\FlowBonus;
-use common\models\FlowCF;
-use common\models\FlowGaragePoints;
-use common\models\FlowLX;
-use common\models\FlowReconsumePoints;
-use common\models\FlowTourismPoints;
-use common\models\FlowVillaPoints;
-use common\models\InvoiceFlow;
-use common\models\Period;
-use common\models\DeclarationLevel;
-use common\models\DecRole;
-use common\models\FlowExchangePoints;
-use common\models\UserPeriodPoints;
-use common\models\UserWallet;
-use common\models\UserBonus;
-use common\models\UserInfo;
-use common\models\UserPeriodExchangePoints;
-use yii\base\Exception;
-use yii\db\Expression;
-
-class Balance {
-    const INCR_REDUCE = 0;      // 减少
-    const INCR_ADD = 1;         // 增加
-    const INCR_FREEZE = 2;      // 冻结
-    const INCR_UNFREEZE = 3;    // 解冻
-
-    const BONUS_BALANCE_LOCK_KEY = 'Bonus';
-    const RECONSUME_POINTS_BALANCE_LOCK_KEY = 'reconsumePoints';
-    const EXCHANGE_POINTS_BALANCE_LOCK_KEY = 'exchangePoints';
-    const CF_BALANCE_LOCK_KEY = 'CF';
-    const LX_BALANCE_LOCK_KEY = 'LX';
-    const INVOICE_BALANCE_LOCK_KEY = 'Invoice';
-    const TOURISM_POINTS_BALANCE_LOCK_KEY = 'tourismPoints';
-    const GARAGE_POINTS_BALANCE_LOCK_KEY = 'garagePoints';
-    const VILLA_POINTS_BALANCE_LOCK_KEY = 'villaPoints';
-
-    const BALANCE_TYPE = [
-        'exchange' => [
-            'id'    => 'exchange',
-            'title' => '兑换点数',
-            'attr'  => 'EXCHANGE_POINTS',
-            'pv'    => false,
-        ],
-        'tourism_points' => [
-            'id'    => 'tourism_points',
-            'title' => '旅游积分',
-            'attr'  => 'TOURISM_POINTS',
-            'pv'    => false,
-        ],
-        'garage_points' => [
-            'id'    => 'garage_points',
-            'title' => '车奖积分',
-            'attr'  => 'GARAGE_POINTS',
-            'pv'    => false,
-        ],
-        'villa_points' => [
-            'id'    => 'villa_points',
-            'title' => '房奖积分',
-            'attr'  => 'VILLA_POINTS',
-            'pv'    => false,
-        ],
-    ];
-
-    /**
-     * 发票流水
-     * @param $userId
-     * @param $amount
-     * @param $params
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function changeInvoice($userId, $amount, $params) {
-        if ($amount == 0) return true;
-        $period = Period::instance();
-        if (!isset($params['PERIOD_NUM'])) {
-            $periodNum = $period->getNowPeriodNum();
-        } else {
-            $periodNum = $params['PERIOD_NUM'];
-        }
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        // redis加锁(防止并发余额数值不准确出错)
-        $lockKey = self::INVOICE_BALANCE_LOCK_KEY . $userId;
-        if (RedisLock::instance()->lock($lockKey)) {
-            $userInfo = UserInfo::findOne(['USER_ID' => $userId]);
-            $totals = $userInfo->INVOICE_BALANCE + $amount;
-            $userInfo->INVOICE_BALANCE = $totals;
-            if (!$userInfo->save()) {
-                throw new \Exception(Form::formatErrorsForApi($userInfo->getErrors()));
-            }
-            //记录流水
-            $baseInfo = Info::baseInfoZh($userId);
-            $flowInsertData = [
-                'USER_ID' => $userId,
-                'REAL_NAME' => $baseInfo['REAL_NAME'],
-                'DEC_LV' => $baseInfo['DEC_LV'],
-                'EMP_LV' => $baseInfo['EMP_LV'],
-                'MOBILE' => $baseInfo['MOBILE'],
-                'REG_TYPE' => $userInfo['REG_TYPE'],
-                'REG_NAME' => $userInfo['REG_NAME'],
-                'CREDIT_CODE' => $userInfo['CREDIT_CODE'],
-                'SALE_NAME' => $params['SALE_NAME'] ?? null,
-                'TAXPAYER_NUMBER' => $params['TAXPAYER_NUMBER'] ?? null,
-                'INVOICE_SN' => $params['INVOICE_SN'] ?? null,
-                'INVOICE_ACCOUNT' => $params['INVOICE_ACCOUNT'] ?? null,
-                'TAX_ACCOUNT' => $params['TAX_ACCOUNT'] ?? null,
-                'OUTED_AT' => $params['OUTED_AT'] ?? 0,
-                'AMOUNT' => abs($amount),
-                'TOTAL' => $totals,
-                'WITHDRAW_SN' => $params['WITHDRAW_SN'] ?? null,
-                'IS_INCR' => $amount > 0 ? self::INCR_ADD : self::INCR_REDUCE,
-                'PERIOD_NUM' => $periodNum,
-                'CALC_MONTH' => $calcYearMonth,
-                'REMARK' => $params['REMARK'] ?? null,
-                'CREATE_ADMIN' => $params['CREATE_ADMIN'],
-                'CREATE_REMARK' => $params['CREATE_REMARK'] ?? null,
-                'CREATE_TIME' => $params['CREATE_TIME'],
-                'AUDIT_ADMIN' => $params['AUDIT_ADMIN'],
-                'AUDIT_REMARK' => $params['AUDIT_REMARK'] ?? null,
-                'AUDIT_TIME' => $params['AUDIT_TIME'],
-                'P_MONTH' => Date::ociToDate(),
-                'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
-            ];
-            InvoiceFlow::insertOne($flowInsertData);
-            unset($flowInsertData);
-            RedisLock::instance()->unlock($lockKey);
-        } else {
-            throw new Exception('流水产生错误');
-        }
-        return true;
-    }
-
-    /**
-     * 获取当前可用余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getAvailableBalance($userId) {
-        $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if ($oneData) {
-            return $oneData['BONUS'] - $oneData['BONUS_FREEZE'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 获取当前车房养老奖余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getBalanceCF($userId) {
-        $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if ($oneData) {
-            return $oneData['CF'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 获取当前复消积分余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getBalanceReconsumePoints($userId) {
-        $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if ($oneData) {
-            return $oneData['RECONSUME_POINTS'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 获取当前兑换积分余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getBalanceExchangePoints($userId) {
-        $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if ($oneData) {
-            return $oneData['EXCHANGE_POINTS'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 获取当前车房养老奖余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getBalanceLX($userId) {
-        $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if ($oneData) {
-            return $oneData['LX'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 获取当前旅游积分余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getBalanceTourism($userId) {
-        $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        return $oneData['TOURISM_POINTS'] ?? 0;
-    }
-
-    /**
-     * 获取当前车房余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getBalanceGarage($userId) {
-        $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        return $oneData['GARAGE_POINTS'] ?? 0;
-    }
-
-    /**
-     * 查询会员账户余额.
-     * @param $userId
-     * @param $payType
-     * @return int|mixed
-     */
-    public static function getAccountBalance($userId, $payType) {
-        $oneData = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        return !$oneData ? 0 : $oneData[Balance::BALANCE_TYPE[$payType]['attr']] ?? 0;
-    }
-
-    /**
-     * 改变会员的余额
-     * @param $userId
-     * @param $type
-     * @param $amount
-     * @param array $params
-     * @param bool $allowMinus
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function changeUserBonus($userId, $type, $amount, $params = [], $allowMinus = false) {
-        if (array_key_exists($type, UserBonus::TYPE)) {
-            $type = strtoupper($type);
-        }
-        if ($amount == 0) return true;
-        $period = Period::instance();
-        if (!isset($params['PERIOD_NUM'])) {
-            $periodNum = $period->getNowPeriodNum();
-        } else {
-            $periodNum = $params['PERIOD_NUM'];
-        }
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        // 汇率
-        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
-        // redis加锁(防止并发余额数值不准确出错)
-        switch ($type) {
-            case 'BONUS':
-                $lockKey = self::BONUS_BALANCE_LOCK_KEY . $userId;
-                break;
-            case 'RECONSUME_POINTS':
-                $lockKey = self::RECONSUME_POINTS_BALANCE_LOCK_KEY . $userId;
-                break;
-            case 'EXCHANGE_POINTS':
-                $lockKey = self::EXCHANGE_POINTS_BALANCE_LOCK_KEY . $userId;
-                break;
-            case 'CF':
-                $lockKey = self::CF_BALANCE_LOCK_KEY . $userId;
-                break;
-            case 'LX':
-                $lockKey = self::LX_BALANCE_LOCK_KEY . $userId;
-                break;
-            case 'TOURISM_POINTS':
-                $lockKey = self::TOURISM_POINTS_BALANCE_LOCK_KEY . $userId;
-                break;
-            case 'GARAGE_POINTS':
-                $lockKey = self::GARAGE_POINTS_BALANCE_LOCK_KEY . $userId;
-                break;
-            case 'VILLA_POINTS':
-                $lockKey = self::VILLA_POINTS_BALANCE_LOCK_KEY . $userId;
-                break;
-            default:
-                throw new Exception('流水类型错误');
-        }
-        if (RedisLock::instance()->lock($lockKey)) {
-            // 改变发奖
-            $paramData = [];
-            $oneUserBonusModel = UserBonus::findOne(['USER_ID' => $userId]);
-            // 是否奖金发放操作
-            $issueBonus = $params['BONUS_ISSUE'] ?? false;
-            if ($oneUserBonusModel) {
-                $paramData[$type] = new Expression($type.' + ' . ($issueBonus ? $amount * $exchangeRate : $amount));
-
-                $oneUserBonusModel->$type += ($issueBonus ? $amount * $exchangeRate : $amount);
-                if ($oneUserBonusModel->$type < 0) {
-                    RedisLock::instance()->unlock($lockKey);
-                    throw new Exception('金额不足');
-                }
-
-                if (isset($params['QY'])) {
-                    $paramData['QY_TOTAL'] = new Expression('QY_TOTAL + ' . ($issueBonus ? $params['QY'] * $exchangeRate : $params['QY']));
-                    //$oneUserBonusModel->QY_TOTAL += $params['QY'];
-                }
-                if (isset($params['FW'])) {
-                    $paramData['FW_TOTAL'] = new Expression('FW_TOTAL + ' . ($issueBonus ? $params['FW'] * $exchangeRate : $params['FW']));
-                }
-                if (isset($params['YC'])) {
-                    $paramData['YC_TOTAL'] = new Expression('YC_TOTAL + ' . ($issueBonus ? $params['YC'] * $exchangeRate : $params['YC']));
-                    //$oneUserBonusModel->YC_TOTAL += $params['YC'];
-                }
-                if (isset($params['VIP'])) {
-                    $paramData['VIP_TOTAL'] = new Expression('VIP_TOTAL + ' . ($issueBonus ? $params['VIP'] * $exchangeRate : $params['VIP']));
-                }
-                if (isset($params['BD'])) {
-                    $paramData['BD_TOTAL'] = new Expression('BD_TOTAL + ' . ($issueBonus ? $params['BD'] * $exchangeRate : $params['BD']));
-                    //$oneUserBonusModel->BD_TOTAL += $params['BD'];
-                }
-                if (isset($params['TG'])) {
-                    $paramData['TG_TOTAL'] = new Expression('TG_TOTAL + ' . ($issueBonus ? $params['TG'] * $exchangeRate : $params['TG']));
-                    //$oneUserBonusModel->TG_TOTAL += $params['TG'];
-                }
-                if (isset($params['YJ'])) {
-                    $paramData['YJ_TOTAL'] = new Expression('YJ_TOTAL + ' . ($issueBonus ? $params['YJ'] * $exchangeRate : $params['YJ']));
-                    //$oneUserBonusModel->YJ_TOTAL += $params['YJ'];
-                }
-                if (isset($params['GX'])) {
-                    $paramData['GX_TOTAL'] = new Expression('GX_TOTAL + ' . ($issueBonus ? $params['GX'] * $exchangeRate : $params['GX']));
-                    //$oneUserBonusModel->GX_TOTAL += $params['GX'];
-                }
-                if (isset($params['GL'])) {
-                    $paramData['GL_TOTAL'] = new Expression('GL_TOTAL + ' . ($issueBonus ? $params['GL'] * $exchangeRate : $params['GL']));
-                    //$oneUserBonusModel->GL_TOTAL += $params['GL'];
-                }
-                if (isset($params['BS'])) {
-                    $paramData['BS_TOTAL'] = new Expression('BS_TOTAL + ' . ($issueBonus ? $params['BS'] * $exchangeRate : $params['BS']));
-                }
-                if (isset($params['BS_MNT'])) {
-                    $paramData['BS_MNT_TOTAL'] = new Expression('BS_MNT_TOTAL + ' . ($issueBonus ? $params['BS_MNT'] * $exchangeRate : $params['BS_MNT']));
-                }
-                if (isset($params['BS_ABBR'])) {
-                    $paramData['BS_ABBR_TOTAL'] = new Expression('BS_ABBR_TOTAL + ' . ($issueBonus ? $params['BS_ABBR'] * $exchangeRate : $params['BS_ABBR']));
-                }
-                if (isset($params['TOURISM_POINTS'])) {
-                    $paramData['TOURISM_POINTS_TOTAL'] = new Expression('TOURISM_POINTS_TOTAL + ' . ($issueBonus ? $params['TOURISM_POINTS'] * $exchangeRate : $params['TOURISM_POINTS']));
-                }
-                if (isset($params['GARAGE_POINTS'])) {
-                    $paramData['GARAGE_POINTS_TOTAL'] = new Expression('GARAGE_POINTS_TOTAL + ' . ($issueBonus ? $params['GARAGE_POINTS'] * $exchangeRate : $params['GARAGE_POINTS']));
-                }
-                if (isset($params['VILLA_POINTS'])) {
-                    $paramData['VILLA_POINTS_TOTAL'] = new Expression('VILLA_POINTS_TOTAL + ' . ($issueBonus ? $params['VILLA_POINTS'] * $exchangeRate : $params['VILLA_POINTS']));
-                }
-                if (isset($params['RECONSUME_POINTS_TOTAL'])) {
-                    $paramData['RECONSUME_POINTS_TOTAL'] = new Expression('RECONSUME_POINTS_TOTAL + ' . ($issueBonus ? $params['RECONSUME_POINTS_TOTAL'] * $exchangeRate : $params['RECONSUME_POINTS_TOTAL']));
-                    //$oneUserBonusModel->RECONSUME_POINTS_TOTAL += $params['RECONSUME_POINTS_TOTAL'];
-                }
-                if (isset($params['EXCHANGE_POINTS_TOTAL'])) {
-                    $paramData['EXCHANGE_POINTS_TOTAL'] = new Expression('EXCHANGE_POINTS_TOTAL + ' . ($issueBonus ? $params['EXCHANGE_POINTS_TOTAL'] * $exchangeRate : $params['EXCHANGE_POINTS_TOTAL']));
-                    //$oneUserBonusModel->RECONSUME_POINTS_TOTAL += $params['RECONSUME_POINTS_TOTAL'];
-                }
-                if (isset($params['MANAGE_TAX'])) {
-                    $paramData['MANAGE_TAX'] = new Expression('MANAGE_TAX + ' . ($issueBonus ? $params['MANAGE_TAX'] * $exchangeRate : $params['MANAGE_TAX']));
-                    //$oneUserBonusModel->MANAGE_TAX += $params['MANAGE_TAX'];
-                }
-
-                if (isset($params['ORI_QY'])) {
-                    $paramData['ORI_QY_TOTAL'] = new Expression('ORI_QY_TOTAL + ' . ($issueBonus ? $params['ORI_QY'] * $exchangeRate : $params['ORI_QY']));
-                    //$oneUserBonusModel->ORI_QY_TOTAL += $params['ORI_QY'];
-                }
-//                if (isset($params['ORI_FW'])) {
-//                    $paramData['ORI_FW_TOTAL'] = new Expression('ORI_FW_TOTAL + '.$params['ORI_FW']);
-//                }
-                if (isset($params['ORI_YC'])) {
-                    $paramData['ORI_YC_TOTAL'] = new Expression('ORI_YC_TOTAL + ' . ($issueBonus ? $params['ORI_YC'] * $exchangeRate : $params['ORI_YC']));
-                    //$oneUserBonusModel->ORI_YC_TOTAL += $params['ORI_YC'];
-                }
-                if (isset($params['ORI_VIP'])) {
-                    $paramData['ORI_VIP_TOTAL'] = new Expression('ORI_VIP_TOTAL + ' . ($issueBonus ? $params['ORI_VIP'] * $exchangeRate : $params['ORI_VIP']));
-                }
-                if (isset($params['ORI_STANDARD'])) {
-                    $paramData['ORI_STANDARD_TOTAL'] = new Expression('ORI_STANDARD_TOTAL + ' . ($issueBonus ? $params['ORI_STANDARD'] * $exchangeRate : $params['ORI_STANDARD']));
-                }
-                if (isset($params['ORI_TG'])) {
-                    $paramData['ORI_TG_TOTAL'] = new Expression('ORI_TG_TOTAL + ' . ($issueBonus ? $params['ORI_TG'] * $exchangeRate : $params['ORI_TG']));
-                    //$oneUserBonusModel->ORI_TG_TOTAL += $params['ORI_TG'];
-                }
-                if (isset($params['ORI_YJ'])) {
-                    $paramData['ORI_YJ_TOTAL'] = new Expression('ORI_YJ_TOTAL + ' . ($issueBonus ? $params['ORI_YJ'] * $exchangeRate : $params['ORI_YJ']));
-                    //$oneUserBonusModel->ORI_YJ_TOTAL += $params['ORI_YJ'];
-                }
-                if (isset($params['ORI_GX'])) {
-                    $paramData['ORI_GX_TOTAL'] = new Expression('ORI_GX_TOTAL + ' . ($issueBonus ? $params['ORI_GX'] * $exchangeRate : $params['ORI_GX']));
-                    //$oneUserBonusModel->ORI_GX_TOTAL += $params['ORI_GX'];
-                }
-                if (isset($params['ORI_GL'])) {
-                    $paramData['ORI_GL_TOTAL'] = new Expression('ORI_GL_TOTAL + ' . ($issueBonus ? $params['ORI_GL'] * $exchangeRate : $params['ORI_GL']));
-                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
-                }
-                if (isset($params['ORI_BS'])) {
-                    $paramData['ORI_BS_TOTAL'] = new Expression('ORI_BS_TOTAL + ' . ($issueBonus ? $params['ORI_BS'] * $exchangeRate : $params['ORI_BS']));
-                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
-                }
-                if (isset($params['ORI_BS_MNT'])) {
-                    $paramData['BS_MNT_ORI_TOTAL'] = new Expression('BS_MNT_ORI_TOTAL + ' . ($issueBonus ? $params['ORI_BS_MNT'] * $exchangeRate : $params['ORI_BS_MNT']));
-                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
-                }
-                if (isset($params['ORI_BS_ABBR'])) {
-                    $paramData['BS_ABBR_ORI_TOTAL'] = new Expression('BS_ABBR_ORI_TOTAL + ' . ($issueBonus ? $params['ORI_BS_ABBR'] * $exchangeRate : $params['ORI_BS_ABBR']));
-                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
-                }
-
-                if (isset($params['BONUS_TOTAL'])) {
-                    $paramData['BONUS_TOTAL'] = new Expression('BONUS_TOTAL + ' . ($issueBonus ? $params['BONUS_TOTAL'] * $exchangeRate : $params['BONUS_TOTAL']));
-                    //$oneUserBonusModel->BONUS_TOTAL += $params['BONUS_TOTAL'];
-                }
-                UserBonus::updateAll($paramData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-
-            } else {
-                $paramData = [
-                    'USER_ID'=>$userId,
-                    $type=>$amount,
-                    'CREATED_AT'=>Date::nowTime()
-                ];
-                if (isset($params['QY'])) {
-//                    $paramData['QY_TOTAL'] = new Expression('QY_TOTAL + '.$params['QY']);
-                    $paramData['QY_TOTAL'] =  ($issueBonus ? $params['QY'] * $exchangeRate : $params['QY']);
-                }
-                if (isset($params['FW'])) {
-//                    $paramData['FW_TOTAL'] = new Expression('FW_TOTAL + '.$params['FW']);
-                    $paramData['FW_TOTAL'] = ($issueBonus ? $params['FW'] * $exchangeRate : $params['FW']);
-                }
-                if (isset($params['YC'])) {
-//                    $paramData['YC_TOTAL'] = new Expression('YC_TOTAL + '.$params['YC']);
-                    $paramData['YC_TOTAL'] = ($issueBonus ? $params['YC'] * $exchangeRate : $params['YC']);
-                }
-                if (isset($params['VIP'])) {
-//                    $paramData['VIP_TOTAL'] = new Expression('VIP_TOTAL + '.$params['VIP']);
-                    $paramData['VIP_TOTAL'] = ($issueBonus ? $params['VIP'] * $exchangeRate : $params['VIP']);
-                }
-
-                if (isset($params['BD'])) {
-//                    $paramData['BD_TOTAL'] = new Expression('BD_TOTAL + '.$params['BD']);
-                    $paramData['BD_TOTAL'] = ($issueBonus ? $params['BD'] * $exchangeRate : $params['BD']);
-                    //$oneUserBonusModel->BD_TOTAL += $params['BD'];
-                }
-                if (isset($params['TG'])) {
-//                    $paramData['TG_TOTAL'] = new Expression('TG_TOTAL + '.$params['TG']);
-                    $paramData['TG_TOTAL'] = ($issueBonus ? $params['TG'] * $exchangeRate : $params['TG']);
-                }
-                if (isset($params['YJ'])) {
-//                    $paramData['YJ_TOTAL'] = new Expression('YJ_TOTAL + '.$params['YJ']);
-                    $paramData['YJ_TOTAL'] = ($issueBonus ? $params['YJ'] * $exchangeRate : $params['YJ']);
-                }
-                if (isset($params['GX'])) {
-//                    $paramData['GX_TOTAL'] = new Expression('GX_TOTAL + '.$params['GX']);
-                    $paramData['GX_TOTAL'] = ($issueBonus ? $params['GX'] * $exchangeRate : $params['GX']);
-                }
-                if (isset($params['GL'])) {
-//                    $paramData['GL_TOTAL'] = new Expression('GL_TOTAL + '.$params['GL']);
-                    $paramData['GL_TOTAL'] = ($issueBonus ? $params['GL'] * $exchangeRate : $params['GL']);
-                }
-                if (isset($params['BS'])) {
-                    $paramData['BS_TOTAL'] = ($issueBonus ? $params['BS'] * $exchangeRate : $params['BS']);
-                    //$oneUserBonusModel->GL_TOTAL += $params['GL'];
-                }
-                if (isset($params['BS_MNT'])) {
-                    $paramData['BS_MNT_TOTAL'] = ($issueBonus ? $params['BS_MNT'] * $exchangeRate : $params['BS_MNT']);
-                }
-                if (isset($params['BS_ABBR'])) {
-                    $paramData['BS_ABBR_TOTAL'] = ($issueBonus ? $params['BS_ABBR'] * $exchangeRate : $params['BS_ABBR']);
-                }
-                if (isset($params['TOURISM_POINTS'])) {
-                    $paramData['TOURISM_POINTS_TOTAL'] = $params['TOURISM_POINTS'];
-                }
-                if (isset($params['GARAGE_POINTS'])) {
-                    $paramData['GARAGE_POINTS_TOTAL'] = $params['GARAGE_POINTS'];
-                }
-                if (isset($params['VILLA_POINTS'])) {
-                    $paramData['VILLA_POINTS_TOTAL'] = $params['VILLA_POINTS'];
-                }
-                if (isset($params['RECONSUME_POINTS_TOTAL'])) {
-//                    $paramData['RECONSUME_POINTS_TOTAL'] = new Expression('RECONSUME_POINTS_TOTAL + '.$params['RECONSUME_POINTS_TOTAL']);
-                    $paramData['RECONSUME_POINTS_TOTAL'] = ($issueBonus ? $params['RECONSUME_POINTS_TOTAL'] * $exchangeRate : $params['RECONSUME_POINTS_TOTAL']);
-                }
-                if (isset($params['MANAGE_TAX'])) {
-//                    $paramData['MANAGE_TAX'] = new Expression('MANAGE_TAX + '.$params['MANAGE_TAX']);
-                    $paramData['MANAGE_TAX'] = ($issueBonus ? $params['MANAGE_TAX'] * $exchangeRate : $params['MANAGE_TAX']);
-                }
-
-                if (isset($params['ORI_QY'])) {
-//                    $paramData['ORI_QY_TOTAL'] = new Expression('ORI_QY_TOTAL + '.$params['ORI_QY']);
-                    $paramData['ORI_QY_TOTAL'] = ($issueBonus ? $params['ORI_QY'] * $exchangeRate : $params['ORI_QY']);
-                }
-//                if (isset($params['ORI_FW'])) {
-////                    $paramData['ORI_FW_TOTAL'] = new Expression('ORI_FW_TOTAL + '.$params['ORI_FW']);
-//                    $paramData['ORI_FW_TOTAL'] = $params['ORI_FW'];
-//                }
-                if (isset($params['ORI_YC'])) {
-//                    $paramData['ORI_YC_TOTAL'] = new Expression('ORI_YC_TOTAL + '.$params['ORI_YC']);
-                    $paramData['ORI_YC_TOTAL'] = ($issueBonus ? $params['ORI_YC'] * $exchangeRate : $params['ORI_YC']);
-                }
-                if (isset($params['ORI_VIP'])) {
-//                    $paramData['ORI_VIP_TOTAL'] = new Expression('ORI_VIP_TOTAL + '.$params['ORI_VIP']);
-                    $paramData['ORI_VIP_TOTAL'] = ($issueBonus ? $params['ORI_VIP'] * $exchangeRate : $params['ORI_VIP']);
-                }
-                if (isset($params['ORI_STANDARD'])) {
-                    $paramData['ORI_STANDARD_TOTAL'] = ($issueBonus ? $params['ORI_STANDARD'] * $exchangeRate : $params['ORI_STANDARD']);
-                }
-                if (isset($params['ORI_BD'])) {
-//                    $paramData['ORI_BD_TOTAL'] = new Expression('ORI_BD_TOTAL + '.$params['ORI_BD']);
-                    $paramData['ORI_BD_TOTAL'] = ($issueBonus ? $params['ORI_BD'] * $exchangeRate : $params['ORI_BD']);
-                }
-                if (isset($params['ORI_TG'])) {
-//                    $paramData['ORI_TG_TOTAL'] = new Expression('ORI_TG_TOTAL + '.$params['ORI_TG']);
-                    $paramData['ORI_TG_TOTAL'] = ($issueBonus ? $params['ORI_TG'] * $exchangeRate : $params['ORI_TG']);
-                }
-                if (isset($params['ORI_YJ'])) {
-//                    $paramData['ORI_YJ_TOTAL'] = new Expression('ORI_YJ_TOTAL + '.$params['ORI_YJ']);
-                    $paramData['ORI_YJ_TOTAL'] = ($issueBonus ? $params['ORI_YJ'] * $exchangeRate : $params['ORI_YJ']);
-                }
-                if (isset($params['ORI_GX'])) {
-//                    $paramData['ORI_GX_TOTAL'] = new Expression('ORI_GX_TOTAL + '.$params['ORI_GX']);
-                    $paramData['ORI_GX_TOTAL'] = ($issueBonus ? $params['ORI_GX'] * $exchangeRate : $params['ORI_GX']);
-                }
-                if (isset($params['ORI_GL'])) {
-//                    $paramData['ORI_GL_TOTAL'] = new Expression('ORI_GL_TOTAL + '.$params['ORI_GL']);
-                    $paramData['ORI_GL_TOTAL'] = ($issueBonus ? $params['ORI_GL'] * $exchangeRate : $params['ORI_GL']);
-                }
-                if (isset($params['ORI_BS'])) {
-                    $paramData['ORI_BS_TOTAL'] = ($issueBonus ? $params['ORI_BS'] * $exchangeRate : $params['ORI_BS']);
-                    //$oneUserBonusModel->ORI_GL_TOTAL += $params['ORI_GL'];
-                }
-                if (isset($params['ORI_BS_MNT'])) {
-                    $paramData['BS_MNT_ORI_TOTAL'] = ($issueBonus ? $params['ORI_BS_MNT'] * $exchangeRate : $params['ORI_BS_MNT']);
-                }
-                if (isset($params['ORI_BS_ABBR'])) {
-                    $paramData['BS_ABBR_ORI_TOTAL'] = ($issueBonus ? $params['ORI_BS_ABBR'] * $exchangeRate : $params['ORI_BS_ABBR']);
-                }
-
-                if (isset($params['BONUS_TOTAL'])) {
-//                    $paramData['BONUS_TOTAL'] = new Expression('BONUS_TOTAL + '.$params['BONUS_TOTAL']);
-                    $paramData['BONUS_TOTAL'] = ($issueBonus ? $params['BONUS_TOTAL'] * $exchangeRate : $params['BONUS_TOTAL']);
-                }
-                UserBonus::insertOne($paramData);
-            }
-
-            unset($oneUserBonusModel,$paramData);
-            // 获取发放完成的奖金信息
-            $oneUserBonus = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-            $userInfo = Info::getLastInfo($userId);
-            // 记录流水
-            $flowInsertData = [
-                'USER_ID' => $userId,
-                'LAST_DEC_LV' => $userInfo['DEC_LV'],
-                'LAST_EMP_LV' => $userInfo['EMP_LV'],
-                'LAST_STATUS' => $userInfo['STATUS'],
-                'CALC_ID' => $params['CALC_ID'] ?? null,
-                'AMOUNT' => ($issueBonus ? $amount * $exchangeRate : $amount),
-                'AMOUNT_STANDARD' => (!$issueBonus ? $amount / $exchangeRate : $amount),
-                'EXCHANGE_RATE' => $exchangeRate,
-                'TOTAL' => $oneUserBonus[$type],
-                'IS_INCR' => $amount > 0 ? FlowBonus::INCR_ADD : FlowBonus::INCR_REDUCE,
-                'REMARK' => $params['REMARK'] ?? null,
-                'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
-                'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
-                'CALC_MONTH' => $calcYearMonth,
-                'P_MONTH' => Date::ociToDate(),
-                'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
-                'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
-                'DEAL_TYPE_ID' => $params['DEAL_TYPE_ID'] ?? '',
-                'DEAL_TYPE_IS_PRESET' => $params['DEAL_TYPE_IS_PRESET'] ?? 1,
-                'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
-                'SORT' => $params['SORT'] ?? 0,
-            ];
-
-            if (strtolower($type) == 'reconsume_points' || strtolower($type) == 'cf' || strtolower($type) == 'lx' 
-                || strtolower($type) == 'exchange_points'
-            ) {
-                unset($flowInsertData['CALC_ID']);
-                unset($flowInsertData['TRANSFER_SN']);
-                unset($flowInsertData['SORT']);
-            }
-            if (strtolower($type) == 'bonus') {
-                FlowBonus::insertOne($flowInsertData);
-//            } elseif (strtolower($type) == 'reconsume_points') {
-//                //记录和扣除期数的积分
-//                if( $amount > 0 ) {
-//                    self::addPeriodReconsumePoints($userId, $periodNum, $amount);
-//                }else {
-//                    self::deductPeriodReconsumePoints($userId, abs($amount));
-//                }
-//                FlowReconsumePoints::insertOne($flowInsertData);
-            } elseif (strtolower($type) == 'exchange_points') {
-                //记录和扣除期数的积分
-                if( $amount > 0 ) {
-                    self::addPeriodExchangePoints($userId, $periodNum, (!$issueBonus ? $amount / $exchangeRate : $amount));
-                }else {
-                    self::deductPeriodExchangePoints($userId, abs($amount));
-                }
-                FlowExchangePoints::insertOne($flowInsertData);
-            } elseif (strtolower($type) == 'cf') {
-                FlowCF::insertOne($flowInsertData);
-            } elseif (strtolower($type) == 'lx') {
-                FlowLX::insertOne($flowInsertData);
-            } elseif (strtolower($type) == 'tourism_points') {
-                $flowInsertData['LAST_CROWN_LV'] = $userInfo['LAST_CROWN_LV'];
-                FlowTourismPoints::insertOne($flowInsertData);
-            } elseif (strtolower($type) == 'garage_points') {
-                $flowInsertData['LAST_CROWN_LV'] = $userInfo['LAST_CROWN_LV'];
-                FlowGaragePoints::insertOne($flowInsertData);
-            } elseif (strtolower($type) == 'villa_points') {
-                $flowInsertData['LAST_CROWN_LV'] = $userInfo['LAST_CROWN_LV'];
-                FlowVillaPoints::insertOne($flowInsertData);
-            }
-
-            unset($flowInsertData, $userInfo, $oneUserBonus);
-            RedisLock::instance()->unlock($lockKey);
-        } else {
-            throw new Exception('流水产生错误');
-        }
-        return true;
-    }
-
-    /**
-     * 添加对应期数的复消积分
-     * @param $userId
-     * @param $periodNum
-     * @param $amount
-     * @throws \yii\db\Exception
-     * @return boolean
-     */
-    public static function addPeriodReconsumePoints($userId, $periodNum, $amount) {
-        if($amount <= 0) return false;
-        $exists = UserPeriodPoints::find()->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
-            'USER_ID' => $userId,
-            'PERIOD_NUM' => $periodNum,
-        ])->asArray()->exists();
-        if( $exists ) {
-            UserPeriodPoints::updateAllCounters([
-                'RECONSUME_POINTS' => $amount,
-                'REMAINDER_POINTS' => $amount,
-            ], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
-                'USER_ID' => $userId,
-                'PERIOD_NUM' => $periodNum,
-            ]);
-        }else {
-            UserPeriodPoints::insertOne([
-                'USER_ID' => $userId,
-                'PERIOD_NUM' => $periodNum,
-                'RECONSUME_POINTS' => $amount,
-                'REMAINDER_POINTS' => $amount,
-                'EXPIRED' => 0,
-                'CREATED_AT' => Date::nowTime()
-            ]);
-        }
-
-        return true;
-    }
-
-    /**
-     * 添加对应期数的兑换积分
-     * @param $userId
-     * @param $periodNum
-     * @param $amount
-     * @throws \yii\db\Exception
-     * @return boolean
-     */
-    public static function addPeriodExchangePoints($userId, $periodNum, $amount) {
-        if($amount <= 0) return false;
-        $exists = UserPeriodExchangePoints::find()->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
-            'USER_ID' => $userId,
-            'PERIOD_NUM' => $periodNum,
-        ])->asArray()->exists();
-        if( $exists ) {
-            UserPeriodExchangePoints::updateAllCounters([
-                'EXCHANGE_POINTS' => $amount,
-                'REMAINDER_POINTS' => $amount,
-            ], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
-                'USER_ID' => $userId,
-                'PERIOD_NUM' => $periodNum,
-            ]);
-        }else {
-            UserPeriodExchangePoints::insertOne([
-                'USER_ID' => $userId,
-                'PERIOD_NUM' => $periodNum,
-                'EXCHANGE_POINTS' => $amount,
-                'REMAINDER_POINTS' => $amount,
-                'EXPIRED' => 0,
-                'CREATED_AT' => Date::nowTime()
-            ]);
-        }
-
-        return true;
-    }
-
-
-    /**
-     * 减少
-     * @param $userId
-     * @param $amount
-     * @return bool
-     */
-    public static function deductPeriodReconsumePoints($userId, $amount) {
-        if( $amount <= 0 ) return false;
-        $avalidList = UserPeriodPoints::find()->where('USER_ID=:USER_ID AND EXPIRED=:EXPIRED AND REMAINDER_POINTS>0', [
-            'USER_ID' => $userId,
-            'EXPIRED'=>0
-        ])->orderBy('PERIOD_NUM ASC')->asArray()->all();
-        if( !$avalidList ) return false;
-
-        foreach ($avalidList as $everyData) {
-            if( $amount <= 0 ) break;
-
-            $remainderPoints = floatval($everyData['REMAINDER_POINTS']);
-            if( $amount >= $remainderPoints ) {
-                UserPeriodPoints::updateAllCounters([
-                    'REMAINDER_POINTS' => (-1) * $remainderPoints
-                ], 'ID=:ID', ['ID'=>$everyData['ID']]);
-
-                $amount -= $remainderPoints;
-            }else {
-                UserPeriodPoints::updateAllCounters([
-                    'REMAINDER_POINTS' => (-1) * $amount
-                ], 'ID=:ID', ['ID'=>$everyData['ID']]);
-
-                $amount = 0;
-            }
-
-            unset($everyData, $remainderPoints);
-        }
-        if( $amount > 0 ) return false;
-
-        return true;
-    }
-
-    /**
-     * 减少
-     * @param $userId
-     * @param $amount
-     * @return bool
-     */
-    public static function deductPeriodExchangePoints($userId, $amount) {
-        if( $amount <= 0 ) return false;
-        $avalidList = UserPeriodExchangePoints::find()->where('USER_ID=:USER_ID AND EXPIRED=:EXPIRED AND REMAINDER_POINTS>0', [
-            'USER_ID' => $userId,
-            'EXPIRED'=>0
-        ])->orderBy('PERIOD_NUM ASC')->asArray()->all();
-        if( !$avalidList ) return false;
-
-        foreach ($avalidList as $everyData) {
-            if( $amount <= 0 ) break;
-
-            $remainderPoints = floatval($everyData['REMAINDER_POINTS']);
-            if( $amount >= $remainderPoints ) {
-                UserPeriodExchangePoints::updateAllCounters([
-                    'REMAINDER_POINTS' => (-1) * $remainderPoints
-                ], 'ID=:ID', ['ID'=>$everyData['ID']]);
-
-                $amount -= $remainderPoints;
-            }else {
-                UserPeriodExchangePoints::updateAllCounters([
-                    'REMAINDER_POINTS' => (-1) * $amount
-                ], 'ID=:ID', ['ID'=>$everyData['ID']]);
-
-                $amount = 0;
-            }
-
-            unset($everyData, $remainderPoints);
-        }
-        if( $amount > 0 ) return false;
-
-        return true;
-    }
-
-    /**
-     * 冻结用户余额
-     * @param $userId
-     * @param $amount
-     * @param null $remark
-     * @param null $time
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function freezeUserBonus($userId, $amount, $remark = null, $time = null) {
-        return self::changeFreezeUserBonus($userId, $amount, ['REMARK' => $remark, 'TIME' => $time]);
-    }
-
-    /**
-     * 解冻用户余额
-     * @param $userId
-     * @param $amount
-     * @param null $remark
-     * @param null $time
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function unfreezeUserBonus($userId, $amount, $remark = null, $time = null) {
-        return self::changeFreezeUserBonus($userId, -$amount, ['REMARK' => $remark, 'TIME' => $time]);
-    }
-
-    /**
-     * @param $userId
-     * @param $amount
-     * @param $params
-     * [
-     *      'REMARK' => '备注',
-     *      'PERIOD_NUM' => 100,
-     * ]
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function changeFreezeUserBonus($userId, $amount, $params) {
-        if ($amount == 0) return true;
-        $period = Period::instance();
-        if (!isset($params['PERIOD_NUM'])) {
-            $periodNum = $period->getNowPeriodNum();
-        } else {
-            $periodNum = $params['PERIOD_NUM'];
-        }
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        // 改变冻结
-        $oneUserBonusModel = UserBonus::findOne(['USER_ID' => $userId]);
-        if ($oneUserBonusModel) {
-            $oneUserBonusModel->BONUS_FREEZE = $oneUserBonusModel->BONUS_FREEZE + $amount;
-        } else {
-            $oneUserBonusModel = new UserBonus();
-            $oneUserBonusModel->USER_ID = $userId;
-            $oneUserBonusModel->BONUS_FREEZE = $amount;
-        }
-        if (!$oneUserBonusModel->save()) {
-            throw new Exception(Form::formatErrorsForApi($oneUserBonusModel->getErrors()));
-        }
-        unset($oneUserBonusModel);
-        // 流水
-        // 获取发放完成的奖金信息
-        $oneUserBonus = UserBonus::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        // 记录流水
-        $flowInsertData = [
-            'USER_ID' => $userId,
-            'AMOUNT' => abs($amount),
-            'TOTAL' => $oneUserBonus['BONUS'],
-            'IS_INCR' => $amount > 0 ? FlowBonus::INCR_FREEZE : FlowBonus::INCR_UNFREEZE,
-            'REMARK' => $params['REMARK'] ?? null,
-            'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
-            'CALC_MONTH' => $calcYearMonth,
-            'P_MONTH' => Date::ociToDate(),
-            'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
-        ];
-
-        FlowBonus::insertOne($flowInsertData);
-        unset($flowInsertData);
-        return true;
-    }
-
-    /**
-     * 清空会员奖金有流水
-     * @param $userId
-     * @param array $params
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function clearAllBonus($userId, $params = []) {
-        // 先查找会员的全部余额
-        $userBonus = UserBonus::findOne(['USER_ID' => $userId]);
-        // 如果没有会员余额数据,新建余额数据
-        if (!$userBonus) {
-            UserBonus::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
-        } else {
-            $period = Period::instance();
-            foreach (\Yii::$app->params['bonusWalletType'] as $type) {
-                $field = strtoupper($type['name']);
-                if ($userBonus[$field]<=0) continue;
-                $userInfo = Info::getLastInfo($userId);
-                $flowInsertData = [
-                    'USER_ID' => $userId,
-                    'LAST_DEC_LV' => $userInfo['DEC_LV'],
-                    'LAST_EMP_LV' => $userInfo['EMP_LV'],
-                    'LAST_STATUS' => $userInfo['STATUS'],
-                    'CALC_ID' => $params['CALC_ID'] ?? null,
-                    'AMOUNT' => -$userBonus[$field],
-                    'TOTAL' => 0,
-                    'IS_INCR' => FlowBonus::INCR_REDUCE,
-                    'REMARK' => $params['REMARK'] ?? null,
-                    'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
-                    'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $period->getNowPeriodNum(),
-                    'CALC_MONTH' => $period->getNowYearMonth(),
-                    'P_MONTH' => Date::ociToDate(),
-                    'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
-                    'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
-                    'DEAL_TYPE_ID' => $params['DEAL_TYPE_ID'] ?? '',
-                    'DEAL_TYPE_IS_PRESET' => $params['DEAL_TYPE_IS_PRESET'] ?? 1,
-                    'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
-                    'SORT' => $params['SORT'] ?? 0,
-                ];
-
-                // 流水
-                if (strtolower($field) == 'bonus') FlowBonus::insertOne($flowInsertData);
-                elseif (strtolower($field) == 'cf') {
-                    unset($flowInsertData['CALC_ID']);
-                    unset($flowInsertData['SORT']);
-                    unset($flowInsertData['TRANSFER_SN']);
-                    FlowCF::insertOne($flowInsertData);
-                } elseif (strtolower($field) == 'lx') {
-                    unset($flowInsertData['CALC_ID']);
-                    unset($flowInsertData['SORT']);
-                    unset($flowInsertData['TRANSFER_SN']);
-                    FlowLX::insertOne($flowInsertData);
-                }
-            }
-            // 清空
-            $userBonus->BONUS = 0;
-            $userBonus->CF = 0;
-            $userBonus->LX = 0;
-            if (!$userBonus->save()) {
-                throw new Exception(Form::formatErrorsForApi($userBonus->getErrors()));
-            }
-        }
-        FlowBonus::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-        FlowCF::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-        FlowLX::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-    }
-
-    /**
-     * 是否存在奖金余额
-     * @param $userId
-     * @return bool
-     */
-    public static function hasBonus($userId) {
-        $userBonus = UserBonus::findOne(['USER_ID' => $userId]);
-        if (!$userBonus) {
-            return false;
-        }
-        foreach (\Yii::$app->params['bonusWalletType'] as $type) {
-            $field = strtoupper($type['name']);
-            if (isset($userBonus[$field]) && $userBonus[$field] > 0) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * 获取金额用于日志
-     * @param $userId
-     * @return array
-     */
-    public static function getLogData($userId){
-        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
-        $cash = !empty($userWallet) ? $userWallet['CASH'] : '';
-        $userName = Info::getUserNameByUserId($userId);
-        $data = [];
-        $data[$userId]['label'] = $userName.'余额';
-        $data[$userId]['value'] = '奖金'.self::getAvailableBalance($userId).',现金'.$cash;
-        return $data;
-    }
-}

+ 0 - 201
common/helpers/user/Cash.php

@@ -1,201 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/10/30
- * Time: 下午3:19
- */
-
-namespace common\helpers\user;
-
-use common\helpers\Date;
-use common\helpers\Form;
-use common\libs\lock\RedisLock;
-use common\models\FlowWallet;
-use common\models\Period;
-use common\models\UserWallet;
-use yii\base\Exception;
-use yii\db\Expression;
-
-class Cash {
-    const INCR_REDUCE = 0;      // 减少
-    const INCR_ADD = 1;         // 增加
-    const INCR_FREEZE = 2;      // 冻结
-    const INCR_UNFREEZE = 3;    // 解冻
-
-    const CASH_BALANCE_LOCK_KEY = 'Cash';
-
-    /**
-     * 获取当前可用余额
-     * @param $userId
-     * @return int|mixed
-     */
-    public static function getAvailableBalance($userId) {
-        $oneData = UserWallet::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if ($oneData) {
-            return $oneData['CASH'];
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * 改变会员的现金余额
-     * @param $userId
-     * @param $type
-     * @param $amount
-     * @param array $params
-     * @param bool $allowMinus
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function changeUserCash($userId, $type='CASH', $amount, $params = [], $allowMinus = false) {
-        if ($amount == 0) return true;
-        $period = Period::instance();
-        if (!isset($params['PERIOD_NUM'])) {
-            $periodNum = $period->getNowPeriodNum();
-        } else {
-            $periodNum = $params['PERIOD_NUM'];
-        }
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        // redis加锁(防止并发余额数值不准确出错)
-        switch ($type) {
-            case 'CASH':
-                $lockKey = self::CASH_BALANCE_LOCK_KEY . $userId;
-                break;
-            default:
-                throw new Exception('流水类型错误');
-        }
-        if (RedisLock::instance()->lock($lockKey)) {
-            // 改变发奖
-            $paramData = [];
-            $oneUserBonusModel = UserWallet::findOne(['USER_ID' => $userId]);
-            if ($oneUserBonusModel) {
-                $paramData[$type] = new Expression($type.' + '.$amount);
-
-                $oneUserBonusModel->$type += $amount;
-                if ($oneUserBonusModel->$type < 0) {
-                    RedisLock::instance()->unlock($lockKey);
-                    throw new Exception('金额不足');
-                }
-                UserWallet::updateAll($paramData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-
-            } else {
-                $paramData = [
-                    'USER_ID'=>$userId,
-                    $type=>$amount,
-                    'UPDATED_AT'=>Date::nowTime()
-                ];
-                UserWallet::insertOne($paramData);
-
-//                $oneUserBonusModel = new UserWallet();
-//                $oneUserBonusModel->USER_ID = $userId;
-//                $oneUserBonusModel->$type = $amount;
-//                $oneUserBonusModel->UPDATED_AT = Date::nowTime();
-//                if (!$oneUserBonusModel->save()) {
-//                    throw new \yii\db\Exception(Form::formatErrorsForApi($oneUserBonusModel->getErrors()));
-//                }
-            }
-
-            unset($oneUserBonusModel,$paramData);
-            // 获取发放完成的奖金信息
-            $oneUserBonus = UserWallet::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-            // 记录流水
-            $flowInsertData = [
-                'USER_ID' => $userId,
-                'CALC_ID' => $params['CALC_ID'] ?? null,
-                'AMOUNT' => $amount,
-                'TOTAL' => $oneUserBonus[$type],
-                'IS_INCR' => $amount > 0 ? FlowWallet::INCR_ADD : FlowWallet::INCR_REDUCE,
-                'REMARK' => $params['REMARK'] ?? null,
-                'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $periodNum,
-                'CALC_MONTH' => $calcYearMonth,
-                'P_MONTH' => Date::ociToDate(),
-                'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
-                'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
-                'SORT' => $params['SORT'] ?? 0,
-                'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
-            ];
-            if (strtolower($type) == 'cash') FlowWallet::insertOne($flowInsertData);
-            unset($flowInsertData);
-            RedisLock::instance()->unlock($lockKey);
-        } else {
-            throw new Exception('流水产生错误');
-        }
-        return true;
-    }
-
-    /**
-     * 清空会员现金所有流水
-     * @param $userId
-     * @param array $params
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function clearAllCash($userId, $params = []) {
-        // 先查找会员的全部余额
-        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
-        // 如果没有会员余额数据,新建余额数据
-        if (!$userWallet) {
-            UserWallet::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
-        } else {
-            $period = Period::instance();
-            $field = 'CASH';
-            if ($userWallet[$field]<=0) return;
-            $flowInsertData = [
-                'USER_ID' => $userId,
-                'CALC_ID' => $params['CALC_ID'] ?? null,
-                'AMOUNT' => -$userWallet[$field],
-                'TOTAL' => 0,
-                'IS_INCR' => FlowWallet::INCR_REDUCE,
-                'REMARK' => $params['REMARK'] ?? null,
-                'PERIOD_NUM' => $params['PERIOD_NUM'] ?? $period->getNowPeriodNum(),
-                'CALC_MONTH' => $period->getNowYearMonth(),
-                'P_MONTH' => Date::ociToDate(),
-                'CREATED_AT' => $params['TIME'] ?? Date::nowTime(),
-                'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
-                'SORT' => $params['SORT'] ?? 0,
-                'TRANSFER_SN' => $params['TRANSFER_SN'] ?? '',
-            ];
-            // 流水
-            if (strtolower($field) == 'cash') FlowWallet::insertOne($flowInsertData);
-
-            // 清空
-            $userWallet->CASH = 0;
-            if (!$userWallet->save()) {
-                throw new Exception(Form::formatErrorsForApi($userWallet->getErrors()));
-            }
-        }
-        FlowWallet::updateAll(['DELETED' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-    }
-
-    /**
-     * 是否存在现金余额
-     * @param $userId
-     * @return bool
-     */
-    public static function hasCash($userId) {
-        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
-        if (!$userWallet) {
-            return false;
-        }
-        if (isset($userWallet['CASH']) && $userWallet['CASH'] > 0) {
-            return true;
-        }
-    }
-
-    /**
-     * 获取金额用于日志
-     * @param $userId
-     * @return array
-     */
-    public static function getLogData($userId){
-        $userWallet = UserWallet::findOne(['USER_ID' => $userId]);
-        $userName = Info::getUserNameByUserId($userId);
-        $data = [];
-        $data[$userId]['label'] = $userName.'余额';
-        $data[$userId]['value'] = '奖金'.self::getAvailableBalance($userId).',现金'.$userWallet['CASH'];
-        return $data;
-    }
-}

+ 0 - 634
common/helpers/user/Info.php

@@ -1,634 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/11/2
- * Time: 上午9:16
- */
-
-namespace common\helpers\user;
-
-
-use common\components\ActiveQuery;
-use common\components\ActiveRecord;
-use common\helpers\Cache;
-use common\helpers\Tool;
-use common\models\Config;
-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\OpenBank;
-use common\models\Region;
-use common\models\User;
-use common\models\UserBonus;
-use common\models\UserInfo;
-use common\models\UserNetwork;
-use common\models\UserRelation;
-use common\models\UserSystem;
-use common\models\UserWallet;
-use yii\base\Exception;
-
-class Info {
-
-    /**
-     * 获取用户ID
-     * @param $userName
-     * @return mixed
-     */
-    public static function getUserIdByUserName($userName) {
-        $user = UserInfo::findOneAsArray('USER_NAME=:USER_NAME AND DELETED=0', [':USER_NAME' => $userName], 'USER_ID');
-        return $user ? $user['USER_ID'] : null;
-    }
-
-    /**
-     * 获取会员名通过ID
-     * @param $userId
-     * @return mixed|null
-     */
-    public static function getUserNameByUserId($userId) {
-        $user = UserInfo::findOneAsArray('USER_ID=:USER_ID AND DELETED=0', [':USER_ID' => $userId], 'USER_NAME');
-        return $user ? $user['USER_NAME'] : null;
-    }
-
-    /**
-     * 获取用户EMAIL
-     * @param $userName
-     * @return mixed
-     */
-    public static function getEmailByUserId($userId) {
-        $user = UserInfo::findOneAsArray('USER_ID=:USER_ID AND DELETED=0', [':USER_ID' => $userId], 'USER_NAME');
-        return $user ? $user['EMAIL'] : null;
-    }
-
-    /**
-     * 获取会员姓名通过ID
-     * @param $userId
-     * @return null
-     */
-    public static function getUserRealNameByUserId($userId) {
-        $user = User::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'REAL_NAME');
-        return $user ? $user['REAL_NAME'] : null;
-    }
-
-    /**
-     * 获取会员邮箱通过ID
-     * @param $userId
-     * @return null
-     */
-    public static function getUserEmailByUserId($userId) {
-        $user = User::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'EMAIL');
-        return $user ? $user['EMAIL'] : null;
-    }
-
-    /**
-     * 获取手机号通过ID
-     * @param $userId
-     * @return null
-     */
-    public static function getUserMobileByUserId($userId) {
-        $user = User::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'MOBILE');
-        return $user ? $user['MOBILE'] : null;
-    }
-
-    /**
-     * 通过用户ID获取用户的编号和名称
-     * @param $userId
-     * @return array|null
-     */
-    public static function getBaseUserById($userId) {
-        return User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID,USER_NAME,REAL_NAME');
-    }
-
-    /**
-     * 通过用户ID获取用户的编号和名称
-     * @param $username
-     * @return array|null
-     */
-    public static function getBaseUserByUserName($username) {
-        return User::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $username]);
-    }
-
-    /**
-     * 当前期数的会员信息
-     * @param $userId
-     * @return array|\yii\db\ActiveRecord|null
-     * @throws Exception
-     */
-    public static function baseInfoNowPeriod($userId) {
-        $data = User::find()->where('ID=:ID', [':ID' => $userId])->asArray()->one();
-        if (!$data) throw new Exception('Member does not exist'.$userId);//会员不存在
-        $infoData = UserInfo::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->select('ZC_PV,CON_UID,REC_UID,CON_NUM,REC_NUM,NETWORK_DEEP,RELATION_DEEP,SYSTEM_ID,REG_TYPE,REG_NAME,CREDIT_CODE,PREMISES,LEGAL_PERSON,CLOSE_LOGIN,IS_BIND_MAIN,HIGHEST_EMP_LV,HIGHEST_EMP_LV_PERIOD,SHOULD_REG_TYPE,IS_SYSTEM_LEADER,ALLOW_TRANSFER,TRANSFER_PROP,IS_GROUP_LEADER,GROUP_LEADER_AT,SHOW_EMP_LV')->asArray()->one();
-        if ($infoData) {
-            $data = array_merge($data, $infoData);
-        }
-        if (!$data['DEC_LV']) $data['DEC_LV'] = DeclarationLevel::getDefaultLevelId();
-        if (!$data['LAST_DEC_LV']) $data['LAST_DEC_LV'] = DeclarationLevel::getDefaultLevelId();
-        if (!$data['EMP_LV']) $data['EMP_LV'] = EmployLevel::getDefaultLevelId();
-        return $data;
-    }
-
-    /**
-     * 获取会员信息,通过用户编号
-     * @param $userId
-     * @return array|\yii\db\ActiveRecord|null
-     * @throws Exception
-     */
-    public static function baseInfoByUserName($userName) {
-        $data = User::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $userName])->asArray()->one();
-        if (!$data) throw new Exception('Member does not exist:'.$userName);//会员不存在
-        $userId  = $data['ID'];
-        $infoData = UserInfo::find()
-        ->where('USER_ID=:USER_ID', [':USER_ID' => $userId])
-        ->select('ZC_PV,CON_UID,REC_UID,CON_NUM,REC_NUM,NETWORK_DEEP,RELATION_DEEP,SYSTEM_ID,REG_TYPE,REG_NAME,
-        CREDIT_CODE,PREMISES,LEGAL_PERSON,CLOSE_LOGIN,IS_BIND_MAIN,HIGHEST_EMP_LV,HIGHEST_EMP_LV_PERIOD,
-        SHOULD_REG_TYPE,IS_SYSTEM_LEADER,ALLOW_TRANSFER,TRANSFER_PROP,IS_GROUP_LEADER,GROUP_LEADER_AT,SHOW_EMP_LV')
-        ->asArray()
-        ->one();
-        if ($infoData) {
-            $data = array_merge($data, $infoData);
-        }
-        if (!$data['DEC_LV']) $data['DEC_LV'] = DeclarationLevel::getDefaultLevelId();
-        if (!$data['LAST_DEC_LV']) $data['LAST_DEC_LV'] = DeclarationLevel::getDefaultLevelId();
-        if (!$data['EMP_LV']) $data['EMP_LV'] = EmployLevel::getDefaultLevelId();
-        return $data;
-    }
-
-    public static function baseInfoZhByUserName($userName) {
-        $baseInfo = self::baseInfoByUserName($userName);
-        // 状态处理
-        $baseInfo['STATUS_NAME'] = \Yii::$app->params['userStatus'][$baseInfo['STATUS']]['label'];
-        //登录状态
-        $baseInfo['LOGIN_STATUS_NAME'] = $baseInfo['ALLOW_LOGIN'] == 0 ? '禁止登录' : '允许登录';
-        // 子公司
-        $baseInfo['SUB_COM_NAME'] = '';
-        $baseInfo['PROVINCE_NAME'] = $baseInfo['PROVINCE'] ? Region::getCnName($baseInfo['PROVINCE']) : '';
-        $baseInfo['CITY_NAME'] = $baseInfo['CITY'] ? Region::getCnName($baseInfo['CITY']) : '';
-        $baseInfo['COUNTY_NAME'] = $baseInfo['COUNTY'] ? Region::getCnName($baseInfo['COUNTY']) : '';
-        $baseInfo['BANK_PROVINCE_NAME'] = $baseInfo['BANK_PROVINCE'] ? Region::getCnName($baseInfo['BANK_PROVINCE']) : '';
-        $baseInfo['BANK_CITY_NAME'] = $baseInfo['BANK_CITY'] ? Region::getCnName($baseInfo['BANK_CITY']) : '';
-        $baseInfo['BANK_COUNTY_NAME'] = $baseInfo['BANK_COUNTY'] ? Region::getCnName($baseInfo['BANK_COUNTY']) : '';
-        $baseInfo['OPEN_BANK_NAME'] = $baseInfo['OPEN_BANK'] ? OpenBank::getCnName($baseInfo['OPEN_BANK']) : '';
-        // 获取会员体系
-        $baseInfo['SYSTEM_NAME'] = '';
-        // 获取会员级别名称
-        $baseInfo['DEC_LV_NAME'] = Cache::getDecLevelConfig()[$baseInfo['DEC_LV']]['LEVEL_NAME'];
-        $baseInfo['LAST_DEC_LV_NAME'] = Cache::getDecLevelConfig()[$baseInfo['LAST_DEC_LV']]['LEVEL_NAME'];
-        $baseInfo['EMP_LV_NAME'] = Cache::getEmpLevelConfig()[$baseInfo['EMP_LV']]['LEVEL_NAME'];
-        $baseInfo['HIGHEST_EMP_LV_NAME'] = '';
-        // 获取会员报单级别
-        $baseInfo['DEC_ROLE_NAME'] = '无';
-        //民族
-        $baseInfo['NATION_NAME'] = \Yii::$app->params['nation'][$baseInfo['NATION']]['name']??'';
-        return $baseInfo;
-    }
-
-    /**
-     * 基本信息
-     * @param $userId
-     * @param $periodNum
-     * @return array|\yii\db\ActiveRecord|null
-     * @throws Exception
-     */
-    public static function baseInfo($userId, $periodNum = null) {
-        if($periodNum == null){
-            return self::baseInfoNowPeriod($userId);
-        } else {
-            // 获取当前期数
-            $tableName = '{{%USER_ALL_'.$periodNum.'}}';
-            if(ActiveRecord::isExistsTable($tableName, 'dbNetPoint')){
-                if($data = \Yii::$app->dbNetPoint->createCommand("SELECT * FROM $tableName WHERE ID=:ID")->bindValues([':ID'=>$userId])->queryOne()) {
-                    if (!$data['DEC_LV']) $data['DEC_LV'] = DeclarationLevel::getDefaultLevelId();
-                    if (!$data['LAST_DEC_LV']) $data['LAST_DEC_LV'] = DeclarationLevel::getDefaultLevelId();
-                    if (!$data['EMP_LV']) $data['EMP_LV'] = EmployLevel::getDefaultLevelId();
-                    if (!$data['HIGHEST_EMP_LV']) $data['HIGHEST_EMP_LV'] = EmployLevel::getDefaultLevelId();
-                    return $data;
-                }else{
-                    return self::baseInfoNowPeriod($userId);
-                }
-            } else {
-                return self::baseInfoNowPeriod($userId);
-            }
-        }
-    }
-
-    /**
-     * 基本信息含中文地区和中文子公司
-     * @param $userId
-     * @param $periodNum
-     * @return array|\yii\db\ActiveRecord|null
-     * @throws Exception
-     */
-    public static function baseInfoZh($userId, $periodNum = null) {
-        $baseInfo = self::baseInfo($userId, $periodNum);
-        // 状态处理
-        $baseInfo['STATUS_NAME'] = \Yii::$app->params['userStatus'][$baseInfo['STATUS']]['label'];
-        //登录状态
-        $baseInfo['LOGIN_STATUS_NAME'] = $baseInfo['ALLOW_LOGIN'] == 0 ? '禁止登录' : '允许登录';
-        // 子公司
-        $baseInfo['SUB_COM_NAME'] = '';
-        $baseInfo['PROVINCE_NAME'] = $baseInfo['PROVINCE'] ? Region::getCnName($baseInfo['PROVINCE']) : '';
-        $baseInfo['CITY_NAME'] = $baseInfo['CITY'] ? Region::getCnName($baseInfo['CITY']) : '';
-        $baseInfo['COUNTY_NAME'] = $baseInfo['COUNTY'] ? Region::getCnName($baseInfo['COUNTY']) : '';
-        $baseInfo['BANK_PROVINCE_NAME'] = $baseInfo['BANK_PROVINCE'] ? Region::getCnName($baseInfo['BANK_PROVINCE']) : '';
-        $baseInfo['BANK_CITY_NAME'] = $baseInfo['BANK_CITY'] ? Region::getCnName($baseInfo['BANK_CITY']) : '';
-        $baseInfo['BANK_COUNTY_NAME'] = $baseInfo['BANK_COUNTY'] ? Region::getCnName($baseInfo['BANK_COUNTY']) : '';
-        $baseInfo['OPEN_BANK_NAME'] = $baseInfo['OPEN_BANK'] ? OpenBank::getCnName($baseInfo['OPEN_BANK']) : '';
-        // 获取会员体系
-        $baseInfo['SYSTEM_NAME'] = '';
-        // 获取会员级别名称
-        $baseInfo['DEC_LV_NAME'] = Cache::getDecLevelConfig()[$baseInfo['DEC_LV']]['LEVEL_NAME'];
-        $baseInfo['LAST_DEC_LV_NAME'] = Cache::getDecLevelConfig()[$baseInfo['LAST_DEC_LV']]['LEVEL_NAME'];
-        $baseInfo['EMP_LV_NAME'] = Cache::getEmpLevelConfig()[$baseInfo['EMP_LV']]['LEVEL_NAME'];
-        $baseInfo['HIGHEST_EMP_LV_NAME'] = '';
-        // 获取会员报单级别
-        $baseInfo['DEC_ROLE_NAME'] = '无';
-        //民族
-        $baseInfo['NATION_NAME'] = \Yii::$app->params['nation'][$baseInfo['NATION']]['name']??'';
-        return $baseInfo;
-    }
-
-    /**
-     * 基本信息及余额
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     */
-    public static function baseInfoWithBalance($userId, $periodNum = null) {
-        $baseInfo = self::baseInfoZh($userId, $periodNum);
-
-        if ($baseInfo) {
-            $userBonus = self::BalanceInfo($userId);
-        }
-        return array_merge($baseInfo, $userBonus);
-    }
-
-    /**
-     * 获取余额信息
-     * @param $userId
-     * @return array|int[]|null
-     */
-    public static function BalanceInfo($userId) {
-        $userBonus = [
-            'BONUS' => 0,
-            'BONUS_FREEZE' => 0,
-            'CF' => 0,
-            'LX' => 0,
-            'QY_TOTAL' => 0,
-            'YC_TOTAL' => 0,
-            'FX_TOTAL' => 0,
-            'LS_TOTAL' => 0,
-            'CF_TOTAL' => 0,
-            'LX_TOTAL' => 0,
-            'FL_TOTAL' => 0,
-            'BT_TOTAL' => 0,
-            'FW_TOTAL' => 0,
-            'CASH' => 0,
-        ];
-
-        if ($userBonusResult = UserBonus::findOneAsArray(['USER_ID' => $userId])) {
-            $userBonus = $userBonusResult;
-        }
-        if ($userCashResult = UserWallet::findOneAsArray(['USER_ID' => $userId])) {
-            $userBonus['CASH'] = $userCashResult['CASH'];
-        }
-
-        return $userBonus;
-    }
-
-    /**
-     * 基本信息带着网络和节点信息
-     * @param $userId
-     * @param $periodNum
-     * @return array|null|\yii\db\ActiveRecord
-     */
-    public static function baseInfoWithNet($userId, $periodNum = null) {
-        $baseInfo = self::baseInfoZh($userId, $periodNum);
-        $baseInfo['CON_USER_NAME'] = '';
-        $baseInfo['CON_REAL_NAME'] = '';
-        $baseInfo['LOCATION'] = '';
-        $baseInfo['REC_USER_NAME'] = '';
-        $baseInfo['REC_REAL_NAME'] = '';
-        $baseInfo['DEC_USER_NAME'] = '';
-        $baseInfo['DEC_REAL_NAME'] = '';
-        $baseInfo['DEC_DEC_LV'] = '';
-        $baseInfo['DEC_DEC_LV_NAME'] = '';
-        if ($baseInfo) {
-            if (isset($baseInfo['CON_UID']) && $baseInfo['CON_UID']) {
-                // 安置网上级
-                //$netParentUserInfo = UserNetwork::getFirstParentUserInfo($userId);
-                $netParentBaseInfo = self::baseInfo($baseInfo['CON_UID']);
-                $networkParent = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId]);
-                //$baseInfo['CON_UID'] = $baseInfo['CON_UID'];
-                $baseInfo['CON_USER_NAME'] = $netParentBaseInfo['USER_NAME'];
-                $baseInfo['CON_REAL_NAME'] = $netParentBaseInfo['REAL_NAME'];
-                $baseInfo['LOCATION'] = $networkParent['RELATIVE_LOCATION'];
-            }
-            if (isset($baseInfo['REC_UID']) && $baseInfo['REC_UID']) {
-                // 推荐网上级
-                //$relationParentUserInfo = UserRelation::getFirstParentUserInfo($userId);
-                $relationParentBaseInfo = self::baseInfo($baseInfo['REC_UID']);
-                //$baseInfo['REC_UID'] = $relationParentUserInfo['USER_ID'];
-                $baseInfo['REC_USER_NAME'] = $relationParentBaseInfo['USER_NAME'];
-                $baseInfo['REC_REAL_NAME'] = $relationParentBaseInfo['REAL_NAME'];
-            }
-            if (isset($baseInfo['DEC_ID']) && $baseInfo['DEC_ID']) {
-                $decBaseInfo = self::baseInfoZh($baseInfo['DEC_ID']);
-                $baseInfo['DEC_USER_NAME'] = $decBaseInfo['USER_NAME'];
-                $baseInfo['DEC_REAL_NAME'] = $decBaseInfo['REAL_NAME'];
-                $baseInfo['DEC_DEC_LV'] = $decBaseInfo['DEC_LV'];
-                $baseInfo['DEC_DEC_LV_NAME'] = $decBaseInfo['DEC_LV_NAME'];
-                $baseInfo['DEC_DEC_ROLE_NAME'] = $decBaseInfo['DEC_ROLE_NAME'];
-                $baseInfo['DEC_DEC_ROLE_ID'] = $decBaseInfo['DEC_ROLE_ID'];
-            }
-        }
-
-        return $baseInfo;
-    }
-
-    /**
-     * 基本信息含网络和余额
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     */
-    public static function baseInfoWithNetAndBalance($userId, $periodNum = null) {
-        return array_merge(self::baseInfoWithNet($userId), self::BalanceInfo($userId));
-    }
-
-    /**
-     * 通过用户名获取用户信息从INFO表
-     * @param $userName
-     * @return array|null|\yii\db\ActiveRecord
-     */
-    public static function getUserByUserNameFromUserInfoTable($userName) {
-        return UserInfo::findOneAsArray(['USER_NAME' => $userName]);
-    }
-
-    /**
-     * 获取报单级别
-     * @param $userId
-     * @param null $periodNum
-     * @return mixed
-     * @throws \yii\db\Exception
-     */
-    public static function getDecLv($userId, $periodNum = null) {
-        if ($periodNum === null) {
-            $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'DEC_LV');
-            $decLv = $data['DEC_LV'];
-        } else {
-            $period = Period::instance();
-            $yearMonth = $period->getYearMonth($periodNum);
-            $data = PerfPeriod::find()->yearMonth($yearMonth)->select('LAST_DEC_LV')->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $userId, ':PERIOD_NUM' => $periodNum])->asArray()->one();
-            $decLv = $data ? $data['LAST_DEC_LV'] : DeclarationLevel::getDefaultLevelId();
-        }
-        return $decLv;
-    }
-
-    /**
-     * 获取聘级
-     * @param $userId
-     * @param null $periodNum
-     * @return mixed
-     * @throws \yii\db\Exception
-     */
-    public static function getEmpLv($userId, $periodNum = null) {
-        if ($periodNum === null) {
-            $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'EMP_LV');
-            $empLv = $data['EMP_LV'];
-        } else {
-            $period = Period::instance();
-            $yearMonth = $period->getYearMonth($periodNum);
-            $data = PerfMonth::find()->yearMonth($yearMonth)->select('LAST_EMP_LV')->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $userId, ':CALC_MONTH' => $yearMonth])->asArray()->one();
-            $empLv = $data ? $data['LAST_EMP_LV'] : EmployLevel::getDefaultLevelId();
-        }
-        return $empLv;
-    }
-
-    /**
-     * 获取最高聘级
-     * @param $userId
-     * @return mixed
-     */
-    public static function getHighEmpLv($userId){
-        $data = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'HIGHEST_EMP_LV');
-        $empLv = $data ? $data['HIGHEST_EMP_LV'] : EmployLevel::getDefaultLevelId();
-        return $empLv;
-    }
-
-    /**
-     * 获取报单级别名称
-     * @param $userId
-     * @param null $periodNum
-     * @return mixed
-     * @throws \yii\db\Exception
-     */
-    public static function getDecLvName($userId, $periodNum = null) {
-        if (!$decLv = self::getDecLv($userId, $periodNum)) {
-            $decLv = DeclarationLevel::getDefaultLevelId();
-        }
-        return Cache::getDecLevelConfig()[$decLv]['LEVEL_NAME'];
-    }
-
-    /**
-     * 获取聘级名称
-     * @param $userId
-     * @param null $periodNum
-     * @return mixed
-     * @throws \yii\db\Exception
-     */
-    public static function getEmpLvName($userId, $periodNum = null) {
-        if (!$empLv = self::getEmpLv($userId, $periodNum)) {
-            $empLv = EmployLevel::getDefaultLevelId();
-        }
-        return Cache::getEmpLevelConfig()[$empLv]['LEVEL_NAME'];
-    }
-
-    /**
-     * 获取民族对应的代码
-     * @param $str
-     * @return int|string
-     */
-    public static function getNationCode($str) {
-        $str = preg_replace('/族$/', '', $str);
-        $allNation = \Yii::$app->params['nation'];
-        foreach ($allNation as $key => $nation) {
-            if ($str . '族' == $nation['name']) {
-                return $key;
-            }
-        }
-        return 0;
-    }
-
-    /**
-     * 生成用户名
-     * @param string $prefix
-     * @param int $length
-     * @return string
-     */
-    public static function generateUserName(string $prefix = 'HZ', int $length = 10) {
-        $result = Tool::randomString($length, $prefix).array_rand([0,1,2,3,5,6,7,8,9],1);
-        if (User::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
-            return self::generateUserName($prefix, $length);
-        }
-        return $result;
-    }
-
-    /**
-     * 新增加的 生成前端姓名里用户名
-     * @param string $prefix
-     * @param int $length
-     * @return string
-     */
-    public static function generateWebUserName(string $prefix = 'HZ', int $length = 10) {
-        $result = Tool::randomString($length, $prefix).array_rand([0,1,2,3,5,6,7,8,9],1);
-        if (substr($result ,-1) == '4'){
-            return self::generateWebUserName($prefix, $length);
-        }
-        if (User::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
-            return self::generateWebUserName($prefix, $length);
-        }
-        return $result;
-    }
-
-    /**
-     * 定位会员的子公司
-     * @param $userArea
-     * @return array|bool
-     */
-    public static function location($userArea){
-        if(!is_array($userArea)){
-            $userArea = json_decode($userArea, true);
-        }
-        if(!$userArea || !isset($userArea[0])){
-            return false;
-        }
-        //获取会员的所在省份
-        $userProvince = $userArea[0];
-        $list = [];
-        if(!$list){
-            return false;
-        }
-        $matched = [];
-        $userCity = isset($userArea[1]) ? intval($userArea[1]) : 0;
-        $userCounty = isset($userArea[2]) ? intval($userArea[2]) : 0;
-        foreach($list as $row){
-            $manageRange = json_decode($row['MANAGE_RANGE'], true);
-            foreach($manageRange as $manage){
-                // $manage = ["370000","371000","371082"] or ["210000",""];
-                $pro = isset($manage[0]) ? intval($manage[0]) : 0;
-                $city = isset($manage[1]) ? intval($manage[1]) : 0;
-                $county = isset($manage[2]) ? intval($manage[2]) : 0;
-                if($userProvince == $pro && $userCity == $city && $userCounty == $county){
-                    $matched = $row;
-                    break;
-                }
-                if($userProvince == $pro && $userCity == $city && $county == 0){
-                    $matched = $row;
-                    break;
-                }
-                if($userProvince == $pro && $city == 0 && $county == 0){
-                    $matched = $row;
-                    break;
-                }
-            }
-        }
-        unset($userCounty, $userCity, $userArea, $userProvince, $list);
-        return $matched;
-    }
-
-    /**
-     * 通过id获取身份证号
-     * @param $userId
-     * @return null
-     */
-    public static function getIdCardByUserId($userId) {
-        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID_CARD');
-        return $user ? $user['ID_CARD'] : null;
-    }
-
-    /**
-     * 通过id获取状态
-     * @param $userId
-     * @return null
-     */
-    public static function getStatusByUserId($userId){
-        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'STATUS');
-        return $user ? $user['STATUS'] : null;
-    }
-
-    /**
-     * 通过id获取期数
-     * @param $userId
-     * @return null
-     */
-    public static function getPeriodNumByUserId($userId) {
-        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'PERIOD_AT');
-        return $user ? $user['PERIOD_AT'] : null;
-    }
-
-    /**
-     * 是否实名认证
-     * @param $userId
-     * @return bool
-     */
-    public static function isVerified($userId) {
-        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'VERIFIED');
-        if ($user && $user['VERIFIED'] == 1) return true;
-        return false;
-    }
-
-    /**
-     * 根据商城设置获取密码
-     * @param $idCard
-     * @param $userName
-     * @param bool $payPwd
-     * @return bool|string
-     */
-    public static function passwordGenerator($idCard,$userName,$payPwd=false) {
-        $systemConfig = Cache::getSystemConfig();
-        if($payPwd){
-            $config = $systemConfig['payPasswordRule'];
-        }else{
-            $config = $systemConfig['passwordRule'];
-        }
-        $rule = $config['VALUE'];  //id_s_6 , id_p_8, user_name 后台设置,分别为身份证的后6位,前8位或者用户名
-        switch ($rule) {
-            case 'id_s_6':
-                $password = substr($idCard, -6);
-                break;
-            case 'id_p_8':
-                $password = substr($idCard, 0, 8);
-                break;
-            case 'user_name':
-                $password = $userName;
-                break;
-            default:
-                $password = '123456';
-        }
-        return $password;
-    }
-
-    /**
-     * 当时会员级别状态等
-     * @param $userId
-     * @return array|null
-     */
-    public static function getLastInfo($userId){
-        $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'LAST_DEC_LV AS DEC_LV,EMP_LV,STATUS,CROWN_LV AS LAST_CROWN_LV');
-        return $data;
-    }
-
-    /**
-     * 是否合作会员
-     * @param $userId
-     * @return bool
-     */
-    public static function isUnion($userId){
-        $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'IS_UNION');
-        if ($data && $data['IS_UNION'] == 1) return true;
-        return false;
-    }
-}

+ 0 - 395
common/helpers/user/Perf.php

@@ -1,395 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/10/9
- * Time: 下午3:25
- */
-
-namespace common\helpers\user;
-
-
-use common\helpers\Date;
-use common\helpers\Tool;
-use common\models\PerfMonth;
-use common\models\PerfPeriod;
-use common\models\Period;
-use common\models\DecOrder;
-use common\models\UserNetwork;
-use common\models\UserPerf;
-use common\models\UserRelation;
-use yii\helpers\Json;
-
-class Perf
-{
-    const CACHE_PERIOD_NEW_PERF_PREFIX = 'periodNewPerf_';
-    const CACHE_PERIOD_DEEP_IN_NEW_PERF_PREFIX = 'periodDeepInNewPerf_';
-
-    /**
-     * 获取该会员当期新增业绩
-     * @param $userId
-     * @param null $relationDeep
-     * 传推荐网络代数,如果传了此值,则只计算这个代数的所有子会员给的业绩
-     * @return array
-     */
-    public static function getPeriodNewPerf($userId, $periodNum = null, $relationDeep = null){
-        $period = Period::instance();
-        if(!$periodNum) {
-            $periodNum = $period->getNowPeriodNum();
-        }
-        $redisKey = self::CACHE_PERIOD_NEW_PERF_PREFIX.$userId;
-        $perfArr = \Yii::$app->redis->get($redisKey);
-        if($perfArr){
-            $perfArr = Json::decode($perfArr);
-            if($perfArr['periodNum'] == $periodNum){
-                return $perfArr['perf'];
-            }
-        }
-        $perf = [
-            'PV_TOTAL' => 0,
-            'PV_1L' => 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_ZC' => 0,
-            'PV_2L_YH' => 0,
-            'PV_2L_ZG' => 0,
-            'PV_2L_LS' => 0,
-            'PV_2L_FX' => 0,
-            'PV_3L' => 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_ZC' => 0,
-            'PV_4L_YH' => 0,
-            'PV_4L_ZG' => 0,
-            'PV_4L_LS' => 0,
-            'PV_4L_FX' => 0,
-            'PV_5L' => 0,
-            'PV_5L_ZC' => 0,
-            'PV_5L_YH' => 0,
-            'PV_5L_ZG' => 0,
-            'PV_5L_LS' => 0,
-            'PV_5L_FX' => 0,
-            'PV_PCS' => 0,
-            'PV_PSS' => 0,
-        ];
-        if ($period->isSent($periodNum)) {
-            if ($perf = PerfPeriod::find()->select('PV_1L,PV_1L_ZC,PV_1L_YH,PV_1L_ZG,PV_1L_LS,PV_1L_FX,PV_2L,PV_2L_ZC,PV_2L_YH,PV_2L_ZG,PV_2L_LS,PV_2L_FX,PV_3L,PV_3L_ZC,PV_3L_YH,PV_3L_ZG,PV_3L_LS,PV_3L_FX,PV_4L,PV_4L_ZC,PV_4L_YH,PV_4L_ZG,PV_4L_LS,PV_4L_FX,PV_5L,PV_5L_ZC,PV_5L_YH,PV_5L_ZG,PV_5L_LS,PV_5L_FX,PV_PCS,PV_PSS')->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID'=>$userId, ':PERIOD_NUM' => $periodNum])->asArray()->one()) {
-                $perf['PV_TOTAL'] = $perf['PV_1L'] + $perf['PV_2L'] + $perf['PV_3L'] + $perf['PV_4L'] + $perf['PV_5L'];
-            }
-        } else {
-            foreach ($perf as $k => $item) {
-                $perf[$k] = Tool::formatPrice($item);
-            }
-        }
-
-        // 把业绩加入缓存中5分钟(防止频繁获取)
-        \Yii::$app->redis->set($redisKey, Json::encode(['periodNum'=>$periodNum, 'perf'=>$perf]));
-        \Yii::$app->redis->expire($redisKey, 5 * 60);
-        return $perf;
-    }
-
-    /**
-     * 获取期数业绩
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     */
-    public static function getPeriodPerf($userId, $periodNum){
-        $period = Period::instance();
-        $yearMonth = $period->getYearMonth($periodNum);
-        $result = PerfPeriod::findUseSlaves()->yearMonth($yearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID'=>$userId, ':PERIOD_NUM'=>$periodNum])->asArray()->one();
-        $userStatus = Status::getStatus($userId, $periodNum);
-        if(!$result || $userStatus == \Yii::$app->params['userStatus'][2]['value'] || $userStatus == \Yii::$app->params['userStatus'][9]['value']){
-            $result = [
-                'PV_PCS' => 0,
-                'PV_PCS_ZC' => 0,
-                'PV_PCS_YH' => 0,
-                'PV_PCS_ZG' => 0,
-                'PV_PCS_LS' => 0,
-                'PV_PCS_FX' => 0,
-                'PV_1L' => 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_ZC' => 0,
-                'PV_2L_YH' => 0,
-                'PV_2L_ZG' => 0,
-                'PV_2L_LS' => 0,
-                'PV_2L_FX' => 0,
-                'PV_3L' => 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_ZC' => 0,
-                'PV_4L_YH' => 0,
-                'PV_4L_ZG' => 0,
-                'PV_4L_LS' => 0,
-                'PV_4L_FX' => 0,
-                'PV_5L' => 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_LS' => 0,
-            ];
-        }
-
-        return $result;
-    }
-
-    /**
-     * 获取指定深度这一代会员给我的业绩
-     * @param $userId
-     * @param $relationDeep
-     * @return int|mixed
-     */
-    public static function getChildrenDeepInNewPerf($userId, $relationDeep){
-        $period = Period::instance();
-        $yearMonth = $period->getNowYearMonth();
-        $periodNum = $period->getNowPeriodNum();
-        $redisKey = self::CACHE_PERIOD_DEEP_IN_NEW_PERF_PREFIX.$relationDeep.'_'.$userId;
-        $perfArr = \Yii::$app->redis->get($redisKey);
-        if($perfArr){
-            $perfArr = Json::decode($perfArr);
-            if($perfArr['periodNum'] == $periodNum){
-                return $perfArr['perf'];
-            }
-        }
-        static $allData = [];
-        if(!$allData){
-            $allData = DecOrder::find()->where('PERIOD_NUM=:PERIOD_NUM AND IS_DEL=0', [':PERIOD_NUM'=>$periodNum])->asArray()->all();
-        }
-        $perf = [
-            'PV_ZC' => 0,
-            'PV_YH' => 0,
-            'PV_ZG' => 0,
-            'PV_LS' => 0,
-            'PV_FX' => 0,
-        ];
-        foreach($allData as $data){
-            if(UserRelation::deepWithParent($data['TO_USER_ID'], $userId) != $relationDeep){
-                continue;
-            }
-            $perf['PV_'.$data['TYPE']] += $data['DEC_PV'];
-        }
-        // 把业绩加入缓存中5分钟(防止频繁获取)
-        \Yii::$app->redis->set($redisKey, Json::encode(['periodNum'=>$periodNum, 'perf'=>$perf]));
-        \Yii::$app->redis->expire($redisKey, 5 * 60);
-        return $perf;
-    }
-
-    /**
-     * 获取月业绩
-     * @param $userId
-     * @param null $yearMonth
-     * @return array
-     */
-    public static function getMonthPerf($userId, $yearMonth = null){
-        $result = [
-            'PV_PCS'=>0,//新增个人业绩
-            'PV_1L'=>0,//当月新增
-            'PV_2L'=>0,
-            'PV_3L'=>0,
-            'PV_4L'=>0,
-            'PV_5L'=>0,
-            'PV_1L_TOTAL'=>0,//总业绩
-            'PV_2L_TOTAL'=>0,
-            'PV_3L_TOTAL'=>0,
-            'PV_4L_TOTAL'=>0,
-            'PV_5L_TOTAL'=>0,
-            'PV_TOTAL' => 0,//当月新增
-            'PV_TOTAL_TOTAL' => 0,//总业绩
-            'PV_PSS' => 0,//新增团队业绩
-            'PV_PSS_TOTAL' => 0,//团队总业绩
-        ];
-        $userStatus = Status::getStatus($userId);
-        if($userStatus == \Yii::$app->params['userStatus'][2]['value'] || $userStatus == \Yii::$app->params['userStatus'][9]['value']){
-            return $result;
-        }
-        // 当月业绩
-        if($yearMonth === null){
-            $period = Period::instance();
-            $yearMonth = $period->getNowYearMonth();
-            // 获取本月已挂网的其他期业绩
-            // 该月所有已经挂网的期数
-            $allSentPeriod = Period::monthSentAllPeriodNum($yearMonth);
-            $sentPeriodWhere = '';
-            if($allSentPeriod){
-                $sentPeriodWhere = implode("','", $allSentPeriod);
-                $sentPeriodWhere = " AND PERIOD_NUM IN ('$sentPeriodWhere')";
-            }
-            $perfPeriodSum = PerfPeriod::find()->yearMonth($yearMonth)->select('SUM(PV_PCS) AS PV_PCS,SUM(PV_1L) AS PV_1L,SUM(PV_2L) AS PV_2L,SUM(PV_3L) AS PV_3L,SUM(PV_4L) AS PV_4L,SUM(PV_5L) AS PV_5L,SUM(PV_PSS) AS PV_PSS')->where('USER_ID=:USER_ID'.$sentPeriodWhere, [':USER_ID'=>$userId])->asArray()->one();
-            if($perfPeriodSum){
-                $result['PV_PCS'] += $perfPeriodSum['PV_PCS'];
-                $result['PV_1L'] += $perfPeriodSum['PV_1L'];
-                $result['PV_2L'] += $perfPeriodSum['PV_2L'];
-                $result['PV_3L'] += $perfPeriodSum['PV_3L'];
-                $result['PV_4L'] += $perfPeriodSum['PV_4L'];
-                $result['PV_5L'] += $perfPeriodSum['PV_5L'];
-                $result['PV_PSS'] += $perfPeriodSum['PV_PSS'];
-                $result['PV_TOTAL'] += ($perfPeriodSum['PV_1L'] + $perfPeriodSum['PV_2L'] + $perfPeriodSum['PV_3L'] + $perfPeriodSum['PV_4L'] + $perfPeriodSum['PV_5L']);
-            }
-            // 获取本期业绩
-            $nowPeriodPerf = self::getPeriodNewPerf($userId);
-            if($nowPeriodPerf){
-                $result['PV_PCS'] += $nowPeriodPerf['PV_PCS'];
-                $result['PV_1L'] += $nowPeriodPerf['PV_1L'];
-                $result['PV_2L'] += $nowPeriodPerf['PV_2L'];
-                $result['PV_3L'] += $nowPeriodPerf['PV_3L'];
-                $result['PV_4L'] += $nowPeriodPerf['PV_4L'];
-                $result['PV_5L'] += $nowPeriodPerf['PV_5L'];
-                $result['PV_PSS'] += $nowPeriodPerf['PV_PSS'];
-                $result['PV_TOTAL'] += ($nowPeriodPerf['PV_1L'] + $nowPeriodPerf['PV_2L'] + $nowPeriodPerf['PV_3L'] + $nowPeriodPerf['PV_4L'] + $nowPeriodPerf['PV_5L']);
-            }
-            return $result;
-        }
-        // 往月业绩
-        $perfMonth = PerfMonth::find()->yearMonth($yearMonth)->select('PV_PCS,PV_1L,PV_2L,PV_3L,PV_4L,PV_5L,PV_PSS,PV_PSS_TOTAL')->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID'=>$userId, ':CALC_MONTH' => $yearMonth])->asArray()->one();
-        if($perfMonth){
-            $result['PV_PCS'] = $result['PV_PCS'] + $perfMonth['PV_PCS'];
-            $result['PV_1L_TOTAL'] = $result['PV_1L'] + $perfMonth['PV_1L'];
-            $result['PV_2L_TOTAL'] = $result['PV_2L'] + $perfMonth['PV_2L'];
-            $result['PV_3L_TOTAL'] = $result['PV_3L'] + $perfMonth['PV_3L'];
-            $result['PV_4L_TOTAL'] = $result['PV_4L'] + $perfMonth['PV_4L'];
-            $result['PV_5L_TOTAL'] = $result['PV_5L'] + $perfMonth['PV_5L'];
-            $result['PV_PSS'] = $result['PV_PSS'] + $perfMonth['PV_PSS'];
-            $result['PV_PSS_TOTAL'] = $result['PV_PSS_TOTAL'] + $perfMonth['PV_PSS_TOTAL'];
-            $result['PV_TOTAL'] = ($result['PV_1L_TOTAL'] + $result['PV_2L_TOTAL'] + $result['PV_3L_TOTAL'] + $result['PV_4L_TOTAL'] + $result['PV_5L_TOTAL']);
-        }
-        foreach ($result as $k=>$item) {
-            $result[$k] = Tool::formatPrice($item);
-        }
-        return $result;
-    }
-
-    /**
-     * 获取到会员的当前的总业绩,含未挂网
-     * @param $userId
-     * @return array
-     */
-    public static function getMonthAndNewPeriodPerf($userId){
-        $perf = self::getMonthPerf($userId);
-        // 当期业绩
-        $newPerf = self::getPeriodNewPerf($userId);
-        return [
-            'PV_1L' => $perf['PV_1L'] + $newPerf['PV_1L'],
-            'PV_2L' => $perf['PV_2L'] + $newPerf['PV_2L'],
-            'PV_3L' => $perf['PV_3L'] + $newPerf['PV_3L'],
-            'PV_4L' => $perf['PV_4L'] + $newPerf['PV_4L'],
-            'PV_5L' => $perf['PV_5L'] + $newPerf['PV_5L'],
-            'PV_TOTAL' => $perf['PV_TOTAL'] + $newPerf['PV_TOTAL'],
-        ];
-    }
-
-    /**
-     * 所传期数的业绩
-     * @param $userId
-     * @param $periodNum
-     * @return array
-     * @throws \yii\db\Exception
-     */
-    public static function getPeriodTotalPerf($userId, $periodNum){
-        // 获取所传期数的上一个结算月
-        $period = Period::instance();
-        $lastMonthArr = $period->getLastMonth($periodNum);
-        $yearMonth = $period->getYearMonth($periodNum);
-        $lastYearMonth = $lastMonthArr['yearMonth'];
-        // 获取上一个结算月的业绩
-        $lastYearMonthPerf = self::getMonthPerf($userId, $lastYearMonth);
-        $result = [
-            'PV_1L' => $lastYearMonthPerf['PV_1L'],
-            'PV_2L' => $lastYearMonthPerf['PV_2L'],
-            'PV_3L' => $lastYearMonthPerf['PV_3L'],
-            'PV_4L' => $lastYearMonthPerf['PV_4L'],
-            'PV_5L' => $lastYearMonthPerf['PV_5L'],
-            'PV_TOTAL' => $lastYearMonthPerf['PV_TOTAL'],
-        ];
-        // 获取所传期数的本月的已结算的全部期数
-        $allCalcPeriodNumArr = Period::monthCalcAllPeriodNum($yearMonth);
-        foreach($allCalcPeriodNumArr as $calcPeriodNum){
-            // 达到所传期数停止
-            if($calcPeriodNum > $periodNum) break;
-            $periodPerf = self::getPeriodPerf($userId, $periodNum);
-            $result['PV_1L'] += $periodPerf['PV_1L'];
-            $result['PV_2L'] += $periodPerf['PV_2L'];
-            $result['PV_3L'] += $periodPerf['PV_3L'];
-            $result['PV_4L'] += $periodPerf['PV_4L'];
-            $result['PV_5L'] += $periodPerf['PV_5L'];
-            $result['PV_TOTAL'] += ($periodPerf['PV_1L'] + $periodPerf['PV_2L'] + $periodPerf['PV_3L'] + $periodPerf['PV_4L'] + $periodPerf['PV_5L']);
-        }
-        return $result;
-    }
-
-    /**
-     * 获取总业绩
-     * @param $userId
-     * @return array
-     */
-    public static function getTotalPerf($userId){
-        $result = [
-            'PV_1L' => 0,
-            'PV_2L' => 0,
-            'PV_3L' => 0,
-            'PV_4L' => 0,
-            'PV_5L' => 0,
-            'PV_TOTAL' => 0,
-        ];
-        $userStatus = Status::getStatus($userId);
-        if($userStatus == \Yii::$app->params['userStatus'][2]['value'] || $userStatus == \Yii::$app->params['userStatus'][9]['value']){
-            return $result;
-        }
-        // 历史已挂网业绩
-        $perf = UserPerf::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId], 'PV_1L,PV_2L,PV_3L,PV_4L,PV_5L');
-        if($perf){
-            $result['PV_1L'] += $perf['PV_1L'];
-            $result['PV_2L'] += $perf['PV_2L'];
-            $result['PV_3L'] += $perf['PV_3L'];
-            $result['PV_4L'] += $perf['PV_4L'];
-            $result['PV_5L'] += $perf['PV_5L'];
-            $result['PV_TOTAL'] += ($perf['PV_1L'] + $perf['PV_2L'] + $perf['PV_3L'] + $perf['PV_4L'] + $perf['PV_5L']);
-        }
-        // 获取本期业绩
-        $nowPeriodPerf = self::getPeriodNewPerf($userId);
-        if($nowPeriodPerf){
-            $result['PV_1L'] += $nowPeriodPerf['PV_1L'];
-            $result['PV_2L'] += $nowPeriodPerf['PV_2L'];
-            $result['PV_3L'] += $nowPeriodPerf['PV_3L'];
-            $result['PV_4L'] += $nowPeriodPerf['PV_4L'];
-            $result['PV_5L'] += $nowPeriodPerf['PV_5L'];
-            $result['PV_TOTAL'] += ($nowPeriodPerf['PV_1L'] + $nowPeriodPerf['PV_2L'] + $nowPeriodPerf['PV_3L'] + $nowPeriodPerf['PV_4L'] + $nowPeriodPerf['PV_5L']);
-        }
-        return $result;
-    }
-
-    /**
-     * 获取用户业绩
-     * @param $userId
-     * @return array|\yii\db\ActiveRecord
-     */
-    public static function getUserPerf( $userId ) {
-        $data = UserPerf::find()->where('USER_ID=:USER_ID', ['USER_ID'=>$userId])->asArray()->one();
-        return $data ?? [];
-    }
-
-}

+ 0 - 486
common/helpers/user/Reconsume.php

@@ -1,486 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: liyunlong
- * Date: 2019-01-30
- * Time: 14:21
- */
-
-namespace common\helpers\user;
-
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\helpers\Tool;
-use common\models\PerfMonth;
-use common\models\Period;
-use common\models\ReconsumePool;
-use common\models\ReconsumePoolFlow;
-use common\models\DeclarationLevel;
-use common\models\EmployLevel;
-use common\models\User;
-use yii\base\Exception;
-use yii\db\Expression;
-
-class Reconsume {
-
-    const TYPE_DEC = 1;
-    const TYPE_CALC = 2;
-    const TYPE_AUDIT_PV = 3;
-    const TYPE_AUDIT_MONTH = 4;
-    const TYPE_MANUAL = 5;
-    const TYPE_RESEND_QY = 7;
-    const TYPE = [
-        1 => ['label' => '报单预存', 'value' => 1],
-        2 => ['label' => '结算自动扣除', 'value' => 2],
-        3 => ['label' => '调整复销池余额', 'value' => 3],
-        4 => ['label' => '调整复销池月数', 'value' => 4],
-        5 => ['label' => '手工扣除月复销', 'value' => 5],
-        //7 => ['label' => '补发区域津贴', 'value' => 7],
-    ];
-
-    /**
-     * 可用复销余额
-     * @param $userId
-     * @return mixed
-     */
-    public static function getBalance($userId) {
-        $oneData = ReconsumePool::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'UNUSED_PV');
-        return $oneData['UNUSED_PV'];
-    }
-
-    /**
-     * 增加复销或扣除复销池的PV
-     * @param $userId
-     * @param $pv
-     * @param array $params
-     * @param bool $mustHasUser
-     * 该参数主要用于批量报单,复销会员是新首购的新会员,数据库中不存在该会员,此时不能要求一定存在会员,然后先把复销池数据插进去
-     * @return int
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function changePoolPV($userId, $pv, $params = [], $mustHasUser = true) {
-        if ($pv == 0) return 0;
-        $period = Period::instance();
-        if (!isset($params['PERIOD_NUM'])) {
-            $periodNum = $period->getNowPeriodNum();
-        } else {
-            $periodNum = $params['PERIOD_NUM'];
-        }
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        // 查看是否有数据
-        if (!ReconsumePool::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->exists()) {
-            // 新建一条用户的复销池数据
-            ReconsumePool::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
-        }
-        // 如果扣除pv的话,检测是否够扣,不够扣,则返回0
-        if ($pv < 0) {
-            $oneDataBefore = ReconsumePool::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-            if ($oneDataBefore['UNUSED_PV'] < abs($pv)) {
-                throw new Exception('复销池余额不足');
-            }
-        }
-        $updateData = [];
-        $updateData['UNUSED_PV'] = new Expression("UNUSED_PV + $pv");
-        // 变更复销池Pv
-        ReconsumePool::updateAll($updateData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-        unset($updateData);
-        // 获取变更完的数据
-        $oneDataAfter = ReconsumePool::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        // 记录流水
-        if($mustHasUser){
-            $userInfo = Info::baseInfo($userId);
-        } else {
-            $userInfo =[
-                'DEC_LV' => DeclarationLevel::getDefaultLevelId(),
-                'EMP_LV' => EmployLevel::getDefaultLevelId(),
-                'STATUS' => 1,
-            ];
-        }
-        $flowInsertData = [
-            'RECONSUME_POOL_SN' => ReconsumePoolFlow::generateSN(),
-            'USER_ID' => $userId,
-            'LAST_DEC_LV' => $userInfo['DEC_LV'],
-            'LAST_EMP_LV' => $userInfo['EMP_LV'],
-            'LAST_STATUS' => $userInfo['STATUS'],
-            'DEAL_TYPE' => $params['DEAL_TYPE'],
-            'RECONSUME_POOL_TYPE' => ReconsumePoolFlow::POOL_TYPE_PV,
-            'DEDUCT_PV' => $pv,
-            'UNUSED_PV' => $oneDataAfter['UNUSED_PV'],
-            'UNUSED_MONTH' => $oneDataAfter['UNUSED_MONTH'],
-            'REMARK' => $params['REMARK'] ?? null,
-            'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
-            'PERIOD_NUM' => $periodNum,
-            'CALC_MONTH' => $calcYearMonth,
-            'P_CALC_MONTH' => Date::ociToDate($calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-            'CREATED_AT' => Date::nowTime(),
-            'ADMIN_NAME' => $params['ADMIN_NAME'] ?? null,
-        ];
-
-        ReconsumePoolFlow::insertOne($flowInsertData);
-        unset($flowInsertData);
-        return $pv;
-    }
-
-    /**
-     * 扣除月复销
-     * @param $userId
-     * @param $periodNum
-     * @param array $params
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public static function deductFx($userId, $periodNum, array $params = []) {
-        $period = Period::instance();
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        return self::deductFxByCalcMonth($userId, $calcYearMonth, $params);
-    }
-
-    /**
-     * 通过结算月来扣复销
-     * @param $userId
-     * @param $calcYearMonth
-     * @param array $params
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function deductFxByCalcMonth($userId, $calcYearMonth, array $params = []) {
-        $sysConfig = Cache::getSystemConfig();
-        $pv = $sysConfig['reConsumePerf']['VALUE'];
-
-        // 看是否本月注册,本月注册不扣除@190904
-        if(Status::isMonthJoin($userId,$calcYearMonth)) return true;
-
-        // 查看是否有数据
-        if (!ReconsumePool::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->exists()) {
-            // 新建一条用户的复销池数据
-            ReconsumePool::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
-        }
-        // 查看这个月是否已经扣过了,如果扣过了就不在扣了!直接返回扣除过的业绩
-        $isDeducted = ReconsumePoolFlow::find()->yearMonth($calcYearMonth)->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND IS_FX_DEDUCT=1', [':USER_ID' => $userId, ':CALC_MONTH' => $calcYearMonth])->asArray()->one();
-        if ($isDeducted) {
-            return true;
-        }
-        // 检测是否够扣,不够扣,则扣除月有效期
-        $deductPv = 0;
-        $deductMonth = 0;
-        $oneDataBefore = ReconsumePool::find()->select('UNUSED_PV,UNUSED_MONTH')->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if ($oneDataBefore['UNUSED_PV'] < abs($pv)) {
-            if ($oneDataBefore['UNUSED_MONTH'] < abs(1)) {
-                return false;
-            } else {
-                $deductMonth = 1;
-            }
-        } else {
-            $deductPv = $pv;
-        }
-        $updateData = [];
-        $updateData['UNUSED_PV'] = new Expression("UNUSED_PV - $deductPv");
-        $updateData['UNUSED_MONTH'] = new Expression("UNUSED_MONTH - $deductMonth");
-        // 变更复销池Pv
-        ReconsumePool::updateAll($updateData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-        // 获取变更完的数据
-        $oneDataAfter = ReconsumePool::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        // 获取该结算月的最大期数,即为结算月的期节点
-        $periodNum = Period::getPeriodNumPointFromMonth(substr($calcYearMonth, 0, 4), intval(substr($calcYearMonth, 4, 2)));
-        // 记录流水
-        $userInfo = Info::baseInfo($userId);
-        $flowInsertData = [
-            'RECONSUME_POOL_SN' => ReconsumePoolFlow::generateSN(),
-            'USER_ID' => $userId,
-            'LAST_DEC_LV' => $userInfo['DEC_LV'],
-            'LAST_EMP_LV' => $userInfo['EMP_LV'],
-            'LAST_STATUS' => $userInfo['STATUS'],
-            'DEAL_TYPE' => $params['DEAL_TYPE'],
-            'RECONSUME_POOL_TYPE' => $deductMonth != 0 ? ReconsumePoolFlow::POOL_TYPE_MONTH : ReconsumePoolFlow::POOL_TYPE_PV,
-            'DEDUCT_PV' => $deductPv == 0 ? 0 : -$deductPv,
-            'DEDUCT_MONTH' => $deductMonth == 0 ? 0 : -$deductMonth,
-            'UNUSED_PV' => $oneDataAfter['UNUSED_PV'],
-            'UNUSED_MONTH' => $oneDataAfter['UNUSED_MONTH'],
-            'IS_FX_DEDUCT' => 1,
-            'REMARK' => $params['REMARK'] ?? null,
-            'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
-            'PERIOD_NUM' => $periodNum,
-            'CALC_MONTH' => $calcYearMonth,
-            'P_CALC_MONTH' => Date::ociToDate($calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-            'CREATED_AT' => Date::nowTime(),
-            'ADMIN_NAME' => $params['ADMIN_NAME'] ?? 'system',
-        ];
-        ReconsumePoolFlow::insertOne($flowInsertData);
-        unset($oneDataBefore, $updateData, $oneDataAfter, $flowInsertData);
-        return true;
-    }
-
-    /**
-     * 查看该会员是否能扣除复销
-     * @param $userId
-     * @param $calcYearMonth
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public static function isCanDeduct($userId, $calcYearMonth) {
-        // 查看会员是否本月加入
-        if (Status::isMonthJoin($userId, $calcYearMonth)) return false;
-        // 会员未加入的结算月不允许扣除
-        if (Status::afterMonthJoin($userId, $calcYearMonth)) return false;
-        // 查看该结算月是否已经扣过
-        return !(ReconsumePoolFlow::find()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND IS_FX_DEDUCT=1', [':USER_ID' => $userId, ':CALC_MONTH' => $calcYearMonth])->exists());
-    }
-
-    /**
-     * 是否有得奖资格
-     * @param $userId
-     * @param $calcYearMonth
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public static function isCanGetBonus($userId, $calcYearMonth) {
-        // 查看会员是否本月加入
-        if (Status::isMonthJoin($userId, $calcYearMonth)) return true;
-        // 查看会员上月是否已经扣除过复销
-        $periodNum = Period::getPeriodNumPointFromMonth(substr($calcYearMonth, 0, 4), intval(substr($calcYearMonth, 4, 2)));
-        $period = Period::instance();
-        $lastMonth = $period->getLastMonth($periodNum);
-        // 查看业绩表中该结算月的上个月是否有复销资格
-        return PerfMonth::find()->yearMonth($lastMonth['yearMonth'])->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND FX_STATUS=1', [':USER_ID' => $userId, ':CALC_MONTH' => $lastMonth['yearMonth']])->exists();
-//        return ReconsumePoolFlow::find()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND IS_FX_DEDUCT=1', [':USER_ID'=>$userId, ':CALC_MONTH'=>$lastMonth['yearMonth']])->exists();
-    }
-
-    /**
-     * 变化有效月数
-     * @param $userId
-     * @param $monthNum
-     * @param array $params
-     * @return int
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public static function changePoolMonthNum($userId, $monthNum, array $params = []) {
-        $periodNum = $params['periodNum'] ?? null;
-        if ($monthNum == 0) return 0;
-        $period = Period::instance();
-        if (!$periodNum) {
-            $periodNum = $period->getNowPeriodNum();
-        }
-        $calcYearMonth = $period->getYearMonth($periodNum);
-        // 查看是否有数据
-        if (!ReconsumePool::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->exists()) {
-            // 新建一条用户的复销池数据
-            ReconsumePool::insertOne(['USER_ID' => $userId, 'CREATED_AT' => Date::nowTime()]);
-        }
-        // 如果扣除pv的话,检测是否够扣,不够扣,则返回0
-        if ($monthNum < 0) {
-            $oneDataBefore = ReconsumePool::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-            if ($oneDataBefore['UNUSED_MONTH'] < abs($monthNum)) {
-                throw new Exception('复销池剩余月数不足');
-            }
-        }
-        // 增加月份数
-        $updateData = [];
-        $updateData['UNUSED_MONTH'] = new Expression("UNUSED_MONTH + $monthNum");
-        // 变更复销池Pv
-        ReconsumePool::updateAll($updateData, 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
-        // 获取变更完的数据
-        $oneDataAfter = ReconsumePool::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        // 记录流水
-        $userInfo = Info::baseInfo($userId);
-        $flowInsertData = [
-            'RECONSUME_POOL_SN' => ReconsumePoolFlow::generateSN(),
-            'USER_ID' => $userId,
-            'LAST_DEC_LV' => $userInfo['DEC_LV'],
-            'LAST_EMP_LV' => $userInfo['EMP_LV'],
-            'LAST_STATUS' => $userInfo['STATUS'],
-            'DEAL_TYPE' => $params['DEAL_TYPE'],
-            'RECONSUME_POOL_TYPE' => ReconsumePoolFlow::POOL_TYPE_MONTH,
-            'DEDUCT_MONTH' => $monthNum,
-            'UNUSED_PV' => $oneDataAfter['UNUSED_PV'],
-            'UNUSED_MONTH' => $oneDataAfter['UNUSED_MONTH'],
-            'REMARK' => $params['REMARK'] ?? null,
-            'REMARK_IS_SHOW' => $params['REMARK_IS_SHOW'] ?? 1,
-            'PERIOD_NUM' => $periodNum,
-            'CALC_MONTH' => $calcYearMonth,
-            'P_CALC_MONTH' => Date::ociToDate($calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
-            'CREATED_AT' => Date::nowTime(),
-            'ADMIN_NAME' => $params['ADMIN_NAME'] ?? null,
-        ];
-
-        ReconsumePoolFlow::insertOne($flowInsertData);
-        unset($updateData, $oneDataAfter, $flowInsertData);
-        return $monthNum;
-    }
-
-    /**
-     * 获取复销剩余时间
-     * @param $userId
-     * @return array
-     * @throws \yii\db\Exception
-     */
-    public static function getUserReconsumePool($userId) {
-        $pool = ReconsumePool::findUseSlaves()->select('UNUSED_PV,UNUSED_MONTH')->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
-        if (!$pool) {
-            $pool['UNUSED_PV'] = 0;
-            $pool['UNUSED_MONTH'] = 0;
-            /*return [
-                'unusedPV' => 0,
-                'unusedMonth' => 0,
-                'reConsumeTimes' => 0,
-                'toTime' => 0,
-                'toDate' => 0,
-            ];*/
-        }
-        // 第一步 获取复销剩余总月数
-        $systemConfig = Cache::getSystemConfig();
-        $reConsumePerf = $systemConfig['reConsumePerf']['VALUE'];
-        if ($reConsumePerf <= 0) {
-            return ['unusedPV' => 0,
-                'unusedMonth' => 0,
-                'reConsumeTimes' => 0,
-                'toTime' => 0,
-                'toDate' => 0,
-                'isPass' => 0,
-            ];
-        }
-        $reConsumeTimes = intval($pool['UNUSED_PV'] / $reConsumePerf);
-        $reConsumeTimes += $pool['UNUSED_MONTH'];
-
-        // 第二步 获取最近一次未挂网的结算月
-        $period = Period::instance();
-        $sentMaxPeriodNum = Period::sentMaxPeriodNum() + 1;
-        $sentYear = $period->getYear($sentMaxPeriodNum);
-        $sentMonth = Tool::numFix($period->getMonth($sentMaxPeriodNum), 2);
-        $sentYearMonth = $period->getYearMonth($sentMaxPeriodNum);
-
-        //看会员这个月是否复销
-        if (ReconsumePoolFlow::find()->yearMonth($sentYearMonth)->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND IS_FX_DEDUCT=1', [':USER_ID' => $userId, ':CALC_MONTH' => $sentYearMonth])->asArray()->one()) {
-            //已扣复销当前月15日为时间基点
-            $baseDate = $sentYear . '-' . $sentMonth . '-15';
-            $reConsumeTimes += 1;
-        } else {
-            //获取上一个结算月
-            $lastMonth = $period->getLastMonth($sentMaxPeriodNum);
-            $baseDate = $lastMonth['year'] . '-' . $lastMonth['month'] . '-15';
-            //是否本月注册会员
-            if (Status::isMonthJoin($userId, $sentYearMonth)) {
-                $reConsumeTimes += 2;
-            } //是否上月注册会员
-            elseif (Status::isMonthJoin($userId, $lastMonth['yearMonth'])) {
-                $reConsumeTimes += 1;
-            } elseif (Status::afterMonthJoin($userId, $sentYearMonth)){
-                $reConsumeTimes +=Period::getMonthNum($sentMaxPeriodNum,Info::getPeriodNumByUserId($userId));
-                $reConsumeTimes +=1;
-            } else {
-                //是否扣复销
-                if (!ReconsumePoolFlow::find()->yearMonth($lastMonth['yearMonth'])->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND IS_FX_DEDUCT=1', [':USER_ID' => $userId, ':CALC_MONTH' => $lastMonth['yearMonth']])->asArray()->one()) {
-                    //会员过期
-                    if ($reConsumeTimes <= 0) {
-                        //上一次扣复销的时间
-                        if ($flow = ReconsumePoolFlow::find()->select('PERIOD_NUM')->where('USER_ID=:USER_ID AND IS_FX_DEDUCT=1', [':USER_ID' => $userId])->orderBy('PERIOD_NUM DESC')->asArray()->one()) {
-                            $nextMonth = $period->getNextMonth($flow['PERIOD_NUM']);
-                            $overPeriod = Period::getPeriodPointFromMonth($nextMonth['year'], $nextMonth['month']);
-                            $toTime = $overPeriod['END_TIME'];
-                            $toPeriod = Period::getPeriodPointFromMonth($sentYear, $sentMonth);
-                            $toRechargeTime = $toPeriod['END_TIME'];
-                            return [
-                                'unusedPV' => $pool['UNUSED_PV'],
-                                'unusedMonth' => $pool['UNUSED_MONTH'],
-                                'reConsumeTimes' => 0,
-                                'toTime' => $toTime,
-                                'toDate' => \date('Y-m-d', $toTime),
-                                'toRechargeTime' => $toRechargeTime,
-                                'toRechargeDate' => \date('Y-m-d', $toRechargeTime),
-                                'isPass' => 0,
-                            ];
-                        } else {
-                            $nextMonth = $period->getNextMonth(Info::getPeriodNumByUserId($userId));
-                            $overPeriod = Period::getPeriodPointFromMonth($nextMonth['year'], $nextMonth['month']);
-                            $toTime = $overPeriod['END_TIME'];
-                            $toPeriod = Period::getPeriodPointFromMonth($sentYear, $sentMonth);
-                            $toRechargeTime = $toPeriod['END_TIME'];
-                            return [
-                                'unusedPV' => $pool['UNUSED_PV'],
-                                'unusedMonth' => $pool['UNUSED_MONTH'],
-                                'reConsumeTimes' => 0,
-                                'toTime' => $toTime,
-                                'toDate' => \date('Y-m-d', $toTime),
-                                'toRechargeTime' => $toRechargeTime,
-                                'toRechargeDate' => \date('Y-m-d', $toRechargeTime),
-                                'isPass' => 0,
-                            ];
-                        }
-                    } else {
-                        $baseDate = $lastMonth['year'] . '-' . $lastMonth['month'] . '-15';
-                    }
-                }else{
-                    $reConsumeTimes += 1;
-                }
-            }
-        }
-
-        $calcTime = strtotime("+$reConsumeTimes month", strtotime($baseDate));
-
-        //获取toTime结算月最后一期封期时间
-        $toPeriod = Period::getPeriodFromTime($calcTime);
-        $periodPoint = Period::getPeriodPointFromMonth($toPeriod['CALC_YEAR'], $toPeriod['CALC_MONTH']);
-        $toTime = $periodPoint['END_TIME'];
-        $toDate = $toTime?(\date('Y-m-d', $toTime)):'长期';
-
-        $toRechargeTime = $periodPoint['END_TIME'];
-        $toRechargeDate = $toRechargeTime?(\date('Y-m-d', $toRechargeTime)):'长期';
-        unset($toPeriod, $toYear, $toMonth, $periodPoint);
-        return [
-            'unusedPV' => $pool['UNUSED_PV'],
-            'unusedMonth' => $pool['UNUSED_MONTH'],
-            'reConsumeTimes' => $reConsumeTimes,
-            'toTime' => $toTime,
-            'toDate' => $toDate,
-            'toRechargeTime' => $toRechargeTime,
-            'toRechargeDate' => $toRechargeDate,
-            'isPass' => 1,
-        ];
-    }
-
-    /**
-     * 通过用户名获取会员复销池相关
-     * @param $userName
-     * @return array
-     */
-    public static function getUserReconsumePoolByUserName($userName) {
-        return self::getUserReconsumePool(Info::getUserIdByUserName($userName));
-    }
-
-    /**
-     * 不能扣除月复销的月份
-     * @param $userId
-     * @param int|null $year
-     * @return array|\yii\db\ActiveRecord[]
-     * @throws \yii\db\Exception
-     */
-    public static function cantDeductMonth($userId, int $year = null) {
-        $period = Period::instance();
-        $sentMaxPeriodNum = Period::sentMaxPeriodNum() + 1;
-        if ($year === null) {
-            $year = $period->getYear($sentMaxPeriodNum);
-        }
-        $allData = ReconsumePoolFlow::find()->select('CALC_MONTH')->where('USER_ID=:USER_ID AND CALC_MONTH>=:YEAR_START AND CALC_MONTH<=:YEAR_END AND IS_FX_DEDUCT=1', [':USER_ID' => $userId, ':YEAR_START' => intval($year . '01'), ':YEAR_END' => intval($year . '12')])->asArray()->all();
-
-        //@190904 会员注册当月及以前都不能扣除
-        $oneUser = User::find()->select('PERIOD_AT')->where('ID=:USER_ID', [':USER_ID'=>$userId])->asArray()->one();
-        $period = Period::instance();
-        $addYear = $period->getYear($oneUser['PERIOD_AT']);
-        if($addYear==$year){
-            $addMonth = $period->getMonth($oneUser['PERIOD_AT']);
-            for($i=1;$i<=$addMonth;$i++){
-                $allData[] = ['CALC_MONTH'=>$year.Tool::numFix($i, 2)];
-            }
-        }
-        if($year == $period->getYear($sentMaxPeriodNum)){
-            $sentMonth = $period->getMonth($sentMaxPeriodNum);
-            for($i=$sentMonth;$i<=12;$i++){
-                $allData[] = ['CALC_MONTH'=>$year.Tool::numFix($i, 2)];
-            }
-        }
-        return $allData;
-    }
-}

+ 0 - 178
common/helpers/user/Status.php

@@ -1,178 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/10/30
- * Time: 下午3:19
- */
-
-namespace common\helpers\user;
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\models\forms\UserStatusForm;
-use common\models\PerfMonth;
-use common\models\Period;
-use common\models\UserWallet;
-use common\models\User;
-use common\models\UserClose;
-use common\models\UserInfo;
-use common\models\UserStatusAudit;
-
-class Status
-{
-    /**
-     * 根据所传期数获取当前期数是否可以因为复销得到奖金
-     * @param $userId
-     * @param $periodNum
-     * @return bool
-     */
-    public static function fxGetBonusStatusByPeriodNum($userId, $periodNum){
-        $period = Period::instance();
-        $lastYearMonth = $period->getLastMonth($periodNum);
-        return PerfMonth::find()->yearMonth($lastYearMonth['yearMonth'])->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND FX_STATUS=1', [':USER_ID'=>$userId, ':CALC_MONTH'=>$lastYearMonth['yearMonth']])->exists();
-    }
-
-//    public static function fxGetBonusStatusByYearMonth($userId, $yearMonth){
-//        $period = Period::instance();
-//        $lastYearMonth = Date::lastNumMonth($yearMonth);
-//        return PerfMonth::find()->yearMonth($lastYearMonth)->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND FX_STATUS=1', [':USER_ID'=>$userId, ':CALC_MONTH'=>$lastYearMonth])->exists();
-//    }
-
-    /**
-     * 是否所传的结算月加入
-     * @param $userId
-     * @param $calcMonth
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public static function isMonthJoin($userId, $calcMonth){
-        $oneUser = User::find()->select('PERIOD_AT')->where('ID=:USER_ID', [':USER_ID'=>$userId])->asArray()->one();
-        $period = Period::instance();
-        $addYearMonth = $period->getYearMonth($oneUser['PERIOD_AT']);
-        return $addYearMonth == $calcMonth;
-    }
-
-    /**
-     * 所传结算月之后加入
-     * @param $userId
-     * @param $calcMonth
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public static function afterMonthJoin($userId, $calcMonth){
-        $oneUser = User::find()->select('PERIOD_AT')->where('ID=:USER_ID', [':USER_ID'=>$userId])->asArray()->one();
-        $period = Period::instance();
-        $addYearMonth = $period->getYearMonth($oneUser['PERIOD_AT']);
-        return $addYearMonth > $calcMonth;
-    }
-
-    /**
-     * 是否完善了身份证照片
-     * @param $userId
-     * @return bool
-     */
-    public static function isFinishIdCard($userId){
-        return User::find()->where('ID=:ID AND ID_IMAGE IS NOT NULL',[':ID'=>$userId])->exists();
-    }
-
-    /**
-     * 是否存在点位合作情况
-     * @param $userId
-     * @return bool
-     */
-    public static function isTeamwork($userId){
-        return UserInfo::find()->where('IS_TEAM=1 AND USER_ID=:USER_ID', [':USER_ID' => $userId])->exists();
-    }
-
-    /**
-     * 点位绑定情况
-     * @param $userId
-     * @return array|null|\yii\db\ActiveRecord
-     */
-    public static function chkBind($userId){
-        $userBind=UserInfo::find()->select('IS_BIND,IS_BIND_MAIN')->where('USER_ID=:USER_ID',[':USER_ID'=>$userId])->asArray()->one();
-        return $userBind;
-    }
-
-    /**
-     * 会员状态
-     * @param $userId
-     * @param null $periodNum
-     * @return string
-     */
-    public static function getStatus($userId, $periodNum = null){
-        $period = Period::instance();
-        $nowPeriod = $period->getNowPeriodNum();
-        if($periodNum === null || $periodNum = $nowPeriod){
-            $user = User::findOneAsArray('ID=:ID', ['ID'=>$userId], 'STATUS');
-            return $user['STATUS'];
-        } else {
-            // 获取会员所传期数之前的最后一次修改状态的记录
-            $data = UserStatusAudit::findUseSlaves()->where('USER_ID=:USER_ID AND AUDIT_STATUS=:AUDIT_STATUS AND PERIOD_NUM<=:PERIOD_NUM', [':USER_ID' => $userId, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['true']['value'], ':PERIOD_NUM' => $periodNum])->orderBy('AUDITED_AT DESC')->asArray()->one();
-            if($data) {
-                return $data['STATUS_VALUE'];
-            } else {
-                return self::getStatus($userId, null);
-            }
-        }
-    }
-
-    /**
-     * 获取超过关停时间的会员
-     * @param bool $hasClear 清除过钱包
-     * @return array|null|\yii\db\ActiveRecord[]
-     */
-    public static function getCloseUser($hasClear = false){
-        $days = Cache::getSystemConfig()['closeInspectClearDays']['VALUE'];
-        if($hasClear){
-            $users = User::findAllAsArray('STATUS=:STATUS AND STATUS_AT<:STATUS_AT',[':STATUS'=>UserStatusForm::STATUS_CLOSE,'STATUS_AT'=>Date::lastNumDay($days)],'ID,STATUS,REAL_NAME,STATUS_AT');
-        }else{
-            $users = User::find()->from(User::tableName() . ' AS U')->select('U.ID,U.STATUS,U.REAL_NAME,U.STATUS_AT')->where('U.STATUS=:STATUS AND U.STATUS_AT<:STATUS_AT AND UW.CLEAR_BY_CLOSED_AT=0',[':STATUS'=>UserStatusForm::STATUS_CLOSE,'STATUS_AT'=>Date::lastNumDay($days)])->join('LEFT JOIN',UserWallet::tableName().' AS UW','U.ID=UW.USER_ID')->asArray()->all();
-        }
-        foreach ($users as $k=>$u){
-            $users[$k]['STATUS_NAME'] = \Yii::$app->params['userStatus'][$u['STATUS']]['label'];
-        }
-        return $users;
-    }
-
-    public static function getLoginStatus() {
-
-    }
-
-//    /**
-//     * 是否关停状态
-//     * @param $userId
-//     * @param null $periodNum
-//     * @return bool
-//     */
-//    public static function isCloseAccount($userId, $periodNum=null){
-//        if($periodNum === null){
-//            $data = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId], 'CLOSE_ACCOUNT');
-//            return boolval($data['CLOSE_ACCOUNT']);
-//        } else {
-//            // 获取会员所传期数之前的最后一次关停并审核的记录
-//            $data = UserClose::find()->where('USER_ID=:USER_ID AND TYPE=:TYPE AND AUDIT_STATUS=:AUDIT_STATUS AND PERIOD_NUM<=:PERIOD_NUM', [':USER_ID'=>$userId, ':TYPE' => UserClose::TYPE_GT, ':AUDIT_STATUS'=>\Yii::$app->params['auditStatus']['true']['value'], ':PERIOD_NUM'=>$periodNum])->orderBy('AUDITED_AT DESC')->asArray()->one();
-//            if($data) return boolval($data['IS_CLOSE']);
-//            return false;
-//        }
-//    }
-//
-//    /**
-//     * 是否停发状态
-//     * @param $userId
-//     * @param null $periodNum
-//     * @return bool
-//     */
-//    public static function isCloseBonus($userId, $periodNum=null){
-//        if($periodNum === null){
-//            $data = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId], 'CLOSE_BONUS');
-//            return boolval($data['CLOSE_BONUS']);
-//        } else {
-//            // 获取会员所传期数之前的最后一次关停并审核的记录
-//            $data = UserClose::find()->where('USER_ID=:USER_ID AND TYPE=:TYPE AND AUDIT_STATUS=:AUDIT_STATUS AND PERIOD_NUM<=:PERIOD_NUM', [':USER_ID'=>$userId, ':TYPE' => UserClose::TYPE_TF, ':AUDIT_STATUS'=>\Yii::$app->params['auditStatus']['true']['value'], ':PERIOD_NUM'=>$periodNum])->orderBy('AUDITED_AT DESC')->asArray()->one();
-//            if($data) return boolval($data['IS_CLOSE']);
-//            return false;
-//        }
-//    }
-}

+ 0 - 107
common/models/ExcelAddUser.php

@@ -1,107 +0,0 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%EXCEL_ADD_USER}}".
- *
- * @property string $ID
- * @property string $EXCEL_IMPORT_ID 导入记录表ID
- * @property string $USER_NAME 用户名
- * @property string $DEC_LV 会员级别
- * @property string $REAL_NAME 会员姓名
- * @property string $ID_CARD 身份证
- * @property string $MOBILE 手机
- * @property string $TEL 电话
- * @property string $AREA_PROVINCE 省市
- * @property string $AREA_CITY 市区
- * @property string $AREA_COUNTY 区县
- * @property string $ADDRESS 地址
- * @property string $OPEN_BANK 开户银行
- * @property string $BANK_ADDRESS 开户行地址
- * @property string $BANK_NO 银行账号
- * @property string $BANK_PROVINCE 银行省市
- * @property string $BANK_CITY 银行市区
- * @property string $BANK_COUNTY 银行区县
- * @property string $SUB_COM 子公司
- * @property string $IS_DEC 是否报单中心
- * @property string $DEC_ROLE 报单中心级别
- * @property string $DEC_USER_NAME 所属报单中心编号
- * @property string $BIRTHDAY 生日
- * @property string $CON_USER_NAME 接点人
- * @property string $REC_USER_NAME 开拓人
- * @property string $LOCATION 区位
- * @property int $SORT 审核管理员ID
- * @property int $STATUS 审核管理员ID
- * @property string $ERROR_REMARK 审核管理员ID
- * @property int $CREATED_AT 创建时间
- */
-class ExcelAddUser extends \common\components\ActiveRecord
-{
-    const STATUS_UN = 0; //未导入
-    const STATUS_SUCCESS = 1; // 导入成功
-    const STATUS_FAIL = 2; // 导入失败
-
-    /**
-     * {@inheritdoc}
-     */
-    public static function tableName()
-    {
-        return '{{%EXCEL_ADD_USER}}';
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function rules()
-    {
-        return [
-            [['EXCEL_IMPORT_ID', 'SORT', 'CREATED_AT'], 'required'],
-            [['SORT', 'STATUS', 'CREATED_AT'], 'integer'],
-            [['ID', 'EXCEL_IMPORT_ID', 'USER_NAME', 'DEC_LV', 'REAL_NAME', 'ID_CARD', 'MOBILE', 'TEL', 'AREA_PROVINCE', 'AREA_CITY', 'AREA_COUNTY', 'ADDRESS', 'OPEN_BANK', 'BANK_ADDRESS', 'BANK_NO', 'BANK_PROVINCE', 'BANK_CITY', 'BANK_COUNTY', 'SUB_COM', 'IS_DEC', 'DEC_ROLE', 'DEC_USER_NAME', 'BIRTHDAY', 'CON_USER_NAME', 'REC_USER_NAME', 'LOCATION'], 'string', 'max' => 32],
-            [['ERROR_REMARK'], 'string', 'max' => 4000],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'EXCEL_IMPORT_ID' => '导入记录表ID',
-            'USER_NAME' => '用户名',
-            'DEC_LV' => '会员级别',
-            'REAL_NAME' => '会员姓名',
-            'ID_CARD' => '身份证',
-            'MOBILE' => '手机',
-            'TEL' => '电话',
-            'AREA_PROVINCE' => '省市',
-            'AREA_CITY' => '市区',
-            'AREA_COUNTY' => '区县',
-            'ADDRESS' => '地址',
-            'OPEN_BANK' => '开户银行',
-            'BANK_ADDRESS' => '开户行地址',
-            'BANK_NO' => '银行账号',
-            'BANK_PROVINCE' => '银行省市',
-            'BANK_CITY' => '银行市区',
-            'BANK_COUNTY' => '银行区县',
-            'SUB_COM' => '子公司',
-            'IS_DEC' => '是否报单中心',
-            'DEC_ROLE' => '报单中心级别',
-            'DEC_USER_NAME' => '所属报单中心编号',
-            'BIRTHDAY' => '生日',
-            'CON_USER_NAME' => '接点人',
-            'REC_USER_NAME' => '开拓人',
-            'LOCATION' => '区位',
-            'SORT' => '审核管理员ID',
-            'STATUS' => '审核管理员ID',
-            'ERROR_REMARK' => '审核管理员ID',
-            'CREATED_AT' => '创建时间',
-        ];
-    }
-}

+ 0 - 75
common/models/ExcelChangeBalance.php

@@ -1,75 +0,0 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%EXCEL_CHANGE_BALANCE}}".
- *
- * @property string $ID
- * @property string $EXCEL_IMPORT_ID 导入记录表ID
- * @property string $USER_NAME 会员编号
- * @property string $REAL_NAME 会员姓名
- * @property string $TYPE 账户类型
- * @property string $AMOUNT 调整金额
- * @property string $DEAL_TYPE 交易类型
- * @property string $REMARK 备注
- * @property string $REMARK_IS_SHOW 备注显示
- * @property int $SORT 序号
- * @property int $STATUS 状态
- * @property string $ERROR_REMARK 错误记录
- * @property int $CREATED_AT 创建时间
- */
-class ExcelChangeBalance extends \common\components\ActiveRecord
-{
-    /**
-     * {@inheritdoc}
-     */
-    public static function tableName()
-    {
-        return '{{%EXCEL_CHANGE_BALANCE}}';
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function rules()
-    {
-        return [
-            [['EXCEL_IMPORT_ID', 'USER_NAME', 'REAL_NAME', 'TYPE', 'DEAL_TYPE', 'REMARK_IS_SHOW'], 'required'],
-            [['SORT', 'STATUS', 'CREATED_AT'], 'integer'],
-            [['AMOUNT'], 'number'],
-            [['ID', 'EXCEL_IMPORT_ID', 'REAL_NAME'], 'string', 'max' => 32],
-            [['ERROR_REMARK'], 'string', 'max' => 1000],
-            [['USER_NAME'], 'string', 'max' => 16],
-            [['TYPE'], 'string', 'max' => 20],
-            [['DEAL_TYPE'], 'string', 'max' => 128],
-            [['REMARK'], 'string', 'max' => 2000],
-            [['REMARK_IS_SHOW'], 'string', 'max' => 8],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'EXCEL_IMPORT_ID' => '导入记录表ID',
-            'USER_NAME' => '会员编号',
-            'REAL_NAME' => '会员姓名',
-            'TYPE' => '账户类型',
-            'AMOUNT' => '调整金额',
-            'DEAL_TYPE' => '交易类型',
-            'REMARK' => '备注',
-            'REMARK_IS_SHOW' => '备注显示',
-            'SORT' => '序号',
-            'STATUS' => '状态',
-            'ERROR_REMARK' => '错误记录',
-            'CREATED_AT' => '创建时间',
-        ];
-    }
-}

+ 0 - 61
common/models/ExcelImport.php

@@ -1,61 +0,0 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%EXCEL_IMPORT}}".
- *
- * @property string $ID
- * @property string $OPTION_NAME 业务名称
- * @property string $TABLE_NAME 对应的待导入数据表名
- * @property string $UPLOAD_ID 上传文件ID
- * @property int $AUDIT_STATUS 审核状态
- * @property string $IMPORT_ADMIN_ID 导入管理员ID
- * @property string $AUDIT_ADMIN_ID 审核管理员ID
- * @property int $CREATED_AT 创建时间
- * @property int $AUDITED_AT 审核时间
- */
-class ExcelImport extends \common\components\ActiveRecord
-{
-
-    /**
-     * {@inheritdoc}
-     */
-    public static function tableName()
-    {
-        return '{{%EXCEL_IMPORT}}';
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function rules()
-    {
-        return [
-            [['OPTION_NAME', 'IMPORT_ADMIN_ID', 'CREATED_AT'], 'required'],
-            [['AUDIT_STATUS', 'CREATED_AT', 'AUDITED_AT'], 'integer'],
-            [['ID', 'OPTION_NAME', 'TABLE_NAME', 'UPLOAD_ID', 'IMPORT_ADMIN_ID', 'AUDIT_ADMIN_ID'], 'string', 'max' => 32],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'OPTION_NAME' => '业务名称',
-            'TABLE_NAME' => '对应的待导入数据表名',
-            'UPLOAD_ID' => '上传文件ID',
-            'AUDIT_STATUS' => '审核状态',
-            'IMPORT_ADMIN_ID' => '导入管理员ID',
-            'AUDIT_ADMIN_ID' => '审核管理员ID',
-            'CREATED_AT' => '创建时间',
-            'AUDITED_AT' => '审核时间',
-        ];
-    }
-}

+ 0 - 58
common/models/ExcelOrderShop.php

@@ -1,58 +0,0 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%EXCEL_ORDER_SHOP}}".
- *
- * @property string $ID
- * @property int $PERIOD_NUM 期数
- * @property int $ORDER_DAY 日期
- * @property int $ORDER_TYPE 订单类型
- * @property int $STATUS 状态
- * @property int $UPDATED_AT 更新时间
- * @property int $CREATED_AT 创建时间
- */
-class ExcelOrderShop extends \common\components\ActiveRecord
-{
-    /**
-     * {@inheritdoc}
-     */
-    public static function tableName()
-    {
-        return '{{%EXCEL_ORDER_SHOP}}';
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function rules()
-    {
-        return [
-            [['ID', 'STATUS'], 'required'],
-            [['PERIOD_NUM', 'STATUS', 'UPDATED_AT', 'CREATED_AT'], 'integer'],
-            [['ID'], 'string', 'max' => 32],
-            //[['PERIOD_NUM'], 'unique'],
-            //[['ORDER_DAY'], 'unique'],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => Yii::t('app', 'ID'),
-            'PERIOD_NUM' => Yii::t('app', 'Period  Num'),
-            'ORDER_DAY' => Yii::t('app', 'Order Day'),
-            'ORDER_TYPE' => Yii::t('app', 'Order Type'),
-            'STATUS' => Yii::t('app', 'Status'),
-            'UPDATED_AT' => Yii::t('app', 'Updated  At'),
-            'CREATED_AT' => Yii::t('app', 'Created  At'),
-        ];
-    }
-}

+ 0 - 90
common/models/ExcelRegInfo.php

@@ -1,90 +0,0 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%EXCEL_REG_INFO}}".
- *
- * @property string $ID
- * @property string $EXCEL_IMPORT_ID 导入记录表ID
- * @property string $USER_NAME 会员编号
- * @property string $REAL_NAME 会员姓名
- * @property string $ID_CARD 身份证
- * @property string $REG_TYPE 注册类型
- * @property string $REG_NAME 注册名称
- * @property string $CREDIT_CODE 统一社会信用代码
- * @property string $PREMISES 经营场所
- * @property string $REG_EXPIRES 注册有效期
- * @property string $LEGAL_PERSON 法人
- * @property string $OPEN_NAME 企业开户银行
- * @property string $OPEN_BANK 企业开户银行
- * @property string $BANK_ADDRESS 企业开户行地址
- * @property string $BANK_NO 企业银行账号
- * @property string $BANK_PROVINCE 企业银行省市
- * @property string $BANK_CITY 企业银行市区
- * @property string $BANK_COUNTY 企业银行区县
- * @property string $REMARK 备注
- * @property int $SORT 序号
- * @property int $STATUS 状态
- * @property string $ERROR_REMARK 错误备注
- * @property int $CREATED_AT 创建时间
- */
-class ExcelRegInfo extends \common\components\ActiveRecord
-{
-    /**
-     * {@inheritdoc}
-     */
-    public static function tableName()
-    {
-        return '{{%EXCEL_REG_INFO}}';
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function rules()
-    {
-        return [
-            [['EXCEL_IMPORT_ID', 'SORT', 'CREATED_AT'], 'required'],
-            [['SORT', 'STATUS', 'CREATED_AT'], 'integer'],
-            [['ID', 'EXCEL_IMPORT_ID', 'USER_NAME', 'REAL_NAME', 'ID_CARD', 'REG_TYPE', 'BANK_NO', 'BANK_PROVINCE', 'BANK_CITY', 'BANK_COUNTY'], 'string', 'max' => 32],
-            [['REG_NAME', 'CREDIT_CODE', 'PREMISES', 'REG_EXPIRES', 'LEGAL_PERSON', 'OPEN_NAME', 'OPEN_BANK', 'BANK_ADDRESS'], 'string', 'max' => 255],
-            [['REMARK', 'ERROR_REMARK'], 'string', 'max' => 4000],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function attributeLabels()
-    {
-        return [
-            'ID' => 'ID',
-            'EXCEL_IMPORT_ID' => '导入记录表ID',
-            'USER_NAME' => '会员编号',
-            'REAL_NAME' => '会员姓名',
-            'ID_CARD' => '身份证',
-            'REG_TYPE' => '注册类型',
-            'REG_NAME' => '注册名称',
-            'CREDIT_CODE' => '统一社会信用代码',
-            'PREMISES' => '经营场所',
-            'REG_EXPIRES' => '注册有效期',
-            'LEGAL_PERSON' => '法人',
-            'OPEN_NAME' => '企业开户银行',
-            'OPEN_BANK' => '企业开户银行',
-            'BANK_ADDRESS' => '企业开户行地址',
-            'BANK_NO' => '企业银行账号',
-            'BANK_PROVINCE' => '企业银行省市',
-            'BANK_CITY' => '企业银行市区',
-            'BANK_COUNTY' => '企业银行区县',
-            'REMARK' => '备注',
-            'SORT' => '序号',
-            'STATUS' => '状态',
-            'ERROR_REMARK' => '错误备注',
-            'CREATED_AT' => '创建时间',
-        ];
-    }
-}

+ 0 - 73
common/models/ExcelWithdrawPaidFalse.php

@@ -1,73 +0,0 @@
-<?php
-
-namespace common\models;
-
-use Yii;
-
-/**
- * This is the model class for table "{{%EXCEL_WITHDRAW_PAID_FALSE}}".
- *
- * @property string $ID
- * @property string $EXCEL_IMPORT_ID 导入记录表ID
- * @property string $SN 提现流水号
- * @property int $WITHDRAW_PERIOD_NUM 提现期数
- * @property string $PAID_AT 付款日期
- * @property string $PAID_FAIL_REMARK 付款失败原因
- * @property string $USER_NAME 会员编号
- * @property string $REAL_NAME 会员姓名
- * @property string $AMOUNT 实付金额
- * @property string $BANK_REAL_NAME 实时开户名
- * @property string $BANK_NO 实时银行账户
- * @property int $SORT 序号
- * @property int $STATUS 状态
- * @property string $ERROR_REMARK 错误记录
- * @property int $CREATED_AT 创建时间
- */
-class ExcelWithdrawPaidFalse extends \common\components\ActiveRecord {
-    /**
-     * {@inheritdoc}
-     */
-    public static function tableName() {
-        return '{{%EXCEL_WITHDRAW_PAID_FALSE}}';
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function rules() {
-        return [
-            [['EXCEL_IMPORT_ID', 'SN', 'USER_NAME', 'REAL_NAME', 'BANK_REAL_NAME', 'BANK_NO'], 'required'],
-            [['WITHDRAW_PERIOD_NUM', 'SORT', 'STATUS', 'CREATED_AT'], 'integer'],
-            [['AMOUNT'], 'number'],
-            [['ID', 'EXCEL_IMPORT_ID', 'SN', 'REAL_NAME', 'BANK_NO'], 'string', 'max' => 32],
-            [['PAID_FAIL_REMARK', 'ERROR_REMARK'], 'string', 'max' => 1000],
-            [['USER_NAME'], 'string', 'max' => 16],
-            [['PAID_AT'], 'string', 'max' => 32],
-            [['BANK_REAL_NAME'], 'string', 'max' => 255],
-            [['ID'], 'unique'],
-        ];
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function attributeLabels() {
-        return [
-            'ID' => 'ID',
-            'EXCEL_IMPORT_ID' => '导入记录表ID',
-            'SN' => '提现流水号',
-            'WITHDRAW_PERIOD_NUM' => '提现期数',
-            'PAID_AT' => '付款日期',
-            'PAID_FAIL_REMARK' => '付款失败原因',
-            'USER_NAME' => '会员编号',
-            'REAL_NAME' => '会员姓名',
-            'AMOUNT' => '实付金额',
-            'BANK_REAL_NAME' => '实时开户名',
-            'BANK_NO' => '实时银行账户',
-            'SORT' => '序号',
-            'STATUS' => '状态',
-            'ERROR_REMARK' => '错误记录',
-            'CREATED_AT' => '创建时间',
-        ];
-    }
-}

+ 0 - 356
common/models/forms/ConfigForm.php

@@ -1,356 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Date;
-use common\libs\logging\operate\AdminOperate;
-use common\models\Config;
-use yii\db\Exception;
-use yii\helpers\Json;
-
-/**
- * Login form
- */
-class ConfigForm extends Model
-{
-    const BONUS_TO_STRING_FIELD = [
-        //共享奖
-        'shareRecIncomeFrom',
-        'shareIncomeFrom',
-        //管理奖
-        'parentOddIncomeFrom_0',
-        'parentOddIncomeFrom_1',
-        'parentOddIncomeFrom_2',
-        'parentOddIncomeFrom_3',
-
-        //共享奖-复消
-        'fxShareRecIncomeFrom',
-        'fxShareIncomeFrom',
-        //管理奖
-        'fxParentOddIncomeFrom_0',
-        'fxParentOddIncomeFrom_1',
-        'fxParentOddIncomeFrom_2',
-        'fxParentOddIncomeFrom_3',
-        //服务奖
-        'decRoleBonusFrom',
-    ];
-
-    const BONUS_JSON_FIELD = [
-        'jxStandard'
-    ];
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => Config::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            //[['postData'], 'required'],
-        ];
-    }
-
-    public function attributeLabels()
-    {
-        return [
-            //'postData' => '传入数据',
-        ];
-    }
-
-    /**
-     * 更新配置
-     * @return bool|null
-     * @throws Exception
-     */
-    public function updateBase(){
-        if(!$this->validate()){
-            return null;
-        }
-        $configs = Config::find()->where("TYPE='base'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
-        $configNames = [];
-        foreach ($configs as $value){
-            $configNames[] = $value['CONFIG_NAME'];
-        }
-        $beforeData = Config::getConfigByType('base');
-        $this->adminOperateLogger->saveBeforeContent=$beforeData;
-        $postData = \Yii::$app->request->post();
-        $transaction = \Yii::$app->db->beginTransaction();
-        try{
-            foreach ($configs as $key => $value) {
-                if (array_key_exists($key, $postData)) {
-                    if (!$postData[$key]) $postData[$key] = 0;
-                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e){
-            $transaction->rollBack();
-            $this->addError('updateBase', $e->getMessage());
-            return null;
-        }
-        $afterData = Config::getConfigByType('base');
-        $this->adminOperateLogger->saveAfterContent=$afterData;
-        unset($beforeData,$afterData);
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '更新站点设置',
-        ]);
-        return true;
-    }
-
-    /**
-     * 更新奖金配置
-     * @return bool|null
-     * @throws Exception
-     */
-    public function updateBonus(){
-        if(!$this->validate()){
-            return null;
-        }
-        $configs = Config::find()->where("TYPE='bonus'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
-        $configNames = [];
-        foreach ($configs as $value){
-            $configNames[] = $value['CONFIG_NAME'];
-        }
-        $beforeData = Config::getConfigByType('bonus');
-        $this->adminOperateLogger->saveBeforeContent=$beforeData;
-        $postData = \Yii::$app->request->post();
-        $transaction = \Yii::$app->db->beginTransaction();
-        try{
-            foreach ($configs as $key => $value) {
-                if (array_key_exists($key, $postData)) {
-                    if (!$postData[$key]) $postData[$key] = 0;
-                    if( in_array($key, self::BONUS_TO_STRING_FIELD) ) $postData[$key] = implode(",", $postData[$key]);
-                    if( in_array($key, self::BONUS_JSON_FIELD) ) $postData[$key] = JSON::encode($postData[$key]);
-
-                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e){
-            $transaction->rollBack();
-            $this->addError('updateBase', $e->getMessage());
-            return null;
-        }
-        $afterData = Config::getConfigByType('bonus');
-        $this->adminOperateLogger->saveAfterContent=$afterData;
-        unset($beforeData,$afterData);
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '更新奖金配置',
-        ]);
-        return true;
-    }
-
-    /**
-     * 更新短信配置
-     * @return bool|null
-     * @throws Exception
-     */
-    public function updateSms(){
-        if(!$this->validate()){
-            return null;
-        }
-        $configs = Config::find()->where("TYPE='sms'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
-        $configNames = [];
-        foreach ($configs as $value){
-            $configNames[] = $value['CONFIG_NAME'];
-        }
-        $beforeData = Config::getConfigByType('sms');
-        $this->adminOperateLogger->saveBeforeContent=$beforeData;
-        $postData = \Yii::$app->request->post();
-        $transaction = \Yii::$app->db->beginTransaction();
-        try{
-            foreach ($configs as $key => $value) {
-                if (array_key_exists($key, $postData)) {
-                    if (!$postData[$key]) $postData[$key] = 0;
-                    if(is_array($postData[$key])) $postData[$key] = implode(",", $postData[$key]);
-                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e){
-            $transaction->rollBack();
-            $this->addError('updateSms', $e->getMessage());
-            return null;
-        }
-        $afterData = Config::getConfigByType('sms');
-        $this->adminOperateLogger->saveAfterContent=$afterData;
-        unset($beforeData,$afterData);
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '更新短信配置',
-        ]);
-        return true;
-    }
-
-    /**
-     * 更新转账配置
-     * @return bool|null
-     * @throws Exception
-     */
-    public function updateTransfer(){
-        if(!$this->validate()){
-            return null;
-        }
-        $configs = Config::find()->where("TYPE='transfer'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
-        $configNames = [];
-        foreach ($configs as $value){
-            $configNames[] = $value['CONFIG_NAME'];
-        }
-        $beforeData = Config::getConfigByType('transfer');
-        $this->adminOperateLogger->saveBeforeContent=$beforeData;
-        $postData = \Yii::$app->request->post();
-        $transaction = \Yii::$app->db->beginTransaction();
-        try{
-            foreach ($configs as $key => $value) {
-                if (array_key_exists($key, $postData)) {
-                    if (!$postData[$key]) $postData[$key] = 0;
-                    if(is_array($postData[$key])) $postData[$key] = Json::encode($postData[$key]);
-                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e){
-            $transaction->rollBack();
-            $this->addError('updateTransfer', $e->getMessage());
-            return null;
-        }
-        $afterData = Config::getConfigByType('transfer');
-        $this->adminOperateLogger->saveAfterContent=$afterData;
-        unset($beforeData,$afterData);
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '更新转账配置',
-        ]);
-        return true;
-    }
-
-    /**
-     * 更新分数配置
-     * @return bool|null
-     * @throws Exception
-     */
-    public function updateScore(){
-        if(!$this->validate()){
-            return null;
-        }
-        $configs = Config::find()->where("TYPE='score'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
-        $configNames = [];
-        foreach ($configs as $value){
-            $configNames[] = $value['CONFIG_NAME'];
-        }
-        $beforeData = Config::getConfigByType('score');
-        $this->adminOperateLogger->saveBeforeContent=$beforeData;
-        $postData = \Yii::$app->request->post();
-        $transaction = \Yii::$app->db->beginTransaction();
-        try{
-            foreach ($configs as $key => $value) {
-                if (array_key_exists($key, $postData)) {
-                    if (!$postData[$key]) $postData[$key] = 0;
-                    if(is_array($postData[$key])) $postData[$key] = Json::encode($postData[$key]);
-                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e){
-            $transaction->rollBack();
-            $this->addError('updateScore', $e->getMessage());
-            return null;
-        }
-        $afterData = Config::getConfigByType('score');
-        $this->adminOperateLogger->saveAfterContent=$afterData;
-        unset($beforeData,$afterData);
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '更新分数配置',
-        ]);
-        return true;
-    }
-
-    /**
-     * 更新其他配置
-     * @return bool|null
-     * @throws Exception
-     */
-    public function updateOther(){
-        if(!$this->validate()){
-            return null;
-        }
-        $configs = Config::find()->where("TYPE='other'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
-        $configNames = [];
-        foreach ($configs as $value){
-            $configNames[] = $value['CONFIG_NAME'];
-        }
-        $beforeData = Config::getConfigByType('other');
-        $this->adminOperateLogger->saveBeforeContent=$beforeData;
-        $postData = \Yii::$app->request->post();
-        $transaction = \Yii::$app->db->beginTransaction();
-        try{
-            foreach ($configs as $key => $value) {
-                if (array_key_exists($key, $postData)) {
-                    if (!$postData[$key]) $postData[$key] = 0;
-                    if(is_array($postData[$key])) $postData[$key] = implode(",", $postData[$key]);
-                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e){
-            $transaction->rollBack();
-            $this->addError('updateOther', $e->getMessage());
-            return null;
-        }
-        $afterData = Config::getConfigByType('other');
-        $this->adminOperateLogger->saveAfterContent=$afterData;
-        unset($beforeData,$afterData);
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '更新其他配置',
-        ]);
-        return true;
-    }
-
-    /**
-     * 更新汇率配置
-     * @return bool|null
-     */
-    public function updateExchangeRate(): ?bool
-    {
-        if(!$this->validate()){
-            return null;
-        }
-
-        $beforeData = Config::getConfigByType('exchangeRate');
-        $this->adminOperateLogger->saveBeforeContent = $beforeData;
-
-        $postData = \Yii::$app->request->post();
-        $transaction = \Yii::$app->db->beginTransaction();
-        try{
-            Config::updateAll(['VALUE' => $postData['VALUE'], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => 'exchangeRate']);
-
-            if ($postData['synchronize']) {
-                unset($postData['synchronize']);
-                // 异步属性商品价格
-                $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle('config/update-exchange-rate', $postData);
-                if($taskKey === false){
-                    throw new Exception('请求异步服务器失败');
-                }
-            }
-
-            $transaction->commit();
-        } catch (Exception $e){
-            $transaction->rollBack();
-            $this->addError('updateExchangeRate', $e->getMessage());
-            return null;
-        }
-
-        $afterData = Config::getConfigByType('exchangeRate');
-        $this->adminOperateLogger->saveAfterContent = $afterData;
-        unset($beforeData,$afterData);
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '更新汇率配置',
-        ]);
-
-        return true;
-    }
-}

+ 0 - 241
common/models/forms/ExcelOrderDecForm.php

@@ -1,241 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\helpers\snowflake\SnowFake;
-use common\models\ExcelOrderShop;
-use common\models\OrderDec;
-use common\models\OrderGoodsDec;
-use common\models\Period;
-use common\models\User;
-use common\models\UserInfo;
-use Yii;
-use yii\base\Exception;
-
-class ExcelOrderDecForm extends \common\components\ActiveRecord
-{
-    CONST EXCEL_ORDER_SHOP_FIELD = [
-        '会员编号' => 'USER_NAME',
-//        '报单中心' => 'DEC_USER_NAME',
-//        '订单号' => 'ORDER_SN',
-        '订单状态' => 'STATUS',
-        '收货人' => 'CONSIGNEE',
-        '联系方式1' => 'MOBILE',
-        '省' => 'PROVINCE',
-        '市' => 'CITY',
-        '区' => 'COUNTY',
-        '详细地址' => 'ADDRESS',
-        '期数' => 'PERIOD_NUM',
-        '订单类型' => 'ORDER_TYPE',
-        '创建时间' => 'CREATED_AT',
-        '支付时间' => 'PAY_AT',
-        '发货时间' => 'DELIVERY_AT',
-        '运费' => 'FREIGHT',
-        '快递公司' => 'EXPRESS_COMPANY',
-        '快递单号' => 'ORDER_TRACK_NO',
-        '发货方式' => 'EXPRESS_TYPE',
-        '会员备注' => 'FRONT_REMARK',
-        '发货仓' => 'WAREHOUSE',
-        '发货状态' => 'DELIVERY_STATUS',
-    ];
-
-    CONST EXCEL_ORDER_SHOP_GOODS_FIELD = [
-        '订单号' => 'ORDER_SN',
-//        '订单状态' => 'STATUS',
-        '存货编码' => 'SKU_CODE',
-        '存货名称' => 'GOODS_TITLE',
-        '数量' => 'BUY_NUMS',
-        '商品单价' => 'PRICE',
-        '商品金额' => 'REAL_PRICE',
-        '商品BV' => 'PV',
-        'BV合计' => 'REAL_PV',
-        '期数' => 'PERIOD_NUM',
-    ];
-
-    private $_isSentMaxPeriodNum = 0;
-
-    /**
-     * 初始化最小未挂网的期数
-     */
-    public function initNoClosedMinPeriodNum() {
-        $periodModel = Period::instance();
-        $this->_isSentMaxPeriodNum = $periodModel->getMaxIsSentPeriodNum();
-    }
-
-    /**
-     * 导入excel数据
-     * @param $excelData
-     * @param $orderDay
-     * @param $payType
-     * @return bool
-     * @throws \Exception
-     */
-    public function run($excelData,$orderDay,$payType) {
-        if( !$excelData ) return false;
-        $this->initNoClosedMinPeriodNum();
-
-        foreach ($excelData as $everyData) {
-            if( !$everyData ) continue;
-
-            $formatOrderData = [];
-            $formatOrderGoodsData = [];
-            foreach ($everyData as $key => $value) {
-                if(isset(self::EXCEL_ORDER_SHOP_FIELD[$key])) {
-                    $formatOrderData[self::EXCEL_ORDER_SHOP_FIELD[$key]] = $value;
-                }
-
-                if(isset(self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key])) {
-                    $formatOrderGoodsData[self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key]] = $value;
-                }
-            }
-
-            if( !isset($formatOrderGoodsData['ORDER_SN']) ) {
-                throw new \Exception('缺少订单编号字段');
-            }
-
-            if ( !isset($formatOrderData['PERIOD_NUM']) ) {
-                throw new \Exception('缺少期数字段');
-            }
-
-            if ( $formatOrderData['PERIOD_NUM'] <= $this->_isSentMaxPeriodNum ) {
-                throw new \Exception(sprintf('不可以导入已经挂网期数【%s】的数据', $formatOrderData['PERIOD_NUM']));
-            }
-
-            //判断商城订单是表中是否已经存在该订单
-            $one = OrderDec::find()->select(["USER_ID", "PERIOD_NUM", "SN", "ORDER_AMOUNT", "PV", "PAY_AMOUNT", "PAY_PV"])->where('SN=:SN', ['SN' => $formatOrderGoodsData['ORDER_SN']])->asArray()->one();
-            if ($one) {
-                if ( $one['PERIOD_NUM'] != $formatOrderData['PERIOD_NUM'] ) {
-                    throw new \Exception(sprintf('订单号【%s】重复不可以导入', $formatOrderGoodsData['ORDER_SN']));
-                }
-
-                OrderDec::updateAllCounters([
-                    'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
-                ], 'SN=:SN', [
-                    'SN' => $formatOrderGoodsData['ORDER_SN']
-                ]);
-
-                //会员状态激活
-                $amount = $one['ORDER_AMOUNT'] + $formatOrderGoodsData['REAL_PRICE'];
-                if ($amount >= 300) {
-                    $userStatus = User::find()->select(["ID", "STATUS"])->where('ID=:ID', ['ID' => $one['USER_ID']])->asArray()->one();
-                    if ($userStatus && $userStatus['STATUS'] == 0) {
-                        User::updateAll(['STATUS' => 1], 'ID=:ID', ['ID' => $one['USER_ID']]);
-                    }
-                }
-                unset($amount, $userStatus);
-
-            } else {
-                $userInfoArr = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $formatOrderData['USER_NAME']], 'USER_ID');
-                if (!isset($userInfoArr['USER_ID']) || !$userInfoArr['USER_ID']) {
-//                    echo $formatOrderData['USER_NAME'] . PHP_EOL;
-                    continue;
-                }
-                //insertOrderDec
-                $orderShopInsertData = array_merge($formatOrderData, [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'SN' => $formatOrderGoodsData['ORDER_SN'],
-                    'USER_ID' => $userInfoArr['USER_ID'],
-                    'ORDER_TYPE' => 'ZC',
-                    'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AT' => strtotime(self::excelTime($formatOrderData['PAY_AT'])),
-                    'DELIVERY_AT' => strtotime(self::excelTime($formatOrderData['DELIVERY_AT'])),
-                    'CREATED_AT' => strtotime(self::excelTime($formatOrderData['CREATED_AT'])),
-                    'CREATE_USER' => $formatOrderData['USER_NAME'],
-                    'PAY_TYPE' => $payType,//@todo
-                    'STATUS' => 1,
-                    'P_CALC_MONTH' => self::excelTime($formatOrderData['CREATED_AT'],'Y-m-d'),
-                    'DELIVERY_STATUS' => $formatOrderData['DELIVERY_STATUS'] === '已发货' ? 1 : 0,
-                    'ORDER_DAY' => $orderDay,
-                ]);
-                OrderDec::insertOne($orderShopInsertData);
-
-                //会员状态激活
-                if ($orderShopInsertData['ORDER_AMOUNT'] >= 300) {
-                    $userStatus = User::find()->select(["ID", "STATUS"])->where('ID=:ID', ['ID' => $userInfoArr['USER_ID']])->asArray()->one();
-                    if ($userStatus && $userStatus['STATUS'] == 0) {
-                        User::updateAll(['STATUS' => 1], 'ID=:ID', ['ID' => $userInfoArr['USER_ID']]);
-                    }
-                }
-                unset($orderShopInsertData, $userInfoArr, $userStatus);
-            }
-
-            $decGoodsInsertData[] = array_merge($formatOrderGoodsData, [
-                'ORDER_DAY' => $orderDay,
-                'P_CALC_MONTH' => self::excelTime($formatOrderData['CREATED_AT'],'Y-m-d')
-            ]);
-            unset($formatOrderData, $formatOrderGoodsData, $everyData);
-        }
-
-        if( isset($decGoodsInsertData) && $decGoodsInsertData ) OrderGoodsDec::batchInsert($decGoodsInsertData);
-        unset($newStartRow, $goodsInsertData,$decGoodsInsertData);
-
-        return true;
-    }
-
-    /**
-     * 检测导入状态
-     * @param $orderDay
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public function checkStatus($orderDay) {
-//        if( !$periodNum ) {
-//            throw new Exception('期数不能为空');
-//        }
-        $periodData = Period::getPeriodFromTime(strtotime($orderDay));
-        if(!$periodData){
-            throw new Exception('期数有误');
-        }
-        $periodNum = $periodData['PERIOD_NUM'];
-        //检查是否已经导入过了
-        $excelPeriodData = ExcelOrderShop::find()->where("ORDER_DAY=:ORDER_DAY AND ORDER_TYPE='ZC'", [':ORDER_DAY'=>$orderDay])->asArray()->one();
-        if( !$excelPeriodData ) {
-            ExcelOrderShop::insertOne(
-                [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'PERIOD_NUM' => $periodNum,
-                    'ORDER_DAY' => $orderDay,
-                    'ORDER_TYPE' => 'ZC',
-                    'STATUS' => 0,
-                    'CREATED_AT' => Date::nowTime(),
-                ]
-            );
-        }
-
-//        if( $excelPeriodData['STATUS'] == 1 ) {
-//            throw new Exception(sprintf('%s订单已经导入过了,不可以重复导入', $orderDay));
-//        }
-
-        //清空已经导入的数据
-        $this->_clearPeriodOrder($orderDay);
-    }
-
-    protected function _clearPeriodOrder($orderDay) {
-        OrderDec::pageDeleteAll("ORDER_DAY='".$orderDay."'");
-        OrderGoodsDec::pageDeleteAll("ORDER_DAY='".$orderDay."'");
-    }
-
-    public function finished($orderDay) {
-        if( !$orderDay ) return false;
-
-        ExcelOrderShop::updateAll(['STATUS' => 1], "ORDER_DAY=:ORDER_DAY AND ORDER_TYPE='ZC'", [':ORDER_DAY'=>$orderDay]);
-        return true;
-    }
-
-    public function excelTime($orderDay,$format='Y-m-d H:i:s') {
-        if(is_numeric($orderDay)){
-            $t1 = intval(($orderDay - 25569) * 3600 * 24);
-            $orderDay=gmdate($format,$t1);
-        }
-        return $orderDay;
-    }
-
-
-
-}

+ 0 - 258
common/models/forms/ExcelOrderShopForm.php

@@ -1,258 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\helpers\snowflake\SnowFake;
-use common\models\ExcelOrderShop;
-use common\models\OrderGoodsShop;
-use common\models\OrderShop;
-use common\models\Period;
-use common\models\User;
-use common\models\UserInfo;
-use Yii;
-use yii\base\Exception;
-
-class ExcelOrderShopForm extends \common\components\ActiveRecord
-{
-    CONST EXCEL_ORDER_SHOP_FIELD = [
-        '会员编号' => 'USER_NAME',
-//        '报单中心' => 'DEC_USER_NAME',
-//        '订单号' => 'ORDER_SN',
-        '订单状态' => 'STATUS',
-        '收货人' => 'CONSIGNEE',
-        '联系方式1' => 'MOBILE',
-        '省' => 'PROVINCE',
-        '市' => 'CITY',
-        '区' => 'COUNTY',
-        '详细地址' => 'ADDRESS',
-        '期数' => 'PERIOD_NUM',
-        '订单类型' => 'ORDER_TYPE',
-        '创建时间' => 'CREATED_AT',
-        '支付时间' => 'PAY_AT',
-        '发货时间' => 'DELIVERY_AT',
-        '运费' => 'FREIGHT',
-        '快递公司' => 'EXPRESS_COMPANY',
-        '快递单号' => 'ORDER_TRACK_NO',
-        '发货方式' => 'EXPRESS_TYPE',
-        '会员备注' => 'FRONT_REMARK',
-        '发货仓' => 'WAREHOUSE',
-        '发货状态' => 'DELIVERY_STATUS',
-    ];
-
-    CONST EXCEL_ORDER_SHOP_GOODS_FIELD = [
-        '订单号' => 'ORDER_SN',
-//        '订单状态' => 'STATUS',
-        '存货编码' => 'SKU_CODE',
-        '存货名称' => 'GOODS_TITLE',
-        '数量' => 'BUY_NUMS',
-        '商品单价' => 'PRICE',
-        '商品金额' => 'REAL_PRICE',
-        '商品BV' => 'PV',
-        'BV合计' => 'REAL_PV',
-        '期数' => 'PERIOD_NUM',
-    ];
-
-    private $_isSentMaxPeriodNum = 0;
-
-    /**
-     * 初始化最小未挂网的期数
-     */
-    public function initNoClosedMinPeriodNum() {
-        $periodModel = Period::instance();
-        $this->_isSentMaxPeriodNum = $periodModel->getMaxIsSentPeriodNum();
-    }
-
-
-    /**
-     * 导入excel数据
-     * @param $excelData
-     * @param $orderDay
-     * @param $payType
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function run($excelData,$orderDay,$payType) {
-        if( !$excelData ) return false;
-        $this->initNoClosedMinPeriodNum();
-
-        foreach ($excelData as $everyData) {
-            if( !$everyData ) continue;
-
-            $formatOrderData = [];
-            $formatOrderGoodsData = [];
-            foreach ($everyData as $key => $value) {
-                if(isset(self::EXCEL_ORDER_SHOP_FIELD[$key])) {
-                    $formatOrderData[self::EXCEL_ORDER_SHOP_FIELD[$key]] = $value;
-                }
-
-                if(isset(self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key])) {
-                    $formatOrderGoodsData[self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key]] = $value;
-                }
-            }
-
-            if( !isset($formatOrderGoodsData['ORDER_SN']) ) {
-                throw new \Exception('缺少订单编号字段');
-            }
-
-            if ( !isset($formatOrderData['PERIOD_NUM']) ) {
-                throw new \Exception('缺少期数字段');
-            }
-
-            if ( $formatOrderData['PERIOD_NUM'] <= $this->_isSentMaxPeriodNum ) {
-                throw new \Exception(sprintf('不可以导入已经挂网期数【%s】的数据', $formatOrderData['PERIOD_NUM']));
-            }
-
-            //判断商城订单是表中是否已经存在该订单
-            $one = OrderShop::find()->select(["USER_ID", "PERIOD_NUM", "SN", "ORDER_AMOUNT", "PV", "PAY_AMOUNT", "PAY_PV"])->where('SN=:SN', ['SN' => $formatOrderGoodsData['ORDER_SN']])->asArray()->one();
-            if ($one) {
-
-                if ( $one['PERIOD_NUM'] != $formatOrderData['PERIOD_NUM'] ) {
-                    throw new \Exception(sprintf('订单号【%s】重复不可以导入', $formatOrderGoodsData['ORDER_SN']));
-                }
-
-                OrderShop::updateAllCounters([
-                    'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
-                ], 'SN=:SN', [
-                    'SN' => $formatOrderGoodsData['ORDER_SN']
-                ]);
-
-                //会员状态激活
-                $amount = $one['ORDER_AMOUNT'] + $formatOrderGoodsData['REAL_PRICE'];
-                if ($amount >= 300) {
-                    $userStatus = User::find()->select(["ID", "STATUS"])->where('ID=:ID', ['ID' => $one['USER_ID']])->asArray()->one();
-                    if ($userStatus && $userStatus['STATUS'] == 0) {
-                        User::updateAll(['STATUS' => 1], 'ID=:ID', ['ID' => $one['USER_ID']]);
-                    }
-                }
-                unset($amount, $userStatus);
-
-            } else {
-                $userInfoArr = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $formatOrderData['USER_NAME']], 'USER_ID');
-                if (!isset($userInfoArr['USER_ID']) || !$userInfoArr['USER_ID']) {
-//                    echo $formatOrderData['USER_NAME'] . PHP_EOL;
-                    continue;
-                }
-
-                //insertOrderShop
-                $orderShopInsertData = array_merge($formatOrderData, [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'SN' => $formatOrderGoodsData['ORDER_SN'],
-                    'USER_ID' => $userInfoArr['USER_ID'],
-                    'ORDER_TYPE' => 'FX',
-                    'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AT' => strtotime(self::excelTime($formatOrderData['PAY_AT'])),
-                    'DELIVERY_AT' => strtotime(self::excelTime($formatOrderData['DELIVERY_AT'])),
-                    'CREATED_AT' => strtotime(self::excelTime($formatOrderData['CREATED_AT'])),
-                    'CREATE_USER' => $formatOrderData['USER_NAME'],
-                    'PAY_TYPE' => $payType,//@todo
-                    'STATUS' => 1,
-                    'P_CALC_MONTH' => self::excelTime($formatOrderData['CREATED_AT'],'Y-m-d'),
-                    'DELIVERY_STATUS' => $formatOrderData['DELIVERY_STATUS'] === '已发货' ? 1 : 0,
-                    'ORDER_DAY' => $orderDay,
-                ]);
-                OrderShop::insertOne($orderShopInsertData);
-
-                //会员状态激活
-                if ($orderShopInsertData['ORDER_AMOUNT'] >= 300) {
-                    $userStatus = User::find()->select(["ID", "STATUS"])->where('ID=:ID', ['ID' => $userInfoArr['USER_ID']])->asArray()->one();
-                    if ($userStatus && $userStatus['STATUS'] == 0) {
-                        User::updateAll(['STATUS' => 1], 'ID=:ID', ['ID' => $userInfoArr['USER_ID']]);
-                    }
-                }
-
-                unset($orderShopInsertData, $userInfoArr, $userStatus);
-            }
-            $goodsInsertData[] = array_merge($formatOrderGoodsData, [
-                'ORDER_DAY' => $orderDay,
-                'PAY_TYPE' => $payType,
-                'P_CALC_MONTH' => self::excelTime($formatOrderData['CREATED_AT'],'Y-m-d')
-            ]);
-            unset($formatOrderData, $formatOrderGoodsData, $everyData);
-
-        }
-
-        if( isset($goodsInsertData) && $goodsInsertData ) OrderGoodsShop::batchInsert($goodsInsertData);
-        unset($newStartRow, $goodsInsertData,$decGoodsInsertData);
-
-        return true;
-    }
-
-    /**
-     * 检测导入状态
-     * @param $orderDay
-     * @param $orderType
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public function checkStatus($orderDay,$orderType) {
-//        if( !$periodNum ) {
-//            throw new Exception('期数不能为空');
-//        }
-        $periodData = Period::getPeriodFromTime(strtotime($orderDay));
-        if(!$periodData){
-            throw new Exception('期数有误');
-        }
-        $periodNum = $periodData['PERIOD_NUM'];
-        //检查是否已经导入过了
-        //$excelPeriodData = ExcelOrderShop::find()->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM'=>$periodNum])->asArray()->one();
-        if($orderType=='cash'){
-            $ot = 'FX';
-        }else{
-            $ot = 'PT';
-        }
-        $excelPeriodData = ExcelOrderShop::find()->where("ORDER_DAY=:ORDER_DAY AND ORDER_TYPE=:ORDER_TYPE", [':ORDER_DAY'=>$orderDay,':ORDER_TYPE'=>$ot])->asArray()->one();
-        if( !$excelPeriodData ) {
-            ExcelOrderShop::insertOne(
-                [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'PERIOD_NUM' => $periodNum,
-                    'ORDER_DAY' => $orderDay,
-                    'ORDER_TYPE' => $ot,
-                    'STATUS' => 0,
-                    'CREATED_AT' => Date::nowTime(),
-                ]
-            );
-        }
-//            if( $excelPeriodData['STATUS'] == 1 ) {
-//                throw new Exception(sprintf('%s订单已经导入过了,不可以重复导入', $orderDay));
-//            }
-
-
-        //清空已经导入的数据
-        $this->_clearPeriodOrder($orderDay,$orderType);
-    }
-
-    protected function _clearPeriodOrder($orderDay,$orderType) {
-        OrderShop::pageDeleteAll("ORDER_DAY='".$orderDay."' and PAY_TYPE='".$orderType."'");
-        OrderGoodsShop::pageDeleteAll("ORDER_DAY='".$orderDay."' and PAY_TYPE='".$orderType."'");
-    }
-
-    public function finished($orderDay,$orderType) {
-        if( !$orderDay ) return false;
-
-        if($orderType=='cash'){
-            $ot = 'FX';
-        }else{
-            $ot = 'PT';
-        }
-        ExcelOrderShop::updateAll(['STATUS' => 1], "ORDER_DAY=:ORDER_DAY AND ORDER_TYPE=:ORDER_TYPE", [':ORDER_DAY'=>$orderDay,':ORDER_TYPE'=>$ot]);
-        return true;
-    }
-
-    public function excelTime($orderDay,$format='Y-m-d H:i:s') {
-        if(is_numeric($orderDay)){
-            $t1 = intval(($orderDay - 25569) * 3600 * 24);
-            $orderDay=gmdate($format,$t1);
-        }
-        return $orderDay;
-    }
-
-
-
-}

+ 0 - 169
common/models/forms/ExcelOrderStandardForm.php

@@ -1,169 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\helpers\snowflake\SnowFake;
-use common\models\ExcelOrderShop;
-use common\models\OrderGoodsShop;
-use common\models\OrderShop;
-use common\models\OrderStandard;
-use common\models\OrderStandardGoods;
-use common\models\Period;
-use common\models\User;
-use common\models\UserInfo;
-use Yii;
-use yii\base\Exception;
-
-class ExcelOrderStandardForm extends \common\components\ActiveRecord
-{
-    CONST EXCEL_ORDER_SHOP_FIELD = [
-        '会员编号' => 'USER_NAME',
-//        '报单中心' => 'DEC_USER_NAME',
-//        '订单号' => 'ORDER_SN',
-        '订单状态' => 'STATUS',
-        '收货人' => 'CONSIGNEE',
-        '联系方式1' => 'MOBILE',
-        '省' => 'PROVINCE',
-        '市' => 'CITY',
-        '区' => 'COUNTY',
-        '详细地址' => 'ADDRESS',
-        '期数' => 'PERIOD_NUM',
-        '订单类型' => 'ORDER_TYPE',
-        '创建时间' => 'CREATED_AT',
-        '支付时间' => 'PAY_AT',
-        '发货时间' => 'DELIVERY_AT',
-        '运费' => 'FREIGHT',
-        '快递公司' => 'EXPRESS_COMPANY',
-        '快递单号' => 'ORDER_TRACK_NO',
-        '发货方式' => 'EXPRESS_TYPE',
-        '会员备注' => 'FRONT_REMARK',
-        '发货仓' => 'WAREHOUSE',
-        '发货状态' => 'DELIVERY_STATUS',
-    ];
-
-    CONST EXCEL_ORDER_SHOP_GOODS_FIELD = [
-        '订单号' => 'ORDER_SN',
-//        '订单状态' => 'STATUS',
-        '存货编码' => 'SKU_CODE',
-        '存货名称' => 'GOODS_TITLE',
-        '数量' => 'BUY_NUMS',
-        '商品单价' => 'PRICE',
-        '商品金额' => 'REAL_PRICE',
-        '商品PV' => 'PV',
-        'PV合计' => 'REAL_PV',
-        '期数' => 'PERIOD_NUM',
-    ];
-
-    /**
-     * 导入excel数据
-     * @param $excelData
-     * @param $orderMonth
-     * @param $payType
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public function run($excelData,$orderMonth,$payType) {
-        if( !$excelData ) return false;
-        foreach ($excelData as $everyData) {
-            if( !$everyData ) continue;
-
-            $formatOrderData = [];
-            $formatOrderGoodsData = [];
-            foreach ($everyData as $key => $value) {
-                if(isset(self::EXCEL_ORDER_SHOP_FIELD[$key])) {
-                    $formatOrderData[self::EXCEL_ORDER_SHOP_FIELD[$key]] = $value;
-                }
-
-                if(isset(self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key])) {
-                    $formatOrderGoodsData[self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key]] = $value;
-                }
-            }
-
-            if( !isset($formatOrderGoodsData['ORDER_SN']) ) continue;
-
-            //判断商城订单是表中是否已经存在该订单
-            $one = OrderStandard::find()->select(["USER_ID", "SN", "ORDER_AMOUNT", "PV", "PAY_AMOUNT", "PAY_PV"])->where('SN=:SN', ['SN' => $formatOrderGoodsData['ORDER_SN']])->asArray()->one();
-            if ($one) {
-                OrderStandard::updateAllCounters([
-                    'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
-                ], 'SN=:SN', [
-                    'SN' => $formatOrderGoodsData['ORDER_SN']
-                ]);
-            } else {
-                $userInfoArr = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $formatOrderData['USER_NAME']], 'USER_ID');
-                if (!isset($userInfoArr['USER_ID']) || !$userInfoArr['USER_ID']) {
-//                    echo $formatOrderData['USER_NAME'] . PHP_EOL;
-                    continue;
-                }
-
-                //insertOrderShop
-                $orderShopInsertData = array_merge($formatOrderData, [
-                    'ID' => SnowFake::instance()->generateId(),
-                    'SN' => $formatOrderGoodsData['ORDER_SN'],
-                    'USER_ID' => $userInfoArr['USER_ID'],
-                    'ORDER_TYPE' => 'FX',
-                    'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                    'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
-                    'PAY_AT' => strtotime(self::excelTime($formatOrderData['PAY_AT'])),
-                    'DELIVERY_AT' => strtotime(self::excelTime($formatOrderData['DELIVERY_AT'])),
-                    'CREATED_AT' => strtotime(self::excelTime($formatOrderData['CREATED_AT'])),
-                    'CREATE_USER' => $formatOrderData['USER_NAME'],
-                    'PAY_TYPE' => $payType,//@todo
-                    'STATUS' => 1,
-                    'DELIVERY_STATUS' => $formatOrderData['DELIVERY_STATUS'] === '已发货' ? 1 : 0,
-                    'CALC_MONTH' => $this->_getCalcMonth($orderMonth),
-                ]);
-                OrderStandard::insertOne($orderShopInsertData);
-            }
-            $goodsInsertData[] = array_merge($formatOrderGoodsData, [
-                'CALC_MONTH' => $this->_getCalcMonth($orderMonth),
-                'PAY_TYPE' => $payType,
-            ]);
-            unset($formatOrderData, $formatOrderGoodsData, $everyData);
-
-        }
-
-        if( isset($goodsInsertData) && $goodsInsertData ) OrderStandardGoods::batchInsert($goodsInsertData);
-        unset($newStartRow, $goodsInsertData,$decGoodsInsertData);
-
-        return true;
-    }
-
-    /**
-     * 检测导入状态
-     * @param $orderMonth
-     */
-    public function checkStatus($orderMonth) {
-        //清空已经导入的数据
-        $this->_clearPeriodOrder($orderMonth);
-    }
-
-    protected function _clearPeriodOrder($orderMonth) {
-        OrderStandard::pageDeleteAll("CALC_MONTH=".$this->_getCalcMonth($orderMonth));
-        OrderStandardGoods::pageDeleteAll("CALC_MONTH=".$this->_getCalcMonth($orderMonth));
-    }
-
-    protected function _getCalcMonth($orderMonth) {
-        return date('Ym', strtotime($orderMonth.'-01'));
-    }
-
-    public function excelTime($orderDay,$format='Y-m-d H:i:s') {
-        if(is_numeric($orderDay)){
-            $t1 = intval(($orderDay - 25569) * 3600 * 24);
-            $orderDay=gmdate($format,$t1);
-        }
-        return $orderDay;
-    }
-
-    public function finished($orderMonth) {
-        return true;
-    }
-
-
-
-}

+ 0 - 480
common/models/forms/OrderDeleteForm.php

@@ -1,480 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\snowflake\SnowFake;
-use common\helpers\user\Balance;
-use common\helpers\user\Cash;
-use common\helpers\user\Info;
-use common\libs\logging\operate\AdminOperate;
-use common\models\ApproachDecOrder;
-use common\models\ApproachOrder;
-use common\models\DealType;
-use common\models\DecOrder;
-use common\models\Order;
-use common\models\OrderGoods;
-use common\models\Period;
-use common\models\ReceiveAddress;
-use common\models\Region;
-use common\models\ReturnOrder;
-use common\models\ShopGoods;
-use common\models\User;
-use common\models\UserBonus;
-use common\models\UserNetwork;
-use common\models\UserWallet;
-use yii\base\Exception;
-
-/**
- * 删除订单
- */
-class OrderDeleteForm extends Model
-{
-    public $orderSn;
-
-    /**
-     * @var Order
-     */
-    private $_model;
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['orderSn'], 'trim'],
-            [['orderSn'], 'required'],
-            [['orderSn'], 'checkOrderType'],
-        ];
-    }
-
-    public function attributeLabels()
-    {
-        return [
-            'orderSn' => '订单号',
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios()
-    {
-        $parentScenarios =  parent::scenarios();
-        $customScenarios = [
-            // // 管理员发货
-            // 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
-            // // 会员确认收货
-            // 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
-            // // 管理员修改订单状态
-            // 'adminStatus' => ['sn', 'status'],
-            // // 管理员修改备注
-            // 'adminRemark' => ['sn', 'remark'],
-            // // 会员下单
-            // 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword'],
-            // // 帮会员复消下单
-            // 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    /**
-     * @throws Exception
-     */
-    public function returnOrder() {
-        if(!$this->validate()){
-            return null;
-        }
-        $sn = $this->orderSn;
-        // 获取订单详情
-        $orderInfo = Order::findUseDbCalc()
-        ->select('ID,DEC_SN,SN,USER_ID,ORDER_TYPE,IS_DELETE,PAY_AMOUNT,PAY_TYPE,ORDER_AMOUNT,USER_NAME,PV,PAY_PV,PERIOD_NUM,PROVINCE,CITY,COUNTY,ADDRESS,STATUS,NOTE')
-        ->where("SN=:SN", [':SN' => $sn])
-        ->asArray()
-        ->one();
-
-        $approachOrderInfo = [];
-        // 如果是PayStack支付,订单是未支付状态,则去中间表查询,如果两个表都没有数据,订单不存在
-        if (!$orderInfo) {
-            $approachOrderInfo = ApproachOrder::findUseDbCalc()
-                ->select('ID,DEC_SN,SN,USER_ID,ORDER_TYPE,IS_DELETE,PAY_AMOUNT,PAY_TYPE,ORDER_AMOUNT,USER_NAME,PV,PAY_PV,PERIOD_NUM,PROVINCE,CITY,COUNTY,ADDRESS,STATUS,NOTE')
-                ->where("SN=:SN", [':SN' => $sn])
-                ->asArray()
-                ->one();
-        }
-        if (!$orderInfo && !$approachOrderInfo) {
-            throw new Exception('订单不存在');
-        }
-
-        $orderInfo = $orderInfo ?: $approachOrderInfo;
-
-        // 如果会员已经是锁定状态了,删除订单的时候,是否还要退还金额
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $userId = $orderInfo['USER_ID'];
-            $decInfo = [];
-            $isLock = 0 ; // 是否锁定会员单
-            // 如果是注册订单,则删除订单并退还金额,然后再冻结用户
-            if ($orderInfo['ORDER_TYPE'] == 'ZC') {
-                // 查询报单数据,因为如果是报单,则要退还给报单中心
-                if (!$approachOrderInfo) {
-                    $decInfo = DecOrder::findUseDbCalc()
-                        ->select('USER_ID,TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,ORI_LV,UPGRADE_LV')
-                        ->where("ORDER_SN=:ORDER_SN", [':ORDER_SN' => $sn])
-                        ->asArray()
-                        ->one();
-                    // 删除报单
-                    $delDecOrder = DecOrder::updateAll(
-                        ['IS_DEL'=>1, 'DELETED_AT'=>Date::nowTime()],
-                        'ORDER_SN=:ORDER_SN',
-                        ['ORDER_SN'=>$sn]
-                    );
-                } else {
-                    $decInfo = ApproachDecOrder::findUseDbCalc()
-                        ->select('USER_ID,TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,ORI_LV,UPGRADE_LV')
-                        ->where("ORDER_SN=:ORDER_SN", [':ORDER_SN' => $sn])
-                        ->asArray()
-                        ->one();
-                    // 删除报单
-                    $delDecOrder = ApproachDecOrder::updateAll(
-                        ['IS_DEL'=>1, 'DELETED_AT'=>Date::nowTime()],
-                        'ORDER_SN=:ORDER_SN',
-                        ['ORDER_SN'=>$sn]
-                    );
-                }
-
-                $userId = $decInfo['USER_ID']; 
-
-                if (!$delDecOrder) {
-                    $transaction->rollBack();
-                    throw new Exception('删除报单失败,删除订单失败');
-                }
-
-                // 支付成功才需要处理
-                if ($orderInfo['STATUS'] == \Yii::$app->params['orderStatus']['paid']['value']) {
-                    // 如果删除的是升级单,则需要回退用户的级别
-                    if ($decInfo['DETAIL_TYPE'] == 2) {
-                        $oriLv = $decInfo['ORI_LV'];
-                        $userModel = User::findOne(['ID' => $orderInfo['USER_ID']]);
-                        $userModel->DEC_LV = $oriLv;
-                        $userModel->UPDATED_AT = Date::nowTime();
-                        if(!$userModel->save(false)) {
-                            $transaction->rollBack();
-                            throw new Exception('回退会员级别失败,删除订单失败');
-                        }
-                    } else {
-                        // 锁定用户
-                        $userModel = User::findOne(['ID' => $orderInfo['USER_ID']]);
-                        $userModel->STATUS = 0;
-                        $userModel->STATUS_AT = Date::nowTime();
-                        if(!$userModel->save(false)) {
-                            $transaction->rollBack();
-                            throw new Exception('锁定会员失败,删除订单失败');
-                        }
-                        $isLock = 1;
-                    }
-                }
-            }
-
-            if (!$approachOrderInfo) {
-                // 公共的退钱,删除订单操作
-                $delOrder = Order::updateAll(
-                    ['IS_DELETE' => 1, 'DELETED_AT' => Date::nowTime()],
-                    'SN=:SN',
-                    ['SN' => $sn]
-                );
-            } else {
-                // 公共的退钱,删除订单操作
-                $delOrder = ApproachOrder::updateAll(
-                    ['IS_DELETE' => 1, 'DELETED_AT' => Date::nowTime()],
-                    'SN=:SN',
-                    ['SN' => $sn]
-                );
-            }
-            if (!$delOrder) {
-                $transaction->rollBack();
-                throw new Exception('删除订单失败');
-            }
-
-            $payType = $orderInfo['PAY_TYPE']; // 支付方式
-            if ($payType != 'pay_stack') {
-                // 记录退还前的账户原资金
-                $cash = $point = $bonus = $exchange = 0;
-                $userBonus = UserBonus::findUseSlaves()
-                    ->select('BONUS,RECONSUME_POINTS,EXCHANGE_POINTS')
-                    ->where('USER_ID=:USER_ID', [':USER_ID' => $userId])
-                    ->asArray()
-                    ->one();
-                if ($userBonus) {
-                    $point = $userBonus['RECONSUME_POINTS'];
-                    $bonus = $userBonus['BONUS'];
-                    $exchange = $userBonus['EXCHANGE_POINTS'];
-                }
-                $cashWallet = UserWallet::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'CASH');
-                if ($cashWallet) {
-                    $cash = $cashWallet['CASH'];
-                }
-                // 开始退钱,退积分等
-                $payAmount = $orderInfo['PAY_AMOUNT']; // 支付的金额
-                //退还
-                if ($payType == 'cash') {
-                    $amountResult = Cash::changeUserCash($userId, 'CASH', +abs($payAmount), ['REMARK' => '退货退还余额']);
-                } else if ($payType == 'exchange') {
-                    $amountResult = Balance::changeUserBonus($userId, 'exchange_points', +abs($payAmount), ['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE, 'REMARK' => '退货退还无业绩兑换点数']);
-                } else {
-                    $amountResult = Balance::changeUserBonus($userId, 'reconsume_points', +abs($payAmount), ['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '退货退还复销点数']);
-                }
-
-                if ($amountResult !== true) {
-                    $transaction->rollBack();
-                    throw new Exception('退还订单金额失败,删除订单失败');
-                }
-
-                $upgradeType = 0; // 升级单类型
-                $returnLv = '';
-                $oriLvs = '';
-                if (!empty($decInfo)) {
-                    $upgradeType = $decInfo['UPGRADE_TYPE'];
-                    $returnLv = $decInfo['ORI_LV'];
-                    $oriLvs = $decInfo['UPGRADE_LV'];
-                }
-
-                // 退款成功,记录数据信息
-                $periodObj = Period::instance();
-                $nowPeriodNum = $periodObj->getNowPeriodNum();
-                $returnOrderModel = new ReturnOrder();
-                $returnOrderModel->ID = SnowFake::instance()->generateId();
-                $returnOrderModel->SN = $sn;
-                $returnOrderModel->DEC_SN = $orderInfo['DEC_SN'];
-                $returnOrderModel->CREATE_AT = Date::nowTime();
-                $returnOrderModel->ORDER_TYPE = $orderInfo['ORDER_TYPE'];
-                $returnOrderModel->ORDER_AMOUNT = $orderInfo['ORDER_AMOUNT'];
-                $returnOrderModel->PV = $orderInfo['PV'];
-                $returnOrderModel->PAY_PV = $orderInfo['PAY_PV'];
-                $returnOrderModel->PAY_AMOUNT = $orderInfo['PAY_AMOUNT'];
-                $returnOrderModel->PAY_TYPE = $orderInfo['PAY_TYPE'];
-                $returnOrderModel->USER_ID = $orderInfo['USER_ID'];
-                $returnOrderModel->PERIOD_NUM = $nowPeriodNum;
-                $returnOrderModel->PAY_STATUS = $orderInfo['STATUS'];
-                $returnOrderModel->PAY_NOTE = $orderInfo['NOTE'];
-                $returnOrderModel->ORDER_PERIOD_NUM = $orderInfo['PERIOD_NUM'];
-                $returnOrderModel->UPGRADE_TYPE = $upgradeType;
-                $returnOrderModel->USER_NAME = $orderInfo['USER_NAME'];
-                $returnOrderModel->PROVINCE = $orderInfo['PROVINCE'];
-                $returnOrderModel->CITY = $orderInfo['CITY'] ?? 0;
-                $returnOrderModel->COUNTY = $orderInfo['COUNTY'] ?? 0;
-                $returnOrderModel->ADDRESS = $orderInfo['ADDRESS'] ?? '';
-                $returnOrderModel->ADMIN_ID = \Yii::$app->user->id;
-                $returnOrderModel->ORI_CASH = $cash;
-                $returnOrderModel->ORI_BONUS = $bonus;
-                $returnOrderModel->ORI_EXCHANGE_POINTS = $exchange;
-                $returnOrderModel->ORI_RECONSUME_POINTS = $point;
-                $returnOrderModel->ORI_DEC_LV = $oriLvs;
-                $returnOrderModel->RETURN_DEC_LV = $returnLv;
-                $returnOrderModel->IS_LOCKING = $isLock;
-                if (!$returnOrderModel->save()) {
-                    $transaction->rollBack();
-                    $this->addErrors($returnOrderModel->getErrors());
-                    return false;
-                }
-            } else {
-                // 如果是PayStack支付,只处理支付成功的
-                $upgradeType = 0; // 升级单类型
-                $returnLv = '';
-                $oriLvs = '';
-                if (!empty($decInfo)) {
-                    $upgradeType = $decInfo['UPGRADE_TYPE'];
-                    $returnLv = $decInfo['ORI_LV'];
-                    $oriLvs = $decInfo['UPGRADE_LV'];
-                }
-
-                // 退款成功,记录数据信息
-                $periodObj = Period::instance();
-                $nowPeriodNum = $periodObj->getNowPeriodNum();
-                $returnOrderModel = new ReturnOrder();
-                $returnOrderModel->ID = SnowFake::instance()->generateId();
-                $returnOrderModel->SN = $sn;
-                $returnOrderModel->DEC_SN = $orderInfo['DEC_SN'];
-                $returnOrderModel->CREATE_AT = Date::nowTime();
-                $returnOrderModel->ORDER_TYPE = $orderInfo['ORDER_TYPE'];
-                $returnOrderModel->ORDER_AMOUNT = $orderInfo['ORDER_AMOUNT'];
-                $returnOrderModel->PV = $orderInfo['PV'];
-                $returnOrderModel->PAY_PV = $orderInfo['PAY_PV'];
-                $returnOrderModel->PAY_AMOUNT = $orderInfo['PAY_AMOUNT'];
-                $returnOrderModel->PAY_TYPE = $orderInfo['PAY_TYPE'];
-                $returnOrderModel->USER_ID = $orderInfo['USER_ID'];
-                $returnOrderModel->PERIOD_NUM = $nowPeriodNum;
-                $returnOrderModel->PAY_STATUS = $orderInfo['STATUS'];
-                $returnOrderModel->PAY_NOTE = $orderInfo['NOTE'];
-                $returnOrderModel->ORDER_PERIOD_NUM = $orderInfo['PERIOD_NUM'];
-                $returnOrderModel->UPGRADE_TYPE = $upgradeType;
-                $returnOrderModel->USER_NAME = $orderInfo['USER_NAME'];
-                $returnOrderModel->PROVINCE = $orderInfo['PROVINCE'];
-                $returnOrderModel->CITY = $orderInfo['CITY'] ?? 0;
-                $returnOrderModel->COUNTY = $orderInfo['COUNTY'] ?? 0;
-                $returnOrderModel->ADDRESS = $orderInfo['ADDRESS'] ?? '';
-                $returnOrderModel->ADMIN_ID = \Yii::$app->user->id;
-                $returnOrderModel->ORI_CASH = 0;
-                $returnOrderModel->ORI_BONUS = 0;
-                $returnOrderModel->ORI_EXCHANGE_POINTS = 0;
-                $returnOrderModel->ORI_RECONSUME_POINTS = 0;
-                $returnOrderModel->ORI_DEC_LV = $oriLvs;
-                $returnOrderModel->RETURN_DEC_LV = $returnLv;
-                $returnOrderModel->IS_LOCKING = $isLock;
-                if (!$returnOrderModel->save()) {
-                    $transaction->rollBack();
-                    $this->addErrors($returnOrderModel->getErrors());
-                    return false;
-                }
-            }
-            
-            $transaction->commit();
-        } catch(Exception $e) {
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return null;
-        }
-
-        return true;
-    }
-
-    // 判断订单类型
-    public function checkOrderType($attribute) {
-        $sn = $this->orderSn;
-        $orderDetail = Order::findUseDbCalc()
-        ->select('ID,DEC_SN,USER_ID,ORDER_TYPE,IS_DELETE,PERIOD_NUM')
-        ->where("SN=:SN", [':SN' => $sn])
-        ->asArray()
-        ->one();
-
-        $approachOrderDetail = [];
-        if (!$orderDetail) {
-            $orderDetail = $approachOrderDetail = ApproachOrder::findUseDbCalc()
-                ->select('ID,DEC_SN,USER_ID,ORDER_TYPE,IS_DELETE,PERIOD_NUM')
-                ->where("SN=:SN", [':SN' => $sn])
-                ->asArray()
-                ->one();
-        }
-
-        if (empty($orderDetail)) {
-            $this->addError($attribute, '未找到订单信息,订单编号为:'.$this->orderSn);
-            return ;
-        }
-        if ($orderDetail['IS_DELETE'] == 1) {
-            $this->addError($attribute, '订单已被删除,订单编号为'.$this->orderSn);
-            return ;
-        }
-        // 已挂网或者挂网中的业绩期订单,不能进行删除操作
-        $periodNum = $orderDetail['PERIOD_NUM'];
-        $periodObj = Period::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
-        if (empty($periodObj)) {
-            $this->addError($attribute, '订单对应业绩期不存在,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
-            return ;
-        }
-        if ($periodObj['IS_SENT'] == 1) {
-            $this->addError($attribute, '订单对应业绩期已挂网,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
-            return ;
-        }
-        if ($periodObj['IS_SENDING'] == 1) {
-            $this->addError($attribute, '订单对应业绩期正在挂网,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
-            return ;
-        }
-
-        if ($orderDetail['ORDER_TYPE'] == 'ZC') {
-            if (!$approachOrderDetail) {
-                $decDetail = DecOrder::findUseDbCalc()
-                    ->select('TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,IS_DEL')
-                    ->where("ORDER_SN=:ORDER_SN", [':ORDER_SN' => $sn])
-                    ->asArray()
-                    ->one();
-            } else {
-                $decDetail = ApproachDecOrder::findUseDbCalc()
-                    ->select('TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,IS_DEL')
-                    ->where("ORDER_SN=:ORDER_SN", [':ORDER_SN' => $sn])
-                    ->asArray()
-                    ->one();
-            }
-
-            if (empty($decDetail)) {
-                $this->addError($attribute, '未获取到对应报单信息,订单编号为:'.$this->orderSn);
-                return ;
-            }
-            if ($decDetail['IS_DEL'] == 1) {
-                $this->addError($attribute, '对应报单信息已被删除,订单编号为:'.$this->orderSn);
-                return ;
-            }
-
-            if ($decDetail['DETAIL_TYPE'] == 2) {
-                if (!$approachOrderDetail) {
-                    // 如果删除升级单,则此升级单必须是用户的最后一个升级单
-                    $lastUpgradeOrder = DecOrder::findUseDbCalc()
-                        ->select('ORDER_SN')
-                        ->where("TO_USER_ID=:TO_USER_ID AND IS_DEL=0 AND DETAIL_TYPE=2", [':TO_USER_ID' => $decDetail['TO_USER_ID']])
-                        ->orderBy('CREATED_AT DESC')
-                        ->asArray()
-                        ->one();
-                } else {
-                    // 如果删除升级单,则此升级单必须是用户的最后一个升级单
-                    $lastUpgradeOrder = ApproachDecOrder::findUseDbCalc()
-                        ->select('ORDER_SN')
-                        ->where("TO_USER_ID=:TO_USER_ID AND IS_DEL=0 AND DETAIL_TYPE=2", [':TO_USER_ID' => $decDetail['TO_USER_ID']])
-                        ->orderBy('CREATED_AT DESC')
-                        ->asArray()
-                        ->one();
-                }
-
-                $lastUpgradeSn = $lastUpgradeOrder['ORDER_SN'];
-                if ($sn != $lastUpgradeSn) {
-                    $this->addError($attribute, '有更晚的订单,此订单不能删除,订单编号为:'.$this->orderSn);
-                    return ;
-                }
-            } else {
-                // 如果是注册单,但是这个用户存在升级单,则也不能进行删除
-                if (!$approachOrderDetail) {
-                    $hasUpgradeOrder = DecOrder::findUseDbCalc()
-                        ->select('TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,IS_DEL')
-                        ->where("TO_USER_ID=:TO_USER_ID AND IS_DEL=0 AND DETAIL_TYPE=2", [':TO_USER_ID' => $decDetail['TO_USER_ID']])
-                        ->asArray()
-                        ->one();
-                } else {
-                    $hasUpgradeOrder = ApproachDecOrder::findUseDbCalc()
-                        ->select('TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,IS_DEL')
-                        ->where("TO_USER_ID=:TO_USER_ID AND IS_DEL=0 AND DETAIL_TYPE=2", [':TO_USER_ID' => $decDetail['TO_USER_ID']])
-                        ->asArray()
-                        ->one();
-                }
-
-                if (!empty($hasUpgradeOrder)) {
-                    $this->addError($attribute, '此注册报单,存在升级单,无法删除,订单编号为:'.$this->orderSn);
-                    return ;
-                }
-
-                if (!$approachOrderDetail) {
-                    // 删除注册单,判断是否有复消单,如果存在复消单,需要先删除复消单
-                    $hasFxOrder = Order::findUseDbCalc()
-                        ->select('SN')
-                        ->where("USER_ID=:USER_ID AND IS_DELETE=0 AND ORDER_TYPE='FX'", [':USER_ID' => $decDetail['TO_USER_ID']])
-                        ->asArray()
-                        ->one();
-                } else {
-                    // 删除注册单,判断是否有复消单,如果存在复消单,需要先删除复消单
-                    $hasFxOrder = ApproachOrder::findUseDbCalc()
-                        ->select('SN')
-                        ->where("USER_ID=:USER_ID AND IS_DELETE=0 AND ORDER_TYPE='FX'", [':USER_ID' => $decDetail['TO_USER_ID']])
-                        ->asArray()
-                        ->one();
-                }
-                if (!empty($hasFxOrder)) {
-                    $this->addError($attribute, '此注册报单,存在复消单,无法删除,订单编号为:'.$this->orderSn);
-                    return ;
-                }
-            }   
-        }
-        return true; 
-    }
-}

+ 0 - 1015
common/models/forms/OrderForm.php

@@ -1,1015 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\PayStack;
-use common\helpers\user\Balance;
-use common\helpers\user\Cash;
-use common\helpers\user\Info;
-use common\libs\logging\operate\AdminOperate;
-use common\models\DealType;
-use common\models\Order;
-use common\models\OrderGoods;
-use common\models\Period;
-use common\models\ReceiveAddress;
-use common\models\Region;
-use common\models\ShopGoods;
-use common\models\User;
-use common\models\UserNetwork;
-use common\models\RemainPv;
-use common\models\FlowRemainPv;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class OrderForm extends Model
-{
-    public $sn;
-    public $expressCompany;
-    public $orderTrackNo;
-    public $status;
-    public $remark;
-
-    public $type;
-    public $addressId;
-    public $payType;
-    public $goodsId;
-    public $goodsNum;
-    public $payPassword;
-    public $email;
-
-    public $userName;
-    public $consignee;
-    public $acceptMobile;
-    public $province;
-    public $city;
-    public $county;
-    public $detailaddress;
-
-    private $_address;
-    private $_decAmount;
-    private $_decPv;
-    private $_freight;
-    private $_payAmount;
-    private $_orderGoods;
-    private $_standardAmount;
-    private $_decAmountStandard;
-    private $_exchangeRate;
-    private $_remainPv;
-    private $_realPv;
-
-    /**
-     * @var Order
-     */
-    private $_model;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => Order::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province'/*,'city','county'*/,'cityName','lgaName','detailaddress','email'], 'trim'],
-            [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress'/*,'email'*/], 'required'],
-            [['status'], 'isStatus'],
-            [['addressId'], 'isAddress'],
-            [['payType'], 'isPayType'],
-            [['payPassword'], 'validatePassword'],
-        ];
-    }
-
-    public function attributeLabels()
-    {
-        return [
-            'sn' => 'Order Code', // 订单号
-            'expressCompany' => '快递公司',
-            'orderTrackNo' => '快递单号',
-            'status' => 'State', // 状态
-            'remark' => 'Remark', // 备注
-            'type' => 'Order Type',// 订单类型
-            'addressId' => 'Shipping address',// 收货地址
-            'payType' => 'Pay Type',// 支付方式
-            'goodsId' => 'Product ID',//商品ID
-            'goodsNum' => 'Product quantity',//商品数量
-            'userName' => 'Repeat sales Member No. does not exist',//复消会员编号
-            'consignee' => 'Consignee',// 收货人
-            'acceptMobile' => 'Accept Mobile',// 收货电话
-            'province' => 'Province',// 省
-            'city' => 'City',// 市
-            'county' => 'County',// 区
-            'lgaName' => 'Lga Name',
-            'cityName' => 'City Name',
-            'detailaddress' => 'Address',// 收货详细地址
-            'email' => 'Email',
-        ];
-    }
-
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios()
-    {
-        $parentScenarios =  parent::scenarios();
-        $customScenarios = [
-            // 管理员发货
-            'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
-            // 会员确认收货
-            'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
-            // 管理员修改订单状态
-            'adminStatus' => ['sn', 'status'],
-            // 管理员修改备注
-            'adminRemark' => ['sn', 'remark'],
-            // 会员下单
-            'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword'],
-            // 帮会员复消下单
-            'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'],
-            // 管理员退款
-            'adminRefund' => ['sn'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    /**
-     * 校验之前
-     * @return bool
-     */
-    public function beforeValidate()
-    {
-        $parentValidate = parent::beforeValidate();
-        if ($this->sn) {
-            $this->_model = Order::findOne(['SN'=>$this->sn]);
-            if (!$this->_model){
-                $this->addError('sn', '订单不存在');
-                return false;
-            }
-        }
-        if ($this->scenario == 'adminDelivery'){
-            if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['cancel']) {
-                $this->addError('sn', '订单已取消不能发货');
-                return false;
-            }
-            if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
-                $this->addError('sn', '订单已删除不能发货');
-                return false;
-            }
-        }
-
-        if ($this->scenario == 'adminRefund'){
-            if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['paid']['value']) {
-                $this->addError('sn', '订单状态支付状态不支持退款');
-                return false;
-            }
-            if ($this->_model['DELIVERY_STATUS'] != \Yii::$app->params['deliveryStatus']['notDelivery']['value']) {
-                $this->addError('sn', '订单物流状态不支持退款');
-                return false;
-            }
-            if ($this->_model['PAY_TYPE'] != 'pay_stack') {
-                $this->addError('sn', '订单支付方式不支持退款');
-                return false;
-            }
-            if (!$this->_model['REMARK']) {
-                $this->addError('sn', '订单支付信息不存在');
-                return false;
-            }
-        }
-
-        return $parentValidate;
-    }
-
-    /**
-     * 校验支付密码
-     * @param $attribute
-     * @param $params
-     */
-    public function validatePassword($attribute, $params) {
-        if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
-            $this->addError($attribute, 'The payment password is incorrect');//支付密码不正确
-        }
-    }
-
-    /**
-     * 判断收货地址是否存在
-     * @param $attribute
-     */
-    public function isAddress($attribute){
-        if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
-            $this->addError($attribute, '收货地址不存在');
-        } else {
-            $this->_address = $receiveAddress;
-        }
-    }
-
-    /**
-     * 判断支付方式
-     * @param $attribute
-     */
-    public function isPayType($attribute){
-        if(!array_key_exists($this->payType, ShopGoods::payTypes())){
-            $this->addError($attribute, '支付方式错误1');
-            return;
-        }
-
-        // 一个订单只能包含一类商品
-        $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
-        $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
-        if (count($goodsCategoryType) != 1) {
-            $this->addError($attribute, '订单不能包含多种商品分类');
-            return;
-        }
-
-        // 购买方式
-        $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
-        if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
-            $this->addError($attribute, '支付方式错误2');
-            return;
-        }
-
-        // 所选支付方式必须是商品分类支持的类型
-        $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
-        // 商品类型
-        $currCategoryType = $goodsCategoryType[0];
-        if (!array_key_exists($currCategoryType, $categoryType)) {
-            $this->addError($attribute, '商品分类错误');
-            return;
-        }
-
-        $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
-        if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
-            $this->addError($attribute, '支付方式错误3');
-            return;
-        }
-    }
-
-    /**
-     * 校验类型
-     * @param $attribute
-     */
-    public function isStatus($attribute){
-        if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
-            $this->addError($attribute, '类型错误');
-            return ;
-        }
-        if ($this->scenario == 'adminStatus'){
-            if ($this->status == $this->_model['STATUS']) {
-                $this->addError($attribute, '订单状态没有改变');
-                return ;
-            }
-            if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
-                $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
-                return ;
-            }
-            elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
-                $this->addError($attribute, '订单已失效不能处理');
-                return ;
-            }
-            elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
-                $this->addError($attribute, '订单不能单独处理为物流状态');
-                return ;
-            }
-            elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
-                $this->addError($attribute, '订单已失效不能处理');
-                return ;
-            }
-            elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
-                if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
-                    $this->addError($attribute, '订单已完成不能取消');
-                    return ;
-                }
-                if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
-                    $this->addError($attribute, '订单已删除不能取消');
-                    return ;
-                }
-            }
-            elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
-                if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
-                    $this->addError($attribute, '订单已完成不能删除');
-                    return ;
-                }
-            }
-        }
-
-    }
-
-    /**
-     * 管理员发货
-     * @return Order|null
-     * @throws \yii\db\Exception
-     */
-    public function adminDelivery(){
-        if(!$this->validate()){
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $period = Period::instance();
-            $this->_model->DELIVERY_STATUS = \Yii::$app->params['deliveryStatus']['delivered']['value'];
-            $this->_model->DELIVERY_PERIOD = $period->getNowPeriodNum();
-            $this->_model->DELIVERY_AT = Date::nowTime();
-            $this->_model->EXPRESS_COMPANY = $this->expressCompany;
-            $this->_model->ORDER_TRACK_NO = $this->orderTrackNo;
-            $this->_model->STATUS = \Yii::$app->params['orderStatus']['delivery']['value'];
-            if(!$this->_model->save()){
-                throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-        return $this->_model;
-    }
-
-    /**
-     * 校验支付
-     * @return Order|null
-     * @throws Exception
-     */
-    public function verifyPayStack(): ?Order
-    {
-        if(!$this->validate()){
-            return null;
-        }
-
-        // 调用PayStack支付校验
-        $payload = PayStack::transactionVerify($this->remark['reference']);
-        if ($payload['status'] !== true) {
-            throw new Exception(Form::formatErrorsForApi($payload['message']));
-        }
-        if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
-            throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
-        }
-
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $this->_model->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
-            $this->_model->REMARK = json_encode($this->remark);
-            $this->_model->PAY_AT = Date::nowTime();
-            if (!$this->_model->save()) {
-                throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-
-        return $this->_model;
-    }
-
-    /**
-     * 订单退款
-     * @return Order|null
-     * @throws Exception
-     */
-    public function adminRefund()
-    {
-        if(!$this->validate()){
-            return null;
-        }
-
-        // 支付信息存在于remark中
-        $remark = $this->_model->REMARK ? json_decode($this->_model->REMARK, true) : [];
-        $reference = $remark['reference'] ?? '';
-        if (!$reference) {
-            throw new Exception(Form::formatErrorsForApi('支付信息不存在'));
-        }
-        // 退款金额. 订单支付金额 * 100
-        $amount = $this->_model->PAY_AMOUNT * 100;
-        // 调用PayStack支付校验
-        $payload = PayStack::transactionRefund($reference, $amount);
-        if ($payload['status'] !== true) {
-            throw new Exception(Form::formatErrorsForApi($payload['message']));
-        }
-
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $this->_model->STATUS = \Yii::$app->params['orderStatus']['refund']['value'];
-            $this->_model->REMARK = json_encode([
-                    'payment' => $remark,
-                    'refund'  => $payload['data']
-                ]
-            );
-            if (!$this->_model->save()) {
-                throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-
-        return $this->_model;
-    }
-
-    /**
-     * BV分期
-     *
-     *
-     */
-    private function _pvSplit($oPv){
-        $currentPv = $oPv % 30 + 30;
-        $remainPv = $oPv - $currentPv;
-        return [
-            'current' => $currentPv,
-            'remain' => $remainPv
-        ];
-    }
-
-    /**
-     * 复销
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public function add(){
-        if(!$this->validate()){
-            return null;
-        }
-        $ids = $this->goodsId;
-        $totalAmount = 0;
-        $totalPv = 0;
-        $totalRealPv = 0;
-        $totalAmountStandard = 0;
-        $goodsType = ShopGoods::GOODS_TYPE;
-        $this->_remainPv = 0;
-        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
-        foreach ($this->goodsNum as $k => $v) {
-            if ($v) {
-                $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
-                if($goods['STORE_NUMS']>0){
-                    if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
-                        $discount = $goodsType[$goods['TYPE']]['discount'];
-                        $realPrice = $goods['SELL_PRICE'] * $discount/100;
-                        $realPv = $goods['PRICE_PV'] * $discount/100;
-                        $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
-                    } else {
-                        $discount = $goods['SELL_DISCOUNT'];
-                        $realPrice = $goods['SELL_PRICE'] * $discount;
-                        $realPv = $goods['PRICE_PV'] * $discount;
-                        $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
-                    }
-                    if($goods['PV_SPLIT']==1){ // 当商品为PV分期时
-                        $pvSplit = $this->_pvSplit($realPv);
-                        $currentPv = $pvSplit['current'];
-                        $remainPv = $pvSplit['remain'];
-                        $totalPv += $currentPv * intval($v);
-                        $totalRealPv += $realPv * intval($v);
-                        $this->_remainPv += $remainPv * intval($v);
-                    }else{
-                        $currentPv = $goods['PRICE_PV'];
-                        $totalPv += $realPv * intval($v);
-                        $totalRealPv += $realPv * intval($v);
-                        $remainPv = 0;
-                        $this->_remainPv += 0;
-                    }
-                    $totalAmount += $realPrice * intval($v);
-                    $totalAmountStandard += $realPriceStandard * intval($v);
-//                    if($this->payType=='cash') {
-//                        $discount = $goodsType[$goods['TYPE']]['discount'];
-//                        $realPrice = $goods['SELL_PRICE'] * $discount/100;
-//                        $realPv = $goods['PRICE_PV'] * $discount/100;
-//                        $totalAmount += $realPrice * intval($v);
-//                        $totalPv += $realPv * intval($v);
-//                    }else{
-//                        $realPrice = $goods['SELL_PRICE'];
-//                        $realPv = $goods['PRICE_PV'];
-//                        $totalAmount += $realPrice * intval($v);
-//                        $totalPv += $realPv * intval($v);
-//                    }
-                    $this->_orderGoods[] = [
-                        'GOODS_ID' => $goods['ID'],
-                        'PRICE' => $goods['SELL_PRICE'],
-                        'PV' => $currentPv, // $goods['PRICE_PV'],
-                        'REAL_PRICE' => $realPrice,
-                        'REAL_PV' => $realPv,
-                        'REMAIN_PV' => $remainPv,
-                        'POINT' => $goods['POINT'],
-                        'BUY_NUMS' => intval($v),
-                        'SKU_CODE' => $goods['GOODS_NO'],
-                        'GOODS_TITLE' => $goods['GOODS_NAME'],
-                        'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
-                        'PAY_TYPE' => $this->payType,
-                        'EMAIL' => $this->email,
-                        'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
-                        'REAL_STANDARD_PRICE' => $realPriceStandard,
-                        'EXCHANGE_RATE' => $exchangeRate,
-                        'TAX_RATE' => $goods['TAX_RATE'],
-                    ];
-                }
-            }
-        }
-
-        // 汇率
-        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
-        // 运费.美元转奈拉
-        $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
-        // 普通商品免运费阈值.美元转奈拉
-        $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
-
-        $this->_decAmount = $totalAmount;
-        $this->_decPv = $totalPv;
-        $this->_realPv = $totalRealPv;
-        $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
-        if($this->_address['PROVINCE']==1){
-            $this->_freight = 0;
-        }
-        $this->_payAmount = $this->_decAmount + $this->_freight;
-
-        $this->_decAmountStandard = $totalAmountStandard;
-        $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
-
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            //判断用户余额是否充足
-            $result = $this->getBalanceAdequate($this->payType, $this->_payAmount);
-            if ($result['code'] !== 200) {
-                throw new Exception($result['message']);
-            }
-
-			/**
-             * 2022-04-28
-             * York
-             * 支付后减少库存
-             */
-            foreach ($this->goodsNum as $k => $v){
-                if ($v){
-                    $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
-                    if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
-                        $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
-                        $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
-                        $data->STORE_NUMS = $goods_store_nums;
-                        $data->update();
-                        //下单后库存小于等于0 商品下架
-                        if($goods_store_nums <= 0){
-                            $data->STATUS = 0;
-                            $data->UPDATED_AT = Date::nowTime();
-                            $data->update();
-
-                        }
-                    }else{
-                        throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
-
-                    }
-                }
-            }
-
-            //写入订单
-            if (!$orderResult = $this->addOrder()) {
-                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
-            }
-
-            $transaction->commit();
-
-            return $orderResult;
-        }catch (\Exception $e){
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return null;
-        }
-    }
-
-    /**
-     * 判断对应账户余额是否充足.
-     * @param $payType string 支付方式.
-     * @param $payAmount numeric 支付金额
-     * @return array|int[]
-     */
-    public function getBalanceAdequate(string $payType, $payAmount): array
-    {
-        $loginUserId = \Yii::$app->user->id;
-
-        if ($payType == 'cash') {
-            if (Cash::getAvailableBalance($loginUserId) < $payAmount) {
-                return ['code' => 500, 'message' => '余额不足,无法购买商品'];
-            }
-        } else if ($payType =='exchange') {
-            if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) {
-                return ['code' => 500, 'message' => '兑换积分不足,无法购买商品'];
-            }
-        } else if ($payType == 'tourism_points') {
-            if ($payAmount > Balance::getBalanceTourism($loginUserId)) {
-                return ['code' => 500, 'message' => '旅游积分不足,无法购买商品'];
-            }
-        } else if ($payType == 'garage_points') {
-            if ($payAmount > Balance::getBalanceGarage($loginUserId)) {
-                return ['code' => 500, 'message' => '车房积分不足,无法购买商品'];
-            }
-//        } else{
-//            if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
-//                return ['code' => 500, 'message' => '复消积分不足,无法购买商品'];
-//            }
-        }
-
-        return ['code' => 200];
-    }
-
-    /**
-     * 复销订单
-     * @throws Exception
-     */
-    public function addOrder(){
-        $periodObj = Period::instance();
-        $nowPeriodNum = $periodObj->getNowPeriodNum();
-        $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
-
-        $userId = \Yii::$app->user->id;
-
-        $userName = Info::getUserNameByUserId($userId);
-        $userRealName = Info::getUserRealNameByUserId($userId);
-        $userMobile = Info::getUserMobileByUserId($userId);
-        $userEmail = Info::getUserEmailByUserId($userId);
-        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
-        // 加入订单信息
-        if ($this->_address['PROVINCE'] != 1) {
-            $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
-            if (!$warehouse) {
-                throw new Exception('地区2暂时不支持配送,具体联系客服');
-            }
-        }else{
-            $warehouse = '01';
-        }
-        $_hasPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_decPv;
-        $_hasRealPV = in_array($this->payType, ['exchange', 'tourism_points', 'garage_points']) ? 0 : $this->_realPv;
-
-        $ordNo = $this->_generateSn();
-        $orderModel = new Order();
-        $orderModel->SN = 'OS'.$ordNo;
-        $orderModel->DEC_SN = 'DS'.$ordNo;
-        $orderModel->ORDER_TYPE = $this->type;
-        $orderModel->USER_ID = $userId;
-        $orderModel->USER_NAME = $userName;
-        $orderModel->ORDER_AMOUNT = $this->_decAmount;
-        $orderModel->PV = $_hasPV;
-        $orderModel->PAY_AMOUNT = $this->_payAmount;
-        $orderModel->PAY_PV = $_hasRealPV; // 兑换积分不能算业绩
-        $orderModel->REMAIN_PV = $this->_remainPv;
-        $orderModel->PAY_AT = Date::nowTime();
-        $orderModel->PAY_TYPE = $this->payType;
-        $orderModel->PERIOD_NUM = $nowPeriodNum;
-        $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
-        $orderModel->FREIGHT = $this->_freight;
-        $orderModel->PAY_FREIGHT = $this->_freight;
-        $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
-        $orderModel->MOBILE = $this->_address['MOBILE'];
-        $orderModel->PROVINCE = $this->_address['PROVINCE'];
-//        $orderModel->CITY = $this->_address['CITY'];
-//        $orderModel->COUNTY = $this->_address['COUNTY'];
-        $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
-        $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
-        $orderModel->ADDRESS = $this->_address['ADDRESS'];
-        $orderModel->FRONT_REMARK = $this->remark;
-        $orderModel->WAREHOUSE = $warehouse;
-        $orderModel->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
-        $orderModel->CREATED_AT = Date::nowTime();
-        $orderModel->CREATE_USER = $userName;
-        $orderModel->EMAIL = $userEmail ?? '';
-        $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
-        $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
-        $orderModel->EXCHANGE_RATE = $exchangeRate;
-        if($this->_address['PROVINCE']==1){
-            $orderModel->EXPRESS_TYPE = 1;
-            $orderModel->CONSIGNEE = $userRealName;
-            $orderModel->MOBILE = $userMobile;
-            $orderModel->PROVINCE = 1;
-            $orderModel->CITY = 1;
-            $orderModel->COUNTY = 1;
-            $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
-            $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
-            $orderModel->ADDRESS = 'Self Pick-up';
-        }
-        if(!$orderModel->save()){
-            $this->addErrors($orderModel->getErrors());
-            return false;
-        }
-        // 加入商品到订单商品表
-        foreach($this->_orderGoods as $key=>$value){
-            // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0
-            if (in_array($orderModel->PAY_TYPE, ['exchange', 'tourism_points', 'garage_points'])) {
-                $this->_orderGoods[$key]['REAL_PV'] = 0;
-            }
-            $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
-            $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
-        }
-        OrderGoods::batchInsert($this->_orderGoods);
-
-        //扣除会员余额/积分
-        if($this->payType=='cash') {
-            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
-        } else if ($this->payType=='exchange') {
-            Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']);
-        } else if ($this->payType == 'tourism_points') {
-            Balance::changeUserBonus(\Yii::$app->user->id, 'tourism_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TOURISM_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换']);
-        } else if ($this->payType == 'garage_points') {
-            Balance::changeUserBonus(\Yii::$app->user->id, 'garage_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::GARAGE_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换']);
-        }  else if ($this->payType == 'villa_points') {
-            Balance::changeUserBonus(\Yii::$app->user->id, 'villa_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::VILLA_POINTS_EXCHANGE,'REMARK' => '会员房奖积分兑换']);
-        } else if ($this->payType == 'reconsume_points') {
-            Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换']);
-        }
-
-//        if($this->_remainPv>0) {
-//            $oRemainPv = RemainPv::find()->where(['USER_ID' => $userId])->one();
-//
-//            $transactionRemain = \Yii::$app->db->beginTransaction();
-//            try{
-//                $flowRemainPvModel = new FlowRemainPv();
-//                $flowRemainPvModel->ID = $this->_generateSn();
-//                $flowRemainPvModel->USER_ID = $userId;
-//                $flowRemainPvModel->REMAIN_PV_FLOW = $this->_remainPv;
-//                $flowRemainPvModel->REMAIN_PV_TOTAL = $oRemainPv['REMAIN_PV'] + $this->_remainPv;
-//                $flowRemainPvModel->PERIOD_NUM = $nowPeriodNum;
-//                $flowRemainPvModel->UPDATED_AT = Date::nowTime();
-//                $flowRemainPvModel->ORDER_SN = 'OS'.$ordNo;
-//                if(!$flowRemainPvModel->save()){
-//                    $this->addErrors($flowRemainPvModel->getErrors());
-//                    return false;
-//                }
-//
-//                $oRemainPv = RemainPv::find()->where(['USER_ID' => $userId])->one();
-//                if($oRemainPv){
-//                    $oRemainPv->updateCounters(['REMAIN_PV'=>$this->_remainPv]);
-//                }else{
-//                    $remainPvModel = new RemainPv();
-//                    $remainPvModel->ID = $this->_generateSn();
-//                    $remainPvModel->USER_ID = $userId;
-//                    $remainPvModel->UPDATED_AT = Date::nowTime();
-//                    $remainPvModel->REMAIN_PV = $this->_remainPv;
-//                    $remainPvModel->STATUS = 1;
-//                    if(!$remainPvModel->save()){
-//                        $this->addErrors($remainPvModel->getErrors());
-//                        return false;
-//                    }
-//                }
-//                $transactionRemain->commit();
-//            } catch (Exception $e) {
-//                $transactionRemain->rollBack();
-//                $this->addError('add', $e->getMessage());
-//                return null;
-//            }
-//        }
-        return $orderModel;
-    }
-
-    /**
-     * 帮会员复销
-     * @return bool|null
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public function reconsumeAdd(){
-        if(!$this->validate()){
-            return null;
-        }
-        $ids = $this->goodsId;
-        $totalAmount = 0;
-        $totalPv = 0;
-        $goodsType = ShopGoods::GOODS_TYPE;
-        foreach ($this->goodsNum as $k => $v) {
-            if ($v) {
-                $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
-                if($goods['STORE_NUMS']>0){
-                    if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
-                        $discount = $goodsType[$goods['TYPE']]['discount'];
-                        $realPrice = $goods['SELL_PRICE'] * $discount/100;
-                        $realPv = $goods['PRICE_PV'] * $discount/100;
-                    } else {
-                        $discount = $goods['SELL_DISCOUNT'];
-                        $realPrice = $goods['SELL_PRICE'] * $discount;
-                        $realPv = $goods['PRICE_PV'] * $discount;
-                    }
-                    $totalAmount += $realPrice * intval($v);
-                    $totalPv += $realPv * intval($v);
-                    $this->_orderGoods[] = [
-                        'GOODS_ID' => $goods['ID'],
-                        'PRICE' => $goods['SELL_PRICE'],
-                        'PV' => $goods['PRICE_PV'],
-                        'REAL_PRICE' => $realPrice,
-                        'REAL_PV' => $realPv,
-                        'POINT' => $goods['POINT'],
-                        'BUY_NUMS' => intval($v),
-                        'SKU_CODE' => $goods['GOODS_NO'],
-                        'GOODS_TITLE' => $goods['GOODS_NAME']
-                    ];
-                }
-            }
-        }
-        $this->_decAmount = $totalAmount;
-        $this->_decPv = $totalPv;
-        $this->_freight = ($totalAmount>=300) ? 0 : 15;
-        if($this->_address['PROVINCE']==1){
-            $this->_freight = 0;
-        }
-        $this->_payAmount = $this->_decAmount + $this->_freight;
-
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $loginUserId = \Yii::$app->user->id;
-
-            //是否开启伞下会员限制
-            $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
-            if($isResaleUmbrella){
-                $userId = Info::getUserIdByUserName($this->userName);
-                $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
-                if(!$userNetwork){
-                    throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
-                }
-            }
-            //判断用户余额是否充足
-            if($this->payType=='cash') {
-                if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
-                    throw new Exception('余额不足,无法购买商品');
-                }
-            }else{
-                if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
-                    throw new Exception('复消积分不足,无法购买商品');
-                }
-            }
-			
-			
-			
-			/**
-			             * 2022-04-28
-			             * York
-			             * 支付后减少库存
-			             */
-			            foreach ($this->goodsNum as $k => $v){
-			                if ($v){
-			                    $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
-			                    if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
-			                        $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
-			                        $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
-			                        $data->STORE_NUMS = $goods_store_nums;
-			                        $data->update();
-			                        //下单后库存小于等于0 商品下架
-			                        if($goods_store_nums <= 0){
-			                            $data->STATUS = 0;
-			                            $data->UPDATED_AT = Date::nowTime();
-			                            $data->update();
-			
-			                        }
-			                    }else{
-			                        throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
-			
-			                    }
-			
-			
-			                }
-			            }
-			//                exit();
-			
-			
-            //写入订单
-            if (!$orderResult = $this->addUserOrder()) {
-                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
-            }
-            $transaction->commit();
-        }catch (\Exception $e){
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return null;
-        }
-        return true;
-    }
-
-    /**
-     * 帮会员复消的订单
-     */
-    public function addUserOrder(){
-        $periodObj = Period::instance();
-        $nowPeriodNum = $periodObj->getNowPeriodNum();
-        $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
-        //帮复消会员Id(登陆会员)
-        $loginUserId = \Yii::$app->user->id;
-        $loginUserName = Info::getUserNameByUserId($loginUserId);
-        //订单会员Id
-        $userId = Info::getUserIdByUserName($this->userName);
-        $email = Info::getEmailByUserId($this->userName);
-
-        // 加入订单信息
-        if($this->province!=1){
-            $warehouse = Region::getWarehouseByCode($this->province);//仓库
-            if(!$warehouse){
-                throw new Exception('地区1暂时不支持配送,具体联系客服');
-            }
-        }else{
-            $warehouse = '01';
-        }
-        $ordNo = $this->_generateSn();
-        $orderModel = new Order();
-        $orderModel->SN = 'OS'.$ordNo;
-        $orderModel->DEC_SN = 'DS'.$ordNo;
-        $orderModel->ORDER_TYPE = $this->type;
-        $orderModel->USER_ID = $userId;
-        $orderModel->USER_NAME = $this->userName;
-        $orderModel->ORDER_AMOUNT = $this->_decAmount;
-        $orderModel->PV = $this->_decPv;
-        $orderModel->PAY_AMOUNT = $this->_payAmount;
-        $orderModel->PAY_PV = $this->_decPv;
-        $orderModel->PAY_AT = Date::nowTime();
-        $orderModel->PAY_TYPE = $this->payType;
-        $orderModel->PERIOD_NUM = $nowPeriodNum;
-        $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
-        $orderModel->FREIGHT = $this->_freight;
-        $orderModel->PAY_FREIGHT = $this->_freight;
-        $orderModel->CONSIGNEE = $this->consignee;
-        $orderModel->MOBILE = $this->acceptMobile;
-        $orderModel->PROVINCE = $this->province;
-//        $orderModel->CITY = $this->city;
-//        $orderModel->COUNTY = $this->county;
-        $orderModel->ADDRESS = $this->detailaddress;
-        $orderModel->FRONT_REMARK = $this->remark;
-        $orderModel->WAREHOUSE = $warehouse;
-        $orderModel->STATUS = 1;
-        $orderModel->CREATED_AT = Date::nowTime();
-        $orderModel->CREATE_USER = $loginUserName;
-        $orderModel->EMAIL = $email;
-        if(!$orderModel->save()){
-            $this->addErrors($orderModel->getErrors());
-            return false;
-        }
-        // 加入商品到订单商品表
-        foreach($this->_orderGoods as $key=>$value){
-            $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
-            $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
-        }
-        OrderGoods::batchInsert($this->_orderGoods);
-
-        //扣除会员余额/积分
-        if($this->payType=='cash') {
-            Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
-        }else{
-            Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']);
-        }
-        return $orderModel;
-    }
-
-    /**
-     * 生成流水号
-     * @return string
-     */
-    private function _generateSn() {
-        return Date::today('Ymd') . $this->_random(10, 1);
-    }
-
-    /**
-     * 生成随机数
-     * @param $length
-     * @param int $numeric
-     * @return string
-     */
-    private function _random($length, $numeric = 0) {
-        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
-        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
-        $hash = '';
-        $max = strlen($seed) - 1;
-        for ($i = 0; $i < $length; $i++) {
-            $hash .= $seed[mt_rand(0, $max)];
-        }
-        return $hash;
-    }
-
-    public function addFakeOrder($userId, $periodNum){
-        $userName = Info::getUserNameByUserId($userId);
-        $ordNo = $this->_generateSn();
-        $orderModel = new Order();
-        $orderModel->SN = 'OS'.$ordNo;
-        $orderModel->DEC_SN = 'DS'.$ordNo;
-        $orderModel->USER_ID = $userId;
-        $orderModel->USER_NAME = $userName;
-        $orderModel->PERIOD_NUM = $periodNum;
-        $orderModel->CREATE_USER = 'FAKE';
-        $orderModel->ORDER_TYPE = 'FX';
-        $orderModel->STATUS = 1;
-        $orderModel->PV = 30;
-        $orderModel->PAY_PV = 30;
-        $orderModel->P_CALC_MONTH = '1970-01-01';
-        $orderModel->CREATED_AT = Date::nowTime();
-        $orderModel->EXPRESS_TYPE = 1;
-        $orderModel->IS_AUTO = 1;
-        if(!$orderModel->save()){
-            $this->addErrors($orderModel->getErrors());
-            return false;
-        }
-        return $orderModel;
-    }
-}

+ 0 - 291
common/models/forms/RechargeForm.php

@@ -1,291 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\helpers\Form;
-use common\helpers\Tool;
-use common\helpers\user\Cash;
-use common\helpers\user\Info;
-use common\models\Recharge;
-use common\models\UserInfo;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class RechargeForm extends Model {
-    public $selectedIds;
-    public $auditStatus;
-    public $createRemark;
-
-    public $userName;
-    public $applyAmount;
-    public $openBank;
-    public $bankAddress;
-    public $bankNo;
-//    public $bankProvince;
-//    public $bankCity;
-//    public $bankCounty;
-
-    public $sn;
-    public $amount;
-    public $bankRealName;
-
-    private $_userId;
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['userName', 'idCard', 'applyAmount', 'auditStatus', 'remark', 'selectedIds', 'sn','amount', 'bankRealName', 'bankNo'], 'trim'],
-            [['selectedIds', 'auditStatus', 'userName','applyAmount','openBank','bankNo'/*,'bankAddress'*/], 'required'],
-            [['selectedIds'], 'exist', 'targetClass' => Recharge::class, 'targetAttribute' => 'ID', 'message' => 'Recharge does not exist'], // 充值申请不存在
-            [['userName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME', 'message' => 'Member does not exist'],// 会员不存在
-            [['applyAmount'], 'price'],
-            [['applyAmount'], 'isApplyAmount'],
-            [['applyAmount'], 'number', 'max' => 10000000000, 'min' => 1],
-            [['selectedIds'], 'isSelected'],
-            //[['sn'], 'isSn'],
-        ];
-    }
-
-    /**
-     * 指定场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'addByAdmin' => ['userName', 'applyAmount'],
-            'addByUser' => ['applyAmount','openBank','bankNo','bankAddress'/*,'currency'*/],
-            'statusByAdmin' => ['selectedIds', 'auditStatus', 'createRemark'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    /**
-     * @return array
-     */
-    public function attributeLabels() {
-        return [
-            'selectedIds' => 'RechargeID',// 充值申请ID
-            'userName' => 'Member code',// 会员编号
-            'applyAmount' => 'Apply Amount', // 申请充值的金额
-            'openBank' => 'Bank name',// 汇款银行
-            'bankNo' => 'Bank account', // 汇款账号
-//            'bankAddress' => '银行支行',
-//            'bankProvince' => '银行省',
-//            'bankCity' => '银行市',
-//            'bankCounty' => '银行县',
-        ];
-    }
-
-    /**
-     * 校验申请金额是否小于当前余额并符合配置中的设置
-     * @param $attribute
-     * @return bool
-     */
-    public function isApplyAmount($attribute) {
-        if ($this->applyAmount <= 0) {
-            $this->addError('scenario', 'The recharge amount must be greater than 0'); // 充值金额必须大于0
-        }
-        if ((int)($this->applyAmount)!=$this->applyAmount) {
-            $this->addError('scenario', 'The recharge amount must be an integer');// 充值金额必须是整数
-        }
-        if ($this->scenario == 'addByUser') {
-            $this->_userId = \Yii::$app->user->id;
-        } elseif ($this->scenario == 'addByAdmin') {
-            $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
-            if (!$userInfo) {
-                $this->addError('scenario', $this->userName . 'Member does not exist');// 会员不存在
-            }else{
-                $this->_userId = $userInfo['USER_ID'];
-            }
-        } else {
-            $this->addError($attribute, 'Scenes does not exist'); // 场景不存在
-            return false;
-        }
-    }
-
-    /**
-     * 批量数据
-     * @param $attributes
-     */
-    public function isSelected($attributes) {
-        if (!$this->selectedIds) {
-            $this->addError($attributes, 'A piece of data must be selected'); // 必须选择一条数据
-        }
-//        if (!is_array($this->selectedIds)) {
-//            $this->selectedIds = [$this->selectedIds];
-//        }
-    }
-
-    /**
-     * 判断信息是否一致
-     * @param $attribute
-     * @throws Exception
-     */
-    public function isSn($attribute) {
-        $sn = $this->sn;
-        if (!$oneWithdraw = Recharge::findOneAsArray('SN=:SN AND AUDIT_STATUS=:AUDIT_STATUS', [':SN' => $sn, ':AUDIT_STATUS' => Recharge::STATUS_AUDITED])) {
-            $this->addError($attribute, '不存在充值流水号为' . $sn . '的已审核记录');
-        }
-        if ($oneWithdraw) {
-            $info = Info::baseInfo($oneWithdraw['USER_ID']);
-            if ($this->userName != $info['USER_NAME']) {
-                $this->addError($attribute, 'Excel中充值流水号' . $sn . '的用户名' . $this->userName . '与系统中的信息【' . $info['USER_NAME'] . '】不一致');
-            }
-            if ($this->amount != $oneWithdraw['AMOUNT']) {
-                $this->addError($attribute, 'Excel中充值流水号' . $sn . '的充值金额' . $this->amount . '与系统中的信息【' . $oneWithdraw['AMOUNT'] . '】不一致');
-            }
-            if ($this->bankRealName != $oneWithdraw['REAL_NAME']) {
-                $this->addError($attribute, 'Excel中充值流水号' . $sn . '的实时开户名' . $this->bankRealName . '与系统中的信息【' . $oneWithdraw['REAL_NAME'] . '】不一致');
-            }
-            if ($this->bankNo != $oneWithdraw['BANK_NO']) {
-                $this->addError($attribute, 'Excel中充值流水号' . $sn . '的实时银行账户' . $this->bankNo . '与系统中的信息【' . $oneWithdraw['BANK_NO'] . '】不一致');
-            }
-        }
-    }
-
-    /**
-     * 管理员充值
-     * @return null|string
-     * @throws \yii\db\Exception
-     */
-    public function recharge() {
-        if (!$this->validate()) {
-            return false;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            Cash::changeUserCash($this->_userId, 'CASH', $this->applyAmount, ['REMARK' => 'Background administrator recharge']);
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return false;
-        }
-        return true;
-    }
-
-
-    /**
-     * 添加充值申请
-     * @return null|string
-     * @throws \yii\db\Exception
-     */
-    public function add() {
-        if (!$this->validate()) {
-            return false;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $nowTime = Date::nowTime();
-            $period = Recharge::getPeriod($nowTime);
-            //增加记录
-            $userInfo = Info::baseInfo($this->_userId);
-
-            $rechargeModel = new Recharge();
-            $rechargeModel->SN = $this->_generateSn();
-            $rechargeModel->USER_ID = $this->_userId;
-            $rechargeModel->REAL_NAME = Info::getUserRealNameByUserId($this->_userId);
-            $rechargeModel->ID_CARD = $userInfo['ID_CARD'];
-            $rechargeModel->RECHARGE_PERIOD_NUM = $period['nowPeriodNum'];
-            $rechargeModel->RECHARGE_YEAR = $period['nowYear'];
-            $rechargeModel->RECHARGE_MONTH = $period['nowMonth'];
-            $rechargeModel->AMOUNT = $this->applyAmount;
-            $rechargeModel->OPEN_BANK = $this->openBank;
-            $rechargeModel->BANK_ADDRESS = $this->bankAddress;
-            $rechargeModel->BANK_NO = $this->bankNo;
-//            $rechargeModel->BANK_PROVINCE = $this->bankProvince ?? 0;
-//            $rechargeModel->BANK_CITY = $this->bankCity ?? 0;
-//            $rechargeModel->BANK_COUNTY = $this->bankCounty ?? 0;
-            $rechargeModel->P_MONTH = Date::ociToDate($period['yearMonth'], Date::OCI_TIME_FORMAT_SHORT_MONTH);
-            $rechargeModel->AUDIT_STATUS = Recharge::STATUS_APPLIED;
-            $rechargeModel->CREATED_AT = $nowTime;
-            if (!$rechargeModel->save()) {
-                throw new Exception(Form::formatErrorsForApi($rechargeModel->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return false;
-        }
-        return $rechargeModel;
-    }
-
-    /**
-     * 生成流水号
-     * @return string
-     */
-    private function _generateSn() {
-        return 'CZ' . Date::today('Ymd') . $this->_random(10, 1);
-    }
-
-    /**
-     * 生成随机数
-     *
-     * @param $length
-     * @param int $numeric
-     * @return string
-     */
-    private function _random($length, $numeric = 0) {
-        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
-        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
-        $hash = '';
-        $max = strlen($seed) - 1;
-        for ($i = 0; $i < $length; $i++) {
-            $hash .= $seed[mt_rand(0, $max)];
-        }
-        return $hash;
-    }
-
-    /**
-     * 设置充值订单的状态
-     * @return null|static
-     * @throws \yii\db\Exception
-     */
-    public function changeStatus() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $logs = [];
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $oneRecharge = Recharge::findOne(['ID' => $this->selectedIds]);
-            //判断状态
-            if (($msg = Recharge::chkAuditStatus($oneRecharge->SN, $oneRecharge->AUDIT_STATUS, $this->auditStatus)) != '') {
-                throw new Exception($msg);
-            }
-            //待审核->已审核 修改会员现金钱包
-            if ($this->auditStatus == Recharge::STATUS_AUDITED) {
-                Cash::changeUserCash($oneRecharge->USER_ID, 'CASH', abs($oneRecharge->AMOUNT), ['REMARK' => 'Review member recharge application']);
-            }
-            $oneRecharge->REMARK = $this->createRemark ?? '';
-            $oneRecharge->AUDIT_ADMIN = \Yii::$app->user->id;
-            $oneRecharge->AUDIT_STATUS = $this->auditStatus;
-            $oneRecharge->AUDITED_AT = Date::nowTime();
-            if (!$oneRecharge->save()) {
-                throw new Exception(Form::formatErrorsForApi($oneRecharge->getErrors()));
-            }
-            $logs[$this->selectedIds] = $oneRecharge->SN;
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('auditStatus', $e->getMessage());
-            return null;
-        }
-        return ['logs' => $logs, 'status' => $this->auditStatus];
-    }
-
-}

+ 0 - 359
common/models/forms/SendCFAndLXForm.php

@@ -1,359 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\Tool;
-use common\helpers\user\Balance;
-use common\helpers\user\Info;
-use common\libs\logging\operate\AdminOperate;
-use common\models\CFLXAudit;
-use common\models\DealType;
-use common\models\UserBonus;
-use common\models\UserTeamwork;
-use yii\base\Exception;
-
-/**
- * Login form
- *
- * @private CFLXAudit $_model
- */
-class SendCFAndLXForm extends Model {
-    public $id;
-    //public $year;
-    public $selectedIds;
-    public $statusValue;
-    public $sendType;
-    public $remark;
-    public $auditStatus;
-
-    private $_model;
-
-    const SEND_TYPES = ['all' => '车房养老奖和领袖分红奖', 'cf' => '车房养老奖', 'lx' => '领袖分红奖'];
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => UserBonus::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['id', 'remark', 'auditStatus', 'selectedIds', 'sendType', 'statusValue'], 'trim'],
-            [['id', 'auditStatus', 'remark', 'sendType', 'statusValue'], 'required'],
-            [['sendType'], 'isType'],
-            [['statusValue'], 'isStatusValue'],
-            [['selectedIds'], 'isSelected'],
-            [['auditStatus'], 'isAuditStatus'],
-        ];
-    }
-
-    public function attributeLabels() {
-        return [
-            'id' => '审核表ID',
-            'sendType' => '发放类型',
-            'statusValue' => '包含会员状态',
-            //'year' => '发放年度',
-            'remark' => '备注',
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'apply' => ['selectedIds', 'sendType', 'statusValue', 'remark'],
-            'audit' => ['selectedIds', 'auditStatus', 'remark'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    /**
-     * 年份是否正确
-     * @param $attribute
-     */
-    public function isYear($attribute) {
-        if (CFLXAudit::find()->where('YEAR=:YEAR AND AUDIT_STATUS=:AUDIT_STATUS', [':YEAR' => $this->year, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['true']['value']])->exists()) {
-            $this->addError($attribute, '本年度已经发放');
-        }
-    }
-
-    /**
-     * 发放类型
-     * @param $attribute
-     */
-    public function isType($attribute) {
-        if (!in_array($this->sendType, array_keys(self::SEND_TYPES))) {
-            $this->addError($attribute, '请选择正确的发放类型');
-        }
-    }
-
-    /**
-     * 状态类型校验
-     * @param $attribute
-     */
-    public function isStatusValue($attribute) {
-        foreach ($this->statusValue as $status) {
-            if (!array_key_exists($status, \Yii::$app->params['userStatus'])) {
-                $this->addError($attribute, '请选择正确的会员状态');
-                break;
-            }
-        }
-    }
-
-    /**
-     * 校验审核状态
-     * @param $attributes
-     */
-    public function isAuditStatus($attributes){
-        if (!array_key_exists($this->auditStatus, \Yii::$app->params['auditStatus'])) {
-            $this->addError($attributes, '无效的审核状态');
-        }
-    }
-
-    /**
-     * 批量数据
-     * @param $attributes
-     */
-    public function isSelected($attributes) {
-        if (!$this->selectedIds) {
-            $this->addError($attributes, 'A piece of data must be selected'); // 必须选择一条数据
-        }
-        if (!is_array($this->selectedIds)) {
-            $this->selectedIds = [$this->selectedIds];
-        }
-        if($this->scenario=='apply') {
-            $this->selectedIds = array_unique($this->selectedIds);
-            //根据会员状态及审核状态筛选
-            foreach ($this->selectedIds as $key => $value) {
-                if ($status = Info::getStatusByUserId($value)) {
-                    if (!in_array($status, $this->statusValue)) {
-                        unset($this->selectedIds[$key]);
-                    }
-                }
-                if (CFLXAudit::find()->where('USER_ID=:USER_ID AND AUDIT_STATUS =:AUDIT_STATUS', [':USER_ID' => $value, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['un']['value']])->exists()) {
-                    unset($this->selectedIds[$key]);
-                }
-            }
-            $this->selectedIds = array_values($this->selectedIds);
-        }
-    }
-
-    /**
-     * 申请
-     * @return CFLXAudit|null
-     * @throws \yii\db\Exception
-     */
-    public function add() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $model = $this->_model;
-            $model->YEAR = Date::nowYear();
-            $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
-            $model->CREATE_ADMIN = \Yii::$app->user->id;
-            $model->CREATE_REMARK = $this->remark;
-            $model->CREATED_AT = Date::nowTime();
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return null;
-        }
-        return $model;
-    }
-
-    /**
-     * 批量发放车房领袖
-     * @return array|null
-     * @throws \yii\db\Exception
-     */
-    public function apply() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $logs = [];
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            foreach ($this->selectedIds as $select) {
-                $model = new CFLXAudit();
-                if ($this->sendType == 'lx') {
-                    if (!$oneData = UserBonus::findOneAsArray('LX>0 AND USER_ID=:USER_ID', [':USER_ID' => $select])) continue;
-                    $model->LX = $oneData['LX'];
-                } elseif ($this->sendType == 'cf') {
-                    if (!$oneData = UserBonus::findOneAsArray('CF>0 AND USER_ID=:USER_ID', [':USER_ID' => $select])) continue;
-                    $model->CF = $oneData['CF'];
-                } else {
-                    if (!$oneData = UserBonus::findOneAsArray('(CF>0 OR LX>0) AND USER_ID=:USER_ID', [':USER_ID' => $select])) continue;
-                    $model->LX = $oneData['LX'];
-                    $model->CF = $oneData['CF'];
-                }
-                $model->USER_ID = $select;
-                $model->YEAR = Date::nowYear();
-                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
-                $model->CREATE_ADMIN = \Yii::$app->user->id;
-                $model->CREATE_REMARK = $this->remark;
-                $model->CREATED_AT = Date::nowTime();
-                if (!$model->save()) {
-                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-                }
-                /*if($model->LX>0){
-                    Balance::changeUserBonus($select, 'lx', -$model->LX, ['REMARK' => '年度领袖分红奖申请']);
-                }
-                if($model->CF>0){
-                    Balance::changeUserBonus($select, 'cf', -$model->CF, ['REMARK' => '年度车房养老奖申请']);
-                }*/
-                $logs[] = $model->ID;
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('apply', $e->getMessage());
-            return null;
-        }
-        $this->adminOperateLogger->fetchClass = CFLXAudit::class;
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($logs, 'ID');
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '年度奖申请发放',
-            'remark' => $this->remark,
-        ]);
-        return ['logs' => $logs, 'typeName' => self::SEND_TYPES[$this->sendType]];
-    }
-
-    /**
-     * 审核
-     * @return array|null
-     * @throws \yii\db\Exception
-     */
-    public function audit() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $logs = [];
-        $uids=[];
-        if($this->auditStatus=='true'){
-            foreach ($this->selectedIds as $select) {
-                $oneBalanceAudit = CFLXAudit::findOneAsArray('AUDIT_STATUS=0 AND ID=:ID',[':ID'=>$select],'USER_ID');
-                $uids[]=$oneBalanceAudit['USER_ID'];
-            }
-        }
-        if($this->auditStatus=='true'){
-            $this->adminOperateLogger->fetchClass = UserBonus::class;
-            $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($uids, 'USER_ID');
-        }else{
-            $this->adminOperateLogger->fetchClass = CFLXAudit::class;
-            $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->selectedIds, 'ID');
-        }
-
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            foreach ($this->selectedIds as $key => $select) {
-                $model=CFLXAudit::findOne(['ID'=>$select]);
-                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus'][$this->auditStatus]['value'];
-                $model->CREATE_REMARK = $this->remark?$this->remark:$model->CREATE_REMARK;
-                $model->AUDIT_ADMIN = \Yii::$app->user->id;
-                $model->AUDITED_AT = Date::nowTime();
-                if ($this->auditStatus == 'true') {
-                    if ($model->CF > 0) {
-                        Balance::changeUserBonus($model->USER_ID, 'cf', -$model->CF, ['REMARK' => '车房养老转出至会员账户', 'DEAL_TYPE_ID' => DealType::CF_TRANSFER_OUT]);
-                        Balance::changeUserBonus($model->USER_ID, 'bonus', $model->CF, ['SORT' => $key *10, 'REMARK' => '车房养老转入至会员账户', 'DEAL_TYPE_ID' => DealType::CF_TRANSFER_IN]);
-                        $this->_teamworkBonus($model->USER_ID, $model->CF, 'cf', $key);
-                    }
-                    if ($model->LX > 0) {
-                        Balance::changeUserBonus($model->USER_ID, 'lx', -$model->LX, ['REMARK' => '领袖分红转出至会员账户', 'DEAL_TYPE_ID' => DealType::LX_TRANSFER_OUT]);
-                        Balance::changeUserBonus($model->USER_ID, 'bonus', $model->LX, ['SORT' => $key *10 + 5, 'REMARK' => '领袖分红转入至会员账户', 'DEAL_TYPE_ID' => DealType::LX_TRANSFER_IN]);
-                        $this->_teamworkBonus($model->USER_ID, $model->LX, 'lx', $key);
-                    }
-                }
-                if (!$model->save()) {
-                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-                }
-                $logs[] = $model->USER_ID;
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('audit', $e->getMessage());
-            return null;
-        }
-
-        if($this->auditStatus=='true'){
-            $this->adminOperateLogger->fetchClass = UserBonus::class;
-            $this->adminOperateLogger->setIsBatch(true)->afterUpdate($uids, 'USER_ID')->clean()->save([
-                'optType' => '审核年度奖申请',
-                'remark' => $this->remark,
-            ]);
-        }else{
-            $this->adminOperateLogger->fetchClass = CFLXAudit::class;
-            $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->selectedIds, 'ID')->clean()->save([
-                'optType' => '审核年度奖申请',
-                'remark' => $this->remark,
-            ]);
-        }
-
-        return ['logs' => $logs];
-    }
-
-    /**
-     * 点位合作时转账
-     * @param $userId
-     * @param $amount
-     * @param null $type
-     * @return bool
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    private function _teamworkBonus($userId, $amount, $type = null, $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;
-        $fromUserName = Info::getUserNameByUserId($userId);
-        foreach ($teamwork as $value) {
-            $bonus = Tool::formatPrice($amount * $value['DIVIDE_PERCENT'] * 0.01);
-            if ($bonus <= 0) continue;
-            $toUserName = Info::getUserNameByUserId($value['USER_ID']);
-            if ($type == 'cf') {
-                Balance::changeUserBonus($userId, 'bonus', -abs($bonus), ['SORT' => $key*10+1, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_OUT, 'REMARK' => 'To:' . $toUserName . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
-                Balance::changeUserBonus($value['USER_ID'], 'bonus', abs($bonus), ['SORT' => $key*10+1, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_IN, 'REMARK' => 'From:' . $fromUserName . ' Per' . $value['DIVIDE_PERCENT'] . '%']);
-            } elseif ($type == 'lx') {
-                Balance::changeUserBonus($userId, 'bonus', -abs($bonus), ['SORT' => $key*10+2, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_OUT, 'REMARK' => 'To:' . $toUserName . ' 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:' . $fromUserName . ' Per' . $value['DIVIDE_PERCENT'] . '%']);
-            }
-        }
-    }
-
-    /**
-     * 删除前
-     * @param $selected
-     */
-    public function beforeDelete($selected) {
-        $this->adminOperateLogger->fetchClass = CFLXAudit::class;
-        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
-    }
-    /**
-     * 删除
-     * @param $selected
-     * @throws Exception
-     */
-    public function delete($selected) {
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '删除年度奖申请',
-        ]);
-    }
-
-}

+ 0 - 350
common/models/forms/ShopGoodsForm.php

@@ -1,350 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\helpers\Form;
-use common\helpers\LoggerTool;
-use common\libs\logging\operate\AdminOperate;
-use common\models\ShopGoods;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class ShopGoodsForm extends Model
-{
-    public $selectedIds;
-    public $id;
-    public $goodsName;
-    public $type;
-    public $sellDiscount;
-    public $giftType;
-    public $sellType;
-    public $pvSplit;
-    public $goodsNo;
-    public $unit;
-    public $taxRate;
-    public $cover;
-    public $sellPrice;
-    public $sellPriceStandard;
-    public $marketPrice;
-    public $pricePv;
-    //public $point;
-    public $storeNums;
-    public $content;
-    public $sort;
-    public $status;
-    public $categoryType;
-
-    private $_model;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => ShopGoods::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['id','sellDiscount','giftType','sellType','goodsNo', 'goodsName', 'unit', 'sellPrice', 'marketPrice', 'pricePv', 'storeNums', 'content', 'sort','status','cover'], 'trim'],
-            [['goodsName','sellDiscount','giftType','goodsNo', 'storeNums','sellPrice','marketPrice','pricePv', 'sort','status', 'categoryType', 'sellPriceStandard'], 'required'],
-            [['id'], 'required', 'on'=>'edit'],
-            [['id'], 'exist', 'targetClass'=>ShopGoods::class, 'targetAttribute'=>'ID'],
-            [['sellPrice','marketPrice','pricePv', 'sellPriceStandard'], 'price'],
-            [['id'], 'initModel'],
-            [['selectedIds'], 'isSelected'],
-            [['sort'], 'isSort'],
-            [['sellDiscount'], 'isDiscount'],
-        ];
-    }
-
-    public function attributeLabels()
-    {
-        return [
-            'selectedIds' => 'ID',
-            'id' => 'Product ID',
-            'goodsName' => 'Product Name', // 商品名称
-            'sellDiscount' => 'Discount Rate', // 会员折扣
-            'giftType' => 'Product Type', // 商品类型
-            'categoryType' => 'Product Category', // 商品分类
-            'sellType' => 'SellType', // 出售方式
-            'pvSplit' => 'PV Split', // pv分期
-            'goodsNo' => 'Product Code', // 产品编号
-            'unit' => 'Unit', // 单位
-            'cover' => 'Cover',// 封面
-            'sellPrice' => 'Price', // 销售价格
-            'sellPriceStandard' => 'US price',
-            'marketPrice' => 'Market Price', // 市场价格
-            'pricePv' => 'BV', // 销售PV
-            //'point' => '兑换积分',
-            'storeNums' => 'Inventory', // 库存
-            'content' => 'Content',
-            'listOrder' => 'Order',// 排序
-            'taxRate' => 'Tax',// 税率
-        ];
-    }
-
-    /**
-     * 指定场景
-     * @return array
-     */
-    public function scenarios()
-    {
-        $parentScenarios =  parent::scenarios();
-        $customScenarios = [
-            'add' => ['goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','sellPrice','marketPrice','pricePv','storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'taxRate', 'taxAmount','pvSplit'],
-            'edit' => ['id','goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','sellPrice','marketPrice','pricePv', 'storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'taxRate','pvSplit'],
-            'changeStatus' => ['selectedIds', 'status'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    /**
-     * 初始化model
-     * @param $attributes
-     */
-    public function initModel($attributes) {
-        $this->_model = ShopGoods::findOne(['ID' => $this->id]);
-        if (!$this->_model) {
-            $this->addError($attributes, 'The data does not exist'); // 数据不存在
-        }
-    }
-
-    /**
-     * 前置数据填充和校验.
-     * @return bool
-     */
-    public function beforeValidate()
-    {
-        if($this->categoryType){
-            // 处理sellType
-            $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
-            $sellType = $categoryType[$this->categoryType]['sell_type'] ?? [];
-//            print_r($formModel);
-//            print_r($this);
-//            exit;
-            if (!$sellType) {
-                $this->addError('add', '商品购买方式错误');
-            } else {
-                foreach ($sellType as $item) {
-                    if (!in_array($item['id'], array_keys(ShopGoods::SALE_TYPE))) {
-                        $this->addError('add', '商品购买方式错误');
-                        break;
-                    }
-                }
-                // 购买方式格式化为','分割的方式
-                $this->sellType = implode(',', array_column($sellType, 'id'));
-                // 如果是普通商品,有PV,旅游、名车、豪宅商品没有PV
-                if ($this->categoryType != 1) {
-                    $this->pricePv = 0;
-                }
-            }
-        }
-
-        return parent::beforeValidate();
-    }
-
-    /**
-     * 批量数据
-     * @param $attributes
-     */
-    public function isSelected($attributes) {
-        if (!$this->selectedIds) {
-            $this->addError($attributes, 'A piece of data must be selected'); // 必须选择一条数据
-        }
-        if (!is_array($this->selectedIds)) {
-            $this->selectedIds = [$this->selectedIds];
-        }
-    }
-    /**
-     * 排序需大于等于1
-     * @param $attributes
-     */
-    public function isSort($attributes) {
-        if ($this->sort < 1) {
-            $this->addError($attributes, '排序请填写大于等于1的数字');
-        }
-    }
-
-    // 折扣为0-1
-    public function isDiscount($attributes) {
-        if ($this->sellDiscount < 0 || $this->sellDiscount > 1 || !is_numeric($this->sellDiscount)) {
-            $this->addError($attributes, '折扣请填写0-1之间的数');
-        }
-    }
-
-    /**
-     * 添加
-     * @return ShopGoods|null
-     * @throws \yii\db\Exception
-     */
-    public function add() {
-        if (!$this->validate()) {
-            return null;
-        }
-
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            // 添加商品
-            $shopGoods = new ShopGoods();
-            $shopGoods->GOODS_NAME = $this->goodsName;
-            //$shopGoods->TYPE = $this->type;
-            $shopGoods->SELL_DISCOUNT = $this->sellDiscount;
-            $shopGoods->GIFT_TYPE = implode(',',$this->giftType);
-//             $shopGoods->SELL_TYPE = implode(',',$this->sellType);
-            $shopGoods->SELL_TYPE = $this->sellType;
-            $shopGoods->PV_SPLIT = $this->pvSplit;
-            $shopGoods->GOODS_NO = $this->goodsNo;
-            $shopGoods->UNIT = $this->unit ? $this->unit : '个';
-            $shopGoods->COVER = $this->cover ? $this->cover : '';
-            $shopGoods->SELL_PRICE_STANDARD = $this->sellPriceStandard;
-            $shopGoods->SELL_PRICE = $this->sellPrice;
-            $shopGoods->MARKET_PRICE = $this->marketPrice;
-            $shopGoods->PRICE_PV = $this->pricePv;
-            //$shopGoods->POINT = $this->point;
-            $shopGoods->CONTENT = $this->content;
-            $shopGoods->STORE_NUMS = $this->storeNums;
-            $shopGoods->TAX_RATE = $this->taxRate;
-            $shopGoods->SORT = $this->sort;
-            $shopGoods->CATE_ID = '1';
-            $shopGoods->CREATED_AT = Date::nowTime();
-            $shopGoods->CATEGORY_TYPE = $this->categoryType;
-            if (!$shopGoods->save()) {
-                throw new Exception(Form::formatErrorsForApi($shopGoods->getErrors()));
-            }
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return null;
-        }
-        return $shopGoods;
-    }
-
-    /**
-     * 编辑商品
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function edit() {
-        if (!$this->validate()) {
-            return null;
-        }
-
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $model = $this->_model;
-            $model->GOODS_NAME = $this->goodsName;
-            $model->TYPE = 0;
-            $model->SELL_DISCOUNT = $this->sellDiscount;
-            $model->GIFT_TYPE = implode(',',$this->giftType);
-//            $model->SELL_TYPE = implode(',',$this->sellType);
-            $model->SELL_TYPE = $this->sellType;
-            $model->PV_SPLIT = $this->pvSplit;
-            $model->GOODS_NO = $this->goodsNo;
-            $model->UNIT = $this->unit ? $this->unit : '个';
-            $model->COVER = $this->cover ? $this->cover : '';
-            $model->SELL_PRICE_STANDARD = $this->sellPriceStandard;
-            $model->SELL_PRICE = $this->sellPrice;
-            $model->MARKET_PRICE = $this->marketPrice;
-            $model->PRICE_PV = $this->pricePv;
-            $model->TAX_RATE = $this->taxRate;
-            //$model->POINT = $this->point;
-            $model->CONTENT = $this->content;
-            $model->STORE_NUMS = $this->storeNums;
-            $model->SORT = $this->sort;
-            $model->UPDATED_AT = Date::nowTime();
-            $model->CATEGORY_TYPE = $this->categoryType;
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-        return $model;
-    }
-
-    /**
-     * 上下架
-     * @return null|static
-     * @throws \yii\db\Exception
-     */
-    public function changeStatus() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            foreach ($this->selectedIds as $select) {
-                $oneGoods = ShopGoods::findOne(['ID' => $select]);
-                //判断状态
-                if (($msg = ShopGoods::chkAuditStatus($oneGoods->STATUS, $this->status)) != '') {
-                    throw new Exception($msg);
-                }
-                $oneGoods->STATUS = $this->status;
-                $oneGoods->UPDATED_AT = Date::nowTime();
-                if (!$oneGoods->save()) {
-                    throw new Exception(Form::formatErrorsForApi($oneGoods->getErrors()));
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('changeStatus', $e->getMessage());
-            return null;
-        }
-        return ['status' => $this->status];
-    }
-
-    /**
-     * 异步更新商品属性表
-     * @return bool
-     */
-    public function updateAsync(){
-        // 汇率
-        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
-        // 商品列表
-        $goods = ShopGoods::findAll(['STATUS' => 1]);
-
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            foreach ($goods as $good) {
-                $content = [
-                    'id'                => $good->ID,
-                    'exchangeRate'      => $exchangeRate,
-                    'priceStandard'     => $good->SELL_PRICE_STANDARD,
-                    'originSellPrice'   => $good->SELL_PRICE,
-                    'modernSellPrice'   => $good->SELL_PRICE_STANDARD * $exchangeRate,
-                ];
-
-                $good->SELL_PRICE = $good->SELL_PRICE_STANDARD * $exchangeRate;
-                $good->UPDATED_AT = Date::nowTime();
-                if (!$good->save()) {
-                    throw new Exception(Form::formatErrorsForApi($good->getErrors()));
-                }
-
-                $item = json_encode($content);
-                echo "商品 {$item} 更新成功!" . PHP_EOL;
-            }
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('update', $e->getMessage());
-            return false;
-        }
-        return true;
-    }
-}

+ 0 - 102
common/models/forms/TransferBonusForm.php

@@ -1,102 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\user\Balance;
-use common\models\Article;
-use common\models\ArticleCategory;
-use common\models\DealType;
-use common\models\Period;
-use common\models\Transfer;
-use common\models\User;
-use common\models\UserBind;
-use common\models\UserBonus;
-use common\models\UserInfo;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class TransferBonusForm extends Model
-{
-    public $toUserId;
-    public $amount;
-    public $fromUserId;
-
-    private $_fromUserInfo;
-    private $_toUserInfo;
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['toUserId', 'amount', 'fromUserId'], 'trim'],
-            [['toUserName', 'amount', 'fromUserId'], 'required'],
-            [['amount'], 'price'],
-            [['amount'], 'isAmount'],
-        ];
-    }
-
-    public function attributeLabels()
-    {
-        return [
-            'toUserId' => '转入会员编号',
-            'amount' => '金额',
-            'fromUserId' => '转出会员编号',
-        ];
-    }
-
-    /**
-     * 归集批量转账
-     * @param $main_uid
-     * @return Transfer|null
-     * @throws \yii\db\Exception
-     */
-    public function collectBind($main_uid){
-        $result = [];
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $userBinds = UserBind::findAllAsArray('MAIN_UID=:MAIN_UID AND IS_DEL=0',[':MAIN_UID'=>$main_uid]);
-            if(!$userBinds){
-                throw new Exception('不存在点位绑定关系');
-            }
-            $period = Period::instance();
-            $totals=0;
-            foreach ($userBinds as $value){
-                if($value['USER_ID']==$main_uid) continue;
-                $bonus=Balance::getAvailableBalance($value['USER_ID']);
-                if($bonus<=0) continue;
-                $totals+=$bonus;
-                Balance::changeUserBonus($value['USER_ID'], 'bonus', -abs($bonus), ['DEAL_TYPE_ID' => DealType::BIND_TRANSFER_OUT, 'REMARK' => 'To:'.$main_uid]);
-                Balance::changeUserBonus($main_uid, 'bonus', abs($bonus), ['DEAL_TYPE_ID' => DealType::BIND_TRANSFER_IN, 'REMARK' => 'From:'.$value['USER_ID']]);
-                $array = [
-                    'FROM_UID'=>$value['USER_ID'],
-                    'TO_UID'=>$main_uid,
-                    'FROM_WALLET'=>'bonus',
-                    'IN_WALLET'=>'bonus',
-                    'AMOUNT'=>$bonus,
-                    'PERIOD_NUM'=>$period->getNowPeriodNum(),
-                    'CALC_MONTH'=>$period->getNowYearMonth(),
-                    'CREATED_AT'=>Date::nowTime(),
-                ];
-                $result[] = $array;
-            }
-            if($result) Transfer::batchInsert($result);
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-        unset($parents ,$res ,$model);
-        return $totals;
-    }
-
-
-}

+ 0 - 375
common/models/forms/TransferForm.php

@@ -1,375 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\snowflake\SnowFake;
-use common\helpers\Tool;
-use common\helpers\user\Balance;
-use common\helpers\user\Cash;
-use common\helpers\user\Info;
-use common\libs\logging\operate\UserOperate;
-use common\models\Article;
-use common\models\ArticleCategory;
-use common\models\DealType;
-use common\models\DecOrder;
-use common\models\Order;
-use common\models\PerfPeriod;
-use common\models\Period;
-use common\models\Transfer;
-use common\models\User;
-use common\models\UserBind;
-use common\models\UserBonus;
-use common\models\UserInfo;
-use common\models\UserRelation;
-use common\models\UserSystem;
-use yii\base\Exception;
-use yii\helpers\Json;
-
-/**
- * Login form
- */
-class TransferForm extends Model {
-    const allowTransferType = [1, 2, 3];
-    const BONUS_TO_BALANCE = 1;
-    const BONUS_TO_BONUS = 2;
-    const BALANCE_TO_BALANCE = 3;
-
-    public $toUserName;
-    public $toRealName;
-    public $amount;
-    public $payPassword;
-    public $type;
-    public $remark;
-    public $transferCode;
-
-    private $_fromUserInfo;
-    private $_toUserInfo;
-    private $_transferProp;
-    private $_transferConfig;
-    private $_fee = 0;
-
-    public function init() {
-        parent::init();
-        $this->userOperateLogger = new UserOperate([
-            'fetchClass' => Transfer::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['toUserName', 'toRealName', 'amount', 'type', 'remark'], 'trim'],
-            [['toUserName', 'toRealName', 'amount', 'type', 'payPassword', 'transferCode'], 'required'],
-            [['toUserName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
-            [['type'], 'isType'],
-            [['toUserName'], 'initUser'],
-            [['amount'], 'price'],
-            [['amount'], 'isAmount'],
-            [['transferCode'], 'validateCode'],
-            [['payPassword'], 'validatePassword'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'transfer' => ['type', 'toUserName', 'toRealName', 'amount', 'remark', 'payPassword', 'transferCode'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'toUserName' => '转入会员编号',
-            'amount' => '金额',
-            'payPassword' => '支付密码',
-            'transferCode' => '转账校验码',
-        ];
-    }
-
-    /**
-     * 初始化转入转出用户信息
-     * @param $attribute
-     * @return null
-     * @throws Exception
-     */
-    public function initUser($attribute) {
-        // 转账记录
-        if(!$toUserId = Info::getUserIdByUserName($this->toUserName)){
-            $this->addError($attribute, '转入会员不存在');
-            return null;
-        }
-//        if(Info::getUserRealNameByUserId($toUserId)!=$this->toRealName){
-//            $this->addError($attribute, '转入会员会员姓名不正确');
-//            return null;
-//        }
-        $this->_toUserInfo = Info::baseInfo($toUserId);
-
-        $fromUserId = \Yii::$app->user->id;
-        $fromUser = Info::baseInfo($fromUserId);
-        if (!$fromUser) {
-            $this->addError($attribute, '转出会员不存在');
-            return null;
-        }
-        // 转账条件判断
-        $orderAmount = Order::find()->where('USER_ID=:USER_ID', [':USER_ID' => $fromUserId])->SUM('ORDER_AMOUNT');
-        $recNum = intval(DecOrder::find()->where('REC_USER_ID=:REC_USER_ID', [':REC_USER_ID' => $fromUserId])->count());
-        //$recNum = UserRelation::firstFloorChildNum($fromUserId);
-//        if ($orderAmount < 300 && $recNum==0) {
-//            $this->addError($attribute, '消费未满300元或未推荐新人,暂不能转账');
-//            return null;
-//        }
-        $this->_fromUserInfo = $fromUser;
-        //是否同体系转账
-//        if($this->_transferConfig['isSystem']==1){
-//            if($this->_toUserInfo['SYSTEM_ID']!=$this->_fromUserInfo['SYSTEM_ID']){
-//                $this->addError($attribute, '只能同一体系间转账');
-//                return null;
-//            }
-//        }
-
-        //是否点位绑定转账
-//        if ($this->_transferConfig['isBind'] == 1) {
-//            if (!UserBind::sameBind($this->_toUserInfo['ID'], $this->_fromUserInfo['ID'])) {
-//                $this->addError($attribute, '只能点位绑定在一起的会员之间转账');
-//                return null;
-//            }
-//        }
-
-
-
-        //奖金转奖金限同一身份证
-        /*if ($this->type == self::BONUS_TO_BONUS) {
-            $toIdCard = User::findOneAsArray('ID=:ID', [':ID' => $toUser['USER_ID']], 'ID_CARD');
-            $fromIdCard = User::findOneAsArray('ID=:ID', [':ID' => $fromUser['USER_ID']], 'ID_CARD');
-            if ($toIdCard['ID_CARD'] && ($toIdCard['ID_CARD'] != $fromIdCard['ID_CARD'])) {
-                $this->addError($attribute, '奖金转奖金只能在同一身份证下进行');
-                return null;
-            }
-        }*/
-        //奖金转现金限一周一次
-        /*if ($this->type == self::BONUS_TO_BALANCE) {
-            if (Transfer::hasThisWeekTransfer(\Yii::$app->user->id)) {
-                $this->addError($attribute, '转账失败,每周只可以转账一次');
-                return null;
-            }
-        }*/
-    }
-
-    /**
-     * 校验申请金额是否小于当前余额并符合配置中的设置
-     * @param $attribute
-     * @return null
-     */
-    public function isAmount($attribute) {
-        if(!$this->_fromUserInfo){
-            $this->addError($attribute, '会员信息未验证通过');
-            return null;
-        }
-        if ($this->amount <= 0) {
-            $this->addError($attribute, '转账金额必须大于0');
-        }
-        if ((int)$this->amount!=$this->amount) {
-            $this->addError('scenario', '转账金额必须是整数');
-        }
-        $minAmount = $this->_transferConfig['outMin'];
-        if ($this->amount < $minAmount) {
-            $this->addError($attribute, '转账金额低于转账下限');
-        }
-        $maxAmount = $this->_transferConfig['outMax'];
-        if ($maxAmount && $this->amount > $maxAmount) {
-            $this->addError($attribute, '转账金额高于转账上限');
-        }
-        //周转账上限
-        if($this->_transferConfig['weekMax']!=0){
-            if($this->amount+Transfer::weekTransfer($this->_fromUserInfo['ID'])>$this->_transferConfig['weekMax']){
-                $this->addError($attribute, '超出周转账上限');
-            }
-        }
-        //月转账上限
-        if($this->_transferConfig['monthMax']!=0){
-            if($this->amount+Transfer::monthTransfer($this->_fromUserInfo['ID'])>$this->_transferConfig['weekMax']){
-                $this->addError($attribute, '超出月转账上限');
-            }
-        }
-
-        // 获取当前用户的可用金额
-        if( $this->type == self::BALANCE_TO_BALANCE ) {
-            $haveBalance = Cash::getAvailableBalance($this->_fromUserInfo['ID']);
-        }else {
-            $haveBalance = Balance::getAvailableBalance($this->_fromUserInfo['ID']);
-        }
-        if ($this->amount > $haveBalance) {
-            $this->addError($attribute, '转账金额必须小于自己的可用余额');
-        }
-        // 转账比例
-        if ($this->type == self::BONUS_TO_BALANCE) {
-            $isCanTransferProp = Cache::getSystemConfig()['isCanTransferProp']['VALUE'];
-            if ($isCanTransferProp == 1) {
-                $maxAmount = Tool::formatPrice($this->_fromUserInfo['TRANSFER_PROP'] * Balance::getAvailableBalance($this->_fromUserInfo['ID']) * 0.01);
-                if ($this->amount > $maxAmount) {
-                    $this->addError($attribute, '转账金额超出转账比例限额');
-                }
-            }
-        }
-
-        //手续费
-        if($this->_transferConfig['fee']!=0){
-            $fee = Tool::formatPrice($this->amount * ($this->_transferConfig['fee']) * 0.01);
-            if($this->_transferConfig['feeMin']!=0&&$fee<$this->_transferConfig['feeMin']){
-                $fee = $this->_transferConfig['feeMin'];
-            }
-            if($this->_transferConfig['feeMax']!=0&&$fee>$this->_transferConfig['feeMax']){
-                $fee = $this->_transferConfig['feeMax'];
-            }
-            $this->_fee = $fee;
-        }
-    }
-
-    /**
-     * 转账类型判断
-     * @param $attribute
-     */
-    public function isType($attribute) {
-        if (!in_array($this->type, self::allowTransferType)) {
-            $this->addError($attribute, '不允许的转账类型');
-        }
-        //获取转账参数
-        if(!$this->_transferConfig = Json::decode(Cache::getSystemConfig()['allowWallet']['VALUE'])[$this->type-1]){
-            $this->addError($attribute, '错误的转账类型');
-        }
-        if(!$this->_transferConfig['isOpen']){
-            $this->addError($attribute, '不可用的转账类型');
-        }
-    }
-
-    /**
-     * 校验支付密码
-     * @param $attribute
-     * @param $params
-     */
-    public function validatePassword($attribute, $params) {
-        if (!User::validatePayPassword($this->_fromUserInfo['ID'], $this->payPassword)) {
-            $this->addError($attribute, '支付密码不正确');
-        }
-    }
-
-    public function validateCode($attribute, $params) {
-        $uid = \Yii::$app->user->id;
-        $redisCode = \Yii::$app->redis->getset('transferCode_'.$uid,'');
-        \Yii::$app->redis->del('transferCode_'.$uid);
-        if ($this->transferCode!=$redisCode) {
-            $this->addError($attribute, '转账校验失败'.$redisCode);
-        }
-    }
-    /**
-     * 生成随机数
-     * @param $length
-     * @param int $numeric
-     * @return string
-     */
-    public function random($length, $numeric = 0) {
-        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
-        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
-        $hash = '';
-        $max = strlen($seed) - 1;
-        for ($i = 0; $i < $length; $i++) {
-            $hash .= $seed[mt_rand(0, $max)];
-        }
-        return $hash;
-    }
-
-    /**
-     * 转账
-     * @return Transfer|null
-     * @throws \Exception
-     */
-    public function transfer() {
-        if (!$this->validate()) {
-            return null;
-        }
-
-        $fromData = Balance::getLogData($this->_fromUserInfo['ID']);
-        $toData = Balance::getLogData($this->_toUserInfo['ID']);
-        $this->userOperateLogger->saveBeforeContent=array_merge($fromData,$toData);
-
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $amount = Tool::formatPrice($this->amount - $this->_fee);
-            // 转账记录
-            $period = Period::instance();
-            $model = new Transfer();
-            $model->ID = SnowFake::instance()->generateId();
-            $model->TRANSFER_SN = Transfer::generateSN();
-            $model->OUT_UID = $this->_fromUserInfo['ID'];
-            $model->LAST_OUT_USER_NAME = $this->_fromUserInfo['USER_NAME'];
-            $model->LAST_OUT_REAL_NAME = $this->_fromUserInfo['REAL_NAME'];
-            $model->LAST_OUT_DEC_LV = $this->_fromUserInfo['DEC_LV'];
-            $model->LAST_OUT_DEC_ROLE_ID = $this->_fromUserInfo['DEC_ROLE_ID'];
-            $model->OUT_WALLET = $this->_transferConfig['out'];
-            $model->LAST_OUT_SYSTEM_ID = $this->_fromUserInfo['SYSTEM_ID'] ? $this->_fromUserInfo['SYSTEM_ID'] : '';
-            $model->IN_UID = $this->_toUserInfo['ID'];
-            $model->LAST_IN_USER_NAME = $this->_toUserInfo['USER_NAME'];
-            $model->LAST_IN_REAL_NAME = $this->_toUserInfo['REAL_NAME'];
-            $model->LAST_IN_DEC_LV = $this->_toUserInfo['DEC_LV'];
-            $model->IN_WALLET = $this->_transferConfig['in'];
-            $model->LAST_IN_SYSTEM_ID = $this->_toUserInfo['SYSTEM_ID'] ? $this->_toUserInfo['SYSTEM_ID'] : '';
-            $model->ORI_AMOUNT = $this->amount;
-            $model->FEE = $this->_fee;
-            $model->AMOUNT = $amount;
-            $model->REMARK = $this->remark;
-            $model->PERIOD_NUM = $period->getNowPeriodNum();
-            $model->CALC_MONTH = $period->getNowYearMonth();
-            $model->CREATED_AT = Date::nowTime();
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            if ($this->type == self::BONUS_TO_BALANCE) {
-                // 会员金额减少
-                Balance::changeUserBonus($this->_fromUserInfo['ID'], 'bonus', -abs($this->amount), ['TRANSFER_SN' => $model->TRANSFER_SN, 'DEAL_TYPE_ID' => DealType::TRANSFER_OUT, 'REMARK' => 'To:' . $this->_toUserInfo['USER_NAME'] . ',' . $this->remark]);
-                Cash::changeUserCash($this->_toUserInfo['ID'], 'CASH', abs($amount), ['TRANSFER_SN' => $model->TRANSFER_SN,'DEAL_TYPE_ID' => DealType::TRANSFER_IN, 'REMARK' => 'From:' . $this->_fromUserInfo['USER_NAME'] . ',' . $this->remark]);
-            } elseif($this->type == self::BONUS_TO_BONUS) {
-                // 会员金额减少
-                Balance::changeUserBonus($this->_fromUserInfo['ID'], 'bonus', -abs($this->amount), ['TRANSFER_SN' => $model->TRANSFER_SN, 'DEAL_TYPE_ID' => DealType::TRANSFER_OUT, 'REMARK' => 'To:' . $this->_toUserInfo['USER_NAME'] . ',' . $this->remark]);
-                Balance::changeUserBonus($this->_toUserInfo['ID'], 'bonus', abs($amount), ['TRANSFER_SN' => $model->TRANSFER_SN, 'DEAL_TYPE_ID' => DealType::TRANSFER_IN, 'REMARK' => 'From:' . $this->_fromUserInfo['USER_NAME'] . ',' . $this->remark]);
-            }else if ($this->type == self::BALANCE_TO_BALANCE) {
-                // 会员金额减少
-                Cash::changeUserCash($this->_fromUserInfo['ID'], 'CASH', -abs($this->amount), ['TRANSFER_SN' => $model->TRANSFER_SN,'DEAL_TYPE_ID' => DealType::TRANSFER_OUT, 'REMARK' => 'To:' . $this->_toUserInfo['USER_NAME'] . ',' . $this->remark]);
-                Cash::changeUserCash($this->_toUserInfo['ID'], 'CASH', abs($amount), ['TRANSFER_SN' => $model->TRANSFER_SN,'DEAL_TYPE_ID' => DealType::TRANSFER_IN, 'REMARK' => 'From:' . $this->_fromUserInfo['USER_NAME'] . ',' . $this->remark]);
-            }else {
-                throw new \Exception('错误的交易类型');
-            }
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-
-        $fromData = Balance::getLogData($this->_fromUserInfo['ID']);
-        $toData = Balance::getLogData($this->_toUserInfo['ID']);
-        $this->userOperateLogger->saveAfterContent=array_merge($fromData,$toData);
-        unset($fromData,$toData);
-        $this->userOperateLogger->clean()->save([
-            'optType' => '会员转账',
-            'userId' => \Yii::$app->user->id,
-            'userName' => Info::getUserNameByUserId(\Yii::$app->user->id),
-            'remark' => $this->remark,
-        ]);
-        return $model;
-    }
-
-
-}

+ 0 - 227
common/models/forms/UserBasicForm.php

@@ -1,227 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Date;
-use common\libs\logging\operate\AdminOperate;
-use common\models\User;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class UserBasicForm extends Model {
-    public $userId;
-    public $password;
-    public $passwordType;
-
-    //个人资料
-    public $nation;
-    public $realName;
-    public $idCard;
-    public $mobile;
-    public $openBank;
-    public $bankAddress;
-    public $bankNo;
-
-    public $status;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => User::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['userId', 'password', 'passwordType','realName', 'mobile','openBank','bankAddress','bankNo','status'], 'trim'],
-            [['userId'], 'required'],
-            [[/*'idCard', */'allData'], 'required', 'on'=>['addWithUserName']],
-            [['nation','realName', 'mobile', /*'idCard', */'openBank', 'bankAddress', 'bankNo'], 'required', 'on'=>'modifyProfile'],
-            [['mobile'], 'mobile'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'modifyPassword' => ['userId', 'password', 'passwordType'],
-            'modifyProfile' => ['userId','realName',/*'idCard',*/'mobile','openBank','bankAddress','bankNo'],
-            'modifyStatus' => ['userId','status'],
-            'isModifyPasswordStatus' => ['userId','status'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'ID' => 'ID',
-            'password' => '密码',
-            'passwordType' => '密码类型',
-//            'nation' => '民族',
-            'realName' => '真实姓名',
-//            'idCard' => '身份证号',
-            'mobile' => '手机号',
-            'openBank' => '银行名称',
-            'bankAddress' => '开户支行',
-            'bankNo' => '银行账号',
-            'status' => '状态',
-        ];
-    }
-
-    public function beforeValidate() {
-        return parent::beforeValidate();
-    }
-
-    /**
-     * 编辑用户信息
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function edit() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $userModel = User::findOne(['ID'=>$this->userId]);
-            if( $this->passwordType === 'password' ) {
-                $userModel->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
-            }else {
-                $userModel->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->password);
-            }
-
-            if( !$userModel->save(false) ) {
-                throw new Exception($userModel->getErrors());
-            }
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            return null;
-        }
-
-        return $userModel;
-
-    }
-
-    /**
-     * 修改个人资料
-     * @return User|null
-     * @throws \yii\db\Exception
-     */
-    public function modifyProfile(){
-        if(!$this->validate()){
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $userModel = User::findOne(['ID' => $this->userId]);
-            $this->adminOperateLogger->beforeUpdate($userModel);
-//            $userModel->NATION = $this->nation;
-            $userModel->REAL_NAME = $this->realName;
-            $userModel->MOBILE = $this->mobile;
-//            $userModel->ID_CARD = $this->idCard;
-            $userModel->OPEN_BANK = $this->openBank;
-            $userModel->BANK_NO = $this->bankNo;
-            $userModel->BANK_ADDRESS = $this->bankAddress;
-            if( !$userModel->save(false) ) {
-                throw new Exception($userModel->getErrors());
-            }
-            $transaction->commit();
-            $this->adminOperateLogger->afterUpdate($userModel)->clean()->save([
-                'optType' => 'Modification of Member information', // 修改会员资料
-                'userId' => $this->userId,
-                'userName' => $userModel->USER_NAME,
-//                'nation' => $this->nation,
-                'realName' => $this->realName,
-                'mobile' => $this->mobile,
-//                'idCard' => $this->idCard,
-                'openBank' => $this->openBank,
-                'bankNo' => $this->bankNo,
-                'bankAddress' => $this->bankAddress,
-            ]);
-        }catch (Exception $e) {
-            $transaction->rollBack();
-            return null;
-        }
-        return $userModel;
-    }
-
-
-    /**
-     * 修改会员状态
-     * @return User|null
-     * @throws \yii\db\Exception
-     */
-    public function modifyStatus(){
-        if(!$this->validate()){
-            return null;
-        }
-        $this->adminOperateLogger->beforeUpdate($this->userId, 'ID',['select'=>'ID,STATUS']);
-
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $userModel = User::findOne(['ID' => $this->userId]);
-            if($userModel->STATUS==$this->status){
-                $statusName = ($userModel->STATUS == 1) ? 'activation' : 'lock'; // 激活 锁定
-                throw new Exception('The current member status is【' . $statusName . '】,Do not need to set it again!'); // 当前会员状态已  无需重复设置
-            }
-            $userModel->STATUS = $this->status;
-            $userModel->STATUS_AT = Date::nowTime();
-            if( !$userModel->save(false) ) {
-                throw new Exception($userModel->getErrors());
-            }
-            $transaction->commit();
-        }catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('modifyStatus', $e->getMessage());
-            return null;
-        }
-        $this->adminOperateLogger->afterUpdate($this->userId,'ID',['select'=>'ID,STATUS'])->clean()->save([
-            'optType' => ($this->status == 1) ? 'Member activation' : 'Member of the lock', // 会员激活 会员锁定
-        ]);
-        return $userModel;
-    }
-
-    /**
-     * @return User|null
-     * @throws \yii\db\Exception
-     */
-    public function isModifyPasswordStatus(){
-        if(!$this->validate()){
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $userModel = User::findOne(['ID' => $this->userId]);
-            if($userModel->IS_MODIFY_PASSWORD==$this->status){
-                throw new Exception('The status has not changed, and do not need to set it again');// 状态没有发生改变,无需重复设置!
-            }
-            $userModel->IS_MODIFY_PASSWORD = $this->status;
-            if( !$userModel->save(false) ) {
-                throw new Exception($userModel->getErrors());
-            }
-            $transaction->commit();
-        }catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('isModifyPasswordStatus', $e->getMessage());
-            return null;
-        }
-        return $userModel;
-    }
-
-}

+ 0 - 377
common/models/forms/UserBindForm.php

@@ -1,377 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\helpers\user\Info;
-use common\helpers\user\Status;
-use common\components\Model;
-use common\helpers\Form;
-use common\libs\logging\operate\AdminOperate;
-use common\libs\logging\operate\UserOperate;
-use common\models\Period;
-use common\models\User;
-use common\models\UserBind;
-use common\models\UserInfo;
-use yii\base\Exception;
-
-/**
- * 点位绑定表单
- */
-class UserBindForm extends Model {
-    public $id;
-    public $userId;
-    public $mainUid;
-    public $userName;
-    public $mainUserName;
-
-    private $_uid;
-    private $_mainUid;
-    private $_model;
-    private $_userIdcard;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => UserBind::class,
-        ]);
-        $this->userOperateLogger = new UserOperate([
-            'fetchClass' => UserBind::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['id', 'userName', 'mainUserName', 'mainUid', 'userId'], 'trim'],
-            [['id', 'userName', 'mainUserName'], 'required'],
-            [['userName'], 'isUserName'],
-            [['mainUserName'], 'isMainUserName'],
-            //[['mainUid'], 'isMainUid'],
-            //[['userId'], 'isUserId'],
-            [['id'], 'initModel'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'add' => ['userName', 'mainUserName'],
-            'edit' => ['id', 'mainUid'],
-            'frontEdit' => ['id', 'mainUid'],
-            'autoBind' => ['userId', 'mainUid'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'userName' => '会员编号',
-            'mainUserName' => '主会员编号',
-        ];
-    }
-
-    /**
-     * 初始化model
-     * @param $attributes
-     */
-    public function initModel($attributes) {
-        $this->_model = UserBind::findOne(['ID' => $this->id]);
-        if (!$this->_model) {
-            $this->addError($attributes, 'The data does not exist'); // 数据不存在
-        }
-        if($this->scenario=='frontEdit'){
-            if (Info::getIdCardByUserId(\Yii::$app->user->id) != Info::getIdCardByUserId($this->_model['MAIN_UID'])) {
-                $this->addError($attributes, '无权限编辑');
-            }
-        }
-    }
-
-    /**
-     * 用户名是否正确
-     * @param $attributes
-     */
-    public function isUserName($attributes) {
-        if ($this->userName == $this->mainUserName) {
-            $this->addError($attributes, '同一会员不能绑定');
-        }
-        $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
-        if ($userInfo && Info::isVerified(($userInfo['USER_ID']))) {
-            if (UserBind::find()->where('USER_ID=:USER_ID AND IS_DEL=0', [':USER_ID' => $userInfo['USER_ID']])->exists()) {
-                $this->addError($attributes, '填写的会员已有绑定关系');
-            }
-            $this->_uid = $userInfo['USER_ID'];
-        } else {
-            $this->addError($attributes, '会员不存在或未完成实名认证');
-        }
-
-    }
-
-    /**
-     * 主会员编号
-     * @param $attributes
-     */
-    public function isMainUserName($attributes) {
-        $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->mainUserName]);
-        if ($userInfo && Info::isVerified(($userInfo['USER_ID']))) {
-            if (UserBind::find()->where('USER_ID=:USER_ID AND IS_DEL=0 AND MAIN_UID!=:USER_ID', [':USER_ID' => $userInfo['USER_ID']])->exists()) {
-                $this->addError($attributes, '填写的主会员已被其他主会员绑定');
-            }
-            $this->_mainUid = $userInfo['USER_ID'];
-        } else {
-            $this->addError($attributes, '主会员不存在或未完成实名认证');
-            return false;
-        }
-        if (Info::getIdCardByUserId($this->_uid) != Info::getIdCardByUserId($this->_mainUid)) {
-            $this->addError($attributes, '两个会员身份证号不一致无法绑定');
-        }
-        $idCard = Info::getIdCardByUserId($this->_mainUid);
-        //是否有其他绑定关系
-        $hasUsers = User::find()->select('ID')->where('ID!=:ID AND ID!=:IDU AND VERIFIED=1 AND ID_CARD=:ID_CARD', [':ID' => $this->_mainUid, ':IDU'=>$this->_uid, ':ID_CARD' => $idCard])->orderBy('CREATED_AT ASC')->asArray()->all();
-        if($hasUsers){
-            foreach ($hasUsers as $u){
-                if (UserBind::find()->where('USER_ID=:USER_ID AND IS_DEL=0 AND MAIN_UID!=:MAIN_UID', [':USER_ID' => $u['ID'], ':MAIN_UID'=>$this->_mainUid])->exists()) {
-                    $this->addError($attributes, '身份证'.$idCard.'有其他的绑定关系,请查证');
-                    break;
-                }
-            }
-        }
-    }
-
-    public function isMainUid($attributes) {
-        if(!Info::isVerified($this->mainUid)){
-            $this->addError($attributes, '主会员未完成实名认证');
-            return false;
-        }
-    }
-
-    public function isUserId($attributes) {
-        if(!Info::isVerified($this->userId)){
-            $this->addError($attributes, '会员未完成实名认证');
-            return false;
-        }
-    }
-
-
-
-    /**
-     * 添加
-     * @return UserBind|null
-     * @throws \yii\base\Exception
-     */
-    public function add() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $period = Period::instance();
-
-            // 查看主点位是否已经存在
-            if (!UserBind::find()->where('USER_ID=:USER_ID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':USER_ID' => $this->_mainUid, ':MAIN_UID' => $this->_mainUid])->exists()) {
-                UserBind::insertOne([
-                    'USER_ID' => $this->_mainUid,
-                    'MAIN_UID' => $this->_mainUid,
-                    'PERIOD_NUM' => $period->getNowPeriodNum(),
-                    'IS_DEL' => 0,
-                    'CREATE_ADMIN' => \Yii::$app->user->id,
-                    'CREATED_AT' => Date::nowTime(),
-                ]);
-            }
-            // 会员信息表添加点位合作标识
-            UserInfo::updateAll(['IS_BIND' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_uid]);
-            UserInfo::updateAll(['IS_BIND' => 1, 'IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_mainUid]);
-            // 添加会员合作点位
-            $model = new UserBind();
-            $model->USER_ID = $this->_uid;
-            $model->MAIN_UID = $this->_mainUid;
-            $model->PERIOD_NUM = $period->getNowPeriodNum();
-            $model->IS_DEL = 0;
-            $model->CREATE_ADMIN = \Yii::$app->user->id;
-            $model->CREATED_AT = Date::nowTime();
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return null;
-        }
-        $this->adminOperateLogger->afterInsert($model);
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '添加点位绑定',
-            'userId' => $model->USER_ID,
-            'userName' => Info::getUserNameByUserId($model->USER_ID),
-        ]);
-        return $model;
-    }
-
-    /**
-     * 前台编辑主点位
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function frontEdit() {
-        if (!$this->validate()) {
-            return null;
-        }
-
-        $this->userOperateLogger->beforeUpdate($this->_model->ID,'ID',['select'=>'USER_ID,MAIN_UID']);
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $model = $this->_model;
-            if ($model->MAIN_UID == $this->mainUid) {
-                throw new Exception('未做任何修改');
-            }
-            //撤销主会员
-            UserInfo::updateAll(['IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $model->MAIN_UID]);
-            //设置主会员
-            UserInfo::updateAll(['IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->mainUid]);
-            //更新绑定表的主会员
-            UserBind::updateAll(['MAIN_UID' => $this->mainUid, 'UPDATED_AT' => Date::nowTime(), 'UPDATE_ADMIN' => \Yii::$app->user->id], 'MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $model->MAIN_UID]);
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('frontEdit', $e->getMessage());
-            return null;
-        }
-        $this->userOperateLogger->afterUpdate($this->_model->ID,'ID',['select'=>'USER_ID,MAIN_UID']);
-
-        $this->userOperateLogger->clean()->save([
-            'optType' => '修改主点位',
-            'userId' => $model->USER_ID,
-            'userName' => Info::getUserNameByUserId($model->USER_ID),
-        ]);
-        return $model;
-    }
-
-    /**
-     * 编辑主点位
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function edit() {
-        if (!$this->validate()) {
-            return null;
-        }
-
-        $this->adminOperateLogger->beforeUpdate($this->_model);
-
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $model = $this->_model;
-            if ($model->MAIN_UID == $this->mainUid) {
-                throw new Exception('未做任何修改');
-            }
-            //撤销主会员
-            UserInfo::updateAll(['IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $model->MAIN_UID]);
-            //设置主会员
-            UserInfo::updateAll(['IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->mainUid]);
-            //更新绑定表的主会员
-            UserBind::updateAll(['MAIN_UID' => $this->mainUid, 'UPDATED_AT' => Date::nowTime(), 'UPDATE_ADMIN' => \Yii::$app->user->id], 'MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $model->MAIN_UID]);
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-        $this->adminOperateLogger->afterUpdate(UserBind::findOne(['ID' => $this->id]));
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '编辑点位绑定',
-            'userId' => $model->USER_ID,
-            'userName' => Info::getUserNameByUserId($model->USER_ID),
-        ]);
-        return $model;
-    }
-
-    public function beforeDelete($selected){
-        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
-    }
-
-    /**
-     * 删除
-     * @param $selected
-     * @throws Exception
-     */
-    public function delete($selected) {
-        foreach ($selected as $select) {
-            $userBind = UserBind::findOneAsArray('ID=:ID', [':ID' => $select], 'USER_ID,MAIN_UID');
-            //无法删除有子会员的
-            if (UserBind::find()->where('MAIN_UID=:USER_ID AND IS_DEL=0 AND USER_ID!=:USER_ID', [':USER_ID' => $userBind['USER_ID']])->exists()) {
-                throw new Exception('该主会员有子会员,无法撤销');
-            }
-            UserInfo::updateAll(['IS_BIND' => 0, 'IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userBind['USER_ID']]);
-            User::updateAll(['VERIFIED' => 0], 'ID=:USER_ID', [':USER_ID' => $userBind['USER_ID']]);
-            $bindNum = UserBind::findOneAsArray('IS_DEL=0 AND MAIN_UID=:MAIN_UID', [':MAIN_UID' => $userBind['MAIN_UID']],'COUNT(*) AS NUM');
-            if (isset($bindNum['NUM']) && $bindNum['NUM'] < 2) {
-                UserBind::updateAll(['IS_DEL' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $userBind['MAIN_UID']]);
-                UserInfo::updateAll(['IS_BIND' => 0, 'IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userBind['MAIN_UID']]);
-            }
-        }
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '撤销点位绑定',
-        ]);
-    }
-
-    /**
-     * 自动绑定点位
-     * @return UserBind|null
-     * @throws \yii\db\Exception
-     */
-    public function autoBind() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            //判断hz
-            if (Info::isUnion($this->mainUid) && !Info::isUnion($this->userId)) {
-                $userId = $this->mainUid;
-                $this->mainUid = $this->userId;
-                $this->userId = $userId;
-            }
-
-            $period = Period::instance();
-            // 查看主点位是否已经存在
-            if (!UserBind::find()->where('USER_ID=:USER_ID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':USER_ID' => $this->mainUid, ':MAIN_UID' => $this->mainUid])->exists()) {
-                UserBind::insertOne([
-                    'USER_ID' => $this->mainUid,
-                    'MAIN_UID' => $this->mainUid,
-                    'PERIOD_NUM' => $period->getNowPeriodNum(),
-                    'IS_DEL' => 0,
-                    'CREATE_ADMIN' => \Yii::$app->id == 'app-backendApi' ? \Yii::$app->user->id : null,
-                    'CREATED_AT' => Date::nowTime(),
-                ]);
-            }
-            // 会员信息表添加点位合作标识
-            UserInfo::updateAll(['IS_BIND' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->userId]);
-            UserInfo::updateAll(['IS_BIND' => 1, 'IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->mainUid]);
-            // 添加会员合作点位
-            $model = new UserBind();
-            $model->USER_ID = $this->userId;
-            $model->MAIN_UID = $this->mainUid;
-            $model->PERIOD_NUM = $period->getNowPeriodNum();
-            $model->IS_DEL = 0;
-            $model->CREATE_USER = $this->userId;
-            $model->CREATED_AT = Date::nowTime();
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('autoAdd', $e->getMessage());
-            return null;
-        }
-        return $model;
-    }
-
-}

+ 0 - 269
common/models/forms/UserCloseForm.php

@@ -1,269 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\user\Status;
-use common\models\Period;
-use common\models\User;
-use common\models\UserClose;
-use common\models\UserInfo;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class UserCloseForm extends Model {
-    public $id;
-    public $userName;
-    public $type;
-    public $isClose;
-    public $remark;
-    public $auditStatus;
-
-    private $_userId;
-    private $_userCloseModel;
-    private $_periodNum;
-    private $_closeInfo = [
-        UserClose::TYPE_GT => '关停',
-        UserClose::TYPE_TF => '停发',
-    ];
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['id', 'userName', 'type', 'isClose', 'remark', 'auditStatus'], 'trim'],
-            [['id', 'userName', 'type', 'isClose'], 'required'],
-            [['userName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
-            [['id', 'userName'], 'initModel'],
-            [['id'], 'exist', 'targetClass' => UserClose::class, 'targetAttribute' => 'ID'],
-            [['type'], 'isType'],
-            [['isClose'], 'checkClose'],
-            [['auditStatus'], 'isAuditStatus'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            // 手动申请
-            'add' => ['userName', 'type', 'isClose', 'remark'],
-            // 自动关停
-            'auto' => ['userName', 'type', 'isClose', 'remark'],
-            // 审核关停
-            'audit' => ['id', 'auditStatus']
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'id' => 'ID',
-            'userName' => '会员编号',
-            'type' => '类型',
-            'isClose' => '是否关停',
-            'remark' => '备注',
-        ];
-    }
-
-    /**
-     * 初始化model和userId
-     * @param $attribute
-     */
-    public function initModel($attribute) {
-        $period = Period::instance();
-        $this->_periodNum = $period->getNowPeriodNum();
-        if ($this->scenario == 'audit') {
-            $this->_userCloseModel = UserClose::findOne(['ID' => $this->id]);
-            $this->_userId = $this->_userCloseModel->USER_ID;
-        } elseif ($this->scenario == 'add' || $this->scenario == 'auto') {
-            $this->_userCloseModel = new UserClose();
-            $oneUser = UserInfo::findOneAsArray(['USER_NAME' => $this->userName], [], 'USER_ID');
-            $this->_userId = $oneUser['USER_ID'];
-            // 查看数据库中是否已经存在了该会员的申请未审核
-            $oneUserClose = UserClose::findOne(['USER_ID' => $this->_userId, 'AUDIT_STATUS' => \Yii::$app->params['auditStatus']['un']['value'], 'TYPE' => $this->type]);
-            if ($oneUserClose && $this->scenario == 'add') {
-                // 不允许重复申请
-                $this->addError($attribute, '已经存在该会员的待审核数据,请等待审核后再申请');
-            } elseif ($oneUserClose && $this->scenario == 'auto') {
-                // 如果是自动关停时,如果遇上未审核的,直接审核拒绝,防止影响自动关停的进程
-                $oneUserClose->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
-                $oneUserClose->AUDITED_AT = Date::nowTime();
-                $oneUserClose->save();
-            }
-        } else {
-            $this->addError($attribute, '场景不正确');
-        }
-    }
-
-    /**
-     * 关停还是停发
-     * @param $attribute
-     */
-    public function isType($attribute) {
-        if (!in_array($this->type, [UserClose::TYPE_GT, UserClose::TYPE_TF])) {
-            $this->addError($attribute, '类型不正确');
-        }
-    }
-
-    /**
-     * 校验该用户是否已经被关闭
-     * @param $attribute
-     */
-    public function checkClose($attribute) {
-        if ($this->type == UserClose::TYPE_GT) {
-            if ($this->isClose == 1 && Status::isCloseAccount($this->_userId)) {
-                $this->addError($attribute, '该会员已经被关停');
-            } elseif ($this->isClose == 0 && !Status::isCloseAccount($this->_userId)) {
-                $this->addError($attribute, '该会员没有被关停');
-            }
-        } elseif ($this->type == UserClose::TYPE_TF) {
-            if ($this->isClose == 1 && Status::isCloseBonus($this->_userId)) {
-                $this->addError($attribute, '该会员已经被停发');
-            } elseif ($this->isClose == 0 && !Status::isCloseBonus($this->_userId)) {
-                $this->addError($attribute, '该会员没有被停发');
-            }
-        }
-    }
-
-    /**
-     * 审核状态是否正确
-     * @param $attributes
-     */
-    public function isAuditStatus($attributes) {
-        if (!array_key_exists($this->auditStatus, \Yii::$app->params['auditStatus'])) {
-            $this->addError($attributes, '无效的审核状态');
-        }
-    }
-
-    /**
-     * 申请
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function edit() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $model = $this->_userCloseModel;
-            $model->USER_ID = $this->_userId;
-            $model->TYPE = $this->type;
-            $model->PERIOD_NUM = $this->_periodNum;
-            $model->IS_CLOSE = $this->isClose;
-            $model->REMARK = $this->remark;
-            if ($this->scenario == 'add') {
-                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
-                $model->IS_MANUAL = 1;
-                $model->ADMIN_ID = \Yii::$app->user->id;
-            } elseif ($this->scenario == 'auto') {
-                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
-                $model->AUDITED_AT = Date::nowTime();
-            } else {
-                $this->addError('setClose', '场景不正确');
-            }
-            $model->CREATED_AT = Date::nowTime();
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            // 把商城会员表的状态改为0
-            $isCloseShopUser = false;
-            $closeShopStatus = 0;
-            if ($this->scenario == 'auto' && $this->type == UserClose::TYPE_GT && $this->isClose == 1) {
-                $isCloseShopUser = true;
-                $closeShopStatus = 0;
-            } elseif ($this->scenario == 'auto' && $this->type == UserClose::TYPE_GT && $this->isClose == 0) {
-                $isCloseShopUser = true;
-                $closeShopStatus = 1;
-            }
-            if ($isCloseShopUser) {
-                $oneUser = User::findOne(['ID' => $this->_userId]);
-                $oneUser->STATUS = $closeShopStatus;
-                if (!$oneUser->save()) {
-                    throw new Exception(Form::formatErrorsForApi($oneUser->getErrors()));
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-        return $model;
-
-    }
-
-    /**
-     * 审核
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function audit() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $model = $this->_userCloseModel;
-            if ($this->auditStatus == 'true') {
-                $model->AUDIT_ADMIN_ID = \Yii::$app->user->id;
-                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
-                $model->AUDITED_AT = Date::nowTime();
-                if (!$model->save()) {
-                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-                }
-                if ($model->IS_CLOSE) {
-                    $closedAt = Date::nowTime();
-                } else {
-                    $closedAt = 0;
-                }
-                // 修改结算系统会员表的状态
-                $closeField = UserClose::TYPE_GT ? 'CLOSE_ACCOUNT' : 'CLOSE_BONUS';
-                UserInfo::updateAll([$closeField => $model->IS_CLOSE, 'CLOSE_ACCOUNT_AT' => $closedAt], 'USER_ID=:USER_ID', [':USER_ID' => $this->_userId]);
-                // 把商城会员表的状态改为0
-                $isCloseShopUser = false;
-                $closeShopStatus = 0;
-                if ($model->TYPE == UserClose::TYPE_GT && $model->IS_CLOSE == 1) {
-                    $isCloseShopUser = true;
-                    $closeShopStatus = 0;
-                } elseif ($model->TYPE == UserClose::TYPE_GT && $model->IS_CLOSE == 0) {
-                    $isCloseShopUser = true;
-                    $closeShopStatus = 1;
-                }
-                if ($isCloseShopUser) {
-                    $oneUser = User::findOne(['ID' => $this->_userId]);
-                    $oneUser->STATUS = $closeShopStatus;
-                    if (!$oneUser->save()) {
-                        throw new Exception(Form::formatErrorsForApi($oneUser->getErrors()));
-                    }
-                }
-            } elseif ($this->auditStatus == 'reject') {
-                $model->AUDIT_ADMIN_ID = \Yii::$app->user->id;
-                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
-                $model->AUDITED_AT = Date::nowTime();
-                if (!$model->save()) {
-                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError($e->getMessage());
-            return null;
-        }
-        return $model;
-    }
-
-
-}

+ 0 - 190
common/models/forms/UserDecForm.php

@@ -1,190 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Date;
-use common\libs\logging\operate\AdminOperate;
-use common\models\User;
-use common\models\UserInfo;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class UserDecForm extends Model {
-    public $userIds;
-    public $isDec;
-    public $isStudio;
-    public $isAtlas;
-    public $isRecharge;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => User::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['userIds', 'isDec','isStudio', 'isAtlas', 'isRecharge'], 'trim'],
-            [['userIds'], 'required'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'isDec' => ['userIds', 'isDec'],
-            'isAtlas' => ['userIds', 'isAtlas'],
-            'isStudio' => ['userIds', 'isStudio'],
-            'isRecharge' => ['userIds', 'isRecharge'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'userIds' => '会员ID',
-            'isDec' => '是否报单中心',
-            'isStudio' => '是否工作室',
-            'isAtlas' => '是否显示图谱',
-            'isRecharge' => '是否显示充值',
-        ];
-    }
-
-    public function beforeValidate() {
-        return parent::beforeValidate();
-    }
-
-    /**
-     * 是否报单中心
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function isDec() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'ID',['select'=>'ID,IS_DEC']);
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $allUidIn = implode("','", $this->userIds);
-            if (!User::updateAll(['IS_DEC' => $this->isDec ? $this->isDec : 0], "ID IN ('" . $allUidIn . "')")) {
-                throw new Exception('设置报单中心更新失败');
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'ID',['select'=>'ID,IS_DEC']);
-        $this->adminOperateLogger->setBatchField('USER_ID')->clean()->save([
-            'optType' => $this->isDec ? '设置报单中心' : '取消报单中心',
-        ]);
-
-
-
-        return $this->userIds;
-    }
-
-    /**
-     * 是否工作室
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function isStudio() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'ID',['select'=>'ID,IS_STUDIO']);
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $allUidIn = implode("','", $this->userIds);
-            if (!User::updateAll(['IS_STUDIO' => $this->isStudio ? $this->isStudio : 0], "ID IN ('" . $allUidIn . "')")) {
-                throw new Exception('设置工作室更新失败');
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'ID',['select'=>'ID,IS_STUDIO']);
-        $this->adminOperateLogger->setBatchField('USER_ID')->clean()->save([
-            'optType' => $this->isStudio ? '设置工作室' : '取消工作室',
-        ]);
-        return $this->userIds;
-    }
-
-    /**
-     * 是否显示图谱
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function isAtlas() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'ID',['select'=>'ID,IS_ATLAS']);
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $allUidIn = implode("','", $this->userIds);
-            if (!User::updateAll(['IS_ATLAS' => $this->isAtlas ? $this->isAtlas : 0], "ID IN ('" . $allUidIn . "')")) {
-                throw new Exception('设置图谱更新失败');
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'ID',['select'=>'ID,IS_ATLAS']);
-        $this->adminOperateLogger->setBatchField('USER_ID')->clean()->save([
-            'optType' => $this->isAtlas ? '显示图谱' : '隐藏图谱',
-        ]);
-
-
-
-        return $this->userIds;
-    }
-
-    /**
-     * 是否显示充值
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function isRecharge() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'ID',['select'=>'ID,IS_RECHARGE']);
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $allUidIn = implode("','", $this->userIds);
-            if (!User::updateAll(['IS_RECHARGE' => $this->isRecharge ? $this->isRecharge : 0], "ID IN ('" . $allUidIn . "')")) {
-                throw new Exception('充值管理设置更新失败');
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'ID',['select'=>'ID,IS_RECHARGE']);
-        $this->adminOperateLogger->setBatchField('USER_ID')->clean()->save([
-            'optType' => $this->isRecharge ? '显示充值' : '隐藏充值',
-        ]);
-        return $this->userIds;
-    }
-
-}

+ 0 - 91
common/models/forms/UserGroupForm.php

@@ -1,91 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Date;
-use common\libs\logging\operate\AdminOperate;
-use common\models\User;
-use common\models\UserInfo;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class UserGroupForm extends Model {
-    public $userIds;
-    public $isGroup;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => UserInfo::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['userIds', 'isGroup'], 'trim'],
-            [['userIds'], 'required'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'group' => ['userIds', 'isGroup'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'userIds' => '会员ID',
-            'isGroup' => '是否团队领导人',
-        ];
-    }
-
-    public function beforeValidate() {
-        return parent::beforeValidate();
-    }
-
-    /**
-     * 是否团队领导人
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function group() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'USER_ID',['select'=>'USER_ID,IS_GROUP_LEADER,GROUP_LEADER_AT']);
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $allUidIn = implode("','", $this->userIds);
-            if (!UserInfo::updateAll(['IS_GROUP_LEADER' => $this->isGroup ? $this->isGroup : 0, 'GROUP_LEADER_AT' => Date::nowTime()], "USER_ID IN ('" . $allUidIn . "')")) {
-                throw new Exception('团队领导人更新失败');
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'USER_ID',['select'=>'USER_ID,IS_GROUP_LEADER,GROUP_LEADER_AT']);
-        $this->adminOperateLogger->setBatchField('USER_ID')->clean()->save([
-            'optType' => $this->isGroup ? '设置团队领导人' : '取消团队领导人',
-        ]);
-
-
-
-        return $this->userIds;
-    }
-
-}

+ 0 - 625
common/models/forms/UserStatusForm.php

@@ -1,625 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\Tool;
-use common\helpers\user\Balance;
-use common\helpers\user\Info;
-use common\helpers\user\Status;
-use common\libs\logging\operate\AdminOperate;
-use common\models\DealType;
-use common\models\PerfPeriod;
-use common\models\Period;
-use common\models\EmployLevel;
-use common\models\UserWallet;
-use common\models\User;
-use common\models\UserBind;
-use common\models\UserBonus;
-use common\models\UserClose;
-use common\models\UserInfo;
-use common\models\UserPerf;
-use common\models\UserStatusAudit;
-use common\models\Withdraw;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class UserStatusForm extends Model {
-    public $id;
-    public $userName;
-    public $statusValue;
-    public $remark;
-    public $auditStatus;
-    public $isPeriodAddT;
-    public $addTPeriodNum;
-    public $isPeriodOpen;
-    public $openPeriodNum;
-    public $userId;
-    public $periodNum;
-    public $userIds;
-    public $isOperating;
-
-    private $_userId;
-    private $_userStatusModel;
-    private $_userModel;
-    private $_periodNum;
-
-    const STATUS_NORMAL = 1;
-    const STATUS_LOGOUT = 2;//注销
-    const STATUS_BLACKLIST = 3;//黑名单
-    const STATUS_STOP_SEND = 4;//停发
-    const STATUS_CLOSE = 9;//永久关停
-
-    public function init()
-    {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => UserStatusAudit::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['id', 'userName', 'statusValue', 'remark', 'auditStatus', 'isPeriodAddT', 'addTPeriodNum', 'isPeriodOpen', 'openPeriodNum', 'userIds', 'isOperating', 'userId', 'periodNum'], 'trim'],
-            [['id', 'userName', 'statusValue', 'auditStatus', 'userIds'], 'required'],
-            [['userName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
-            [['id'], 'exist', 'targetClass' => UserStatusAudit::class, 'targetAttribute' => 'ID'],
-            [['statusValue'], 'isStatus'],
-            [['auditStatus'], 'isAuditStatus'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            // 手动申请
-            'add' => ['userName', 'statusValue', 'remark', 'isPeriodAddT', 'addTPeriodNum', 'isPeriodOpen', 'openPeriodNum'],
-            // 审核
-            'audit' => ['id', 'auditStatus', 'remark', 'isPeriodAddT', 'addTPeriodNum', 'isPeriodOpen', 'openPeriodNum'],
-            // 调整是否运作
-            'operating' => ['userIds', 'isOperating'],
-            'autoClose' => ['userId'],
-            'clearWallet' => ['remark'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'id' => 'ID',
-            'userName' => '会员编号',
-            'statusValue' => '调整状态',
-            'remark' => '备注',
-            'auditStatus' => '审核状态',
-            'isPeriodAddT' => '是否立即加T',
-            'addTPeriodNum' => '加T的期数',
-            'isPeriodOpen' => '是否马上开通',
-            'openPeriodNum' => '开通的期数',
-            'userIds' => '会员ID',
-            'isOperating' => '是否运作',
-        ];
-    }
-
-    public function beforeValidate() {
-        // 调整是否运作不走初始化流程
-        if ($this->scenario == 'add' || $this->scenario == 'audit' || $this->scenario == 'autoClose' ) {
-            $this->initModel();
-        }
-        return parent::beforeValidate();
-    }
-
-    /**
-     * 初始化model和userId
-     */
-    public function initModel() {
-        $period = Period::instance();
-        $this->_periodNum = $period->getNowPeriodNum();
-        if ($this->scenario == 'audit') {
-            $this->_userStatusModel = UserStatusAudit::findOne(['ID' => $this->id]);
-            $this->_userId = $this->_userStatusModel->USER_ID;
-        } elseif ($this->scenario == 'add') {
-            $this->_userStatusModel = new UserStatusAudit();
-            $oneUser = UserInfo::findOneAsArray(['USER_NAME' => $this->userName], [], 'USER_ID');
-            $this->_userId = $oneUser['USER_ID'];
-            // 查看数据库中是否已经存在了该会员的申请未审核
-            $oneUserStatus = UserStatusAudit::findOne(['USER_ID' => $this->_userId, 'AUDIT_STATUS' => \Yii::$app->params['auditStatus']['un']['value']]);
-            if ($oneUserStatus && $this->scenario == 'add') {
-                // 不允许重复申请
-                $this->addError('initModel', '已经存在该会员的待审核数据,请等待审核后再申请');
-            }
-            // 查看,如果数据库中存在一条已审核,并且是关停转开通,并且是按照期数开通,并且是大于当前期数,则提示存在待开通状态,不能申请
-            if (UserStatusAudit::find()->where('USER_ID=:USER_ID AND IS_PERIOD_OPEN=1 AND OPEN_PERIOD_NUM>:NOW_PERIOD_NUM AND STATUS_VALUE=:STATUS_VALUE', [':USER_ID' => $this->_userId, ':NOW_PERIOD_NUM' => $this->_periodNum, ':STATUS_VALUE' => self::STATUS_NORMAL])->exists()) {
-                $this->addError('initModel', '该会员处于到期等待开通状态,不能修改其他状态');
-            }
-        } else {
-            $this->addError('initModel', '场景不正确');
-        }
-        $this->_userModel = User::findOne(['ID' => $this->_userId]);
-    }
-
-    /**
-     * 状态类型校验
-     * @param $attribute
-     */
-    public function isStatus($attribute) {
-        if (!array_key_exists($this->statusValue, \Yii::$app->params['userStatus'])) {
-            $this->addError($attribute, '类型不正确');
-        }
-        // 会员当前状态
-        if ($this->_userModel['STATUS'] == $this->statusValue) {
-            $this->addError($attribute, '调整状态与调整前状态一致,无需提交');
-        }
-        $period = Period::instance();
-        $nowPeriodNum = $period->getNowPeriodNum();
-        // 只有注销状态才需要校验是否立即加T
-        if ($this->statusValue == self::STATUS_LOGOUT || $this->statusValue == self::STATUS_STOP_SEND) {
-            if ($this->isPeriodAddT && $this->addTPeriodNum <= $nowPeriodNum) {
-                $this->addError($attribute, '加T的期数不能小于当前期数');
-            }
-        }
-        // 从关停状态改为正常状态需要判断开通期数不能小于当前期数
-        if ($this->_userModel['STATUS'] == self::STATUS_CLOSE && $this->statusValue == self::STATUS_NORMAL) {
-            if ($this->isPeriodOpen && $this->openPeriodNum <= $nowPeriodNum) {
-                $this->addError($attribute, '开通的期数不能小于当前的期数');
-            }
-        }
-    }
-
-    /**
-     * 审核状态是否正确
-     * @param $attributes
-     */
-    public function isAuditStatus($attributes) {
-        if (!array_key_exists($this->auditStatus, \Yii::$app->params['auditStatus'])) {
-            $this->addError($attributes, '无效的审核状态');
-        }
-    }
-
-    /**
-     * 申请
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function add() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            // 获取会员当前的状态
-            $oriStatus = Status::getStatus($this->_userId);
-            $model = $this->_userStatusModel;
-            $model->USER_ID = $this->_userId;
-            $model->STATUS_VALUE = $this->statusValue;
-            $model->ORI_VALUE = $oriStatus;
-            $model->PERIOD_NUM = $this->_periodNum;
-            $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
-            $model->IS_PERIOD_ADD_T = $this->isPeriodAddT ? $this->isPeriodAddT : 0;
-            $model->ADD_T_PERIOD_NUM = $this->addTPeriodNum;
-            $model->IS_PERIOD_OPEN = $this->isPeriodOpen ? $this->isPeriodOpen : 0;
-            $model->OPEN_PERIOD_NUM = $this->openPeriodNum;
-            $model->CREATE_REMARK = $this->remark;
-            $model->CREATE_ADMIN = \Yii::$app->user->id;
-            $model->CREATED_AT = Date::nowTime();
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-
-        // 记录日志
-        $this->adminOperateLogger->afterInsert($model)->clean()->save([
-            'optType' => '申请修改会员状态',
-            'userId' => $model->USER_ID,
-            'userName' => Info::getUserNameByUserId($model->USER_ID),
-            'remark' => $model->CREATE_REMARK,
-        ]);
-
-        return $model;
-
-    }
-
-    /**
-     * 审核
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function audit() {
-        if (!$this->validate()) {
-            return null;
-        }
-
-        // 日志记录操作前的数据
-        $this->adminOperateLogger->beforeUpdate($this->_userStatusModel);
-
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $model = $this->_userStatusModel;
-            if ($this->auditStatus == 'true') {
-                // 获取该会员的当前的聘级和报单级别
-                $model->DEC_LV = Info::getDecLv($model->USER_ID);
-                $model->EMP_LV = Info::getEmpLv($model->USER_ID);
-                // 获取当前会员的各个区的业绩
-                $userPerf = UserPerf::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $model->USER_ID]);
-                $model->PV_1L = $userPerf['PV_1L'];
-                $model->PV_2L = $userPerf['PV_2L'];
-                $model->PV_3L = $userPerf['PV_3L'];
-                $model->PV_4L = $userPerf['PV_4L'];
-                $model->PV_5L = $userPerf['PV_5L'];
-                // 获取当前会员的最新已挂网的会员的剩余业绩
-                $maxPeriodNum = Period::sentMaxPeriodNum();
-                $perfPeriod = PerfPeriod::findOne(['USER_ID' => $model->USER_ID, 'PERIOD_NUM' => $maxPeriodNum]);
-                $model->SURPLUS_1L = $perfPeriod['SURPLUS_1L'] ?? 0;
-                $model->SURPLUS_2L = $perfPeriod['SURPLUS_2L'] ?? 0;
-                $model->SURPLUS_3L = $perfPeriod['SURPLUS_3L'] ?? 0;
-                $model->SURPLUS_4L = $perfPeriod['SURPLUS_4L'] ?? 0;
-                $model->SURPLUS_5L = $perfPeriod['SURPLUS_5L'] ?? 0;
-                $model->IS_PERIOD_ADD_T = $this->isPeriodAddT ? $this->isPeriodAddT : 0;
-                $model->ADD_T_PERIOD_NUM = $this->addTPeriodNum ? $this->addTPeriodNum : null;
-                $model->IS_PERIOD_OPEN = $this->isPeriodOpen ? $this->isPeriodOpen : 0;
-                $model->OPEN_PERIOD_NUM = $this->openPeriodNum;
-                $model->CREATE_REMARK = $this->remark;
-                $model->AUDIT_ADMIN = \Yii::$app->user->id;
-                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
-                $model->AUDITED_AT = Date::nowTime();
-                if (!$model->save()) {
-                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-                }
-                // 把商城会员表的状态修改
-                // 如果是从关停修改为正常状态,并且不是马上开通的先不开通,等待封期时,到那一期再给会员开通,其他的情况现在就调整状态
-                $userModel = $this->_userModel;
-                $beforeStatus = $userModel->STATUS;
-                if (!($model->ORI_VALUE == self::STATUS_CLOSE && $model->STATUS_VALUE == self::STATUS_NORMAL && $model->IS_PERIOD_OPEN)) {
-                    $userModel->STATUS = $model->STATUS_VALUE;
-                    $userModel->STATUS_AT = Date::nowTime();
-                    if (!$userModel->save()) {
-                        throw new Exception(Form::formatErrorsForApi($userModel->getErrors()));
-                    }
-                }
-                if (!($model->ORI_VALUE == self::STATUS_CLOSE && $model->IS_PERIOD_OPEN)) {
-                    UserWallet::updateAll(['CLEAR_BY_CLOSED_AT'=> 0], 'USER_ID=:USER_ID', [':USER_ID' => $model->USER_ID]);
-                }
-                // 开始会员状态相关的后续功能
-                // 注销立即清空全部会员所有钱包余额、奖金余额、大区剩余业绩、和各区业绩,自动提现改为手动提现
-                // 注销需要设置立即加T,还是按照设定期数加T,(思路:假设115封期的时候先从会员状态审核表查看116期,批量更新116期需要加T的会员的身份证表前缀为字母T)
-                // 设置成黑名单后自动提现改为手动提现
-                // 停发立即加T,自动提现改为手动提现,清空的参照奖金需求
-                // 取消关停状态可以选择期数开通,到期自动开
-                // 老会员需要开通时选择报单级别
-                // 关停开通时,首次报复销单需要交足额的复销,这个在会员表有参数 IS_FIRST_OPEN
-                if ($model->STATUS_VALUE == self::STATUS_NORMAL) {
-                    if (!$this->isPeriodOpen) {
-                        // 身份证号取消加T
-                        User::updateAll(['ID_CARD_PREFIX' => ''], 'ID=:ID', [':ID' => $userModel->ID]);
-                        // 查看开通之前的状态是什么,如果是关停状态,就把会员表的首次开通的字段设标记
-                        if ($beforeStatus == self::STATUS_CLOSE) {
-                            User::updateAll(['IS_FIRST_OPEN' => 1], 'ID=:ID', [':ID' => $userModel->ID]);
-                        }
-                    }
-                }
-                //注销
-                elseif ($model->STATUS_VALUE == self::STATUS_LOGOUT) {
-                    if ($perfPeriod) {
-                        // 清空大区剩余业绩
-                        $perfPeriod->SURPLUS_1L = 0;
-                        $perfPeriod->SURPLUS_2L = 0;
-                        $perfPeriod->SURPLUS_3L = 0;
-                        $perfPeriod->SURPLUS_4L = 0;
-                        $perfPeriod->SURPLUS_5L = 0;
-                        if (!$perfPeriod->save()) {
-                            throw new Exception(Form::formatErrorsForApi($perfPeriod->getErrors()));
-                        }
-                    }
-                    // 清空各区业绩
-                    $userPerf = UserPerf::findOne(['USER_ID' => $userModel->ID]);
-                    if ($userPerf) {
-                        $userPerf->PV_1L = 0;
-                        $userPerf->PV_2L = 0;
-                        $userPerf->PV_3L = 0;
-                        $userPerf->PV_4L = 0;
-                        $userPerf->PV_5L = 0;
-                        if (!$userPerf->save()) {
-                            throw new Exception(Form::formatErrorsForApi($userPerf->getErrors()));
-                        }
-                    }
-                    // 清空所有奖金
-                    Balance::clearAllBonus($userModel->ID, ['REMARK' => '清空账户余额','DEAL_TYPE'=>DealType::DEDUCT_LOGOUT]);
-                    // 取消自动提现
-                    Withdraw::setAutoWithdraw($userModel->ID, 0);
-                    // 向下找新的主会员
-                    UserBind::setNewMainBind($userModel->ID);
-                    // 如果立即加T,否则到期数自动加T(从封期实现)
-                    if (!$this->isPeriodAddT) {
-                        User::updateAll(['ID_CARD_PREFIX' => 'T'], 'ID=:ID', [':ID' => $userModel->ID]);
-                    }
-                } elseif ($model->STATUS_VALUE == self::STATUS_BLACKLIST) {
-                    // 取消自动提现
-                    Withdraw::setAutoWithdraw($userModel->ID, 0);
-                    // 向下找新的主会员
-                    UserBind::setNewMainBind($userModel->ID);
-                } elseif ($model->STATUS_VALUE == self::STATUS_STOP_SEND) {
-                    // 取消自动提现
-                    Withdraw::setAutoWithdraw($userModel->ID, 0);
-                    // 向下找新的主会员
-                    UserBind::setNewMainBind($userModel->ID);
-                    // 如果立即加T,否则到期数自动加T(从封期实现)
-                    if (!$this->isPeriodAddT) {
-                        User::updateAll(['ID_CARD_PREFIX' => 'T'], 'ID=:ID', [':ID' => $userModel->ID]);
-                    }
-                }
-                //永久关停
-                elseif ($model->STATUS_VALUE == self::STATUS_CLOSE) {
-                    $this->_afterClose($userModel->ID,$perfPeriod);
-                }
-            } elseif ($this->auditStatus == 'reject') {
-                $model->CREATE_REMARK = $this->remark;
-                $model->AUDIT_ADMIN = \Yii::$app->user->id;
-                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
-                $model->AUDITED_AT = Date::nowTime();
-                if (!$model->save()) {
-                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-                }
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('audit', $e->getMessage());
-            return null;
-        }
-
-        // 记录日志
-        $this->adminOperateLogger->afterUpdate($model)->clean()->save([
-            'optType' => '审核会员状态',
-            'userId' => $model->USER_ID,
-            'userName' => Info::getUserNameByUserId($model->USER_ID),
-            'remark' => $model->CREATE_REMARK,
-        ]);
-
-        return $model;
-    }
-
-    /**
-     * 调整是否运作
-     * @return User|null
-     */
-    public function operating() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $this->adminOperateLogger->fetchClass = User::class;
-        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'ID',['select'=>'ID,NOT_OPERATING']);
-
-        $allUidIn = implode("','", $this->userIds);
-        User::updateAll(['NOT_OPERATING' => !$this->isOperating], "ID IN ('" . $allUidIn . "')");
-
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'ID',['select'=>'ID,NOT_OPERATING']);
-        $this->adminOperateLogger->setBatchField('ID')->setOptObjField('ID')->clean()->save([
-            'optType' => '调整会员运作状态【'.($this->isOperating ? '运作' : '不运作').'】',
-            'remark' => $this->remark,
-        ]);
-        return $this->userIds;
-    }
-
-    /**
-     * 自动关停
-     * @return UserStatusAudit|null
-     * @throws \yii\db\Exception
-     */
-    public function autoClose() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            // 获取会员当前的状态
-            $oriStatus = Status::getStatus($this->userId);
-            $model = new UserStatusAudit();
-            $model->USER_ID = $this->userId;
-            $model->STATUS_VALUE = self::STATUS_CLOSE;
-            $model->ORI_VALUE = $oriStatus;
-            $model->PERIOD_NUM = $this->periodNum;
-            $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
-            $model->IS_PERIOD_ADD_T = 0;
-            $model->ADD_T_PERIOD_NUM = 0;
-            $model->IS_PERIOD_OPEN = 0;
-            $model->OPEN_PERIOD_NUM = 0;
-            $model->CREATE_REMARK = '自动关停';
-            $model->CREATE_ADMIN = 0;
-            $model->CREATED_AT = Date::nowTime();
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            $userModel = User::findOne(['ID' => $this->userId]);
-            $userModel->STATUS = self::STATUS_CLOSE;
-            $userModel->STATUS_AT = Date::nowTime();
-            if (!$userModel->save()) {
-                throw new Exception(Form::formatErrorsForApi($userModel->getErrors()));
-            }
-            $this->_afterClose($this->userId);
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('autoClose', $e->getMessage());
-            return null;
-        }
-        return $model;
-    }
-
-    /**
-     * 关停后对会员操作
-     * @param $userId
-     * @param null $perfPeriod
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    private function _afterClose($userId,$perfPeriod=null){
-        if(!$perfPeriod) {
-            $maxPeriodNum = Period::sentMaxPeriodNum();
-            $perfPeriod = PerfPeriod::findOne(['USER_ID' => $userId, 'PERIOD_NUM' => $maxPeriodNum]);
-        }
-        // 清空大区剩余业绩
-        if ($perfPeriod) {
-            $perfPeriod->SURPLUS_1L = 0;
-            $perfPeriod->SURPLUS_2L = 0;
-            $perfPeriod->SURPLUS_3L = 0;
-            $perfPeriod->SURPLUS_4L = 0;
-            $perfPeriod->SURPLUS_5L = 0;
-            if (!$perfPeriod->save()) {
-                throw new Exception(Form::formatErrorsForApi($perfPeriod->getErrors()));
-            }
-        }
-        // 清空各区业绩
-        $userPerf = UserPerf::findOne(['USER_ID' => $userId]);
-        if ($userPerf) {
-            $userPerf->PV_1L = 0;
-            $userPerf->PV_2L = 0;
-            $userPerf->PV_3L = 0;
-            $userPerf->PV_4L = 0;
-            $userPerf->PV_5L = 0;
-            if (!$userPerf->save()) {
-                throw new Exception(Form::formatErrorsForApi($userPerf->getErrors()));
-            }
-        }
-        // 清空所有奖金 暂时不清奖金<19.10.1>@190730
-        // Balance::clearAllBonus($userId, ['REMARK' => '会员永久关停']);
-        // 取消自动提现
-        Withdraw::setAutoWithdraw($userId, 0);
-        // 身份证号立即加T,聘级将为无聘级
-        User::updateAll(['ID_CARD_PREFIX' => 'T', 'EMP_LV' => EmployLevel::getDefaultLevelId()], 'ID=:ID', [':ID' => $userId]);
-        // 向下找新的主会员
-        UserBind::setNewMainBind($userId);
-    }
-
-    /**
-     * 自动关停
-     * @param $periodNum
-     * @param int $closedAt
-     * @param $limit
-     * @param int $start
-     * @param null $closeInspectStart
-     * @param null $closeInspectPv
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public static function autoChkClose($periodNum, $closedAt = 0, $limit, $start = 0, $closeInspectStart = null, $closeInspectPv = null) {
-        //初始化
-        if (!$closeInspectStart || !$closeInspectPv) {
-            $systemConfig = Cache::getSystemConfig();
-            $closeInspectMonth = $systemConfig['closeInspectMonth']['VALUE'];
-            $closeInspectStart = Date::lastNumMonth($closeInspectMonth, $closedAt);
-            $closeInspectPv = $systemConfig['closeInspectPv']['VALUE'];
-        }
-        //考察所有未注销未关停的会员 (修复UserInfo没有STATUS)
-        $allData = User::find()->where('STATUS!=:STATUS_CLOSE AND STATUS!=:STATUS_LOGOUT AND SUB_COM_LEADER!=1',[':STATUS_CLOSE'=>self::STATUS_CLOSE,':STATUS_LOGOUT'=>self::STATUS_LOGOUT])->select('ID')->offset($start)->limit($limit)->asArray()->all();
-        if ($allData) {
-            foreach ($allData as $data) {
-                // 修复绑定的START和END是关键字不允许作为绑定参数
-                $pvPcs = PerfPeriod::find()->where('CREATED_AT>:START_TIME AND CREATED_AT<:END_TIME', [':START_TIME' => $closeInspectStart, ':END_TIME' => $closedAt])->SUM('PV_PCS');
-                if ($pvPcs < $closeInspectPv) {
-                    //未达到业绩,封停会员
-                    $formModel = new UserStatusForm();
-                    $formModel->scenario = 'autoClose';
-                    $formModel->userId = $data['ID'];
-                    $formModel->periodNum = $periodNum;
-                    if (!$formModel->autoClose()) {
-                        continue;
-                    }
-                    unset($formModel);
-                }
-            }
-            unset($allData);
-            $start = $start + $limit;
-            return self::autoChkClose($periodNum, $closedAt, $limit, $start, $closeInspectStart, $closeInspectPv);
-        }
-        return true;
-    }
-
-    /**
-     * 删除前
-     * @param $selected
-     */
-    public function beforeDelete($selected) {
-        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
-    }
-    /**
-     * 删除
-     * @param $selected
-     * @throws Exception
-     */
-    public function delete($selected) {
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '删除会员状态待审核数据',
-        ]);
-    }
-
-    /**
-     * 清空关停会员钱包
-     * @return array|null
-     * @throws Exception
-     * @throws \yii\db\Exception
-     */
-    public function clearWallet() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $uids = [];
-        $users = Status::getCloseUser();
-        if ($users) {
-            $uids = array_column($users, 'ID');
-            $this->adminOperateLogger->fetchClass = UserBonus::class;
-            $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($uids, 'USER_ID');
-            $userBonus = $this->adminOperateLogger->saveBeforeContent;
-            $this->adminOperateLogger->fetchClass = UserWallet::class;
-            $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($uids, 'USER_ID');
-            $shopWallet = $this->adminOperateLogger->saveBeforeContent;
-            $this->adminOperateLogger->saveBeforeContent=Tool::mergeArrayWithKey($userBonus,$shopWallet);
-
-            $db = \Yii::$app->db;
-            $transaction = $db->beginTransaction();
-            try {
-                foreach ($users as $u) {
-                    // 清空所有奖金
-                    Balance::clearAllBonus($u['ID'], ['REMARK' => '清空账户余额', 'DEAL_TYPE' => DealType::DEDUCT_CLOSE]);
-                }
-                $transaction->commit();
-            } catch (Exception $e) {
-                $transaction->rollBack();
-            }
-
-            $this->adminOperateLogger->fetchClass = UserBonus::class;
-            $this->adminOperateLogger->setIsBatch(true)->afterUpdate($uids, 'USER_ID');
-            $userBonus = $this->adminOperateLogger->saveAfterContent;
-            $this->adminOperateLogger->fetchClass = UserWallet::class;
-            $this->adminOperateLogger->setIsBatch(true)->afterUpdate($uids, 'USER_ID');
-            $shopWallet = $this->adminOperateLogger->saveAfterContent;
-            $this->adminOperateLogger->saveAfterContent=Tool::mergeArrayWithKey($userBonus,$shopWallet);
-            $this->adminOperateLogger->setBatchField('USER_ID')->setOptObjField('USER_ID')->clean()->save([
-                'optType' => '清空关停会员钱包',
-                'remark' => $this->remark,
-            ]);
-
-            return $uids;
-        } else {
-            throw new Exception('暂无符合条件的会员');
-        }
-    }
-}

+ 0 - 246
common/models/forms/UserSystemForm.php

@@ -1,246 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\Log;
-use common\helpers\user\Info;
-use common\libs\logging\operate\AdminOperate;
-use common\models\BonusAsync;
-use common\models\Period;
-use common\models\UserInfo;
-use common\models\UserRelation;
-use common\models\UserSystem;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class UserSystemForm extends Model {
-    public $id;
-    public $systemName;
-    public $leaderUserName;
-    public $remark;
-
-    private $_leaderUid;
-    private $_tempSystemLeaders = [];  // 用于循环给下级设置体系的时候,临时设置子集领导的数组
-    private $_limit = 2;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => UserSystem::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['id', 'systemName', 'leaderUserName', 'remark'], 'trim'],
-            [['id', 'systemName', 'leaderUserName'], 'required'],
-            [['systemName'], 'unique', 'on' => 'update', 'targetClass' => UserSystem::class, 'targetAttribute' => 'SYSTEM_NAME', 'when' => function ($model) {
-                return $model->isAttributeChanged('SYSTEM_NAME');
-            }],
-            [['leaderUserName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
-            [['id'], 'exist', 'targetClass' => UserSystem::class, 'targetAttribute' => 'ID', 'on'=>'renewSystem'],
-            [['leaderUserName'], 'isLeaderUser'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'add' => ['systemName', 'leaderUserName','remark'],
-            'edit' => ['systemName','leaderUserName', 'remark'],
-            'renewSystem' => ['id'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'systemName' => '体系名称',
-            'leaderUserName' => '领导人会员编号',
-        ];
-    }
-
-    public function isLeaderUser($attributes) {
-        $leaderUserInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->leaderUserName]);
-        if ($leaderUserInfo) {
-            $this->_leaderUid = $leaderUserInfo['USER_ID'];
-        }
-    }
-
-    /**
-     * 页面端编辑
-     * @return UserSystem|null|static
-     * @throws \yii\db\Exception
-     */
-    public function edit() {
-        if (!$this->validate()) {
-            return null;
-        }
-        return $this->_editHandle();
-    }
-
-    /**
-     * 恢复
-     * @return UserSystem|null
-     * @throws \yii\db\Exception
-     */
-    public function renewSystem(){
-        if (!$this->validate()) {
-            return null;
-        }
-        return $this->_editHandle();
-    }
-
-    /**
-     * 撤销体系前
-     * @param $selected
-     * @throws Exception
-     */
-    public function beforeDelete($selected) {
-        $this->adminOperateLogger->setIsBatch(true)->setOptObjField('LEADER_UID')->beforeDelete($selected, 'ID');
-        foreach ($selected as $id) {
-            $period = Period::instance();
-            $model = UserSystem::findOne(['ID' => $id]);
-            $model->UPDATED_AT = Date::nowTime();
-            $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
-            $model->UPDATE_ADMIN = \Yii::$app->user->id;
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            $leaderUid = $model->LEADER_UID;
-            // 把该体系对应的领导人及下级所有是该体系的会员,全部改为上级的体系
-            // 获取该体系的上级会员所在的体系
-            $parentUserInfo = UserRelation::getFirstParentUserInfo($leaderUid);
-            if ($parentUserInfo) {
-                $newSystemId = $parentUserInfo['SYSTEM_ID'];
-            } else {
-                $newSystemId = null;
-            }
-            UserInfo::updateAll(['IS_SYSTEM_LEADER' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $leaderUid]);
-            // 把该体系的所有体系都改成新体系
-            UserInfo::updateAll(['SYSTEM_ID' => $newSystemId], 'SYSTEM_ID=:SYSTEM_ID AND IS_SYSTEM_LEADER=0', [':SYSTEM_ID' => $id]);
-        }
-    }
-
-    /**
-     * 撤销体系
-     * @param $selected
-     */
-    public function delete($selected) {
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '撤销体系',
-        ]);
-    }
-
-    /**
-     * 处理编辑
-     * @return UserSystem|null
-     * @throws \yii\db\Exception
-     */
-    private function _editHandle() {
-        if($this->scenario!='add'){
-            $this->adminOperateLogger->beforeUpdate(UserSystem::findOne(['ID' => $this->id]));
-        }
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $period = Period::instance();
-            if ($this->scenario == 'add') {
-                $model = new UserSystem();
-                $model->SYSTEM_NAME = $this->systemName;
-                $model->LEADER_UID = $this->_leaderUid;
-                $model->PERIOD_NUM = $period->getNowPeriodNum();
-                $model->CREATE_REMARK = $this->remark;
-                $model->CREATE_ADMIN = \Yii::$app->user->id;
-                $model->CREATED_AT = Date::nowTime();
-            } elseif ($this->scenario == 'edit') {
-                $model = UserSystem::findOne(['ID' => $this->id]);
-                if($model->IS_DEL){
-                    $this->addError('id', '该体系已被撤销,不能编辑');
-                    return null;
-                }
-                $model->SYSTEM_NAME = $this->systemName;
-                $model->LEADER_UID = $this->_leaderUid;
-                $model->UPDATED_AT = Date::nowTime();
-                $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
-                $model->UPDATE_ADMIN = \Yii::$app->user->id;
-                $model->CREATE_REMARK = $this->remark;
-            } elseif ($this->scenario == 'renewSystem') {
-                $model = UserSystem::findOne(['ID' => $this->id]);
-                $model->IS_DEL = 0;
-                $model->UPDATED_AT = Date::nowTime();
-                $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
-                $model->UPDATE_ADMIN = \Yii::$app->user->id;
-                $this->_leaderUid = $model->LEADER_UID;
-            }else {
-                $this->addError('id', '提交场景不存在');
-                return null;
-            }
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            // 下级会员全部变成该体系的会员
-            //if ($this->scenario == 'add') {
-                // 自己也变成该体系
-                UserInfo::updateAll(['SYSTEM_ID' => $model->ID, 'IS_SYSTEM_LEADER'=>1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_leaderUid]);
-                $this->_childrenChangeSystem($this->_leaderUid, $model->ID);
-           //}
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-        if($this->scenario!='add'){
-            $this->adminOperateLogger->afterUpdate($model);
-
-        }else{
-            $this->adminOperateLogger->afterInsert($model);
-        }
-        $optType = '添加体系';
-        if($this->scenario=='edit'){
-            $optType = '编辑体系';
-        }elseif ($this->scenario=='renewSystem'){
-            $optType = '恢复体系';
-        }
-        $this->adminOperateLogger->clean()->save([
-            'optType' => $optType,
-            'userId' => $model->LEADER_UID,
-            'userName' => Info::getUserNameByUserId($model->LEADER_UID),
-            'remark' => $this->remark??''
-        ]);
-        return $model;
-    }
-
-    /**
-     * 改变子会员的体系
-     * @param $userId
-     * @param $systemId
-     * @throws \yii\db\Exception
-     */
-    private function _childrenChangeSystem($userId, $systemId){
-        // 查询子会员里面是体系领导人的所有子会员
-        $allChildSystemLeader = UserRelation::find()->select('UR.*,UI.SYSTEM_ID')->from(UserRelation::tableName().' AS UR')->join('LEFT JOIN', UserInfo::tableName().' AS UI', 'UI.USER_ID=UR.USER_ID')->where('UR.PARENT_UID=:PARENT_UID AND UI.IS_SYSTEM_LEADER=1', [':PARENT_UID'=>$userId])->asArray()->all();
-        // 先把所有子会员的体系,全部改成新体系
-        $sql = "UPDATE {{%USER_INFO}} UI SET UI.SYSTEM_ID=:SYSTEM_ID WHERE EXISTS (SELECT UR.USER_ID FROM {{%USER_RELATION}} UR WHERE UI.USER_ID=UR.USER_ID AND UR.PARENT_UID=:PARENT_UID)";
-        \Yii::$app->db->createCommand($sql)->bindValues([':SYSTEM_ID'=>$systemId, ':PARENT_UID'=>$userId])->query();
-        // 循环把所有子会员的体系都设置了
-        foreach($allChildSystemLeader as $ChildSystemLeader){
-            UserInfo::updateAll(['SYSTEM_ID' => $ChildSystemLeader['SYSTEM_ID']], 'USER_ID=:USER_ID', [':USER_ID' => $ChildSystemLeader['USER_ID']]);
-            $sql = "UPDATE {{%USER_INFO}} UI SET UI.SYSTEM_ID=:SYSTEM_ID WHERE EXISTS (SELECT UR.USER_ID FROM {{%USER_RELATION}} UR WHERE UI.USER_ID=UR.USER_ID AND UR.PARENT_UID=:PARENT_UID)";
-            \Yii::$app->db->createCommand($sql)->bindValues([':SYSTEM_ID'=>$ChildSystemLeader['SYSTEM_ID'], ':PARENT_UID'=>$ChildSystemLeader['USER_ID']])->query();
-        }
-    }
-
-}

+ 0 - 201
common/models/forms/UserTeamForm.php

@@ -1,201 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\Log;
-use common\models\BonusAsync;
-use common\models\Period;
-use common\models\UserInfo;
-use common\models\UserNetwork;
-use common\models\UserRelation;
-use common\models\UserTeam;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class UserTeamForm extends Model {
-    public $id;
-    public $teamName;
-    public $leaderUserName;
-    public $remark;
-
-    private $_leaderUid;
-    private $_tempTeamLeaders = [];  // 用于循环给下级设置团队的时候,临时设置子集领导的数组
-    private $_limit = 2;
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['id', 'teamName', 'leaderUserName', 'remark'], 'trim'],
-            [['id', 'teamName', 'leaderUserName'], 'required'],
-            [['leaderUserName'], 'unique', 'targetClass' => UserTeam::class, 'targetAttribute' => 'TEAM_NAME'],
-            [['leaderUserName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
-            [['id'], 'exist', 'targetClass' => UserTeam::class, 'targetAttribute' => 'ID', 'on'=>'renewTeam'],
-            [['leaderUserName'], 'isLeaderUser'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'add' => ['teamName', 'leaderUserName','remark'],
-            'edit' => ['teamName','leaderUserName', 'remark'],
-            'renewTeam' => ['id'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'teamName' => '团队名称',
-            'leaderUserName' => '领导人会员编号',
-        ];
-    }
-
-    public function isLeaderUser($attributes) {
-        $leaderUserInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->leaderUserName]);
-        if ($leaderUserInfo) {
-            $this->_leaderUid = $leaderUserInfo['USER_ID'];
-        }
-    }
-
-    /**
-     * 页面端编辑
-     * @return UserTeam|null|static
-     * @throws \yii\db\Exception
-     */
-    public function edit() {
-        if (!$this->validate()) {
-            return null;
-        }
-        return $this->_editHandle();
-    }
-
-    /**
-     * 恢复
-     * @return UserTeam|null
-     * @throws \yii\db\Exception
-     */
-    public function renewTeam(){
-        if (!$this->validate()) {
-            return null;
-        }
-        return $this->_editHandle();
-    }
-
-    /**
-     * 删除团队的
-     * @param $id
-     * @throws Exception
-     */
-    public function delete($id) {
-        $period = Period::instance();
-        $model = UserTeam::findOne(['ID' => $id]);
-        $model->UPDATED_AT = Date::nowTime();
-        $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
-        $model->UPDATE_ADMIN = \Yii::$app->user->id;
-        if (!$model->save()) {
-            throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-        }
-        $leaderUid = $model->LEADER_UID;
-        // 把该团队对应的领导人及下级所有是该团队的会员,全部改为上级的团队
-        // 获取该团队的上级会员所在的团队
-        $parentUserInfo = UserNetwork::getFirstParentUserInfo($leaderUid);
-        if ($parentUserInfo) {
-            $newTeamId = $parentUserInfo['TEAM_ID'];
-        } else {
-            $newTeamId = null;
-        }
-        // 把该团队的所有团队都改成新团队
-        UserInfo::updateAll(['TEAM_ID' => $newTeamId], 'TEAM_ID=:TEAM_ID AND IS_TEAM_LEADER=0', [':TEAM_ID' => $id]);
-    }
-
-    /**
-     * 处理编辑
-     * @return UserTeam|null
-     * @throws \yii\db\Exception
-     */
-    private function _editHandle() {
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $period = Period::instance();
-            if ($this->scenario == 'add') {
-                $model = new UserTeam();
-                $model->TEAM_NAME = $this->teamName;
-                $model->LEADER_UID = $this->_leaderUid;
-                $model->PERIOD_NUM = $period->getNowPeriodNum();
-                $model->CREATE_REMARK = $this->remark;
-                $model->CREATE_ADMIN = \Yii::$app->user->id;
-                $model->CREATED_AT = Date::nowTime();
-            } elseif ($this->scenario == 'edit') {
-                $model = UserTeam::findOne(['ID' => $this->id]);
-                if($model->IS_DEL){
-                    $this->addError('id', '该团队已被撤销,不能编辑');
-                    return null;
-                }
-                $model->TEAM_NAME = $this->teamName;
-                $model->LEADER_UID = $this->_leaderUid;
-                $model->UPDATED_AT = Date::nowTime();
-                $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
-                $model->UPDATE_ADMIN = \Yii::$app->user->id;
-                $model->CREATE_REMARK = $this->remark;
-            } elseif ($this->scenario == 'renewTeam') {
-                $model = UserTeam::findOne(['ID' => $this->id]);
-                $model->IS_DEL = 0;
-                $model->UPDATED_AT = Date::nowTime();
-                $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
-                $model->UPDATE_ADMIN = \Yii::$app->user->id;
-                $this->_leaderUid = $model->LEADER_UID;
-            }else {
-                $this->addError('id', '提交场景不存在');
-                return null;
-            }
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            // 下级会员全部变成该团队的会员
-            //if ($this->scenario == 'add') {
-                // 自己也变成该团队
-                UserInfo::updateAll(['TEAM_ID' => $model->ID, 'IS_TEAM_LEADER'=>1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_leaderUid]);
-                $this->_childrenChangeTeam($this->_leaderUid, $model->ID);
-           //}
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('edit', $e->getMessage());
-            return null;
-        }
-        return $model;
-    }
-
-    /**
-     * 改变子会员的团队
-     * @param $userId
-     * @param $teamId
-     * @throws \yii\db\Exception
-     */
-    private function _childrenChangeTeam($userId, $teamId){
-        // 查询子会员里面是团队领导人的所有子会员
-        $allChildTeamLeader = UserNetwork::find()->select('UR.*,UI.TEAM_ID')->from(UserNetwork::tableName().' AS UR')->join('LEFT JOIN', UserInfo::tableName().' AS UI', 'UI.USER_ID=UR.USER_ID')->where('UR.PARENT_UID=:PARENT_UID AND UI.IS_TEAM_LEADER=1', [':PARENT_UID'=>$userId])->asArray()->all();
-        // 先把所有子会员的团队,全部改成新团队
-        $sql = "UPDATE {{%USER_INFO}} UI SET UI.TEAM_ID=:TEAM_ID WHERE EXISTS (SELECT UR.USER_ID FROM {{%USER_NETWORK}} UR WHERE UI.USER_ID=UR.USER_ID AND UR.PARENT_UID=:PARENT_UID)";
-        \Yii::$app->db->createCommand($sql)->bindValues([':TEAM_ID'=>$teamId, ':PARENT_UID'=>$userId])->query();
-        // 循环把所有子会员的团队都设置了
-        foreach($allChildTeamLeader as $ChildTeamLeader){
-            UserInfo::updateAll(['TEAM_ID' => $ChildTeamLeader['TEAM_ID']], 'USER_ID=:USER_ID', [':USER_ID' => $ChildTeamLeader['USER_ID']]);
-            $sql = "UPDATE {{%USER_INFO}} UI SET UI.TEAM_ID=:TEAM_ID WHERE EXISTS (SELECT UR.USER_ID FROM {{%USER_NETWORK}} UR WHERE UI.USER_ID=UR.USER_ID AND UR.PARENT_UID=:PARENT_UID)";
-            \Yii::$app->db->createCommand($sql)->bindValues([':TEAM_ID'=>$ChildTeamLeader['TEAM_ID'], ':PARENT_UID'=>$ChildTeamLeader['USER_ID']])->query();
-        }
-    }
-
-}

+ 0 - 429
common/models/forms/UserTeamworkForm.php

@@ -1,429 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\user\Info;
-use common\libs\logging\operate\AdminOperate;
-use common\models\Period;
-use common\models\DeclarationLevel;
-use common\models\EmployLevel;
-use common\models\User;
-use common\models\UserBind;
-use common\models\UserInfo;
-use common\models\UserTeamwork;
-use yii\base\Exception;
-
-/**
- * 点位合作表单
- */
-class UserTeamworkForm extends Model {
-    public $id;
-    public $type;
-    public $userName;
-    public $mainUserName;
-    public $dividePercent;
-    public $divideArr;
-    public $nation;
-    public $realName;
-    public $idCard;
-    public $mobile;
-    public $address;
-    public $openBank;
-    public $bankAddress;
-    public $bankNo;
-    public $bankAreaSelected;
-    public $areaSelected;
-    public $tel;
-    public $remark;
-
-
-    const HAS_USER = 1;   // 在网站已有会员
-    const NOT_USER = 0;   // 在网站没有会员
-
-    private $_uid;
-    private $_mainUid;
-    private $_model;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => UserTeamwork::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['id', 'type', 'userName', 'mainUserName', 'dividePercent', 'nation', 'realName', 'idCard', 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankAreaSelected', 'areaSelected', 'tel', 'remark'], 'trim'],
-            [['id', 'type', 'userName', 'mainUserName', 'dividePercent', 'idCard', 'realName'], 'required'],
-            [['dividePercent'], 'price', 'message' => '分成比例必须是整数或者两位小数'],
-            [['type'], 'boolean', 'message' => '添加类型格式不正确'],
-            [['userName'], 'isUserName'],
-            [['mobile', 'tel'], 'mobile'],
-            [['bankNo'], 'string', 'max' => 19],
-            [['mainUserName'], 'isMainUserName'],
-            [['dividePercent'], 'isDivide'],
-            [['divideArr'], 'isDivideArr'],
-            [['id'], 'initModel'],
-            [['userName'], 'userName'],
-            [['idCard'], 'isIdCard'],
-            [['realName','address','bankAddress'], 'realName'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'add' => ['type', 'userName', 'mainUserName', 'dividePercent', 'nation', 'realName', 'idCard', 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankAreaSelected', 'areaSelected', 'tel', 'remark'],
-            'changeDivide' => ['id', 'divideArr', 'remark'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'type' => '添加类型',
-            'userName' => '会员编号',
-            'mainUserName' => '主会员编号',
-            'dividePercent' => '分成比例',
-            'nation' => '民族',
-            'realName' => '会员姓名',
-            'idCard' => '身份证',
-            'mobile' => '手机号',
-            'address' => '地址',
-            'openBank' => '开户行',
-            'bankAddress' => '银行地址',
-            'bankNo' => '银行账号',
-            'bankAreaSelected' => '银行地区',
-            'areaSelected' => '地区',
-            'tel' => '电话',
-            'remark' => '备注',
-        ];
-    }
-
-    /**
-     * 初始化model
-     * @param $attributes
-     */
-    public function initModel($attributes) {
-        $this->_model = UserTeamwork::findOne(['ID' => $this->id]);
-        if (!$this->_model) {
-            $this->addError($attributes, 'The data does not exist'); // 数据不存在
-        }
-    }
-
-    /**
-     * 用户名是否正确
-     * @param $attributes
-     * @throws Exception
-     */
-    public function isUserName($attributes) {
-        if ($this->userName == $this->mainUserName) {
-            $this->addError($attributes, '同一会员不能合作');
-        }
-        if ($this->type == self::HAS_USER) {
-            $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
-            if ($userInfo) {
-                $this->_uid = $userInfo['USER_ID'];
-                if ($userInfo['IS_TEAM_MAIN'] == 1) {
-                    $this->addError($attributes, '该会员是其他点位合作的主会员,无法添加');
-                }
-                $info = Info::baseInfo($this->_uid);
-                /*if ($info['STATUS'] == UserStatusForm::STATUS_LOGOUT || $info['STATUS'] == UserStatusForm::STATUS_CLOSE) {
-                    $this->addError($attributes, '注销或永久关停的会员不允许设置点位合作');
-                }*/
-                if ($info['STATUS'] != UserStatusForm::STATUS_NORMAL) {
-                    $this->addError($attributes, '非正常的会员不允许设置点位合作');
-                }
-            } else {
-                $this->addError($attributes, 'Member does not exist'); // 会员不存在
-            }
-        } else {
-            if (strpos(strtolower($this->userName), 'hz') !== 0) {
-                $this->addError($attributes, '无点位的会员编号必须是以hz开头');
-            }
-            if (!$this->realName || !$this->idCard) {
-                $this->addError($attributes, '请详细填写新增无点位会员的相关信息');
-            }
-        }
-
-    }
-
-    /**
-     * 主会员编号
-     * @param $attributes
-     * @throws Exception
-     */
-    public function isMainUserName($attributes) {
-        $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->mainUserName]);
-        if ($userInfo) {
-            if (UserTeamwork::find()->where('USER_ID=:USER_ID AND MAIN_UID!=:USER_ID AND IS_DEL=0', [':USER_ID' => $userInfo['USER_ID']])->exists()) {
-                $this->addError($attributes, '主会员已在其他点位有合作情况');
-            }
-            $info = Info::baseInfo($userInfo['USER_ID']);
-            if ($info['STATUS'] != UserStatusForm::STATUS_NORMAL) {
-                $this->addError($attributes, '非正常的主会员不允许设置点位合作');
-            }
-            $this->_mainUid = $userInfo['USER_ID'];
-        } else {
-            $this->addError($attributes, '主会员不存在');
-        }
-    }
-
-    /**
-     * 校验分成比例
-     * @param $attributes
-     * @return bool
-     */
-    public function isDivide($attributes) {
-        /*$divideSum = UserTeamwork::findOneAsArray('USER_ID=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $this->_mainUid], 'DIVIDE_PERCENT');
-        if ($divideSum && $divideSum['DIVIDE_PERCENT'] <= $this->dividePercent) {
-            $this->addError($attributes, '该合作者的分成比例不能超过主会员分成比例【' . $divideSum . '】');
-        }*/
-    }
-
-    /**
-     * 校验身份证号
-     * @param $attributes
-     * @return bool
-     */
-    public function isIdCard($attributes) {
-        if($user=User::findOneAsArray('ID_CARD=:ID_CARD',[':ID_CARD'=>$this->idCard],'REAL_NAME')){
-            if($user['REAL_NAME']!=$this->realName){
-                $this->addError($attributes, '填写的会员姓名与已经实名认证的会员姓名不一致');
-            }
-        }
-    }
-
-    /**
-     * 校验分成数组
-     * @param $attributes
-     * @return bool
-     */
-    public function isDivideArr($attributes) {
-        $sum = 0;
-        foreach ($this->divideArr as $value) {
-            if (!preg_match("/^[0-9]+([.]{1}[0-9]{1,2})?$/", $value['DIVIDE_PERCENT'])) {
-                $this->addError($attributes, '分成比例必须是整数或者两位小数');
-                return false;
-            }
-            $sum += $value['DIVIDE_PERCENT'];
-        }
-        if ($sum != 100) {
-            $this->addError($attributes, '确保总分成比例为100');
-        }
-    }
-
-    /**
-     * 添加
-     * @return UserTeamwork|null
-     * @throws \yii\base\Exception
-     */
-    public function add() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $period = Period::instance();
-            // 如果需要添加虚拟合作会员的,先新增会员
-            if ($this->type == self::NOT_USER) {
-                // 商城表增加会员
-                $user = new User();
-                $user->USER_NAME = $this->userName;
-                $pwd = Info::passwordGenerator($this->idCard,$user->USER_NAME);
-                $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($pwd);
-                $pwd = Info::passwordGenerator($this->idCard,$user->USER_NAME,true);
-                $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($pwd);
-                $user->NATION = $this->nation ? $this->nation : 1;
-                $user->REAL_NAME = $this->realName;
-                $user->ID_CARD = $this->idCard;
-                $user->MOBILE = $this->mobile;
-                $user->ADDRESS = $this->address ? $this->address : '无';
-                $user->ADDRESS = '无';
-                $user->OPEN_BANK = $this->openBank;
-                $user->BANK_ADDRESS = $this->bankAddress;
-                $user->BANK_NO = $this->bankNo;
-                $user->BANK_PROVINCE = $this->bankAreaSelected[0] ?? '0';
-                $user->BANK_CITY = $this->bankAreaSelected[1] ?? '0';
-                $user->BANK_COUNTY = $this->bankAreaSelected[2] ?? '0';
-                $user->CREATED_AT = Date::nowTime();
-                $user->STATUS = 1;
-                $user->DEC_LV = DeclarationLevel::getDefaultLevelId();
-                $user->EMP_LV = EmployLevel::getDefaultLevelId();
-                $user->PROVINCE = $this->areaSelected[0] ?? '0';
-                $user->CITY = $this->areaSelected[1] ?? '0';
-                $user->COUNTY = $this->areaSelected[2] ?? '0';
-                $user->TEL = $this->tel;
-                //$user->REG_IS_COMPLETED = 1;
-                $user->SUB_COM_ID = null;
-                $user->AVATAR = 'avatar/1.png';
-                $user->IS_DEC = 0;
-                $user->DEC_ID = \Yii::$app->params['mainUserId'];
-                $user->BIRTHDAY = null;
-                $user->DEC_ROLE_ID = null;
-                $user->PERIOD_AT = $period->getNowPeriodNum();
-                $user->IS_UNION = 1;//合作会员标识
-                $user->IS_DIRECT_SELLER = 0;
-                $user->VERIFIED = 1;
-                $user->VERIFIED_AT = Date::nowTime();;
-                if (!$user->save()) {
-                    throw new Exception(Form::formatErrorsForApi($user->getErrors()));
-                }
-                $this->_uid = $user->ID;
-                // 结算表用户表增加会员但不写入点位关系
-                $userInfoModel = new UserInfo();
-                $userInfoModel->USER_ID = $this->_uid;
-                $userInfoModel->USER_NAME = $this->userName;
-                $userInfoModel->CON_UID = '0';
-                $userInfoModel->REC_UID = '0';
-                $userInfoModel->IS_TEAM = 1;
-                //$userInfoModel->PERIOD_NUM = $period->getNowPeriodNum();
-                $userInfoModel->CREATED_AT = Date::nowTime();
-                $userInfoModel->HIGHEST_EMP_LV = EmployLevel::getDefaultLevelId();
-                $userInfoModel->ALLOW_TRANSFER = 1;
-                $userInfoModel->HIGHEST_EMP_LV_PERIOD = $period->getNowPeriodNum();
-                $userInfoModel->TRANSFER_PROP = 100.00;
-                $userInfoModel->IS_GROUP_LEADER = 0;
-                if (!$userInfoModel->save()) {
-                    throw new Exception(Form::formatErrorsForApi($userInfoModel->getErrors()));
-                }
-            }
-            // 查看主点位是否已经存在
-            if (!UserTeamwork::find()->where('USER_ID=:USER_ID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':USER_ID' => $this->_mainUid, ':MAIN_UID' => $this->_mainUid])->exists()) {
-                UserTeamwork::insertOne([
-                    'USER_ID' => $this->_mainUid,
-                    'MAIN_UID' => $this->_mainUid,
-                    'DIVIDE_PERCENT' => 100 - $this->dividePercent,
-                    'PERIOD_NUM' => $period->getNowPeriodNum(),
-                    'IS_DEL' => 0,
-                    'CREATE_REMARK' => $this->remark,
-                    'CREATE_ADMIN' => \Yii::$app->user->id,
-                    'CREATED_AT' => Date::nowTime(),
-                ]);
-            } else {
-                $mainModel = UserTeamwork::findOne(['USER_ID' => $this->_mainUid]);
-                $mainModel->DIVIDE_PERCENT = $mainModel->DIVIDE_PERCENT - $this->dividePercent;
-                if (!$mainModel->save()) {
-                    throw new Exception(Form::formatErrorsForApi($mainModel->getErrors()));
-                }
-            }
-            // 会员信息表添加点位合作标识
-            UserInfo::updateAll(['IS_TEAM' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_uid]);
-            UserInfo::updateAll(['IS_TEAM' => 1, 'IS_TEAM_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_mainUid]);
-            // 添加会员合作点位
-            $model = new UserTeamwork();
-            $model->USER_ID = $this->_uid;
-            $model->MAIN_UID = $this->_mainUid;
-            $model->DIVIDE_PERCENT = $this->dividePercent;
-            $model->PERIOD_NUM = $period->getNowPeriodNum();
-            $model->IS_DEL = 0;
-            $model->CREATE_REMARK = $this->remark;
-            $model->CREATE_ADMIN = \Yii::$app->user->id;
-            $model->CREATED_AT = Date::nowTime();
-            if (!$model->save()) {
-                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-            }
-            //点位绑定
-            UserBind::autoBind($this->_uid,$this->idCard,1);
-
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            User::deleteAll(['ID'=>$this->_uid]);
-            $this->addError('add', $e->getMessage());
-            return null;
-        }
-        if ($this->type == self::NOT_USER) {
-            $this->adminOperateLogger->fetchClass = User::class;
-            $this->adminOperateLogger->afterInsert($this->_uid, 'ID', ['select' => 'ID,NATION,REAL_NAME,ID_CARD,ADDRESS,MOBILE,PROVINCE,CITY,COUNTY,OPEN_BANK,BANK_ADDRESS,BANK_NO,BANK_PROVINCE,BANK_CITY,BANK_COUNTY,TEL,CREATED_AT,IS_UNION']);
-            $userData = $this->adminOperateLogger->saveAfterContent;
-            $this->adminOperateLogger->fetchClass = UserTeamwork::class;
-            $this->adminOperateLogger->afterInsert($model);
-            $infoData = $this->adminOperateLogger->saveAfterContent;
-            $this->adminOperateLogger->saveAfterContent = array_merge($userData, $infoData);
-        }else{
-            $this->adminOperateLogger->afterInsert($model);
-        }
-        $this->adminOperateLogger->clean()->save([
-            'optType' => '添加合作点位',
-            'userId' => $model->USER_ID,
-            'userName' => Info::getUserNameByUserId($model->USER_ID),
-            'remark' => $this->remark
-        ]);
-        return $model;
-    }
-
-    /**
-     * 改变分成比例
-     * @return array|null
-     * @throws \yii\db\Exception
-     */
-    public function changeDivide() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $logs = [];
-
-        $ids = array_column($this->divideArr, 'ID');
-        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($ids,'ID');
-
-        $transaction = \Yii::$app->db->beginTransaction();
-        try {
-            $period = Period::instance();
-            foreach ($this->divideArr as $value) {
-                $model = UserTeamwork::findOne(['ID'=>$value['ID']]);
-                $model->DIVIDE_PERCENT = $value['DIVIDE_PERCENT'];
-                $model->UPDATE_ADMIN = \Yii::$app->user->id;
-                $model->CREATE_REMARK = $this->remark;
-                $model->UPDATED_PERIOD = $period->getNowPeriodNum();
-                $model->UPDATED_AT = Date::nowTime();
-                if (!$model->save()) {
-                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
-                }
-                $logs[$value['USER_ID']] = $value['DIVIDE_PERCENT'];
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('changeDivide', $e->getMessage());
-            return null;
-        }
-
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($ids,'ID');
-        $this->adminOperateLogger->setOptObjField('USER_ID')->clean()->save([
-            'optType' => '编辑合作点位',
-            'remark' => $this->remark
-        ]);
-        return ['logs' => $logs];
-    }
-
-    /**
-     * 删除
-     * @param $selected
-     */
-    public static function delete($selected) {
-        foreach ($selected as $select) {
-            $userTeamwork = UserTeamwork::findOneAsArray('ID=:ID', [':ID' => $select], 'USER_ID');
-            UserInfo::updateAll(['IS_TEAM' => 0, 'IS_TEAM_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userTeamwork['USER_ID']]);
-            // 如果是主合作者位取消了合作,那么子合作者也自动同时取消合作
-            if ($userTeamwork['USER_ID'] == $userTeamwork['MAIN_UID']) {
-                $allTeamUser = UserTeamwork::findAllAsArray('MAIN_UID=:MAIN_UID', [':MAIN_UID' => $userTeamwork['USER_ID']]);
-                foreach ($allTeamUser as $user) {
-                    UserInfo::updateAll(['IS_TEAM' => 0, 'IS_TEAM_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $user['USER_ID']]);
-                }
-                UserTeamwork::updateAll(['IS_DEL' => 1], 'MAIN_UID=:MAIN_UID', [':MAIN_UID' => $userTeamwork['USER_ID']]);
-            }
-        }
-    }
-}

+ 0 - 99
common/models/forms/UserTransferPropForm.php

@@ -1,99 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\components\Model;
-use common\helpers\Form;
-use common\helpers\user\Balance;
-use common\helpers\user\Info;
-use common\helpers\user\Status;
-use common\libs\logging\operate\AdminOperate;
-use common\models\PerfPeriod;
-use common\models\Period;
-use common\models\UserWallet;
-use common\models\User;
-use common\models\UserClose;
-use common\models\UserInfo;
-use common\models\UserPerf;
-use common\models\UserStatusAudit;
-use common\models\Withdraw;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class UserTransferPropForm extends Model {
-    public $userIds;
-    public $allowTransfer;
-    public $transferProp;
-    public $remark;
-
-    public function init() {
-        parent::init();
-        $this->adminOperateLogger = new AdminOperate([
-            'fetchClass' => UserInfo::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['userIds', 'transferProp', 'allowTransfer', 'remark'], 'trim'],
-            [['transferProp', 'userIds'], 'required']
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'change' => ['userIds', 'transferProp', 'allowTransfer', 'remark'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels() {
-        return [
-            'userIds' => '会员ID',
-            'transferProp' => '转账比例',
-        ];
-    }
-
-    /**
-     * 调整比例
-     * @return null
-     * @throws \yii\db\Exception
-     */
-    public function change() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'USER_ID',['select'=>'USER_ID,ALLOW_TRANSFER,TRANSFER_PROP']);
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $allUidIn = implode("','", $this->userIds);
-            if(!UserInfo::updateAll(['ALLOW_TRANSFER'=>$this->allowTransfer?$this->allowTransfer:0,'TRANSFER_PROP' => $this->transferProp], "USER_ID IN ('" . $allUidIn . "')")){
-                throw new Exception('调整会员转账/提现比例失败');
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            return null;
-        }
-        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'USER_ID',['select'=>'USER_ID,ALLOW_TRANSFER,TRANSFER_PROP']);
-        $this->adminOperateLogger->setBatchField('USER_ID')->clean()->save([
-            'optType' => '调整会员转账/提现比例',
-            'remark' => $this->remark,
-        ]);
-        return $this->userIds;
-    }
-
-}

+ 0 - 706
common/models/forms/WithdrawForm.php

@@ -1,706 +0,0 @@
-<?php
-
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Cache;
-use common\helpers\Date;
-use common\helpers\Form;
-use common\helpers\Tool;
-use common\helpers\user\Balance;
-use common\helpers\user\Info;
-use common\helpers\user\Status;
-use common\libs\logging\operate\UserOperate;
-use common\models\CompanyBank;
-use common\models\DealType;
-use common\models\DecOrder;
-use common\models\InvoiceAudit;
-use common\models\Order;
-use common\models\PerfPeriod;
-use common\models\Period;
-use common\models\RegType;
-use common\models\User;
-use common\models\UserBonus;
-use common\models\UserInfo;
-use common\models\UserRelation;
-use common\models\UserTeamwork;
-use common\models\Withdraw;
-use common\models\WithdrawLevel;
-use common\helpers\http\LingYunGongApi;
-use yii\base\Exception;
-
-/**
- * Login form
- */
-class WithdrawForm extends Model {
-    public $id;
-    public $selectedIds;
-    public $userName;
-    public $realName;
-    public $idCard;
-    public $regType;
-    public $applyAmount;
-    public $payPassword;
-    public $auditStatus;
-    public $planPaidAt;
-    public $createdAt;
-    public $createRemark;
-    public $withdrawCode;
-    public $withdrawAudit;
-
-    public $sn;
-    public $withdrawPeriodNum;
-    public $paidAt;
-    public $paidFailRemark;
-    public $amount;
-    public $bankRealName;
-    public $bankNo;
-
-    private $_userId;
-
-    public function init() {
-        parent::init();
-        $this->userOperateLogger = new UserOperate([
-            'fetchClass' => Withdraw::class,
-        ]);
-    }
-
-    /**
-     * @inheritdoc
-     */
-    public function rules() {
-        return [
-            [['id', 'userName', 'realName', 'idCard', 'regType', 'applyAmount', 'payPassword', 'planPaidAt', 'auditStatus', 'createdAt', 'remark', 'createRemark', 'selectedIds', 'sn', 'withdrawPeriodNum', 'paidAt', 'paidFailRemark', 'amount', 'bankRealName', 'bankNo'], 'trim'],
-            [['id', 'userName', 'applyAmount', 'payPassword', 'auditStatus','withdrawCode','withdrawAudit'], 'required'],
-            [['id'], 'exist', 'targetClass' => Withdraw::class, 'targetAttribute' => 'ID', 'message' => '提现申请不存在'],
-            [['userName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME', 'message' => '会员不存在'],
-            [['applyAmount'], 'price'],
-            [['applyAmount'], 'isApplyAmount'],
-            [['userName'], 'isUserName'],
-            [['payPassword'], 'validatePassword'],
-            [['withdrawCode'], 'validateCode'],
-            [['withdrawAudit'], 'validateAuditCode'],
-            [['planPaidAt'], 'isPlanPaidAt'],
-            [['selectedIds'], 'isSelected'],
-            [['sn'], 'isSn'],
-            //[['auditStatus'], 'isStatus'],
-        ];
-    }
-
-    /**
-     * 指定场景
-     * @return array
-     */
-    public function scenarios() {
-        $parentScenarios = parent::scenarios();
-        $customScenarios = [
-            'addByAdmin' => ['userName', 'realName', 'idCard', 'regType', 'applyAmount', 'createRemark'],
-            'addByUser' => ['applyAmount', 'payPassword','withdrawCode'],
-            'addByAuto' => ['userName', 'applyAmount'],
-            'statusByAdmin' => ['selectedIds', 'auditStatus', 'createRemark','planPaidAt', 'paidAt','withdrawAudit'],
-            'editByAdmin' => ['id', 'planPaidAt', 'createRemark'],
-            'backByUser' => ['id', 'createRemark'],
-            'excelPaidFalse' => ['sn', 'withdrawPeriodNum', 'paidAt', 'paidFailRemark', 'userName', 'realName', 'amount', 'bankRealName', 'bankNo'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    /**
-     * @return array
-     */
-    public function attributeLabels() {
-        return [
-            'id' => '提现申请ID',
-            'userName' => '会员编号',
-            'applyAmount' => '申请提现的金额',
-            'withdrawCode' => '申请提现校验码',
-            'withdrawAudit' => '提现审核校验码',
-        ];
-    }
-
-    /**
-     * 用户名是否正确
-     * @param $attributes
-     * @throws Exception
-     */
-    public function isUserName($attributes) {
-        $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
-        if ($userInfo) {
-            if ($this->scenario == 'addByAdmin') {
-                $baseInfo = Info::baseInfoZh($userInfo['USER_ID']);
-                if ($baseInfo['REAL_NAME'] != $this->realName || $baseInfo['ID_CARD'] != $this->idCard) {
-                    $this->addError($attributes, '输入的会员姓名或身份证号与系统不一致');
-                }
-                if ($userInfo['REG_TYPE'] != $this->regType) {
-                    $this->addError($attributes, '选择的会员注册类型与系统不一致');
-                }
-            }
-            $this->_userId = $userInfo['USER_ID'];
-        } else {
-            $this->addError($attributes, $this->userName . 'Member does not exist'); // 会员不存在
-        }
-    }
-
-    /**
-     * 校验申请金额是否小于当前余额并符合配置中的设置
-     * @param $attribute
-     * @return bool
-     */
-    public function isApplyAmount($attribute) {
-        $config = Cache::getSystemConfig();
-        if ($this->applyAmount <= 0) {
-            $this->addError('scenario', '提现金额必须大于0');
-        }
-        if ((int)($this->applyAmount)!=$this->applyAmount) {
-            $this->addError('scenario', '提现金额必须是整数');
-        }
-        $minAmount = 0;
-        $maxAmount = 0;
-        if ($this->scenario == 'addByUser') {
-            $minAmount = $config['manualWithdrawMinAmount']['VALUE'];
-//            $maxAmount = $config['manualWithdrawMaxAmount']['VALUE'];
-            $this->_userId = \Yii::$app->user->id;
-        } elseif ($this->scenario == 'addByAdmin') {
-            $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
-            $this->_userId = $userInfo['USER_ID'];
-        } else {
-            $this->addError($attribute, '场景不存在');
-            return false;
-        }
-        if ($minAmount != 0 && $this->applyAmount < $minAmount) {
-            $this->addError($attribute, '提现金额不能少于' . $minAmount . '元');
-        }
-        if ($maxAmount != 0 && $this->applyAmount > $maxAmount) {
-            $this->addError($attribute, '提现金额不能高于' . $maxAmount . '元');
-        }
-
-        // 提现条件判断
-        $orderAmount = Order::find()->where('USER_ID=:USER_ID', [':USER_ID' => $this->_userId])->SUM('ORDER_AMOUNT');
-        $recNum = intval(DecOrder::find()->where('REC_USER_ID=:REC_USER_ID', [':REC_USER_ID' => $this->_userId])->count());
-        //$recNum = UserRelation::firstFloorChildNum($this->_userId);
-//        if ($orderAmount < 300 && $recNum==0) {
-//            $this->addError($attribute, '奖金不能提现');
-//            return null;
-//        }
-        // 获取当前提现用户的金额
-        if ($this->applyAmount > Balance::getAvailableBalance($this->_userId)) {
-            $this->addError('scenario', '提现金额必须小于的可用余额');
-        }
-    }
-
-    /**
-     * 校验支付密码
-     * @param $attribute
-     * @param $params
-     */
-    public function validatePassword($attribute, $params) {
-        if (!User::validatePayPassword($this->_userId, $this->payPassword)) {
-            $this->addError($attribute, '支付密码不正确');
-        }
-    }
-
-    public function validateCode($attribute) {
-        $uid = \Yii::$app->user->id;
-        $redisCode = \Yii::$app->redis->getset('withdrawCode_'.$uid,'');
-        \Yii::$app->redis->del('withdrawCode_'.$uid);
-        if ($this->withdrawCode!=$redisCode) {
-            $this->addError($attribute, '申请提现校验失败');
-        }
-    }
-
-    public function validateAuditCode($attribute) {
-        $adminId = \Yii::$app->user->id;
-        $redisCode = \Yii::$app->redis->getset('withdrawAudit_'.$adminId,'');
-        if ($this->withdrawAudit!=$redisCode) {
-            $this->addError($attribute, '提现审核校验失败');
-        }
-    }
-
-    /**
-     * 批量数据
-     * @param $attributes
-     */
-    public function isSelected($attributes) {
-        if (!$this->selectedIds) {
-            $this->addError($attributes, 'A piece of data must be selected'); // 必须选择一条数据
-        }
-        if (!is_array($this->selectedIds)) {
-            $this->selectedIds = [$this->selectedIds];
-        }
-    }
-
-    /**
-     * 校验状态
-     * @param $attribute
-     */
-    public function isStatus($attribute) {
-    }
-
-    /**
-     * 计划付款日期
-     * @param $attribute
-     */
-    public function isPlanPaidAt($attribute) {
-        if (Date::utcToTime($this->planPaidAt) < Date::nowTime()) {
-            $this->addError($attribute, '不能选择过去的日期');
-        }
-    }
-
-    /**
-     * 判断信息是否一致
-     * @param $attribute
-     * @throws Exception
-     */
-    public function isSn($attribute) {
-        $sn = $this->sn;
-        if (!$oneWithdraw = Withdraw::findOneAsArray('SN=:SN AND AUDIT_STATUS=:AUDIT_STATUS', [':SN' => $sn, ':AUDIT_STATUS' => Withdraw::STATUS_PAID])) {
-            $this->addError($attribute, '不存在提现流水号为' . $sn . '的已付款记录');
-        }
-        if ($oneWithdraw) {
-            $info = Info::baseInfo($oneWithdraw['USER_ID']);
-            if ($this->userName != $info['USER_NAME']) {
-                $this->addError($attribute, 'Excel中提现流水号' . $sn . '的用户名' . $this->userName . '与系统中的信息【' . $info['USER_NAME'] . '】不一致');
-            }
-            if ($this->realName != $info['REAL_NAME']) {
-                $this->addError($attribute, 'Excel中提现流水号' . $sn . '的会员姓名' . $this->realName . '与系统中的信息【' . $info['REAL_NAME'] . '】不一致');
-            }
-            if ($this->withdrawPeriodNum != $oneWithdraw['WITHDRAW_PERIOD_NUM']) {
-                $this->addError($attribute, 'Excel中提现流水号' . $sn . '的提现期数' . $this->withdrawPeriodNum . '与系统中的信息【' . $oneWithdraw['WITHDRAW_PERIOD_NUM'] . '】不一致');
-            }
-            if (Date::convert(Date::utcToTime($this->paidAt)) != Date::convert($oneWithdraw['PAID_AT'])) {
-                $this->addError($attribute, 'Excel中提现流水号' . $sn . '的付款日期' . Date::convert(Date::utcToTime($this->paidAt)) . '与系统中的信息【' . Date::convert($oneWithdraw['PAID_AT']) . '】不一致');
-            }
-            if ($this->amount != $oneWithdraw['AMOUNT']) {
-                $this->addError($attribute, 'Excel中提现流水号' . $sn . '的提现金额' . $this->amount . '与系统中的信息【' . $oneWithdraw['AMOUNT'] . '】不一致');
-            }
-            if ($this->bankRealName != $oneWithdraw['REAL_NAME']) {
-                $this->addError($attribute, 'Excel中提现流水号' . $sn . '的实时开户名' . $this->bankRealName . '与系统中的信息【' . $oneWithdraw['REAL_NAME'] . '】不一致');
-            }
-            if ($this->bankNo != $oneWithdraw['BANK_NO']) {
-                $this->addError($attribute, 'Excel中提现流水号' . $sn . '的实时银行账户' . $this->bankNo . '与系统中的信息【' . $oneWithdraw['BANK_NO'] . '】不一致');
-            }
-        }
-    }
-
-
-    /**
-     * 添加提现申请
-     * @return null|string
-     * @throws \yii\db\Exception
-     */
-    public function add() {
-        if (!$this->validate()) {
-            return false;
-        }
-
-        $beforeData = Balance::getLogData(\Yii::$app->user->id);
-        $this->userOperateLogger->saveBeforeContent=$beforeData;
-
-        $config = Cache::getSystemConfig();
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $nowTime = $this->createdAt ? $this->createdAt : Date::nowTime();
-            $period = Withdraw::getPeriod($nowTime);
-            //扣除会员奖金
-            Balance::changeUserBonus($this->_userId, 'BONUS', -abs($this->applyAmount), ['DEAL_TYPE_ID'=>DealType::WITHDRAW,'REMARK' => 'Period '. $period['nowPeriodNum'].' '.($this->scenario == 'addByAuto' ? 'auto withdrawal' : 'manual withdrawal'), 'TIME' => $nowTime]);
-            //增加记录
-            $userInfo = Info::baseInfo($this->_userId);
-
-            //手续费
-            $fees = $this->applyAmount * $config['withdrawFee']['VALUE']/100;
-            $fees = Tool::formatPrice($fees);
-            $realAmount = $this->applyAmount - $fees;
-            //判断付款类型
-            $payType = Withdraw::PAY_TYPE_NO_INVOICE;
-            $withdrawModel = new Withdraw();
-            $withdrawModel->SN = $this->_generateSn();
-            $withdrawModel->USER_ID = $this->_userId;
-            $withdrawModel->ID_CARD = $userInfo['ID_CARD'];
-            $withdrawModel->WITHDRAW_PERIOD_NUM = $period['nowPeriodNum'];
-            $withdrawModel->WITHDRAW_YEAR = $period['nowYear'];
-            $withdrawModel->WITHDRAW_MONTH = $period['nowMonth'];
-            $withdrawModel->PAY_TYPE = $payType;
-            $withdrawModel->IS_AUTO_WITHDRAW = $this->scenario == 'addByAuto' ? 1 : 0;
-            $withdrawModel->AMOUNT = $this->applyAmount;
-            $withdrawModel->FEES = $fees;
-            $withdrawModel->REAL_AMOUNT = $realAmount;
-            $withdrawModel->P_MONTH = Date::ociToDate($period['yearMonth'], Date::OCI_TIME_FORMAT_SHORT_MONTH);
-//            if ($payType == Withdraw::PAY_TYPE_NO_INVOICE) {
-//                $withdrawModel->AUDIT_STATUS = Withdraw::STATUS_AUDITED;
-//                $withdrawModel->AUDITED_AT = $nowTime;
-//            } else {
-            $withdrawModel->AUDIT_STATUS = Withdraw::STATUS_APPLIED;
-//            }
-            $withdrawModel->CREATED_AT = $nowTime;
-            //预计付款时间
-            $withdrawModel->PLAN_PAID_AT = $period['endTime'] + $config['withdrawFreezeDays']['VALUE'] * 3600 * 24;
-
-            if ($this->scenario == 'addByAdmin') {
-                $withdrawModel->UPDATE_ADMIN = \Yii::$app->user->id;
-                $withdrawModel->UPDATE_REMARK = $this->createRemark;
-            }
-            if (!$withdrawModel->save()) {
-                throw new Exception(Form::formatErrorsForApi($withdrawModel->getErrors()));
-            }
-            //考核会员注册类型
-//            RegType::chkRegType($this->_userId, $userInfo['SHOULD_REG_TYPE'], $period['nowYear'], $period['nowMonth']);
-
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('add', $e->getMessage());
-            return false;
-        }
-
-        $afterData = Balance::getLogData(\Yii::$app->user->id);
-        $this->userOperateLogger->saveAfterContent=$afterData;
-        unset($beforeData,$afterData);
-        $this->userOperateLogger->clean()->save([
-            'optType' => '会员提现申请',
-            'userId' => \Yii::$app->user->id,
-            'userName' => Info::getUserNameByUserId(\Yii::$app->user->id),
-            'remark' => $this->createRemark,
-        ]);
-        return $withdrawModel;
-    }
-
-    /**
-     * 检测是否上传身份证
-     * @return int
-     */
-    public function checkHasIdCardInfo() {
-        if ($this->scenario !== 'addByUser') return 0;
-        $userId = \Yii::$app->user->id;
-        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID,USER_NAME,ID_CARD');
-        if( !$user ) {
-            $this->addError('add', '不存在该用户');
-            return -1;
-        }
-//        if( !$user['ID_CARD'] ) {
-//            $this->addError('add', '完善身份信息后才可以提现');
-//            return -1;
-//        }
-//
-//        $response = LingYunGongApi::hasIdCardInfo($user['ID_CARD']);
-//        if( !$response ) {
-//            $this->addError('add', '接口网络错误');
-//            return -1;
-//        }
-//
-//        if( !isset($response['has']) ) {
-//            $this->addError('add', '接口格式错误');
-//            return -1;
-//        }
-//
-//
-//        if( $response['has'] === true ) {
-//            return 0;
-//        }else {
-//            $this->addError('add', $response['err_msg']['msg']);
-//            return -2;
-//        }
-        return 0;
-    }
-
-    /**
-     * 生成流水号
-     * @return string
-     */
-    private function _generateSn() {
-        return 'TX' . Date::today('Ymd') . $this->_random(10, 1);
-    }
-
-    /**
-     * 生成随机数
-     *
-     * @param $length
-     * @param int $numeric
-     * @return string
-     */
-    private function _random($length, $numeric = 0) {
-        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
-        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
-        $hash = '';
-        $max = strlen($seed) - 1;
-        for ($i = 0; $i < $length; $i++) {
-            $hash .= $seed[mt_rand(0, $max)];
-        }
-        return $hash;
-    }
-
-    /**
-     * 生成随机数
-     * @param $length
-     * @param int $numeric
-     * @return string
-     */
-    public function wdcode($length, $numeric = 0) {
-        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
-        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
-        $hash = '';
-        $max = strlen($seed) - 1;
-        for ($i = 0; $i < $length; $i++) {
-            $hash .= $seed[mt_rand(0, $max)];
-        }
-        return $hash;
-    }
-
-    /**
-     * 修改预计打款日期
-     * @return null|static
-     * @throws \yii\db\Exception
-     */
-    public function editByAdmin() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $oneWithdraw = Withdraw::findOne(['ID' => $this->id]);
-            $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
-            $oneWithdraw->REMARK = $this->createRemark;
-            $planPaidAt = Date::utcToTime($this->planPaidAt);
-            if ($oneWithdraw->PLAN_PAID_AT != $planPaidAt) {
-                $oneWithdraw->PLAN_PAID_AT = $planPaidAt;
-            }
-            if (!$oneWithdraw->save()) {
-                throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('status', $e->getMessage());
-            return null;
-        }
-        return $oneWithdraw;
-    }
-
-    /**
-     * 前台提现退回
-     * @return null|static
-     * @throws \yii\db\Exception
-     */
-    public function backByUser() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $oneWithdraw = Withdraw::findOne(['ID' => $this->id]);
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            if (Cache::getSystemConfig()['isCanWithdrawBack']['VALUE'] != 1) {
-                throw new Exception('提现退回已关闭');
-            }
-            if (!Withdraw::find()->where('USER_ID=:USER_ID AND ID=:ID AND AUDIT_STATUS=:AUDIT_STATUS_1', ['USER_ID' => \Yii::$app->user->id, ':ID' => $this->id, ':AUDIT_STATUS_1' => Withdraw::STATUS_APPLIED])->exists()) {
-                throw new Exception('符合退回的提现记录不存在');
-            }
-            $oneWithdraw->BACK_REMARK = $this->createRemark;
-            $oneWithdraw->BACK_FAIL_AT = Date::nowTime();
-            $oneWithdraw->AUDIT_STATUS = Withdraw::STATUS_RETURN;
-            Balance::changeUserBonus($oneWithdraw['USER_ID'], 'BONUS', abs($oneWithdraw['AMOUNT']), ['DEAL_TYPE_ID'=>DealType::WITHDRAW_RETURN,'REMARK' => $oneWithdraw->WITHDRAW_PERIOD_NUM.'期前台提现退回']);
-            if (!$oneWithdraw->save()) {
-                throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
-            }
-
-            //发票设置为审核拒绝
-//            if ($invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw->INVOICE_ID])) {
-//                $invoiceModel->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
-//                $invoiceModel->AUDIT_REMARK = '提现退回';
-//                $invoiceModel->AUDITED_AT = Date::nowTime();
-//                if (!$invoiceModel->save()) {
-//                    throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
-//                }
-//            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('auditStatus', $e->getMessage());
-            return null;
-        }
-        return $oneWithdraw;
-    }
-
-    /**
-     * 设置提现订单的状态
-     * @return null|static
-     * @throws \yii\db\Exception
-     */
-    public function changeStatus() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $logs = [];
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            foreach ($this->selectedIds as $select) {
-                $oneWithdraw = Withdraw::findOne(['ID' => $select]);
-                //判断状态
-                if (($msg = Withdraw::chkAuditStatus($oneWithdraw->SN, $oneWithdraw->AUDIT_STATUS, $this->auditStatus)) != '') {
-                    throw new Exception($msg);
-                }
-                //待审核->已审核
-                if ($this->auditStatus == Withdraw::STATUS_AUDITED) {
-                    //同时审核发票
-                    if ($invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw['INVOICE_ID']])) {
-                        if (InvoiceAudit::find()->where('INVOICE_NUM=:INVOICE_NUM AND WITHDRAW_ID!=:WITHDRAW_ID AND AUDIT_STATUS=:AUDIT_STATUS', [':INVOICE_NUM' => $invoiceModel->INVOICE_NUM, ':WITHDRAW_ID' => $invoiceModel->WITHDRAW_ID, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['true']['value']])->exists()) {
-                            throw new Exception('提现流水号' . $oneWithdraw->SN . '发票的发票号码【' . $invoiceModel->INVOICE_NUM . '】已被使用');
-                        }
-                        $invoiceModel->AUDIT_ADMIN = \Yii::$app->user->id;
-                        $invoiceModel->CREATE_REMARK = $this->createRemark ?? '';
-                        $invoiceModel->AUDITED_AT = Date::nowTime();
-                        if (!$invoiceModel->save()) {
-                            throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
-                        }
-                    }
-                    $oneWithdraw->REMARK = $this->createRemark ?? '';
-                } //已审核->待付款
-                elseif ($this->auditStatus == Withdraw::STATUS_WAIT_PAID) {
-                    $oneWithdraw->PAID_FAIL_REMARK = '';
-                    $oneWithdraw->PAID_FAIL_AT = 0;
-                    $oneWithdraw->REMARK = $this->createRemark ?? '';
-                    $oneWithdraw->PLAN_PAID_AT = Date::utcToTime($this->planPaidAt);
-                } //待付款->已付款
-                elseif ($this->auditStatus == Withdraw::STATUS_PAID) {
-                    $oneWithdraw->PAID_AT = Date::utcToTime($this->paidAt);
-                    //记录付款信息
-                    $baseInfo = Info::baseInfo($oneWithdraw->USER_ID);
-                    if ($baseInfo['REG_TYPE'] == '758BF69C25C3422AA7743936BC77EE64') {
-                        $companyBank = CompanyBank::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseInfo['ID']]);
-                        $oneWithdraw->REAL_NAME = $companyBank['OPEN_NAME'];
-                        $oneWithdraw->OPEN_BANK = $companyBank['OPEN_BANK'];
-                        $oneWithdraw->BANK_PROVINCE = $companyBank['BANK_PROVINCE'];
-                        $oneWithdraw->BANK_CITY = $companyBank['BANK_CITY'];
-                        $oneWithdraw->BANK_COUNTY = $companyBank['BANK_COUNTY'];
-                        $oneWithdraw->BANK_ADDRESS = $companyBank['BANK_ADDRESS'];
-                        $oneWithdraw->BANK_NO = $companyBank['BANK_NO'];
-                    } else {
-                        $oneWithdraw->REAL_NAME = $baseInfo['REAL_NAME'];
-                        $oneWithdraw->OPEN_BANK = $baseInfo['OPEN_BANK'];
-                        $oneWithdraw->BANK_PROVINCE = $baseInfo['BANK_PROVINCE'];
-                        $oneWithdraw->BANK_CITY = $baseInfo['BANK_CITY'];
-                        $oneWithdraw->BANK_COUNTY = $baseInfo['BANK_COUNTY'];
-                        $oneWithdraw->BANK_ADDRESS = $baseInfo['BANK_ADDRESS'];
-                        $oneWithdraw->BANK_NO = $baseInfo['BANK_NO'];
-                    }
-                    $oneWithdraw->REMARK = $this->createRemark ?? '';
-                } //已付款->付款失败
-                elseif ($this->auditStatus == Withdraw::STATUS_PAID_FALSE) {
-                    $oneWithdraw->PAID_FAIL_AT = Date::nowTime();
-                    $oneWithdraw->PAID_FAIL_REMARK = $this->createRemark ?? '';
-                } //提现退回
-                elseif ($this->auditStatus == Withdraw::STATUS_RETURN) {
-                    $oneWithdraw->BACK_REMARK = $this->createRemark ?? '';
-                    $oneWithdraw->BACK_FAIL_AT = Date::nowTime();
-                    Balance::changeUserBonus($oneWithdraw['USER_ID'], 'BONUS', abs($oneWithdraw['AMOUNT']), [
-                        'DEAL_TYPE_ID' => DealType::WITHDRAW_RETURN,
-                        'REMARK' => 'Period' . $oneWithdraw->WITHDRAW_PERIOD_NUM . ' ' . ($oneWithdraw->IS_AUTO_WITHDRAW ? 'Auto' : 'Manual') . ' withdrawal return' // 自动、手动、提现退回
-                    ]);
-                    //发票设置为审核拒绝
-                    $invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw->INVOICE_ID]);
-                    if ($invoiceModel) {
-                        $invoiceModel->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
-                        $invoiceModel->AUDIT_ADMIN = \Yii::$app->user->id;
-                        $invoiceModel->AUDIT_REMARK = ' withdrawal return'; // 提现退回
-                        $invoiceModel->AUDITED_AT = Date::nowTime();
-                        if (!$invoiceModel->save()) {
-                            throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
-                        }
-                    }
-                }
-                $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
-                $oneWithdraw->AUDIT_STATUS = $this->auditStatus;
-                $oneWithdraw->AUDITED_AT = Date::nowTime();
-                if (!$oneWithdraw->save()) {
-                    throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
-                }
-                $logs[$select] = $oneWithdraw->SN;
-            }
-            $adminId = \Yii::$app->user->id;
-            \Yii::$app->redis->del('withdrawAudit_'.$adminId);
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('auditStatus', $e->getMessage());
-            return null;
-        }
-        return ['logs' => $logs, 'status' => $this->auditStatus];
-    }
-
-    /**
-     * 标记为付款失败
-     * @return null|static
-     * @throws \yii\db\Exception
-     */
-    public function excelPaidFalse() {
-        if (!$this->validate()) {
-            return null;
-        }
-        $db = \Yii::$app->db;
-        $transaction = $db->beginTransaction();
-        try {
-            $oneWithdraw = Withdraw::findOne(['SN' => $this->sn]);
-            $oneWithdraw->PAID_FAIL_AT = Date::nowTime();
-            $oneWithdraw->PAID_FAIL_REMARK = $this->paidFailRemark;
-            $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
-            $oneWithdraw->AUDIT_STATUS = Withdraw::STATUS_PAID_FALSE;
-            $oneWithdraw->AUDITED_AT = Date::nowTime();
-            if (!$oneWithdraw->save()) {
-                throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
-            }
-            $transaction->commit();
-        } catch (Exception $e) {
-            $transaction->rollBack();
-            $this->addError('auditStatus', $e->getMessage());
-            return null;
-        }
-        return $oneWithdraw;
-    }
-
-
-    /**
-     * 循环自动提现
-     * @param $limit
-     * @param int $start
-     * @return bool
-     * @throws \yii\db\Exception
-     */
-    public static function autoLoopWithdraw($limit, $start = 0) {
-        // 获取设置自动提现的最低金额
-        $systemConfig = Cache::getSystemConfig();
-        $autoWithdrawMinAmount = $systemConfig['autoWithdrawMinAmount']['VALUE'];
-        $autoWithdrawMaxAmount = $systemConfig['autoWithdrawMaxAmount']['VALUE'];
-        // 获取全部设置了自动提现的会员的奖金大于这个数额的会员
-        $allData = UserInfo::find()->select('UI.USER_ID,UI.USER_NAME,UI.IS_BIND_MAIN,UB.BONUS,UB.BONUS_FREEZE')->from(UserInfo::tableName() . ' AS UI')->join('LEFT JOIN', UserBonus::tableName() . ' AS UB', 'UI.USER_ID=UB.USER_ID')->where('UI.IS_AUTO_WITHDRAW=1 AND (UI.IS_BIND_MAIN=1 OR (UB.BONUS - UB.BONUS_FREEZE >= :WITHDRAW_AMOUNT AND UI.IS_BIND=0))', [':WITHDRAW_AMOUNT' => $autoWithdrawMinAmount])->offset($start)->limit($limit)->asArray()->all();
-        if ($allData) {
-            foreach ($allData as $data) {
-                //本月提现过的忽略
-                if (Withdraw::hasThisMonthWithdraw($data['USER_ID'])) continue;
-                //汇总主点位
-                $collectBind = 0;
-                if ($data['IS_BIND_MAIN'] == 1) {
-                    $transferBonusForm = new TransferBonusForm();
-                    $collectBind = $transferBonusForm->collectBind($data['USER_ID']);
-                }
-                $totalAmount = $data['BONUS'] + $collectBind - $data['BONUS_FREEZE'];
-                if ($autoWithdrawMinAmount != 0 && $totalAmount < $autoWithdrawMinAmount) continue;
-                $formModel = new WithdrawForm();
-                $formModel->scenario = 'addByAuto';
-                $formModel->userName = $data['USER_NAME'];
-                //自动提现金额取整数
-                $formModel->applyAmount = floor(($autoWithdrawMaxAmount > 0 && $totalAmount > $autoWithdrawMaxAmount) ? $autoWithdrawMaxAmount : $totalAmount);
-                if (!$formModel->add()) {
-                    continue;
-                }
-                unset($formModel);
-            }
-            unset($allData);
-            $start = $start + $limit;
-            return self::autoLoopWithdraw($limit, $start);
-        }
-        return true;
-    }
-
-}

+ 0 - 116
common/models/forms/WithdrawLevelForm.php

@@ -1,116 +0,0 @@
-<?php
-namespace common\models\forms;
-
-use common\components\Model;
-use common\helpers\Date;
-use common\models\WithdrawLevel;
-
-/**
- * Login form
- */
-class WithdrawLevelForm extends Model
-{
-    public $id;
-    public $minAmount;
-    public $maxAmount;
-    public $taxPercent;
-
-    /**
-     * @inheritdoc
-     */
-    public function rules()
-    {
-        return [
-            [['minAmount', 'maxAmount', 'taxPercent'], 'trim'],
-            [['minAmount', 'taxPercent'], 'required'],
-            [['id'], 'exist', 'targetClass'=>WithdrawLevel::class, 'targetAttribute'=>'ID'],
-            [['minAmount', 'maxAmount', 'taxPercent'], 'price'],
-            [['minAmount', 'maxAmount'], 'isRightAmount'],
-        ];
-    }
-
-    /**
-     * 指定校验场景
-     * @return array
-     */
-    public function scenarios()
-    {
-        $parentScenarios =  parent::scenarios();
-        $customScenarios = [
-            'add' => ['minAmount', 'maxAmount', 'taxPercent'],
-            'edit' => ['id', 'minAmount', 'maxAmount', 'taxPercent'],
-        ];
-        return array_merge($parentScenarios, $customScenarios);
-    }
-
-    public function attributeLabels()
-    {
-        return [
-            'minAmount' => '最小提现金额',
-            'maxAmount' => '最高提现金额',
-            'taxPercent' => '扣税比率',
-        ];
-    }
-
-    /**
-     * 校验最小金额
-     * @param $attribute
-     */
-    public function isRightAmount($attribute){
-        if($this->maxAmount){
-            if($this->minAmount >= $this->maxAmount){
-                $this->addError($attribute, '最小提现金额比最高提现金额大');
-            }
-        }
-        $where = 'MIN_AMOUNT<=:AMOUNT AND MAX_AMOUNT>=:AMOUNT';
-        $params = [
-            ':AMOUNT'=>$this->$attribute
-        ];
-        if($this->scenario == 'edit'){
-            $where .= ' AND ID<>:ID';
-            $params[':ID'] = $this->id;
-        }
-        if(WithdrawLevel::find()->where($where, $params)->exists()){
-            $this->addError($attribute, $this->attributeLabels()[$attribute].'和其他设置有冲突');
-        }
-        $whereT = 'MIN_AMOUNT<=:AMOUNT AND MAX_AMOUNT IS NULL';
-        $paramsT = [
-            ':AMOUNT'=>floatval($this->$attribute)
-        ];
-        if($this->scenario == 'edit'){
-            $whereT .= ' AND ID<>:ID';
-            $paramsT[':ID'] = $this->id;
-        }
-        if(WithdrawLevel::find()->where($whereT, $paramsT)->exists()){
-            $this->addError($attribute, $this->attributeLabels()[$attribute].'和其他设置有冲突');
-        }
-    }
-
-    /**
-     * 编辑
-     * @return WithdrawLevel|null|static
-     */
-    public function edit(){
-        if(!$this->validate()){
-            return null;
-        }
-        if($this->scenario == 'add'){
-            $model = new WithdrawLevel();
-            $model->CREATED_AT = Date::nowTime();
-        } elseif($this->scenario == 'edit') {
-            $model = WithdrawLevel::findOne(['ID'=>$this->id]);
-        } else {
-            $this->addError('id', '提交场景不存在');
-            return null;
-        }
-        $model->MIN_AMOUNT = $this->minAmount;
-        $model->MAX_AMOUNT = $this->maxAmount;
-        $model->TAX_PERCENT = $this->taxPercent;
-        if($model->save()){
-            return $model;
-        } else {
-            $this->addErrors($model->getErrors());
-            return null;
-        }
-    }
-}

+ 0 - 55
console/controllers/BonusController.php

@@ -7,12 +7,8 @@
  */
 namespace console\controllers;
 
-use backendApi\modules\v1\models\lists\bonus\BalanceList;
-use backendApi\modules\v1\models\lists\bonus\PerfOrderList;
-use backendApi\modules\v1\models\lists\bonus\PeriodBonusList;
 use common\helpers\Cache;
 use common\helpers\Form;
-use common\libs\export\module\BonusExport;
 use common\models\forms\CalcServePeriodForm;
 use common\models\forms\PeriodForm;
 use yii\db\Exception;
@@ -147,55 +143,4 @@ class BonusController extends BaseController
 //            ]);
         }
     }
-
-    /**
-     * 奖金余额导出
-     * @param $taskId
-     * @return bool
-     */
-    public function actionBalanceExport($taskId){
-        return $this->_export($taskId, BalanceList::class, '会员奖金余额列表');
-    }
-
-    /**
-     * 最新奖金列表导出
-     * @param $taskId
-     * @return bool
-     */
-    public function actionNewPeriodBonusExport($taskId){
-        return $this->_export($taskId, PeriodBonusList::class, '最新奖金列表');
-    }
-
-    /**
-     * 业绩单导出
-     * @param $taskId
-     * @return bool
-     */
-    public function actionPerfOrderExport($taskId){
-        return $this->_export($taskId, PerfOrderList::class, '业绩单列表');
-    }
-
-    /**
-     * 导出方法
-     * @param $taskId
-     * @param $className
-     * @param $listName
-     * @return bool
-     */
-    private function _export($taskId, $className, $listName){
-        $factory = BonusExport::factory($taskId);
-        $factory->listModelClass = $className;
-        try {
-            if ($factory->generate()) {
-                \Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), $listName.'导出成功');
-            }
-            unset($factory, $taskId, $className, $listName);
-            return true;
-        } catch (\Exception $e) {
-            echo $listName.'导出失败。详情:' . $e->getMessage();
-            \Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), $listName.'导出失败。详情:' . $e->getMessage(), false);
-        }
-        unset($factory, $taskId, $className, $listName);
-        return false;
-    }
 }

+ 0 - 210
console/controllers/ChangeNetController.php

@@ -1,210 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: liang
- * Date: 2020/2/18
- * Time: 6:36 PM
- */
-namespace console\controllers;
-
-
-use common\models\UserInfo;
-use common\models\UserNetwork;
-use common\models\UserRelation;
-
-class ChangeNetController extends BaseController {
-
-    //顶点ID列表
-    const TOP_ID_LIST = [
-        '670B84FD7C216D4EE055736AECE8644D',
-        '80552117701578757',
-    ];
-    //LOCATION缓存键
-    const CHANGE_NET_CACHE_LOCATION_TAG_KEY = 'changeNet:cache:locationTag:key';
-
-    /**
-     * 清空缓存
-     */
-    public function actionClearCache() {
-        $this->_clearTagCache();
-    }
-
-    /**
-     * 加入安置数据
-     * @param int $startPage
-     * @throws \yii\db\Exception
-     */
-    public function actionAddNetwork($startPage=1) {
-        $allCount = UserInfo::find()->where('1=1')->orderBy(' NETWORK_DEEP ASC,USER_ID ASC')->count('ID');
-        $limit = 1000;
-        $pageCount = ceil($allCount/$limit);
-        unset($allCount);
-        for($page=$startPage;$page<=$pageCount;$page++) {
-            $userList = UserInfo::find()->where('1=1')->orderBy('NETWORK_DEEP ASC,USER_ID ASC')->limit($limit)->offset(($page-1)*$limit)->asArray()->all();
-            $batchInsertList = [];
-            foreach ($userList as $everyUser) {
-                $netParentList = \Yii::$app->db->createCommand("SELECT * FROM AR_USER_NETWORK WHERE USER_ID=:USER_ID ORDER  BY PARENT_UID ASC")->bindValues([':USER_ID'=>$everyUser['USER_ID']])->queryAll();
-
-                if( !$netParentList ) {
-                    echo '不存在parentList :' . $everyUser['USER_ID'] . PHP_EOL;
-                    continue;
-                }
-                $parentUidsStr = '';
-                $topUid = '';
-                $location = 0;
-                foreach ($netParentList as $netParentData) {
-                    if( !$netParentData['PARENT_UID'] ) continue;
-
-                    if( !$topUid ) {
-                        $topUid = $netParentData['TOP_UID'];
-                    }
-                    if(  $netParentData['PARENT_UID'] === $everyUser['CON_UID'] ) {
-                        $location = $netParentData['LOCATION'];
-                    }
-
-                    $parentUidsStr .= $netParentData['PARENT_UID'] . ',';
-
-                    unset($netParentData);
-                }
-
-                if( $location === 0 && !in_array($everyUser['USER_ID'], self::TOP_ID_LIST) ) {
-                    echo 'location Error :' . $everyUser['USER_ID'] . PHP_EOL;
-                    continue;
-                }
-
-                $parentUidsStr = rtrim($parentUidsStr, ',');
-                unset($netParentList);
-
-                $parentLocationTag = $this->_getLocationTagCache($everyUser['CON_UID']);
-                if( $parentLocationTag ) {
-                    $locationTag = $parentLocationTag . $location;
-                }else {
-                    $locationTag = '1';
-                }
-                if( $locationTag ==='1' && !in_array($everyUser['USER_ID'], self::TOP_ID_LIST) ) {
-                    echo 'locationTag错误 :' . $everyUser['USER_ID'] . PHP_EOL;
-                    continue;
-                }
-
-                $this->_addLocationTagCache($everyUser['USER_ID'], $locationTag);
-
-                if( $topUid === '' && in_array($everyUser['USER_ID'], self::TOP_ID_LIST) ) {
-                    $topUid = $everyUser['USER_ID'];
-                }
-                $batchInsertList[] = [
-                    'USER_ID' => $everyUser['USER_ID'],
-                    'PARENT_UID' => $everyUser['CON_UID'],
-                    'LOCATION_TAG' => $locationTag,
-                    'RELATIVE_LOCATION' => $location,
-                    'TOP_UID' => $topUid,
-                    'TOP_DEEP' => $everyUser['NETWORK_DEEP'],
-                    'PARENT_UIDS' => $parentUidsStr,
-                    'CREATED_AT' => $everyUser['CREATED_AT'],
-//                    'UPDATED_AT' => '',
-                ];
-
-                unset($everyUser, $location, $locationTag, $topUid, $parentUidsStr);
-            }
-            unset($userList);
-
-            UserNetwork::batchInsert($batchInsertList);
-            unset($batchInsertList);
-
-            echo sprintf("导入新网体表数据,总页数【%s】,当前页数:【%s】写入成功".PHP_EOL, $pageCount, $page);
-
-        }
-
-    }
-
-    /**
-     * 加入推荐数据
-     * @param int $startPage
-     * @throws \yii\db\Exception
-     */
-    public function actionAddRelation($startPage=1) {
-        $allCount = UserInfo::find()->where('1=1')->orderBy(' RELATION_DEEP ASC,USER_ID ASC')->count('ID');
-        $limit = 1000;
-        $pageCount = ceil($allCount/$limit);
-        unset($allCount);
-        for($page=$startPage;$page<=$pageCount;$page++) {
-            $userList = UserInfo::find()->where('1=1')->orderBy('RELATION_DEEP ASC,USER_ID ASC')->limit($limit)->offset(($page-1)*$limit)->asArray()->all();
-            $batchInsertList = [];
-            foreach ($userList as $everyUser) {
-                $relationParentList = \Yii::$app->db->createCommand("SELECT * FROM AR_USER_RELATION WHERE USER_ID=:USER_ID ORDER  BY PARENT_UID ASC")->bindValues([':USER_ID'=>$everyUser['USER_ID']])->queryAll();
-
-                if( !$relationParentList ) {
-                    echo '不存在parentList :' . $everyUser['USER_ID'] . PHP_EOL;
-                    continue;
-                }
-                $parentUidsStr = '';
-                $topUid = '';
-                foreach ($relationParentList as $relationParentData) {
-                    if( !$relationParentData['PARENT_UID'] ) continue;
-
-                    if( !$topUid ) {
-                        $topUid = $relationParentData['TOP_UID'];
-                    }
-
-                    $parentUidsStr .= $relationParentData['PARENT_UID'] . ',';
-
-                    unset($relationParentData);
-                }
-
-                $parentUidsStr = rtrim($parentUidsStr, ',');
-                unset($relationParentList);
-
-                if( $topUid === '' && in_array($everyUser['USER_ID'], self::TOP_ID_LIST) ) {
-                    $topUid = $everyUser['USER_ID'];
-                }
-                $batchInsertList[] = [
-                    'USER_ID' => $everyUser['USER_ID'],
-                    'PARENT_UID' => $everyUser['REC_UID'],
-                    'TOP_UID' => $topUid,
-                    'TOP_DEEP' => $everyUser['RELATION_DEEP'],
-                    'PARENT_UIDS' => $parentUidsStr,
-                    'CREATED_AT' => $everyUser['CREATED_AT'],
-//                    'UPDATED_AT' => '',
-                ];
-
-
-                unset($everyUser, $topUid, $parentUidsStr);
-            }
-            unset($userList);
-
-            UserRelation::batchInsert($batchInsertList);
-            unset($batchInsertList);
-
-            echo sprintf("导入新推荐表数据,总页数【%s】,当前页数:【%s】写入成功".PHP_EOL, $pageCount, $page);
-
-        }
-
-    }
-
-    /**
-     * 添加网体标记Cache数据
-     * @param $userId
-     * @param $locationTag
-     * @return mixed
-     */
-    private function _addLocationTagCache($userId, $locationTag) {
-        return \Yii::$app->redis->hSet(self::CHANGE_NET_CACHE_LOCATION_TAG_KEY, $userId, $locationTag);
-    }
-
-    /**
-     * 获取网体标记Cache数据
-     * @param $userId
-     * @return mixed
-     */
-    private function _getLocationTagCache($userId) {
-        return \Yii::$app->redis->hGet(self::CHANGE_NET_CACHE_LOCATION_TAG_KEY, $userId);
-    }
-
-    /**
-     * 清空网体标记Cache数据
-     * @return mixed
-     */
-    private function _clearTagCache() {
-        return \Yii::$app->redis->del(self::CHANGE_NET_CACHE_LOCATION_TAG_KEY);
-    }
-
-}

+ 0 - 1022
console/controllers/ImportController.php

@@ -1,1022 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: xiaohuitu
- * Date: 2020/2/18
- * Time: 6:36 PM
- */
-namespace console\controllers;
-
-
-use common\helpers\Cache;
-use common\helpers\Excel;
-
-use common\helpers\snowflake\SnowFake;
-use common\helpers\user\Info;
-use common\models\Declaration;
-use common\models\DeclarationLevel;
-use common\models\DecOrder;
-use common\models\ImportScore;
-use common\models\Order;
-use common\models\OrderShop;
-use common\models\PerfMonth;
-use common\models\PerfPeriod;
-use common\models\TmpAreaNetwork;
-use common\models\TmpDeleteUser;
-use common\models\TmpFreezeUser;
-use common\models\TmpOldNetwork;
-use common\models\TmpOldNetworkAll;
-use common\models\TmpOldNetworkError;
-use common\models\TmpOldNetworkReplenish;
-use common\models\TmpOldUser;
-use common\models\User;
-use common\models\UserInfo;
-use common\models\UserMove;
-use common\models\UserNetwork;
-use common\models\UserReg;
-use common\models\UserRelation;
-use console\models\ImportForm;
-use yii\base\BaseObject;
-
-
-class ImportController extends BaseController
-{
-    const LIMIT = 1000;
-
-    CONST EXCEL_TABLE_USER_FIELD = [
-        '序号' => 'SORT',
-        '会员编号' => 'USER_NAME',
-        '会员姓名' => 'REAL_NAME',
-        '推荐人编号' => 'REC_USER_NAME',
-        '推荐人姓名' => 'REC_REAL_NAME',
-        '安置人编号' => 'NET_USER_NAME',
-        '安置人姓名' => 'NET_REAL_NAME',
-    ];
-
-    CONST EXCEL_TABLE_NETWORK_FIELD = [
-        '会员编号' => 'USER_NAME',
-        '会员名称' => 'REAL_NAME',
-        '推荐人编号' => 'PARENT_USER_NAME',
-        '推荐人名称' => 'PARENT_REAL_NAME',
-        '安置人编号' => 'NET_USER_NAME',
-        '安置人名称' => 'NET_REAL_NAME',
-    ];
-
-    CONST EXCEL_TABLE_POINTS_FIELD = [
-        '会员编号' => 'USER_NAME',
-        '会员姓名' => 'REAL_NAME',
-        '会员级别' => 'LEVEL_NAME',
-        '会员荣衔' => 'EMP_LEVEL_NAME',
-        '总奖金' => 'BONUS_TOTAL',
-        '原总奖金' => 'ORI_BONUS_TOTAL',
-        '基础积分' => 'BASE_SCORE',
-        '级别积分' => 'LEVEL_SCORE',
-        '升级积分' => 'UPGRADE_SCORE',
-        '总积分' => 'TOTAL_SCORE',
-    ];
-
-    const TOP_USER_NAME = 'Q94839185';
-    const TOP_REAL_NAME = '齐长青';
-
-    const IMPORT_CACHE_SORT_KEY = 'console:importCacheSortKey';
-
-    /**
-     * @param string $fileName
-     * @param int $rowCount
-     * @param int $startRow
-     * @throws \yii\base\Exception
-     */
-    public function actionOldUser($fileName, $rowCount=1000, $startRow=1)
-    {
-        $excel = new Excel();
-        $result = $excel->pageImportDataByExcelFile($fileName, $rowCount, $startRow, self::LIMIT);
-
-        $insertData = [];
-        foreach ($result as $everyData) {
-            if( !$everyData ) continue;
-
-            $oneInsertData = [];
-            foreach ($everyData as $key => $value) {
-                if( !isset(self::EXCEL_TABLE_USER_FIELD[$key]) ) continue;
-
-                $oneInsertData[self::EXCEL_TABLE_USER_FIELD[$key]] = $value;
-            }
-
-            $insertData[] = $oneInsertData;
-            unset($oneInsertData, $everyData);
-        }
-//        var_dump($insertData);die;
-        TmpOldUser::batchInsert($insertData);
-        unset($insertData);
-
-        echo sprintf("【%s】导入成功".PHP_EOL, $fileName);
-    }
-
-    /**
-     * @param string $fileName
-     * @param int $rowCount
-     * @param int $startRow
-     * @throws \yii\base\Exception
-     */
-    public function actionOldNetwork($fileName, $rowCount=1000, $startRow=1)
-    {
-        ini_set('memory_limit','512M');
-        $pageCount = ceil($rowCount/self::LIMIT);
-        $excel = new Excel();
-        for($page=1;$page<=$pageCount;$page++) {
-            $newStartRow = $startRow + self::LIMIT * ($page - 1);
-            $result = $excel->pageImportDataByExcelFile($fileName, $rowCount, $newStartRow, self::LIMIT);
-
-            $insertData = [];
-            foreach ($result as $sort => $everyData) {
-                if( !$everyData ) continue;
-
-                $oneInsertData = [];
-                $oneInsertData['SORT'] = $newStartRow + $sort;
-                foreach ($everyData as $key => $value) {
-                    if( !isset(self::EXCEL_TABLE_NETWORK_FIELD[$key]) ) continue;
-
-                    $oneInsertData[self::EXCEL_TABLE_NETWORK_FIELD[$key]] = $value;
-                }
-
-
-                //判断用户表中是否已经存在该会员
-                $one = UserInfo::find()->select(["ID", "USER_NAME"])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$oneInsertData['USER_NAME']])->asArray()->one();
-                if( $one ){
-                    echo '会员编号'.$oneInsertData['USER_NAME'].'已存在'.PHP_EOL;
-                    continue;
-                }
-
-
-                if( $oneInsertData['NET_USER_NAME'] === self::TOP_USER_NAME ) {
-                    $oneInsertData['NET_DEEP'] = 1;
-                    $oneInsertData['REC_DEEP'] = 1;
-                }else {
-                    $oneInsertData['NET_DEEP'] = 0;
-                    $oneInsertData['REC_DEEP'] = 0;
-                }
-
-                if($oneInsertData['NET_USER_NAME']==NULL) {
-                    $oneInsertData['NET_USER_NAME'] = '';
-                    $oneInsertData['NET_REAL_NAME'] = $oneInsertData['NET_REAL_NAME'] ?? '';
-                    echo '用户编号'.$oneInsertData['USER_NAME'].'的接点人为空'.PHP_EOL;
-                }
-                if($oneInsertData['PARENT_USER_NAME']==NULL) {
-                    $oneInsertData['PARENT_USER_NAME'] = '';
-                    $oneInsertData['PARENT_REAL_NAME'] = $oneInsertData['PARENT_REAL_NAME'] ?? '';
-                    echo '用户编号'.$oneInsertData['USER_NAME'].'的推荐人为空'.PHP_EOL;
-                }
-
-                //更正tmp_old_network表中的错误数据
-//                $importOne = TmpOldNetwork::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$oneInsertData['USER_NAME']])->asArray()->one();
-//                if( $importOne ) {
-//                    echo $oneInsertData['USER_NAME'] . PHP_EOL;
-//                    TmpOldNetwork::updateAll([
-//                        'PARENT_USER_NAME' => $oneInsertData['PARENT_USER_NAME'],
-//                        'PARENT_REAL_NAME' => $oneInsertData['PARENT_REAL_NAME'],
-//                        'NET_USER_NAME' => $oneInsertData['NET_USER_NAME'],
-//                        'NET_REAL_NAME' => $oneInsertData['NET_REAL_NAME']
-//                    ], 'ID=:ID', ['ID'=>$importOne['ID']]);
-//                }else {
-//                    $insertData[] = $oneInsertData;
-//                }
-//
-//                unset($importOne);
-
-                $insertData[] = $oneInsertData;
-                unset($oneInsertData, $everyData);
-            }
-
-            if( $insertData ) TmpOldNetwork::batchInsert($insertData);
-            unset($newStartRow, $insertData);
-
-            echo sprintf("文件:【%s】页数:【%s】导入成功".PHP_EOL, $fileName, $page);
-        }
-    }
-
-    //计算导入会员中顶点的开拓深度
-    public function actionUpdateRecTopDeep($startPage=1) {
-        $numCount = TmpOldNetwork::find()->where("1=1")->orderBy("SORT ASC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-
-            $pageList = TmpOldNetwork::find()->where("1=1")->orderBy("SORT ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-
-                $one = TmpOldNetwork::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['PARENT_USER_NAME']])->asArray()->one();
-                if( !$one ) {
-                    //推荐人不在导入会员中 获取深度
-                    $userInfoOne = UserInfo::find()->select(['USER_NAME', 'RELATION_DEEP'])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['PARENT_USER_NAME']])->asArray()->one();
-                    if( !$userInfoOne ) {
-                        echo sprintf("在系统中未找到推荐人,会员编号: 【%s】,推荐人编号:【%s】" . PHP_EOL, $pageData['USER_NAME'], $pageData['PARENT_USER_NAME']);
-                        unset($one, $userInfoOne);
-                        continue;
-                    }
-                    TmpOldNetwork::updateAll(['REC_DEEP'=>$userInfoOne['RELATION_DEEP']+1], 'ID=:ID', ['ID'=>$pageData['ID']]);
-                    unset($userInfoOne);
-                }
-                unset($pageData,$one);
-            }
-            unset($pageList);
-        }
-        unset($numCount, $pageCount);
-    }
-
-    public function actionUpdateNetTopDeep($startPage=1) {
-        $numCount = TmpOldNetwork::find()->where("1=1")->orderBy("SORT ASC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-
-            $pageList = TmpOldNetwork::find()->where("1=1")->orderBy("SORT ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-
-                $one = TmpOldNetwork::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['NET_USER_NAME']])->asArray()->one();
-                if( !$one ) {
-                    //安置人不在导入会员中 获取深度
-                    $userInfoOne = UserInfo::find()->select(['USER_NAME', 'NETWORK_DEEP'])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['NET_USER_NAME']])->asArray()->one();
-                    if( !$userInfoOne ) {
-                        echo sprintf("在系统中未找到安置人,会员编号: 【%s】,安置人编号:【%s】" . PHP_EOL, $pageData['USER_NAME'], $pageData['NET_USER_NAME']);
-                        unset($one, $userInfoOne);
-                        continue;
-                    }
-                    //更新深度
-                    TmpOldNetwork::updateAll(['NET_DEEP'=>$userInfoOne['NETWORK_DEEP']+1], 'ID=:ID', ['ID'=>$pageData['ID']]);
-                    unset($userInfoOne);
-                }
-                unset($pageData,$one);
-            }
-            unset($pageList);
-        }
-        unset($numCount, $pageCount);
-    }
-
-    /**
-     * 更新安置深度
-     * @param int $deep
-     * @return int
-     */
-    public function actionUpdateNetDeep($deep=1) {
-        echo sprintf("更新安置深度开始,当前安置深度为【%s】".PHP_EOL, $deep);
-        $list = TmpOldNetwork::find()->where('NET_DEEP=:NET_DEEP', ['NET_DEEP'=>$deep])->asArray()->all();
-        if( !$list ) return $deep;
-        foreach ($list as $data) {
-//            echo $data['USER_NAME'] . PHP_EOL;
-            TmpOldNetwork::updateAll([
-                'NET_DEEP' => $deep + 1,
-            ], 'NET_USER_NAME=:NET_USER_NAME', ['NET_USER_NAME'=>$data['USER_NAME']]);
-
-            unset($data);
-        }
-
-        unset($list);
-        return $this->actionUpdateNetDeep($deep+1);
-    }
-
-    /**
-     * 更新安置深度
-     * @param int $startDeep
-     * @param int $endDeep
-     * @return bool
-     */
-    public function actionUpdateNetDeepTwo($startDeep=1, $endDeep=10) {
-        for( $deep=$startDeep;$deep<=$endDeep;$deep++ ) {
-            $deep = $this->actionUpdateNetDeep($deep);
-        }
-
-        return true;
-    }
-
-    /**
-     * 更新推荐深度
-     * @param int $deep
-     * @return int
-     */
-    public function actionUpdateRecDeep($deep=1) {
-        echo sprintf("更新推荐深度开始,当前推荐深度为【%s】".PHP_EOL, $deep);
-        $list = TmpOldNetwork::find()->where('REC_DEEP=:REC_DEEP', ['REC_DEEP'=>$deep])->asArray()->all();
-        if( !$list ) return $deep;
-        foreach ($list as $data) {
-
-            TmpOldNetwork::updateAll([
-                'REC_DEEP' => $deep + 1,
-            ], 'PARENT_USER_NAME=:PARENT_USER_NAME', ['PARENT_USER_NAME'=>$data['USER_NAME']]);
-
-            unset($data);
-        }
-
-        unset($list);
-        return $this->actionUpdateRecDeep($deep+1);
-    }
-
-
-    /**
-     * 更新推荐深度
-     * @param int $startDeep
-     * @param int $endDeep
-     * @return bool
-     */
-    public function actionUpdateRecDeepTwo($startDeep=1, $endDeep=10) {
-        for( $deep=$startDeep;$deep<=$endDeep;$deep++ ) {
-            $deep = $this->actionUpdateRecDeep($deep);
-        }
-
-        return true;
-    }
-
-
-    /**
-     * 清空缓存
-     */
-    public function actionClearCache() {
-        $importForm = new ImportForm();
-        $importForm->clearInfoCache();
-
-        echo "清空完成" . PHP_EOL;
-    }
-
-
-
-    public function actionOnlineUser($startPage=1) {
-        //加入顶点信息
-        $importForm = new ImportForm();
-
-        //从old_network中获取所有的会员信息
-        $numCount = TmpOldNetwork::find()->where("1=1")->orderBy("NET_DEEP ASC, REC_DEEP ASC, SORT ASC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = TmpOldNetwork::find()->where("1=1")->orderBy("NET_DEEP ASC, REC_DEEP ASC, SORT ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-
-            foreach ($pageList as $pageData) {
-                $importForm->addOnlineUser($pageData);
-                unset($pageData,$userData);
-            }
-            unset($pageList);
-            echo sprintf("导入【用户】数据,总页数【%s】,当前页数:【%s】导入成功".PHP_EOL, $pageCount, $page);
-        }
-        unset($db, $numCount, $pageCount);
-    }
-
-    /**
-     * 写入用户缓存数据
-     * @param int $startPage
-     */
-    public function actionAddUserCache($startPage=1) {
-        $importForm = new ImportForm();
-        $importForm->clearCache();
-
-        $numCount = User::find()->where("1=1")->orderBy("ID DESC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = User::find()->select(['ID', 'USER_NAME'])->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                $importForm->cacheUserId($pageData['USER_NAME'], $pageData['ID']);
-                unset($pageData);
-            }
-            unset($pageList);
-
-            echo sprintf("写入用户缓存数据,总页数【%s】,当前页数:【%s】写入成功".PHP_EOL, $pageCount, $page);
-        }
-    }
-
-    //写userinfo及关系表
-    public function actionOnlineInfo($startPage=1 ,$startStatus=true,$startUserName=NULL) {
-        //从old_network中获取所有的会员信息
-        $numCount = TmpOldNetwork::find()->where("1=1")->orderBy("NET_DEEP ASC, REC_DEEP ASC, SORT ASC")->count("ID");
-
-//        $db = \Yii::$app->db;
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = TmpOldNetwork::find()->where("1=1")->orderBy("NET_DEEP ASC, REC_DEEP ASC, SORT ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-//            $transaction = $db->beginTransaction();
-            $importForm = new ImportForm();
-//            try {
-            foreach ($pageList as $pageData) {
-                if( !$startStatus && $pageData["USER_NAME"] === $startUserName )
-                {
-                    $startStatus = true;
-                }
-                if( !$startStatus ) continue;
-
-                $importForm->addOnlineInfo($pageData);
-            }
-
-//                $transaction->commit();
-//            }catch (\Exception $e) {
-//                $transaction->rollBack();
-//
-//                echo $e->getTraceAsString();die;
-//            }
-
-            unset($pageList);
-
-            echo sprintf("导入【关系】数据,总页数【%s】,页数:【%s】导入成功".PHP_EOL, $pageCount, $page);
-        }
-
-        unset($db, $numCount, $pageCount);
-
-    }
-
-
-    //写推荐关系表
-    public function actionOnlineRelation($startPage=1 ,$startStatus=true,$startUserName=NULL) {
-        //从old_network中获取所有的会员信息
-        $numCount = TmpOldNetwork::find()->where("1=1")->orderBy("REC_DEEP ASC, SORT ASC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = TmpOldNetwork::find()->where("1=1")->orderBy("REC_DEEP ASC, SORT ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-
-            $transaction = \Yii::$app->db->beginTransaction();
-            try {
-
-                foreach ($pageList as $pageData) {
-                    if( !$startStatus && $pageData["USER_NAME"] === $startUserName )
-                    {
-                        $startStatus = true;
-                    }
-                    if( !$startStatus ) continue;
-
-                    //会员ID
-                    $userId = Info::getUserIdByUserName($pageData['USER_NAME']);
-                    //推荐人ID
-                    $userInfoRec = UserInfo::find()->select(['USER_ID'])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['PARENT_USER_NAME']])->asArray()->one();
-                    $recUid = $userInfoRec['USER_ID'];
-
-                    //推荐关系
-                    $conRelationInfo = UserRelation::findOneAsArray(['USER_ID'=>$recUid]);
-                    if( !$conRelationInfo ) {
-                        throw new Exception('推荐人'.$pageData['PARENT_USER_NAME'].'不存在');
-                    }
-                    //修改深度
-                    $deep = $conRelationInfo['TOP_DEEP'] + 1;
-                    UserInfo::updateAll([
-                        "RELATION_DEEP" => $deep,
-                    ], "USER_ID='{$userId}'");
-
-                    // 加入推荐网络关系
-                    $insertData = [
-                        'ID' => SnowFake::instance()->generateId(),
-                        "USER_ID"  => $userId,
-                        "PARENT_UID"  => $recUid,
-                        "TOP_UID"  => $conRelationInfo['TOP_UID'],
-                        "TOP_DEEP"  => $deep,
-                        "PARENT_UIDS"  => $conRelationInfo['PARENT_UIDS'] . ',' . $recUid,
-                        "CREATED_AT"  => time(),
-                    ];
-                    UserRelation::insertOne($insertData);
-
-                    if(!UserInfo::updateAllCounters(['REC_NUM'=>1], "USER_ID=:USER_ID", [':USER_ID'=>$recUid])){
-                        throw new Exception('会员开拓关系下级节点数量更新失败');
-                    }
-                    unset($userId,$userInfoRec,$recUid,$conRelationInfo,$deep,$insertData);
-                }
-
-                $transaction->commit();
-            }catch (\Exception $e) {
-                $transaction->rollBack();
-                echo $e->getMessage();die;
-            }
-
-            unset($pageList);
-
-            echo sprintf("导入【关系】数据,总页数【%s】,页数:【%s】导入成功".PHP_EOL, $pageCount, $page);
-        }
-
-        unset($db, $numCount, $pageCount);
-
-    }
-
-
-    /**
-     * 检测排序
-     * @param int $startPage
-     */
-    public function actionCheckSort($startPage=1){
-        \Yii::$app->redis->del(self::IMPORT_CACHE_SORT_KEY);
-        $numCount = User::find()->where("1=1")->orderBy("ID DESC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = User::find()->select(['ID', 'USER_NAME'])->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                \Yii::$app->redis->hSet(self::IMPORT_CACHE_SORT_KEY, $pageData['USER_NAME'], 1);
-                unset($pageData);
-            }
-            unset($pageList);
-
-//            echo sprintf("写入用户缓存数据,总页数【%s】,当前页数:【%s】写入成功".PHP_EOL, $pageCount, $page);
-        }
-        unset($numCount);
-
-        $numCount = TmpOldNetwork::find()->where("1=1")->orderBy("NET_DEEP ASC, REC_DEEP ASC, SORT ASC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = TmpOldNetwork::find()->where("1=1")->orderBy("NET_DEEP ASC, REC_DEEP ASC, SORT ASC")->offset(($page - 1) * self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                $recStatus = \Yii::$app->redis->hGet(self::IMPORT_CACHE_SORT_KEY, $pageData['PARENT_USER_NAME']);
-                $netStatus = \Yii::$app->redis->hGet(self::IMPORT_CACHE_SORT_KEY, $pageData['NET_USER_NAME']);
-                if( !$recStatus || !$netStatus ) {
-                    echo sprintf("用户编号: %s,用户姓名:%s,推荐人编号:%s,推荐人姓名:%s,安置人编号:%s,安置人姓名:%s" . PHP_EOL, $pageData['USER_NAME'], $pageData['REAL_NAME'], $pageData['PARENT_USER_NAME'], $pageData['PARENT_REAL_NAME'], $pageData['NET_USER_NAME'], $pageData['NET_REAL_NAME']);
-                    TmpOldNetworkError::insertOne($pageData);
-                    TmpOldNetwork::deleteAll('ID=:ID', ['ID'=>$pageData['ID']]);
-                }
-                unset($recStatus, $netStatus);
-                \Yii::$app->redis->hSet(self::IMPORT_CACHE_SORT_KEY, $pageData['USER_NAME'], 1);
-
-                unset($pageData);
-            }
-            unset($pageList);
-
-//            echo sprintf("写入导入缓存数据,总页数【%s】,当前页数:【%s】写入成功".PHP_EOL, $pageCount, $page);
-        }
-    }
-
-
-    public function actionCheckErrorSort() {
-        $numCount = TmpOldNetwork::find()->where("1=1")->orderBy("SORT ASC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=1;$page<=$pageCount;$page++) {
-            $pageList = TmpOldNetwork::find()->where("1=1")->orderBy("SORT ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                //查询这个人的推荐人和接点人是否在当前表中
-                $one = TmpOldNetwork::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['PARENT_USER_NAME']])->asArray()->one();
-                if( !$one ) {
-                    $userInfoOne = UserInfo::find()->select(['USER_NAME', 'RELATION_DEEP', 'NETWORK_DEEP'])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['PARENT_USER_NAME']])->asArray()->one();
-                    if( !$userInfoOne ) {
-                        TmpOldNetworkError::insertOne($pageData);
-                        TmpOldNetwork::deleteAll('ID=:ID', ['ID'=>$pageData['ID']]);
-                        echo 'REC ERROR' . $pageData['USER_NAME'] . PHP_EOL;
-                        unset($one, $userInfoOne);
-                        continue;
-                    }
-                    unset($userInfoOne);
-                }
-                unset($one);
-
-                if( $pageData['PARENT_USER_NAME'] !== $pageData['NET_USER_NAME'] ) {
-                    //接点人
-                    $one = TmpOldNetwork::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['NET_USER_NAME']])->asArray()->one();
-                    if( !$one ) {
-                        $userInfoOne = UserInfo::find()->select(['USER_NAME', 'RELATION_DEEP', 'NETWORK_DEEP'])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['NET_USER_NAME']])->asArray()->one();
-                        if( !$userInfoOne ) {
-                            TmpOldNetworkError::insertOne($pageData);
-                            TmpOldNetwork::deleteAll('ID=:ID', ['ID'=>$pageData['ID']]);
-                            echo 'NET ERROR' . $pageData['USER_NAME'] . PHP_EOL;
-                            unset($one, $userInfoOne);
-                            continue;
-                        }
-                        unset($userInfoOne);
-                    }
-
-                    unset($one);
-                }
-
-                unset($pageData);
-            }
-
-            unset($pageList);
-        }
-    }
-
-
-    /**
-     * 为上级增加数量
-     * @param int $startPage
-     */
-    public function actionUpdateParentNum($startPage=1){
-
-        $numCount = UserInfo::find()->select('USER_ID,CON_UID,REC_UID')->where("1=1")->orderBy("ID DESC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-
-            $pageList = UserInfo::find()->select('USER_ID,CON_UID,REC_UID')->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                if($pageData['CON_UID']){
-                    UserInfo::updateAllCounters(['CON_NUM'=> 1], "USER_ID=:USER_ID", [':USER_ID'=>$pageData['CON_UID']]);
-                }
-                if($pageData['REC_UID']){
-                    UserInfo::updateAllCounters(['REC_NUM'=> 1], "USER_ID=:USER_ID", [':USER_ID'=>$pageData['REC_UID']]);
-                }
-                unset($pageData);
-            }
-            unset($pageList);
-
-            echo sprintf("导入【关系】数据,总页数【%s】,页数:【%s】导入成功".PHP_EOL, $pageCount, $page);
-        }
-        unset($numCount, $pageCount);
-    }
-
-    //删除未写入完整的用户信息
-    public function actionDeleteUserInfo($userName) {
-        //从User中获取会员ID
-        $userData = User::find()->select(['ID'])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$userName])->asArray()->one();
-        if( !$userData ) {
-            return true;
-        }
-        UserInfo::deleteAll("USER_ID='{$userData['ID']}'");
-        $netInfo = UserNetwork::find()->where('USER_ID=:USER_ID', ['USER_ID'=>$userData['ID']])->asArray()->one();
-        if($netInfo){
-            UserNetwork::deleteAll("USER_ID='{$userData['ID']}'");
-        }
-        $recInfo = UserNetwork::find()->where('USER_ID=:USER_ID', ['USER_ID'=>$userData['ID']])->asArray()->one();
-        if($recInfo){
-            UserRelation::deleteAll("USER_ID='{$userData['ID']}'");
-        }
-        echo sprintf("删除用户【%s】,成功".PHP_EOL, $userName);
-
-        unset($userData,$netInfo,$recInfo);
-    }
-
-
-    /**
-     * 按深度更新期数
-     * @param int $startDeep
-     */
-    public function actionUpdatePeriod($startDeep=1) {
-        for( $deep=$startDeep;$deep<=515;$deep++ ) {
-            UserNetwork::updateAll(['PERIOD_NUM'=>103], 'TOP_DEEP='.$deep);
-            UserRelation::updateAll(['PERIOD_NUM'=>103], 'TOP_DEEP='.$deep);
-            echo sprintf("更新【期数】数据,当前深度为【%s】成功".PHP_EOL, $deep);
-        }
-    }
-
-    /**
-     * 写入用户信息缓存数据
-     * @param int $startPage
-     */
-    public function actionAddUserInfoCache($startPage=1) {
-        $importForm = new ImportForm();
-        $importForm->clearInfoCache();
-
-        $numCount = UserInfo::find()->where("1=1")->orderBy("ID DESC")->count("ID");
-
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = UserInfo::find()->select(['USER_ID', 'USER_NAME', 'CON_UID', 'REC_UID'])->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                $importForm->cacheUserInfo($pageData['USER_ID'], $pageData);
-                unset($pageData);
-            }
-            unset($pageList);
-
-            echo sprintf("写入用户缓存数据,总页数【%s】,当前页数:【%s】写入成功".PHP_EOL, $pageCount, $page);
-        }
-    }
-
-
-
-    /**
-     * 获取最终父顶点
-     * @param string $userName
-     * @return bool
-     */
-    public function actionFindParent($userName='H15678858') {
-        echo $userName . PHP_EOL;
-//        $circleData = [
-//            'H19546931',
-//            'H52702897',
-//            'H71350536',
-//            'H15116023',
-//        ];
-//        if( in_array($userName, $circleData) ) {
-//            return true;
-//        }
-//        unset($circleData);
-        $data = TmpOldNetwork::find()->select(['NET_USER_NAME'])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$userName])->asArray()->one();
-        if( !$data ) {
-            return true;
-        }
-
-        unset($userName);
-        $this->actionFindParent($data['NET_USER_NAME']);
-
-    }
-
-    public function actionFindRecParent($userName='A14998649') {
-        echo $userName . PHP_EOL;
-
-        $data = TmpOldNetworkAll::find()->select(['PARENT_USER_NAME'])->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$userName])->asArray()->one();
-        if( !$data ) {
-            return true;
-        }
-
-        unset($userName);
-        $this->actionFindRecParent($data['PARENT_USER_NAME']);
-
-    }
-
-    public function actionGetNextUser($page=1) {
-        $hitUserName = 'D17173496';
-        $pageList = TmpOldNetwork::find()->where("1=1")->orderBy("NET_DEEP ASC, REC_DEEP ASC, SORT ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-        $key = 0;
-        $hit = false;
-        foreach ($pageList as $key => $pageData) {
-            if( $pageData['USER_NAME'] === $hitUserName ) {
-                $hit = true;
-                break;
-            }
-        }
-
-        if( $hit ) {
-            echo 'hit' . PHP_EOL;
-            $hitKey = $key+1;
-            if( isset($pageList[$hitKey]) ) {
-                echo sprintf("hit user is %s" . PHP_EOL, $pageList[$hitKey]['USER_NAME']);
-            }else {
-                echo sprintf("hit user is %s first one" . PHP_EOL, $page+1);
-            }
-        }else {
-            echo 'no hit' . PHP_EOL;
-        }
-
-    }
-
-    //超出点位验证
-    public function actionFindNetPoint($startPage=1) {
-        $numCount = TmpOldNetwork::find()->select(["NET_USER_NAME"])->where("1=1")->orderBy("ID DESC")->count("ID");
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = TmpOldNetwork::find()->select(['NET_USER_NAME'])->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                $location = TmpOldNetwork::find()->where('NET_USER_NAME=:NET_USER_NAME', ['NET_USER_NAME'=>$pageData['NET_USER_NAME']])->count();
-
-                $userId = Info::getUserIdByUserName($pageData['NET_USER_NAME']);
-                if($userId){
-                    $location2 = UserInfo::find()->where('CON_UID=:CON_UID', ['CON_UID'=>$userId])->count();
-                }else{
-                    $location2=0;
-                }
-                $points = $location + $location2;
-                if($points>3){
-                    echo sprintf("安置人编号【%s】,点位数:【%s】超出".PHP_EOL, $pageData['NET_USER_NAME'], $points);
-                }
-                unset($pageData,$location,$location2,$points);
-            }
-            unset($pageList);
-
-            echo sprintf("查询安置人点位,总页数【%s】,当前页数:【%s】完成".PHP_EOL, $pageCount, $page);
-        }
-        unset($numCount, $pageCount);
-    }
-
-    //接点人是否存在
-    public function actionFindNetUser($startPage=1) {
-        $numCount = TmpOldNetwork::find()->select(["NET_USER_NAME"])->where("1=1")->orderBy("ID DESC")->count("ID");
-        $pageCount = ceil($numCount/self::LIMIT);
-        $i=0;
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = TmpOldNetwork::find()->select(['NET_USER_NAME'])->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-
-                $jiedian2 = TmpOldNetwork::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['NET_USER_NAME']])->count();
-                if(!$jiedian2){
-                   $one = User::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['NET_USER_NAME']])->asArray()->one();
-                    $i++;
-//                    $deep = $one['NETWORK_DEEP'];
-//                    TmpOldNetwork::updateAll([
-//                        'NET_DEEP' => $deep+1
-//                    ], 'USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['USER_NAME']]);
-                    //echo sprintf("安置人编号【%s】,导入数据中存在".PHP_EOL, $pageData['NET_USER_NAME']);
-                    if(!$one) {
-                        echo sprintf("安置人编号【%s】,系统与导入数据中都不存在" . PHP_EOL, $pageData['NET_USER_NAME'], $one['NETWORK_DEEP']);
-                    }
-                }
-
-                unset($pageData,$location,$location2,$points);
-            }
-            unset($pageList);
-
-            echo sprintf("查询安置人是否存在,总页数【%s】,当前页数:【%s】完成".PHP_EOL, $pageCount, $page);
-        }
-        echo $i;
-        unset($numCount, $pageCount);
-    }
-    //推荐人是否存在
-    public function actionFindRecUser($startPage=1) {
-        $numCount = TmpOldNetwork::find()->select(["PARENT_USER_NAME"])->where("1=1")->orderBy("ID DESC")->count("ID");
-        $pageCount = ceil($numCount/self::LIMIT);
-        $i=0;
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = TmpOldNetwork::find()->select(['PARENT_USER_NAME'])->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-
-                $jiedian2 = TmpOldNetwork::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['PARENT_USER_NAME']])->count();
-                if(!$jiedian2){
-                    $one = User::find()->where('USER_NAME=:USER_NAME', ['USER_NAME'=>$pageData['PARENT_USER_NAME']])->asArray()->one();
-                    $i++;
-                    if(!$one) {
-                        echo sprintf("推荐人编号【%s】,系统与导入数据中都不存在" . PHP_EOL, $pageData['PARENT_USER_NAME']);
-                    }
-                }
-
-                unset($pageData,$location,$location2,$points);
-            }
-            unset($pageList);
-
-            echo sprintf("查询推荐人是否存在,总页数【%s】,当前页数:【%s】完成".PHP_EOL, $pageCount, $page);
-        }
-        echo $i;
-        unset($numCount, $pageCount);
-    }
-
-
-    //导出会员及推荐人、级别信息
-    public function actionGetAllUser($startPage=1) {
-        $numCount = User::find()->where("1=1")->orderBy("ID DESC")->count("ID");
-        $pageCount = ceil($numCount/self::LIMIT);
-        echo sprintf("会员编号,会员姓名,推荐人,手机号,级别,密文密码".PHP_EOL);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-
-            $pageList = User::find()->select(["ID","USER_NAME","PASSWORD_HASH","REAL_NAME","MOBILE","DEC_LV"])->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                //报单级别
-                $decLevel = DeclarationLevel::find()->where('ID=:ID', ['ID'=>$pageData['DEC_LV']])->asArray()->one();
-                $decLvName = $decLevel['LEVEL_NAME']??'';
-                //推荐人
-                $recUser = UserInfo::find()->select(["REC_UID"])->where('USER_ID=:USER_ID', ['USER_ID'=>$pageData['ID']])->asArray()->one();
-                $recName = Info::getUserNameByUserId($recUser['REC_UID']);
-                //输出
-                echo sprintf("【%s】,%s,%s,%s,%s,【%s】".PHP_EOL, $pageData['USER_NAME'], $pageData['REAL_NAME'], $recName, $pageData['MOBILE'], $decLvName, $pageData['PASSWORD_HASH']);
-
-                unset($pageData,$decLevel,$decLvName,$recUser,$recName);
-            }
-            unset($pageList);
-
-            echo sprintf("导出会员信息,总页数【%s】,当前页数:【%s】完成".PHP_EOL, $pageCount, $page);
-        }
-        unset($numCount, $pageCount);
-    }
-
-
-    public function actionPerfMonth($startPage=1) {
-        $numCount = PerfMonth::find()->where("CALC_MONTH='202007'")->orderBy("ID ASC")->count("ID");
-        $pageCount = ceil($numCount/self::LIMIT);
-        echo sprintf("会员编号,个人业绩,月新增团队业绩,月累计团队业绩".PHP_EOL);
-
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-            $pageList = PerfMonth::find()->select('USER_ID,PV_PCS,PV_PSS,PV_PSS_TOTAL')->where("CALC_MONTH='202007'")->orderBy("ID ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-
-            foreach ($pageList as $pageData) {
-                $userName = Info::getUserNameByUserId($pageData['USER_ID']);
-                echo sprintf("%s,%s,%s,%s" . PHP_EOL, $userName, $pageData['PV_PCS'], $pageData['PV_PSS'], $pageData['PV_PSS_TOTAL']);
-                unset($pageData,$userName);
-            }
-            unset($pageList);
-            echo sprintf("导出会员业绩信息,总页数【%s】,当前页数:【%s】完成".PHP_EOL, $pageCount, $page);
-        }
-        unset($numCount, $pageCount);
-    }
-
-    //根据条件判断会员激活状态
-    public function actionEditUserStatus($startPage=1) {
-        $numCount = User::find()->where("1=1")->orderBy("ID DESC")->count("ID");
-        $pageCount = ceil($numCount/self::LIMIT);
-
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-
-            $pageList = User::find()->select(["ID","STATUS","USER_NAME"])->where("1=1")->orderBy("ID DESC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                // 下单金额/推荐人数
-                $orderAmount = Order::find()->where('USER_ID=:USER_ID', [':USER_ID' => $pageData['ID']])->SUM('ORDER_AMOUNT');
-                $orderShopAmount = OrderShop::find()->where('USER_ID=:USER_ID', [':USER_ID' => $pageData['ID']])->SUM('ORDER_AMOUNT');
-                $amount = $orderAmount + $orderShopAmount;
-
-                $recNum = intval(DecOrder::find()->where('REC_USER_ID=:REC_USER_ID', [':REC_USER_ID' => $pageData['ID']])->count());
-
-                if ($amount < 300 && $recNum==0) {
-                    //修改为冻结状态
-                    User::updateAll([
-                        'STATUS' => 0
-                    ], 'ID=:ID', ['ID' => $pageData['ID']]);
-                    echo sprintf("修改会员编号【%s】状态冻结" . PHP_EOL, $pageData['USER_NAME']);
-                }
-
-                unset($pageData,$orderAmount,$orderShopAmount,$amount,$recNum);
-            }
-            unset($pageList);
-
-            echo sprintf("修改会员状态,总页数【%s】,当前页数:【%s】完成".PHP_EOL, $pageCount, $page);
-        }
-
-        unset($numCount, $pageCount);
-    }
-
-    public function actionUsernameUpper($startPage=1) {
-        $numCount = User::find()->where("1=1")->orderBy("ID ASC")->count("ID");
-
-        $i = 0;
-        $j = 0;
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-
-            $pageList = User::find()->where("1=1")->orderBy("ID ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                //含中文会员编号跳过
-                if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $pageData['USER_NAME'], $match)) {
-                    continue;
-                }
-                //会员编号字母转大写
-                $username = strtoupper($pageData['USER_NAME']);
-                if($pageData['USER_NAME']===$username) continue;
-
-                $one = User::find()->where("USER_NAME='".$username."' and ID!='".$pageData['ID']."'")->asArray()->one();
-                if( !$one ) {
-                    User::updateAll(['USER_NAME'=> $username], 'ID=:ID', ['ID'=>$pageData['ID']]);
-                    $j++;
-                    echo sprintf("修改会员编号成功,会员编号: 【%s】,会员ID:【%s】" . PHP_EOL, $username, $pageData['ID']);
-                }else{
-                    $i++;
-                    echo sprintf("会员编号重复,会员编号: 【%s】,会员ID:【%s】" . PHP_EOL, $username, $pageData['ID']);
-                }
-                unset($pageData,$one);
-            }
-            unset($pageList);
-            echo sprintf("修改会员编号,总页数【%s】,当前页数:【%s】完成".PHP_EOL, $pageCount, $page);
-        }
-        echo $i.'=='.$j;
-        unset($numCount, $pageCount);
-    }
-
-    public function actionUserinfoUpper($startPage=1) {
-        $numCount = UserInfo::find()->where("1=1")->orderBy("ID ASC")->count("ID");
-
-        $i = 0;
-        $j = 0;
-        $pageCount = ceil($numCount/self::LIMIT);
-        for ($page=$startPage;$page<=$pageCount;$page++) {
-
-            $pageList = UserInfo::find()->where("1=1")->orderBy("ID ASC")->offset(($page-1)*self::LIMIT)->limit(self::LIMIT)->asArray()->all();
-            foreach ($pageList as $pageData) {
-                //含中文会员编号跳过
-                if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $pageData['USER_NAME'], $match)) {
-                    continue;
-                }
-                //会员编号字母转大写
-                $username = strtoupper($pageData['USER_NAME']);
-                if($pageData['USER_NAME']===$username) continue;
-
-                $one = UserInfo::find()->where("USER_NAME='".$username."' and ID!='".$pageData['ID']."'")->asArray()->one();
-                if( !$one ) {
-                    UserInfo::updateAll(['USER_NAME'=> $username], 'ID=:ID', ['ID'=>$pageData['ID']]);
-                    $j++;
-                    echo sprintf("修改会员编号成功,会员编号: 【%s】,会员ID:【%s】" . PHP_EOL, $username, $pageData['USER_ID']);
-                }else{
-                    $i++;
-                    echo sprintf("会员编号重复,会员编号: 【%s】,会员ID:【%s】" . PHP_EOL, $username, $pageData['USER_ID']);
-                }
-                unset($pageData,$one);
-            }
-            unset($pageList);
-            echo sprintf("修改会员编号,总页数【%s】,当前页数:【%s】完成".PHP_EOL, $pageCount, $page);
-        }
-        echo $i.'=='.$j;
-        unset($numCount, $pageCount);
-    }
-
-
-    /**
-     * 导入积分数据
-     * @param $fileName
-     * @param int $rowCount
-     * @param int $startRow
-     * @throws \Exception
-     */
-    public function actionPointsData($fileName, $rowCount=1000, $startRow=1)
-    {
-        $excel = new Excel();
-        $result = $excel->pageImportDataByExcelFile($fileName, $rowCount, $startRow, self::LIMIT);
-
-        $insertData = [];
-        foreach ($result as $everyData) {
-            if( !$everyData ) continue;
-
-            $oneInsertData = [];
-            foreach ($everyData as $key => $value) {
-                if( !isset(self::EXCEL_TABLE_POINTS_FIELD[$key]) ) continue;
-                
-                $oneInsertData[self::EXCEL_TABLE_POINTS_FIELD[$key]] = $value;
-            }
-
-            $user = Info::getBaseUserByUserName($oneInsertData['USER_NAME']);
-            if ( !$user ) {
-                throw new \Exception(sprintf("用户【%s】不存在", $oneInsertData['USER_NAME']));
-            }
-            $oneInsertData['USER_ID'] = $user['ID'];
-
-            $insertData[] = $oneInsertData;
-            unset($oneInsertData, $everyData);
-        }
-//        var_dump($insertData);die;
-        ImportScore::batchInsert($insertData);
-        unset($insertData);
-
-        echo sprintf("【%s】导入成功".PHP_EOL, $fileName);
-    }
-}

+ 0 - 143
console/controllers/ImportOrderController.php

@@ -1,143 +0,0 @@
-<?php
-namespace console\controllers;
-
-
-use common\helpers\Cache;
-use common\helpers\Excel;
-use common\helpers\snowflake\SnowFake;
-use common\helpers\user\Info;
-use common\models\OrderGoodsShop;
-use common\models\OrderShop;
-use common\models\TmpOldNetwork;
-use common\models\UserInfo;
-
-/**
- * Class ImportOrderController
- * @package console\controllers
- */
-class ImportOrderController extends BaseController
-{
-    const LIMIT = 1000;
-    CONST EXCEL_ORDER_SHOP_FIELD = [
-        '会员编号' => 'USER_NAME',
-//        '报单中心' => 'DEC_USER_NAME',
-//        '订单号' => 'ORDER_SN',
-        '订单状态' => 'STATUS',
-        '收货人' => 'CONSIGNEE',
-        '联系方式1' => 'MOBILE',
-        '省' => 'PROVINCE',
-        '市' => 'CITY',
-        '区' => 'COUNTY',
-        '详细地址' => 'ADDRESS',
-        '期数' => 'PERIOD_NUM',
-//        '订单类型' => 'ORDER_TYPE',
-        '创建时间' => 'CREATED_AT',
-        '支付时间' => 'PAY_AT',
-        '发货时间' => 'DELIVERY_AT',
-        '运费' => 'FREIGHT',
-        '快递公司' => 'EXPRESS_COMPANY',
-        '快递单号' => 'ORDER_TRACK_NO',
-        '发货方式' => 'EXPRESS_TYPE',
-        '会员备注' => 'FRONT_REMARK',
-        '发货仓' => 'WAREHOUSE',
-        '发货状态' => 'DELIVERY_STATUS',
-    ];
-
-    CONST EXCEL_ORDER_SHOP_GOODS_FIELD = [
-        '订单号' => 'ORDER_SN',
-//        '订单状态' => 'STATUS',
-        '存货编码' => 'SKU_CODE',
-        '存货名称' => 'GOODS_TITLE',
-        '数量' => 'BUY_NUMS',
-        '商品单价' => 'PRICE',
-        '商品金额' => 'REAL_PRICE',
-        '商品PV' => 'PV',
-        'PV合计' => 'REAL_PV',
-        '期数' => 'PERIOD_NUM',
-    ];
-
-    public function actionRun($fileName, $rowCount=1000, $startRow=1)
-    {
-        ini_set('memory_limit','512M');
-        $pageCount = ceil($rowCount/self::LIMIT);
-        $excel = new Excel();
-        for($page=1;$page<=$pageCount;$page++) {
-            $newStartRow = $startRow + self::LIMIT * ($page - 1);
-            $result = $excel->pageImportDataByExcelFile($fileName, $rowCount, $newStartRow, self::LIMIT);
-
-            $goodsInsertData = [];
-            foreach ($result as $everyData) {
-                if( !$everyData ) continue;
-
-                $formatOrderData = [];
-                $formatOrderGoodsData = [];
-                foreach ($everyData as $key => $value) {
-                    if(isset(self::EXCEL_ORDER_SHOP_FIELD[$key])) {
-                        $formatOrderData[self::EXCEL_ORDER_SHOP_FIELD[$key]] = $value;
-                    }
-
-                    if(isset(self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key])) {
-                        $formatOrderGoodsData[self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key]] = $value;
-                    }
-                }
-
-                if( !isset($formatOrderGoodsData['ORDER_SN']) ) continue;
-
-                //判断商城订单是表中是否已经存在该订单
-                $one = OrderShop::find()->select(["SN", "ORDER_AMOUNT", "PV", "PAY_AMOUNT", "PAY_PV"])->where('SN=:SN', ['SN'=>$formatOrderGoodsData['ORDER_SN']])->asArray()->one();
-                if( $one ){
-                    OrderShop::updateAllCounters([
-                        'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                        'PV' => $formatOrderGoodsData['REAL_PV'],
-                        'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                        'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
-                    ], 'SN=:SN', [
-                        'SN'=>$formatOrderGoodsData['ORDER_SN']
-                    ]);
-                }else {
-                    $userInfoArr = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $formatOrderData['USER_NAME']], 'USER_ID');
-                    if( !isset($userInfoArr['USER_ID']) || !$userInfoArr['USER_ID'] ) {
-                        echo $formatOrderData['USER_NAME'] . PHP_EOL;
-                        continue;
-                    }
-                    //insertOrderShop
-                    $orderShopInsertData = array_merge($formatOrderData, [
-                        'ID' => SnowFake::instance()->generateId(),
-                        'SN'=> $formatOrderGoodsData['ORDER_SN'],
-                        'USER_ID' => $userInfoArr['USER_ID'],
-                        'ORDER_TYPE' => 'FX',
-                        'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                        'PV' => $formatOrderGoodsData['REAL_PV'],
-                        'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
-                        'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
-                        'PAY_AT' => strtotime($formatOrderData['PAY_AT']),
-                        'DELIVERY_AT' => strtotime($formatOrderData['DELIVERY_AT']),
-                        'CREATED_AT' => strtotime($formatOrderData['CREATED_AT']),
-                        'CREATE_USER' => $formatOrderData['USER_NAME'],
-                        'PAY_TYPE' => 'cash',//@todo
-                        'STATUS' => 1,
-                        'P_CALC_MONTH' => date('Y-m-d', strtotime($formatOrderData['CREATED_AT'])),
-                        'DELIVERY_STATUS' => $formatOrderData['DELIVERY_STATUS'] === '已发货' ? 1 : 0,
-
-                    ]);
-                    OrderShop::insertOne($orderShopInsertData);
-                    unset($orderShopInsertData, $userInfoArr);
-                }
-
-                $goodsInsertData[] = array_merge($formatOrderGoodsData, [
-                    'P_CALC_MONTH' => date('Y-m-d', strtotime($formatOrderData['CREATED_AT']))
-                ]);
-                unset($formatOrderData, $formatOrderGoodsData, $everyData);
-            }
-
-            if( $goodsInsertData ) OrderGoodsShop::batchInsert($goodsInsertData);
-            unset($newStartRow, $goodsInsertData);
-
-            echo sprintf("文件:【%s】页数:【%s】导入成功".PHP_EOL, $fileName, $page);
-        }
-    }
-
-
-
-
-}

+ 0 - 67
console/controllers/ReconsumeController.php

@@ -1,67 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/3/9
- * Time: 上午11:56
- */
-
-namespace console\controllers;
-
-use backendApi\modules\v1\models\lists\finance\RechargeList;
-use common\libs\export\module\ReconsumeExport;
-use Yii;
-
-class ReconsumeController extends BaseController {
-
-//    /**
-//     * 复销池余额列表导出
-//     * @param $taskId
-//     * @return bool
-//     */
-//    public function actionPoolListExport($taskId) {
-//        return $this->_export($taskId, PoolList::class, '复销池余额列表');
-//    }
-//
-//    /**
-//     * 复销余额调整审核列表导出
-//     * @param $taskId
-//     * @return bool
-//     */
-//    public function actionChangeAuditListExport($taskId) {
-//        return $this->_export($taskId, ReconsumeAuditList::class, '复销余额调整审核列表');
-//    }
-//
-//    /**
-//     * 复销流水导出
-//     * @param $taskId
-//     * @return bool
-//     */
-//    public function actionFlowListExport($taskId) {
-//        return $this->_export($taskId, FlowList::class, '复销流水');
-//    }
-
-    /**
-     * 导出方法
-     * @param $taskId
-     * @param $className
-     * @param $listName
-     * @return bool
-     */
-    private function _export($taskId, $className, $listName){
-        $factory = ReconsumeExport::factory($taskId);
-        $factory->listModelClass = $className;
-        try {
-            if ($factory->generate()) {
-                \Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), $listName.'导出成功');
-            }
-            unset($factory, $taskId, $className, $listName);
-            return true;
-        } catch (\Exception $e) {
-            \Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), $listName.'导出失败。详情:' . $e->getMessage(), false);
-        }
-        unset($factory, $taskId, $className, $listName);
-        return false;
-    }
-
-}

+ 0 - 133
console/controllers/ShopController.php

@@ -1,133 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/3/9
- * Time: 上午11:56
- */
-namespace console\controllers;
-
-use backendApi\modules\v1\models\lists\shop\DecOrderList;
-use backendApi\modules\v1\models\lists\shop\GoodsList;
-use backendApi\modules\v1\models\lists\shop\OrderList;
-use common\libs\export\module\ShopExport;
-use Yii;
-
-class ShopController extends BaseController
-{
-
-    /**
-     * 报单列表导出
-     * @param $taskId
-     * @return bool
-     */
-    public function actionDecOrderListExport($taskId){
-        $factory = ShopExport::factory($taskId);
-        $factory->listModelClass = DecOrderList::class;
-        try {
-            if ($factory->generate()) {
-                Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '报单列表导出成功');
-            }
-            unset($factory);
-            return true;
-        } catch (\Exception $e) {
-            echo '报单列表导出失败。详情:' . $e->getMessage();
-            Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '报单列表导出失败。详情:' . $e->getMessage(), false);
-        }
-        unset($factory);
-        return false;
-    }
-
-    /**
-     * 订单列表导出
-     * @param $taskId
-     * @return bool
-     */
-    public function actionOrderListExport($taskId){
-        $factory = ShopExport::factory($taskId);
-        $factory->listModelClass = OrderList::class;
-        try {
-            if ($factory->generateOrderExcel()) {
-                Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '订单列表导出成功');
-            }
-            unset($factory);
-            return true;
-        } catch (\Exception $e) {
-            echo '订单列表导出失败。详情:' . $e->getMessage();
-            Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '订单列表导出失败。详情:' . $e->getMessage(), false);
-        }
-
-        unset($factory);
-        return false;
-    }
-
-    /**
-     * 商品列表导出
-     * @param $taskId
-     * @return bool
-     */
-    public function actionGoodsListExport($taskId){
-        $factory = ShopExport::factory($taskId);
-        $factory->listModelClass = GoodsList::class;
-        try {
-            if ($factory->generate()) {
-                Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '商品列表导出成功');
-            }
-            unset($factory);
-            return true;
-        } catch (\Exception $e) {
-            echo '商品列表导出失败。详情:' . $e->getMessage();
-            Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '商品列表导出失败。详情:' . $e->getMessage(), false);
-        }
-        unset($factory);
-        return false;
-    }
-
-    /**
-     * 订单列表导出PDF
-     * @param $taskId
-     * @return bool
-     */
-    public function actionOrderListExportPdf($taskId)
-    {
-        $factory = ShopExport::factory($taskId);
-        $factory->listModelClass = OrderList::class;
-        try {
-            if ($factory->generateOrderPDF()) {
-                Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '订单列表导出成功');
-            }
-            unset($factory);
-            return true;
-        } catch (\Exception $e) {
-            echo '订单列表导出失败。详情:' . $e->getMessage();
-            Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '订单列表导出失败。详情:' . $e->getMessage(), false);
-        }
-
-        unset($factory);
-        return false;
-    }
-
-    /**
-     * 订单列表导出PDF
-     * @param $taskId
-     * @return bool
-     */
-    public function actionDecOrderListExportPdf($taskId)
-    {
-        $factory = ShopExport::factory($taskId);
-        $factory->listModelClass = OrderList::class;
-        try {
-            if ($factory->generateDecOrderPDF()) {
-                Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '订单列表导出成功');
-            }
-            unset($factory);
-            return true;
-        } catch (\Exception $e) {
-            echo '订单列表导出失败。详情:' . $e->getMessage();
-            Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), '订单列表导出失败。详情:' . $e->getMessage(), false);
-        }
-
-        unset($factory);
-        return false;
-    }
-}