Explorar el Código

Merge branch 'master' of http://16.162.42.175:8014/guanli/ngds into bugfix/transaction-self

theojeng hace 3 años
padre
commit
81517a7f1b
Se han modificado 100 ficheros con 7868 adiciones y 453 borrados
  1. 5 1
      backendApi/config/menu.php
  2. 12 1
      backendApi/config/urlManagerRules.php
  3. 148 97
      backendApi/modules/v1/controllers/BonusController.php
  4. 106 32
      backendApi/modules/v1/controllers/ShopController.php
  5. 4 1
      backendApi/modules/v1/controllers/SiteController.php
  6. 237 93
      backendApi/modules/v1/controllers/UserController.php
  7. 23 0
      backendApi/modules/v1/models/exportForms/BaShopExportForm.php
  8. 24 0
      backendApi/modules/v1/models/exportForms/BaUserExportForm.php
  9. 12 2
      backendApi/modules/v1/models/lists/atlas/NetworkList.php
  10. 12 2
      backendApi/modules/v1/models/lists/atlas/RelationList.php
  11. 2 2
      backendApi/modules/v1/models/lists/bonus/BalanceList.php
  12. 2 2
      backendApi/modules/v1/models/lists/bonus/FlowBonusList.php
  13. 4 3
      backendApi/modules/v1/models/lists/bonus/PeriodBonusList.php
  14. 2 2
      backendApi/modules/v1/models/lists/finance/BalanceAuditList.php
  15. 1 0
      backendApi/modules/v1/models/lists/log/AdminHandleList.php
  16. 362 0
      backendApi/modules/v1/models/lists/shop/BaOrderList.php
  17. 198 0
      backendApi/modules/v1/models/lists/shop/BaUserList.php
  18. 0 0
      backendApi/modules/v1/models/lists/shop/FlowRemainPvList.php
  19. 9 2
      backendApi/modules/v1/models/lists/shop/OrderList.php
  20. 0 0
      backendApi/modules/v1/models/lists/shop/RemainPvList.php
  21. 171 0
      backendApi/modules/v1/models/lists/user/BaUserList.php
  22. 40 12
      backendApi/modules/v1/models/lists/user/IndexList.php
  23. 6 0
      backendEle/src/components/FilterUser.vue
  24. 36 0
      backendEle/src/router/index.js
  25. 3 0
      backendEle/src/utils/baseInfo.js
  26. 1 1
      backendEle/src/utils/config_trial.js
  27. 13 1
      backendEle/src/utils/index.js
  28. 2 1
      backendEle/src/utils/vuexStore.js
  29. 0 0
      backendEle/src/views/article/detail.vue
  30. 1 1
      backendEle/src/views/atlas/network-opt.vue
  31. 1 1
      backendEle/src/views/atlas/relation-opt.vue
  32. 148 0
      backendEle/src/views/bonus/perf-adjustment.vue
  33. 2 39
      backendEle/src/views/config/bonus-opt.vue
  34. 207 0
      backendEle/src/views/shop/ba-dec-order-list.vue
  35. 144 0
      backendEle/src/views/shop/ba-order-list.vue
  36. 0 0
      backendEle/src/views/shop/flow-remain-pv.vue
  37. 0 0
      backendEle/src/views/shop/remain-pv.vue
  38. 345 0
      backendEle/src/views/user/ba-user-list.vue
  39. 1 1
      backendEle/src/views/user/empty-list.vue
  40. 4 4
      backendEle/src/views/user/index.vue
  41. 1 1
      backendEle/src/views/user/user-add-opt.vue
  42. 1 1
      common/helpers/Excel.php
  43. 24 32
      common/helpers/bonus/BonusCalc.php
  44. 31 8
      common/helpers/bonus/BonusSend.php
  45. 1 17
      common/helpers/bonus/PerfCalc.php
  46. 1 1
      common/helpers/user/Balance.php
  47. 85 1
      common/helpers/user/Info.php
  48. 388 9
      common/libs/export/BaseExport.php
  49. 10 0
      common/libs/export/module/BaShopExport.php
  50. 10 0
      common/libs/export/module/BaUserExport.php
  51. 1 1
      common/models/ApproachDecOrder.php
  52. 0 0
      common/models/ApproachOrderCall.php
  53. 97 0
      common/models/BaApproachDecOrder.php
  54. 131 0
      common/models/BaApproachOrder.php
  55. 77 0
      common/models/BaApproachOrderGoods.php
  56. 92 0
      common/models/BaDecOrder.php
  57. 157 0
      common/models/BaOrder.php
  58. 77 0
      common/models/BaOrderGoods.php
  59. 79 0
      common/models/BaReceiveAddress.php
  60. 487 0
      common/models/BaUser.php
  61. 251 0
      common/models/BaUserInfo.php
  62. 0 0
      common/models/CalcBonusQuarter.php
  63. 0 0
      common/models/CalcBonusVilla.php
  64. 0 0
      common/models/FlowRemainPv.php
  65. 0 0
      common/models/FlowVillaPoints.php
  66. 0 0
      common/models/RemainPv.php
  67. 8 0
      common/models/User.php
  68. 10 0
      common/models/UserInfo.php
  69. 16 0
      common/models/UserPerf.php
  70. 6 3
      common/models/Withdraw.php
  71. 1 1
      common/models/forms/AdminAddUserForm.php
  72. 18 17
      common/models/forms/ApproachDeclarationForm.php
  73. 1 0
      common/models/forms/ApproachDeclarationLoopForm.php
  74. 0 0
      common/models/forms/ApproachDeclarationUpgradeForm.php
  75. 52 23
      common/models/forms/ApproachOrderForm.php
  76. 561 0
      common/models/forms/BaApproachDeclarationForm.php
  77. 216 0
      common/models/forms/BaApproachDeclarationLoopForm.php
  78. 522 0
      common/models/forms/BaApproachOrderForm.php
  79. 547 0
      common/models/forms/BaDeclarationForm.php
  80. 191 0
      common/models/forms/BaDeclarationLoopForm.php
  81. 201 0
      common/models/forms/BaReceiveAddressForm.php
  82. 224 0
      common/models/forms/BaUserBasicForm.php
  83. 234 0
      common/models/forms/BaUserForm.php
  84. 21 15
      common/models/forms/DeclarationForm.php
  85. 1 0
      common/models/forms/DeclarationLoopForm.php
  86. 1 1
      common/models/forms/DeclarationUpgradeForm.php
  87. 126 0
      common/models/forms/PerfAdjustmentForm.php
  88. 7 7
      common/models/forms/ReceiveAddressForm.php
  89. 1 1
      common/models/forms/UploadForm.php
  90. 0 0
      common/models/forms/UserBonusForm.php
  91. 9 9
      common/models/forms/UserForm.php
  92. 1 1
      composer.json
  93. 49 0
      console/controllers/ShopController.php
  94. 35 0
      console/controllers/UserController.php
  95. 8 0
      frontendApi/config/main.php
  96. 5 3
      frontendApi/config/menu.php
  97. 63 0
      frontendApi/config/menuBA.php
  98. 24 0
      frontendApi/config/urlManagerRules.php
  99. 399 0
      frontendApi/modules/v1/components/BrandAuth.php
  100. 21 0
      frontendApi/modules/v1/controllers/AtlasController.php

+ 5 - 1
backendApi/config/menu.php

@@ -55,11 +55,13 @@ return [
             ['name'=>'External mall order list', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-shop-list', 'routePath'=>'shop/order-shop-list', 'show'=>1,], // 外部商城订单列表
             ['name'=>'External mall entry list', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-dec-list', 'routePath'=>'shop/order-dec-list', 'show'=>1,], // 外部商城报单列表
             // ['name'=>'List of qualified orders of external mall', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-standard-list', 'routePath'=>'shop/order-standard-list', 'show'=>1,], // 外部商城达标订单列表
+            ['name'=>'Brand Ambassador Order', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'ba-order-list', 'routePath'=>'shop/ba-order-list', 'show'=>1,], // 会员列表
+//            ['name'=>'Brand Ambassador Dec List', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'ba-dec-order-list', 'routePath'=>'shop/ba-dec-order-list', 'show'=>1,], // 会员列表
 
         ]
     ],
     'user'=>[
-        'name'=>'Member management',//会员管理
+        'name'=>'Member management', // 会员管理
         'class' => '',
         'icon'=>'el-icon-user',
         'controller'=>'user',
@@ -68,6 +70,7 @@ return [
         'show'=>1,
         'child'=>[
             ['name'=>'Member list', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'index', 'routePath'=>'user/index', 'show'=>1,],//会员列表
+            ['name'=>'Brand Ambassador List', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'ba-user-list', 'routePath'=>'user/ba-user-list', 'show'=>1,], // 会员列表
             ['name'=>'登录到前台', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'login-to-frontend', 'routePath'=>'user/login-to-frontend', 'show'=>0,],
 //            ['name'=>'指定会员管理登录管理', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'batch-close-login', 'routePath'=>'user/batch-close-login', 'show'=>0,],
 //            ['name'=>'按条件登录管理', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'close-login', 'routePath'=>'user/close-login', 'show'=>0,],
@@ -281,6 +284,7 @@ return [
 //            ['name'=>'Score-month', 'class'=>'', 'icon'=>'', 'controller'=>'bonus', 'action'=>'score-month', 'routePath'=>'bonus/score-month', 'show'=>1,],//月积分
             ['name'=>'月积分导出', 'class'=>'', 'icon'=>'', 'controller'=>'bonus', 'action'=>'score-month-export', 'routePath'=>'bonus/score-month-export', 'show'=>0,],
             ['name'=>'自动提现', 'class'=>'', 'icon'=>'', 'controller'=>'bonus', 'action'=>'auto-withdraw', 'routePath'=>'bonus/auto-withdraw', 'show'=>0,],
+            ['name'=>'Adjust Performance', 'class'=>'', 'icon'=>'', 'controller'=>'bonus', 'action'=>'perf-adjustment', 'routePath'=>'bonus/perf-adjustment', 'show'=>1,],//调整业绩
         ]
     ],
     /*'report'=>[

+ 12 - 1
backendApi/config/urlManagerRules.php

@@ -68,6 +68,9 @@ return [
             'GET dec-order-list-export-pdf/<orderSn>' => 'dec-order-list-export-pdf',
             'GET remain-pv' => 'remain-pv',
             'GET flow-remain-pv' => 'flow-remain-pv',
+            'GET ba-order-list' => 'ba-order-list',
+            'GET ba-order-list-export' => 'ba-order-list-export',
+            'GET ba-order-list-export-pdf/<orderSn>' => 'ba-order-list-export-pdf',
         ],
     ],
     [
@@ -169,6 +172,13 @@ return [
             'GET status-audit-export' => 'status-audit-export',
             'GET year-highest-emp-lv-export' => 'year-highest-emp-lv-export',
             'POST recharge-to-user' => 'recharge-to-user',
+            'GET ba-user-list' => 'ba-user-list',
+            'GET ba-user-list-export' => 'ba-user-list-export',
+            'POST ba-modify-password' => 'ba-modify-password',
+            'GET ba-profile-get' => 'ba-profile-get',
+            'POST ba-modify-profile' => 'ba-modify-profile',
+            'POST ba-modify-status' => 'ba-modify-status',
+            'POST ba-is-modify-password-status' => 'ba-is-modify-password-status',
         ],
     ],
     [
@@ -406,7 +416,8 @@ return [
             'GET yc-perf' => 'yc-perf',
             'GET period-perf' => 'period-perf',
             'GET period-perf-export' => 'period-perf-export',
-            'GET,POST auto-withdraw' => 'auto-withdraw'
+            'GET,POST auto-withdraw' => 'auto-withdraw',
+            'GET,POST perf-adjustment' => 'perf-adjustment',
         ],
     ],
     [

+ 148 - 97
backendApi/modules/v1/controllers/BonusController.php

@@ -47,6 +47,7 @@ use common\helpers\user\Info;
 use common\helpers\user\Perf;
 use common\models\CalcBonus;
 use common\models\CFLXAudit;
+use common\models\forms\PerfAdjustmentForm;
 use common\models\forms\ResendQYForm;
 use common\models\forms\SendCFAndLXForm;
 use common\models\PerfMonth;
@@ -56,6 +57,8 @@ use common\models\ResendQYAudit;
 use common\models\User;
 use common\models\UserInfo;
 use common\models\UserNetwork;
+use common\models\UserPerf;
+use common\models\UserPerfAdjustment;
 use Yii;
 use common\helpers\Form;
 use common\models\Config;
@@ -65,6 +68,7 @@ use common\models\forms\PeriodForm;
 use common\models\forms\UserBonusForm;
 use common\models\Period;
 use Exception;
+use yii\web\HttpException;
 
 class BonusController extends BaseController {
     public $modelClass = FlowBonus::class;
@@ -80,7 +84,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\InvalidConfigException
      * @throws \yii\httpclient\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPeriod() {
         $filter = $this->filterCondition([
@@ -123,7 +127,7 @@ class BonusController extends BaseController {
      * 封期
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionClosePeriod() {
         $periodNum = \Yii::$app->request->get('periodNum');
@@ -142,7 +146,7 @@ class BonusController extends BaseController {
     /**
      * 计算业绩并生成业绩单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfPeriod() {
         $periodNum = \Yii::$app->request->get('periodNum');
@@ -162,7 +166,7 @@ class BonusController extends BaseController {
     /**
      * 结算封期
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCalcPeriod() {
         $periodNum = \Yii::$app->request->get('periodNum');
@@ -182,7 +186,7 @@ class BonusController extends BaseController {
     /**
      * 挂网
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSendPeriod() {
         $periodNum = \Yii::$app->request->get('periodNum');
@@ -202,7 +206,7 @@ class BonusController extends BaseController {
     /**
      * 查看业绩
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerf() {
         // 获取当前年月
@@ -230,7 +234,7 @@ class BonusController extends BaseController {
      * 奖金流水
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowBonus() {
         $filter = $this->filterCondition([
@@ -262,7 +266,7 @@ class BonusController extends BaseController {
      * 奖金流水
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowBonusExport() {
         $filter = $this->filterCondition([
@@ -295,7 +299,7 @@ class BonusController extends BaseController {
      * 复消积分流水
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowRp() {
         $filter = $this->filterCondition([
@@ -322,7 +326,7 @@ class BonusController extends BaseController {
      * 复消积分流水导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowRpExport() {
         $filter = $this->filterCondition([
@@ -351,7 +355,7 @@ class BonusController extends BaseController {
      * 会员余额流水 
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowBalance() {
         $filter = $this->filterCondition([
@@ -376,7 +380,7 @@ class BonusController extends BaseController {
      * 会员余额流水导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowBalanceExport() {
         $filter = $this->filterCondition([
@@ -403,7 +407,7 @@ class BonusController extends BaseController {
      * 兑换积分流水
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowExchange() {
         $filter = $this->filterCondition([
@@ -430,7 +434,7 @@ class BonusController extends BaseController {
      * 兑换积分流水导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowExchangeExport() {
         $filter = $this->filterCondition([
@@ -458,7 +462,7 @@ class BonusController extends BaseController {
      * 现金钱包流水
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowWallet() {
         $filter = $this->filterCondition([
@@ -485,7 +489,7 @@ class BonusController extends BaseController {
      * 现金钱包流水导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowWalletExport() {
         $filter = $this->filterCondition([
@@ -513,7 +517,7 @@ class BonusController extends BaseController {
      * 车房流水
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowCf() {
         $filter = $this->filterCondition([
@@ -541,7 +545,7 @@ class BonusController extends BaseController {
      * 车房养老奖流水导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowCfExport() {
         $filter = $this->filterCondition([
@@ -570,7 +574,7 @@ class BonusController extends BaseController {
      * 领袖分红流水
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowLx() {
         $filter = $this->filterCondition([
@@ -598,7 +602,7 @@ class BonusController extends BaseController {
      * 导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFlowLxExport() {
         $filter = $this->filterCondition([
@@ -627,7 +631,7 @@ class BonusController extends BaseController {
      * 车房养老奖和领袖分红年度发放审核列表
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCfLxAuditList() {
         $filter = $this->filterCondition([
@@ -652,7 +656,7 @@ class BonusController extends BaseController {
      * 车房养老奖和领袖分红年度发放审核导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCfLxAuditExport() {
         $filter = $this->filterCondition([
@@ -678,7 +682,7 @@ class BonusController extends BaseController {
      * 申请发放车房养老奖和领袖分红
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCfLxApply() {
         if (Yii::$app->request->isPost) {
@@ -701,7 +705,7 @@ class BonusController extends BaseController {
      * 审核车房养老奖和领袖分红
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCfLxAudit() {
         $formModel = new SendCFAndLXForm();
@@ -716,7 +720,7 @@ class BonusController extends BaseController {
      * 删除车房领袖审核信息
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCfLxAuditDelete() {
         $sendCFAndLXForm = new SendCFAndLXForm();
@@ -734,7 +738,7 @@ class BonusController extends BaseController {
      * 查看所传期数的各项奖金
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPeriodDetail() {
         $periodNum = \Yii::$app->request->get('periodNum');
@@ -769,7 +773,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionNewPeriodBonus() {
         $periodNum = Period::calculatedMaxPeriodNum();
@@ -781,7 +785,7 @@ class BonusController extends BaseController {
      * 最新一期奖金导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionNewPeriodBonusExport() {
         $filter = $this->filterCondition([
@@ -831,7 +835,7 @@ class BonusController extends BaseController {
      * 获取往期已结算的奖金
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOtherPeriodBonus() {
         $periodNumRequest = \Yii::$app->request->get('periodNum');
@@ -853,7 +857,7 @@ class BonusController extends BaseController {
      * 往期奖金导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOtherPeriodBonusExport() {
         $filter = $this->filterCondition([
@@ -912,7 +916,7 @@ class BonusController extends BaseController {
     /**
      * 获取筛选类型
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOtherPeriodBonusFilterTypes(){
         $listObj = new PeriodBonusList();
@@ -936,6 +940,7 @@ class BonusController extends BaseController {
             'LAST_REAL_NAME' => 'CB.LAST_REAL_NAME',
             'LAST_DEC_LV_NAME' => 'CB.LAST_DEC_LV',
             'LAST_EMP_LV_NAME' => 'CB.LAST_EMP_LV',
+            'LAST_CROWN_LV_NAME' => 'CB.LAST_CROWN_LV',
             'LAST_MOBILE' => 'CB.LAST_MOBILE',
             'LAST_PERIOD_AT' => 'CB.LAST_PERIOD_AT',
             'LAST_CREATED_AT' => 'CB.LAST_CREATED_AT',
@@ -988,7 +993,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownQy() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1040,7 +1045,7 @@ class BonusController extends BaseController {
      * 团队奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownQyExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1071,7 +1076,7 @@ class BonusController extends BaseController {
      * 团队奖向上追溯
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpQy() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1091,7 +1096,7 @@ class BonusController extends BaseController {
      * 团队奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpQyExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1115,7 +1120,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownYc() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1140,7 +1145,7 @@ class BonusController extends BaseController {
      * 荣衔奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownYcExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1165,7 +1170,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownBd() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1190,7 +1195,7 @@ class BonusController extends BaseController {
      * 服务奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownBdExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1216,7 +1221,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownTg() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1241,7 +1246,7 @@ class BonusController extends BaseController {
      * 推广奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownTgExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1266,7 +1271,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownXf() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1291,7 +1296,7 @@ class BonusController extends BaseController {
      * 消费奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownXfExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1316,7 +1321,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownYj() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1341,7 +1346,7 @@ class BonusController extends BaseController {
      * 业绩奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownYjExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1366,7 +1371,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownGx() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1391,7 +1396,7 @@ class BonusController extends BaseController {
      * 共享奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownGxExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1416,7 +1421,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownGl() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1441,7 +1446,7 @@ class BonusController extends BaseController {
      * 管理奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownGlExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1466,7 +1471,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpYc() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1491,7 +1496,7 @@ class BonusController extends BaseController {
      * 荣衔奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpYcExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1517,7 +1522,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpBd() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1542,7 +1547,7 @@ class BonusController extends BaseController {
      * 服务奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpBdExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1567,7 +1572,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpTg() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1592,7 +1597,7 @@ class BonusController extends BaseController {
      * 推广奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpTgExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1617,7 +1622,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpXf() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1642,7 +1647,7 @@ class BonusController extends BaseController {
      * 推广奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpXfExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1667,7 +1672,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpYj() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1692,7 +1697,7 @@ class BonusController extends BaseController {
      * 业绩奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpYjExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1717,7 +1722,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpGx() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1742,7 +1747,7 @@ class BonusController extends BaseController {
      * 共享奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpGxExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1767,7 +1772,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpGl() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1792,7 +1797,7 @@ class BonusController extends BaseController {
      * 管理奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpGlExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1818,7 +1823,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownFx() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1843,7 +1848,7 @@ class BonusController extends BaseController {
      * 复销奖向下追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceDownFxExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1868,7 +1873,7 @@ class BonusController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpFx() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1893,7 +1898,7 @@ class BonusController extends BaseController {
      * 复销奖向上追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceUpFxExport() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1917,7 +1922,7 @@ class BonusController extends BaseController {
      * 核算会员区域津贴
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCalcQy() {
         $periodNum = Yii::$app->request->get('periodNum');
@@ -1945,7 +1950,7 @@ class BonusController extends BaseController {
      * 补发区域津贴列表
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionResendQyList() {
         $filter = $this->filterCondition([
@@ -1987,7 +1992,7 @@ class BonusController extends BaseController {
      * 区域津贴补发列表导出 
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionResendQyListExport() {
         $filter = $this->filterCondition([
@@ -2030,7 +2035,7 @@ class BonusController extends BaseController {
      * 补发区域津贴
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionResendQy() {
         if (Yii::$app->request->isPost) {
@@ -2057,7 +2062,7 @@ class BonusController extends BaseController {
      * 补发审核表
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionResendQyAuditList() {
         $filter = $this->filterCondition([
@@ -2082,7 +2087,7 @@ class BonusController extends BaseController {
      * 补发审核表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionResendQyAuditListExport() {
         $filter = $this->filterCondition([
@@ -2108,7 +2113,7 @@ class BonusController extends BaseController {
      * 审核补发区域津贴
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionResendQyAudit() {
         $formModel = new ResendQYForm();
@@ -2127,7 +2132,7 @@ class BonusController extends BaseController {
      * 删除补发区域津贴审核信息
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionResendQyAuditDelete() {
         $resendQYForm = new ResendQYForm();
@@ -2145,7 +2150,7 @@ class BonusController extends BaseController {
      * 余额列表
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBalanceList() {
         $filter = $this->filterCondition([
@@ -2175,7 +2180,7 @@ class BonusController extends BaseController {
      * 会员奖金余额导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBalanceExport() {
         $filter = $this->filterCondition([
@@ -2202,7 +2207,7 @@ class BonusController extends BaseController {
      * 报单中心店补/补贴追溯
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceBt() {
         $startPeriodNum = Yii::$app->request->get('startPeriodNum');
@@ -2236,7 +2241,7 @@ class BonusController extends BaseController {
      * 报单中心补贴追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceBtExport() {
         $startPeriodNum = Yii::$app->request->get('startPeriodNum');
@@ -2272,7 +2277,7 @@ class BonusController extends BaseController {
      * 报单中心货补追溯
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceFl() {
         $startPeriodNum = Yii::$app->request->get('startPeriodNum');
@@ -2301,7 +2306,7 @@ class BonusController extends BaseController {
      * 报单中心货补追溯导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceFlExport() {
         $startPeriodNum = Yii::$app->request->get('startPeriodNum');
@@ -2332,7 +2337,7 @@ class BonusController extends BaseController {
      * 区域业绩提成追溯
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceFw() {
         $startPeriodNum = Yii::$app->request->get('startPeriodNum');
@@ -2361,7 +2366,7 @@ class BonusController extends BaseController {
      * 区域业绩提成导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTraceFwExport() {
         $startPeriodNum = Yii::$app->request->get('startPeriodNum');
@@ -2392,7 +2397,7 @@ class BonusController extends BaseController {
      * 业绩单
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfOrder(){
         $filter = $this->filterCondition([
@@ -2422,7 +2427,7 @@ class BonusController extends BaseController {
      * 业绩单导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfOrderExport() {
         $filter = $this->filterCondition([
@@ -2466,7 +2471,7 @@ class BonusController extends BaseController {
      * 月积分
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionScoreMonth(){
         $filter = $this->filterCondition([
@@ -2487,7 +2492,7 @@ class BonusController extends BaseController {
      * 月积分导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionScoreMonthExport() {
         $filter = $this->filterCondition([
@@ -2510,7 +2515,7 @@ class BonusController extends BaseController {
      * 月业绩
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfMonth(){
         $filter = $this->filterCondition([
@@ -2532,7 +2537,7 @@ class BonusController extends BaseController {
      * 月业绩导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfMonthExport() {
         $filter = $this->filterCondition([
@@ -2556,7 +2561,7 @@ class BonusController extends BaseController {
      * 期业绩
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfPeriodList(){
         $filter = $this->filterCondition([
@@ -2577,7 +2582,7 @@ class BonusController extends BaseController {
      * 期业绩导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfPeriodListExport() {
         $filter = $this->filterCondition([
@@ -2601,7 +2606,7 @@ class BonusController extends BaseController {
      * 达标业绩
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfStandard(){
         $filter = $this->filterCondition([
@@ -2623,7 +2628,7 @@ class BonusController extends BaseController {
      * 达标业绩导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPerfStandardExport() {
         $filter = $this->filterCondition([
@@ -2647,7 +2652,7 @@ class BonusController extends BaseController {
     /**
      * 会员实时业绩
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRealTimePerf() {
         $userName = Yii::$app->request->get('userName');
@@ -2676,7 +2681,7 @@ class BonusController extends BaseController {
     /**
      * 荣衔业绩
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionYcPerf() {
         $userName = Yii::$app->request->get('userName');
@@ -2738,7 +2743,7 @@ class BonusController extends BaseController {
     /**
      * 用户业绩
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionUserPerf() {
         $filter = $this->filterCondition([
@@ -2756,7 +2761,7 @@ class BonusController extends BaseController {
      * 月业绩导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionUserPerfExport() {
         $filter = $this->filterCondition([
@@ -2791,4 +2796,50 @@ class BonusController extends BaseController {
         }
     }
 
+    /**
+     * 查询安置网下级会员和业绩、修改业绩
+     * @return mixed|void
+     * @throws HttpException
+     * @throws \yii\base\Exception
+     */
+    public function actionPerfAdjustment()
+    {
+        // 查询业绩
+        if (\Yii::$app->request->isGet) {
+            $memberCode = Yii::$app->request->get('memberCode');
+            $userId = Info::getUserIdByUserName(trim($memberCode));
+
+            // 查询传入会员业绩
+            $perfMarket = UserPerf::getPerfMarket($userId);
+            if ($perfMarket) {
+                // 查询传入会员的安置网下级
+                $memberList = UserNetwork::getFirstFloorChildren($userId);
+                $memberList = array_column($memberList, NULL, 'RELATIVE_LOCATION');
+                // 左腿1市场
+                $leftPerfUserName = (isset($memberList[1]) && $memberList[1]['USER_ID']) ? Info::getUserNameByUserId($memberList[1]['USER_ID']) : '';
+                // 右腿2市场
+                $rightPerfUserName = (isset($memberList[2]) && $memberList[1]['USER_ID']) ? Info::getUserNameByUserId($memberList[2]['USER_ID']) : '';
+
+                // 会员编号
+                $perfMarket['USER_NAME'] = $memberCode;
+                $perfMarket['SURPLUS_1L_USER_NAME'] = $leftPerfUserName;
+                $perfMarket['SURPLUS_2L_USER_NAME'] = $rightPerfUserName;
+
+                return static::notice(['allData' => $perfMarket]);
+            }
+
+            return static::notice('No data', 400);
+        } else if (\Yii::$app->request->isPost) {
+            $formModel = new PerfAdjustmentForm();
+            $formModel->scenario = 'perfAdjustment';
+            $post = \Yii::$app->request->post();
+            if ($formModel->load($post, '') && $formModel->perfAdjustment()) {
+                return static::notice('Successful');
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
+            }
+        } else {
+            return static::notice('Illegal request', 400); // 非法请求
+        }
+    }
 }

+ 106 - 32
backendApi/modules/v1/controllers/ShopController.php

@@ -8,26 +8,23 @@
 
 namespace backendApi\modules\v1\controllers;
 
-use backendApi\modules\v1\models\exportForms\OrderExportForm;
+use backendApi\modules\v1\models\exportForms\BaShopExportForm;
 use backendApi\modules\v1\models\exportForms\ShopExportForm;
 use backendApi\modules\v1\models\lists\shop\DecOrderList;
 use backendApi\modules\v1\models\lists\shop\GoodsList;
 use backendApi\modules\v1\models\lists\shop\OrderDecList;
 use backendApi\modules\v1\models\lists\shop\OrderList;
+use backendApi\modules\v1\models\lists\shop\BaOrderList;
 use backendApi\modules\v1\models\lists\shop\OrderShopList;
 use backendApi\modules\v1\models\lists\shop\OrderStandardList;
 use backendApi\modules\v1\models\lists\shop\PackageList;
 use backendApi\modules\v1\models\lists\shop\RemainPvList;
 use backendApi\modules\v1\models\lists\shop\FlowRemainPvList;
 use common\helpers\Cache;
-use common\helpers\Date;
 use common\helpers\Form;
-use common\helpers\Log;
-use common\helpers\snowflake\SnowFake;
-use common\libs\export\module\ShopExport;
 use common\models\DeclarationPackage;
 use common\models\DecOrder;
-use common\models\ExcelOrderShop;
+use common\models\forms\BaOrderDeleteForm;
 use common\models\forms\DecPackageForm;
 use common\models\forms\ExcelOrderDecForm;
 use common\models\forms\ExcelOrderShopForm;
@@ -37,6 +34,7 @@ use common\models\forms\OrderForm;
 use common\models\forms\ShopGoodsForm;
 use common\models\forms\UploadForm;
 use common\models\ShopGoods;
+use yii\web\HttpException;
 use yii\web\UploadedFile;
 use yii\base\Exception;
 
@@ -53,7 +51,7 @@ class ShopController extends BaseController {
      * 商品列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIndex() {
         $filter = $this->filterCondition([
@@ -79,7 +77,7 @@ class ShopController extends BaseController {
      * 商品列表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGoodsListExport()
     {
@@ -106,7 +104,7 @@ class ShopController extends BaseController {
      * 添加商品
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGoodsAdd() {
         if (\Yii::$app->request->isPost) {
@@ -130,7 +128,7 @@ class ShopController extends BaseController {
      * 编辑商品
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGoodsEdit() {
         $id = \Yii::$app->request->get('id');
@@ -166,7 +164,7 @@ class ShopController extends BaseController {
      * @return mixed
      * @throws \yii\base\Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionUpload(){
         if(\Yii::$app->request->isPost){
@@ -210,7 +208,7 @@ class ShopController extends BaseController {
      * 删除商品
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGoodsDelete(){
         $result = static::delete(ShopGoods::class);
@@ -221,7 +219,7 @@ class ShopController extends BaseController {
      * 套餐列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPackage() {
         $filter = $this->filterCondition([
@@ -243,7 +241,7 @@ class ShopController extends BaseController {
     /**
      * 添加报单套餐
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPackageAdd() {
         if (\Yii::$app->request->isPost) {
@@ -257,7 +255,7 @@ class ShopController extends BaseController {
     /**
      * 报单套餐获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPackageGet() {
         $id = \Yii::$app->request->get('id');
@@ -293,7 +291,7 @@ class ShopController extends BaseController {
      * 删除套餐
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPackageDelete(){
         $result = static::delete(DeclarationPackage::class);
@@ -305,7 +303,7 @@ class ShopController extends BaseController {
      * 报单表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionDecOrderList() {
         $filter = $this->filterCondition([
@@ -337,7 +335,7 @@ class ShopController extends BaseController {
      * 报单表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionDecOrderListExport()
     {
@@ -378,7 +376,7 @@ class ShopController extends BaseController {
      * 订单表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderList() {
         $filter = $this->filterCondition([
@@ -403,7 +401,7 @@ class ShopController extends BaseController {
      * 订单表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderListExport()
     {
@@ -417,7 +415,7 @@ class ShopController extends BaseController {
             'STATUS' => 'O.STATUS',
             'IS_AUTO' => 'O.IS_AUTO'
         ]);
-        $filter['condition'] = !$filter['condition'] ? '1=1 AND O.IS_DELETE=0' : ('O.IS_DELETE=0 ' . $filter['condition']);
+        $filter['condition'] = !$filter['condition'] ? ' AND O.IS_DELETE=0' : ('O.IS_DELETE=0 ' . $filter['condition']);
         $form = new ShopExportForm();
         $result = $form->run($filter, 'Order_List'); // 订单列表
         if (!$result) {
@@ -430,7 +428,7 @@ class ShopController extends BaseController {
      * 外部商城订单列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderShopList() {
         $filter = $this->filterCondition([
@@ -451,7 +449,7 @@ class ShopController extends BaseController {
      * 外部商城报单列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderDecList() {
         $filter = $this->filterCondition([
@@ -509,7 +507,7 @@ class ShopController extends BaseController {
     /**
      * 导入完成标记
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportOrderShop() {
         //$periodNum = \Yii::$app->request->post('periodNum');
@@ -565,7 +563,7 @@ class ShopController extends BaseController {
     /**
      * 报单订单导入完成标记
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportOrderDec() {
         //$periodNum = \Yii::$app->request->post('periodNum');
@@ -584,7 +582,7 @@ class ShopController extends BaseController {
      * 见习达标订单列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderStandardList() {
         $filter = $this->filterCondition([
@@ -604,7 +602,7 @@ class ShopController extends BaseController {
     /**
      * 分页导入excel文件到待导入数据的表中
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportOrderStandardToExcelTable()
     {
@@ -645,7 +643,7 @@ class ShopController extends BaseController {
     /**
      * 达标订单导入完成标记
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportOrderStandard() {
         $orderMonth = \Yii::$app->request->post('orderMonth');
@@ -661,7 +659,7 @@ class ShopController extends BaseController {
     /**
      * 管理员发货
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderDelivery() {
         if(\Yii::$app->request->isPost) {
@@ -674,7 +672,7 @@ class ShopController extends BaseController {
      * 报单表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderListExportPdf()
     {
@@ -703,7 +701,7 @@ class ShopController extends BaseController {
      * 报单表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionDecOrderListExportPdf()
     {
@@ -731,7 +729,7 @@ class ShopController extends BaseController {
     /**
      * 管理员订单退款
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderRefund()
     {
@@ -772,4 +770,80 @@ class ShopController extends BaseController {
         $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
         return static::notice($data);
     }
+
+    /**
+     * BA订单表
+     * @return mixed
+     * @throws Exception
+     * @throws HttpException
+     */
+    public function actionBaOrderList() {
+        $filter = $this->filterCondition([
+            'SN'=> 'O.SN',
+            'USER_NAME'=> 'U.USER_NAME',
+            'MOBILE'=> 'O.MOBILE',
+            'PERIOD_NUM'=> 'O.PERIOD_NUM',
+            'CREATED_AT'=> 'O.CREATED_AT',
+            'ORDER_TYPE'=> 'O.ORDER_TYPE',
+            'STATUS' => 'O.STATUS',
+        ]);
+        $condition = ' 1=1 ' . $filter['condition'];
+        $params = $filter['params'];
+        $condition .= $condition ? ' AND O.IS_DELETE=0' : ' O.IS_DELETE=0';
+        $listObj = new BaOrderList();
+        $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
+        return static::notice($data);
+    }
+
+    /**
+     * BA订单表导出
+     * @return mixed
+     * @throws \yii\db\Exception
+     * @throws HttpException
+     */
+    public function actionBaOrderListExport()
+    {
+        $filter = $this->filterCondition([
+            'SN'=> 'O.SN',
+            'USER_NAME'=> 'U.USER_NAME',
+            'MOBILE'=> 'O.MOBILE',
+            'PERIOD_NUM'=> 'O.PERIOD_NUM',
+            'CREATED_AT'=> 'O.CREATED_AT',
+            'STATUS' => 'O.STATUS',
+        ]);
+        $filter['condition'] = !$filter['condition'] ? '1=1 AND O.IS_DELETE=0' : ('O.IS_DELETE=0 ' . $filter['condition']);
+        $form = new BaShopExportForm();
+        $result = $form->run($filter, 'Ba_Order_List'); // 订单列表
+        if (!$result) {
+            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+        }
+        return static::notice('Starting exporting, please go to File Management - Export Files to view.'); // 导出开始,请到文件管理-导出文件查看
+    }
+
+    /**
+     * 报单表导出
+     * @return mixed
+     * @throws \yii\db\Exception
+     * @throws HttpException
+     */
+    public function actionBaOrderListExportPdf()
+    {
+        $orderSn = \Yii::$app->request->get('orderSn');
+        $filter = $this->filterCondition([
+            'SN'=> 'O.SN',
+            'USER_NAME'=> 'U.USER_NAME',
+            'MOBILE'=> 'O.MOBILE',
+            'PERIOD_NUM'=> 'O.PERIOD_NUM',
+            'CREATED_AT'=> 'O.CREATED_AT',
+        ]);
+
+        $filter['condition'] = ' O.IS_DELETE=0 AND O.SN=:SN';
+        $filter['params'] = [':SN' => $orderSn];
+        $form = new BaShopExportForm();
+        $result = $form->run($filter, 'Brand Ambassador Order');
+        if (!$result) {
+            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+        }
+        return static::notice('Starting exporting, please go to File Management - Export Files to view.'); // 导出开始,请到文件管理-导出文件查看
+    }
 }

+ 4 - 1
backendApi/modules/v1/controllers/SiteController.php

@@ -67,8 +67,10 @@ class SiteController extends BaseController
     public function actionBaseInfo(){
         // 会员级别
         $decLevels = Cache::getDecLevelConfig();
-        // 
+        // 管理星
         $empLevels = Cache::getEmpLevelConfig();
+        // 皇冠星级
+        $crownLevels = Cache::getStarCrownLevelConfig();
         // 注册类型
         $regTypes = RegType::getTypes();
         // 类型
@@ -104,6 +106,7 @@ class SiteController extends BaseController
         return [
             'decLevels' => $decLevels,
             'empLevels' => $empLevels,
+            'crownLevels' => $crownLevels,
             'regTypes' => $regTypes,
             'dealTypes' => $dealTypes,
             'systems' => $systems,

+ 237 - 93
backendApi/modules/v1/controllers/UserController.php

@@ -10,7 +10,9 @@ namespace backendApi\modules\v1\controllers;
 
 use backendApi\modules\v1\components\UserAuth;
 use backendApi\modules\v1\models\Admin;
+use backendApi\modules\v1\models\exportForms\BaUserExportForm;
 use backendApi\modules\v1\models\exportForms\UserExportForm;
+use backendApi\modules\v1\models\lists\shop\BaUserList;
 use backendApi\modules\v1\models\lists\user\BindList;
 use backendApi\modules\v1\models\lists\user\DecLevelList;
 use backendApi\modules\v1\models\lists\user\GroupList;
@@ -29,9 +31,11 @@ use common\helpers\user\Balance;
 use common\helpers\user\Cash;
 use common\helpers\user\Info;
 use common\helpers\user\Status;
+use common\models\BaUser;
 use common\models\CompanyBank;
 use common\models\FlowBonus;
 use common\models\forms\AdminAddUserForm;
+use common\models\forms\BaUserBasicForm;
 use common\models\forms\ChangeShowEmpLvForm;
 use common\models\forms\CloseDecForm;
 use common\models\forms\CloseLoginForm;
@@ -77,6 +81,7 @@ use common\models\User;
 use common\models\UserInfo;
 use common\models\UserTeamwork;
 use yii\base\Exception;
+use yii\web\HttpException;
 use yii\web\UploadedFile;
 
 class UserController extends BaseController
@@ -94,7 +99,7 @@ class UserController extends BaseController
      * 会员列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIndex()
     {
@@ -109,8 +114,9 @@ class UserController extends BaseController
             'DEC_LV_UPDATED_AT' => 'U.DEC_LV_UPDATED_AT',
             'LAST_DEC_LV_NAME' => 'U.LAST_DEC_LV',
             'EMP_LV_NAME' => 'U.EMP_LV',
-//            'HIGHEST_EMP_LV_NAME' => 'UI.HIGHEST_EMP_LV',
-//            'HIGHEST_EMP_LV_PERIOD' => 'UI.HIGHEST_EMP_LV_PERIOD',
+            'LAST_EMP_LV_NAME' => 'U.LAST_EMP_LV',
+            'CROWN_LV_NAME' => 'U.CROWN_LV',
+            'LAST_CROWN_LV_NAME' => 'U.LAST_CROWN_LV',
             'REC_USER_NAME' => 'RU.USER_NAME',
             'CON_USER_NAME' => 'CU.USER_NAME',
             'ID_CARD' => 'U.ID_CARD',
@@ -157,7 +163,7 @@ class UserController extends BaseController
      * 导出会员列表
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIndexExport()
     {
@@ -214,7 +220,7 @@ class UserController extends BaseController
      * 空单会员列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionEmptyList()
     {
@@ -276,7 +282,7 @@ class UserController extends BaseController
      * 点位绑定
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBind()
     {
@@ -301,7 +307,7 @@ class UserController extends BaseController
      * 点位绑定导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBindExport()
     {
@@ -326,7 +332,7 @@ class UserController extends BaseController
     /**
      * 添加点位绑定
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBindAdd()
     {
@@ -341,7 +347,7 @@ class UserController extends BaseController
      * 编辑点位绑定
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBindEdit()
     {
@@ -365,7 +371,7 @@ class UserController extends BaseController
      * 删除点位绑定
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBindDelete()
     {
@@ -382,7 +388,7 @@ class UserController extends BaseController
      * 生成点位合作的用户名
      * @return mixed
      * @throws \yii\base\InvalidConfigException
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGenerateUserName()
     {
@@ -397,7 +403,7 @@ class UserController extends BaseController
      * 点位合作
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamwork()
     {
@@ -425,7 +431,7 @@ class UserController extends BaseController
      * 点位合作导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamworkExport()
     {
@@ -453,7 +459,7 @@ class UserController extends BaseController
     /**
      * 添加点位合作
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamworkAdd()
     {
@@ -473,7 +479,7 @@ class UserController extends BaseController
      * 编辑点位合作
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamworkEdit()
     {
@@ -504,7 +510,7 @@ class UserController extends BaseController
      * 删除方法
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamworkDelete()
     {
@@ -520,7 +526,7 @@ class UserController extends BaseController
      * 会员体系
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystem()
     {
@@ -547,7 +553,7 @@ class UserController extends BaseController
      * 体系管理导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystemExport()
     {
@@ -577,7 +583,7 @@ class UserController extends BaseController
      * @throws \yii\base\InvalidConfigException
      * @throws \yii\db\Exception
      * @throws \yii\httpclient\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystemAdd()
     {
@@ -598,7 +604,7 @@ class UserController extends BaseController
      * @return mixed
      * @throws \yii\base\InvalidConfigException
      * @throws \yii\httpclient\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystemEdit()
     {
@@ -617,7 +623,7 @@ class UserController extends BaseController
     /**
      * 恢复体系
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystemRenew()
     {
@@ -632,7 +638,7 @@ class UserController extends BaseController
      * 删除方法
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystemDelete()
     {
@@ -649,7 +655,7 @@ class UserController extends BaseController
      * 团队领导人列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGroup()
     {
@@ -668,7 +674,7 @@ class UserController extends BaseController
      * 团队领导人列表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGroupExport()
     {
@@ -688,7 +694,7 @@ class UserController extends BaseController
      * 会员移网记录
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMove()
     {
@@ -723,7 +729,7 @@ class UserController extends BaseController
      * 移网管理导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveExport()
     {
@@ -757,7 +763,7 @@ class UserController extends BaseController
      * @return mixed
      * @throws \yii\base\InvalidConfigException
      * @throws \yii\httpclient\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveAdd()
     {
@@ -772,7 +778,7 @@ class UserController extends BaseController
     /**
      * 获取全部移网类型
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveNetType()
     {
@@ -783,7 +789,7 @@ class UserController extends BaseController
      * 获取移网数据
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveGet()
     {
@@ -801,7 +807,7 @@ class UserController extends BaseController
      * 修改移网数据
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveEdit()
     {
@@ -819,7 +825,7 @@ class UserController extends BaseController
      * 审核通过移网数据(实际的移网动作在这里,异步操作)
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMovePass()
     {
@@ -839,7 +845,7 @@ class UserController extends BaseController
      * @throws \yii\base\InvalidConfigException
      * @throws \yii\db\Exception
      * @throws \yii\httpclient\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveAudit()
     {
@@ -856,7 +862,7 @@ class UserController extends BaseController
      * 删除移网数据
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveDelete()
     {
@@ -872,7 +878,7 @@ class UserController extends BaseController
     /**
      * 会员的基础用户信息
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFullInfo()
     {
@@ -897,7 +903,7 @@ class UserController extends BaseController
     /**
      * 会员的基本信息编号名称
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBaseInfo()
     {
@@ -909,7 +915,7 @@ class UserController extends BaseController
     /**
      * 点位合作主点位分成比例
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMainDivide()
     {
@@ -924,7 +930,7 @@ class UserController extends BaseController
     /**
      * 获取子公司
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGetSubCom()
     {
@@ -936,7 +942,7 @@ class UserController extends BaseController
     /**
      * 判断是否在同一推荐网络
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChkRelation()
     {
@@ -956,7 +962,7 @@ class UserController extends BaseController
     /**
      * 获取当前期数
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGetPeriodNum()
     {
@@ -976,7 +982,7 @@ class UserController extends BaseController
     /**
      * 关停列表
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
 //    public function actionClose()
 //    {
@@ -1009,7 +1015,7 @@ class UserController extends BaseController
     /**
      * 申请关停或停发
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
 //    public function actionCloseAdd()
 //    {
@@ -1040,7 +1046,7 @@ class UserController extends BaseController
      * 审核关停或停发
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
 //    public function actionCloseAudit()
 //    {
@@ -1066,7 +1072,7 @@ class UserController extends BaseController
     /**
      * 添加会员
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionUserAdd()
     {
@@ -1090,7 +1096,7 @@ class UserController extends BaseController
     /**
      * 分页导入excel文件到待导入数据的表中
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportUsersToExcelTable()
     {
@@ -1132,7 +1138,7 @@ class UserController extends BaseController
     /**
      * 个人资料获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionProfileGet() {
         $id = Yii::$app->request->get('id');
@@ -1181,7 +1187,7 @@ class UserController extends BaseController
     /**
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsModifyPasswordStatus() {
         $form = new UserBasicForm();
@@ -1196,7 +1202,7 @@ class UserController extends BaseController
     /**
      * 分页把待导入表中的数据导入到真正的数据中
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportUsersAdd()
     {
@@ -1226,7 +1232,7 @@ class UserController extends BaseController
     /**
      * 判断是否满足删除条件
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChkDelUser()
     {
@@ -1276,7 +1282,7 @@ class UserController extends BaseController
      * 删除空单会员
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionUserDel()
     {
@@ -1294,7 +1300,7 @@ class UserController extends BaseController
     /**
      * 复销列表
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionReConsumeList()
     {
@@ -1329,7 +1335,7 @@ class UserController extends BaseController
      *      'CREATED_AT' => '>=,2018-11-10,date'
      * ]
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFilterUser()
     {
@@ -1405,7 +1411,7 @@ class UserController extends BaseController
      * 会员级别变动记录
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionDecLevelList()
     {
@@ -1424,7 +1430,7 @@ class UserController extends BaseController
     /**
      * 调整会员级别报单级别
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChangeUserDecLevel()
     {
@@ -1441,7 +1447,7 @@ class UserController extends BaseController
     /**
      * 调整会员级别报单级别
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChangeUserDecRole()
     {
@@ -1458,7 +1464,7 @@ class UserController extends BaseController
     /**
      * 修改会员前台显示聘级
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChangeShowEmpLevel()
     {
@@ -1476,7 +1482,7 @@ class UserController extends BaseController
      * 注册信息管理
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfo()
     {
@@ -1502,7 +1508,7 @@ class UserController extends BaseController
     /**
      * 注册信息管理中提交修改注册信息
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoEdit()
     {
@@ -1520,7 +1526,7 @@ class UserController extends BaseController
      * 会员注册信息审核
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAudit()
     {
@@ -1552,7 +1558,7 @@ class UserController extends BaseController
     /**
      * 会员注册信息添加
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditAdd()
     {
@@ -1567,7 +1573,7 @@ class UserController extends BaseController
     /**
      * 会员注册信息添加获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditAddOpt()
     {
@@ -1579,7 +1585,7 @@ class UserController extends BaseController
      * 会员注册信息获取
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditGet()
     {
@@ -1601,7 +1607,7 @@ class UserController extends BaseController
      * 会员注册信息修改
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditEdit()
     {
@@ -1619,7 +1625,7 @@ class UserController extends BaseController
      * 会员注册信息审核
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditAudit()
     {
@@ -1636,7 +1642,7 @@ class UserController extends BaseController
     /**
      * 分页导入excel文件到待导入数据的表中
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportRegInfoToExcelTable()
     {
@@ -1669,7 +1675,7 @@ class UserController extends BaseController
      * 分页把待导入表中的数据导入到真正的数据中
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportRegInfo()
     {
@@ -1695,7 +1701,7 @@ class UserController extends BaseController
      * 会员注册信息删除
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditDelete()
     {
@@ -1709,7 +1715,7 @@ class UserController extends BaseController
     /**
      * 禁止登录
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseLogin()
     {
@@ -1727,7 +1733,7 @@ class UserController extends BaseController
     /**
      * 禁止登陆类型获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseLoginGet()
     {
@@ -1737,7 +1743,7 @@ class UserController extends BaseController
     /**
      * 关闭地区登录
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseAreaLogin()
     {
@@ -1758,7 +1764,7 @@ class UserController extends BaseController
     /**
      * 批量登录管理
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBatchCloseLogin()
     {
@@ -1782,7 +1788,7 @@ class UserController extends BaseController
     /**
      * 关闭报单信息获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseDecGet()
     {
@@ -1792,7 +1798,7 @@ class UserController extends BaseController
     /**
      * 关闭报单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseDec()
     {
@@ -1809,7 +1815,7 @@ class UserController extends BaseController
     /**
      * 批量关闭报单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBatchCloseDec()
     {
@@ -1832,7 +1838,7 @@ class UserController extends BaseController
     /**
      * 按地区关闭报单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseAreaDec()
     {
@@ -1853,7 +1859,7 @@ class UserController extends BaseController
      * 会员状态管理
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
 //    public function actionStatusAuditList()
 //    {
@@ -1885,7 +1891,7 @@ class UserController extends BaseController
      * 会员状态管理导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditExport()
     {
@@ -1917,7 +1923,7 @@ class UserController extends BaseController
     /**
      * 申请修改会员状态
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditAdd()
     {
@@ -1933,7 +1939,7 @@ class UserController extends BaseController
     /**
      * 获取全部移网类型
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditGetStatuses()
     {
@@ -1945,7 +1951,7 @@ class UserController extends BaseController
      * 获取会员状态数据
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditGet()
     {
@@ -1973,7 +1979,7 @@ class UserController extends BaseController
      * @return mixed
      * @throws Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAudit()
     {
@@ -1991,7 +1997,7 @@ class UserController extends BaseController
      * 删除审核修改会员状态
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditDelete()
     {
@@ -2009,7 +2015,7 @@ class UserController extends BaseController
     /**
      * 设置是否运作
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsOperating()
     {
@@ -2030,7 +2036,7 @@ class UserController extends BaseController
     /**
      * 团队领导人
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsGroup()
     {
@@ -2051,7 +2057,7 @@ class UserController extends BaseController
     /**
      * 报单中心
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsDec()
     {
@@ -2063,7 +2069,7 @@ class UserController extends BaseController
     /**
      * 工作室
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsStudio()
     {
@@ -2075,7 +2081,7 @@ class UserController extends BaseController
     /**
      * 网络图谱
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsAtlas()
     {
@@ -2087,7 +2093,7 @@ class UserController extends BaseController
     /**
      * 会员充值管理显隐设置
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsRecharge()
     {
@@ -2099,7 +2105,7 @@ class UserController extends BaseController
     /**
      * 获取企业银行信息
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCompanyBankGet()
     {
@@ -2120,7 +2126,7 @@ class UserController extends BaseController
     /**
      * 调整会员转账/提现比例
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChangeTransferProp()
     {
@@ -2149,7 +2155,7 @@ class UserController extends BaseController
      * @return mixed
      * @throws Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionClearWallet()
     {
@@ -2172,7 +2178,7 @@ class UserController extends BaseController
      * 会员历史年度最高聘级表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionYearHighestEmpLv()
     {
@@ -2193,7 +2199,7 @@ class UserController extends BaseController
      * 会员历史年度最高聘级表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionYearHighestEmpLvExport()
     {
@@ -2215,7 +2221,7 @@ class UserController extends BaseController
      * 会员现金充值
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRechargeToUser()
     {
@@ -2226,4 +2232,142 @@ class UserController extends BaseController
         }
         return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
     }
+
+    /**
+     * 会员修改密码
+     * @return mixed
+     * @throws HttpException
+     */
+    public function actionBaModifyPassword()
+    {
+        $form = new BaUserBasicForm();
+        $form->scenario = 'modifyPassword';
+        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->edit()){
+            return static::notice('Password modified successfully'); // 密码修改成功
+        } else {
+            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+        }
+    }
+
+    /**
+     * 个人资料获取
+     * @return mixed
+     * @throws HttpException
+     */
+    public function actionBaProfileGet() {
+        $id = Yii::$app->request->get('id');
+        $userInfo = BaUser::findOneAsArray('ID=:ID', [':ID' => $id]);
+        if (!$userInfo) {
+            return static::notice('Data does not exist', 400);//数据不存在
+        }
+        $data['userInfo'] = [
+            'userId' => $userInfo['ID'],
+            'realName' => $userInfo['REAL_NAME'],
+            'mobile' => $userInfo['MOBILE'],
+        ];
+
+        return static::notice($data);
+    }
+
+    public function actionBaModifyProfile() {
+        $form = new BaUserBasicForm();
+        $form->scenario = 'modifyProfile';
+        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->modifyProfile()){
+            return static::notice('Personal data modified successfully');//个人资料修改成功
+        } else {
+            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+        }
+    }
+
+    public function actionBaModifyStatus() {
+        $form = new BaUserBasicForm();
+        $form->scenario = 'modifyStatus';
+        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->modifyStatus()){
+            return static::notice('Member status modified successfully');//会员状态修改成功
+        } else {
+            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+        }
+    }
+
+    /**
+     * @return mixed
+     * @throws \yii\db\Exception
+     * @throws HttpException
+     */
+    public function actionBaIsModifyPasswordStatus() {
+        $form = new BaUserBasicForm();
+        $form->scenario = 'isModifyPasswordStatus';
+        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->isModifyPasswordStatus()){
+            return static::notice('Status modified successfully');//状态修改成功
+        } else {
+            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+        }
+    }
+
+    /**
+     * BA会员列表
+     * @return mixed
+     * @throws Exception
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaUserList() {
+        $filter = $this->filterCondition([
+            'USER_NAME' => 'U.USER_NAME',
+            'REAL_NAME' => 'U.REAL_NAME',
+            'STATUS' => 'U.STATUS',
+            'ALLOW_LOGIN' => 'U.ALLOW_LOGIN',
+            'CREATED_AT' => 'U.CREATED_AT',
+            'PERIOD_AT' => 'U.PERIOD_AT',
+            'SPOUSE_NAME' => 'U.SPOUSE_NAME',
+            'MOBILE' => 'U.MOBILE',
+            'TEL' => 'U.TEL',
+            'SEX' => 'U.SEX',
+            'AREA' => [
+                'FIELD' => ['U.PROVINCE', 'U.CITY', 'U.COUNTY'],
+                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
+            ],
+            'ADDRESS' => 'U.ADDRESS',
+            'ALLOW_TRANSFER' => 'UI.ALLOW_TRANSFER',
+        ]);
+        $condition = $filter['condition'];
+        $params = $filter['params'];
+        $condition .= ' AND UI.DELETED=0 ';
+        $listObj = new BaUserList();
+        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
+        return static::notice($data);
+    }
+
+    /**
+     * @throws \yii\db\Exception
+     * @throws HttpException
+     */
+    public function actionBaUserListExport() {
+        $filter = $this->filterCondition([
+            'USER_NAME' => 'U.USER_NAME',
+            'REAL_NAME' => 'U.REAL_NAME',
+            'STATUS' => 'U.STATUS',
+            'ALLOW_LOGIN' => 'U.ALLOW_LOGIN',
+            'CREATED_AT' => 'U.CREATED_AT',
+            'PERIOD_AT' => 'U.PERIOD_AT',
+            'REC_USER_NAME' => 'RU.USER_NAME',
+            'CON_USER_NAME' => 'CU.USER_NAME',
+            'SPOUSE_NAME' => 'U.SPOUSE_NAME',
+            'SYSTEM_NAME' => 'U.SYSTEM_ID',
+            'MOBILE' => 'U.MOBILE',
+            'TEL' => 'U.TEL',
+            'SEX' => 'U.SEX',
+            'AREA' => [
+                'FIELD' => ['U.PROVINCE', 'U.CITY', 'U.COUNTY'],
+                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
+            ],
+            'ADDRESS' => 'U.ADDRESS',
+            'ALLOW_TRANSFER' => 'UI.ALLOW_TRANSFER',
+        ]);
+        $form = new BaUserExportForm();
+        $result = $form->run($filter, 'Brand_Ambassador_List');
+        if (!$result) {
+            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+        }
+        return static::notice('Starting exporting, please go to File Management - Export Files to view.'); // 导出开始,请到文件管理-导出文件查看
+    }
 }

+ 23 - 0
backendApi/modules/v1/models/exportForms/BaShopExportForm.php

@@ -0,0 +1,23 @@
+<?php
+namespace backendApi\modules\v1\models\exportForms;
+
+use common\libs\export\module\BaShopExport;
+use yii\db\Exception;
+
+class BaShopExportForm extends BaseExportForm
+{
+    /**
+     * 导出
+     * @param $filter
+     * @param $listName
+     * @param null $consoleRouter
+     * @return bool
+     * @throws Exception
+     */
+    public function run($filter, $listName, $consoleRouter = null){
+        $this->exportObj = BaShopExport::instance();
+        return $this->export($filter, $listName, $consoleRouter);
+    }
+
+
+}

+ 24 - 0
backendApi/modules/v1/models/exportForms/BaUserExportForm.php

@@ -0,0 +1,24 @@
+<?php
+namespace backendApi\modules\v1\models\exportForms;
+
+use common\libs\export\module\BaUserExport;
+use yii\db\Exception;
+
+class BaUserExportForm extends BaseExportForm
+{
+    /**
+     * 导出
+     * @param $filter
+     * @param $listName
+     * @param null $consoleRouter
+     * @return bool
+     * @throws Exception
+     */
+    public function run($filter, $listName, $consoleRouter = null): bool
+    {
+        $this->exportObj = BaUserExport::instance();
+        return $this->export($filter, $listName, $consoleRouter);
+    }
+
+
+}

+ 12 - 2
backendApi/modules/v1/models/lists/atlas/NetworkList.php

@@ -10,8 +10,10 @@ use common\helpers\user\Perf;
 use common\libs\dataList\column\Price;
 use common\libs\dataList\DataListInterface;
 use common\models\CalcBonus;
+use common\models\EmployLevel;
 use common\models\PerfMonth;
 use common\models\Period;
+use common\models\StarCrownLevel;
 use common\models\UserBind;
 use common\models\UserInfo;
 use common\libs\dataList\column\DateTime;
@@ -42,6 +44,7 @@ class NetworkList extends \common\libs\dataList\DataList implements DataListInte
         $mainUserInfo = Info::baseInfo($userId, $periodNum);
         $decLevelConfig = Cache::getDecLevelConfig();
         $empLevelConfig = Cache::getEmpLevelConfig();
+        $crownLevelConfig = Cache::getStarCrownLevelConfig();
         $param = [];
         if ( $this->pageSize ) $param['pageSize'] = $this->pageSize;
         if ( $this->page !== null ) $param['page'] = $this->page;
@@ -56,7 +59,8 @@ class NetworkList extends \common\libs\dataList\DataList implements DataListInte
             $this->listData['list'][$key]['REAL_NAME'] = $userBaseInfo['REAL_NAME'];
             $this->listData['list'][$key]['PERIOD_AT'] = $userBaseInfo['PERIOD_AT'];
             $this->listData['list'][$key]['DEC_LV_NAME'] = $decLevelConfig[$userBaseInfo['DEC_LV']]['LEVEL_NAME'];
-            $this->listData['list'][$key]['EMP_LV_NAME'] = isset($empLevelConfig[$userBaseInfo['EMP_LV']])?$empLevelConfig[$userBaseInfo['EMP_LV']]['LEVEL_NAME']:'';
+            $this->listData['list'][$key]['EMP_LV_NAME'] = isset($empLevelConfig[$userBaseInfo['EMP_LV']])?$empLevelConfig[$userBaseInfo['EMP_LV']]['LEVEL_NAME']:$empLevelConfig[EmployLevel::getDefaultLevelId()]['LEVEL_NAME'];
+            $this->listData['list'][$key]['CROWN_LV_NAME'] = isset($crownLevelConfig[$userBaseInfo['CROWN_LV']]) ? $crownLevelConfig[$userBaseInfo['CROWN_LV']]['LEVEL_NAME'] : $crownLevelConfig[StarCrownLevel::getDefaultLevelId()]['LEVEL_NAME'];
         }
         $this->listData['periodNum'] = $periodNum;
         $this->listData['listTopDeep'] = $mainUserInfo['NETWORK_DEEP'];
@@ -89,7 +93,13 @@ class NetworkList extends \common\libs\dataList\DataList implements DataListInte
                     ],
                 ],
                 'EMP_LV_NAME' => [
-                    'header' => 'Recommended Member Rank', // 推荐会员聘级
+                    'header' => 'Highest Director', // 最高管理星级
+                    'headerOther' => [
+                        'width' => '210',
+                    ],
+                ],
+                'CROWN_LV_NAME' => [
+                    'header' => 'Highest Crown', // 最高皇冠星级
                     'headerOther' => [
                         'width' => '210',
                     ],

+ 12 - 2
backendApi/modules/v1/models/lists/atlas/RelationList.php

@@ -9,7 +9,9 @@ use common\helpers\user\Info;
 use common\libs\dataList\column\Price;
 use common\libs\dataList\DataListInterface;
 use common\models\CalcBonus;
+use common\models\EmployLevel;
 use common\models\Period;
+use common\models\StarCrownLevel;
 use common\models\UserBind;
 use common\models\UserInfo;
 use common\libs\dataList\column\DateTime;
@@ -40,6 +42,7 @@ class RelationList extends \common\libs\dataList\DataList implements DataListInt
         $mainUserInfo = Info::baseInfo($userId, $periodNum);
         $decLevelConfig = Cache::getDecLevelConfig();
         $empLevelConfig = Cache::getEmpLevelConfig();
+        $crownLevelConfig = Cache::getStarCrownLevelConfig();
         $param = [];
         if ( $this->pageSize ) $param['pageSize'] = $this->pageSize;
         if ( $this->page !== null ) $param['page'] = $this->page;
@@ -53,7 +56,8 @@ class RelationList extends \common\libs\dataList\DataList implements DataListInt
             $this->listData['list'][$key]['REAL_NAME'] = $userBaseInfo['REAL_NAME'];
             $this->listData['list'][$key]['PERIOD_AT'] = $userBaseInfo['PERIOD_AT'];
             $this->listData['list'][$key]['DEC_LV_NAME'] = $decLevelConfig[$userBaseInfo['DEC_LV']]['LEVEL_NAME'];
-            $this->listData['list'][$key]['EMP_LV_NAME'] = isset($empLevelConfig[$userBaseInfo['EMP_LV']])?$empLevelConfig[$userBaseInfo['EMP_LV']]['LEVEL_NAME']:'';
+            $this->listData['list'][$key]['EMP_LV_NAME'] = isset($empLevelConfig[$userBaseInfo['EMP_LV']]) ? $empLevelConfig[$userBaseInfo['EMP_LV']]['LEVEL_NAME'] : $empLevelConfig[EmployLevel::getDefaultLevelId()]['LEVEL_NAME'];
+            $this->listData['list'][$key]['CROWN_LV_NAME'] = isset($crownLevelConfig[$userBaseInfo['CROWN_LV']]) ? $crownLevelConfig[$userBaseInfo['CROWN_LV']]['LEVEL_NAME'] : $crownLevelConfig[StarCrownLevel::getDefaultLevelId()]['LEVEL_NAME'];
         }
         $this->listData['periodNum'] = $periodNum;
         $this->listData['listTopDeep'] = $mainUserInfo['RELATION_DEEP'];
@@ -89,7 +93,13 @@ class RelationList extends \common\libs\dataList\DataList implements DataListInt
                     ],
                 ],
                 'EMP_LV_NAME' => [
-                    'header' => 'Recommended Member Rank', // 推荐会员聘级
+                    'header' => 'Highest Director', // 推荐会员聘级
+                    'headerOther' => [
+                        'width' => '210',
+                    ],
+                ],
+                'CROWN_LV_NAME' => [
+                    'header' => 'Highest Crown ', // 推荐会员聘级
                     'headerOther' => [
                         'width' => '210',
                     ],

+ 2 - 2
backendApi/modules/v1/models/lists/bonus/BalanceList.php

@@ -74,7 +74,7 @@ class BalanceList extends \common\libs\dataList\DataList implements DataListInte
                     ],
                 ],
                 'IS_DEC' => [
-                    'header' => 'Whether Declaration Center', // 是否报单中心
+                    'header' => 'Whether Stockist', // 是否报单中心
                     'value' => function($row) {
                         return (new YesNo([
                             'value' => $row['IS_DEC'],
@@ -199,7 +199,7 @@ class BalanceList extends \common\libs\dataList\DataList implements DataListInte
             $this->filterTypes = [
                 'USER_NAME'=> ['isUserTable'=> false, 'name'=> 'Member Code'], // 会员编号
                 'REAL_NAME'=> ['isUserTable'=> false, 'name'=> 'Member Name'], // 会员姓名
-                'IS_DEC'=> ['isUserTable'=> false, 'name'=> 'Whether Declaration Center', 'other'=> 'yesOrNo'], // 是否报单中心
+                'IS_DEC'=> ['isUserTable'=> false, 'name'=> 'Whether Stockist', 'other'=> 'yesOrNo'], // 是否报单中心
                 'BONUS'=> ['isUserTable'=> false, 'name'=> 'Member Bonus'], // 会员奖金余额
                 'CASH'=> ['isUserTable'=> false, 'name'=> 'Member Ecoin'], // 会员余额
                 'PERIOD_AT'=> ['isUserTable'=> false, 'name'=> 'Joining Period'], // 加入期数

+ 2 - 2
backendApi/modules/v1/models/lists/bonus/FlowBonusList.php

@@ -110,7 +110,7 @@ class FlowBonusList extends \common\libs\dataList\DataList implements DataListIn
                     ],
                 ],
                 'IS_DEC' => [
-                    'header' => 'Whether Declaration Center', // 是否报单中心
+                    'header' => 'Whether Stockist', // 是否报单中心
                     'value' => function ($row) {
                         return (new YesNo([
                             'value' => $row['IS_DEC'],
@@ -206,7 +206,7 @@ class FlowBonusList extends \common\libs\dataList\DataList implements DataListIn
                 'REAL_NAME' => ['isUserTable' => false, 'name' => 'Member Name'], // 会员姓名
                 'LAST_DEC_LV_NAME' => ['isUserTable' => false, 'name' => 'Member Level', 'other' => 'decLevel'], // 会员等级
                 'LAST_EMP_LV_NAME' => ['isUserTable' => false, 'name' => 'Rank', 'other' => 'empLevel'], // 聘级
-                'IS_DEC' => ['isUserTable' => false, 'name' => 'Whether Declaration Center', 'other' => 'yesOrNo'], // 是否报单中心
+                'IS_DEC' => ['isUserTable' => false, 'name' => 'Whether Stockist', 'other' => 'yesOrNo'], // 是否报单中心
                 'AMOUNT' => ['isUserTable' => false, 'name' => 'Debit/Credit'], // 交易额
                 'TOTAL' => ['isUserTable' => false, 'name' => 'New Balance'], // 交易后余额
                 'ADMIN_NAME' => ['isUserTable' => false, 'name' => 'Operator'], // 操作人

+ 4 - 3
backendApi/modules/v1/models/lists/bonus/PeriodBonusList.php

@@ -118,13 +118,13 @@ class PeriodBonusList extends \common\libs\dataList\DataList implements DataList
                     ],
                 ],
                 'LAST_EMP_LV_NAME' => [
-                    'header' => 'Director Rank', // 结算时会员聘
+                    'header' => 'Latest Director', // 结算时会员最新管理星
                     'headerOther' => [
                         'width' => '140',
                     ],
                 ],
                 'LAST_CROWN_LV_NAME' => [
-                    'header' => 'Crown Rank',//结算时会员聘
+                    'header' => 'Latest Crown',//结算时会员最新皇冠星
                     'headerOther' => [
                         'width' => '140',
                     ],
@@ -304,7 +304,8 @@ class PeriodBonusList extends \common\libs\dataList\DataList implements DataList
                 'LAST_USER_NAME'=> ['isUserTable'=> false, 'name'=> 'Member Code'], // 会员编号
                 'LAST_REAL_NAME'=> ['isUserTable'=> false, 'name'=> 'Member Name'], // 会员姓名
                 'LAST_DEC_LV_NAME'=> ['isUserTable'=> false, 'name'=> 'PC Member Level', 'other'=> 'decLevel'], // 结算时会员级别
-                'LAST_EMP_LV_NAME'=> ['isUserTable'=> false, 'name'=> 'Director Rank', 'other'=> 'empLevel'], // 结算时会员聘级
+                'LAST_EMP_LV_NAME'=> ['isUserTable'=> false, 'name'=> 'Latest Director', 'other'=> 'empLevel'], // 结算时会员管理星级
+                'LAST_CROWN_LV_NAME'=> ['isUserTable'=> false, 'name'=> 'Latest Crown', 'other'=> 'crownLevel'], // 结算时会员皇冠星级
                 'LAST_MOBILE'=> ['isUserTable'=> false, 'name'=> 'Phone Number'], // 手机号
                 'LAST_PERIOD_AT'=> ['isUserTable'=> false, 'name'=> 'Joining Period'], // 加入期数
                 'LAST_CREATED_AT'=> ['isUserTable'=> false, 'name'=> 'Joining Date', 'other'=> 'date'], // 加入时间

+ 2 - 2
backendApi/modules/v1/models/lists/finance/BalanceAuditList.php

@@ -87,7 +87,7 @@ class BalanceAuditList extends \common\libs\dataList\DataList implements DataLis
                     ],
                 ],
                 'LAST_DEC_ROLE_NAME' => [
-                    'header' => 'Declaration center level', // 报单中心级别
+                    'header' => 'Stockist level', // 报单中心级别
                     'headerOther' => [
                         'width' => '170',
                     ],
@@ -207,7 +207,7 @@ class BalanceAuditList extends \common\libs\dataList\DataList implements DataLis
                 'USER_NAME' => ['isUserTable' => false, 'name' => 'Member code'], //会员编号
                 'REAL_NAME' => ['isUserTable' => false, 'name' => 'Member name'], //会员姓名
                 'LAST_DEC_LV_NAME' => ['isUserTable' => false, 'name' => 'Member level', 'other' => 'decLevel'], // 会员级别
-                'LAST_DEC_ROLE_NAME' => ['isUserTable' => false, 'name' => 'Declaration center level', 'other' => 'decRole'], // 报单中心级别
+                'LAST_DEC_ROLE_NAME' => ['isUserTable' => false, 'name' => 'Stockist level', 'other' => 'decRole'], // 报单中心级别
                 'LAST_EMP_LV_NAME' => ['isUserTable' => false, 'name' => 'rank', 'other' => 'empLevel'], // 聘级
                 'TYPE_NAME' => ['isUserTable' => false, 'name' => 'Account type', 'other' => 'select', 'selectData' => Tool::formatFilter(BalanceAudit::TYPE, 'name', 'label')], // 账户类型
                 'DEAL_TYPE_NAME' => ['isUserTable' => false, 'name' => 'Transaction type', 'other' => 'select', 'selectData' => Tool::formatFilter(DealType::getAllTypesForShow(), 'ID', 'TYPE_NAME')], // 交易类型

+ 1 - 0
backendApi/modules/v1/models/lists/log/AdminHandleList.php

@@ -155,6 +155,7 @@ class AdminHandleList extends \common\libs\dataList\DataList implements DataList
                 ['id'=>'添加体系','name'=>'添加体系'],
                 ['id'=>'编辑体系','name'=>'编辑体系'],
                 ['id'=>'恢复体系','name'=>'恢复体系'],
+                ['id'=>'perf adjustment','name'=>'perf adjustment'],
             ];
             $this->filterTypes = [
                 'opt_type' => ['isUserTable'=>false, 'name'=>'操作类型', 'other'=> 'select', 'selectData'=> $selectData],

+ 362 - 0
backendApi/modules/v1/models/lists/shop/BaOrderList.php

@@ -0,0 +1,362 @@
+<?php
+namespace backendApi\modules\v1\models\lists\shop;
+
+use common\helpers\Cache;
+use common\helpers\Tool;
+use common\helpers\user\Info;
+use common\libs\dataList\DataListInterface;
+
+use common\models\BaApproachOrder;
+use common\models\BaApproachOrderGoods;
+use common\models\BaOrder;
+use common\models\BaOrderGoods;
+
+use common\models\ShopGoods;
+use common\models\BaUser;
+use common\libs\dataList\column\DateTime;
+use yii\data\Pagination;
+use yii\db\Query;
+
+class BaOrderList extends \common\libs\dataList\DataList implements DataListInterface
+{
+    /**
+     * 列表名称
+     * @return string
+     */
+    public function getListName(){
+        return 'BA订单列表';
+    }
+
+    /**
+     * 列表筛选到的数据
+     */
+    public function dataHandle()
+    {
+        $orderQuery = BaOrder::find()
+            ->alias('O')
+            ->where($this->condition, $this->params)
+            ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
+            ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
+            ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
+            ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
+            ->orderBy('O.CREATED_AT DESC');
+
+        // 订单中间表只查询待支付和支付失败的订单
+        $this->params[':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value'];   // 待支付
+        $this->params[':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value'];   // 支付失败
+        $orderStandardQuery = BaApproachOrder::find()
+            ->alias('O')
+            ->where($this->condition . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params)
+            ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
+            ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
+            ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
+            ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
+            ->orderBy('O.CREATED_AT DESC');
+
+        $queryAll = $orderQuery->union($orderStandardQuery, true);
+        $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
+
+        $totalCount = $query->count();
+        $pagination = new Pagination(['totalCount' => $totalCount, 'pageSize' => \Yii::$app->request->get('pageSize')]);
+        $lists = $query->offset($pagination->offset)->limit($pagination->limit)->all();
+
+        $this->listData = [
+            'list' => $lists,
+            'currentPage'=>$pagination->page,
+            'totalPages'=>$pagination->pageCount,
+            'startNum' => $pagination->page * $pagination->pageSize + 1,
+            'totalCount' => $pagination->totalCount,
+            'pageSize' => $pagination->pageSize,
+        ];
+
+        foreach ($this->listData['list'] as $key => $value) {
+            $CREATE_USER_ID = Info::getBaUserIdByUserName($value['CREATE_USER']);
+            $this->listData['list'][$key]['DEC_USER_NAME'] = Info::getBaUserNameByUserId($value['DEC_ID']);
+            $this->listData['list'][$key]['CREATE_USER_NAME'] = Info::getBaUserRealNameByUserId($CREATE_USER_ID);
+        }
+    }
+
+    /**
+     * 要展示和导出的所有字段
+     * @return array
+     */
+    public function getColumn(){
+        $regionConfig = Cache::getRegionConfig();
+        if(!$this->columns){
+            $this->columns = [
+                'ID' => null,
+                'DEC_SN' => null,
+                'USER_NAME' => [
+                    'header' => 'Member code',//会员编号
+                    'headerOther' => ['width' => '120'],
+                ],
+                'DEC_USER_NAME' => [
+                    'header' => 'Stockist', // 报单中心
+                    'headerOther' => ['width' => '120'],
+                ],
+                'CREATE_USER' => [
+                    'header' => 'Creator No',//创建人编号
+                    'headerOther' => ['width' => '120'],
+                ],
+                'CREATE_USER_NAME' => [
+                    'header' => 'Stockist Name',//创建人姓名
+                    'headerOther' => ['width' => '120'],
+                ],
+                'SN' => [
+                    'header' => 'Order Code',//订单号
+                    'headerOther' => ['width' => '200'],
+                ],
+                'STATUS' => [
+                    'header' => 'Status',//订单状态
+                    'headerOther' => [
+                        'width' => '110',
+                    ],
+                    'value' => function ($row) {
+                        return \Yii::$app->params['orderStatus'][$row['STATUS']]['label'] ?? '';
+                    },
+                ],
+                'SKU_CODE' => [
+                    'header' => 'Product Code',//存货编码
+                    'headerOther' => ['width' => '150'],
+                ],
+                'GOODS_TITLE' => [
+                    'header' => 'Product Name', // 存货名称
+                    'headerOther' => ['width' => '200'],
+                ],
+                'BUY_NUMS' => [
+                    'header' => 'Qty',//数量
+                    'headerOther' => ['width' => '100'],
+                ],
+                'CONSIGNEE' => [
+                    'header' => 'Recipient',//收货人
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'MOBILE' => [
+                    'header' => 'Contact 1',//联系方式1
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                ],
+                'TEL' => [
+                    'header' => 'Contact 2',//联系方式2
+                ],
+                'PROVINCE' => [
+                    'header' => 'State', // 州
+                    'headerOther' => ['width' => '120'],
+                    'value' => function ($row) use($regionConfig) {
+                        return $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
+                    },
+                ],
+                'CITY' => [
+                    'header' => 'Local Government Area', // 地方政府
+                    'headerOther' => ['width' => '120'],
+                    'value' => function ($row) use($regionConfig) {
+                        return $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
+                    },
+                ],
+                'COUNTY' => [
+                    'header' => 'City', // 区
+                    'headerOther' => ['width' => '120'],
+                    'value' => function ($row) use($regionConfig) {
+                        return $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
+                    },
+                ],
+                'ADDRESS' => [
+                    'header' => 'Detailed Address',//详细地址
+                    'headerOther' => [
+                        'width' => '300',
+                    ],
+                ],
+                'PERIOD_NUM' => [
+                    'header' => 'Period',//期数
+                ],
+                'ORDER_TYPE' => [
+                    'header' => 'Order Type',//订单类型
+                    'headerOther' => ['width' => '140'],
+                    'value' => function ($row) {
+                        switch ($row['ORDER_TYPE']) {
+                            case 'ZC':
+                                return 'Welcome Pack';
+                            case 'FX':
+                                return 'Repeat Purchase';
+                        }
+                        return '';
+                    },
+                ],
+                'CREATED_AT' => [
+                    'header' => 'Creation Time',//创建时间
+                    'value' => function ($row) {
+                        return (new DateTime([
+                            'value' => $row['CREATED_AT'],
+                        ]))->result();
+                    },
+                    'headerOther' => ['width' => '190'],
+                ],
+                'PAY_TYPE' => [
+                    'header' => 'Pay Type',// 支付方式
+                    'value' => function ($row) {
+                        return ShopGoods::payTypes()[$row['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'];
+                    },
+                    'headerOther' => ['width' => '190'],
+                ],
+                'PAY_AT' => [
+                    'header' => 'Payment Time',//支付时间
+                    'value' => function ($row) {
+                        return (new DateTime([
+                            'value' => $row['PAY_AT'],
+                        ]))->result();
+                    },
+                    'headerOther' => ['width' => '190'],
+                ],
+                'DELIVERY_AT' => [
+                    'header' => 'Delivery Time',//发货时间
+                    'value' => function ($row) {
+                        return (new DateTime([
+                            'value' => $row['DELIVERY_AT'],
+                        ]))->result();
+                    },
+                    'headerOther' => ['width' => '190'],
+                ],
+                'REAL_PRICE' => [
+                    'header' => 'Item Pricing',//商品单价
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                    'value' => function ($row) {
+                        return Tool::formatPrice($row['REAL_PRICE']);
+                    },
+                    'valueOther' => function ($row) {
+                        return [
+                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
+                        ];
+                    },
+                ],
+                'REAL_PV' => [
+                    'header' => 'Commodity Amount',//商品金额
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                    'value' => function ($row) {
+                        return Tool::formatPrice($row['REAL_PV']);
+                    },
+                    'valueOther' => function ($row) {
+                        return [
+                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
+                        ];
+                    },
+                ],
+                'PAY_FREIGHT' => [
+                    'header' => 'Freight',//运费
+                    'value' => function ($row) {
+                        return Tool::formatPrice($row['FREIGHT']);
+                    },
+                    'valueOther' => function ($row) {
+                        return [
+                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
+                        ];
+                    },
+                ],
+                'TAX_RATE' => [
+                    'header' => 'Tax Rate',//税率
+                    'value' => function ($row) {
+                        return Tool::formatPrice($row['TAX_RATE']);
+                    },
+                    'valueOther' => function ($row) {
+                        return [
+                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
+                        ];
+                    },
+                ],
+                'TAX_AMOUNT' => [
+                    'header' => 'Tax',//税额
+                    'headerOther' => [
+                        'width' => '150',
+                    ],
+                    'value' => function ($row) {
+                        return Tool::formatPrice(($row['REAL_PRICE'] - $row['REAL_PRICE'] / (1 + $row['TAX_RATE'] / 100)));
+                    },
+                    'valueOther' => function ($row) {
+                        return [
+                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
+                        ];
+                    },
+                ],
+                'EXPRESS_COMPANY' => [
+                    'header' => 'Courier Services Company',//快递公司
+                    'headerOther' => ['width' => '150'],
+                ],
+                'ORDER_TRACK_NO' => [
+                    'header' => 'Courier Number',//快递单号
+                    'headerOther' => ['width' => '200'],
+                ],
+                'EXPRESS_TYPE' => [
+                    'header' => 'Shipping Method',//发货方式
+                    'headerOther' => ['width' => '150'],
+                    'value' => function ($row) {
+                        return $row['EXPRESS_TYPE']==0 ? 'mailing ':' auto pick ';//'邮寄' : '自提'
+                    },
+                ],
+                'FRONT_REMARK' => [
+                    'header' => 'Member Notes',//会员备注
+                    'headerOther' => [
+                        'width' => '200',
+                    ],
+                    'value' => function ($row) {
+                        return $row['FRONT_REMARK'];
+                    },
+                    'showValue' => function ($row) {
+                        return '<div title="'.$row['FRONT_REMARK'].'" style="width:180px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'.$row['FRONT_REMARK'].'</div>';
+                    },
+                ],
+                'DELIVERY_STATUS' => null,
+                'DELIVERY_STATUS_NAME' => [
+                    'header' => 'Shipment Status',//发货状态
+                    'headerOther' => [
+                        'width' => '110',
+                    ],
+                    'value' => function ($row) {
+                        return \Yii::$app->params['deliveryStatus'][$row['DELIVERY_STATUS']]['label'] ?? '';
+                    },
+                ],
+            ];
+        }
+        return $this->columns;
+    }
+
+    /**
+     * 前台用于筛选的类型集合
+     * @return mixed
+     */
+    public function getFilterTypes()
+    {
+        if(!$this->filterTypes){
+            $this->filterTypes = [
+                'SN'=> ['name'=> 'Order No'],//订单编号
+                'USER_NAME'=> ['name'=> 'Member Code'],//会员编号
+                'MOBILE'=> ['name'=> 'Contact 1'],//联系方式1
+                'ORDER_TYPE'=> [
+                    'name'=> 'Order Type',
+                    'other'=> 'select',
+                    'selectData'=> [
+                        ['id' => 'ZC', 'name' => 'Welcome Pack'],
+                        ['id' => 'FX', 'name' => 'Repeat Purchase'],
+                    ]
+                ],
+                'PERIOD_NUM'=> ['name'=> 'Number Of Periods'],//期数
+                'CREATED_AT'=> ['name'=> 'Creation Time', 'other'=>'date'],//创建时间
+                'STATUS'=> [
+                    'name'=> 'Status',
+                    'other'=> 'select',
+                    'selectData'=> [
+                        ['id' => \Yii::$app->params['orderStatus']['paid']['value'], 'name' => \Yii::$app->params['orderStatus']['paid']['label']],
+                        ['id' => \Yii::$app->params['orderStatus']['notPaid']['value'], 'name' => \Yii::$app->params['orderStatus']['notPaid']['label']],
+                        ['id' => \Yii::$app->params['orderStatus']['failPaid']['value'], 'name' => \Yii::$app->params['orderStatus']['failPaid']['label']]
+                    ]
+                ],
+            ];
+        }
+        return $this->filterTypes;
+    }
+}

+ 198 - 0
backendApi/modules/v1/models/lists/shop/BaUserList.php

@@ -0,0 +1,198 @@
+<?php
+namespace backendApi\modules\v1\models\lists\shop;
+
+use common\helpers\Cache;
+use common\helpers\http\BackendToFrontendApi;
+use common\helpers\user\Info;
+use common\libs\dataList\DataListInterface;
+use common\models\DecRole;
+use common\models\OpenBank;
+use common\models\Region;
+use common\models\BaUser;
+use common\models\BaUserInfo;
+use common\libs\dataList\column\DateTime;
+use common\libs\dataList\column\YesNo;
+use common\models\User;
+use common\models\UserNetwork;
+use common\models\UserSystem;
+use Yii;
+
+class BaUserList extends \common\libs\dataList\DataList implements DataListInterface
+{
+    /**
+     * 列表名称
+     * @return string
+     */
+    public function getListName(){
+        return 'BA会员列表';
+    }
+
+    /**
+     * 列表筛选到的数据
+     */
+    public function dataHandle()
+    {
+//        $this->condition .= ' AND UN.USER_ID=UI.USER_ID AND UN.PARENT_UID=UI.CON_UID';
+        $this->listData = BaUser::lists($this->condition, $this->params, [
+            'select' => 'U.*,
+                UI.USER_ID, UI.ZC_PV, UI.CON_UID, UI.REC_UID, UI.CON_NUM, UI.REC_NUM, UI.NETWORK_DEEP, 
+                UI.RELATION_DEEP, UI.SYSTEM_ID, UI.IS_GROUP_LEADER, UI.IS_SYSTEM_LEADER, UI.IS_TEAM, UI.IS_BIND, 
+                UI.IS_TEAM_MAIN, UI.IS_BIND_MAIN, UI.IS_AUTO_WITHDRAW, UI.CLOSE_LOGIN, UI.REG_TYPE, UI.SHOULD_REG_TYPE, 
+                UI.REG_NAME, UI.CREDIT_CODE, UI.PREMISES, UI.LEGAL_PERSON, UI.REG_EXPIRES, UI.STORE_TYPE, UI.INVOICE_BALANCE, 
+                UI.HIGHEST_EMP_LV, UI.CLOSE_LOGIN_AT, UI.PULLED_AT, U.WHETHER_UPGRADE,
+                UI.GROUP_LEADER_AT, UI.ALLOW_TRANSFER, UI.ALLOW_RECONSUME_SMS, UI.ALLOW_RECONSUME_SMS_TO, 
+                UI.HIGHEST_EMP_LV_PERIOD, UI.TRANSFER_PROP, UI.LOGIN_NUMS, UI.FAIL_NUMS, UI.LAST_LOGIN_IP, 
+                RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,
+                DU.USER_NAME DEC_USER_NAME
+                ',
+            'orderBy' => 'UI.CREATED_AT DESC, UI.ID DESC',
+            'from' => BaUser::tableName() . ' AS U',
+            'join' => [
+                ['LEFT JOIN', BaUserInfo::tableName() . ' AS UI', 'UI.USER_ID=U.ID'],
+                ['LEFT JOIN', User::tableName() . ' AS RU', 'UI.REC_UID=RU.ID'],
+                ['LEFT JOIN', BaUser::tableName() . ' AS DU', 'U.DEC_ID=DU.ID'],
+            ],
+            'page' => $this->page,
+            'pageSize' => $this->pageSize,
+        ]);
+        foreach ($this->listData['list'] as $key => $value) {
+            // 后台访问前台的请求参数
+            if (!$this->isExport && Yii::$app->user->validateAdminAction('user', 'login-to-frontend')) {
+                $urlParams = BackendToFrontendApi::paramsFormat(['id' => $value['USER_ID']]);
+                $urlParamStr = '';
+                foreach ($urlParams as $pKey => $pValue) {
+                    $urlParamStr .= $pKey . '=' . $pValue . '&';
+                }
+                $urlParamStr = substr($urlParamStr, 0, -1);
+                $this->listData['list'][$key]['BTF_URL'] = $urlParamStr;
+            } else {
+                $this->listData['list'][$key]['BTF_URL'] = null;
+            }
+        }
+    }
+
+    /**
+     * 要展示和导出的所有字段
+     * @return array
+     */
+    public function getColumn(){
+        $regionConfig = Cache::getRegionConfig();
+        if(!$this->columns){
+            $this->columns = [
+                'USER_ID' => null, // 这种传输方式主要是用于索引,因为过滤后的字段可能没有这种ID,但是一些功能的操作还需要用这种ID去关联,例如前台会员列表中的勾选批量状态管理,这里需要的就是USER_ID
+                'BTF_URL' => null,
+                'USER_NAME' => [
+                    'header' => 'Member code',//会员编号
+                    'headerOther' => ['width' => '150'],
+                ],
+                'REAL_NAME' => [
+                    'header' => 'Member name',//会员姓名
+                    'headerOther' => [
+                        'width' => '120',
+                    ],
+                    'valueOther' => [
+                        'tag'=>['type'=>'success', 'size' => 'small', 'class'=>'no-border']
+                    ],
+                ],
+                'LOGIN_STATUS_NAME' => [
+                    'header' => 'Login status',//登录状态
+                    'value' => function($row) {
+                        return $row['ALLOW_LOGIN'] == 1 ? 'allow Login': 'prohibit Login';//'允许登录' : '禁止登录'
+                    },
+                    'headerOther' => ['width' => '110'],
+                ],
+                'STATUS' => [
+                    'header' => 'Status',//状态
+                    'value' => function($row) {
+                        return $row['STATUS'] == 1 ? 'activate': 'lock';//'激活' : '锁定'
+                    },
+                    'headerOther' => ['width' => '110'],
+                ],
+                'ALLOW_LOGIN' => ['header' => 'Filter allow login','hidden'=>true],//筛选允许登录
+                'CREATED_AT' => [
+                    'header' => 'Joining Date', // 加入日期
+                    'value' => function($row) {
+                        return (new DateTime([
+                            'value' => $row['CREATED_AT'],
+                        ]))->result();
+                    },
+                    'headerOther' => ['width' => '170'],
+                ],
+//                'PERIOD_AT' => [
+//                    'header' => 'Joining Period',//加入期数
+//                    'headerOther' => ['width' => '180'],
+//                ],
+                'REC_USER_NAME' => [
+                    'header' => 'Recommendation No',//推荐编号
+                    'headerOther' => ['width' => '150'],
+                ],
+                'REC_REAL_NAME' => [
+                    'header' => 'Recommended Name',//推荐姓名
+                    'headerOther' => ['width' => '100'],
+                ],
+                'MOBILE' => [
+                    'header' => 'Phone Number',//手机号码
+                    'value' => function($row) {
+                        return "\t".$row['MOBILE'];
+                    },
+                    'headerOther' => ['width' => '120'],
+                ],
+                'TEL' => [
+                    'header' => 'Alternate Phone Number', // 备用手机号码
+                    'value' => function($row) {
+                        return "\t".$row['TEL'];
+                    },
+                    'headerOther' => ['width' => '120'],
+                ],
+                'AREA' => [
+                    'header' => 'Common address',//常用地址
+                    'value' => function($row) use($regionConfig) {
+                        $province = $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
+                        $city = $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
+                        $county = $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
+                        return $province.$city.$county;
+                    },
+                    'showValue' => function($row) {
+                        $province = $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
+                        $city = $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
+                        $county = $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
+                        return '<div class="addr" title='.$province.$city.$county.'>'.$province.$city.$county.'</div>';
+                    },
+                    'headerOther' => [
+                        'width' => '200'
+                    ],
+                ],
+                'WHETHER_UPGRADE' => [
+                    'header' => 'Whether Upgrade',// 是否已转正
+                    'value' => function($row) {
+                        return $row['WHETHER_UPGRADE'] == 1 ? 'YES': 'NO';
+                    },
+                    'headerOther' => ['width' => '110'],
+                ],
+            ];
+        }
+        return $this->columns;
+    }
+
+    /**
+     * 前台用于筛选的类型集合
+     * @return mixed
+     */
+    public function getFilterTypes()
+    {
+        if(!$this->filterTypes){
+            $this->filterTypes = [
+                'USER_NAME'=> ['name'=> 'Member code'], // 会员编号
+                'REAL_NAME'=> ['name'=> 'Member name'], // 会员姓名
+                'CREATED_AT'=> ['name'=> 'Joining Date', 'other'=> 'date'], // 加入日期
+                'PERIOD_AT'=> ['name'=> 'Joining Period'], // 加入期数
+                'REC_USER_NAME'=> ['name'=> 'Recommendation No'],//推荐编号
+                'CON_USER_NAME'=> ['name'=> 'Placement No'],//安置编号
+                'MOBILE'=> ['name'=> 'Phone Number'],//手机号码
+                'AREA'=> ['name'=> 'Common address', 'other'=> 'area'],//常用地址
+                'STATUS'=> ['name'=> 'Active status', 'other'=> 'select', 'selectData'=> [['id'=> 0, 'name'=> 'locking'],['id'=> 1, 'name'=> 'activation']]],
+            ];
+        }
+        return $this->filterTypes;
+    }
+}

+ 0 - 0
backendApi/modules/v1/models/lists/shop/FlowRemainPvList.php


+ 9 - 2
backendApi/modules/v1/models/lists/shop/OrderList.php

@@ -178,7 +178,7 @@ class OrderList extends \common\libs\dataList\DataList implements DataListInterf
                     'value' => function ($row) {
                         switch ($row['ORDER_TYPE']) {
                             case 'ZC':
-                                return 'Welcome pack';
+                                return 'Welcome Pack';
                             case 'FX':
                                 return in_array($row['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Repeat Purchase': 'Points'; //'重消' : '积分'
                         }
@@ -361,7 +361,14 @@ class OrderList extends \common\libs\dataList\DataList implements DataListInterf
                 'SN'=> ['name'=> 'Order No'],//订单编号
                 'USER_NAME'=> ['name'=> 'Member Code'],//会员编号
                 'MOBILE'=> ['name'=> 'Contact 1'],//联系方式1
-                'ORDER_TYPE'=> ['name'=> 'Order Type'],
+                'ORDER_TYPE'=> [
+                    'name'=> 'Order Type',
+                    'other'=> 'select',
+                    'selectData'=> [
+                        ['id' => 'ZC', 'name' => 'Welcome Pack'],
+                        ['id' => 'FX', 'name' => 'Repeat Purchase'],
+                    ]
+                    ],
                 'PERIOD_NUM'=> ['name'=> 'Number Of Periods'],//期数
                 'CREATED_AT'=> ['name'=> 'Creation Time', 'other'=>'date'],//创建时间
                 'STATUS'=> [

+ 0 - 0
backendApi/modules/v1/models/lists/shop/RemainPvList.php


+ 171 - 0
backendApi/modules/v1/models/lists/user/BaUserList.php

@@ -0,0 +1,171 @@
+<?php
+namespace backendApi\modules\v1\models\lists\user;
+
+use common\helpers\Cache;
+use common\helpers\http\BackendToFrontendApi;
+use common\libs\dataList\DataListInterface;
+use common\models\BaUser;
+use common\models\BaUserInfo;
+use common\models\User;
+use common\libs\dataList\column\DateTime;
+use common\models\UserNetwork;
+use Yii;
+
+class BaUserList extends \common\libs\dataList\DataList implements DataListInterface
+{
+    /**
+     * 列表名称
+     * @return string
+     */
+    public function getListName(){
+        return 'Brand_Ambassador_List';
+    }
+
+    /**
+     * 列表筛选到的数据
+     */
+    public function dataHandle()
+    {
+//        $this->condition .= ' AND UN.USER_ID=UI.USER_ID AND UN.PARENT_UID=UI.CON_UID';
+        $this->listData = BaUser::lists($this->condition, $this->params, [
+            'select' => 'U.*,
+                UI.USER_ID, UI.ZC_PV, UI.CON_UID, UI.REC_UID, UI.CON_NUM, UI.REC_NUM, UI.NETWORK_DEEP, 
+                UI.RELATION_DEEP, UI.SYSTEM_ID, UI.IS_GROUP_LEADER, UI.IS_SYSTEM_LEADER, UI.IS_TEAM, UI.IS_BIND, 
+                UI.IS_TEAM_MAIN, UI.IS_BIND_MAIN, UI.IS_AUTO_WITHDRAW, UI.CLOSE_LOGIN, UI.REG_TYPE, UI.SHOULD_REG_TYPE, 
+                UI.REG_NAME, UI.CREDIT_CODE, UI.PREMISES, UI.LEGAL_PERSON, UI.REG_EXPIRES, UI.STORE_TYPE, UI.INVOICE_BALANCE, 
+                UI.HIGHEST_EMP_LV, UI.CLOSE_LOGIN_AT, UI.PULLED_AT, 
+                UI.GROUP_LEADER_AT, UI.ALLOW_TRANSFER, UI.ALLOW_RECONSUME_SMS, UI.ALLOW_RECONSUME_SMS_TO, 
+                UI.HIGHEST_EMP_LV_PERIOD, UI.TRANSFER_PROP, UI.LOGIN_NUMS, UI.FAIL_NUMS, UI.LAST_LOGIN_IP, 
+                UI.LAST_LOGIN_AT,
+                RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,
+                DU.USER_NAME DEC_USER_NAME',
+            'orderBy' => 'UI.CREATED_AT DESC, UI.ID DESC',
+            'from' => BaUser::tableName() . ' AS U',
+            'join' => [
+                ['LEFT JOIN', BaUserInfo::tableName() . ' AS UI', 'UI.USER_ID=U.ID'],
+                ['LEFT JOIN', User::tableName() . ' AS RU', 'UI.REC_UID=RU.ID'],
+                ['LEFT JOIN', BaUser::tableName() . ' AS DU', 'U.DEC_ID=DU.ID'],
+            ],
+            'page' => $this->page,
+            'pageSize' => $this->pageSize,
+        ]);
+    }
+
+    /**
+     * 要展示和导出的所有字段
+     * @return array
+     */
+    public function getColumn()
+    {
+        $regionConfig = Cache::getRegionConfig();
+        if(!$this->columns){
+            $this->columns = [
+                'USER_ID' => null, // 这种传输方式主要是用于索引,因为过滤后的字段可能没有这种ID,但是一些功能的操作还需要用这种ID去关联,例如前台会员列表中的勾选批量状态管理,这里需要的就是USER_ID
+                'BTF_URL' => null,
+                'USER_NAME' => [
+                    'header' => 'Member Code', // 会员编号
+                    'headerOther' => ['width' => '150'],
+                ],
+                'REAL_NAME' => [
+                    'header' => 'Member Name', // 会员姓名
+                    'headerOther' => [
+                        'width' => '120',
+                    ],
+                    'valueOther' => [
+                        'tag'=>['type'=>'success', 'size' => 'small', 'class'=>'no-border']
+                    ],
+                ],
+                'LOGIN_STATUS_NAME' => [
+                    'header' => 'Login Status', // 登录状态
+                    'value' => function($row) {
+                        return $row['ALLOW_LOGIN'] == 1 ? 'Allow Login': 'Prohibit Login'; // '允许登录' : '禁止登录'
+                    },
+                    'headerOther' => ['width' => '110'],
+                ],
+                'STATUS' => [
+                    'header' => 'Status', // 状态
+                    'value' => function($row) {
+                        return $row['STATUS'] == 1 ? 'Activate': 'Lock'; // '激活' : '锁定'
+                    },
+                    'headerOther' => ['width' => '110'],
+                ],
+                'ALLOW_LOGIN' => ['header' => 'Filter Allow Login','hidden'=>true], // 筛选允许登录
+                'CREATED_AT' => [
+                    'header' => 'Joining Date', // 加入日期
+                    'value' => function($row) {
+                        return (new DateTime([
+                            'value' => $row['CREATED_AT'],
+                        ]))->result();
+                    },
+                    'headerOther' => ['width' => '170'],
+                ],
+                'PERIOD_AT' => [
+                    'header' => 'Joining Period', // 加入期数
+                    'headerOther' => ['width' => '180'],
+                ],
+                'REC_USER_NAME' => [
+                    'header' => 'Recommendation No', // 推荐编号
+                    'headerOther' => ['width' => '160'],
+                ],
+                'REC_REAL_NAME' => [
+                    'header' => 'Recommended Name', // 推荐姓名
+                    'headerOther' => ['width' => '160'],
+                ],
+                'MOBILE' => [
+                    'header' => 'Phone Number', // 手机号码
+                    'value' => function($row) {
+                        return "\t".$row['MOBILE'];
+                    },
+                    'headerOther' => ['width' => '120'],
+                ],
+                'TEL' => [
+                    'header' => 'Alternate Phone Number', // 备用手机号码
+                    'value' => function($row) {
+                        return "\t".$row['TEL'];
+                    },
+                    'headerOther' => ['width' => '180'],
+                ],
+                'AREA' => [
+                    'header' => 'Common Address', // 常用地址
+                    'value' => function($row) use($regionConfig) {
+                        $province = $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
+                        $city = $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
+                        $county = $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
+                        return $province.$city.$county;
+                    },
+                    'showValue' => function($row) {
+                        $province = $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
+                        $city = $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
+                        $county = $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
+                        return '<div class="addr" title='.$province.$city.$county.'>'.$province.$city.$county.'</div>';
+                    },
+                    'headerOther' => [
+                        'width' => '200'
+                    ],
+                ],
+            ];
+        }
+        return $this->columns;
+    }
+
+    /**
+     * 前台用于筛选的类型集合
+     * @return mixed
+     */
+    public function getFilterTypes()
+    {
+        if(!$this->filterTypes){
+            $this->filterTypes = [
+                'USER_NAME'=> ['name'=> 'Member code'], // 会员编号
+                'REAL_NAME'=> ['name'=> 'Member name'], // 会员姓名
+                'CREATED_AT'=> ['name'=> 'Joining Date', 'other'=> 'date'], // 加入日期
+                'PERIOD_AT'=> ['name'=> 'Joining Period'], // 加入期数
+                'REC_USER_NAME'=> ['name'=> 'Recommendation No'],//推荐编号
+                'MOBILE'=> ['name'=> 'Phone Number'],//手机号码
+                'AREA'=> ['name'=> 'Common address', 'other'=> 'area'],//常用地址
+                'STATUS'=> ['name'=> 'Active status', 'other'=> 'select', 'selectData'=> [['id'=> 0, 'name'=> 'locking'],['id'=> 1, 'name'=> 'activation']]],
+            ];
+        }
+        return $this->filterTypes;
+    }
+}

+ 40 - 12
backendApi/modules/v1/models/lists/user/IndexList.php

@@ -6,8 +6,10 @@ use common\helpers\http\BackendToFrontendApi;
 use common\helpers\user\Info;
 use common\libs\dataList\DataListInterface;
 use common\models\DecRole;
+use common\models\EmployLevel;
 use common\models\OpenBank;
 use common\models\Region;
+use common\models\StarCrownLevel;
 use common\models\User;
 use common\models\UserInfo;
 use common\libs\dataList\column\DateTime;
@@ -167,24 +169,48 @@ class IndexList extends \common\libs\dataList\DataList implements DataListInterf
                     ],
                 ],
                 'EMP_LV_NAME' => [
-                    'header' => 'Current Director Rank', // 实时聘
+                    'header' => 'Highest Director', // 最高管理星
                     'headerOther' => [
-                        'width' => '160',
+                        'width' => '190',
                     ],
                     'value' => function($row) use($empLevelConfig) {
-                        return isset($empLevelConfig[$row['EMP_LV']])?$empLevelConfig[$row['EMP_LV']]['LEVEL_NAME']:'';
+                        return isset($empLevelConfig[$row['EMP_LV']]) ? $empLevelConfig[$row['EMP_LV']]['LEVEL_NAME'] : $empLevelConfig[EmployLevel::getDefaultLevelId()]['LEVEL_NAME'];
+                    },
+                    'valueOther' => [
+                        'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
+                    ],
+                ],
+                'LAST_EMP_LV_NAME' => [
+                    'header' => 'Latest Director', // 最新管理星级
+                    'headerOther' => [
+                        'width' => '190',
+                    ],
+                    'value' => function($row) use($empLevelConfig) {
+                        return isset($empLevelConfig[$row['LAST_EMP_LV']]) ? $empLevelConfig[$row['LAST_EMP_LV']]['LEVEL_NAME'] : $empLevelConfig[EmployLevel::getDefaultLevelId()]['LEVEL_NAME'];
                     },
                     'valueOther' => [
                         'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
                     ],
                 ],
                 'CROWN_LV_NAME' => [
-                    'header' => 'Current Crown Rank', // 实时星级
+                    'header' => 'Highest Crown ', // 最高皇冠星级
+                    'headerOther' => [
+                        'width' => '180',
+                    ],
+                    'value' => function($row) use($crownLevelConfig) {
+                        return isset($crownLevelConfig[$row['CROWN_LV']]) ? $crownLevelConfig[$row['CROWN_LV']]['LEVEL_NAME'] : $crownLevelConfig[StarCrownLevel::getDefaultLevelId()]['LEVEL_NAME'];
+                    },
+                    'valueOther' => [
+                        'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
+                    ],
+                ],
+                'LAST_CROWN_LV_NAME' => [
+                    'header' => 'Latest Crown', // 最新皇冠星级
                     'headerOther' => [
-                        'width' => '150',
+                        'width' => '180',
                     ],
                     'value' => function($row) use($crownLevelConfig) {
-                        return isset($crownLevelConfig[$row['CROWN_LV']])?$crownLevelConfig[$row['CROWN_LV']]['LEVEL_NAME']:'';
+                        return isset($crownLevelConfig[$row['LAST_CROWN_LV']]) ? $crownLevelConfig[$row['LAST_CROWN_LV']]['LEVEL_NAME'] : $crownLevelConfig[StarCrownLevel::getDefaultLevelId()]['LEVEL_NAME'];
                     },
                     'valueOther' => [
                         'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
@@ -229,7 +255,7 @@ class IndexList extends \common\libs\dataList\DataList implements DataListInterf
                     'headerOther' => ['width' => '150'],
                 ],
                 'IS_DEC' => [
-                    'header' => 'Whether Declaration Center', // 是否报单中心
+                    'header' => 'Whether Stockist', // 是否报单中心
                     'value' => function($row) {
                         return (new YesNo([
                             'value' => $row['IS_DEC'],
@@ -245,7 +271,7 @@ class IndexList extends \common\libs\dataList\DataList implements DataListInterf
                     },
                 ],
                 'IS_ATLAS' => [
-                    'header' => 'Wheter Atlas Display', // 是否显示图谱
+                    'header' => 'Whether Chart Display', // 是否显示图谱
                     'value' => function($row) {
                         return (new YesNo([
                             'value' => $row['IS_ATLAS'],
@@ -263,7 +289,7 @@ class IndexList extends \common\libs\dataList\DataList implements DataListInterf
                     },
                 ],
                 'IS_RECHARGE' => [
-                    'header' => 'Wheter Recharge Display', // 是否显示充值
+                    'header' => 'Whether Recharge Display', // 是否显示充值
                     'value' => function($row) {
                         return (new YesNo([
                             'value' => $row['IS_RECHARGE'],
@@ -356,8 +382,10 @@ class IndexList extends \common\libs\dataList\DataList implements DataListInterf
                 'DEC_LV_NAME'=> ['name'=> 'Real time membership level', 'other'=> 'decLevel'], // 实时会员级别
 //                'DEC_LV_UPDATED_AT'=> ['name'=> '实时调整日期', 'other'=> 'date'],
 //                'LAST_DEC_LV_NAME'=> ['name'=> '结算时会员级别', 'other'=> 'decLevel'],
-                'EMP_LV_NAME'=> ['name'=> 'Real time employment', 'other'=> 'empLevel'], // 实时聘级
-                'CROWN_LV_NAME'=> ['name'=> 'Real time Crown', 'other'=> 'crownLevel'], // 实时聘级
+                'EMP_LV_NAME'=> ['name'=> 'Highest Director', 'other'=> 'empLevel'], // 最高管理星级
+                'LAST_EMP_LV_NAME'=> ['name'=> 'Latest Director', 'other'=> 'empLevel'], // 最新管理星级
+                'CROWN_LV_NAME'=> ['name'=> 'Highest Crown', 'other'=> 'crownLevel'], // 最高皇冠星级
+                'LAST_CROWN_LV_NAME'=> ['name'=> 'Latest Crown', 'other'=> 'crownLevel'], // 最新皇冠星级
 //                'HIGHEST_EMP_LV_NAME'=> ['name'=> '历史最高聘级', 'other'=> 'empLevel'],
 //                'HIGHEST_EMP_LV_PERIOD'=> ['name'=> '首次达到历史最高聘级的期数'],
                 'REC_USER_NAME'=> ['name'=> 'Recommendation No'],//推荐编号
@@ -371,7 +399,7 @@ class IndexList extends \common\libs\dataList\DataList implements DataListInterf
                 'MOBILE'=> ['name'=> 'Phone Number'],//手机号码
 //                'TEL'=> ['name'=> '备用手机号码'],
                 'DEC_USER_NAME'=> ['name'=> 'Stockist Code'], // 所属报单中心编号
-                'IS_DEC'=> ['name'=> 'Declaration center or not', 'other'=> 'yesOrNo'],//是否报单中心
+                'IS_DEC'=> ['name'=> 'Stockist or not', 'other'=> 'yesOrNo'],//是否报单中心
                 'IS_STUDIO'=> ['name'=> 'Studio or not', 'other'=> 'yesOrNo'],//是否工作室
                 'DEC_ROLE_NAME'=> ['name'=> 'Stockist Level', 'other'=> 'decRole'],//报单中心级别
 //                'OPEN_BANK_NAME'=> ['name'=> '开户银行', 'other'=> 'banks'],

+ 6 - 0
backendEle/src/components/FilterUser.vue

@@ -172,6 +172,12 @@ export default {
           valueField: 'ID',
           values: baseInfo.empLevels()
         },
+        crownLevel: {
+          placeholder: 'Select Crown Level', // 请选择聘级
+          labelField: 'LEVEL_NAME',
+          valueField: 'ID',
+          values: baseInfo.crownLevels()
+        },
         decRole: {
           placeholder: 'Select Stockist Level',
           labelField: 'ROLE_NAME',

+ 36 - 0
backendEle/src/router/index.js

@@ -177,6 +177,18 @@ export const constantRouterMap = [
           ],
         },
       },
+      {
+        path: '/shop/ba-order-list',
+        component: _import('shop/ba-order-list'),
+        name: 'ba-order-list',
+        meta: {
+          title: 'Brand Ambassador Order', // BA订单列表
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // Dashboard
+            {title: 'Shopping Mall', path: '/shop/index'} // 商城管理
+          ]
+        }
+      }
     ],
   },
   {
@@ -196,6 +208,18 @@ export const constantRouterMap = [
           ],
         },
       },
+      {
+        path: '/user/ba-user-list',
+        component: _import('user/ba-user-list'),
+        name: 'ba-user-list',
+        meta: {
+          title: 'Brand Ambassador List', // 会员列表
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // Dashboard
+            {title: 'Member management', path: '/user/index'} // 会员管理
+          ]
+        }
+      },
       {
         path: '/user/user-add-opt',
         component: _import('user/user-add-opt'),
@@ -1146,6 +1170,18 @@ export const constantRouterMap = [
           ],
         },
       },
+      {
+        path: '/bonus/perf-adjustment',
+        component: _import('bonus/perf-adjustment'),
+        name: 'bonus-perf-adjustment',
+        meta: {
+          title: 'Adjust Performance', // 业绩调整
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // Dashboard
+            {title: 'Bonus Management', path: '/bonus/period'}, // 奖金管理
+          ],
+        },
+      },
       {
         path: '/bonus/perf-standard',
         component: _import('bonus/perf-standard'),

+ 3 - 0
backendEle/src/utils/baseInfo.js

@@ -25,6 +25,9 @@ const baseInfo = {
   empLevels () {
     return this.get('empLevels')
   },
+  crownLevels () {
+    return this.get('crownLevels')
+  },
   regTypes () {
     return this.get('regTypes')
   },

+ 1 - 1
backendEle/src/utils/config_trial.js

@@ -11,7 +11,7 @@ const ACCESS_TOKEN_PREFIX = 'Bearer '
 const CDN_BASE_URL = 'http://16.163.228.151:8036'
 const CDN_IMG_URL = `${CDN_BASE_URL}/cdn/`
 const PRICE_IS_ROUND = true
-const FRONTEND_SERVER = 'http://16.163.228.151:8035'
+const FRONTEND_SERVER = 'http://16.163.228.151:8033'
 const REGION_URL = `${CDN_BASE_URL}/cdn/jsdata/ar_region_data.js?ver=0.1`
 
 export {

+ 13 - 1
backendEle/src/utils/index.js

@@ -34,6 +34,18 @@ module.exports = {
         cssSourceMap: true
     },
 
+    trial: {
+        env: require('./trial.env'),
+        index: path.resolve(__dirname, '../dist/trial/index.html'),
+        assetsRoot: path.resolve(__dirname, '../dist/trial'),
+        assetsSubDirectory: 'static',
+        assetsPublicPath: '/',
+        productionSourceMap: true,
+        productionGzip: false,
+        productionGzipExtensions: ['js', 'css'],
+        bundleAnalyzerReport: process.env.npm_config_report,
+    },
+
     build: {
         // Template for index.html
         index: path.resolve(__dirname, '../dist/index.html'),
@@ -59,4 +71,4 @@ module.exports = {
         // Set to `true` or `false` to always turn it on or off
         bundleAnalyzerReport: process.env.npm_config_report
     }
-}
+}

+ 2 - 1
backendEle/src/utils/vuexStore.js

@@ -13,6 +13,7 @@ const moduleBaseInfo = {
   state: {
     decLevels: null,
     empLevels: null,
+    crownLevels: null,
     adminRoles: null,
     menu: null,
     daysDiff: null,
@@ -38,4 +39,4 @@ export default new Vuex.Store({
     baseInfo: moduleBaseInfo,
     regionInfo: moduleRegionInfo,
   }
-})
+})

+ 0 - 0
backendEle/src/views/article/detail.vue


+ 1 - 1
backendEle/src/views/atlas/network-opt.vue

@@ -27,7 +27,7 @@
                 <el-tag>Name<!-- 姓名 -->:{{data.REAL_NAME}}</el-tag>
                 <el-tag type="danger"><!-- 区位 -->Location:{{data.RELATIVE_LOCATION}}</el-tag>
                 <el-tag type="success"><!-- 级别 -->Level:{{data.DEC_LV_NAME}}</el-tag>
-                <el-tag type="warning"><!-- 聘级 -->Rank:{{data.EMP_LV_NAME}}, {{data.CROWN_LV_NAME}}</el-tag>
+                <el-tag type="warning"><!-- 聘级 -->Highest:{{data.EMP_LV_NAME}}, {{data.CROWN_LV_NAME}}</el-tag>
                 <el-tag><!-- 加入期数 -->Joining Period:{{data.PERIOD_AT}}</el-tag>
               </span>
             </span>

+ 1 - 1
backendEle/src/views/atlas/relation-opt.vue

@@ -26,7 +26,7 @@
                       <el-tag><!-- 会员编号 -->Member Code:{{ node.label }}</el-tag>
                       <el-tag type="success">Name<!-- 姓名 -->:{{data.REAL_NAME}}</el-tag>
                       <el-tag type="warning">Level<!-- 级别 -->:{{data.DEC_LV_NAME}}</el-tag>
-                      <el-tag type="warning">Rank:<!-- 聘级 -->{{data.EMP_LV_NAME}}, {{data.CROWN_LV_NAME}}</el-tag>
+                      <el-tag type="warning">Highest:<!-- 聘级 -->{{data.EMP_LV_NAME}}, {{data.CROWN_LV_NAME}}</el-tag>
 <!--                      <el-tag type="warning">Star:&lt;!&ndash; 星级 &ndash;&gt;{{data.CROWN_LV_NAME}}</el-tag>-->
                     </span>
                 </span>

+ 148 - 0
backendEle/src/views/bonus/perf-adjustment.vue

@@ -0,0 +1,148 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <div class="filter-user" @keyup.enter="getData()">
+        <el-input v-model="memberCode" size="small" style="width:400px;">
+          <template slot="prepend">Member Code</template>
+        </el-input>
+        <el-button type="primary" icon="el-icon-search" size="small" @click="getData()">Confirm<!-- 确定 --></el-button>
+      </div>
+
+      <div style="margin-top: 25px;" v-show="show">
+        <el-row>
+          <el-col :span="16">
+            <div class="grid-content bg-purple" style="width: 100%">
+              <el-card class="box-card" shadow="hover">
+                <el-form :model="perfForm" status-icon ref="perfForm" label-width="250px" width="100%" class="demo-ruleForm">
+                  <el-form-item label="Member Code" prop="USER_NAME" v-show="false">
+                    <el-input type="text" size="small" v-model="perfForm.USER_ID"></el-input>
+                    <el-input type="text" size="small" v-model="perfForm.USER_NAME"></el-input>
+                  </el-form-item>
+
+                  <el-divider><span style="font-weight: bold;">L. Market Balance Performance</span></el-divider>
+                  <el-form-item label="Member Code" prop="SURPLUS_1L_USER_NAME"><!--会员编号-->
+                    <el-input type="text" size="small" v-model="perfForm.SURPLUS_1L_USER_NAME" autocomplete="off" readonly></el-input>
+                  </el-form-item>
+                  <el-form-item label="Balance Performance" prop="SURPLUS_1L"><!--综合结余业绩-->
+                    <el-input type="text" size="small" v-model="perfForm.SURPLUS_1L" autocomplete="off"></el-input>
+                  </el-form-item>
+                  <el-form-item label="Entry Balance Performance" prop="SURPLUS_1L_ZC"><!--首单结余业绩-->
+                    <el-input type="text" size="small" v-model="perfForm.SURPLUS_1L_ZC" autocomplete="off"></el-input>
+                  </el-form-item>
+                  <el-form-item label="Reconditioning Balance Performance" prop="SURPLUS_1L_FX"><!--复消结余业绩-->
+                    <el-input type="text" size="small" v-model="perfForm.SURPLUS_1L_FX" autocomplete="off"></el-input>
+                  </el-form-item>
+
+                  <el-divider><span style="font-weight: bold;">R. Market Balance Performance</span></el-divider>
+                  <el-form-item label="Member Code" prop="SURPLUS_2L_USER_NAME"><!--会员编号-->
+                    <el-input type="text" size="small" v-model="perfForm.SURPLUS_2L_USER_NAME" autocomplete="off" readonly></el-input>
+                  </el-form-item>
+                  <el-form-item label="Balance Performance" prop="SURPLUS_2L"><!--综合结余业绩-->
+                    <el-input type="text" size="small" v-model="perfForm.SURPLUS_2L" autocomplete="off"></el-input>
+                  </el-form-item>
+                  <el-form-item label="Entry Balance Performance" prop="SURPLUS_2L_ZC">
+                    <el-input type="text" size="small" v-model="perfForm.SURPLUS_2L_ZC" autocomplete="off"></el-input>
+                  </el-form-item>
+                  <el-form-item label="Reconditioning Balance Performance" prop="SURPLUS_2L_FX"><!--复消结余业绩-->
+                    <el-input type="text" size="small" v-model="perfForm.SURPLUS_2L_FX" autocomplete="off"></el-input>
+                  </el-form-item>
+
+                  <el-form-item>
+                    <el-button type="primary" size="small" @click="handlePerfAdjustment('perfForm')">Save</el-button>
+                  </el-form-item>
+                </el-form>
+              </el-card>
+            </div>
+          </el-col>
+        </el-row>
+      </div>
+    </div>
+  </div>
+</template>
+
+<script>
+import network from '@/utils/network'
+
+export default {
+  name: 'bonus-perf-adjustment',
+  data() {
+    return {
+      loading: false,
+      memberCode: '',
+      show: false,
+      perfForm: {
+        USER_ID: '',
+        USER_NAME: '',
+        SURPLUS_1L: '',
+        SURPLUS_1L_ZC: '',
+        SURPLUS_1L_FX: '',
+        SURPLUS_21L_USER_NAME: '',
+        SURPLUS_2L: '',
+        SURPLUS_2L_ZC: '',
+        SURPLUS_2L_FX: '',
+        SURPLUS_2L_USER_NAME: '',
+      },
+    }
+  },
+  methods: {
+    // 查询安置网的下级会员和业绩
+    getData() {
+      if (!this.memberCode.length) {
+        this.$message({
+          message: 'Please enter member code',
+          type: 'info'
+        });
+        return false;
+      }
+
+      // 清除上一次的填充结果
+      this.$refs['perfForm'].resetFields();
+      this.show = false;
+
+      return network.getData(`bonus/perf-adjustment`, { memberCode : this.memberCode }).then(response => {
+        this.perfForm = response.allData;
+        this.show = true;
+        this.loading = false;
+      }).catch(error => {
+        this.$message({
+          message: error,
+          type: 'warning'
+        });
+
+        this.loading = false;
+      })
+    },
+    // 修改会员业绩
+    handlePerfAdjustment(formName) {
+      this.$confirm('Confirm and revise member performance?', 'Hits', { // 确认修改会员业绩
+        confirmButtonText: 'Confirm',
+        cancelButtonText: 'Cancel',
+        type: 'warning'
+      }).then(() => {
+        this.loading = true;
+        return network.postData(`bonus/perf-adjustment`, this.perfForm).then(response => {
+          this.$message({
+            message: response,
+            type: 'success'
+          });
+          this.loading = false;
+
+          // 刷新数据
+          this.getData();
+        }).catch(error => {
+          this.$message({
+            message: error,
+            type: 'warning'
+          });
+          this.loading = false;
+        });
+      })
+    },
+  }
+}
+</script>
+
+<style>
+  .filter-user { font-size: 14px; margin-bottom: 20px; }
+  .filter-user:after { content: ''; display: table;  clear: both; }
+</style>

+ 2 - 39
backendEle/src/views/config/bonus-opt.vue

@@ -119,46 +119,9 @@
         </div>
       </div>
     </div>
-    <div class="panel" v-if="permission.hasPermission(`config/bonus-dec-level`)">
-      <div class="panel-heading">
-        管理奖
-      </div>
-      <div class="panel-wrapper">
-        <div class="panel-body">
-          <el-table :data="decLevelTableData" stripe style="width: 100%;">
-            <el-table-column prop="LEVEL_NAME" label="级别名称"></el-table-column>
-            <el-table-column label="奇数代数(推广1人)">
-              <template slot-scope="scope">
-                <el-input v-model="scope.row.GL_ODD_DEEP_ONE" min="0" max="100">
-                  <template slot="append">代</template>
-                </el-input>
-              </template>
-            </el-table-column>
-            <el-table-column label="奇数代数(推广2人)">
-              <template slot-scope="scope">
-                <el-input v-model="scope.row.GL_ODD_DEEP_TWO" min="0" max="100">
-                  <template slot="append">代</template>
-                </el-input>
-              </template>
-            </el-table-column>
-            <el-table-column label="奇数代数(推广3人)">
-              <template slot-scope="scope">
-                <el-input v-model="scope.row.GL_ODD_DEEP_THREE" min="0" max="100">
-                  <template slot="append">代</template>
-                </el-input>
-              </template>
-            </el-table-column>
-          </el-table>
-        </div>
-        <div class="panel-footer">
-          <el-button type="primary" @click="onGLSubmit" :loading="glSubmitButtonStat" style="float: right;">保存
-          </el-button>
-        </div>
-      </div>
-    </div>
     <div class="panel" v-if="permission.hasPermission(`config/bonus-emp-level`)">
       <div class="panel-heading">
-        荣衔配置
+        总监级别配置
       </div>
       <div class="panel-wrapper">
         <div class="panel-body">
@@ -217,7 +180,7 @@
 
       <div class="panel" v-if="permission.hasPermission(`config/bonus-star-level`)">
           <div class="panel-heading">
-              星级配置
+            皇冠级别配置
           </div>
           <div class="panel-wrapper">
               <div class="panel-body">

+ 207 - 0
backendEle/src/views/shop/ba-dec-order-list.vue

@@ -0,0 +1,207 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <div class="filter-box">
+        <filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
+      </div>
+      <el-table class="table-box" ref="multipleTable" :data="tableData" stripe style="width: 100%;"
+                @selection-change="handleSelectionChange"
+                :height="tool.getTableHeight()">
+        <el-table-column type="selection" width="70" v-if="tableHeaders"></el-table-column>
+        <el-table-column v-for="(tableHeader, key) in tableHeaders" :key="key" :label="tableHeader.header" :width="tableHeader.other.width ? tableHeader.other.width : ''" :prop="tableHeader.other.prop ? tableHeader.other.prop : null">
+          <template slot-scope="scope">
+            <template v-if="scope.row[tableHeader.index].other.tag" >
+              <el-tag :type="scope.row[tableHeader.index].other.tag.type ? scope.row[tableHeader.index].other.tag.type : null" :size="scope.row[tableHeader.index].other.tag.size ? scope.row[tableHeader.index].other.tag.size : null" :class="scope.row[tableHeader.index].other.tag.class ? scope.row[tableHeader.index].other.tag.class : null" >{{scope.row[tableHeader.index].value}}</el-tag>
+            </template>
+            <template v-else>
+              <div v-html="scope.row[tableHeader.index].value"></div>
+            </template>
+          </template>
+        </el-table-column>
+        <el-table-column fixed="right" label="操作" width="180">
+          <template slot-scope="scope">
+            <el-dropdown size="small" trigger="click">
+              <el-button type="primary" size="small" @click.stop="">
+                操作该数据<i class="el-icon-arrow-down el-icon--right"></i>
+              </el-button>
+              <el-dropdown-menu slot="dropdown">
+                <el-dropdown-item command="edit" @click.native="handleDel(scope.row)">Delete order</el-dropdown-item>
+              </el-dropdown-menu>
+            </el-dropdown>
+          </template>
+        </el-table-column>
+      </el-table>
+      <div class="white-box-footer">
+        <el-button type="success" size="small" @click="handleExport" v-show="permission.hasPermission(`shop/dec-order-list-export`)">Export Excel</el-button>
+        <el-button type="primary" size="small" @click="handleExportPDF" v-show="permission.hasPermission(`shop/dec-order-list-export`)">Export PDF</el-button>
+          <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange"
+                    @current-change="handleCurrentChange"></pagination>
+      </div>
+    </div>
+  </div>
+</template>
+
+<script>
+  import network from '@/utils/network'
+  import tool from '@/utils/tool'
+  import baseInfo from '@/utils/baseInfo'
+  import FilterUser from '@/components/FilterUser'
+  import permission from '@/utils/permission'
+  import Pagination from '@/components/Pagination'
+  import filterHelper from '@/utils/filterHelper'
+
+  export default {
+    name: 'shop_dec-order-list',
+    components: {FilterUser, Pagination},
+    mounted() {
+      this.getData()
+    },
+    data() {
+      return {
+        tableHeaders: null,
+        tableData: null,
+        tableHeight: window.innerHeight - 310,
+        loading: true,
+        multipleSelection: [],
+        currentPage: 1,
+        totalPages: 1,
+        totalCount: 1,
+        pageSize: 20,
+        tool: tool,
+        permission: permission,
+        baseDecLevels: baseInfo.decLevels(),
+        baseEmpLevels: baseInfo.empLevels(),
+        filterTypes: null,
+        filterModel: {},
+        dialogVisible: false,
+        dialogLoading: false,
+        statuses: null,
+        form: {
+          selectedIds: [],
+          statusValue: [],
+          sendType: null,
+          remark: null,
+        },
+      }
+    },
+    methods: {
+      handleSelectionChange(val) {
+        this.multipleSelection = val
+      },
+      handleCurrentChange(page) {
+        this.getData(page, this.pageSize)
+      },
+      handleSizeChange(pageSize) {
+        this.getData(this.currentPage, pageSize)
+      },
+      handleFilterUser(filterData) {
+        filterHelper.handleFilterUser(this, filterData)
+      },
+      getData(page, pageSize) {
+        let filterData = this.filterModel
+        network.getPageData(this, 'shop/dec-order-list', page, pageSize, filterData, response => {
+            console.log(response)
+          this.filterTypes = response.filterTypes
+          this.allData = response
+        })
+      },
+      handleExport(){
+        this.$confirm(`Are you sure you want to export the current data?`, 'Hint', {//`确定要导出当前数据吗?`, '提示'
+          confirmButtonText: 'Confirm',//确认
+          cancelButtonText: 'Cancel',//取消
+          type: 'warning'
+        }).then(() => {
+          return network.getData(`shop/dec-order-list-export`, this.filterModel)
+        }).then(response => {
+          this.$message({
+            message: response,
+            type: 'success'
+          })
+        }).catch(response => {
+
+        })
+      },
+      handleShowDeliveryDialog(row) {
+        this.dialogDeliveryVisible = true
+        this.deliveryForm.sn = row['SN'].value
+      },
+      handleDel(row) {
+        let orderSn = row.ORDER_SN.value // order订单表的编号
+        let detailType = row.DETAIL_TYPE // 默认为1注册  2为升级
+        let upgradeType = row.UPGRADE_TYPE //默认0 1 补差额升级  2全额升级
+        this.$confirm(`确定要删除订单:${orderSn}吗?`, '提示', {
+          confirmButtonText: 'Confirm',
+          cancelButtonText: 'Cancel',
+          type: 'warning'
+        }).then(() => {
+          // 删除订单
+        let postData = {
+            orderSn,
+            detailType,
+            upgradeType
+          }
+          return network.postData('shop/delete-order', postData).then(response => {
+              console.log(response);
+              this.$message({
+                  message: response,
+                  type: 'success'
+              })
+              this.submitButtonStat = false
+              // this.$router.go(-1)
+          }).catch(() => {
+              this.submitButtonStat = false
+          })
+        }).then(response => {
+
+        }).catch(response => {
+
+        })
+      },
+        handleExportPDF() {
+            if (this.multipleSelection.length === 0) {
+                this.$message({
+                    message: 'Please select an order to export',//请选择一条订单导出
+                    type: 'error'
+                })
+                return false
+            }
+
+            // 提取订单ID
+            let orderSnList = this.multipleSelection.map((item) => item.SN.value || '');
+            // 去重
+            let orderSnSet = Array.from(new Set(orderSnList))
+            if (orderSnSet.length !== 1) {
+                this.$message({
+                    message: 'Only one order can be exported at a time',//每次只能导出一条订单
+                    type: 'error'
+                })
+                return false
+            }
+
+            this.$confirm(`Are you sure you want to export the current data?`, 'Hint', {//`确定要导出当前数据吗?`, '提示',
+                confirmButtonText: 'Confirm',//确认
+                cancelButtonText: 'Cancel',//取消
+                type: 'warning'
+            }).then(() => {
+                // 导出时只需要订单ID即可
+                let orderSn = orderSnSet[0]
+                network.getData(`shop/dec-order-list-export-pdf/${orderSn}`).then(response => {
+                    this.$message({
+                        message: response,
+                        type: 'success'
+                    })
+                })
+            }).catch(response => {
+                this.$message({
+                    message: response,
+                    type: 'error'
+                })
+            })
+        },
+    }
+  }
+
+</script>
+
+<style scoped>
+</style>

+ 144 - 0
backendEle/src/views/shop/ba-order-list.vue

@@ -0,0 +1,144 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <div class="filter-box">
+        <filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
+      </div>
+      <el-table class="table-box" ref="multipleTable" :data="tableData" stripe style="width: 100%;" @selection-change="handleSelectionChange" :height="tool.getTableHeight()">
+        <el-table-column type="selection" width="70" v-if="tableHeaders"></el-table-column>
+        <el-table-column v-for="(tableHeader, key) in tableHeaders" :key="key" :label="tableHeader.header" :width="tableHeader.other.width ? tableHeader.other.width : ''" :prop="tableHeader.other.prop ? tableHeader.other.prop : null">
+          <template slot-scope="scope">
+            <template v-if="scope.row[tableHeader.index].other.tag" >
+              <el-tag :type="scope.row[tableHeader.index].other.tag.type ? scope.row[tableHeader.index].other.tag.type : null" :size="scope.row[tableHeader.index].other.tag.size ? scope.row[tableHeader.index].other.tag.size : null" :class="scope.row[tableHeader.index].other.tag.class ? scope.row[tableHeader.index].other.tag.class : null" >{{scope.row[tableHeader.index].value}}</el-tag>
+            </template>
+            <template v-else>
+              <div v-html="scope.row[tableHeader.index].value"></div>
+            </template>
+          </template>
+        </el-table-column>
+      </el-table>
+      <div class="white-box-footer">
+        <el-button type="success" size="small" @click="handleExport" v-show="permission.hasPermission(`shop/ba-order-list-export`)">Export Excel</el-button>
+        <el-button type="primary" size="small" @click="handleExportPDF" v-show="permission.hasPermission(`shop/ba-order-list-export`)">Export PDF</el-button>
+        <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
+      </div>
+    </div>
+  </div>
+</template>
+
+<script>
+import network from '@/utils/network'
+import tool from '@/utils/tool'
+import baseInfo from '@/utils/baseInfo'
+import FilterUser from '@/components/FilterUser'
+import permission from '@/utils/permission'
+import Pagination from '@/components/Pagination'
+import filterHelper from '@/utils/filterHelper'
+
+export default {
+  name: 'ba-order-list',
+  components: {FilterUser, Pagination},
+  mounted () {
+    this.getData()
+  },
+  data () {
+    return {
+      tableHeaders: null,
+      tableData: null,
+      tableHeight: window.innerHeight - 310,
+      loading: true,
+      multipleSelection: [],
+      currentPage: 1,
+      totalPages: 1,
+      totalCount: 1,
+      pageSize: 20,
+      tool: tool,
+      permission: permission,
+      filterTypes: null,
+      filterModel: {},
+    }
+  },
+  methods: {
+    handleSelectionChange (val) {
+      this.multipleSelection = val
+    },
+    handleCurrentChange (page) {
+      this.getData(page, this.pageSize)
+    },
+    handleSizeChange (pageSize) {
+      this.getData(this.currentPage, pageSize)
+    },
+    handleFilterUser (filterData) {
+      filterHelper.handleFilterUser(this, filterData)
+    },
+    getData (page, pageSize) {
+      let filterData = this.filterModel
+      network.getPageData(this, 'shop/ba-order-list', page, pageSize, filterData, response => {
+        this.filterTypes = response.filterTypes
+        this.allData = response
+      })
+    },
+    handleExport () {
+      this.$confirm(`Are you sure you want to export the current data?`, 'Hint', { // `确定要导出当前数据吗?`, '提示'
+        confirmButtonText: 'Confirm', // 确定
+        cancelButtonText: 'Cancel', // 取消
+        type: 'warning'
+      }).then(() => {
+        return network.getData(`shop/ba-order-list-export`, this.filterModel)
+      }).then(response => {
+        this.$message({
+          message: response,
+          type: 'success'
+        })
+      }).catch(response => {
+
+      })
+    },
+    handleExportPDF () {
+      if (this.multipleSelection.length === 0) {
+        this.$message({
+          message: 'Please select an order to export', // 请选择一条订单导出
+          type: 'error'
+        })
+        return false
+      }
+
+      // 提取订单ID
+      let orderSnList = this.multipleSelection.map((item) => item.SN.value || '')
+      // 去重
+      let orderSnSet = Array.from(new Set(orderSnList))
+      if (orderSnSet.length !== 1) {
+        this.$message({
+          message: 'Only one order can be exported at a time', // 每次只能导出一条订单
+          type: 'error'
+        })
+        return false
+      }
+
+      this.$confirm(`Are you sure you want to export the current data?`, 'Hint', { // `确定要导出当前数据吗?`, '提示'
+        confirmButtonText: 'Confirm', // 确定
+        cancelButtonText: 'Cancel', // 取消
+        type: 'info'
+      }).then(() => {
+        // 导出时只需要订单ID即可
+        let orderSn = orderSnSet[0]
+        network.getData(`shop/ba-order-list-export-pdf/${orderSn}`).then(response => {
+          this.$message({
+            message: response,
+            type: 'success'
+          })
+        })
+      }).catch(response => {
+        this.$message({
+          message: response,
+          type: 'error'
+        })
+      })
+    },
+  }
+}
+
+</script>
+
+<style scoped>
+</style>

+ 0 - 0
backendEle/src/views/shop/flow-remain-pv.vue


+ 0 - 0
backendEle/src/views/shop/remain-pv.vue


+ 345 - 0
backendEle/src/views/user/ba-user-list.vue

@@ -0,0 +1,345 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <div class="filter-box">
+        <filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
+      </div>
+      <el-table ref="wrapper" :data="tableData" stripe style="width: 100%;" @selection-change="handleSelectionChange" :height="tool.getTableHeight()">
+        <el-table-column fixed type="selection" width="55" v-if="tableHeaders"></el-table-column>
+        <el-table-column v-for="(tableHeader, key) in tableHeaders" :key="key" :label="tableHeader.header"
+            :width="tableHeader.other.width ? tableHeader.other.width : ''" :fixed="tableHeader.index=='USER_NAME' || tableHeader.index=='REAL_NAME' ?true:false">
+          <template slot-scope="scope">
+            <template v-if="scope.row[tableHeader.index].other.tag">
+              <el-tag
+                  :type="scope.row[tableHeader.index].other.tag.type ? scope.row[tableHeader.index].other.tag.type : null"
+                  :size="scope.row[tableHeader.index].other.tag.size ? scope.row[tableHeader.index].other.tag.size : null"
+                  :class="scope.row[tableHeader.index].other.tag.class ? scope.row[tableHeader.index].other.tag.class : null">
+                {{scope.row[tableHeader.index].value}}
+              </el-tag>
+            </template>
+            <template v-else>
+              <template v-if="tableHeader.index === 'USER_NAME'">
+<!--                <el-dropdown v-if="permission.hasPermission(`user/login-to-frontend`)">-->
+                  <span class="el-dropdown-link">
+                    {{scope.row.USER_NAME.value}} <!--<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
+                  </span>
+<!--                  <el-dropdown-menu slot="dropdown">-->
+<!--                    <el-dropdown-item command="login" v-show="scope.row.BTF_URL !== null">-->
+<!--                      <a :href="`${frontendServer}/#/login-by-backend?${scope.row.BTF_URL}`" target="_blank" style="color:#606266;">-->
+<!--                        Quick logon&lt;!&ndash; 快速登录 &ndash;&gt;-->
+<!--                      </a>-->
+<!--                    </el-dropdown-item>-->
+<!--                  </el-dropdown-menu>-->
+<!--                </el-dropdown>-->
+<!--                <el-tag type="primary" size="small" class="no-border" v-if="!permission.hasPermission(`user/login-to-frontend`)">-->
+<!--                  {{scope.row.USER_NAME.value}}-->
+<!--                </el-tag>-->
+              </template>
+              <template v-else>
+                <div v-html="scope.row[tableHeader.index].value"></div>
+              </template>
+            </template>
+          </template>
+        </el-table-column>
+        <el-table-column fixed="right" label="Action" width="180"><!-- 操作 -->
+          <template slot-scope="scope">
+            <el-dropdown size="small" trigger="click">
+              <el-button type="primary" size="small" @click.stop="">
+                Action<!-- 操作该数据 --><i class="el-icon-arrow-down el-icon--right"></i>
+              </el-button>
+              <el-dropdown-menu slot="dropdown">
+                <el-dropdown-item @click.native="handleModifyPassword(scope.row)" v-if="permission.hasPermission(`user/ba-modify-password`)">
+                  Change Password<!-- 修改密码 -->
+                </el-dropdown-item>
+                <el-dropdown-item @click.native="handleModifyProfile(scope.row)" v-if="permission.hasPermission(`user/ba-modify-profile`)">
+                  Modify personal data<!-- 修改个人资料 -->
+                </el-dropdown-item>
+                <el-dropdown-item @click.native="handleStatusActive(scope.row)" v-if="permission.hasPermission(`user/ba-modify-status`)">
+                  Status activation<!-- 状态激活 -->
+                </el-dropdown-item>
+                <el-dropdown-item @click.native="handleStatusLock(scope.row)" v-if="permission.hasPermission(`user/ba-modify-status`)">
+                  Status lock<!-- 状态锁定 -->
+                </el-dropdown-item>
+                <el-dropdown-item @click.native="handleIsModifyPassword(scope.row, 1)" v-if="permission.hasPermission(`user/ba-is-modify-password-status`)">
+                  Open password modification<!-- 开启密码修改 -->
+                </el-dropdown-item>
+                <el-dropdown-item @click.native="handleIsModifyPassword(scope.row, 0)" v-if="permission.hasPermission(`user/ba-is-modify-password-status`)">
+                  Turn off password modification<!-- 关闭密码修改 -->
+                </el-dropdown-item>
+              </el-dropdown-menu>
+            </el-dropdown>
+          </template>
+        </el-table-column>
+      </el-table>
+      <div class="white-box-footer">
+        <el-button type="success" size="small" @click="handleExport" v-show="permission.hasPermission(`user/ba-user-list`)">
+          Export Excel
+        </el-button>
+        <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
+      </div>
+    </div>
+    <el-dialog :title="formModifyPassword.typeName" :visible.sync="dialogModifyPasswordVisible" width="50%">
+      <el-form ref="form" :model="formModifyPassword" label-width="120px" class="form-dialog">
+        <el-form-item label="type"><!-- 类型 -->
+          <el-select v-model="formModifyPassword.passwordType" placeholder="Please select a type"><!-- 请选择类型 -->
+            <el-option v-for="(item,key) in passwordType" :label="item.label" :value="item.type" :key="key"></el-option>
+          </el-select>
+        </el-form-item>
+        <el-form-item label="password"><!-- 密码 -->
+          <el-input placeholder="password" v-model="formModifyPassword.password"><!-- 密码 --></el-input>
+        </el-form-item>
+        <el-form-item>
+          <el-button type="primary" @click="handleModifyPasswordSubmit" :loading="submitPasswordButtonStat">Submit<!-- 提交 --></el-button>
+        </el-form-item>
+      </el-form>
+    </el-dialog>
+
+    <el-dialog :title="formModifyProfile.typeName" :visible.sync="dialogModifyProfileVisible" width="50%">
+      <el-form ref="form" :model="formModifyProfile" label-width="150px" class="form-dialog">
+        <el-form-item label="Member name"><!-- 会员姓名 -->
+          <el-input v-model="formModifyProfile.realName"></el-input>
+        </el-form-item>
+<!--        <el-form-item label="Identity No.">&lt;!&ndash; 身份证号 &ndash;&gt;-->
+<!--          <el-input v-model="formModifyProfile.idCard"></el-input>-->
+<!--        </el-form-item>-->
+        <el-form-item label="Phone Number"><!-- 手机号 -->
+          <el-input v-model="formModifyProfile.mobile"></el-input>
+        </el-form-item>
+<!--        <el-form-item label="Bank name">&lt;!&ndash; 银行名称 &ndash;&gt;-->
+<!--          <el-select v-model="formModifyProfile.openBank" placeholder="Please select a bank name">&lt;!&ndash; 请选择银行名称 &ndash;&gt;-->
+<!--            <el-option v-for="(item,index) in allOpenBank" :key="index" :label="item.BANK_NAME" :value="item.BANK_CODE"></el-option>-->
+<!--          </el-select>-->
+<!--        </el-form-item>-->
+<!--        <el-form-item label="Bank Address">&lt;!&ndash; 开户行地址 &ndash;&gt;-->
+<!--          <el-input v-model="formModifyProfile.bankAddress"></el-input>-->
+<!--        </el-form-item>-->
+<!--        <el-form-item label="Bank account number">&lt;!&ndash; 银行帐号 &ndash;&gt;-->
+<!--          <el-input v-model="formModifyProfile.bankNo"></el-input>-->
+<!--        </el-form-item>-->
+        <el-form-item>
+          <el-button type="primary" @click="handleModifyProfileSubmit" :loading="submitProfileButtonStat">
+            Submit<!-- 提交 -->
+          </el-button>
+        </el-form-item>
+      </el-form>
+    </el-dialog>
+  </div>
+</template>
+
+<script>
+import network from '../../utils/network'
+import tool from '../../utils/tool'
+import {FRONTEND_SERVER} from '@/utils/config'
+import baseInfo from '@/utils/baseInfo'
+import FilterUser from '../../components/FilterUser'
+import store from '../../utils/vuexStore'
+import permission from '@/utils/permission'
+import Pagination from '@/components/Pagination'
+import filterHelper from '../../utils/filterHelper'
+
+export default {
+  name: 'ba-user-list',
+  components: {FilterUser, Pagination},
+  mounted () {
+    let _this = this
+    _this.getData()
+    store.state.socket.onMessageCallback = this.onMessageCallback
+  },
+  data () {
+    return {
+      tableHeaders: null,
+      tableData: null,
+      loading: true,
+      multipleSelection: [],
+      currentPage: 1,
+      totalPages: 1,
+      totalCount: 1,
+      pageSize: 20,
+      frontendServer: FRONTEND_SERVER,
+      tool: tool,
+      permission: permission,
+      filterTypes: null,
+      filterModel: {},
+      dialogVisible: false,
+      formCloseLogin: {
+        userName: null,
+        typeName: 'Login management', // 登录管理
+        type: null,
+        isClose: 0,
+        remark: '',
+        areaSelected: null
+      },
+      regionDataPlus: store.state.regionInfo.regionData,
+      apps: null,
+      closeSwitch: null,
+      submitButtonStat: false,
+      dialogDecVisible: false,
+      dialogModifyPasswordVisible: false,
+      dialogModifyProfileVisible: false,
+      formCloseDec: {
+        userName: null,
+        typeName: 'Manage entry', // 管理报单
+        type: null,
+        isClose: 0,
+        remark: '',
+        areaSelected: null
+      },
+      formModifyPassword: {
+        userId: '',
+        password: '',
+        typeName: 'Change Password', // 修改密码
+        passwordType: 'password'
+        // remark: '',
+      },
+      formModifyProfile: {
+        userId: '',
+        typeName: 'Modify personal data', // 修改个人资料
+        // nation: '',
+        realName: '',
+        // idCard: '',
+        mobile: '',
+        // openBank: '',
+        // bankAddress: '',
+        // bankNo: ''
+      },
+      passwordType: [
+        {
+          type: 'password',
+          label: 'login password' // 登录密码
+        },
+        {
+          type: 'payPassword',
+          label: 'Payment password' // 支付密码
+        }
+      ],
+      // allOpenBank: null,
+      // allNation: null,
+      submitDecButtonStat: false,
+      submitPasswordButtonStat: false,
+      submitProfileButtonStat: false,
+      transferPropForm: {
+        userIds: [],
+        allowTransfer: true,
+        transferProp: 100,
+        withdrawProp: 0,
+        remark: ''
+      },
+      closeUserData: null
+    }
+  },
+  methods: {
+    handleSelectionChange (val) {
+      this.multipleSelection = val
+    },
+    handleCurrentChange (page) {
+      this.getData(page, this.pageSize)
+    },
+    handleSizeChange (pageSize) {
+      this.getData(this.currentPage, pageSize)
+    },
+    handleAdd () {
+      this.$router.push('/user/ba-user-add')
+    },
+    handleFilterUser (filterData) {
+      filterHelper.handleFilterUser(this, filterData)
+    },
+    handleFilter () {
+      this.getData()
+    },
+    getData (page, pageSize, isLoading = true) {
+      network.getPageData(this, 'user/ba-user-list', page, pageSize, this.filterModel, response => {
+        this.filterTypes = response.filterTypes
+      }, isLoading)
+    },
+    handleExport () {
+      this.$confirm(`Are you sure you want to export the current data?`, 'Hint', { // (`确定要导出当前数据吗?`, '提示',
+        confirmButtonText: 'confirm', // 确定
+        cancelButtonText: 'cancel', // 取消
+        type: 'warning'
+      }).then(() => {
+        return network.getData(`user/ba-user-list-export`, this.filterModel)
+      }).then(response => {
+        this.$message({
+          message: response,
+          type: 'success'
+        })
+      }).catch(response => {
+
+      })
+    },
+    onMessageCallback (data) {
+    },
+    handleModifyPassword (row) {
+      this.formModifyPassword.userId = row.USER_ID
+      this.dialogModifyPasswordVisible = true
+    },
+    handleModifyProfile (row) {
+      this.dialogModifyProfileVisible = true
+      let vueObj = this
+      network.getData('user/ba-profile-get', {id: row.USER_ID}).then(response => {
+        vueObj.formModifyProfile = response.userInfo
+        // vueObj.allOpenBank = response.allOpenBank
+        // vueObj.allNation = response.allNation
+      })
+    },
+    handleStatusActive (row) {
+      network.postData('user/ba-modify-status',{userId: row.USER_ID, status: 1}).then(response => {
+        this.$message({
+          message: response,
+          type: 'success'
+        })
+        this.getData(this.currentPage, this.pageSize)
+      })
+    },
+    handleStatusLock (row) {
+      network.postData('user/ba-modify-status',{userId: row.USER_ID, status: 0}).then(response => {
+        this.$message({
+          message: response,
+          type: 'success'
+        })
+        this.getData(this.currentPage, this.pageSize)
+      })
+    },
+    handleIsModifyPassword (row, status) {
+      network.postData('user/ba-is-modify-password-status',{userId: row.USER_ID, status: status}).then(response => {
+        this.$message({
+          message: response,
+          type: 'success'
+        })
+        this.getData(this.currentPage, this.pageSize)
+      })
+    },
+    handleModifyPasswordSubmit () {
+      this.submitPasswordButtonStat = true
+      let path = 'user/ba-modify-password'
+      network.postData(path, this.formModifyPassword).then(response => {
+        this.$message({
+          message: response,
+          type: 'success'
+        })
+        this.getData(this.currentPage, this.pageSize)
+        this.submitPasswordButtonStat = false
+        this.dialogModifyPasswordVisible = false
+      }).catch(response => {
+        this.submitPasswordButtonStat = false
+      })
+    },
+    handleModifyProfileSubmit () {
+      this.submitProfileButtonStat = true
+      let path = 'user/ba-modify-profile'
+      network.postData(path, this.formModifyProfile).then(response => {
+        this.$message({
+          message: response,
+          type: 'success'
+        })
+        this.getData(this.currentPage, this.pageSize)
+        this.submitProfileButtonStat = false
+        this.dialogModifyProfileVisible = false
+      }).catch(response => {
+        this.submitProfileButtonStat = false
+      })
+    }
+  }
+}
+
+</script>

+ 1 - 1
backendEle/src/views/user/empty-list.vue

@@ -364,7 +364,7 @@
                 })
                 return
             }
-            let isAtlasTip = isAtlas === true ? 'show atlas': 'hide atlas'//'显示图谱' : '隐藏图谱'
+            let isAtlasTip = isAtlas === true ? 'show chart': 'hide chart'//'显示图谱' : '隐藏图谱'
             this.$confirm(`Are you sure you want to【${isAtlasTip}】?`, 'Hint', {//`确定要对所选会员【${isAtlasTip}】吗?`, '提示'
                 confirmButtonText: 'confirm', // 确定
                 cancelButtonText: 'cancel', // 取消

+ 4 - 4
backendEle/src/views/user/index.vue

@@ -111,10 +111,10 @@
         <!--</el-dropdown>-->
         <el-dropdown size="small" trigger="click" v-show="permission.hasPermission(`user/is-dec`)">
           <el-button type="primary" size="small" @click.stop="">
-            Declaration Center Management<!-- 报单中心管理 --><i class="el-icon-arrow-down el-icon--right"></i>
+            Stockist Management<!-- 报单中心管理 --><i class="el-icon-arrow-down el-icon--right"></i>
           </el-button>
           <el-dropdown-menu slot="dropdown">
-            <el-dropdown-item command="isDec" @click.native="handleIsDecManage(true)">Set as declaration Center<!-- 设为报单中心 --></el-dropdown-item>
+            <el-dropdown-item command="isDec" @click.native="handleIsDecManage(true)">Set as Stockist<!-- 设为报单中心 --></el-dropdown-item>
             <el-dropdown-item command="notDec" @click.native="handleIsDecManage(false)">Cancel Stockist<!-- 取消报单中心 -->
             </el-dropdown-item>
           </el-dropdown-menu>
@@ -430,7 +430,7 @@
               })
               return
           }
-          let isDecTip = isDec === true ? 'Set as declaration Center' : 'Cancel Stockist'//'设为报单中心' : '取消报单中心'
+          let isDecTip = isDec === true ? 'Set as Stockist' : 'Cancel Stockist'//'设为报单中心' : '取消报单中心'
           this.$confirm(`Are you sure you want to【${isDecTip}】?`, 'Hint', {//确定要对所选会员【${isDecTip}】吗?`, '提示'
               confirmButtonText: 'confirm', // 确定
               cancelButtonText: 'cancel', // 取消
@@ -488,7 +488,7 @@
                 })
                 return
             }
-            let isAtlasTip = isAtlas === true ? 'Display Atlas' : 'Hidden Atlas'//'显示图谱' : '隐藏图谱'
+            let isChartTip = isAtlas === true ? 'Display Chart' : 'Hidden Chart'//'显示图谱' : '隐藏图谱'
             this.$confirm(`Are you sure you want to【${isAtlasTip}】?`, 'Hint', {//`确定要对所选会员【${isAtlasTip}】吗?`, '提示'
                 confirmButtonText: 'confirm', // 确定
                 cancelButtonText: 'cancel', // 取消

+ 1 - 1
backendEle/src/views/user/user-add-opt.vue

@@ -24,7 +24,7 @@
                            :value="item.ID"></el-option>
               </el-select>
             </el-form-item>
-            <el-form-item label="Declaration center or not"><!-- 是否报单中心 -->
+            <el-form-item label="Stockist or not"><!-- 是否报单中心 -->
               <el-switch v-model="form.isDec"></el-switch>
             </el-form-item>
             <el-form-item label="Stockist Level" v-show="form.isDec"><!-- 报单中心级别 -->

+ 1 - 1
common/helpers/Excel.php

@@ -807,7 +807,7 @@ class Excel extends BaseObject {
         }
         $fileNameArray = ExcelImport::find()->select('U.FILE_NAME')->from(ExcelImport::tableName() . ' AS ET')->join('LEFT JOIN', Uploads::tableName() . ' AS U', 'ET.UPLOAD_ID=U.ID')->where('ET.ID=:ID', [':ID' => $excelImportId])->asArray()->one();
 //        $filePath = \Yii::getAlias('@common/runtime/uploads/' . $fileNameArray['FILE_NAME']);
-        $filePath = '/ng/Volumes/HDD/workshop/old/ar.upload.ming/files/' . $fileNameArray['FILE_NAME'];
+        $filePath = '/ng922/Volumes/HDD/workshop/old/ar.upload.ming/files/' . $fileNameArray['FILE_NAME'];
         if ($startRow > $rowCount) {
             return 0;
         }

+ 24 - 32
common/helpers/bonus/BonusCalc.php

@@ -360,7 +360,8 @@ class BonusCalc extends BaseObject {
             echo('结算全部完成,共耗时:' . round($t35 - $t34, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
         } catch (\Exception $e) {
             $this->errorCalcTask();
-            $this->addError('calc', sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
+            LoggerTool::error('calcBonus' . sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
+            $this->addError('calcBonus', sprintf('%s',$e->getMessage()));
             return false;
         }
         return true;
@@ -532,11 +533,6 @@ class BonusCalc extends BaseObject {
                         'decPercentConfig' => $this->_sysConfig['decPercent']['VALUE'],
                         'recNum' => $bonusUserInfo['REC_NUM'],
                         'decAmount' => $bonusUserInfo['ZC_AMOUNT'],
-                        'bonusTotalLimit' => [
-                            $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
-                            $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
-                            $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
-                        ],
                     ]),
                 ];
 
@@ -620,11 +616,6 @@ class BonusCalc extends BaseObject {
                         'recNum' => $userBaseInfo['REC_NUM'],
                         'decAmount' => $userBaseInfo['ZC_AMOUNT'],
                         'decLevel' => $userBaseInfo['DEC_LV'],
-                        'bonusTotalLimit' => [
-                            $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
-                            $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
-                            $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
-                        ],
                     ]),
                 ];
 
@@ -1276,6 +1267,7 @@ class BonusCalc extends BaseObject {
                     'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
                     'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
                     'LAST_CROWN_LV' => $lastCrownLv,
+                    'CROWN_LV' => $userBaseInfo['CROWN_LV'],
                     'LAST_STATUS' => $userBaseInfo['STATUS'],
                     'AMOUNT' => $deductData['surplus'],
                     'ORI_BONUS' => $oriBonus,
@@ -1638,11 +1630,6 @@ class BonusCalc extends BaseObject {
                             'incomeBonus' => $incomeBonus,
                             'recNum' => $userBaseInfo['REC_NUM'],
                             'decAmount' => $userBaseInfo['ZC_AMOUNT'],
-                            'bonusTotalLimit' => [
-                                $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
-                                $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
-                                $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
-                            ],
                         ]),
                     ];
 
@@ -2470,11 +2457,6 @@ class BonusCalc extends BaseObject {
                             'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
                             'fromUserId' => $userId,
                             'decLevel' => $bonusUserBaseInfo['DEC_LV'],
-                            'bonusTotalLimit' => [
-                                $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
-                                $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
-                                $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
-                            ],
                         ]),
                     ];
 
@@ -3690,13 +3672,13 @@ class BonusCalc extends BaseObject {
                         ':PERIOD_NUM' => $this->_periodNum
                     ]
                 );
-                // 奖金流水
-                FlowBonus::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', 
-                    [
-                        ':USER_ID' => $data['USER_ID'],
-                        ':PERIOD_NUM' => $this->_periodNum
-                    ]
-                );
+//                // 奖金流水
+//                FlowBonus::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
+//                    [
+//                        ':USER_ID' => $data['USER_ID'],
+//                        ':PERIOD_NUM' => $this->_periodNum
+//                    ]
+//                );
 //                // 共享奖流水
 //                CalcBonusGX::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
 //                    [
@@ -3767,7 +3749,7 @@ class BonusCalc extends BaseObject {
         $tourismBonus = CalcCache::tourismBonus($userId, $this->_periodNum);
         $garageBonus = CalcCache::garageBonus($userId, $this->_periodNum);
         $villaBonus = CalcCache::villaBonus($userId, $this->_periodNum);
-        $empLv = $baseInfo['EMP_LV'];
+        $nowDirectorLv = $baseInfo['EMP_LV'];
 //        if($this->_isCalcMonth){
 //            $empLv = $this->nowMonthPerfData($userId)['LAST_EMP_LV'];
 //        }
@@ -3813,6 +3795,7 @@ class BonusCalc extends BaseObject {
         if( $this->_isCalcMonth ) {
             // 个人月消费PV大于配置值,才会计算发放蓝星奖
             $fxPvStatus = $this->_isMonthPerfLimit($userId);
+            $nowDirectorLv = EmployLevel::getDefaultLevelId();
             // BONUS_REAL 字段是发到用户的真实奖金
             if ( $fxPvStatus ) {
                 // 管理奖改成了蓝星奖,但是对于用户来说依旧叫管理奖.字段改成bs.
@@ -3860,7 +3843,8 @@ class BonusCalc extends BaseObject {
                 ->one();
                 $realBonusBs = $blueStartAmount; // 蓝星奖直接取数据库中算好的值PRODUCT_POINT
                 $exchangePoints = isset($userBS['PRODUCT_POINT']) && !empty($userBS['PRODUCT_POINT']) ? $userBS['PRODUCT_POINT'] : 0; // 兑换积分
-
+                // 会员最新$nowDirectorLv
+                $nowDirectorLv = $userBS['LEVEL_ID'] ?? $nowDirectorLv;
                 // 蓝星奖总奖金:管理奖+业绩奖
 //                $blueStartOriBonus = $blueStartOriBonusMnt + $blueStartOriBonusAbbr;
 //                $bonus['BONUS_TOTAL'] = $bonus['BONUS_TOTAL'] + $blueStartOriBonus; // 管理奖在存储过程计算,这里单独加上管理奖(即蓝星奖)
@@ -3873,13 +3857,21 @@ class BonusCalc extends BaseObject {
             }
         }
 
+        // 查询会员本期是否有团队奖
+        $userBonusQY = CalcBonusQY::findOneAsArray('PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID',
+            [
+                ':PERIOD_NUM' => $this->_periodNum,
+                ':USER_ID' => $userId
+            ]);
+        // 会员本期最新CrownLV
+        $nowCrownLv = $userBonusQY['LAST_CROWN_LV'] ?? StarCrownLevel::getDefaultLevelId();
         $result = [
             'USER_ID' => $userId,
             'LAST_USER_NAME' => $baseInfo['USER_NAME'],
             'LAST_REAL_NAME' => $baseInfo['REAL_NAME'],
             'LAST_DEC_LV' => $baseInfo['DEC_LV'],
-            'LAST_EMP_LV' => $empLv,
-            'LAST_CROWN_LV' => $starCrownLv ?? StarCrownLevel::getDefaultLevelId(),
+            'LAST_EMP_LV' => $nowDirectorLv,
+            'LAST_CROWN_LV' => $nowCrownLv,
             'LAST_STATUS' => $baseInfo['STATUS'],
             'LAST_MOBILE' => $baseInfo['MOBILE'],
             'LAST_PERIOD_AT' => $baseInfo['PERIOD_NUM'],

+ 31 - 8
common/helpers/bonus/BonusSend.php

@@ -11,6 +11,7 @@ namespace common\helpers\bonus;
 use common\components\ActiveRecord;
 use common\helpers\DataBak;
 use common\helpers\Form;
+use common\helpers\LoggerTool;
 use common\helpers\Tool;
 use common\helpers\user\Balance;
 use common\helpers\user\Info;
@@ -262,7 +263,8 @@ class BonusSend extends BaseObject {
             echo('全部奖金发放完成,耗时:'.round($t7 - $t1, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);
             $this->_updatePercent(100);
         } catch (\Exception $e) {
-            $this->addError('sendBonus', sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
+            LoggerTool::error('sendBonus' . sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
+            $this->addError('sendBonus', sprintf('%s',$e->getMessage()));
             return false;
         }
         if (count($this->_errors) > 0) {
@@ -564,7 +566,7 @@ class BonusSend extends BaseObject {
     public function updateEmpLevel(int $offset = 0) {
         if ($this->_isCalcMonth) {
             $empLv = EmployLevel::getIdConvertLevelSortCache();
-            $allData = CalcBonus::findUseDbCalc()
+            $allData = CalcBonusBS::findUseDbCalc()
             ->yearMonth($this->_calcYearMonth)
             ->where(
                 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM', 
@@ -594,10 +596,16 @@ class BonusSend extends BaseObject {
                             // 如果当前期的级别值大于历史最高级别,则更新用户表里的最高聘级
                             User::updateAll(['EMP_LV' => $nowBsEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
                             User::deleteBaseInfoFromRedis($data['USER_ID']);
-                            unset($data);
-                        } else {
-                            continue;
                         }
+
+                        // 更新最新级别
+                        User::updateAll([
+                            'LAST_EMP_LV' => $nowBsEmpLv,
+                            'LAST_EMP_LV_UPDATED_AT' => time(),
+                            'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum
+                        ], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
+                        User::deleteBaseInfoFromRedis($data['USER_ID']);
+                        unset($data);
                     }
                     $transaction->commit();
                 } catch (Exception $e) {
@@ -609,6 +617,14 @@ class BonusSend extends BaseObject {
                 return $this->updateEmpLevel($offset + $this->_limit);
             }
             unset($allData);
+
+            // 刷新会员EmpLv为0
+            User::updateAll([
+                'LAST_EMP_LV' => '',
+                'LAST_EMP_LV_UPDATED_AT' => time(),
+                'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
+            ], 'LAST_EMP_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_EMP_LV <> ""', [':PERIOD_NUM' => $this->_periodNum]);
+            User::deleteAllBaseInfoFromRedis();
         }
         return true;
     }
@@ -636,13 +652,13 @@ class BonusSend extends BaseObject {
             ->limit($this->_limit)
             ->all();
 
-        $defaultEmpLv = StarCrownLevel::getDefaultLevelId();
+        $defaultCrownLv = StarCrownLevel::getDefaultLevelId();
         if ($allData) {
             $transaction = Yii::$app->db->beginTransaction();
             try {
                 foreach ($allData as $data) {
                     // 默认级别不更新
-                    if( $data['LAST_CROWN_LV'] === $defaultEmpLv ) continue;
+                    if( $data['LAST_CROWN_LV'] === $defaultCrownLv ) continue;
 
                     $modernCrownLv = $data['LAST_CROWN_LV'];   // 本期计算出的最新级别
 
@@ -678,7 +694,14 @@ class BonusSend extends BaseObject {
             unset($transaction, $allData);
             return $this->updateCrownLevel($offset + $this->_limit);
         }
-        unset($allData);
+
+        // 刷新会员CrownLv为0
+        User::updateAll([
+            'LAST_CROWN_LV' => '',
+            'LAST_CROWN_LV_UPDATED_AT' => time(),
+            'LAST_CROWN_LV_UPDATED_PERIOD' => $this->_periodNum,
+        ], 'LAST_CROWN_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_CROWN_LV <> ""' , [':PERIOD_NUM' => $this->_periodNum]);
+        User::deleteAllBaseInfoFromRedis();
 
         return true;
     }

+ 1 - 17
common/helpers/bonus/PerfCalc.php

@@ -1072,16 +1072,7 @@ class PerfCalc {
                 $periodPerf = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
 
                 $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
-                //级别必须为VIP
-                $isVip = false;
-                if( $userBaseInfo['DEC_LV'] === DeclarationLevel::VIP_LEVEL_ID ) {
-                    $isVip= true;
-                }
-                if( $this->_sysConfig['vipBonusGoldDecLevel']['VALUE'] && $userBaseInfo['DEC_LV'] === DeclarationLevel::JIN_ZUAN_LEVEL_ID ) {
-                    $isVip = true;
-                }
-
-
+                
                 $nowMonthPerf = [
                     'USER_ID' => $userId,
                     'FX_AMOUNT_CASH' => $everyData['FX_AMOUNT_CASH_SUM'],
@@ -1094,13 +1085,6 @@ class PerfCalc {
                     'PV_4L' => $everyData['PV_4L_SUM'],
                     'PV_5L' => $everyData['PV_5L_SUM'],
 
-                    //VIP统计相关业绩
-                    'VIP_PV_1L_ZC' => $isVip ? $everyData['PV_1L_ZC_SUM'] : 0,
-                    'VIP_PV_2L_ZC' => $isVip ? $everyData['PV_2L_ZC_SUM'] : 0,
-                    'VIP_PV_3L_ZC' => $isVip ? $everyData['PV_3L_ZC_SUM'] : 0,
-                    'VIP_PV_4L_ZC' => $isVip ? $everyData['PV_4L_ZC_SUM'] : 0,
-                    'VIP_PV_5L_ZC' => $isVip ? $everyData['PV_5L_ZC_SUM'] : 0,
-
                     //总数据,历史+本期。不能用上月加本月,因为上月可能没业绩,上上个月有业绩。
                     'PV_1L_TOTAL' => $periodPerf['PV_1L'] + $userLastPerf['PV_1L'],
                     'PV_2L_TOTAL' => $periodPerf['PV_2L'] + $userLastPerf['PV_2L'],

+ 1 - 1
common/helpers/user/Balance.php

@@ -571,7 +571,7 @@ class Balance {
             $flowInsertData = [
                 'USER_ID' => $userId,
                 'LAST_DEC_LV' => $userInfo['DEC_LV'],
-                'LAST_EMP_LV' => $userInfo['EMP_LV'],
+                'LAST_EMP_LV' => $userInfo['LAST_EMP_LV'],
                 'LAST_STATUS' => $userInfo['STATUS'],
                 'CALC_ID' => $params['CALC_ID'] ?? null,
                 'AMOUNT' => ($issueBonus ? $amount * $exchangeRate : $amount),

+ 85 - 1
common/helpers/user/Info.php

@@ -13,6 +13,8 @@ use common\components\ActiveQuery;
 use common\components\ActiveRecord;
 use common\helpers\Cache;
 use common\helpers\Tool;
+use common\models\BaUser;
+use common\models\BaUserInfo;
 use common\models\Config;
 use common\models\PerfMonth;
 use common\models\PerfPeriod;
@@ -490,6 +492,9 @@ class Info {
         if (User::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
             return self::generateWebUserName($prefix, $length);
         }
+        if (BaUser::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
+            return self::generateWebUserName($prefix, $length);
+        }
         return $result;
     }
 
@@ -617,7 +622,7 @@ class Info {
      * @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');
+        $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'LAST_DEC_LV AS DEC_LV,EMP_LV,LAST_EMP_LV,STATUS,CROWN_LV,LAST_CROWN_LV');
         return $data;
     }
 
@@ -631,4 +636,83 @@ class Info {
         if ($data && $data['IS_UNION'] == 1) return true;
         return false;
     }
+
+    /**
+     * 获取Ba用户ID
+
+     * @param $userName
+     * @return mixed
+     */
+    public static function getBaUserIdByUserName($userName) {
+        $user = BaUserInfo::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 getBaUserNameByUserId($userId) {
+        $user = BaUserInfo::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 getBaEmailByUserId($userId) {
+        $user = BaUserInfo::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 getBaUserRealNameByUserId($userId) {
+        $user = BaUser::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'REAL_NAME');
+        return $user ? $user['REAL_NAME'] : null;
+    }
+
+    /**
+     * 获取会员邮箱通过ID
+     * @param $userId
+     * @return null
+     */
+    public static function getBaUserEmailByUserId($userId) {
+        $user = BaUser::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'EMAIL');
+        return $user ? $user['EMAIL'] : null;
+    }
+
+    /**
+     * 获取手机号通过ID
+     * @param $userId
+     * @return null
+     */
+    public static function getBaUserMobileByUserId($userId) {
+        $user = BaUser::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'MOBILE');
+        return $user ? $user['MOBILE'] : null;
+    }
+
+    /**
+     * 通过用户ID获取用户的编号和名称
+     * @param $userId
+     * @return array|null
+     */
+    public static function getBaBaseUserById($userId) {
+        return BaUser::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID,USER_NAME,REAL_NAME');
+    }
+
+    /**
+     * 通过用户ID获取用户的编号和名称
+     * @param $username
+     * @return array|null
+     */
+    public static function getBaBaseUserByUserName($username) {
+        return BaUser::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $username]);
+    }
 }

+ 388 - 9
common/libs/export/BaseExport.php

@@ -10,22 +10,25 @@ use common\helpers\http\RemoteUploadApi;
 use common\helpers\LoggerTool;
 use common\helpers\Tool;
 use common\helpers\user\Info;
-use common\libs\dataList\column\DateTime;
 use common\libs\dataList\DataList;
 use common\models\ApproachOrder;
 use common\models\ApproachOrderGoods;
+use common\models\BaApproachOrder;
+use common\models\BaApproachOrderGoods;
+use common\models\BaOrder;
+use common\models\BaOrderGoods;
+use common\models\BaUser;
 use common\models\Export;
 use common\models\Order;
 use common\models\OrderGoods;
 use common\models\Region;
 use common\models\ShopGoods;
 use common\models\User;
-use mysql_xdevapi\Result;
 use Yii;
 use yii\base\Exception;
+use yii\base\InvalidConfigException;
 use yii\base\StaticInstanceTrait;
 use yii\base\Component;
-use yii\data\Pagination;
 use yii\db\Query;
 
 class BaseExport extends Component {
@@ -210,11 +213,10 @@ class BaseExport extends Component {
      * 生成
      * @return bool
      * @throws Exception
-     * @throws \yii\base\InvalidConfigException
+     * @throws InvalidConfigException
      * @throws \yii\httpclient\Exception
      */
     public function generate() {
-        //Logger::info(date('Y-m-d H:i:s'), 'export');
         $this->getParams();
         if (!$this->params) {
             throw new Exception('无法获取需要的参数');
@@ -382,7 +384,7 @@ class BaseExport extends Component {
      * 完成
      * @return bool
      * @throws Exception
-     * @throws \yii\base\InvalidConfigException
+     * @throws InvalidConfigException
      * @throws \yii\httpclient\Exception
      */
     public function complete() {
@@ -524,7 +526,7 @@ class BaseExport extends Component {
      * 生成
      * @return bool
      * @throws Exception
-     * @throws \yii\base\InvalidConfigException
+     * @throws InvalidConfigException
      * @throws \yii\httpclient\Exception
      */
     public function generateOrderExcel() {
@@ -565,7 +567,7 @@ class BaseExport extends Component {
      * 生成
      * @return bool
      * @throws Exception
-     * @throws \yii\base\InvalidConfigException
+     * @throws InvalidConfigException
      * @throws \yii\httpclient\Exception
      */
     public function generateOrderPDF() {
@@ -820,7 +822,7 @@ ORDER;
      * 生成
      * @return bool
      * @throws Exception
-     * @throws \yii\base\InvalidConfigException
+     * @throws InvalidConfigException
      * @throws \yii\httpclient\Exception
      */
     public function generateDecOrderPDF() {
@@ -1090,4 +1092,381 @@ ORDER;
 
         return $list['list'];
     }
+
+    /**
+     * 生成
+     * @return bool
+     * @throws Exception
+     * @throws InvalidConfigException
+     * @throws \yii\httpclient\Exception
+     */
+    public function generateBaOrderExcel() {
+        $this->getParams();
+        if (!$this->params) {
+            throw new Exception('无法获取需要的参数');
+        }
+        $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
+        $path = __DS__ . $path;
+        $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
+        $this->completed = false;
+        $this->getExportId();
+        $this->getUserId();
+        $this->_fp = fopen($realFile, 'w');
+        @exec('chown -R www:www /'.$realFile);
+        @exec('chmod -R 777 /'.$realFile);
+        // 获取列表数据及表头
+        $this->_listModel = new $this->listModelClass();
+        $this->_listModel->isExport = true;
+        if(method_exists($this->_listModel, 'getExportHeaders')){
+            if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
+                $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
+            }
+            $headers = $this->_listModel->getExportHeaders($this->userId);
+            fputcsv($this->_fp, $headers);
+            unset($headers);
+            $this->_updateFirst($realFile, 1);
+        } else {
+            throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
+        }
+        $this->_loopWriteDataBaOrder();
+        $this->complete();
+        return true;
+    }
+
+    /**
+     * 循环写入数据
+     */
+    private function _loopWriteDataBaOrder()
+    {
+        $orderQuery = BaOrder::find()
+            ->alias('O')
+            ->where($this->params['condition'], $this->params['params'])
+            ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
+            ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
+            ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
+            ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
+            ->orderBy('O.CREATED_AT DESC');
+
+        // 订单中间表只查询待支付和支付失败的订单
+        $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value'];   // 待支付
+        $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value'];   // 支付失败
+        $orderStandardQuery = BaApproachOrder::find()
+            ->alias('O')
+            ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
+            ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
+            ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
+            ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
+            ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
+            ->orderBy('O.CREATED_AT DESC');
+
+        $queryAll = $orderQuery->union($orderStandardQuery, true);
+        $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
+        $lists = $query->all();
+
+        if(!empty($lists)){
+            $regionConfig = Cache::getRegionConfig();
+            foreach($lists as $columnData) {
+                $CREATE_USER_ID = Info::getBaUserIdByUserName($columnData['CREATE_USER']);
+                $createUserName = Info::getBaUserRealNameByUserId($CREATE_USER_ID);
+                $decUserName = Info::getBaUserNameByUserId($columnData['DEC_ID']);
+
+                $columnAccept = [
+                    'USER_NAME' => $columnData['USER_NAME'],
+                    'DEC_USER_NAME' => $decUserName,
+                    'CREATE_USER' => $columnData['CREATE_USER'],
+                    'CREATE_USER_NAME' => $createUserName,
+                    'SN' => $columnData['SN'],
+                    'STATUS' => \Yii::$app->params['orderStatus'][$columnData['STATUS']]['label'] ?? '',
+                    'SKU_CODE' => $columnData['SKU_CODE'],
+                    'GOODS_TITLE' => $columnData['GOODS_TITLE'],
+                    'BUY_NUMS' => $columnData['BUY_NUMS'],
+                    'CONSIGNEE' => $columnData['CONSIGNEE'],
+                    'MOBILE' => "\t{$columnData['MOBILE']}",
+                    'TEL' => "\t{$columnData['TEL']}",
+                    'PROVINCE' => $regionConfig[$columnData['PROVINCE']]['REGION_NAME'] ?? '',
+                    'CITY' => $regionConfig[$columnData['CITY']]['REGION_NAME'] ?? '',
+                    'COUNTY' => $regionConfig[$columnData['COUNTY']]['REGION_NAME'] ?? '',
+                    'ADDRESS' => $columnData['ADDRESS'],
+                    'PERIOD_NUM' => $columnData['PERIOD_NUM'],
+                    'ORDER_TYPE' => ($columnData['ORDER_TYPE'] == 'ZC') ? 'Welcome pack' : (in_array($columnData['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Reselling': 'Points'),
+                    'CREATED_AT' => Date('Y-m-d H:i:s', $columnData['CREATED_AT']),
+                    'PAY_TYPE' => ShopGoods::payTypes()[$columnData['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'],
+                    'PAY_AT' => $columnData['PAY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['PAY_AT']) : '',
+                    'DELIVERY_AT' => $columnData['DELIVERY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']) : '',
+                    'REAL_PRICE' => $columnData['REAL_PRICE'] ?? 0,
+                    'REAL_PV' => $columnData['REAL_PV'] ?? 0,
+                    'PAY_FREIGHT' => $columnData['PAY_FREIGHT'] ?? 0,
+                    'TAX_RATE' => $columnData['TAX_RATE'],
+                    'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
+                    'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
+                    'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
+                    'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
+                    'FRONT_REMARK' => $columnData['FRONT_REMARK'],
+                    'DELIVERY_STATUS_NAME' => \Yii::$app->params['deliveryStatus'][$columnData['DELIVERY_STATUS']]['label'] ?? '',
+                ];
+                
+                fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
+                unset($percent, $columnData, $columnAccept);
+            }
+            unset($list);
+        }
+
+        unset($list);
+        return 'finish';
+    }
+
+    /**
+     * 生成
+     * @return bool
+     * @throws Exception
+     * @throws InvalidConfigException
+     * @throws \yii\httpclient\Exception
+     */
+    public function generateBaOrderPDF()
+    {
+        $this->getParams();
+        if (!$this->params) {
+            throw new Exception('无法获取需要的参数');
+        }
+        $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
+        $realFile = $path . __DS__ . $this->getFileName('.pdf');
+
+        $this->completed = false;
+        $this->getExportId();
+        $this->getUserId();
+        $fileNameUpdated = false;
+
+        // 获取列表数据及表头
+        $this->_listModel = new $this->listModelClass();
+        $this->_listModel->isExport = true;
+
+        // 查询订单数据
+        $orderQuery = BaOrder::find()
+            ->alias('O')
+            ->where($this->params['condition'], $this->params['params'])
+            ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
+            ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
+            ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
+            ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
+            ->orderBy('O.CREATED_AT DESC');
+
+        // 订单中间表只查询待支付和支付失败的订单
+        $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value'];   // 待支付
+        $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value'];   // 支付失败
+        $orderStandardQuery = BaApproachOrder::find()
+            ->alias('O')
+            ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
+            ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
+            ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
+            ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
+            ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
+            ->orderBy('O.CREATED_AT DESC');
+
+        $queryAll = $orderQuery->union($orderStandardQuery, true);
+        $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
+        $oderList = $query->all();
+
+        if ($oderList) {
+            $userId = '';
+            $userName = '';
+            $address = '';
+            $mobile = '';
+            $orderAt = '';
+            $orderDetails = '';
+            $orderSn = '';
+            $orderAmount = 0;  // 合计总额
+            $orderNums = 0; // 合计总数
+            $totalTaxAmount = 0; // 合计税额
+            $totalAmount = 0;
+            foreach ($oderList as $key => $value) {
+                $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
+                $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
+                $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
+
+                $userId = $value['USER_NAME'];
+                $userName = $value['REAL_NAME'];
+                $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
+                $mobile = $value['MOBILE'];
+                $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
+                $orderSn = $value['SN'];
+                // 总价
+                $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
+                $orderAmount += $totalAmount;
+                $orderNums += $value['BUY_NUMS'];
+                // 税额
+                $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
+                $totalTaxAmount += $taxAmount;
+                $taxAmount = Tool::formatAmount($taxAmount);
+                $totalAmount = Tool::formatAmount($totalAmount);
+                // 订单详情
+                $orderDetails .= <<<EOT
+                <tr>
+                    <td>{$value['SKU_CODE']}</td>
+                    <td>{$value['GOODS_TITLE']}</td>
+                    <td style="text-align: right;">{$value['REAL_PRICE']}</td>
+                    <td>{$value['BUY_NUMS']}</td>
+                    <td style="text-align: right;">{$value['TAX_RATE']}</td>
+                    <td style="text-align: right;">{$taxAmount}</td>
+                    <td style="text-align: right;">{$totalAmount}</td> 
+                </tr>
+EOT;
+            }
+
+            // 订单基本信息
+            $orderBase = <<<ORDER
+            <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Code</td>
+                    <td width="70%">{$userId}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Name</td>
+                    <td width="70%">{$userName}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Address</td>
+                    <td width="70%">{$address}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Phone</td>
+                    <td width="70%">{$mobile}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order Code</td>
+                    <td width="70%">{$orderSn}</td>
+                </tr>
+                <tr>
+                    <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation Time</td>
+                    <td width="70%">{$orderAt}</td>
+                </tr>
+                <tr>
+                    <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order Detail</td>
+                    <td class="bg"></td>
+                </tr>
+            </table>
+ORDER;
+
+            $l['a_meta_charset'] = 'UTF-8';
+            $l['a_meta_dir'] = 'ltr';
+            $l['a_meta_language'] = 'zh';
+            $l['w_page'] = '页面';
+
+            $orderAmount = Tool::formatAmount($orderAmount);
+            $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
+
+            $context = <<<ORDER
+            <!doctype html>
+            <html lang="en">
+            <head>
+                <meta charset="UTF-8" />
+                <title>Order detail</title>
+                <style>
+                    table {
+                        border-collapse: collapse;
+                    }
+                    table td, table th {
+                        border: 1px solid #ccc;
+                        padding: 5px 5px;
+                        border-collapse: collapse;
+                    }
+                    /*td {*/
+                    /*    padding: 120px;*/
+                    /*}*/
+                    .bg {
+                        background-color: #ccc;
+                    }
+                </style>
+            </head>
+            <body>
+                <div class="content">
+                    <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
+                    <div>
+                        <div style="display: block; width: 100%;">
+                            {$orderBase}
+                            
+                            <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
+                                <tr>
+                                    <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
+                                    <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
+                                    <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
+                                    <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
+                                    <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
+                                    <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
+                                    <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
+                                </tr>
+                                {$orderDetails}
+                                <tr>
+                                    <td colspan="3">Total</td>
+                                    <td>{$orderNums}</td>
+                                    <td></td>
+                                    <td style="text-align: right;">{$totalTaxAmount}</td>
+                                    <td style="text-align: right;">{$orderAmount}</td>
+                                </tr>
+                            </table>
+                        </div>
+                        
+                        <div style="width: 100%; margin-top: 50px; height: 30px;">
+                            <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
+                                <tr style="border: none;">
+                                    <td width="70%" style="border: none;"></td>
+                                    <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
+                                </tr>
+                                <tr style="border: none;">
+                                    <td width="70%" style="border: none;"></td>
+                                    <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
+                                </tr>
+                            </table>
+                        </div>
+                    </div>
+                </div>
+            </body>
+            </html>
+ORDER;
+
+            require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
+
+            $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
+            // 设置打印模式
+            $pdf->SetCreator(PDF_CREATOR);
+            $pdf->SetAuthor('DaZe');
+            $pdf->SetTitle($orderSn);
+            $pdf->SetSubject('TCPDF Tutorial');
+            $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
+            // 是否显示页眉
+            $pdf->setPrintHeader(false);
+            // 设置页眉字体
+            $pdf->setHeaderFont(Array('dejavusans', '', '12'));
+            // 页眉距离顶部的距离
+            $pdf->SetHeaderMargin('5');
+            // 是否显示页脚
+            $pdf->setPrintFooter(false);
+            // 设置默认等宽字体
+            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
+            // 设置行高
+            $pdf->setCellHeightRatio(1);
+            // 设置左、上、右的间距
+            $pdf->SetMargins('10', '0', '10');
+            // 设置是否自动分页  距离底部多少距离时分页
+            $pdf->SetAutoPageBreak(TRUE, '15');
+            // 设置图像比例因子
+            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
+            if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
+                require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
+                $pdf->setLanguageArray($l);
+            }
+            $pdf->setFontSubsetting(true);
+            $pdf->AddPage();
+            // 设置字体
+            $pdf->SetFont('stsongstdlight', '', 10, '', true);
+            $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+            $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
+            $pdf->writeHTML($context);
+            $pdf->Output($realFile, 'F');
+
+            $this->_updateFirst($realFile, 1);
+        }
+
+        $this->complete();
+        return true;
+    }
 }

+ 10 - 0
common/libs/export/module/BaShopExport.php

@@ -0,0 +1,10 @@
+<?php
+namespace common\libs\export\module;
+
+use common\libs\export\BaseExport;
+
+class BaShopExport extends BaseExport
+{
+    public $moduleId = 'ba_shop';
+
+}

+ 10 - 0
common/libs/export/module/BaUserExport.php

@@ -0,0 +1,10 @@
+<?php
+namespace common\libs\export\module;
+
+use common\libs\export\BaseExport;
+
+class BaUserExport extends BaseExport
+{
+    public $moduleId = 'ba_user';
+
+}

+ 1 - 1
common/models/ApproachDecOrder.php

@@ -51,7 +51,7 @@ class ApproachDecOrder extends \common\components\ActiveRecord
     public function rules()
     {
         return [
-            [['USER_ID', 'TO_USER_ID','REC_USER_ID','CON_USER_ID','DEC_ID', 'TYPE', 'PAID_WALLET', 'PERIOD_NUM', 'P_CALC_MONTH', 'CREATED_AT'], 'required'],
+            [['USER_ID', 'TO_USER_ID','REC_USER_ID',/*'CON_USER_ID','DEC_ID', */'TYPE', 'PAID_WALLET', 'PERIOD_NUM', 'P_CALC_MONTH', 'CREATED_AT'], 'required'],
             [['IS_ADMIN', 'IS_BATCH', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'IS_DEL', 'DELETED_AT'], 'integer'],
             [['DEC_AMOUNT', 'DEC_PV'], 'number'],
             [['ID', 'DEC_SN', 'ORDER_SN', 'USER_ID', 'TO_USER_ID','REC_USER_ID','CON_USER_ID','DEC_ID', 'TYPE', 'UPDATER', 'UPDATED_AT'], 'string', 'max' => 32],

+ 0 - 0
common/models/ApproachOrderCall.php


+ 97 - 0
common/models/BaApproachDecOrder.php

@@ -0,0 +1,97 @@
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%APPROACH_DEC_ORDER}}".
+ *
+ * @property string $ID
+ * @property string $DEC_SN 报单编号
+ * @property string $ORDER_SN 订单编号
+ * @property string $USER_ID 会员ID
+ * @property string $TO_USER_ID 报单对象ID
+ * @property string $TYPE 报单类型
+ * @property int $IS_ADMIN 是否管理员操作
+ * @property string $DEC_AMOUNT 报单金额
+ * @property string $DEC_PV 报单PV
+ * @property string $PAID_WALLET 支付钱包
+ * @property int $IS_BATCH 是否批量报单
+ * @property string $REMARK 备注
+ * @property string $REC_USER_ID 推荐人ID
+ * @property string $CON_USER_ID 接点人ID
+ * @property string $DEC_ID 报单中心ID
+ * @property int $PERIOD_NUM 报单期数
+ * @property string $P_CALC_MONTH 分区结算月
+ * @property int $CALC_MONTH 结算月
+ * @property int $CREATED_AT 创建时间
+ * @property string $UPDATER 操作人
+ * @property string $UPDATED_AT 更新时间
+ * @property int $IS_DEL 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $DETAIL_TYPE 类型
+ * @property int $UPGRADE_TYPE 升级类型
+ * @property string $ORI_LV 升级前级别
+ * @property string $UPGRADE_LV 升级后级别
+ */
+class BaApproachDecOrder extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%BA_APPROACH_DEC_ORDER}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'TO_USER_ID','REC_USER_ID',/*'CON_USER_ID','DEC_ID', */'TYPE', 'PAID_WALLET', 'PERIOD_NUM', 'P_CALC_MONTH', 'CREATED_AT'], 'required'],
+            [['IS_ADMIN', 'IS_BATCH', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'IS_DEL', 'DELETED_AT'], 'integer'],
+            [['DEC_AMOUNT', 'DEC_PV'], 'number'],
+            [['ID', 'DEC_SN', 'ORDER_SN', 'USER_ID', 'TO_USER_ID','REC_USER_ID','CON_USER_ID','DEC_ID', 'TYPE', 'UPDATER', 'UPDATED_AT'], 'string', 'max' => 32],
+            [['PAID_WALLET'], 'string', 'max' => 48],
+            [['REMARK'], 'string', 'max' => 4000],
+            [['DEC_SN'], 'unique'],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'DEC_SN' => '报单编号',
+            'ORDER_SN' => '订单编号',
+            'USER_ID' => '会员ID',
+            'TO_USER_ID' => '报单对象ID',
+            'TYPE' => '报单类型',
+            'IS_ADMIN' => '是否管理员操作',
+            'DEC_AMOUNT' => '报单金额',
+            'DEC_PV' => '报单PV',
+            'PAID_WALLET' => '支付钱包',
+            'STATUS' => '支付状态',
+            'IS_BATCH' => '是否批量报单',
+            'REMARK' => '备注',
+            'REC_USER_ID' => '开拓人编号',
+            'CON_USER_ID' => '上级编号',
+            'DEC_ID' => '上级编号',
+            'PERIOD_NUM' => '报单期数',
+            'P_CALC_MONTH' => '分区结算月',
+            'CALC_MONTH' => '结算月',
+            'CREATED_AT' => '创建时间',
+            'UPDATER' => '操作人',
+            'UPDATED_AT' => '更新时间',
+            'IS_DEL' => '是否删除',
+            'DELETED_AT' => '删除时间',
+        ];
+    }
+}

+ 131 - 0
common/models/BaApproachOrder.php

@@ -0,0 +1,131 @@
+<?php
+
+namespace common\models;
+
+/**
+ * This is the model class for table "{{%BA_APPROACH_ORDER}}".
+ *
+ * @property string $ID
+ * @property string $SN 订单号
+ * @property string $DEC_SN 报单编号
+ * @property string $USER_ID 用户ID
+ * @property string $USER_NAME 会员编号
+ * @property string $ORDER_TYPE 订货类型
+ * @property string $ORDER_AMOUNT 订单总价格
+ * @property string $PV 订货PV
+ * @property string $PAY_AMOUNT 支付价格
+ * @property string $PAY_PV 实付PV
+ * @property int $PAY_AT 支付时间
+ * @property string $PAY_TYPE 支付方式
+ * @property string $FREIGHT 运费
+ * @property string $PAY_FREIGHT 实付运费金额
+ * @property int $DELIVERY_STATUS 发货状态
+ * @property int $DELIVERY_PERIOD 发货期数
+ * @property int $DELIVERY_AT 发货时间
+ * @property string $EXPRESS_COMPANY 快递公司
+ * @property string $ORDER_TRACK_NO 快递单号
+ * @property int $EXPRESS_TYPE 发货方式
+ * @property string $FRONT_REMARK 前台备注
+ * @property string $REMARK 后台备注
+ * @property int $PERIOD_NUM 期数
+ * @property int $STATUS 订单状态
+ * @property string $CONSIGNEE 收货人
+ * @property string $MOBILE 收货人手机
+ * @property string $TEL 固定电话
+ * @property int $PROVINCE 省份名称
+ * @property int $CITY 城市名称
+ * @property int $COUNTY 县区
+ * @property string $ADDRESS 详细地址
+ * @property string $P_CALC_MONTH 分区日期
+ * @property int $CREATED_AT 订单创建时间
+ * @property string $CREATE_USER 订单创建人
+ * @property int $UPDATED_AT 修改时间
+ * @property string $UPDATER 修改人
+ * @property int $IS_DELETE 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $WAREHOUSE 发货仓
+ * @property string $EMAIL 邮箱
+ * @property string $NOTE 备注说明
+ * @property string $LGA_NAME LGA_NAME
+ * @property string $CITY_NAME 城市
+ */
+class BaApproachOrder extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%BA_APPROACH_ORDER}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'USER_NAME', 'ORDER_TYPE', 'CREATE_USER'], 'required'],
+            [['ORDER_AMOUNT', 'PV', 'PAY_AMOUNT', 'PAY_PV', 'FREIGHT', 'PAY_FREIGHT'], 'number'],
+            [['PAY_AT', 'DELIVERY_STATUS', 'DELIVERY_PERIOD', 'DELIVERY_AT', 'EXPRESS_TYPE', 'PERIOD_NUM', 'STATUS', 'PROVINCE', 'CITY', 'COUNTY', 'CREATED_AT', 'UPDATED_AT', 'IS_DELETE', 'DELETED_AT'], 'integer'],
+            [['ID','SN', 'DEC_SN', 'USER_ID', 'ORDER_TRACK_NO','PAY_TYPE'], 'string', 'max' => 32],
+            [['USER_NAME', 'TEL', 'CREATE_USER', 'UPDATER', 'WAREHOUSE'], 'string', 'max' => 16],
+            [['ORDER_TYPE'], 'string', 'max' => 12],
+            [['EXPRESS_COMPANY'], 'string', 'max' => 128],
+            [['FRONT_REMARK'], 'string', 'max' => 1000],
+            [['REMARK', 'NOTE'], 'string', 'max' => 4000],
+            [['CONSIGNEE'], 'string', 'max' => 120],
+            [['MOBILE'], 'string', 'max' => 11],
+            [['ADDRESS'], 'string', 'max' => 255],
+            [['SN'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'SN' => '订单号',
+            'DEC_SN' => '报单编号',
+            'USER_ID' => '用户ID',
+            'USER_NAME' => '会员编号',
+            'ORDER_TYPE' => '订货类型',
+            'ORDER_AMOUNT' => '订单总价格',
+            'PV' => '订货BV',
+            'PAY_AMOUNT' => '支付价格',
+            'PAY_PV' => '实付BV',
+            'PAY_AT' => '支付时间',
+            'PAY_TYPE' => '支付方式',
+            'FREIGHT' => '运费',
+            'PAY_FREIGHT' => '实付运费金额',
+            'DELIVERY_STATUS' => '发货状态',
+            'DELIVERY_PERIOD' => '发货期数',
+            'DELIVERY_AT' => '发货时间',
+            'EXPRESS_COMPANY' => '快递公司',
+            'ORDER_TRACK_NO' => '快递单号',
+            'EXPRESS_TYPE' => '发货方式',
+            'FRONT_REMARK' => '前台备注',
+            'REMARK' => '后台备注',
+            'PERIOD_NUM' => '期数',
+            'STATUS' => '订单状态',
+            'CONSIGNEE' => '收货人',
+            'MOBILE' => '收货人手机',
+            'TEL' => '固定电话',
+            'LGA_NAME' => 'lga name',
+            'CITY_NAME' => 'City name',
+            'ADDRESS' => '详细地址',
+            'P_CALC_MONTH' => '分区日期',
+            'CREATED_AT' => '订单创建时间',
+            'CREATE_USER' => '订单创建人',
+            'UPDATED_AT' => '修改时间',
+            'UPDATER' => '修改人',
+            'IS_DELETE' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'WAREHOUSE' => '发货仓',
+            'EMAIL' => 'Email'
+        ];
+    }
+}

+ 77 - 0
common/models/BaApproachOrderGoods.php

@@ -0,0 +1,77 @@
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%BA_APPROACH_ORDER_GOODS}}".
+ *
+ * @property string $ID
+ * @property string $ORDER_SN 订单ID
+ * @property string $GOODS_ID 商品ID
+ * @property string $GOODS_TITLE 商品名称
+ * @property string $PRICE 价格
+ * @property string $REAL_PRICE 实际价格
+ * @property string $PV 订货PV
+ * @property string $REAL_PV 实际PV
+ * @property string $TAX_RATE 税率
+ * @property string $POINT 兑换积分
+ * @property string $SKU_CODE 商品编码
+ * @property int $BUY_NUMS 购买数量
+ * @property string $P_CALC_MONTH 分区日期
+ * @property int CATEGORY_TYPE 商品分类
+ * @property int PAY_TYPE 支付方式
+ * @property string $EMAIL Email
+ */
+class BaApproachOrderGoods extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%BA_APPROACH_ORDER_GOODS}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['ORDER_SN', 'GOODS_ID', 'GOODS_TITLE', 'SKU_CODE', 'CATEGORY_TYPE', 'PAY_TYPE', 'EMAIL'], 'required'],
+            [['PRICE', 'REAL_PRICE', 'PV', 'REAL_PV', 'POINT', 'CATEGORY_TYPE', 'PAY_TYPE', 'TAX_RATE'], 'number'],
+            [['BUY_NUMS'], 'integer'],
+            [['ID', 'ORDER_SN', 'GOODS_ID'], 'string', 'max' => 32],
+            [['GOODS_TITLE'], 'string', 'max' => 255],
+            [['SKU_CODE'], 'string', 'max' => 16],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'ORDER_SN' => '订单ID',
+            'GOODS_ID' => '商品ID',
+            'GOODS_TITLE' => '商品名称',
+            'PRICE' => '价格',
+            'REAL_PRICE' => '实际价格',
+            'PV' => '订货BV',
+            'REAL_PV' => '实际BV',
+            'TAX_RATE' => '税率',
+            'POINT' => '兑换积分',
+            'SKU_CODE' => '商品编码',
+            'BUY_NUMS' => '购买数量',
+            'P_CALC_MONTH' => '分区日期',
+            'CATEGORY_TYPE' => '商品分类',
+            'PAY_TYPE' => '支付方式',
+            'EMAIL' => 'Email'
+        ];
+    }
+}

+ 92 - 0
common/models/BaDecOrder.php

@@ -0,0 +1,92 @@
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%DEC_ORDER}}".
+ *
+ * @property string $ID
+ * @property string $DEC_SN 报单编号
+ * @property string $ORDER_SN 订单编号
+ * @property string $USER_ID 会员ID
+ * @property string $TO_USER_ID 报单对象ID
+ * @property string $TYPE 报单类型
+ * @property int $IS_ADMIN 是否管理员操作
+ * @property string $DEC_AMOUNT 报单金额
+ * @property string $DEC_PV 报单PV
+ * @property string $PAID_WALLET 支付钱包
+ * @property int $IS_BATCH 是否批量报单
+ * @property string $REMARK 备注
+ * @property string $REC_USER_ID 推荐人ID
+ * @property string $CON_USER_ID 接点人ID
+ * @property string $DEC_ID 报单中心ID
+ * @property int $PERIOD_NUM 报单期数
+ * @property string $P_CALC_MONTH 分区结算月
+ * @property int $CALC_MONTH 结算月
+ * @property int $CREATED_AT 创建时间
+ * @property string $UPDATER 操作人
+ * @property string $UPDATED_AT 更新时间
+ * @property int $IS_DEL 是否删除
+ * @property int $DELETED_AT 删除时间
+ */
+class BaDecOrder extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%BA_DEC_ORDER}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'TO_USER_ID','REC_USER_ID',/*'CON_USER_ID','DEC_ID',*/ 'TYPE', 'PAID_WALLET', 'PERIOD_NUM', 'P_CALC_MONTH', 'CREATED_AT'], 'required'],
+            [['IS_ADMIN', 'IS_BATCH', 'PERIOD_NUM', 'CALC_MONTH', 'CREATED_AT', 'IS_DEL', 'DELETED_AT'], 'integer'],
+            [['DEC_AMOUNT', 'DEC_PV'], 'number'],
+            [['ID', 'DEC_SN', 'ORDER_SN', 'USER_ID', 'TO_USER_ID','REC_USER_ID','CON_USER_ID','DEC_ID', 'TYPE', 'UPDATER', 'UPDATED_AT'], 'string', 'max' => 32],
+            [['PAID_WALLET'], 'string', 'max' => 48],
+            [['REMARK'], 'string', 'max' => 4000],
+            [['DEC_SN'], 'unique'],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'DEC_SN' => '报单编号',
+            'ORDER_SN' => '订单编号',
+            'USER_ID' => '会员ID',
+            'TO_USER_ID' => '报单对象ID',
+            'TYPE' => '报单类型',
+            'IS_ADMIN' => '是否管理员操作',
+            'DEC_AMOUNT' => '报单金额',
+            'DEC_PV' => '报单PV',
+            'PAID_WALLET' => '支付钱包',
+            'IS_BATCH' => '是否批量报单',
+            'REMARK' => '备注',
+            'REC_USER_ID' => '开拓人编号',
+            'CON_USER_ID' => '上级编号1',
+            'DEC_ID' => '上级编号2',
+            'PERIOD_NUM' => '报单期数',
+            'P_CALC_MONTH' => '分区结算月',
+            'CALC_MONTH' => '结算月',
+            'CREATED_AT' => '创建时间',
+            'UPDATER' => '操作人',
+            'UPDATED_AT' => '更新时间',
+            'IS_DEL' => '是否删除',
+            'DELETED_AT' => '删除时间',
+        ];
+    }
+}

+ 157 - 0
common/models/BaOrder.php

@@ -0,0 +1,157 @@
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%BA_ORDER}}".
+ *
+ * @property string $ID
+ * @property string $SN 订单号
+ * @property string $DEC_SN 报单编号
+ * @property string $USER_ID 用户ID
+ * @property string $USER_NAME 会员编号
+ * @property string $ORDER_TYPE 订货类型
+ * @property string $ORDER_AMOUNT 订单总价格(n)
+ * @property string $ORDER_AMOUNT_STANDARD 订单总价格($)
+ * @property string $PV 订货PV
+ * @property string $PAY_AMOUNT 支付价格
+ * @property string $PAY_AMOUNT_STANDARD 支付价格
+ * @property string $EXCHANGE_RATE 汇率
+ * @property string $PAY_PV 实付PV
+ * @property int $PAY_AT 支付时间
+ * @property string $PAY_TYPE 支付方式
+ * @property string $FREIGHT 运费
+ * @property string $PAY_FREIGHT 实付运费金额
+ * @property int $DELIVERY_STATUS 发货状态
+ * @property int $DELIVERY_PERIOD 发货期数
+ * @property int $DELIVERY_AT 发货时间
+ * @property string $EXPRESS_COMPANY 快递公司
+ * @property string $ORDER_TRACK_NO 快递单号
+ * @property int $EXPRESS_TYPE 发货方式
+ * @property string $FRONT_REMARK 前台备注
+ * @property string $REMARK 后台备注
+ * @property int $PERIOD_NUM 期数
+ * @property int $STATUS 订单状态
+ * @property string $CONSIGNEE 收货人
+ * @property string $MOBILE 收货人手机
+ * @property string $TEL 固定电话
+ * @property int $PROVINCE 省份名称
+ * @property int $CITY 城市名称
+ * @property int $COUNTY 县区
+ * @property string $LGA_NAME
+ * @property string $CITY_NAME
+ * @property string $ADDRESS 详细地址
+ * @property string $P_CALC_MONTH 分区日期
+ * @property int $CREATED_AT 订单创建时间
+ * @property string $CREATE_USER 订单创建人
+ * @property int $UPDATED_AT 修改时间
+ * @property string $UPDATER 修改人
+ * @property int $IS_DELETE 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $WAREHOUSE 发货仓
+ * @property string $EMAIL 邮箱
+ * @property string $NOTE 备注说明
+ */
+class BaOrder extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%BA_ORDER}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'USER_NAME', 'ORDER_TYPE', 'CREATE_USER'/*, 'EMAIL'*/], 'required'],
+            [['ORDER_AMOUNT', 'PV', 'PAY_AMOUNT', 'PAY_PV', 'FREIGHT', 'PAY_FREIGHT', 'ORDER_AMOUNT_STANDARD', 'PAY_AMOUNT_STANDARD', 'EXCHANGE_RATE'], 'number'],
+            [['PAY_AT', 'DELIVERY_STATUS', 'DELIVERY_PERIOD', 'DELIVERY_AT', 'EXPRESS_TYPE', 'PERIOD_NUM', 'STATUS', 'PROVINCE', /*'CITY', 'COUNTY', */'CREATED_AT', 'UPDATED_AT', 'IS_DELETE', 'DELETED_AT'], 'integer'],
+            [['ID','SN', 'DEC_SN', 'USER_ID', 'ORDER_TRACK_NO','PAY_TYPE'], 'string', 'max' => 32],
+            [['USER_NAME', 'TEL', 'CREATE_USER', 'UPDATER', 'WAREHOUSE'], 'string', 'max' => 16],
+            [['ORDER_TYPE'], 'string', 'max' => 12],
+            [['EXPRESS_COMPANY'], 'string', 'max' => 128],
+            [['FRONT_REMARK'], 'string', 'max' => 1000],
+            [['REMARK', 'NOTE'], 'string', 'max' => 4000],
+            [['CONSIGNEE'], 'string', 'max' => 120],
+            [['MOBILE'], 'string', 'max' => 11],
+            [['ADDRESS'], 'string', 'max' => 255],
+            [['SN'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'SN' => '订单号',
+            'DEC_SN' => '报单编号',
+            'USER_ID' => '用户ID',
+            'USER_NAME' => '会员编号',
+            'ORDER_TYPE' => '订货类型',
+            'ORDER_AMOUNT' => '订单总价格',
+            'PV' => '订货BV',
+            'PAY_AMOUNT' => '支付价格',
+            'PAY_PV' => '实付BV',
+            'PAY_AT' => '支付时间',
+            'PAY_TYPE' => '支付方式',
+            'FREIGHT' => '运费',
+            'PAY_FREIGHT' => '实付运费金额',
+            'DELIVERY_STATUS' => '发货状态',
+            'DELIVERY_PERIOD' => '发货期数',
+            'DELIVERY_AT' => '发货时间',
+            'EXPRESS_COMPANY' => '快递公司',
+            'ORDER_TRACK_NO' => '快递单号',
+            'EXPRESS_TYPE' => '发货方式',
+            'FRONT_REMARK' => '前台备注',
+            'REMARK' => '后台备注',
+            'PERIOD_NUM' => '期数',
+            'STATUS' => '订单状态',
+            'CONSIGNEE' => '收货人',
+            'MOBILE' => '收货人手机',
+            'TEL' => '固定电话',
+            'PROVINCE' => '省份名称',
+//            'CITY' => '城市名称',
+//            'COUNTY' => '县区',
+            'ADDRESS' => '详细地址',
+            'P_CALC_MONTH' => '分区日期',
+            'CREATED_AT' => '订单创建时间',
+            'CREATE_USER' => '订单创建人',
+            'UPDATED_AT' => '修改时间',
+            'UPDATER' => '修改人',
+            'IS_DELETE' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'WAREHOUSE' => '发货仓',
+            'EMAIL' => 'Email'
+        ];
+    }
+    /*
+     * 通过 期数和用户ID
+     * 查询当月订单
+     */
+    public static function fetchOrderCurrentMonth($periodNum, $userId){
+        $currentPeriod = Period::findOneAsArray("PERIOD_NUM = :PERIOD_NUM", [':PERIOD_NUM' => $periodNum]);
+
+        switch ($currentPeriod['CALC_WEEKEND']){
+            case 1:
+                $periods = [$periodNum];
+                break;
+            case 2:
+                $periods = [$periodNum-1, $periodNum];
+                break;
+        }
+
+        $periodsStr = implode(",", $periods);
+        $orders = BaOrder::find()->where("USER_ID = :USER_ID AND PERIOD_NUM IN ($periodsStr)", [':USER_ID' => $userId]);
+        return $orders;
+    }
+}

+ 77 - 0
common/models/BaOrderGoods.php

@@ -0,0 +1,77 @@
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%BA_ORDER_GOODS}}".
+ *
+ * @property string $ID
+ * @property string $ORDER_SN 订单ID
+ * @property string $GOODS_ID 商品ID
+ * @property string $GOODS_TITLE 商品名称
+ * @property string $PRICE 价格
+ * @property string $REAL_PRICE 实际价格
+ * @property string $PV 订货PV
+ * @property string $REAL_PV 实际PV
+ * @property string $TAX_RATE 税率
+ * @property string $POINT 兑换积分
+ * @property string $SKU_CODE 商品编码
+ * @property int $BUY_NUMS 购买数量
+ * @property string $P_CALC_MONTH 分区日期
+ * @property int CATEGORY_TYPE 商品分类
+ * @property int PAY_TYPE 支付方式
+ * @property string $EMAIL Email
+ */
+class BaOrderGoods extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%BA_ORDER_GOODS}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['ORDER_SN', 'GOODS_ID', 'GOODS_TITLE', 'SKU_CODE', 'CATEGORY_TYPE', 'PAY_TYPE', 'EMAIL'], 'required'],
+            [['PRICE', 'REAL_PRICE', 'PV', 'REAL_PV', 'POINT', 'CATEGORY_TYPE', 'PAY_TYPE', 'TAX_RATE'], 'number'],
+            [['BUY_NUMS'], 'integer'],
+            [['ID', 'ORDER_SN', 'GOODS_ID'], 'string', 'max' => 32],
+            [['GOODS_TITLE'], 'string', 'max' => 255],
+            [['SKU_CODE'], 'string', 'max' => 16],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'ORDER_SN' => '订单ID',
+            'GOODS_ID' => '商品ID',
+            'GOODS_TITLE' => '商品名称',
+            'PRICE' => '价格',
+            'REAL_PRICE' => '实际价格',
+            'PV' => '订货BV',
+            'REAL_PV' => '实际BV',
+            'TAX_RATE' => 'TAX_RATE',
+            'POINT' => '兑换积分',
+            'SKU_CODE' => '商品编码',
+            'BUY_NUMS' => '购买数量',
+            'P_CALC_MONTH' => '分区日期',
+            'CATEGORY_TYPE' => '商品分类',
+            'PAY_TYPE' => '支付方式',
+            'EMAIL' => 'Email'
+        ];
+    }
+}

+ 79 - 0
common/models/BaReceiveAddress.php

@@ -0,0 +1,79 @@
+<?php
+
+namespace common\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "{{%RECEIVE_ADDRESS}}".
+ *
+ * @property string $ID
+ * @property string $USER_ID 用户ID
+ * @property string $USER_NAME 用户编号
+ * @property string $CONSIGNEE 收货人
+ * @property string $MOBILE 收货人手机
+ * @property int $PROVINCE 省份名称
+ * @property int $CITY 城市名称
+ * @property int $COUNTY 县区名称
+ * @property string $LGA_NAME Lga
+ * @property string $CITY_NAME City
+ * @property string $ADDRESS 详细地址
+ * @property int $IS_DEFAULT 是否默认
+ * @property int $CREATED_AT 创建时间
+ * @property string $UPDATER 修改人
+ * @property int $UPDATED_AT 修改时间
+ */
+class BaReceiveAddress extends \common\components\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return '{{%BA_RECEIVE_ADDRESS}}';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'USER_NAME', 'CONSIGNEE', 'MOBILE', 'PROVINCE', 'ADDRESS'], 'required'],
+            [['PROVINCE', 'IS_DEFAULT', 'CREATED_AT', 'UPDATED_AT'], 'integer'],
+            [['ID', 'USER_ID'], 'string', 'max' => 32],
+            [['USER_NAME'], 'string', 'max' => 16],
+            [['CONSIGNEE'], 'string', 'max' => 120],
+            [['MOBILE'], 'string', 'max' => 11],
+            [['ADDRESS'], 'string', 'max' => 255],
+            [['LGA_NAME'], 'string', 'max' => 50],
+            [['CITY_NAME'], 'string', 'max' => 50],
+            [['UPDATER'], 'string', 'max' => 10],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '用户ID',
+            'USER_NAME' => '用户编号',
+            'CONSIGNEE' => '收货人',
+            'MOBILE' => '收货人手机',
+            'PROVINCE' => '省份名称',
+            'CITY' => '城市名称',
+            'COUNTY' => '县区名称',
+            'LGA_NAME' => 'Lga Name',
+            'CITY_NAME' => 'City Name',
+            'ADDRESS' => '详细地址',
+            'IS_DEFAULT' => '是否默认',
+            'CREATED_AT' => '创建时间',
+            'UPDATER' => '修改人',
+            'UPDATED_AT' => '修改时间',
+        ];
+    }
+}

+ 487 - 0
common/models/BaUser.php

@@ -0,0 +1,487 @@
+<?php
+
+namespace common\models;
+
+use common\components\ActiveRecord;
+use common\helpers\Cache;
+use Yii;
+use yii\helpers\Json;
+use common\libs\logging\operate\valueType\Config as ValueTypeConfig;
+
+/**
+ * This is the model class for table "{{%BA_USER}}".
+ *
+ * @property string $ID
+ * @property string $USER_NAME 帐号
+ * @property string $PASSWORD_HASH 登录密码
+ * @property string $PAY_PASSWORD 支付密码
+ * @property int $NATION 民族
+ * @property string $REAL_NAME 姓名
+ * @property string $ID_CARD 身份证号
+ * @property int $ID_TYPE 证件类型
+ * @property string $MOBILE 手机号
+ * @property string $ADDRESS 身份证地址
+ * @property string $ID_IMAGE 证件图片
+ * @property string $OPEN_BANK 开户行
+ * @property string $BANK_ADDRESS 银行地址
+ * @property string $BANK_NO 银行卡号
+ * @property int $BANK_PROVINCE 银行省份
+ * @property int $BANK_CITY 银行城市
+ * @property int $BANK_COUNTY 银行县区
+ * @property string $SPOUSE_NAME 配偶姓名
+ * @property string $SPOUSE_IDCARD 配偶证件号
+ * @property int $CREATED_AT 创建时间
+ * @property int $UPDATED_AT 更新时间
+ * @property int $STATUS 状态
+ * @property int $DEC_CLOSED 是否关闭报单功能
+ * @property int $DEC_CLOSED_AT 关闭时间
+ * @property string $DEC_LV 报单级别
+ * @property string $EMP_LV 聘级
+ * @property string $CROWN_LV 星级
+ * @property int $PROVINCE 省份
+ * @property int $CITY 城市
+ * @property int $COUNTY 县区
+ * @property string $TEL 座机
+ * @property string $SUB_COM_ID 子公司ID
+ * @property string $AVATAR 头像
+ * @property int $DELETED 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $IS_DEC 是否为报单中心
+ * @property int $IS_ATLAS 是否显示图谱
+ * @property int $IS_RECHARGE 是否显示充值
+ * @property string $DEC_ID 报单中心ID
+ * @property string $BIRTHDAY 生日
+ * @property string $DEC_ROLE_ID 报单中心级别
+ * @property int $PERIOD_AT 期数
+ * @property int $DEC_PROVINCE 报单中心所属的省份
+ * @property int $DEC_CITY 报单中心所属的城市
+ * @property int $DEC_COUNTY 报单中心所属的县区
+ * @property int $IS_UNION 是否为点位合作
+ * @property int $STATUS_AT 状态更改时间
+ * @property int $VERIFIED 是否认证
+ * @property int $VERIFIED_AT 认证时间
+ * @property int $ALLOW_LOGIN 允许登录
+ * @property int $NOT_OPERATING 不运作
+ * @property int $REG_FROM 注册类型
+ * @property string $ID_CARD_PREFIX 身份证前缀
+ * @property string $SEX 性别
+ * @property string $DEC_ACCOUNT_OLD 老系统中的报单中心编号
+ * @property int $BANK_UPDATED_AT 银行信息更新时间
+ * @property int $IS_DIRECT_SELLER 是否为直销员
+ * @property int $DEC_LV_UPDATED_AT 报单级别更新时间
+ * @property int $DEC_LV_UPDATED_PERIOD 报单级别更新期数
+ * @property string $DEC_ADDRESS 报单中心详细地址
+ * @property string $DEC_PHONE 报单中心电话
+ * @property string $GUARANTOR 担保人编号
+ * @property string $GUARANTOR_NAME 担保人姓名
+ * @property int $PART_FUNC_CLOSED 部分功能开启
+ * @property int $LAST_DEC_LV_UPDATED_PERIOD 上次报单级别更新期数
+ * @property string $USER_CREATOR 创建人
+ * @property string $USER_UPDATER 修改人
+ * @property int $LAST_DEC_LV_UPDATED_AT 上次报单级别更新时间
+ * @property int $DEC_CREATED_AT 成为报单中心时间
+ * @property string $PART_FUNC_CLOSED_REMARK 部分功能关闭原因
+ * @property int $DEC_CREATED_PERIOD 成为报单中心期数
+ * @property int $PASSWORD_CHANGED 是否修改过密码
+ * @property int $SUB_COM_LEADER 是否为分公司领导
+ * @property string $ZG_UPGRADE_PV 增购升级PV
+ * @property string $APP_CLIENT_ID APP设备ID
+ * @property int $READ_AGREEMENT 已读协议
+ * @property string $LAST_DEC_LV 上次的报单级别
+ * @property string $BONUS_APP_CLIENT_ID 结算APP设备ID
+ * @property int $IS_FIRST_OPEN 首次开通
+ * @property int $IS_MODIFY_PASSWORD 是否修改密码
+ * @property int $IS_STUDIO 是否是工作室
+ * @property string $EMAIL 邮箱
+ */
+class BaUser extends ActiveRecord
+{
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%BA_USER}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_NAME', 'PASSWORD_HASH', 'PAY_PASSWORD', 'REAL_NAME',/* 'ID_CARD',*/ 'AVATAR'], 'required'],
+            [['NATION', 'ID_TYPE', 'BANK_PROVINCE', 'BANK_CITY', 'BANK_COUNTY', 'CREATED_AT', 'UPDATED_AT', 'STATUS', 'DEC_CLOSED', 'DEC_CLOSED_AT', 'PROVINCE', 'CITY', 'COUNTY', 'DELETED', 'DELETED_AT', 'IS_DEC', 'IS_ATLAS', 'IS_RECHARGE','IS_STUDIO',  'PERIOD_AT', 'DEC_PROVINCE', 'DEC_CITY', 'DEC_COUNTY', 'IS_UNION', 'STATUS_AT', 'VERIFIED', 'VERIFIED_AT', 'ALLOW_LOGIN', 'NOT_OPERATING', 'REG_FROM', 'BANK_UPDATED_AT', 'IS_DIRECT_SELLER', 'DEC_LV_UPDATED_AT', 'DEC_LV_UPDATED_PERIOD', 'PART_FUNC_CLOSED', 'LAST_DEC_LV_UPDATED_PERIOD', 'LAST_DEC_LV_UPDATED_AT', 'DEC_CREATED_AT', 'DEC_CREATED_PERIOD', 'PASSWORD_CHANGED', 'SUB_COM_LEADER', 'READ_AGREEMENT', 'IS_FIRST_OPEN', 'IS_MODIFY_PASSWORD'], 'integer'],
+            [['ZG_UPGRADE_PV'], 'number'],
+            [['ID', 'OPEN_BANK', 'BANK_NO', 'DEC_LV', 'EMP_LV', 'CROWN_LV', 'SUB_COM_ID', 'DEC_ID', 'DEC_ROLE_ID', 'ID_CARD_PREFIX', 'SEX', 'DEC_PHONE', 'GUARANTOR', 'USER_CREATOR', 'USER_UPDATER', 'LAST_DEC_LV', 'EMAIL'], 'string', 'max' => 32],
+            [['USER_NAME', 'SPOUSE_NAME', 'TEL'], 'string', 'max' => 16],
+            [['PASSWORD_HASH', 'PAY_PASSWORD', 'ID_IMAGE', 'BANK_ADDRESS', 'AVATAR'], 'string', 'max' => 255],
+            [['REAL_NAME', 'APP_CLIENT_ID', 'BONUS_APP_CLIENT_ID'], 'string', 'max' => 128],
+//            [['ID_CARD', 'SPOUSE_IDCARD'], 'string','min' => 18, 'max' => 18],
+            [['MOBILE'], 'string','min' => 11, 'max' => 11],
+            [['ADDRESS', 'DEC_ADDRESS'], 'string', 'max' => 2000],
+            [['DEC_ACCOUNT_OLD', 'GUARANTOR_NAME'], 'string', 'max' => 64],
+            [['PART_FUNC_CLOSED_REMARK'], 'string', 'max' => 4000],
+            [['USER_NAME'], 'unique'],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_NAME' => '帐号',
+            'PASSWORD_HASH' => '登录密码',
+            'PAY_PASSWORD' => '支付密码',
+            'NATION' => '民族',
+            'REAL_NAME' => '姓名',
+            'ID_CARD' => '身份证号',
+            'ID_TYPE' => '证件类型',
+            'MOBILE' => '手机号',
+            'ADDRESS' => '身份证地址',
+            'ID_IMAGE' => '证件图片',
+            'OPEN_BANK' => '开户行',
+            'BANK_ADDRESS' => '银行地址',
+            'BANK_NO' => '银行卡号',
+            'BANK_PROVINCE' => '银行省份',
+            'BANK_CITY' => '银行城市',
+            'BANK_COUNTY' => '银行县区',
+            'SPOUSE_NAME' => '配偶姓名',
+            'SPOUSE_IDCARD' => '配偶证件号',
+            'CREATED_AT' => '创建时间',
+            'UPDATED_AT' => '更新时间',
+            'STATUS' => '状态',
+            'DEC_CLOSED' => '是否关闭报单功能',
+            'DEC_CLOSED_AT' => '关闭时间',
+            'DEC_LV' => '报单级别',
+            'EMP_LV' => '聘级',
+            'CROWN_LV' => '星级',
+            'PROVINCE' => '省份',
+            'CITY' => '城市',
+            'COUNTY' => '县区',
+            'TEL' => '座机',
+            'SUB_COM_ID' => '子公司ID',
+            'AVATAR' => '头像',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'IS_DEC' => '是否为报单中心',
+            'IS_ATLAS' => '是否显示图谱',
+            'IS_RECHARGE' => '是否显示充值',
+            'DEC_ID' => '报单中心ID',
+            'BIRTHDAY' => '生日',
+            'DEC_ROLE_ID' => '报单中心级别',
+            'PERIOD_AT' => '期数',
+            'DEC_PROVINCE' => '报单中心所属的省份',
+            'DEC_CITY' => '报单中心所属的城市',
+            'DEC_COUNTY' => '报单中心所属的县区',
+            'IS_UNION' => '是否为点位合作',
+            'STATUS_AT' => '状态更改时间',
+            'VERIFIED' => '是否认证',
+            'VERIFIED_AT' => '认证时间',
+            'ALLOW_LOGIN' => '允许登录',
+            'NOT_OPERATING' => '不运作',
+            'REG_FROM' => '注册类型',
+            'ID_CARD_PREFIX' => '身份证前缀',
+            'SEX' => '性别',
+            'DEC_ACCOUNT_OLD' => '老系统中的报单中心编号',
+            'BANK_UPDATED_AT' => '银行信息更新时间',
+            'IS_DIRECT_SELLER' => '是否为直销员',
+            'DEC_LV_UPDATED_AT' => '报单级别更新时间',
+            'DEC_LV_UPDATED_PERIOD' => '报单级别更新期数',
+            'DEC_ADDRESS' => '报单中心详细地址',
+            'DEC_PHONE' => '报单中心电话',
+            'GUARANTOR' => '担保人编号',
+            'GUARANTOR_NAME' => '担保人姓名',
+            'PART_FUNC_CLOSED' => '部分功能开启',
+            'LAST_DEC_LV_UPDATED_PERIOD' => '上次报单级别更新期数',
+            'USER_CREATOR' => '创建人',
+            'USER_UPDATER' => '修改人',
+            'LAST_DEC_LV_UPDATED_AT' => '上次报单级别更新时间',
+            'DEC_CREATED_AT' => '成为报单中心时间',
+            'PART_FUNC_CLOSED_REMARK' => '部分功能关闭原因',
+            'DEC_CREATED_PERIOD' => '成为报单中心期数',
+            'PASSWORD_CHANGED' => '是否修改过密码',
+            'SUB_COM_LEADER' => '是否为分公司领导',
+            'ZG_UPGRADE_PV' => '增购升级PV',
+            'APP_CLIENT_ID' => 'APP设备ID',
+            'READ_AGREEMENT' => '已读协议',
+            'LAST_DEC_LV' => '上次的报单级别',
+            'BONUS_APP_CLIENT_ID' => '结算APP设备ID',
+            'IS_FIRST_OPEN' => '首次开通',
+            'IS_MODIFY_PASSWORD' => '是否修改密码',
+            'IS_STUDIO' => '是否是工作室',
+            'EMAIL' => 'Email',
+        ];
+    }
+
+    public function getUserInfo()
+    {
+        return $this->hasOne(BaUserInfo::class, ['USER_ID' => 'ID']);
+    }
+
+    /**
+     * 获取会员基本信息
+     * @param $userId
+     * @return array|null|\yii\db\ActiveRecord
+     */
+    public static function getBaseInfo($userId){
+        return static::findUseSlaves()->where('ID=:ID', [':ID'=>$userId])->asArray()->one();
+    }
+
+    /**
+     * 获取用户基本信息从redis里面
+     * @param $userId
+     * @return array|null|\yii\db\ActiveRecord
+     */
+    public static function getBaseInfoFromRedis($userId){
+        $userInfo = Yii::$app->redis->hget(Cache::USER_INFO_KEY, $userId);
+        if(!$userInfo){
+            $userInfo = static::find()->select('ID,USER_NAME,NATION,REAL_NAME,ID_CARD,ID_TYPE,MOBILE,ADDRESS,STATUS,DEC_LV,LAST_DEC_LV,EMP_LV,CROWN_LV,DEC_CLOSED,AVATAR,OPEN_BANK,BANK_ADDRESS,BANK_NO,VERIFIED,IS_UNION,IS_DEC,IS_ATLAS,IS_RECHARGE,IS_STUDIO,DEC_ROLE_ID,PROVINCE,CITY,COUNTY,EMAIL')->where('ID=:ID', [':ID'=>$userId])->asArray()->one();
+            Yii::$app->redis->hset(Cache::USER_INFO_KEY, $userId, Json::encode($userInfo));
+        } else {
+            $userInfo = Json::decode($userInfo);
+        }
+        return $userInfo;
+    }
+
+    /**
+     * 更新缓存
+     * @param $userId
+     * @return mixed
+     */
+    public static function updateBaseInfoToRedis($userId){
+        $userInfo = static::find()->select('ID,USER_NAME,NATION,REAL_NAME,ID_CARD,ID_TYPE,MOBILE,ADDRESS,STATUS,DEC_LV,LAST_DEC_LV,EMP_LV,CROWN_LV,DEC_CLOSED,AVATAR,OPEN_BANK,BANK_ADDRESS,BANK_NO,VERIFIED,IS_UNION,IS_DEC,IS_ATLAS,IS_RECHARGE,IS_STUDIO,DEC_ROLE_ID,PROVINCE,CITY,COUNTY,EMAIL')->where('ID=:ID', [':ID'=>$userId])->asArray()->one();
+        return Yii::$app->redis->hset(Cache::USER_INFO_KEY, $userId, Json::encode($userInfo));
+    }
+
+    /**
+     * @param $userId
+     * 删除用户信息缓存
+     */
+    public static function deleteBaseInfoFromRedis($userId) {
+        Yii::$app->redis->hdel(Cache::USER_INFO_KEY, $userId);
+    }
+
+    /**
+     *  判断用户是否是观察期
+     *  观望期:自加入算起2个月
+     *  例子:2022年5月14日加入, 观望期至2022年7月31日。
+     *  true为是观察期用户  false为不是观察期用户
+     * @param $addAt 用户的加入时间
+     * @param $month 观察期月份限制 系统初始化为2个月
+     */
+    public static function checkIsObserve($addAt, $month) {
+        if (empty($month)) {
+            // 如果0 代表全站全额升级
+            return false;
+        }
+        $appendMonth = date("Y-m", strtotime("first day of +$month month", $addAt)); // 指定月份
+        $lastDay = date("t", strtotime($appendMonth));  // 获取指定月的最后一天
+        $eTime = strtotime($appendMonth.'-'.$lastDay);
+
+        return time() < $eTime ? true : false;
+    }
+
+    /**
+     * 获取会员的部分信息并对敏感信息加密
+     * @param $userId
+     * @return array
+     */
+    public static function getEnCodeInfo($userId){
+        $userInfo = self::getBaseInfoFromRedis($userId);
+        return [
+            'ID' => $userId,
+            'USER_NAME' => $userInfo['USER_NAME'],
+            'NATION' => \Yii::$app->params['nation'][$userInfo['NATION']]['name']??'',
+            'NATION_ID' => \Yii::$app->params['nation'][$userInfo['NATION']]['id']??'',
+            'REAL_NAME' => $userInfo['REAL_NAME'],
+            'ID_CARD' => $userInfo['ID_CARD'],
+//            'ID_CARD' => Tool::hideIdCard($userInfo['ID_CARD']),
+            'MOBILE' => $userInfo['MOBILE'],
+//            'MOBILE' => Tool::hideMobile($userInfo['MOBILE']),
+            'AVATAR' => $userInfo['AVATAR'],
+            'VERIFIED' => $userInfo['VERIFIED'],
+            'IS_UNION' => $userInfo['IS_UNION'],
+            'IS_DEC' => $userInfo['IS_DEC'],
+            'IS_ATLAS' => $userInfo['IS_ATLAS'],
+            'IS_RECHARGE' => $userInfo['IS_RECHARGE'],
+            'IS_STUDIO' => $userInfo['IS_STUDIO'],
+            'DEC_ROLE_ID' => $userInfo['DEC_ROLE_ID'],
+            'OPEN_BANK' => $userInfo['OPEN_BANK'],
+            'BANK_ADDRESS' => $userInfo['BANK_ADDRESS'],
+            'DEC_LV' => $userInfo['DEC_LV'],
+            'EMP_LV' => $userInfo['EMP_LV'],
+            'CROWN_LV' => $userInfo['CROWN_LV'],
+            'PROVINCE' => $userInfo['PROVINCE'],
+            'CITY' => $userInfo['CITY'],
+            'COUNTY' => $userInfo['COUNTY'],
+            'BANK_NO' => $userInfo['BANK_NO'],
+//            'BANK_NO' => Tool::hideBankNo($userInfo['BANK_NO']),
+            'EMAIL' => $userInfo['EMAIL'],
+        ];
+    }
+
+    /**
+     * 验证密码
+     * @param $password
+     * @return bool
+     */
+    public function validatePassword($password) {
+        if( !$this->PASSWORD_HASH ) return false;
+
+        return password_verify($password, $this->PASSWORD_HASH);
+    }
+
+    /**
+     * 验证支付密码
+     * @param $payPassword
+     * @return bool
+     */
+    public function validatePasswordPay($payPassword) {
+        if( !$this->PAY_PASSWORD ) return false;
+
+        return password_verify($payPassword, $this->PAY_PASSWORD);
+    }
+
+    /**
+     * 检验支付密码
+     * @param $userId
+     * @param $password
+     * @return bool
+     */
+    public static function validatePayPassword($userId, $password){
+        $oneUser = static::find()->select('PAY_PASSWORD')->where('ID=:ID', [':ID'=>$userId])->asArray()->one();
+        if($oneUser){
+            return password_verify($password, $oneUser['PAY_PASSWORD']);
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * 操作日志记录条件
+     * @return array
+     */
+    public function attrLabelsWithLogType(){
+        return [
+            'ID' => 'ID',
+            'USER_NAME' => '帐号',
+            'NATION' => [
+                'label' => '民族',
+                'type' => function($data){
+                    $value = $data['value'];
+                    return \Yii::$app->params['nation'][$value]['name']??'';
+                },
+            ],
+            'REAL_NAME' => '姓名',
+            'ID_CARD' => '身份证号',
+            'ID_TYPE' => [
+                'label' => '证件类型',
+                'type' => function($data){
+                    return '身份证';
+                },
+            ],
+            'MOBILE' => '手机号',
+            'ADDRESS' => '身份证地址',
+            'ID_IMAGE' => '证件图片',
+            'OPEN_BANK' => '开户行',
+            'BANK_ADDRESS' => '银行地址',
+            'BANK_NO' => '银行卡号',
+            'BANK_PROVINCE' => [
+                'label' => '银行省份',
+                'type' => ValueTypeConfig::REGION_TYPE
+            ],
+            'BANK_CITY' => [
+                'label' => '银行城市',
+                'type' => ValueTypeConfig::REGION_TYPE
+            ],
+            'BANK_COUNTY' => [
+                'label' => '银行县区',
+                'type' => ValueTypeConfig::REGION_TYPE
+            ],
+            'SPOUSE_NAME' => '配偶姓名',
+            'SPOUSE_IDCARD' => '配偶证件号',
+            'STATUS' => [
+                'label' => '状态',
+                'type' => ValueTypeConfig::USER_STATUS_TYPE
+            ],
+            'DEC_CLOSED' => [
+                'label' => '是否关闭报单功能',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'DEC_CLOSED_AT' => [
+                'label' => '关闭报单时间',
+                'type' => ValueTypeConfig::DATE_TIME_TYPE,
+            ],
+            'DEC_LV' => [
+                'label' => '报单级别',
+                'type' => ValueTypeConfig::DEC_LV_TYPE,
+            ],
+            'EMP_LV' => [
+                'label' => '聘级',
+                'type' => ValueTypeConfig::EMP_LV_TYPE,
+            ],
+            'CROWN_LV' => [
+                'label' => '星级',
+                'type' => ValueTypeConfig::CROWN_LV_TYPE,
+            ],
+            'LAST_DEC_LV' => [
+                'label' => '上次的报单级别',
+                'type' => ValueTypeConfig::DEC_LV_TYPE,
+            ],
+            'PROVINCE' => [
+                'label' => '省份',
+                'type' => ValueTypeConfig::REGION_TYPE
+            ],
+            'CITY' => [
+                'label' => '城市',
+                'type' => ValueTypeConfig::REGION_TYPE
+            ],
+            'COUNTY' => [
+                'label' => '县区',
+                'type' => ValueTypeConfig::REGION_TYPE
+            ],
+            'TEL' => '备用手机号码',
+            'SUB_COM_ID' => '分公司ID',
+            'TRANSFER_PROP' => '转帐比例',
+            'IS_DEC' => [
+                'label' => '是否为报单中心',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'DEC_ROLE_ID' => [
+                'label' => '报单中心级别',
+                'type' => ValueTypeConfig::DEC_ROLE_ID_TYPE,
+            ],
+            'IS_UNION' => [
+                'label' => '是否为点位合作',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'STATUS_AT' => '状态修改时间',
+            'ALLOW_LOGIN' => [
+                'label' => '是否允许商城登录',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'NOT_OPERATING' => [
+                'label' => '不运作',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'BIRTHDAY' => '生日',
+            'SEX' => '性别',
+            'EMAIL' => 'Email'
+        ];
+    }
+
+    /**
+     * Finds user by username
+     *
+     * @param string $username
+     * @return static|null
+     */
+    public static function findByUsername($username) {
+        return static::findOne(['USER_NAME' => $username]);
+    }
+}

+ 251 - 0
common/models/BaUserInfo.php

@@ -0,0 +1,251 @@
+<?php
+
+namespace common\models;
+
+use common\helpers\user\Info;
+use Yii;
+use common\libs\logging\operate\valueType\Config as ValueTypeConfig;
+
+/**
+ * This is the model class for table "{{%USER_INFO}}".
+ *
+ * @property string $ID
+ * @property string $USER_ID 会员ID
+ * @property string $USER_NAME 会员名
+ * @property string $ZC_PV 注册单PV
+ * @property string $CON_UID 接点人ID
+ * @property string $REC_UID 推荐人ID
+ * @property int $CON_NUM 下级节点数量
+ * @property int $REC_NUM 开拓会员数量
+ * @property int $NETWORK_DEEP 安置网络深度
+ * @property int $RELATION_DEEP 开拓网络深度
+ * @property string $SYSTEM_ID 体系ID
+ * @property int $IS_SYSTEM_LEADER 是否体系领导人
+ * @property int $IS_TEAM 是否点位合作
+ * @property int $IS_BIND 是否点位绑定
+ * @property int $IS_TEAM_MAIN 是否点位合作主点
+ * @property int $IS_BIND_MAIN 是否点位绑定主点
+ * @property int $IS_AUTO_WITHDRAW 是否开启自动提现
+ * @property int $CLOSE_LOGIN 关闭结算系统登录
+ * @property string $REG_TYPE 注册类型
+ * @property string $SHOULD_REG_TYPE 应注册类型
+ * @property string $REG_NAME 注册名称
+ * @property string $CREDIT_CODE 信用代码
+ * @property string $PREMISES 经营场所
+ * @property string $LEGAL_PERSON 法人
+ * @property int $REG_EXPIRES 注册有效期
+ * @property int $STORE_TYPE 店铺类型
+ * @property string $INVOICE_BALANCE 发票余额
+ * @property string $HIGHEST_EMP_LV 历史最高聘级
+ * @property int $CREATED_AT 创建时间
+ * @property int $UPDATED_AT 更新时间
+ * @property int $CLOSE_LOGIN_AT 禁止登录时间
+ * @property int $PULLED_AT 站内信拉取时间
+ * @property int $DELETED 是否删除
+ * @property int $DELETED_AT 删除时间
+ * @property int $ALLOW_TRANSFER 开启转账功能
+ * @property int $ALLOW_RECONSUME_SMS 开启复销短信提醒
+ * @property int $ALLOW_RECONSUME_SMS_TO 开启复销短信提醒有效期
+ * @property int $HIGHEST_EMP_LV_PERIOD 首次达到最高聘级期数
+ * @property int $IS_GROUP_LEADER 是否团队领导人
+ * @property int $GROUP_LEADER_AT 成为团队领导人时间
+ * @property string $TRANSFER_PROP 单笔转账比例
+ * @property int $LOGIN_NUMS 登录次数
+ * @property int $FAIL_NUMS 登录失败次数
+ * @property string $LAST_LOGIN_IP 上次登录IP
+ * @property int $LAST_LOGIN_AT 上次登录时间
+ * @property string $SHOW_EMP_LV 展示聘级
+ * @property string $ZC_AMOUNT 注册单报单金额
+ */
+class BaUserInfo extends \common\components\ActiveRecord
+{
+    const STORE_TYPE_NORMAL = 0;    // 一般会员无店铺标识
+    const STORE_TYPE_GENERAL = 1;   // 店铺
+    const STORE_TYPE_IMAGE = 2;     // 形象店
+    const STORE_TYPE_SERVICE = 3;   // 服务点、具有报单功能的会员
+    const STORE_TYPE_AREA = 4;   // 区级店
+
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%BA_USER_INFO}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'USER_NAME',/* 'CON_UID', 'REC_UID',*/ 'CREATED_AT'], 'required'],
+//            [['ZC_PV', 'INVOICE_BALANCE', 'TRANSFER_PROP', 'ZC_AMOUNT'], 'number'],
+            [['CON_NUM', 'REC_NUM', 'NETWORK_DEEP', 'RELATION_DEEP', 'IS_SYSTEM_LEADER', 'IS_TEAM', 'IS_BIND', 'IS_TEAM_MAIN', 'IS_BIND_MAIN', 'IS_AUTO_WITHDRAW', 'CLOSE_LOGIN', 'REG_EXPIRES', 'STORE_TYPE', 'CREATED_AT', 'UPDATED_AT', 'CLOSE_LOGIN_AT', 'PULLED_AT', 'DELETED', 'DELETED_AT', 'ALLOW_TRANSFER', 'HIGHEST_EMP_LV_PERIOD', 'IS_GROUP_LEADER', 'GROUP_LEADER_AT', 'ALLOW_RECONSUME_SMS', 'ALLOW_RECONSUME_SMS_TO', 'LOGIN_NUMS', 'FAIL_NUMS', 'LAST_LOGIN_AT'], 'integer'],
+            [['ID','USER_ID', 'CON_UID', 'REC_UID', 'SYSTEM_ID', 'REG_TYPE', 'SHOULD_REG_TYPE', 'HIGHEST_EMP_LV', 'SHOW_EMP_LV'], 'string', 'max' => 32],
+            [['USER_NAME', 'LAST_LOGIN_IP'], 'string', 'max' => 16],
+            [['REG_NAME', 'CREDIT_CODE', 'PREMISES', 'LEGAL_PERSON'], 'string', 'max' => 255],
+            [['USER_ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '会员ID',
+            'USER_NAME' => '会员名',
+            'ZC_PV' => '注册单PV',
+            'CON_UID' => '接点人ID',
+            'REC_UID' => '推荐人ID',
+            'CON_NUM' => '下级节点数量',
+            'REC_NUM' => '开拓会员数量',
+            'NETWORK_DEEP' => '安置网络深度',
+            'RELATION_DEEP' => '开拓网络深度',
+            'SYSTEM_ID' => '体系ID',
+            'IS_SYSTEM_LEADER' => '是否体系领导人',
+            'IS_TEAM' => '是否点位合作',
+            'IS_BIND' => '是否点位绑定',
+            'IS_TEAM_MAIN' => '是否点位合作主点',
+            'IS_BIND_MAIN' => '是否点位绑定主点',
+            'IS_AUTO_WITHDRAW' => '是否开启自动提现',
+            'CLOSE_LOGIN' => '关闭结算系统登录',
+            'REG_TYPE' => '注册类型',
+            'SHOULD_REG_TYPE' => '应注册类型',
+            'REG_NAME' => '注册名称',
+            'CREDIT_CODE' => '信用代码',
+            'PREMISES' => '经营场所',
+            'LEGAL_PERSON' => '法人',
+            'REG_EXPIRES' => '注册有效期',
+            'STORE_TYPE' => '店铺类型',
+            'INVOICE_BALANCE' => '发票余额',
+            'HIGHEST_EMP_LV' => '历史最高聘级',
+            'CREATED_AT' => '创建时间',
+            'UPDATED_AT' => '更新时间',
+            'CLOSE_LOGIN_AT' => '禁止登录时间',
+            'PULLED_AT' => '站内信拉取时间',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'ALLOW_TRANSFER' => '开启转账功能',
+            'ALLOW_RECONSUME_SMS' => '开启复销短信提醒',
+            'ALLOW_RECONSUME_SMS_TO' => '开启复销短信提醒有效期',
+            'HIGHEST_EMP_LV_PERIOD' => '首次达到最高聘级期数',
+            'IS_GROUP_LEADER' => '是否团队领导人',
+            'GROUP_LEADER_AT' => '团队领导人时间',
+            'TRANSFER_PROP' => '单笔转账比例',
+            'LOGIN_NUMS' => '登录次数',
+            'FAIL_NUMS' => '登录失败次数',
+            'LAST_LOGIN_IP' => '上次登录IP',
+            'LAST_LOGIN_AT' => '上次登录时间',
+            'SHOW_EMP_LV' => '展示聘级',
+            'ZC_AMOUNT' => '注册单报单金额',
+        ];
+    }
+
+    /**
+     * 删除会员
+     * @param $userId
+     */
+    public static function deleteUser($userId){
+        static::deleteAll('USER_ID=:USER_ID', [':USER_ID'=>$userId]);
+        UserNetwork::deleteAll('USER_ID=:USER_ID', [':USER_ID'=>$userId]);
+        UserRelation::deleteAll('USER_ID=:USER_ID', [':USER_ID'=>$userId]);
+        UserBonus::deleteAll('USER_ID=:USER_ID', [':USER_ID'=>$userId]);
+        UserPerf::deleteAll('USER_ID=:USER_ID', [':USER_ID'=>$userId]);
+    }
+
+    /**
+     * 获取会员接点人推荐人
+     * @param $userId
+     * @return array|null
+     */
+    public static function getNetByUserId($userId){
+        return static::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'CON_UID,REC_UID');
+    }
+
+    /**
+     * 操作日志记录条件
+     * @return array
+     */
+    public function attrLabelsWithLogType(){
+        return [
+            'USER_ID' => '会员ID',
+            'USER_NAME' => '会员名',
+//            'ZC_PV' => '注册单PV',
+            'CON_UID' => [
+                'label' => '接点人编号',
+                'type' => function($data){
+                    $value = $data['value'];
+                    return Info::getUserNameByUserId($value);
+                },
+            ],
+            'REC_UID' => [
+                'label' => '接点人编号',
+                'type' => function($data){
+                    $value = $data['value'];
+                    return Info::getUserNameByUserId($value);
+                },
+            ],
+            'CON_NUM' => '下级节点数量',
+            'REC_NUM' => '开拓会员数量',
+            'NETWORK_DEEP' => '安置网络深度',
+            'RELATION_DEEP' => '开拓网络深度',
+            'SYSTEM_ID' => '体系ID',
+            'IS_SYSTEM_LEADER' => '是否体系领导人',
+            'IS_TEAM' => '是否点位合作',
+            'IS_BIND' => '是否点位绑定',
+            'IS_TEAM_MAIN' => '是否点位合作主点',
+            'IS_BIND_MAIN' => '是否点位绑定主点',
+            'IS_AUTO_WITHDRAW' => [
+                'label' => '是否开启自动提现',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'CLOSE_LOGIN' => '关闭结算系统登录',
+            'REG_TYPE' => '注册类型',
+            'SHOULD_REG_TYPE' => '应注册类型',
+            'REG_NAME' => '注册名称',
+            'CREDIT_CODE' => '信用代码',
+            'PREMISES' => '经营场所',
+            'LEGAL_PERSON' => '法人',
+            'REG_EXPIRES' => '注册有效期',
+            'STORE_TYPE' => '店铺类型',
+            'INVOICE_BALANCE' => '发票余额',
+            'HIGHEST_EMP_LV' => '历史最高聘级',
+            'CREATED_AT' => '创建时间',
+            'UPDATED_AT' => '更新时间',
+            'CLOSE_LOGIN_AT' => '禁止登录时间',
+            'PULLED_AT' => '站内信拉取时间',
+            'DELETED' => '是否删除',
+            'DELETED_AT' => '删除时间',
+            'ALLOW_TRANSFER' => [
+                'label' => '开启转账功能',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'ALLOW_RECONSUME_SMS' => [
+                'label' => '开启复销短信提醒',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'ALLOW_RECONSUME_SMS_TO' => [
+                'label' => '开启复销短信提醒有效期',
+                'type' => ValueTypeConfig::DATE_TYPE,
+            ],
+            'HIGHEST_EMP_LV_PERIOD' => '首次达到最高聘级期数',
+            'IS_GROUP_LEADER' => [
+                'label' => '是否团队领导人',
+                'type' => ValueTypeConfig::YES_NO_TYPE,
+            ],
+            'GROUP_LEADER_AT' => [
+                'label' => '团队领导人时间',
+                'type' => ValueTypeConfig::DATE_TIME_TYPE,
+            ],
+            'TRANSFER_PROP' => '单笔转账比例',
+            'SHOW_EMP_LV' => [
+                'label' => '前台显示聘级',
+                'type' => ValueTypeConfig::EMP_LV_TYPE,
+            ],
+        ];
+    }
+}

+ 0 - 0
common/models/CalcBonusQuarter.php


+ 0 - 0
common/models/CalcBonusVilla.php


+ 0 - 0
common/models/FlowRemainPv.php


+ 0 - 0
common/models/FlowVillaPoints.php


+ 0 - 0
common/models/RemainPv.php


+ 8 - 0
common/models/User.php

@@ -267,6 +267,14 @@ class User extends \common\components\ActiveRecord
         Yii::$app->redis->hdel(Cache::USER_INFO_KEY, $userId);
     }
 
+    /**
+     * 批量删除用户
+     * @return void
+     */
+    public static function deleteAllBaseInfoFromRedis() {
+        \Yii::$app->redis->del(Cache::USER_INFO_KEY);
+    }
+
     /**
      *  判断用户是否是观察期
      *  观望期:自加入算起2个月

+ 10 - 0
common/models/UserInfo.php

@@ -248,4 +248,14 @@ class UserInfo extends \common\components\ActiveRecord
             ],
         ];
     }
+
+    /**
+     * 查询安置网的会员
+     * @param $userId
+     * @return array|null
+     */
+    public static function getPlacementChildren($userId): ?array
+    {
+        return static::findAllAsArray('REC_UID=:REC_UID', [':REC_UID' => $userId], 'USER_ID,USER_NAME');
+    }
 }

+ 16 - 0
common/models/UserPerf.php

@@ -171,6 +171,12 @@ class UserPerf extends \common\components\ActiveRecord
             'PV_4L' => '四市场累计业绩',
             'PV_5L' => '五市场累计业绩',
             'PV_PSS' => '推荐团队累计业绩',
+            'SURPLUS_1L'    => '一市场综合结余业绩',
+            'SURPLUS_1L_ZC' => '一市场综合报单业绩',
+            'SURPLUS_1L_FX' => '一市场复消结余业绩',
+            'SURPLUS_2L'    => '二市场综合结余业绩',
+            'SURPLUS_2L_ZC' => '二市场综合报单业绩',
+            'SURPLUS_2L_FX' => '二市场复消结余业绩',
         ];
     }
 
@@ -217,4 +223,14 @@ class UserPerf extends \common\components\ActiveRecord
 
         return $result;
     }
+
+    /**
+     * 查询会员结余业绩
+     * @param $userId
+     * @return array|null
+     */
+    public static function getPerfMarket($userId): ?array
+    {
+        return self::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'USER_ID,SURPLUS_1L,SURPLUS_1L_ZC,SURPLUS_1L_FX,SURPLUS_2L,SURPLUS_2L_ZC,SURPLUS_2L_FX');
+    }
 }

+ 6 - 3
common/models/Withdraw.php

@@ -157,13 +157,16 @@ class Withdraw extends \common\components\ActiveRecord {
      */
     public static function getPeriod($nowTime) {
         $period = Period::instance();
+        $nowPeriodNum = $period->getNowPeriodNum();
         $year = $period->getNowYear();
         $month = $period->getNowMonth();
         $yearMonth = $period->getNowYearMonth();
-        $thisMonth = Period::getPeriodNumRangeFromMonth($year, $month);
-        $period->setPeriodNum($thisMonth['min']);
+//        $thisMonth = Period::getPeriodNumRangeFromMonth($year, $month);
+//        $period->setPeriodNum($thisMonth['min']);
+        $period->setPeriodNum($nowPeriodNum);
         $endTime = $period->getNowPeriodEnd();
-        return ['nowPeriodNum' => $thisMonth['min'], 'nowYear' => $year, 'nowMonth' => $month, 'yearMonth'=>$yearMonth, 'endTime' => $endTime];
+//        return ['nowPeriodNum' => $thisMonth['min'], 'nowYear' => $year, 'nowMonth' => $month, 'yearMonth'=>$yearMonth, 'endTime' => $endTime];
+        return ['nowPeriodNum' => $nowPeriodNum, 'nowYear' => $year, 'nowMonth' => $month, 'yearMonth'=>$yearMonth, 'endTime' => $endTime];
     }
 
     /**

+ 1 - 1
common/models/forms/AdminAddUserForm.php

@@ -114,7 +114,7 @@ class AdminAddUserForm extends Model {
             'decLv' => 'Real time declaration level',//实时报单级别
             'areaSelected' => 'Location',//所在地区
             'tel' => 'Telephone',//电话
-            'isDec' => 'Declaration center or not',//是否报单中心
+            'isDec' => 'Stockist or not',//是否报单中心
             'decUserName' => 'Stockist No', // 报单中心编号
             'birthday' => 'birthday',//生日
             'decRoleId' => 'Stockist Level',//报单中心级别

+ 18 - 17
common/models/forms/ApproachDeclarationForm.php

@@ -67,6 +67,7 @@ class ApproachDeclarationForm extends Model
     public $cityName;
     public $lgaName;
     public $payType;
+    public $decType;
 
     // 传过来的全部数据
     public $allData;
@@ -127,7 +128,7 @@ class ApproachDeclarationForm extends Model
             [['type','decLv','decWay','insertUserName',/* 'insertUserIdCard',*/'password','payPassword','decUserName'], 'required'],
             [['type'], 'isType', 'on'=>['userDec', 'canDec']],
             [['insertUserName'], 'isCanAddUser'],
-            [['decUserName'], 'issetDec'],
+            [['decUserName', 'decType'], 'issetDec'],
             [['conUserName'], 'isConUserName'],
             [['recUserName'], 'isRecUserName'],
             [['location'], 'isLocation'],
@@ -181,8 +182,8 @@ class ApproachDeclarationForm extends Model
     {
         $parentScenarios =  parent::scenarios();
         $customScenarios = [
-            'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankProvince','bankCity','bankCounty', 'consignee','acceptMobile','province',/*'city','county',*/ 'conUserName', 'recUserName','decUserName', 'location', 'email'],
-            'canDec' => ['type', 'insertUserName',/* 'insertUserIdCard',*/ 'conUserName', 'recUserName', 'location'],
+            'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankProvince','bankCity','bankCounty', 'consignee','acceptMobile','province',/*'city','county',*/ 'conUserName', 'recUserName','decUserName', 'location', 'email', 'decType'],
+            'canDec' => ['type', 'insertUserName',/* 'insertUserIdCard',*/ 'conUserName', 'recUserName', 'location', 'decType'],
             'notFull' => ['type', 'insertUserName', 'conUserName', 'recUserName', 'location'],
         ];
         return array_merge($parentScenarios, $customScenarios);
@@ -197,19 +198,19 @@ class ApproachDeclarationForm extends Model
             $this->addError($attribute, 'Stockist does not exist');//报单中心不存在
             return false;
         } else {
-            // 判断报单中心是否在新加入会员的安置网上级中
-            $this->loopFindParentToNetwork($this->insertUserName);
-            //反转数组,in_array搜索错误
-            //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
-            $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
-//            var_dump($flipParent);
-//            echo $this->insertUserName.'=='.$this->decUserName;
-//            exit;
-            if (!isset($flipParent[$this->decUserName])) {
-                //$this->addError($attribute, '为' . $this->insertUserName . '报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
-                $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Stockist' . $this->decUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
-                return ;
+            if ($this->decType !== 'ba') {
+                // 判断报单中心是否在新加入会员的安置网上级中
+                $this->loopFindParentToNetwork($this->insertUserName);
+                //反转数组,in_array搜索错误
+                //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
+                $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
+                if (!isset($flipParent[$this->decUserName])) {
+                    //$this->addError($attribute, '为' . $this->insertUserName . '报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
+                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Stockist' . $this->decUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
+                    return ;
+                }
             }
+
             $this->_decId = $decUser['ID'];
         }
     }
@@ -325,7 +326,7 @@ class ApproachDeclarationForm extends Model
             $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
 
             // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
-            if($this->insertUserName) {
+            if($this->decType !== 'ba' && $this->insertUserName) {
                 $this->loopFindParentToNetwork($this->insertUserName);
                 if (!$this->recUserIsInNetworkParent()) {
                    // $this->addError($attribute, '为' . $this->insertUserName . '报单,开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
@@ -734,7 +735,7 @@ class ApproachDeclarationForm extends Model
         $user->BANK_CITY = $this->bankCity ?? 0;
         $user->BANK_COUNTY = $this->bankCounty ?? 0;
         $user->CREATED_AT = Date::nowTime();
-        $user->STATUS = 1;
+        $user->STATUS = 0;
         $user->DEC_LV = $this->decLv;
         $user->LAST_DEC_LV = $this->decLv;
         $user->EMP_LV = EmployLevel::getDefaultLevelId();

+ 1 - 0
common/models/forms/ApproachDeclarationLoopForm.php

@@ -88,6 +88,7 @@ class ApproachDeclarationLoopForm extends Model
                 $model->conUserName = null;
                 $model->recUserName = null;
                 $model->location = null;
+                $model->decType = null;
             } else {
                 $this->addError($attribute, 'The format of the report data is incorrect');// 报单数据格式错误
             }

+ 0 - 0
common/models/forms/ApproachDeclarationUpgradeForm.php


+ 52 - 23
common/models/forms/ApproachOrderForm.php

@@ -14,6 +14,7 @@ use common\libs\logging\operate\AdminOperate;
 use common\models\ApproachDecOrder;
 use common\models\ApproachOrder;
 use common\models\ApproachOrderGoods;
+use common\models\BaUser;
 use common\models\DealType;
 use common\models\DecLevelLog;
 use common\models\DecOrder;
@@ -299,6 +300,9 @@ class ApproachOrderForm extends Model
             throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
         }
 
+        // 订单类型:userOrder(会员订单)、userUpgrade(会员升级)、userDec(会员报单)
+        $orderType = $this->note['metadata']['custom_fields'][1]['value'] ?? false;
+
         $db = \Yii::$app->db;
         $transaction = $db->beginTransaction();
         try {
@@ -321,37 +325,62 @@ class ApproachOrderForm extends Model
                 $approachOrderGood['EMAIL'] = $this->email;
             }
             OrderGoods::batchInsert($approachOrderGoods);
-            // 同步报单
-            $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
-            if ($approachDecOrder) {
-                unset($approachDecOrder['STATUS']);
+
+            // 会员报单、BA升级
+            if (in_array($orderType, ['userDec', 'baUpgrade', 'userUpgrade'])) {
                 // 同步报单
-                DecOrder::insertOne($approachDecOrder);
-
-                // 会员升级 报单类型:2会员升级单
-                if ($approachDecOrder['DETAIL_TYPE'] == 2) {
-                    // 为被升级人进行升级操作
-                    $decLevelLog = new DecLevelLog();
-                    $decLog = [
-                        'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
-                        'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
-                        'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
-                        'actionId' => $approachDecOrder['USER_ID'],
-                        'remark' => $approachDecOrder['REMARK'],
-                        'lvPv' => $this->_model->PV,
-                    ];
-                    $modifyDecLv = $decLevelLog->frontendChange($decLog);
-                    if (empty($modifyDecLv)) {
-                        $transaction->rollBack();
-                        throw new Exception("Failed to upgrade for member");//为会员升级失败
+                $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+                if ($approachDecOrder) {
+                    unset($approachDecOrder['STATUS']);
+
+                    // 同步报单
+                    DecOrder::insertOne($approachDecOrder);
+
+                    // 修改会员锁定状态
+                    if (in_array($orderType, ['userDec', 'baUpgrade'])) {
+                        if (!User::updateAll(['STATUS' => 1], 'ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']])) {
+                            throw new Exception(Form::formatErrorsForApi('change user status error'));
+                        }
+                    }
+                    // 修改BA会员升级状态
+                    if ($orderType === 'baUpgrade') {
+                        // 查询BA会员名
+                        $userInfo = User::findOneAsArray('ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']]);
+                        if (!BaUser::updateAll(['WHETHER_UPGRADE' => 1, 'BA_UPGRADE_AT' => time()], 'USER_NAME=:USER_NAME', [':USER_NAME' => $userInfo['USER_NAME']])) {
+                            throw new Exception(Form::formatErrorsForApi('Brand Ambassador upgrade error!'));
+                        }
                     }
+
+                    // 正式会员-升级单
+                    if ($orderType === 'userUpgrade') {
+                        // 会员升级 报单类型:2会员升级单
+                        if ($approachDecOrder['DETAIL_TYPE'] == 2) {
+                            // 为被升级人进行升级操作
+                            $decLevelLog = new DecLevelLog();
+                            $decLog = [
+                                'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
+                                'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
+                                'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
+                                'actionId' => $approachDecOrder['USER_ID'],
+                                'remark' => $approachDecOrder['REMARK'],
+                                'lvPv' => $this->_model->PV,
+                            ];
+                            $modifyDecLv = $decLevelLog->frontendChange($decLog);
+                            if (empty($modifyDecLv)) {
+                                $transaction->rollBack();
+                                throw new Exception("Failed to upgrade for member");//为会员升级失败
+                            }
+                        }
+                    }
+
+                    // 删除中间表
+                    ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
                 }
             }
 
             // 删除中间表
             ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
             ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
-            ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
 
             $transaction->commit();
         } catch (Exception $e) {

+ 561 - 0
common/models/forms/BaApproachDeclarationForm.php

@@ -0,0 +1,561 @@
+<?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\helpers\user\Cash;
+use common\helpers\user\Reconsume;
+use common\helpers\user\Info;
+use common\models\ApproachDecOrder;
+use common\models\ApproachOrder;
+use common\models\ApproachOrderGoods;
+use common\models\BaApproachDecOrder;
+use common\models\BaApproachOrder;
+use common\models\BaApproachOrderGoods;
+use common\models\BaReceiveAddress;
+use common\models\BaUser;
+use common\models\DeclarationPackage;
+use common\models\DecOrder;
+use common\models\EmployLevel;
+use common\models\Order;
+use common\models\OrderGoods;
+use common\models\Period;
+use common\models\ReceiveAddress;
+use common\models\ReconsumePool;
+use common\models\ReconsumePoolFlow;
+use common\models\DeclarationLevel;
+use common\models\Region;
+use common\models\ShopGoods;
+use common\models\User;
+use common\models\UserInfo;
+use common\models\UserNetwork;
+use common\models\UserRelation;
+use yii\base\Exception;
+
+/**
+ * Login form
+ */
+class BaApproachDeclarationForm extends Model
+{
+    public $type;
+    public $decLv;
+    public $decWay;
+    public $packageId;
+    public $goodsId;
+    public $goodsNum;
+    public $insertUserName;
+    public $password;
+    public $payPassword;
+    public $realName;
+    public $insertUserIdCard;
+    public $mobile;
+    public $email;
+    public $address;
+    public $openBank;
+    public $bankAddress;
+    public $bankNo;
+    public $bankProvince;
+    public $bankCity;
+    public $bankCounty;
+    public $conUserName;
+    public $recUserName;
+    public $decUserName;
+    public $location;
+    public $consignee;
+    public $acceptMobile;
+    public $province;
+    public $city;
+    public $county;
+    public $cityName;
+    public $lgaName;
+    public $payType;
+
+    // 传过来的全部数据
+    public $allData;
+    private $_decId;
+    public $_insertUserId;
+    private $_decAmount;
+    private $_decPv;
+    private $_orderGoods;
+    private $_standardAmount;
+    private $_decAmountStandard;
+
+    // 批量报单时添加会员的REDIS里面缓存的添加的会员资料
+    const REDIS_WAIT_ADD_USER = 'user:dec:waitAdd';
+
+    const TYPE_ZC = 'ZC';
+//    const TYPE_YH = 'YH';
+    const TYPE_ZG = 'ZG';
+    const TYPE_LS = 'LS';
+    const TYPE_FX = 'FX';
+
+//    private $_modelClass = null;
+    private $_oneOrder = null;
+    private $_userForm = null;
+    // 全部的上级(安置网和开拓网)
+    private $_tempParentUser = [];
+    // 全部的安置网上级
+    private $_tempNetworkParentUser = [];
+    // 全部的开拓网上级
+    private $_tempRelationParentUser = [];
+    private $_types = [
+        self::TYPE_ZC => [
+            'name' => '首购单',
+        ],
+//        self::TYPE_YH => [
+//            'class' => DeclarationYH::class,
+//            'table' => '{{%DECLARATION_YH}}',
+//            'name' => '优惠单',
+//        ],
+        self::TYPE_ZG => [
+            'name' => '升级增购单',
+        ],
+        self::TYPE_LS => [
+            'name' => '零售单',
+        ],
+        self::TYPE_FX => [
+            'name' => '复销单',
+        ],
+    ];
+
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['type','decLv','decWay','packageId', 'insertUserName', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo','bankProvince','bankCity','bankCounty','consignee','acceptMobile','province','city','county','cityName','lgaName','decUserName', 'conUserName', 'recUserName', 'location'], 'trim'],
+            [['type','decLv','decWay','insertUserName',/* 'insertUserIdCard',*/'password','payPassword','decUserName'], 'required'],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'type' => 'Entry type',//报单类型
+            'decLv' => 'Entry level',//报单级别
+            //'decPv' => '报单PV',
+            'decWay' => 'Entry method',//报单方式
+            'packageId' => 'Entry Package',//报单套餐
+            'goodsId' => 'product ID',//商品ID
+            'goodsNum' => 'Product quantity',//商品数量
+            //'addType' => '新增会员方式',
+            'insertUserName' => 'Member user name',//会员用户名
+            'password' => 'Login password',//登陆密码
+            'payPassword' => 'Payment password',//支付密码
+            'realName' => 'Member Name',//会员姓名
+            'insertUserIdCard' => 'ID',//身份证号
+            'mobile' => 'Phone Number',//手机号
+            'openBank' => 'openBank',//开户行
+            'bankAddress' => 'bankAddress',//开户支行
+            'bankNo' => 'bankNo',//银行账号
+            'bankProvince' => 'bankProvince',//银行省份
+            'bankCity' => 'bankCity',//银行城市
+            'bankCounty' => 'bankCounty',//银行县区
+            'conUserName' => 'Instructor user name',//指导老师用户名
+            'recUserName' => 'Developer user name',//开拓人用户名
+            'decUserName' => 'Stockist user name',//报单中心用户名
+            'conUid' => 'Instructor member ID',//指导老师会员ID
+            'recUid' => 'Sponsor member ID',//'开拓人会员ID
+            'location' => 'market',//市场
+            'consignee' => 'consignee',//收货人
+            'acceptMobile' => 'Recipient Phone Number',//收货人手机
+            'province' => 'Receiving Province',//收货省
+            'city' => 'Receiving City',//收货市
+            'county' => 'Receiving area / county',//收货区县
+            'address' => 'Receiving detailed address',//收货详细地址
+        ];
+    }
+
+    /**
+     * 指定场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            'userDec' => ['type','allData', /*'decLv','decWay',*/'insertUserName','password','payPassword', 'realName','mobile', 'address','consignee','acceptMobile','province','conUserName', /*'recUserName','decUserName',*/ 'location', 'email'],
+            'canDec' => ['type', 'insertUserName',/* 'insertUserIdCard',*/ 'conUserName', 'recUserName', 'location'],
+            'notFull' => ['type', 'insertUserName', 'conUserName', 'recUserName', 'location'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 判断报单中心是否存在
+     * @param $attribute
+     * @return false|void
+     */
+    public function issetDec($attribute){
+        if (!User::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
+            $this->addError($attribute, 'Stockist does not exist');//报单中心不存在
+            return false;
+        }
+        return true;
+    }
+
+
+    /**
+     * 判断开拓人
+     * @param $attribute
+     */
+    public function isRecUserName($attribute){
+        if($this->type == self::TYPE_ZC){
+            // 开拓人
+            if(!isset($this->_tempParentUser[$this->recUserName])){
+                $recUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);
+                if(!$recUserTemp){
+                    if($this->insertUserName){
+                        //$this->addError($attribute, '为'.$this->insertUserName.'报单,开拓人'.$this->recUserName.'不存在');
+                        $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->recUserName.'not in exist');
+                    } else {
+                       // $this->addError($attribute, '开拓人'.$this->recUserName.'不存在');
+                        $this->addError($attribute, 'Sponsor'.$this->recUserName.'not in exist');
+                    }
+
+                    return ;
+                }
+                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
+                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
+                $this->_tempParentUser[$this->recUserName] = [
+                    'USER_NAME' => $this->recUserName,
+                    'ZC_PV' => $recUserTemp['ZC_PV'],
+                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
+                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
+                    'CON_NUM' => $recUserTemp['CON_NUM'],
+                    'REC_NUM' => $recUserTemp['REC_NUM'],
+                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
+                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
+                ];
+                // 把该会员下面的5个区是否存在会员都付上
+                for($i=1;$i<=5;$i++){
+                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
+                }
+            }
+            $recUser = $this->_tempParentUser[$this->recUserName];
+            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
+
+            // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
+            if($this->insertUserName) {
+                $this->loopFindParentToNetwork($this->insertUserName);
+                if (!$this->recUserIsInNetworkParent()) {
+                   // $this->addError($attribute, '为' . $this->insertUserName . '报单,开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
+                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Sponsor' . $this->recUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
+                    return ;
+                }
+            }
+
+            // 把自己加入到临时上级会员数组中
+            $this->_tempParentUser[$this->insertUserName] = [
+                'USER_NAME' => $this->insertUserName,
+                //'ZC_PV' => $this->decPv,
+                'CON_USER_NAME' => $this->conUserName,
+                'REC_USER_NAME' => $this->recUserName,
+                'CON_NUM' => 0,
+                'REC_NUM' => 0,
+                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
+                'LOCATION' => $this->location,
+                'LOCATION1' => 0,
+                'LOCATION2' => 0,
+                'LOCATION3' => 0,
+                'LOCATION4' => 0,
+                'LOCATION5' => 0,
+            ];
+        }
+
+    }
+
+    /**
+     * 报单类型
+     * @param $attribute
+     * @param $params
+     */
+    public function isType($attribute, $params){
+        if(array_key_exists($this->type, $this->_types)){
+            if($this->type == self::TYPE_ZC){
+                if($this->scenario == 'userDec'){
+                    if(!$this->insertUserName) $this->addError($attribute, 'Membership number must be filled in for initial purchase');//首购必须填写加入会员编号
+                }
+                if(!$this->insertUserName) $this->addError($attribute, 'Membership number must be filled in for initial purchase');//首购必须填写加入会员编号
+                if(!$this->conUserName) $this->addError($attribute, 'For the first purchase, you must fill in the instructor number of the member');//首购必须填写加入会员的指导老师编号
+                if(!$this->recUserName) $this->addError($attribute, 'For the first purchase, the Sponsor number of the member must be filled in');//首购必须填写加入会员的开拓人编号
+                if(!$this->location) $this->addError($attribute, 'The first purchase must be filled in the market of the member');//首购必须填写加入会员的市场
+            }
+        } else {
+            $this->addError($attribute, 'Incorrect entry type');//报单类型不正确
+        }
+    }
+
+    /**
+     * 添加报单
+     * @param $allData
+     * @return array|bool|BaApproachOrder
+     * @throws Exception
+     */
+    public function add($allData){
+        if(!$this->validate()){
+            return $this->getErrors();
+        }
+        // 首购单,需要添加会员操作
+        if($this->type == self::TYPE_ZC) {
+            try {
+                if (preg_match("/[\x7f-\xff]/", $this->insertUserName)) {  //判断字符串中是否有中文
+                    throw new Exception('Member number cannot contain Chinese characters');//会员编号中不能含有汉字
+                }
+
+                if ($this->decWay == 1) {
+                    $decPackage = DeclarationPackage::findOneAsArray('ID=:ID', [':ID' => $this->packageId]);
+                    $this->_decAmount = $decPackage['AMOUNT'];
+                    $this->_decPv = $decPackage['PV'];
+                    $this->_orderGoods[] = [
+                        'GOODS_ID' => $this->packageId,
+                        'PRICE' => $this->_decAmount,
+                        'REAL_PRICE' => $this->_decAmount,
+                        'PV' => $this->_decPv,
+                        'REAL_PV' => $this->_decPv,
+                        'BUY_NUMS' => 1,
+                        'SKU_CODE' => $decPackage['PACKAGE_NO'],
+                        'GOODS_TITLE' => $decPackage['PACKAGE_NAME'],
+                        'EMAIL' => $this->email
+                    ];
+                } else {
+                    $ids = $this->goodsId;
+                    $totalAmount = 0;
+                    $totalAmountStandard = 0;
+                    $totalPv = 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) {
+                                $totalAmount += $goods['SELL_PRICE'] * intval($v);
+                                $totalAmountStandard += $goods['SELL_PRICE_STANDARD'] * intval($v);
+                                $realPriceStandard = $goods['SELL_PRICE_STANDARD'];
+                                $totalPv += $goods['PRICE_PV'] * intval($v);
+                                $this->_orderGoods[] = [
+                                    'GOODS_ID' => $goods['ID'],
+                                    'PRICE' => $goods['SELL_PRICE'],
+                                    'REAL_PRICE' => $goods['SELL_PRICE'],
+                                    'PV' => $goods['PRICE_PV'],
+                                    'REAL_PV' => $goods['PRICE_PV'],
+                                    'POINT' => $goods['POINT'],
+                                    'BUY_NUMS' => intval($v),
+                                    'SKU_CODE' => $goods['GOODS_NO'],
+                                    'GOODS_TITLE' => $goods['GOODS_NAME'],
+                                    'EMAIL' => $this->email,
+                                    'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
+                                    'REAL_STANDARD_PRICE' => $realPriceStandard,
+                                    'EXCHANGE_RATE' => $exchangeRate,
+                                    'TAX_RATE' => $goods['TAX_RATE'],
+                                ];
+                            }
+                        }
+                    }
+
+                    $this->_decAmount = $totalAmount;
+                    $this->_decPv = $totalPv;
+                    $this->_decAmountStandard = $totalAmountStandard;
+                    $this->_standardAmount = $this->_decAmountStandard;
+                }
+
+                if (!($this->addUser($allData))) {
+                    throw new Exception(Form::formatErrorsForApi($this->_userForm->getErrors()));
+                }
+
+                $decResult = $this->addDecOrder();
+                if (!$decResult) {
+                    throw new Exception(Form::formatErrorsForApi($decResult->getErrors()));
+                }
+
+                return $decResult;
+            } catch (\Exception $e) {
+                throw new Exception(Form::formatErrorsForApi($e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage()));
+            }
+        }
+        return true;
+    }
+
+    /**
+     * 添加会员
+     * @param $allData
+     * @return bool|UserInfo|null
+     * @throws \yii\db\Exception|Exception
+     */
+    public function addUser($allData){
+        $period = Period::instance();
+        // 增加会员
+        $user = new BaUser();
+        $user->USER_NAME = $this->insertUserName;
+        $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
+        $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->payPassword);
+        $user->NATION = 0;
+        $user->REAL_NAME = $this->realName;
+        $user->ID_CARD = $this->mobile;
+        $user->MOBILE = $this->mobile;
+        $user->EMAIL = $this->email;
+        $user->ADDRESS = $this->address ? $this->address : 'nothing';//无
+        $user->OPEN_BANK = $this->openBank;
+        $user->BANK_ADDRESS = $this->bankAddress;
+        $user->BANK_NO = $this->bankNo;
+        $user->BANK_PROVINCE = $this->bankProvince ?? 0;
+        $user->BANK_CITY = $this->bankCity ?? 0;
+        $user->BANK_COUNTY = $this->bankCounty ?? 0;
+        $user->CREATED_AT = Date::nowTime();
+        $user->STATUS = 0;
+        $user->DEC_LV = $this->decLv;
+        $user->LAST_DEC_LV = $this->decLv;
+        $user->EMP_LV = EmployLevel::getDefaultLevelId();
+        $user->PROVINCE = $this->province ?? 0;
+        $user->LGA_NAME = $this->lgaName;
+        $user->CITY_NAME = $this->cityName;
+        $user->AVATAR = 'avatar/1.png';
+        $user->IS_DEC = 0;
+        $user->DEC_ID = $this->_decId ?? '';
+        $user->DEC_ROLE_ID = $this->decRoleId ?? '';
+        $user->PERIOD_AT = $period->getNowPeriodNum();
+        $user->IS_DIRECT_SELLER = 0;
+        $user->VERIFIED = 1;
+        $user->VERIFIED_AT = Date::nowTime();
+
+        if (!$user->save()) {
+            throw new Exception(Form::formatErrorsForApi($user->getErrors()));
+        }
+
+        $this->_insertUserId = $user->ID;
+        $userForm = new BaUserForm();
+        $this->_userForm = $userForm;
+        $userForm->scenario = 'addWithUserName';
+        $userForm->userId = $this->_insertUserId;
+        $userForm->userName = $this->insertUserName;
+        $userForm->zcPv = $this->_decPv;
+        $userForm->zcAmount = $this->_decAmount;
+        $userForm->conUserName = $this->conUserName ?? '';
+        $userForm->recUserName = $this->recUserName;
+        $userForm->location = $this->location;
+        $userForm->idCard = $this->mobile;
+        $userForm->allData = $allData;
+        if(!$userForm->validate()){
+            $this->addErrors($userForm->getErrors());
+            return false;
+        }
+        if($result = $userForm->add()){
+            return $result;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * 添加报单订单
+     * @throws \yii\db\Exception
+     * @throws Exception
+     */
+    public function addDecOrder(){
+        $periodObj = Period::instance();
+        $nowPeriodNum = $periodObj->getNowPeriodNum();
+        $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
+
+        $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
+        // 加入报单信息
+        $decOrderModel = new BaApproachDecOrder();
+        $decOrderModel->DEC_SN = 'DS' . $ord;
+        $decOrderModel->ORDER_SN = 'OS' . $ord;
+        $decOrderModel->TYPE = $this->type;
+        $decOrderModel->USER_ID = \Yii::$app->user->id;
+        $decOrderModel->TO_USER_ID = $this->_insertUserId;
+        $decOrderModel->DEC_AMOUNT = $this->_decAmount;
+        $decOrderModel->DEC_PV = $this->_decPv;
+        $decOrderModel->PERIOD_NUM = $nowPeriodNum;
+        $decOrderModel->CALC_MONTH = $nowCalcMonth;
+        $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        $decOrderModel->PAID_WALLET = $this->payType;
+        $decOrderModel->CON_USER_ID = Info::getUserIdByUserName($this->conUserName) ?? '';
+        $decOrderModel->REC_USER_ID = Info::getUserIdByUserName($this->recUserName) ?? '';
+        $decOrderModel->DEC_ID = $this->_decId ?? '';
+        $decOrderModel->IS_DEL = 0;
+        $decOrderModel->CREATED_AT = Date::nowTime();
+        if(!$decOrderModel->save()){
+            throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
+        }
+
+        // 加入订单信息
+        if ($this->province!=1) {
+            // 仓库
+            $warehouse = Region::getWarehouseByCode($this->province);
+            if (!$warehouse) {
+                // 地区暂时不支持配送,具体联系客服
+                throw new Exception('Delivery is temporarily not supported in the region. Contact customer service for details');
+            }
+        } else {
+            $warehouse = '01';
+        }
+        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
+        $orderModel = new BaApproachOrder();
+        $orderModel->SN = 'OS' . $ord;
+        $orderModel->DEC_SN = 'DS' . $ord;
+        $orderModel->ORDER_TYPE = $this->type;
+        $orderModel->USER_ID = $this->_insertUserId;
+        $orderModel->USER_NAME = $this->insertUserName;
+        $orderModel->ORDER_AMOUNT = $this->_decAmount;
+        $orderModel->PV = $this->_decPv;
+        $orderModel->PAY_AMOUNT = $this->_decAmount;
+        $orderModel->PAY_PV = $this->_decPv;
+        $orderModel->PAY_AT = 0;
+        $orderModel->PAY_TYPE = $this->payType;
+        $orderModel->PERIOD_NUM = $nowPeriodNum;
+        $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        $orderModel->FREIGHT = 0;
+        $orderModel->PAY_FREIGHT = 0;
+        $orderModel->CONSIGNEE = $this->consignee;
+        $orderModel->MOBILE = $this->acceptMobile;
+        $orderModel->EMAIL = $this->email ?: $this->insertUserName . '@elken.net';
+        $orderModel->PROVINCE = $this->province;
+        $orderModel->LGA_NAME = $this->lgaName;
+        $orderModel->CITY_NAME = $this->cityName;
+        $orderModel->ADDRESS = $this->address;
+        $orderModel->WAREHOUSE = $warehouse;
+        $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
+        $orderModel->CREATED_AT = Date::nowTime();
+        $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
+        $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
+        $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
+        $orderModel->EXCHANGE_RATE = $exchangeRate;
+        if ($this->province==1) {
+            $orderModel->EXPRESS_TYPE = 1;
+        }
+        if (!$orderModel->save()) {
+            throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
+        }
+
+        // 加入商品到订单商品表
+        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);
+        }
+        BaApproachOrderGoods::batchInsert($this->_orderGoods);
+
+        // 写入收货地址信息,判断province字段,当不为1时,插入收货地址信息
+        $addressModel = new BaReceiveAddress();
+        if ($this->province != 1) {
+            $addressModel->USER_ID = $this->_insertUserId;
+            $addressModel->USER_NAME = $this->insertUserName;
+            $addressModel->CONSIGNEE = $this->consignee;
+            $addressModel->MOBILE = $this->acceptMobile;
+            $addressModel->PROVINCE = $this->province;
+            $addressModel->CITY_NAME = $this->cityName;
+            $addressModel->LGA_NAME = $this->lgaName;
+            $addressModel->ADDRESS = $this->address;
+            $addressModel->IS_DEFAULT = 1;
+            if (!$addressModel->save()) {
+                throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
+            }
+        }
+
+        return $orderModel;
+    }
+}

+ 216 - 0
common/models/forms/BaApproachDeclarationLoopForm.php

@@ -0,0 +1,216 @@
+<?php
+namespace common\models\forms;
+
+use common\components\Model;
+use common\helpers\Form;
+use common\models\UserBind;
+use yii\base\Exception;
+use yii\helpers\Json;
+use common\models\DeclarationPackage;
+use common\helpers\Date;
+use common\models\ShopGoods;
+
+/**
+ * Login form
+ */
+class BaApproachDeclarationLoopForm extends Model
+{
+    public $data;
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['data'], 'required'],
+            [['data'], 'formatData'],
+            [['data'], 'isData', 'on'=>['canDec', 'notFull']],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'data' => 'Data',// 数据
+        ];
+    }
+
+    /**
+     * 指定场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            'userDec' => ['data'],
+            'canDec' => ['data'],
+            'notFull' => ['data'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 格式化提交的数据
+     * @param $attribute
+     */
+    public function formatData($attribute){
+        //$this->data = Json::decode($this->data);
+        if(!is_array($this->data)){
+            $this->addError($attribute, 'Data format error');// 数据格式错误
+        }
+    }
+
+    /**
+     * 循环校验数据是否合格
+     * @param $attribute
+     */
+    public function isData($attribute){
+        $model = new DeclarationForm();
+        $model->scenario = $this->scenario;
+        $model->allData = $this->data;
+        foreach ($this->data as $value){
+            if(is_array($value)){
+                foreach($value as $key=>$decFormData){
+                    $model->$key = $decFormData;
+                }
+                if(!$model->validate()){
+                    $this->addErrors($model->getErrors());
+                }
+                $model->type = null;
+                $model->decSn = null;
+                $model->userId = null;
+                $model->toUserId = null;
+                $model->decPv = null;
+                $model->insertUserName = null;
+                $model->insertUserIdCard = null;
+                $model->conUserName = null;
+                $model->recUserName = null;
+                $model->location = null;
+            } else {
+                $this->addError($attribute, 'The format of the report data is incorrect');// 报单数据格式错误
+            }
+
+        }
+    }
+
+    /**
+     * 报单
+     * @return bool
+     * @throws \yii\db\Exception
+     */
+    public function add()
+    {
+        if(!$this->validate()){
+            return null;
+        }
+
+        $result = null;
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try{
+            // 所有的首购单会员ID以备点位绑定使用
+            $zcUserIdCard = null;
+            $model = new BaApproachDeclarationForm();
+            $model->scenario = $this->scenario;
+            $model->allData = $this->data;
+            foreach ($this->data as $value) {
+                // 套餐报单
+                if (isset($value['packageId']) && $value['packageId']){
+                    $packagedata = DeclarationPackage::findOneAsArray('ID=:ID', [':ID' => $value['packageId']]);
+                    if($packagedata['STORE_NUMS']>0){
+                        $data =  DeclarationPackage::find()->where(['ID'=> $packagedata['ID'] ])->one();
+                        $goods_store_nums = $data->STORE_NUMS - 1;
+                        $data->STORE_NUMS = $goods_store_nums;
+                        $data->update();
+
+                        //库存为0下架套餐
+                        if ($goods_store_nums <= 0){
+                            $data->STATUS = 0;
+                            $data->UPDATED_AT = Date::nowTime();
+                        }
+                    }else{
+                        throw new Exception($packagedata['PACKAGE_NAME'].'Insufficient inventory');// 库存不足
+                    }
+                }
+                // 普通商品报单
+                if (count($value['goodsId']) > 0 && (count($value['goodsId']) == count($value['goodsNum']))) {
+                    for ($i = 0; $i < count($value['goodsId']) ;$i++) {
+                        $goods = ShopGoods::findOneAsArray('ID=:ID',[':ID'=> $value['goodsId'][$i]]);
+                        if ($goods['STATUS'] == 1 ){
+                            if($goods['STORE_NUMS'] >= $value['goodsNum'][$i]) {
+                                // 减库存
+                                $data = ShopGoods::find()->where(['ID' => $value['goodsId'][$i]])->one();
+                                $goods_store_nums = $data->STORE_NUMS - $value['goodsNum'][$i];
+                                $data->STORE_NUMS = $goods_store_nums;
+                                $data->update();
+
+                                if($goods_store_nums <= 0){
+                                    $data->STATUS = 0;
+                                    $data->UPDATED_AT = Date::nowTime();
+                                    $data->update();
+                                }
+                            } else {
+                                throw new Exception($goods['GOODS_NAME'].'Insufficient inventory');// 商品库存不足
+                            }
+                        }else{
+                            throw new Exception($goods['GOODS_NAME'].'Sold out');// 商品已下架
+                        }
+                    }
+                }
+				
+                if (is_array($value)) {
+                    foreach($value as $key=>$decFormData){
+                        $model->$key = $decFormData;
+                    }
+                    // 把首购单的几个会员归集到一个数组里,将来绑定到一起
+                    if( $model->type == 'ZC'){
+                        if($zcUserIdCard != null){
+                            if($model->insertUserIdCard != $zcUserIdCard){
+                                throw new Exception('Bulk declaration member must be the same member');//批量报单会员必须是同一身份证
+                            }
+                        } else {
+                            $zcUserIdCard = $model->insertUserIdCard;
+                        }
+                    }
+
+                    $result = $model->add($this->data);
+                    if(!$result){
+                        throw new Exception(Form::formatErrorsForApi($model->getErrors()));
+                    }
+                } else {
+                    throw new Exception('The format of the report data is incorrect');// 报单数据格式错误
+                }
+            }
+
+            $transaction->commit();
+
+            return $result;
+        } catch (\Exception $e){
+            $transaction->rollBack();
+            $this->addError('add', $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
+            return null;
+        }
+    }
+
+    /**
+     * RPC服务校验数据
+     * @param $data
+     * @return array
+     */
+    public static function rpcIsData($data){
+        $result = [
+            'error' => false,
+            'message' => 'Data can be reported',//数据可报单
+        ];
+        $formModel = new self();
+        $formModel->scenario = 'canDec';
+        $formModel->data = $data;
+        if(!$formModel->validate()){
+            $result['error'] = true;
+            $result['message'] = Form::formatErrorsForApi($formModel->getErrors());
+        }
+        return $result;
+    }
+}

+ 522 - 0
common/models/forms/BaApproachOrderForm.php

@@ -0,0 +1,522 @@
+<?php
+namespace common\models\forms;
+
+use common\helpers\Cache;
+use common\helpers\Date;
+use common\components\Model;
+use common\helpers\Form;
+use common\helpers\LoggerTool;
+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\ApproachDecOrder;
+use common\models\ApproachOrder;
+use common\models\ApproachOrderGoods;
+use common\models\BaApproachDecOrder;
+use common\models\BaApproachOrder;
+use common\models\BaApproachOrderGoods;
+use common\models\BaDecOrder;
+use common\models\BaOrder;
+use common\models\BaOrderGoods;
+use common\models\BaReceiveAddress;
+use common\models\BaUser;
+use common\models\DealType;
+use common\models\DecLevelLog;
+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\ShopGoods;
+use common\models\User;
+use common\models\UserNetwork;
+use yii\base\Exception;
+
+/**
+ * BAApproachOrderForm
+ */
+class BaApproachOrderForm extends Model
+{
+    public $sn;
+    public $expressCompany;
+    public $orderTrackNo;
+    public $status;
+    public $remark;
+    public $note;
+
+    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 $lgaName;
+    public $cityName;
+    public $detailaddress;
+
+    private $_address;
+    private $_decAmount;
+    private $_decPv;
+    private $_freight;
+    private $_payAmount;
+    private $_orderGoods;
+
+    private $_model;
+
+    public function init()
+    {
+        parent::init();
+        $this->adminOperateLogger = new AdminOperate([
+            'fetchClass' => BaApproachOrder::class,
+        ]);
+        $this->payType = ShopGoods::SALE_TYPE[7]['label'];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules(): array
+    {
+        return [
+            [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','lgaName','cityName','detailaddress','email'], 'trim'],
+            [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','detailaddress'], 'required'],
+            [['status'], 'isStatus'],
+            [['addressId'], 'isAddress'],
+            [['payPassword'], 'validatePassword'],
+        ];
+    }
+
+    public function attributeLabels(): array
+    {
+        return [
+            'sn' => 'Order code',//订单号
+            'expressCompany' => 'Express Company',//快递公司
+            'orderTrackNo' => 'Track Code',//快递单号
+            'status' => 'Status',//状态
+            'remark' => 'Remark',//备注
+            'type' => 'Order Type',//订单类型
+            'addressId' => 'AddressId',//收货地址
+            'payType' => 'PayType',//支付方式
+            'goodsId' => 'Product ID',// 商品编号
+            'goodsNum' => 'Quantity',//
+            'userName' => 'UserName',//复消会员编号
+            'consignee' => 'Consignee',//收货人
+            'acceptMobile' => 'Accept Mobile',//收货电话
+            'lgaName' => 'LgaName',
+            'cityName' => 'CityName',
+            'detailaddress' => 'Detail Address',// 收货详细地址
+            'email' => 'Email',
+        ];
+    }
+
+    /**
+     * 指定校验场景
+     * @return array
+     */
+    public function scenarios(): array
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            // 管理员修改订单状态
+            'adminStatus' => ['sn', 'status'],
+            // 校验订单支付
+            'verifyPayStack' => ['sn', 'note', 'status'],
+            // 会员下单
+            'userOrder' => ['type', 'addressId', 'goodsId', 'goodsNum', 'note', 'payPassword'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 校验之前
+     * @return bool
+     */
+    public function beforeValidate()
+    {
+        $parentValidate = parent::beforeValidate();
+        if ($this->sn) {
+            $this->_model = BaApproachOrder::findOne(['SN' => $this->sn]);
+            if (!$this->_model){
+                $this->addError('sn', 'Order does not exist');// 订单不存在
+                return false;
+            }
+        }
+
+        if ($this->scenario == 'verifyPayStack'){
+            if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
+                $this->addError('sn', '订单支付状态错误');
+                return false;
+            }
+        }
+
+        return $parentValidate;
+    }
+
+    /**
+     * 判断收货地址是否存在
+     * @param $attribute
+     * @param $params
+     */
+    public function isAddress($attribute, $params)
+    {
+        if (!$receiveAddress = BaReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
+            $this->addError($attribute, 'Receive address does not exist'); // 收货地址不存在
+        } else {
+            $this->_address = $receiveAddress;
+        }
+    }
+
+    /**
+     * 校验支付密码
+     * @param $attribute
+     * @param $params
+     */
+    public function validatePassword($attribute, $params) {
+        if (!BaUser::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
+            $this->addError($attribute, 'The payment password is incorrect');//支付密码不正确
+        }
+    }
+
+    /**
+     * 判断支付方式
+     * @param $attribute
+     */
+    public function isPayType($attribute)
+    {
+        if ($this->payType != 'pay_stack'){
+            $this->addError($attribute, '只允许PayStack方式支付');
+            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, 'Order cannot contain multiple product categories');//订单不能包含多种商品分类
+        }
+    }
+
+    /**
+     * 校验类型
+     * @param $attribute
+     */
+    public function isStatus($attribute)
+    {
+        if($this->type && !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 ;
+                }
+            }
+        }
+
+    }
+
+    /**
+     * 校验PayStack支付,更新订单状态.同步到正式订单.
+     * @throws Exception
+     */
+    public function verifyPayStack()
+    {
+        if (!$this->validate()) {
+            return null;
+        }
+
+        // 调用PayStack支付校验
+        LoggerTool::info([$this->note['reference'], $this->note]);
+        $payload = PayStack::transactionVerify($this->note['reference']);
+        LoggerTool::info($payload);
+        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('支付金额与订单金额不符'));
+        }
+
+        // 订单类型:baOrder(BA订单)、baDec(BA报单)
+        $orderType = $this->note['metadata']['custom_fields'][1]['value'] ?? false;
+
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            // 更新准订单状态为已支付
+            $this->_model->STATUS = $this->status;
+            $this->_model->NOTE = json_encode($this->note);
+            $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
+            $this->_model->EMAIL = $this->note['email'];
+            if (!$this->_model->save()) {
+                throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
+            }
+            // 更新订单商品的支付Email
+            BaApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+
+            // 同步准订单到正式订单
+            BaOrder::insertOne($this->_model->toArray());
+            // 同步准订单商品到正式订单商品
+            $approachOrderGoods = BaApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+            foreach ($approachOrderGoods as &$approachOrderGood) {
+                $approachOrderGood['EMAIL'] = $this->email;
+            }
+            BaOrderGoods::batchInsert($approachOrderGoods);
+
+            // BA报单
+            if ($orderType === 'baDec') {
+                // 同步报单
+                $approachDecOrder = BaApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+                if ($approachDecOrder) {
+                    unset($approachDecOrder['STATUS']);
+                    // 同步报单
+                    BaDecOrder::insertOne($approachDecOrder);
+
+                    // 修改会员锁定状态
+                    if (!BaUser::updateAll(['STATUS' => 1], 'ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']])) {
+                        throw new Exception(Form::formatErrorsForApi('Update Brand Ambassador status error'));
+                    }
+                }
+                BaApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+            }
+
+            // 删除中间表
+            BaApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
+            BaApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+
+            $transaction->commit();
+        } catch (Exception $e) {
+            $transaction->rollBack();
+            $this->addError('edit', $e->getFile() . '  ' . $e->getMessage());
+            return null;
+        }
+
+        return $this->_model;
+    }
+
+    /**
+     * 复销
+     */
+    public function add()
+    {
+        if(!$this->validate()){
+            return null;
+        }
+
+        $ids = $this->goodsId;
+        $totalAmount = 0;
+        $totalPv = 0;
+        $goodsType = ShopGoods::GOODS_TYPE;
+        $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;
+                    }
+                    $totalAmount += $realPrice * intval($v);
+                    $totalPv += $realPv * intval($v);
+
+                    $this->_orderGoods[] = [
+                        'GOODS_ID' => $goods['ID'],
+                        'PRICE' => $goods['SELL_PRICE'],
+                        'PV' => 0,
+                        'REAL_PRICE' => $realPrice,
+                        'REAL_PV' => 0,
+                        'POINT' => 0,
+                        'BUY_NUMS' => intval($v),
+                        'TAX_RATE' => $goods['TAX_RATE'],
+                        '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,
+                    ];
+                }
+            }
+        }
+
+        // 运费.奈拉
+        $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
+        // 普通商品免运费阈值.奈拉
+        $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
+
+        $this->_decAmount = $totalAmount;
+        $this->_decPv = $totalPv;
+        $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
+        $this->_payAmount = $this->_decAmount + $this->_freight;
+
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            // 创建订单
+            $orderResult = $this->addOrder();
+            if (!$orderResult) {
+                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
+            }
+
+            $transaction->commit();
+
+            return $orderResult;
+        } catch (\Exception $e) {
+            $transaction->rollBack();
+            $this->addError('add', $e->getMessage());
+            return null;
+        }
+    }
+
+    /**
+     * 复销订单
+     * @throws Exception
+     */
+    public function addOrder()
+    {
+        $periodObj = Period::instance();
+        $nowPeriodNum = $periodObj->getNowPeriodNum();
+        $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
+
+        $userId = \Yii::$app->user->id;
+        $userName = Info::getBaUserNameByUserId($userId);
+        $userMobile = Info::getBaUserMobileByUserId($userId);
+        $userEmail = Info::getBaUserEmailByUserId($userId);
+
+        // 加入订单信息
+        if ($this->_address['PROVINCE'] != 1) {
+            $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
+            if (!$warehouse) {
+//                throw new Exception('地区2暂时不支持配送,具体联系客服');
+            }
+        }else{
+            $warehouse = '01';
+        }
+
+        $_hasPV = 0;
+
+        $ordNo = $this->_generateSn();
+        $orderModel = new BaApproachOrder();
+        $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 = 0;
+        $orderModel->PAY_AT = 0;
+        $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'] ?: $userName;
+        $orderModel->MOBILE = $this->_address['MOBILE'] ?: $userMobile;
+        $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']['notPaid']['value'];
+        $orderModel->CREATED_AT = Date::nowTime();
+        $orderModel->CREATE_USER = $userName;
+        $orderModel->EMAIL = $userEmail ?: $userName . '@elken.net';
+        $orderModel->EXPRESS_TYPE = 1;
+        $orderModel->PROVINCE = 1;
+        $orderModel->CITY = 1;
+        $orderModel->COUNTY = 1;
+        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);
+        }
+        BaApproachOrderGoods::batchInsert($this->_orderGoods);
+
+        return $orderModel;
+    }
+
+    /**
+     * 生成订单流水号
+     * @return string
+     */
+    private function _generateSn(): string
+    {
+        return Date::today('Ymd') . $this->_random(10, 1);
+    }
+
+    /**
+     * 生成随机数
+     * @param $length
+     * @param int $numeric
+     * @return string
+     */
+    private function _random($length, int $numeric = 0): string
+    {
+        $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;
+    }
+}

+ 547 - 0
common/models/forms/BaDeclarationForm.php

@@ -0,0 +1,547 @@
+<?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\helpers\user\Cash;
+use common\helpers\user\Reconsume;
+use common\helpers\user\Info;
+use common\models\DeclarationPackage;
+use common\models\BaDecOrder;
+use common\models\EmployLevel;
+use common\models\BaOrder;
+use common\models\BaOrderGoods;
+use common\models\Period;
+use common\models\ReceiveAddress;
+use common\models\ReconsumePool;
+use common\models\ReconsumePoolFlow;
+use common\models\DeclarationLevel;
+use common\models\Region;
+use common\models\ShopGoods;
+use common\models\BaUser;
+use common\models\UserInfo;
+use common\models\BaUserInfo;
+use common\models\UserNetwork;
+use common\models\UserRelation;
+use yii\base\Exception;
+
+/**
+ * Login form
+ */
+class BaDeclarationForm extends Model
+{
+    public $type;
+    public $decLv;
+    public $decWay;
+    public $packageId;
+    public $goodsId;
+    public $goodsNum;
+    public $insertUserName;
+    public $password;
+    public $payPassword;
+    public $realName;
+    public $insertUserIdCard;
+    public $mobile;
+    public $email;
+    public $address;
+    public $openBank;
+    public $bankAddress;
+    public $bankNo;
+    public $bankProvince;
+    public $bankCity;
+    public $bankCounty;
+    public $conUserName;
+    public $recUserName;
+    public $decUserName;
+    public $location;
+    public $consignee;
+    public $acceptMobile;
+    public $province;
+    public $city;
+    public $county;
+    public $cityName;
+    public $lgaName;
+
+    // 传过来的全部数据
+    public $allData;
+    private $_decId;
+    public $_insertUserId;
+    private $_decAmount;
+//    private $_decPv;
+    private $_orderGoods;
+
+    // 批量报单时添加会员的REDIS里面缓存的添加的会员资料
+    const REDIS_WAIT_ADD_USER = 'user:dec:waitAdd';
+
+    const TYPE_ZC = 'ZC';
+//    const TYPE_YH = 'YH';
+    const TYPE_ZG = 'ZG';
+    const TYPE_LS = 'LS';
+    const TYPE_FX = 'FX';
+
+//    private $_modelClass = null;
+    private $_oneOrder = null;
+    private $_userForm = null;
+    // 全部的上级(安置网和开拓网)
+    private $_tempParentUser = [];
+    // 全部的安置网上级
+    private $_tempNetworkParentUser = [];
+    // 全部的开拓网上级
+    private $_tempRelationParentUser = [];
+    private $_types = [
+        self::TYPE_ZC => [
+            'name' => '首购单',
+        ],
+//        self::TYPE_YH => [
+//            'class' => DeclarationYH::class,
+//            'table' => '{{%DECLARATION_YH}}',
+//            'name' => '优惠单',
+//        ],
+        self::TYPE_ZG => [
+            'name' => '升级增购单',
+        ],
+        self::TYPE_LS => [
+            'name' => '零售单',
+        ],
+        self::TYPE_FX => [
+            'name' => '复销单',
+        ],
+    ];
+
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['type','decLv','decWay','packageId', 'insertUserName', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo','bankProvince','bankCity','bankCounty','consignee','acceptMobile','province','city','county','cityName','lgaName','decUserName', 'conUserName', 'recUserName', 'location'], 'trim'],
+            [['type','decWay','insertUserName',/* 'insertUserIdCard',*/'password','payPassword','decUserName'], 'required'],
+//            [['type'], 'isType', 'on'=>['userDec', 'canDec']],
+//            [['insertUserName'], 'isCanAddUser'],
+//            [['decUserName'], 'issetDec'],
+//            [['conUserName'], 'isConUserName'],
+//            [['recUserName'], 'isRecUserName'],
+//            [['location'], 'isLocation'],
+//            [['insertUserIdCard'], 'isSameSystem'],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'type' => 'Entry type', // 报单类型
+            'goodsId' => 'product ID', // 商品ID
+            'goodsNum' => 'Product quantity', // 商品数量
+            'insertUserName' => 'Member user name', // 会员用户名
+            'password' => 'Login password', // 登陆密码
+            'payPassword' => 'Payment password', // 支付密码
+            'realName' => 'Member name', // 会员姓名
+            'mobile' => 'Phone Number', // 手机号
+            'recUserName' => 'Developer user name', // 开拓人用户名
+            'decUserName' => 'Stockist user name', // 报单中心用户名
+            'conUid' => 'Instructor Member ID', // 指导老师会员ID
+            'recUid' => 'Sponsor Member ID', // 开拓人会员ID
+            'location' => 'market', // 市场
+            'consignee' => 'Recipient', // 收货人
+            'acceptMobile' => 'Recipient Phone Number', // 收货人手机
+            'province' => 'Receiving Province',//收货省
+            'address' => 'Receiving detailed address',//收货详细地址
+        ];
+    }
+
+    /**
+     * 指定场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName', 'mobile', 'address', 'consignee','acceptMobile','province','decUserName', 'location', 'email'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 判断报单中心是否存在
+     * @param $attribute
+     */
+    public function issetDec($attribute){
+        if (!$decUser = BaUser::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
+            $this->addError($attribute, 'Stockist does not exist'); // 报单中心不存在
+            return false;
+        } else {
+            $this->_decId = $decUser['ID'];
+        }
+    }
+
+    /**
+     * 判断开拓人
+     * @param $attribute
+     */
+    public function isRecUserName($attribute){
+        if($this->type == self::TYPE_ZC){
+            // 开拓人
+//            if(!isset($this->_tempParentUser[$this->recUserName])){
+//                $recUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);
+//                if(!$recUserTemp){
+//                    if($this->insertUserName){
+//                        //$this->addError($attribute, '为'.$this->insertUserName.'报单,开拓人'.$this->recUserName.'不存在');
+//                        $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->recUserName.'not in exist');
+//                    } else {
+//                       // $this->addError($attribute, '开拓人'.$this->recUserName.'不存在');
+//                        $this->addError($attribute, 'Sponsor'.$this->recUserName.'not in exist');
+//                    }
+//
+//                    return ;
+//                }
+//                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
+//                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
+//                $this->_tempParentUser[$this->recUserName] = [
+//                    'USER_NAME' => $this->recUserName,
+//                    'ZC_PV' => $recUserTemp['ZC_PV'],
+//                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
+//                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
+//                    'CON_NUM' => $recUserTemp['CON_NUM'],
+//                    'REC_NUM' => $recUserTemp['REC_NUM'],
+//                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
+//                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
+//                ];
+//                // 把该会员下面的5个区是否存在会员都付上
+//                for($i=1;$i<=5;$i++){
+//                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
+//                }
+//            }
+            $recUser = $this->_tempParentUser[$this->recUserName];
+            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
+
+            // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
+//            if($this->insertUserName) {
+//                $this->loopFindParentToNetwork($this->insertUserName);
+//                if (!$this->recUserIsInNetworkParent()) {
+//                   // $this->addError($attribute, '为' . $this->insertUserName . '报单,开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
+//                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Sponsor' . $this->recUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
+//                    return ;
+//                }
+//            }
+//
+//            // 把自己加入到临时上级会员数组中
+//            $this->_tempParentUser[$this->insertUserName] = [
+//                'USER_NAME' => $this->insertUserName,
+//                //'ZC_PV' => $this->decPv,
+//                'CON_USER_NAME' => $this->conUserName,
+//                'REC_USER_NAME' => $this->recUserName,
+//                'CON_NUM' => 0,
+//                'REC_NUM' => 0,
+//                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
+//                'LOCATION' => $this->location,
+//                'LOCATION1' => 0,
+//                'LOCATION2' => 0,
+//                'LOCATION3' => 0,
+//                'LOCATION4' => 0,
+//                'LOCATION5' => 0,
+//            ];
+        }
+
+    }
+
+    /**
+     * 添加报单
+     * @param $allData
+     * @return bool|null
+     * @throws Exception
+     * @throws \yii\db\Exception
+     */
+    public function add($allData){
+        if(!$this->validate()){
+            return null;
+        }
+
+        // 首购单,需要添加会员操作
+        if($this->type == self::TYPE_ZC){
+            if (preg_match("/[\x7f-\xff]/", $this->insertUserName)) {  // 判断字符串中是否有中文
+                throw new Exception('Member number cannot contain Chinese characters'); // 会员编号中不能含有汉字
+            }
+//            //报单商品及PV判断
+//            $decLevelConfig = Cache::getDecLevelConfig();
+//            $decLevel = $decLevelConfig[$this->decLv];
+//            $toDecLevel = $this->decLv;
+//            if(!$this->decLv){
+//                throw new Exception('Please select the entry level'); // 请选择报单级别
+//            }
+
+            $ids = $this->goodsId;
+            $totalAmount = 0;
+            $totalPv = 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){
+                        $totalAmount += $goods['SELL_PRICE'] * intval($v);
+                        $totalPv += $goods['PRICE_PV'] * intval($v);
+                        $this->_orderGoods[] = [
+                            'GOODS_ID' => $goods['ID'],
+                            'PRICE' => $goods['SELL_PRICE'],
+                            'REAL_PRICE' => $goods['SELL_PRICE'],
+                            'PV' => $goods['PRICE_PV'],
+                            'REAL_PV' => $goods['PRICE_PV'],
+                            'POINT' => $goods['POINT'],
+                            'BUY_NUMS' => intval($v),
+                            'SKU_CODE' => $goods['GOODS_NO'],
+                            'GOODS_TITLE' => $goods['GOODS_NAME'],
+                            'EMAIL' => $this->email,
+                            'TAX_RATE' => $goods['TAX_RATE'],
+                        ];
+                    }
+                }
+            }
+//                if($totalPv<$decLevel['PERF']){
+//                    throw new Exception('The total BV of self selected goods cannot be less than the BV of the selected entry level');//自选商品总BV不能小于所选报单级别BV
+//                }
+//                foreach ($decLevelConfig as $key=>$val){
+//                    if($totalPv>=$val['PERF']){
+//                        $toDecLevel = $key;
+//                    }
+//                }
+//                if($this->decLv!=$toDecLevel){
+//                    throw new Exception('The total BV of self selected goods cannot exceed the BV value of the next level under the selected level');//自选商品总BV不能超过已选级别下一个级别的BV值
+//                }
+            $this->_decAmount = $totalAmount;
+//                $this->_decPv = $totalPv;
+
+            //看现金余额是否充足
+            $loginUserId = \Yii::$app->user->id;
+            if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
+                throw new Exception('The applicant is short of cash and cannot complete the declaration');//报单人现金不足,无法完成报单
+            }
+//            print_r($allData);exit;
+            if(!($zcResult = $this->addBaUser($allData))) {
+                throw new Exception(Form::formatErrorsForApi($this->_userForm->getErrors()));
+            }
+//            print_r($allData);exit;
+            if(!($decResult = $this->addBaDecOrder())) {
+                throw new Exception(Form::formatErrorsForApi($decResult->getErrors()));
+            }
+        }
+        return true;
+    }
+
+    /**
+     * 添加会员
+     * @param $allData
+     * @return bool|UserInfo|null
+     * @throws \yii\db\Exception
+     * @throws \Exception
+     */
+    public function addBaUser($allData){
+        $period = Period::instance();
+
+        try {
+            // 增加会员
+            $user = new BaUser();
+            $user->USER_NAME = $this->insertUserName;
+            $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
+            $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->payPassword);
+            $user->NATION = 0;
+            $user->REAL_NAME = $this->realName;
+            $user->ID_CARD = $this->mobile;
+            $user->MOBILE = $this->mobile;
+            $user->EMAIL = $this->email;
+            $user->ADDRESS = $this->address ? $this->address : 'nothing';//无
+            //        $user->OPEN_BANK = $this->openBank;
+            //        $user->BANK_ADDRESS = $this->bankAddress;
+            //        $user->BANK_NO = $this->bankNo;
+            //        $user->BANK_PROVINCE = $this->bankProvince ?? 0;
+            //        $user->BANK_CITY = $this->bankCity ?? 0;
+            //        $user->BANK_COUNTY = $this->bankCounty ?? 0;
+            $user->CREATED_AT = Date::nowTime();
+            $user->STATUS = 1;
+            //        $user->DEC_LV = $this->decLv;
+            //        $user->LAST_DEC_LV = $this->decLv;
+            //        $user->EMP_LV = EmployLevel::getDefaultLevelId();
+            $user->PROVINCE = $this->province ?? 0;
+            $user->LGA_NAME = $this->lgaName;
+            $user->CITY_NAME = $this->cityName;
+            $user->AVATAR = 'avatar/1.png';
+            $user->IS_DEC = 0;
+            $user->DEC_ID = $this->_decId ?? '';
+            $user->DEC_ROLE_ID = $this->decRoleId ?? '';
+            $user->PERIOD_AT = $period->getNowPeriodNum();
+            $user->IS_DIRECT_SELLER = 0;
+            $user->VERIFIED = 1;
+            $user->VERIFIED_AT = Date::nowTime();
+
+            if (!$user->save()) {
+                throw new Exception(Form::formatErrorsForApi($user->getErrors()));
+            }
+
+            $this->_insertUserId = $user->ID;
+            $userForm = new BaUserForm();
+            $this->_userForm = $userForm;
+            $userForm->scenario = 'addWithUserName';
+            $userForm->userId = $this->_insertUserId;
+            $userForm->userName = $this->insertUserName;
+            //        $userForm->zcPv = $this->_decPv;
+            $userForm->zcAmount = $this->_decAmount;
+            //        $userForm->conUserName = $this->conUserName;
+            $userForm->recUserName = $this->recUserName;
+            //        $userForm->location = $this->location;
+            $userForm->idCard = $this->mobile;
+            $userForm->allData = $allData;
+            //        print_r($userForm);exit;
+            if (!$userForm->validate()) {
+                $this->addErrors($userForm->getErrors());
+                return false;
+            }
+            if ($result = $userForm->add()) {
+                return $result;
+            } else {
+                return false;
+            }
+        } catch (\Exception $e) {
+            LoggerTool::info($e->getMessage());
+            throw new \Exception($e->getMessage());
+        }
+    }
+
+    /**
+     * 添加报单订单
+     * @return bool|UserInfo|null
+     * @throws \yii\db\Exception
+     */
+    public function addBaDecOrder(){
+        $periodObj = Period::instance();
+        $nowPeriodNum = $periodObj->getNowPeriodNum();
+        $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
+
+        $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
+        // 加入报单信息
+        $decOrderModel = new BaDecOrder();
+        $decOrderModel->DEC_SN = 'DS'.$ord;
+        $decOrderModel->ORDER_SN = 'OS'.$ord;
+        $decOrderModel->TYPE = $this->type;
+        $decOrderModel->USER_ID = \Yii::$app->user->id;
+        $decOrderModel->TO_USER_ID = $this->_insertUserId;
+        $decOrderModel->DEC_AMOUNT = $this->_decAmount;
+//        $decOrderModel->DEC_PV = $this->_decPv;
+        $decOrderModel->PERIOD_NUM = $nowPeriodNum;
+        $decOrderModel->CALC_MONTH = $nowCalcMonth;
+        $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        $decOrderModel->PAID_WALLET = 'cash';
+//        $decOrderModel->CON_USER_ID = Info::getUserIdByUserName($this->conUserName);
+        $decOrderModel->REC_USER_ID = Info::getUserIdByUserName($this->recUserName);
+//        $decOrderModel->DEC_ID = $this->_decId;
+        $decOrderModel->IS_DEL = 0;
+        $decOrderModel->CREATED_AT = Date::nowTime();
+        if(!$decOrderModel->save()){
+            throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
+        }
+
+        // 加入订单信息
+        if($this->province!=1){
+            $warehouse = Region::getWarehouseByCode($this->province);//仓库
+            if(!$warehouse){
+                throw new Exception('Delivery is temporarily not supported in the region. Contact customer service for details');//地区暂时不支持配送,具体联系客服
+            }
+        }else{
+            $warehouse = '01';
+        }
+        $orderModel = new BaOrder();
+        $orderModel->SN = 'OS'.$ord;
+        $orderModel->DEC_SN = 'DS'.$ord;
+        $orderModel->ORDER_TYPE = $this->type;
+        $orderModel->USER_ID = $this->_insertUserId;
+        $orderModel->USER_NAME = $this->insertUserName;
+        $orderModel->ORDER_AMOUNT = $this->_decAmount;
+//        $orderModel->PV = $this->_decPv;
+        $orderModel->PAY_AMOUNT = $this->_decAmount;
+//        $orderModel->PAY_PV = $this->_decPv;
+        $orderModel->PAY_AT = Date::nowTime();
+        $orderModel->PAY_TYPE = 'cash';
+        $orderModel->PERIOD_NUM = $nowPeriodNum;
+        $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
+        $orderModel->FREIGHT = 0;
+        $orderModel->PAY_FREIGHT = 0;
+        $orderModel->CONSIGNEE = $this->consignee;
+        $orderModel->MOBILE = $this->acceptMobile;
+        $orderModel->EMAIL = $this->email;
+        $orderModel->PROVINCE = $this->province;
+        $orderModel->LGA_NAME = $this->lgaName;
+        $orderModel->CITY_NAME = $this->cityName;
+        $orderModel->ADDRESS = $this->address;
+        $orderModel->WAREHOUSE = $warehouse;
+        $orderModel->STATUS = 1;
+        $orderModel->CREATED_AT = Date::nowTime();
+        $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
+        if($this->province==1){
+            $orderModel->EXPRESS_TYPE = 1;
+        }
+        if(!$orderModel->save()){
+            throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
+        }
+        // 加入商品到订单商品表
+        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);
+        }
+        BaOrderGoods::batchInsert($this->_orderGoods);
+
+        //写入收货地址信息,判断province字段,当不为1时,插入收货地址信息
+        if($this->province!=1){
+            $addressModel = new ReceiveAddress();
+            $addressModel->USER_ID = $this->_insertUserId;
+            $addressModel->USER_NAME = $this->insertUserName;
+            $addressModel->CONSIGNEE = $this->consignee;
+            $addressModel->MOBILE = $this->acceptMobile;
+            $addressModel->PROVINCE = $this->province;
+            $addressModel->CITY_NAME = $this->cityName;
+            $addressModel->LGA_NAME = $this->lgaName;
+            $addressModel->ADDRESS = $this->address;
+            $addressModel->IS_DEFAULT = 1;
+            if(!$addressModel->save()){
+                throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
+            }
+        }else{
+            $addressModel = new ReceiveAddress();
+        }
+        //扣报单人现金钱包
+        Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'To'.$this->insertUserName.'Entry']); // 报单
+        return $addressModel;
+    }
+
+    /**
+     * 删单
+     * @return bool
+     * @throws \yii\db\Exception
+     */
+    public function delete(){
+        if(!$this->validate()){
+            return false;
+        }
+        $transaction = \Yii::$app->db->beginTransaction();
+        try {
+            $oneOrder = $this->_oneOrder;
+            // 首购单要删除会员
+            if($this->type == self::TYPE_ZC){
+                BaUserInfo::deleteUser($oneOrder['TO_USER_ID']);
+            }
+            // 如果是复销单的话,还需要考虑给会员的复销池减去金额
+            elseif($this->type == self::TYPE_FX){
+//                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
+                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'Deletion deduction', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
+            }
+            $transaction->commit();
+        } catch (Exception $e) {
+            $transaction->rollBack();
+            $this->addError('delete', $e->getMessage());
+            return false;
+        }
+        return true;
+    }
+
+}

+ 191 - 0
common/models/forms/BaDeclarationLoopForm.php

@@ -0,0 +1,191 @@
+<?php
+namespace common\models\forms;
+
+use common\components\Model;
+use common\helpers\Form;
+use common\models\UserBind;
+use yii\base\Exception;
+use yii\helpers\Json;
+use common\models\DeclarationPackage;
+use common\helpers\Date;
+use common\models\ShopGoods;
+
+/**
+ * Login form
+ */
+class BaDeclarationLoopForm extends Model
+{
+    public $data;
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['data'], 'required'],
+            [['data'], 'formatData'],
+            [['data'], 'isData', 'on'=>['canDec', 'notFull']],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'data' => 'Data',// 数据
+        ];
+    }
+
+    /**
+     * 指定场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            'userDec' => ['data'],
+            'canDec' => ['data'],
+            'notFull' => ['data'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 格式化提交的数据
+     * @param $attribute
+     */
+    public function formatData($attribute){
+        //$this->data = Json::decode($this->data);
+        if(!is_array($this->data)){
+            $this->addError($attribute, 'Data format error');// 数据格式错误
+        }
+    }
+
+    /**
+     * 循环校验数据是否合格
+     * @param $attribute
+     */
+    public function isData($attribute){
+        $model = new BaDeclarationForm();
+        $model->scenario = $this->scenario;
+        $model->allData = $this->data;
+        foreach ($this->data as $value){
+            if(is_array($value)){
+                foreach($value as $key=>$decFormData){
+                    $model->$key = $decFormData;
+                }
+                if(!$model->validate()){
+                    $this->addErrors($model->getErrors());
+                }
+                $model->type = null;
+                $model->decSn = null;
+                $model->userId = null;
+                $model->toUserId = null;
+                $model->decPv = null;
+                $model->insertUserName = null;
+                $model->insertUserIdCard = null;
+                $model->conUserName = null;
+                $model->recUserName = null;
+                $model->location = null;
+            } else {
+                $this->addError($attribute, 'The format of the report data is incorrect');// 报单数据格式错误
+            }
+
+        }
+    }
+
+    /**
+     * 报单
+     * @return bool
+     * @throws \yii\db\Exception
+     */
+    public function add(){
+        $startTime = microtime(true);
+        if(!$this->validate()){
+            return null;
+        }
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try{
+            // 所有的首购单会员ID以备点位绑定使用
+            $allZcUserIds = [];
+            $zcUserIdCard = null;
+            $model = new BaDeclarationForm();
+            $model->scenario = $this->scenario;
+            $model->allData = $this->data;
+            foreach ($this->data as $value){
+                if (count($value['goodsId']) > 0 && (count($value['goodsId']) == count($value['goodsNum']))){
+                    for ($i=0;$i<count($value['goodsId']);$i++){
+                        $goods = ShopGoods::findOneAsArray('ID=:ID',[':ID'=> $value['goodsId'][$i]]);
+                        if ($goods['STATUS'] == 1 ){
+                            if($goods['STORE_NUMS'] >= $value['goodsNum'][$i]){
+                                $data = ShopGoods::find()->where(['ID' => $value['goodsId'][$i]])->one();
+                                $goods_store_nums = $data->STORE_NUMS - $value['goodsNum'][$i];
+                                $data->STORE_NUMS = $goods_store_nums;
+                                $data->update();
+                                if($goods_store_nums <= 0){
+                                    $data->STATUS = 0;
+                                    $data->UPDATED_AT = Date::nowTime();
+                                    $data->update();
+                                }
+                            }else{
+                                throw new Exception($goods['GOODS_NAME'].'Insufficient inventory');// 商品库存不足
+                            }
+                        }else{
+                            throw new Exception($goods['GOODS_NAME'].'Sold out');// 商品已下架
+                        }
+                    }
+                }
+
+                if(is_array($value)){
+                    foreach($value as $key=>$decFormData){
+                        $model->$key = $decFormData;
+                    }
+                    // 把首购单的几个会员归集到一个数组里,将来绑定到一起
+                    if( $model->type == 'ZC'){
+                        $allZcUserIds[] = null;
+                        if($zcUserIdCard != null){
+                            if($model->insertUserIdCard != $zcUserIdCard){
+                                throw new Exception('Bulk declaration member must be the same member'); // 批量报单会员必须是同一身份证
+                            }
+                        } else {
+                            $zcUserIdCard = $model->insertUserIdCard;
+                        }
+                    }
+                    if(!$model->add($this->data)){
+                        throw new Exception(Form::formatErrorsForApi($model->getErrors()));
+                    }
+                } else {
+                    throw new Exception('The format of the report data is incorrect');// 报单数据格式错误
+                }
+            }
+            $transaction->commit();
+        } catch (\Exception $e){
+            $transaction->rollBack();
+            $this->addError('add', $e->getMessage());
+            return null;
+        }
+        return true;
+    }
+
+    /**
+     * RPC服务校验数据
+     * @param $data
+     * @return array
+     */
+    public static function rpcIsData($data){
+        $result = [
+            'error' => false,
+            'message' => 'Data can be reported',//数据可报单
+        ];
+        $formModel = new self();
+        $formModel->scenario = 'canDec';
+        $formModel->data = $data;
+        if(!$formModel->validate()){
+            $result['error'] = true;
+            $result['message'] = Form::formatErrorsForApi($formModel->getErrors());
+        }
+        return $result;
+    }
+}

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

@@ -0,0 +1,201 @@
+<?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\UserOperate;
+use common\models\Ad;
+use common\models\BaReceiveAddress;
+use common\models\ReceiveAddress;
+use common\models\Region;
+use common\models\User;
+use common\models\UserInfo;
+use yii\base\Exception;
+
+class BaReceiveAddressForm extends Model
+{
+    public $id;
+    public $consignee;
+    public $mobile;
+    public $province;
+    public $city;
+    public $county;
+    public $lgaName;
+    public $cityName;
+    public $address;
+    public $isDefault;
+
+    /**
+     * @var BaReceiveAddress
+     */
+    private $_model;
+
+
+    public function init() {
+        parent::init();
+//        $this->adminOperateLogger = new UserOperate([
+//            'fetchClass' => BaReceiveAddress::class,
+//        ]);
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['id', 'consignee', 'mobile', 'province', 'lgaName', 'cityName', 'address', 'isDefault'], 'trim'],
+            [['id', 'consignee', 'mobile', 'province', 'lgaName', 'cityName', 'address'], 'required'],
+            [['mobile'], 'mobile'],
+            [['province'], 'exist', 'targetClass' => Region::class, 'targetAttribute' => 'REGION_CODE'],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'consignee' => 'Consignee',
+            'mobile' => 'Phone',
+            'province' => 'State',
+            'lgaName' => 'Local Government Area',
+            'cityName' => 'City Name',
+            'address' => 'Address',
+        ];
+    }
+
+    /**
+     * 指定校验场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            'userAdd' => ['consignee', 'mobile', 'province', 'lgaName', 'cityName', 'address', 'isDefault'],
+            'userEdit' => ['id', 'consignee', 'mobile', 'province', 'lgaName', 'cityName', 'address', 'isDefault'],
+            'userIsDefault' => ['id', 'isDefault'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 校验之前
+     * @return bool
+     */
+    public function beforeValidate()
+    {
+        $userId = \Yii::$app->getUser()->getId();
+        $parentResult = parent::beforeValidate();
+        if ($this->scenario == 'userAdd' || $this->scenario == 'userEdit' || $this->scenario == 'userIsDefault') {
+            if ($this->scenario == 'userAdd') {
+
+                $count = BaReceiveAddress::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->count();
+                if ($count > 10) {
+                    $this->addError('id', 'A maximum of 10 shipping addresses can be added'); // 最多只能添加10个收货地址
+                    return $parentResult;
+                }
+            }
+            if ($this->id) {
+                $this->_model = BaReceiveAddress::findOne(["ID" => $this->id]);
+                if (!$this->_model){
+                    $this->addError('id', 'Address does not exist'); // 地址不存在
+                    return $parentResult;
+                }
+                if ($this->_model['USER_ID'] != $userId){
+                    $this->addError('id', 'You have no right to modify this address'); // 无权修改此地址
+                    return $parentResult;
+                }
+            } else {
+                $this->_model = new BaReceiveAddress();
+            }
+        }
+
+        return $parentResult;
+    }
+
+    /**
+     * 添加编辑
+     * @return BaReceiveAddress|null
+     * @throws \yii\db\Exception
+     */
+    public function edit(){
+        if(!$this->validate()){
+            return null;
+        }
+
+        $userId = \Yii::$app->getUser()->getId();
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            // 如果设置了此项为默认则清空所有默认
+            if ($this->isDefault) {
+                BaReceiveAddress::updateAll(['IS_DEFAULT' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
+            }
+
+            if($this->scenario == 'userAdd'){
+                $this->_model->USER_ID = $userId;
+                $this->_model->USER_NAME = Info::getBaUserNameByUserId($userId); // TODO:
+                $this->_model->CONSIGNEE = $this->consignee;
+                $this->_model->MOBILE = $this->mobile;
+                $this->_model->PROVINCE = $this->province;
+                $this->_model->LGA_NAME = $this->lgaName;
+                $this->_model->CITY_NAME = $this->cityName;
+                $this->_model->ADDRESS = $this->address;
+                $this->_model->IS_DEFAULT = $this->isDefault ? 1 : 0;
+                $this->_model->CREATED_AT = Date::nowTime();
+            } elseif($this->scenario == 'userEdit') {
+                $this->_model->CONSIGNEE = $this->consignee;
+                $this->_model->MOBILE = $this->mobile;
+                $this->_model->PROVINCE = $this->province;
+                $this->_model->LGA_NAME = $this->lgaName;
+                $this->_model->CITY_NAME = $this->cityName;
+                $this->_model->ADDRESS = $this->address;
+                $this->_model->IS_DEFAULT = $this->isDefault ? 1 : 0;
+                $this->_model->UPDATED_AT = Date::nowTime();
+            } elseif($this->scenario == 'userIsDefault') {
+                $this->_model->IS_DEFAULT = $this->isDefault ? 1 : 0;
+            } else {
+                throw new Exception('The scene does not exist'); // 场景不存在
+            }
+            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;
+        }
+        if($this->scenario == 'adminAdd'){
+            $this->adminOperateLogger->afterInsert($this->_model)->clean()->save([
+                'optType' => 'Add shipping address', // 添加收货地址
+            ]);
+        } elseif($this->scenario == 'adminEdit') {
+            $this->adminOperateLogger->afterUpdate($this->_model)->clean()->save([
+                'optType' => 'Edit shipping address', // 编辑收货地址
+            ]);
+        }
+        return $this->_model;
+    }
+
+    /**
+     * 删除前
+     * @param $selected
+     */
+    public function beforeDelete($selected) {
+        $this->adminOperateLogger->fetchClass = Ad::class;
+        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
+    }
+    /**
+     * 删除
+     * @param $selected
+     * @throws Exception
+     */
+    public function delete($selected) {
+        $this->adminOperateLogger->clean()->save([
+            'optType' => 'Delete shipping address', // 删除收货地址
+        ]);
+    }
+}

+ 224 - 0
common/models/forms/BaUserBasicForm.php

@@ -0,0 +1,224 @@
+<?php
+
+namespace common\models\forms;
+
+use common\components\Model;
+use common\helpers\Date;
+use common\libs\logging\operate\AdminOperate;
+use common\models\BaUser;
+use yii\base\Exception;
+
+/**
+ * Login form
+ */
+class BaUserBasicForm 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' => BaUser::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 BaUser|null
+     */
+    public function edit()
+    {
+        if (!$this->validate()) {
+            return null;
+        }
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            $userModel = BaUser::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 BaUser|null
+     */
+    public function modifyProfile(){
+        if(!$this->validate()){
+            return null;
+        }
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            $userModel = BaUser::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 BaUser|null
+     */
+    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 = BaUser::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 BaUser|null
+     */
+    public function isModifyPasswordStatus()
+    {
+        if(!$this->validate()){
+            return null;
+        }
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            $userModel = BaUser::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;
+    }
+}

+ 234 - 0
common/models/forms/BaUserForm.php

@@ -0,0 +1,234 @@
+<?php
+namespace common\models\forms;
+
+use common\components\Model;
+use common\helpers\Date;
+use common\helpers\user\Info;
+use common\libs\logging\operate\UserOperate;
+use common\models\BaUser;
+use common\models\BaUserInfo;
+use common\models\User;
+use common\models\UserInfo;
+use yii\db\Exception;
+
+/**
+ * Login form
+ */
+class BaUserForm extends Model
+{
+    public $userId;
+    public $userName;
+    public $zcPv;
+    public $zcAmount;
+    public $conUserName;
+    public $recUserName;
+    public $conUid;
+    public $recUid;
+    public $location;
+    public $idCard;
+    public $allData;   // 批量报单的全部报单数据
+
+    //个人资料
+    public $nation;
+    public $realName;
+    public $mobile;
+    public $openBank;
+    public $bankAddress;
+    public $bankNo;
+    public $email;
+
+    //修改密码
+    public $password;
+    public $oldPassword;
+    public $verifyPassword;
+    public $payPassword;
+
+    private $_conUid;
+    private $_recUid;
+    private $_limit = 1000;
+
+    private $_conTopDeep;
+
+    public function init() {
+        parent::init();
+        $this->userOperateLogger = new UserOperate([
+            'fetchClass' => BaUser::class,
+        ]);
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['userId', 'userName', 'zcPv', 'zcAmount', 'conUserName', 'recUserName','conUid', 'recUid', 'location',/* 'nation', */'realName', /* 'mobile','openBank','bankAddress','bankNo', */ 'email'], 'trim'],
+            [['userId', 'userName',/* 'zcPv', 'zcAmount',*/ 'conUid', 'recUid', 'location'], 'required', 'on'=>'addWithUid'],
+            [['userId', 'userName',/* 'zcPv', 'zcAmount', 'conUserName',*/ 'recUserName', /*'location'*/], 'required', 'on'=>['addWithUserName', 'addByAdmin']],
+            [['idCard', 'allData'], 'required', 'on'=>['addWithUserName']],
+            [['userName'], 'required', 'on'=>['validateUser', 'noLoginModifyPassword']],
+            [['conUid'], 'required', 'on'=>['validateCon', 'validateAddWithUid']],
+            [['conUserName'], 'required', 'on'=>['validateConName', 'validateAddWithName']],
+            [['recUid'], 'required', 'on'=>['validateRec', 'validateAddWithUid']],
+            [['recUserName'], 'required', 'on'=>['validateRecName', 'validateAddWithName']],
+            [['conUid', 'location'], 'required', 'on'=>['validateLocation', 'validateAddWithUid']],
+            [['conUserName', 'location'], 'required', 'on'=>['validateLocationConName', 'validateAddWithName']],
+            [[/* 'nation' ,*/'realName'/*,  'mobile', */ /*'idCard',*/ /* 'openBank', 'bankAddress', 'bankNo' *//*, 'email'*/], 'required', 'on'=>'modifyProfile'],
+            [['oldPassword','verifyPassword'], 'required','on' => ['modifyPassword', 'modifyPasswordPay', 'noLoginModifyPassword']],
+            [['password'], 'required','on' => ['modifyPassword', 'noLoginModifyPassword']],
+            [['payPassword'], 'required','on' => ['modifyPasswordPay']],
+            ['verifyPassword', 'compare', 'compareAttribute' => 'password' ,'message'=>'The two login passwords are inconsistent' ,'on' => ['modifyPassword', 'noLoginModifyPassword']],//两次登录密码输入不一致
+            ['verifyPassword', 'compare', 'compareAttribute' => 'payPassword' ,'message'=>'The two payment passwords are inconsistent' ,'on' => ['modifyPasswordPay']],//两次支付密码输入不一致
+            [['userId'], 'unique', 'targetClass'=>BaUserInfo::class, 'targetAttribute'=>'USER_ID', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
+            [['userName'], 'unique', 'targetClass'=>BaUserInfo::class, 'targetAttribute'=>'USER_NAME' , 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
+            [['recUid'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_ID', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
+            [['recUid'], 'isRecUid', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
+            [['conUserName'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_NAME', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
+            [['recUserName'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_NAME', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
+            [['recUserName'], 'isRec', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
+            [[/*'zcPv',*/ 'zcAmount'], 'price', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'userId' => '会员ID',
+            'recUserName' => '开拓人帐号',
+            'verifyPassword' => 'Confirm password',//确认密码
+            'oldPassword' => 'Original password',//原密码
+            'password' => 'Login password',//登录密码
+            'payPassword' => 'Payment password',//支付密码
+            'email' => 'Email',
+        ];
+    }
+
+    /**
+     * 推荐人是否可用
+     * @param $attribute
+     * @param $params
+     */
+    public function isRecUid($attribute, $params) {
+        $this->_recUid = $this->recUid;
+    }
+
+    /**
+     * 推荐人是否可用
+     * @param $attribute
+     * @param $params
+     */
+    public function isRec($attribute, $params){
+        // 根据账号找到开拓人
+        $oneRecUserInfo = User::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME'=>$this->recUserName]);
+        if($oneRecUserInfo && $oneRecUserInfo['STATUS']){
+            $this->_recUid = $oneRecUserInfo['ID'];
+        } else {
+            $this->addError($attribute, '注册'.$this->userName.'时,开拓人'.$this->recUserName.'帐号无效或未激活');
+        }
+    }
+
+    /**
+     * 添加会员
+     */
+    public function add()
+    {
+        if(!$this->validate()){
+            return null;
+        }
+
+        $insertUid = $this->userId;
+        $insertUserName = $this->userName;
+        $recUid = $this->_recUid;
+
+        try {
+            // 加入会员信息
+            $userInfoModel = new BaUserInfo();
+            $userInfoModel->USER_ID = $insertUid;
+            $userInfoModel->USER_NAME = $insertUserName;
+            $userInfoModel->ZC_AMOUNT = $this->zcAmount;
+            $userInfoModel->CON_UID = '';
+            $userInfoModel->REC_UID = $recUid;
+            $userInfoModel->CREATED_AT = Date::nowTime();
+            $userInfoModel->ALLOW_TRANSFER = 1;
+            $userInfoModel->TRANSFER_PROP = 100.00;
+            $userInfoModel->IS_GROUP_LEADER = 0;
+            $userInfoModel->GROUP_LEADER_AT = 0;
+            $userInfoModel->save();
+
+            return $userInfoModel;
+        } catch (Exception $e) {
+            $this->addError('userId', $e->getMessage());
+            return null;
+        }
+    }
+
+    /**
+     * 修改个人资料
+     */
+    public function modifyProfile(){
+        if(!$this->validate()){
+            return null;
+        }
+        $this->userOperateLogger->beforeUpdate(\Yii::$app->user->id,'ID',['select'=>'NATION,OPEN_BANK,BANK_NO,BANK_ADDRESS,EMAIL']);
+
+        $uid = \Yii::$app->user->id;
+        $model = BaUser::findOne(['ID'=>$uid]);
+        $model->EMAIL = $this->email;
+        if(!$model->save()){
+            $this->addErrors($model->getErrors());
+            return null;
+        }
+        BaUser::updateBaseInfoToRedis($uid);
+
+        $this->userOperateLogger->afterUpdate(\Yii::$app->user->id,'ID',['select'=>'NATION,OPEN_BANK,BANK_NO,BANK_ADDRESS']);
+        $this->userOperateLogger->clean()->save([
+            'optType' => '会员修改资料',
+            'userId' => \Yii::$app->user->id,
+            'userName' => Info::getUserNameByUserId(\Yii::$app->user->id),
+        ]);
+
+        return $model;
+    }
+
+    /**
+     * 修改密码
+     */
+    public function modifyPassword(){
+        if(!$this->validate()){
+            return null;
+        }
+        $uid = \Yii::$app->user->id;
+        $model = BaUser::findOne(['ID'=>$uid]);
+        if ( !$model->validatePassword($this->oldPassword) ) {
+            $this->addError('modifyPassword', 'Original login password error');//原登录密码错误
+            return false;
+        }
+        $model->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
+        if(!$model->save()){
+            $this->addErrors($model->getErrors());
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * 修改支付密码
+     */
+    public function modifyPasswordPay(){
+        if(!$this->validate()){
+            return null;
+        }
+        $uid = \Yii::$app->user->id;
+        $model = BaUser::findOne(['ID'=>$uid]);
+        if ( !$model->validatePasswordPay($this->oldPassword) ) {
+            $this->addError('modifyPasswordPay', 'Original payment password error');//原支付密码错误
+            return false;
+        }
+        $model->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->payPassword);
+        if(!$model->save()){
+            $this->addErrors($model->getErrors());
+            return false;
+        }
+        return true;
+    }
+}

+ 21 - 15
common/models/forms/DeclarationForm.php

@@ -8,6 +8,7 @@ use common\helpers\Form;
 use common\helpers\user\Cash;
 use common\helpers\user\Reconsume;
 use common\helpers\user\Info;
+use common\models\BaUser;
 use common\models\DeclarationPackage;
 use common\models\DecOrder;
 use common\models\EmployLevel;
@@ -62,6 +63,7 @@ class DeclarationForm extends Model
     public $county;
     public $cityName;
     public $lgaName;
+    public $decType;
 
     // 传过来的全部数据
     public $allData;
@@ -189,21 +191,23 @@ class DeclarationForm extends Model
      */
     public function issetDec($attribute){
         if (!$decUser = User::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
-            $this->addError($attribute, 'Stockist does not exist');//报单中心不存在
+            $this->addError($attribute, 'Stockist does not exist'); // 报单中心不存在
             return false;
         } else {
-            // 判断报单中心是否在新加入会员的安置网上级中
-            $this->loopFindParentToNetwork($this->insertUserName);
-            //反转数组,in_array搜索错误
-            //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
-            $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
+            if ($this->decType !== 'ba') {
+                // 判断报单中心是否在新加入会员的安置网上级中
+                $this->loopFindParentToNetwork($this->insertUserName);
+                //反转数组,in_array搜索错误
+                //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
+                $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
 //            var_dump($flipParent);
 //            echo $this->insertUserName.'=='.$this->decUserName;
 //            exit;
-            if (!isset($flipParent[$this->decUserName])) {
-                //$this->addError($attribute, '为' . $this->insertUserName . '报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
-                $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Stockist' . $this->decUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
-                return ;
+                if (!isset($flipParent[$this->decUserName])) {
+                    //$this->addError($attribute, '为' . $this->insertUserName . '报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
+                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Stockist' . $this->decUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
+                    return ;
+                }
             }
             $this->_decId = $decUser['ID'];
         }
@@ -321,11 +325,13 @@ class DeclarationForm extends Model
 
             // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
             if($this->insertUserName) {
-                $this->loopFindParentToNetwork($this->insertUserName);
-                if (!$this->recUserIsInNetworkParent()) {
-                   // $this->addError($attribute, '为' . $this->insertUserName . '报单,开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
-                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Sponsor' . $this->recUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
-                    return ;
+                if ($this->decType !== 'ba') {
+                    $this->loopFindParentToNetwork($this->insertUserName);
+                    if (!$this->recUserIsInNetworkParent()) {
+                        // $this->addError($attribute, '为' . $this->insertUserName . '报单,开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
+                        $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Sponsor' . $this->recUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
+                        return ;
+                    }
                 }
             }
 

+ 1 - 0
common/models/forms/DeclarationLoopForm.php

@@ -88,6 +88,7 @@ class DeclarationLoopForm extends Model
                 $model->conUserName = null;
                 $model->recUserName = null;
                 $model->location = null;
+                $model->decType = null;
             } else {
                 $this->addError($attribute, 'The format of the report data is incorrect');// 报单数据格式错误
             }

+ 1 - 1
common/models/forms/DeclarationUpgradeForm.php

@@ -401,7 +401,7 @@ class DeclarationUpgradeForm extends Model
             $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
             if (!isset($flipParent[$this->decUserName])) {
 //                $this->addError($attribute, '为' . $this->insertUserName . '升级报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
-                $this->addError($attribute, 'by' . $this->insertUserName . 'Upgrade declaration, declaration Center' . $this->decUserName . 'be not in' . $this->insertUserName . 'Online level of resettlement');
+                $this->addError($attribute, 'by' . $this->insertUserName . 'Upgrade declaration, Stockist' . $this->decUserName . 'be not in' . $this->insertUserName . 'Online level of resettlement');
                 return ;
             }
             $this->_decId = $decUser['ID'];

+ 126 - 0
common/models/forms/PerfAdjustmentForm.php

@@ -0,0 +1,126 @@
+<?php
+namespace common\models\forms;
+
+use common\components\Model;
+use common\helpers\Form;
+use common\libs\logging\operate\AdminOperate;
+use common\models\Period;
+use common\models\UserPerf;
+use yii\base\Exception;
+
+class PerfAdjustmentForm extends Model
+{
+    public $USER_ID;
+    public $USER_NAME;
+
+    public $SURPLUS_1L;
+    public $SURPLUS_1L_ZC;
+    public $SURPLUS_1L_FX;
+
+    public $SURPLUS_2L;
+    public $SURPLUS_2L_ZC;
+    public $SURPLUS_2L_FX;
+
+    public function init()
+    {
+        parent::init();
+        $this->adminOperateLogger = new AdminOperate([
+            'fetchClass' => UserPerf::class,
+        ]);
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'SURPLUS_1L', 'SURPLUS_1L_ZC', 'SURPLUS_1L_FX', 'SURPLUS_2L', 'SURPLUS_2L_ZC', 'SURPLUS_2L_FX'], 'required'],
+        ];
+    }
+
+    /**
+     * 指定场景
+     * @return array
+     */
+    public function scenarios() {
+        $parentScenarios = parent::scenarios();
+        $customScenarios = [
+            'perfAdjustment' => ['USER_ID', 'USER_NAME', 'SURPLUS_1L', 'SURPLUS_1L_ZC', 'SURPLUS_1L_FX', 'SURPLUS_2L', 'SURPLUS_2L_ZC', 'SURPLUS_2L_FX']
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'USER_ID'       => '会员ID',
+            'SURPLUS_1L'    => '一市场综合结余业绩',
+            'SURPLUS_1L_ZC' => '一市场综合报单业绩',
+            'SURPLUS_1L_FX' => '一市场复消结余业绩',
+            'SURPLUS_2L'    => '二市场综合结余业绩',
+            'SURPLUS_2L_ZC' => '二市场综合报单业绩',
+            'SURPLUS_2L_FX' => '二市场复消结余业绩',
+        ];
+    }
+
+    /**
+     * 调整会员业绩
+     * @return bool|null
+     */
+    public function perfAdjustment(): ?bool
+    {
+        if (!$this->validate()) {
+            return false;
+        }
+
+        $transaction = \Yii::$app->db->beginTransaction();
+        try {
+            // 修改前业绩
+            $userPerf = UserPerf::find()
+                ->where('USER_ID=:USER_ID', [':USER_ID' => $this->USER_ID])
+                ->select('USER_ID,SURPLUS_1L,SURPLUS_1L_ZC,SURPLUS_1L_FX,SURPLUS_2L,SURPLUS_2L_ZC,SURPLUS_2L_FX')
+                ->one();
+            if (!$userPerf->toArray()) {
+                throw new Exception('Member performance does not exist'); // 会员业绩不存在
+            }
+
+            $this->adminOperateLogger->beforeUpdate($userPerf);
+
+            $modernPerf = [
+                'SURPLUS_1L'    => $this->SURPLUS_1L,
+                'SURPLUS_1L_ZC' => $this->SURPLUS_1L_ZC,
+                'SURPLUS_1L_FX' => $this->SURPLUS_1L_FX,
+                'SURPLUS_2L'    => $this->SURPLUS_2L,
+                'SURPLUS_2L_ZC' => $this->SURPLUS_2L_ZC,
+                'SURPLUS_2L_FX' => $this->SURPLUS_2L_FX,
+            ];
+            if (!UserPerf::updateAll($modernPerf, 'USER_ID=:USER_ID', [':USER_ID' => $this->USER_ID])) {
+                throw new Exception(Form::formatErrorsForApi($userPerf->getErrors()));
+            }
+
+            $transaction->commit();
+
+            $afterUpdate = UserPerf::find()
+                ->where('USER_ID=:USER_ID', [':USER_ID' => $this->USER_ID])
+                ->select('USER_ID,SURPLUS_1L,SURPLUS_1L_ZC,SURPLUS_1L_FX,SURPLUS_2L,SURPLUS_2L_ZC,SURPLUS_2L_FX')
+                ->one();
+            $this->adminOperateLogger->afterUpdate($afterUpdate)->clean()->save([
+                'optType' => 'perf adjustment', // 调整业绩
+                'userId' => $this->USER_ID,
+                'userName' => $this->USER_NAME,
+                'periodNum' => Period::instance()->getNowPeriodNum(),
+            ]);
+        } catch (Exception $e) {
+            $transaction->rollBack();
+            $this->addError('perfAdjustment', $e->getMessage());
+            return false;
+        }
+
+        return true;
+    }
+
+}

+ 7 - 7
common/models/forms/ReceiveAddressForm.php

@@ -95,18 +95,18 @@ class ReceiveAddressForm extends Model
             if ($this->scenario == 'userAdd') {
                 $count = ReceiveAddress::find()->where('USER_ID=:USER_ID', [':USER_ID'=>\Yii::$app->user->id])->count();
                 if ($count > 10) {
-                    $this->addError('id', '最多只能添加10个收货地址');
+                    $this->addError('id', 'A maximum of 10 shipping addresses can be added'); // 最多只能添加10个收货地址
                     return $parentResult;
                 }
             }
             if ($this->id) {
                 $this->_model = ReceiveAddress::findOne(["ID"=>$this->id]);
                 if (!$this->_model){
-                    $this->addError('id', '地址不存在');
+                    $this->addError('id', 'Address does not exist'); // 地址不存在
                     return $parentResult;
                 }
                 if ($this->_model['USER_ID'] != \Yii::$app->user->id){
-                    $this->addError('id', '无权修改此地址');
+                    $this->addError('id', 'You have no right to modify this address'); // 无权修改此地址
                     return $parentResult;
                 }
             } else {
@@ -156,7 +156,7 @@ class ReceiveAddressForm extends Model
             } elseif($this->scenario == 'userIsDefault') {
                 $this->_model->IS_DEFAULT = $this->isDefault ? 1 : 0;
             } else {
-                throw new Exception('提交场景不存在');
+                throw new Exception('The scene does not exist'); // 场景不存在
             }
             if(!$this->_model->save()){
                 throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
@@ -169,11 +169,11 @@ class ReceiveAddressForm extends Model
         }
         if($this->scenario == 'adminAdd'){
             $this->adminOperateLogger->afterInsert($this->_model)->clean()->save([
-                'optType' => '添加收货地址',
+                'optType' => 'Add shipping address', // 添加收货地址
             ]);
         } elseif($this->scenario == 'adminEdit') {
             $this->adminOperateLogger->afterUpdate($this->_model)->clean()->save([
-                'optType' => '编辑收货地址',
+                'optType' => 'Edit shipping address', // 编辑收货地址
             ]);
         }
         return $this->_model;
@@ -194,7 +194,7 @@ class ReceiveAddressForm extends Model
      */
     public function delete($selected) {
         $this->adminOperateLogger->clean()->save([
-            'optType' => '删除收货地址',
+            'optType' => 'Delete shipping address', // 删除收货地址
         ]);
     }
 }

+ 1 - 1
common/models/forms/UploadForm.php

@@ -182,7 +182,7 @@ class UploadForm extends Model {
 //                $fileName = Tool::generateId(false);
                 $fileName = $this->file->baseName;
                 // 保存在本地
-                $localPath = '/ng/Volumes/HDD/workshop/old/ar.upload.ming/files/' . $fileName . '.' . $this->file->extension;
+                $localPath = '/ng922/Volumes/HDD/workshop/old/ar.upload.ming/files/' . $fileName . '.' . $this->file->extension;
                 if (!$this->file->saveAs($localPath)) {
                     throw new Exception('Failed');
                 }

+ 0 - 0
common/models/forms/UserBonusForm.php


+ 9 - 9
common/models/forms/UserForm.php

@@ -83,7 +83,7 @@ class UserForm extends Model
             [['conUid', 'location'], 'required', 'on'=>['validateLocation', 'validateAddWithUid']],
             [['conUserName', 'location'], 'required', 'on'=>['validateLocationConName', 'validateAddWithName']],
 
-            [['nation','realName', 'mobile', /*'idCard',*/ 'openBank', 'bankAddress', 'bankNo'/*, 'email'*/], 'required', 'on'=>'modifyProfile'],
+            [[/*'nation',*/'realName', 'mobile', /*'idCard',*/ /*'openBank', 'bankAddress', 'bankNo'*//*, 'email'*/], 'required', 'on'=>'modifyProfile'],
             [['oldPassword','verifyPassword'], 'required','on' => ['modifyPassword', 'modifyPasswordPay', 'noLoginModifyPassword']],
             [['password'], 'required','on' => ['modifyPassword', 'noLoginModifyPassword']],
             [['payPassword'], 'required','on' => ['modifyPasswordPay']],
@@ -113,13 +113,13 @@ class UserForm extends Model
             'conUserName' => '接点人账号',
             'recUserName' => '开拓人帐号',
             'location' => '区位',
-            'nation' => '民族',
+//            'nation' => '民族',
             //'realName' => '真实姓名',
 //            'idCard' => '身份证号',
             //'mobile' => '手机号',
-            'openBank' => '银行名称',
-            'bankAddress' => '开户支行',
-            'bankNo' => '银行账号',
+//            'openBank' => '银行名称',
+//            'bankAddress' => '开户支行',
+//            'bankNo' => '银行账号',
             'verifyPassword' => 'Confirm password',//确认密码
             'oldPassword' => 'Original password',//原密码
             'password' => 'Login password',//登录密码
@@ -544,13 +544,13 @@ class UserForm extends Model
 
         $uid = \Yii::$app->user->id;
         $model = User::findOne(['ID'=>$uid]);
-        $model->NATION = $this->nation;
+//        $model->NATION = $this->nation;
         //$model->REAL_NAME = $this->realName;
         //$model->MOBILE = $this->mobile;
         //$model->ID_CARD = $this->idCard;
-        $model->OPEN_BANK = $this->openBank;
-        $model->BANK_NO = $this->bankNo;
-        $model->BANK_ADDRESS = $this->bankAddress;
+//        $model->OPEN_BANK = $this->openBank;
+//        $model->BANK_NO = $this->bankNo;
+//        $model->BANK_ADDRESS = $this->bankAddress;
         $model->EMAIL = $this->email;
         if(!$model->save()){
             $this->addErrors($model->getErrors());

+ 1 - 1
composer.json

@@ -26,7 +26,7 @@
         "yiisoft/yii2-redis": "^2.0",
         "ext-pdo": "*",
         "ext-json": "*",
-        "monolog/monolog": "^2.4",
+        "monolog/monolog": "^2.8",
         "tecnickcom/tcpdf": "^6.4",
         "ext-curl": "*",
         "smladeoye/yii2-paystack": "^1.0"

+ 49 - 0
console/controllers/ShopController.php

@@ -10,6 +10,8 @@ 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 backendApi\modules\v1\models\lists\shop\BaOrderList;
+use common\libs\export\module\BaShopExport;
 use common\libs\export\module\ShopExport;
 use Yii;
 
@@ -130,4 +132,51 @@ class ShopController extends BaseController
         unset($factory);
         return false;
     }
+
+    /**
+     * BA订单列表导出
+     * @param $taskId
+     * @return bool
+     */
+    public function actionBaOrderListExport($taskId){
+        $factory = BaShopExport::factory($taskId);
+        $factory->listModelClass = BaOrderList::class;
+        try {
+            if ($factory->generateBaOrderExcel()) {
+                Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), 'BA订单列表导出成功');
+            }
+            unset($factory);
+            return true;
+        } catch (\Exception $e) {
+            echo '订单列表导出失败。详情:' . $e->getMessage();
+            Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($factory->getUserId(), 'BA订单列表导出失败。详情:' . $e->getMessage(), false);
+        }
+
+        unset($factory);
+        return false;
+    }
+
+    /**
+     * 订单列表导出PDF
+     * @param $taskId
+     * @return bool
+     */
+    public function actionBaOrderListExportPdf($taskId)
+    {
+        $factory = BaShopExport::factory($taskId);
+        $factory->listModelClass = BaOrderList::class;
+        try {
+            if ($factory->generateBaOrderPDF()) {
+                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;
+    }
 }

+ 35 - 0
console/controllers/UserController.php

@@ -11,6 +11,7 @@ use backendApi\modules\v1\models\lists\bonus\PerfOrderList;
 use backendApi\modules\v1\models\lists\user\BindList;
 use backendApi\modules\v1\models\lists\user\GroupList;
 use backendApi\modules\v1\models\lists\user\IndexList;
+use backendApi\modules\v1\models\lists\user\BaUserList;
 use backendApi\modules\v1\models\lists\user\MoveList;
 use backendApi\modules\v1\models\lists\user\StatusAuditList;
 use backendApi\modules\v1\models\lists\user\SystemList;
@@ -18,6 +19,7 @@ use backendApi\modules\v1\models\lists\user\TeamworkList;
 use backendApi\modules\v1\models\lists\user\YearHighestEmpLvList;
 use common\helpers\Cache;
 use common\libs\export\BaseExport;
+use common\libs\export\module\BaUserExport;
 use common\libs\export\module\BonusExport;
 use common\libs\export\module\UserExport;
 use common\models\forms\NetMoveForm;
@@ -181,4 +183,37 @@ class UserController extends BaseController
         unset($factory, $taskId, $className, $listName);
         return false;
     }
+
+    /**
+     * BA会员列表导出
+     * @param $taskId
+     * @return bool
+     */
+    public function actionBaUserListExport($taskId) {
+        return $this->_exportBA($taskId, BaUserList::class, 'Brand_Ambassador_List');
+    }
+
+    /**
+     * 导出方法
+     * @param $taskId
+     * @param $className
+     * @param $listName
+     * @return bool
+     */
+    private function _exportBA($taskId, $className, $listName){
+        $factory = BaUserExport::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;
+    }
 }

+ 8 - 0
frontendApi/config/main.php

@@ -43,6 +43,14 @@ return [
             'class' => 'frontendApi\modules\v1\components\UserAuth',
             'identityClass' => 'frontendApi\modules\v1\models\User',
             'enableAutoLogin' => false,
+            'idParam' => '__user'
+        ],
+        'brand' => [
+            'class' => 'frontendApi\modules\v1\components\BrandAuth',
+            'identityClass' => 'frontendApi\modules\v1\models\brand\User',
+            'enableAutoLogin' => false,
+            'idParam' => '__brand',
+            'identityCookie' => ['name' => '_brand_identity', 'httpOnly' => true],
         ],
         'log' => [
             'traceLevel' => YII_DEBUG ? 3 : 0,

+ 5 - 3
frontendApi/config/menu.php

@@ -27,18 +27,19 @@ return [
         'routePath'=>'shop',
         'show'=>1,
         'child'=>[
-            ['name'=>'Products list', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'index', 'routePath'=>'shop/index', 'show'=>1,],//商品列表
+            ['name'=>'Products list', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'index', 'routePath'=>'shop/index', 'show'=>1],//商品列表
             ['name'=>'Welcome Pack management', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'dec', 'routePath'=>'user/dec', 'show'=>1,'allow'=>'declarer',],
             ['name'=>'Welcome Pack Listing', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'dec-order-list', 'routePath'=>'shop/dec-order-list', 'show'=>1,],//报单列表
             ['name'=>'Upgrade management', 'class'=>'', 'icon'=>'', 'controller'=>'upgrade', 'action'=>'dec', 'routePath'=>'user/upgrade', 'show'=>1,'allow'=>'declarer',],//升级管理
 //            ['name'=>'Repeat sales products', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'reconsume', 'routePath'=>'shop/reconsume', 'show'=>1,'allow'=>'studio'],//复消商品
-
 //            ['name'=>'申请退货', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-backing-out', 'routePath'=>'shop/order-backing-out', 'show'=>1,],//申请退货
             ['name'=>'Order List', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-list', 'routePath'=>'shop/order-list', 'show'=>1,],//订单列表
+            ['name'=>'Brand Ambassador', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'ba-dec', 'routePath'=>'user/ba-dec', 'show'=>1,'allow'=>'declarer',],
+            ['name'=>'BA Order List', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'ba-dec-order-list', 'routePath'=>'shop/ba-dec-order-list', 'show'=>1,'allow'=>'declarer',],
         ]
     ],
     'user'=>[
-        'name'=>'Member management',//会员管理
+        'name'=>'Member Management',//会员管理
         'class' => '',
         'icon'=>'el-icon-user',
         'controller'=>'user',
@@ -65,6 +66,7 @@ return [
         'child'=>[
             ['name'=>'Placement network', 'class'=>'', 'icon'=>'', 'controller'=>'atlas', 'action'=>'network', 'routePath'=>'atlas/network', 'show'=>1,],
             ['name'=>'Sponsor network', 'class'=>'', 'icon'=>'', 'controller'=>'atlas', 'action'=>'relation', 'routePath'=>'atlas/relation', 'show'=>1,],
+            ['name'=>'Brand Ambassador List', 'class'=>'', 'icon'=>'', 'controller'=>'atlas', 'action'=>'brand-ambassador-list', 'routePath'=>'atlas/brand-ambassador-list', 'show'=>1,],
         ]
     ],
     'bonus'=>[

+ 63 - 0
frontendApi/config/menuBA.php

@@ -0,0 +1,63 @@
+<?php
+
+return [
+    'dashboard'=>[
+        'name'=>'Dashboard',//控制台
+        'class' => '',
+        'icon'=>'el-icon-guide',
+        'controller'=>'dashboard',
+        'action'=>'index',
+        'routePath'=>'dashboard/ba-index',
+        'show'=>1,
+        'brandAmbassador' => 1,
+        'child'=>[]
+    ],
+    'shop'=>[
+        'name'=>'Shopping Mall',//商城管理
+        'class' => '',
+        'icon'=>'el-icon-goods',
+        'controller'=>'shop',
+        'action'=>'',
+        'routePath'=>'shop',
+        'show'=>1,
+        'child'=>[
+            ['name'=>'Products list', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'/ba-product-list', 'routePath'=>'shop/ba-product-list', 'show'=>1], // 商品列表
+            ['name'=>'Order List', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'ba-order-list', 'routePath'=>'shop/ba-order-list', 'show'=>1], // 订单列表
+        ]
+    ],
+    'user'=>[
+        'name'=>'Member Management',//会员管理
+        'class' => '',
+        'icon'=>'el-icon-user',
+        'controller'=>'user',
+        'action'=>'',
+        'routePath'=>'user',
+        'show'=>1,
+        'child'=>[
+            ['name'=>'Personal info', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'ba-info', 'routePath'=>'user/ba-info', 'show'=>1], // 个人资料
+            ['name'=>'Reset Password', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'ba-password', 'routePath'=>'user/ba-password', 'show'=>1],// 修改密码
+        ]
+    ],
+    'article'=>[
+        'name'=>'Article Management',//文章管理
+        'class' => '',
+        'icon'=>'el-icon-document',
+        'controller'=>'article',
+        'action'=>'',
+        'routePath'=>'article',
+        'show'=>1,
+        'child'=>[]
+    ],
+    'config'=>[
+        'name'=>'Setting',//设置
+        'class' => '',
+        'icon'=>'el-icon-setting',
+        'controller'=>'config',
+        'action'=>'',
+        'routePath'=>'config',
+        'show'=>1,
+        'child'=>[
+            ['name'=>'Shipping Address', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'ba-receive-address-list', 'routePath'=>'config/ba-receive-address-list', 'show'=>1, 'brandAmbassador' => 1], // 收货地址管理
+        ]
+    ],
+];

+ 24 - 0
frontendApi/config/urlManagerRules.php

@@ -19,6 +19,7 @@ return [
             'GET config' => 'config',
             'GET page-data' => 'page-data',
             'GET captcha' => 'captcha',
+            'GET ba-base-info' => 'ba-base-info',
         ],
     ],
     [
@@ -55,6 +56,7 @@ return [
             'GET my-index' => 'my-index',
             'GET period-bonus' => 'period-bonus',
             'GET bonus-num' => 'bonus-num',
+            'GET ba-index' => 'ba-index',
         ],
     ],
     [
@@ -79,6 +81,13 @@ return [
             'POST delete-approach-order' => 'delete-approach-order',
             'POST verify-approach-order' => 'verify-approach-order',
             'GET order-backing-out' => 'order-backing-out',
+            'GET ba-order-list' => 'ba-order-list',
+            'GET ba-product-list' => 'ba-product-list',
+            'GET ba-shopping-cart' => 'ba-shopping-cart',
+            'POST ba-sure-approach-order' => 'ba-sure-approach-order',
+            'POST ba-delete-approach-order' => 'ba-delete-approach-order',
+            'GET ba-dec-order-list' => 'ba-dec-order-list',
+            'GET ba-dec-order-export/<orderSn>' => 'ba-dec-order-export',
         ],
     ],
     [
@@ -101,6 +110,13 @@ return [
             'GET full-info' => 'full-info',
             'GET get-auto-place' => 'get-auto-place',
             'GET user-base-info' => 'user-base-info',
+
+            'GET ba-info' => 'ba-info',
+            'POST ba-edit' => 'ba-edit',
+            'POST ba-password' => 'ba-password',
+            'POST ba-pay-password' => 'ba-pay-password',
+            'GET,POST ba-dec' => 'ba-dec',
+            'GET ba-user-info' => 'ba-user-info',
         ],
     ],
     [
@@ -114,6 +130,7 @@ return [
             'GET relation' => 'relation',
             'GET relation-list' => 'relation-list',
             'GET get-period' => 'get-period',
+            'GET brand-ambassador-list' => 'brand-ambassador-list',
         ],
     ],
     [
@@ -174,6 +191,13 @@ return [
             'POST receive-address-edit' => 'receive-address-edit',
             'POST receive-address-default' => 'receive-address-default',
             'POST receive-address-delete' => 'receive-address-delete',
+
+            'GET ba-receive-address-list' => 'ba-receive-address-list',
+            'GET ba-receive-address-one/<id>' => 'ba-receive-address-one',
+            'POST ba-receive-address-add' => 'ba-receive-address-add',
+            'POST ba-receive-address-edit' => 'ba-receive-address-edit',
+            'POST ba-receive-address-default' => 'ba-receive-address-default',
+            'POST ba-receive-address-delete' => 'ba-receive-address-delete',
         ],
     ],
     [

+ 399 - 0
frontendApi/modules/v1/components/BrandAuth.php

@@ -0,0 +1,399 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: leo
+ * Date: 2018/2/28
+ * Time: 上午10:31
+ */
+
+namespace frontendApi\modules\v1\components;
+
+use common\components\Redis;
+use common\components\Request;
+use common\helpers\Date;
+use common\helpers\Form;
+use common\helpers\http\BackendToFrontendApi;
+use common\models\BaUserInfo;
+use common\models\Message;
+use common\models\UserToken;
+use Yii;
+use yii\db\ActiveRecordInterface;
+use yii\web\HttpException;
+use yii\web\IdentityInterface;
+use yii\web\User;
+
+class BrandAuth extends User {
+    private $_userId = null;
+    private $_apiIdentity = null;
+    private $_token = null;
+    private $_userInfo = null;
+    private $_device = null;
+    private static $_isQuicklyLogin = false;
+
+    /**
+     * 初始化设备信息
+     * @throws \yii\base\InvalidConfigException
+     */
+    public function init() {
+        parent::init();
+        $this->_device = Yii::$app->request->getDevice();
+    }
+
+    /**
+     * 首次以用户名和密码的方式登录
+     * @param IdentityInterface $identity
+     * @return bool
+     * @throws HttpException
+     */
+    public function loginWithUAndP(IdentityInterface $identity) {
+        if ($this->beforeLogin($identity, false, 0)) {
+            $id = $identity->getId();
+            $ip = Yii::$app->getRequest()->getUserIP();
+
+            $this->_userId = $identity['ID'];
+            $this->_apiIdentity = $identity;
+            $this->_userInfo = [
+                'id' => $identity['ID'],
+                'userName' => $identity['USER_NAME'],
+                'accessTokenUpdatedAt' => Date::nowTime(),
+                'ip' => $ip,
+            ];
+
+            BaUserInfo::updateAll(['LAST_LOGIN_IP' => $ip, 'LAST_LOGIN_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID'=>$identity['ID']]);
+            $userToken = UserToken::findOne(['USER_ID' => $identity['ID']]);
+            if (!$userToken) {
+                $userToken = new UserToken();
+                $userToken->USER_ID = $identity['ID'];
+                $userToken->CREATED_AT = Date::nowTime();
+                if (!$userToken->save()) {
+                    throw new HttpException(500, Form::formatErrorsForApi($userToken->getErrors()), 500);
+                }
+            }
+
+            $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access');
+            $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh');
+
+            $this->afterLogin($identity, false, 0);
+        }
+
+        return !$this->getIsGuest();
+    }
+
+    /**
+     * 登录成功之后
+     * @param IdentityInterface $identity
+     * @param bool $cookieBased
+     * @param int $duration
+     * @throws \yii\base\Exception
+     */
+    public function afterLogin($identity, $cookieBased, $duration) {
+        // 拉取站内信
+        Message::pullMsgByUser($identity['ID']);
+        parent::afterLogin($identity, $cookieBased, $duration);
+    }
+
+    /**
+     * 已AccessToken方式登录(即平时直接访问)
+     * @param string $token
+     * @param null $type
+     * @return null|IdentityInterface
+     */
+    public function loginByAccessToken($token, $type = null) {
+        /* @var $class IdentityInterface */
+        $class = $this->identityClass;
+        $userId = $this->_userId = $class::findIdentityByAccessToken($token, $type);
+        if ($userId) {
+            $this->_userInfo = [
+                'id' => $userId,
+                'userName' => Yii::$app->tokenRedis->hget($token, 'USER_NAME'),
+                'accessTokenUpdatedAt' => Yii::$app->tokenRedis->hget($token, 'TOKEN_UPDATED_AT'),
+                'ip' => Yii::$app->getRequest()->getUserIP(),
+            ];
+            return $userId;
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * 从后台登录前台
+     * @param $userId
+     * @return null
+     * @throws HttpException
+     */
+    public function loginByBackend($userId) {
+        if (BaUserInfo::find()->where(['USER_ID' => $userId])->exists()) {
+            $userToken = UserToken::findOne(['USER_ID' => $userId]);
+            if (!$userToken) {
+                $userToken = new UserToken();
+                $userToken->USER_ID = $userId;
+                $userToken->CREATED_AT = Date::nowTime();
+                if (!$userToken->save()) {
+                    return null;
+                }
+            }
+            self::$_isQuicklyLogin = true;
+            $accessTokenResult = $this->updateToken($userToken, $appType = 'pc', $typeToken = 'access', $userId);
+            $refreshTokenResult = $this->updateToken($userToken, $appType = 'pc', $typeToken = 'refresh', $userId);
+            if ($accessTokenResult && $refreshTokenResult) {
+                return $this->getToken();
+            } else {
+                return null;
+            }
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * 用refreshToken生成新的accessToken和refreshToken
+     * @param $refreshToken
+     * @return bool
+     * @throws HttpException
+     */
+    public function refreshToken($refreshToken) {
+        if (!$refreshToken) {
+            return false;
+        }
+        $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
+        if (!$userId) {
+            return false;
+        }
+        $userToken = UserToken::findOne(['USER_ID' => $userId]);
+        $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access', $userId);
+        $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh', $userId);
+        return true;
+    }
+
+    /**
+     * 用refreshToken生成新的accessToken
+     * @param $refreshToken
+     * @return bool
+     * @throws HttpException
+     */
+    public function refreshAccessToken($refreshToken) {
+        if (!$refreshToken) {
+            return false;
+        }
+        $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
+        if (!$userId) {
+            return false;
+        }
+        $userToken = UserToken::findOne(['USER_ID' => $userId]);
+        return $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access', $userId);
+    }
+
+    /**
+     * 用refreshToken生成新的refreshToken
+     * @param $refreshToken
+     * @return bool
+     * @throws HttpException
+     */
+    public function refreshRefreshToken($refreshToken) {
+        if (!$refreshToken) {
+            return false;
+        }
+        $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
+        if (!$userId) {
+            return false;
+        }
+        $userToken = UserToken::findOne(['USER_ID' => $userId]);
+        return $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh', $userId);
+    }
+
+    /**
+     * 更新token 的具体方法
+     * @param ActiveRecordInterface $userTokenModel
+     * @param string $appType (pc|app)
+     * @param string $typeToken
+     * @param $userId
+     * @return bool
+     * @throws HttpException
+     */
+    public function updateToken(ActiveRecordInterface $userTokenModel, $appType = Request::DEVICE_PC, $typeToken = 'access', $userId = 0) {
+        $tokenField = strtoupper($appType . '_' . $typeToken . '_TOKEN');
+        $updateField = '';
+        $expiresIn = 0;
+        if ($appType === Request::DEVICE_PC) {
+            if ($typeToken === 'access') {
+                $updateField = 'PAT_UPDATED_AT';
+                $expiresIn = Yii::$app->params['frontAccessTokenExpiresIn'];
+            } elseif ($typeToken === 'refresh') {
+                $updateField = 'PRT_UPDATED_AT';
+                $expiresIn = Yii::$app->params['frontRefreshTokenExpiresIn'];
+            } else {
+                throw new HttpException(500, 'token字段错误', 500);
+            }
+        } elseif ($appType === Request::DEVICE_APP) {
+            if ($typeToken === 'access') {
+                $updateField = 'AAT_UPDATED_AT';
+                $expiresIn = Yii::$app->params['frontAccessTokenExpiresIn'];
+            } elseif ($typeToken === 'refresh') {
+                $updateField = 'ART_UPDATED_AT';
+                $expiresIn = Yii::$app->params['frontRefreshTokenExpiresIn'];
+            } else {
+                throw new HttpException(500, 'token字段错误', 500);
+            }
+        }
+        // 老token
+        $oldToken = $userTokenModel->$tokenField;
+        // 生成 access_token
+        /* @var $identityClass IdentityInterface */
+        $identityClass = $this->identityClass;
+        $generateTokenMethodName = 'generate' . ucfirst($typeToken) . 'Token';
+        //$token = $identityClass::generateAccessToken();
+        $token = call_user_func([$identityClass, $generateTokenMethodName], $appType);
+        $userTokenModel->$tokenField = $token;
+        $userTokenModel->$updateField = Date::nowTime();
+        if (!$userTokenModel->save()) {
+            throw new HttpException(500, 'token更新失败', 500);
+        }
+        // 查找TOKEN中是否有同一用户产生的垃圾token,有的话就清除
+        Yii::$app->tokenRedis->del($oldToken);
+
+        $identity = $this->_apiIdentity;
+        if (!$this->_apiIdentity) {
+            if (!$userId) {
+                throw new HttpException(500, 'userId不能为空', 500);
+            }
+            $identity = $identityClass::findIdentity($userId);
+        }
+        // 把 accessToken 当做key存入redis中内容为会员的ID和用户名
+        Yii::$app->tokenRedis->hset($token, 'ID', $identity['ID']);
+        Yii::$app->tokenRedis->hset($token, 'USER_NAME', $identity['USER_NAME']);
+        Yii::$app->tokenRedis->hset($token, 'TOKEN_UPDATED_AT', $userTokenModel->$updateField);
+        Yii::$app->tokenRedis->expire($token, $expiresIn);
+
+        // 标记为快速登录的会员
+        if (self::$_isQuicklyLogin) {
+            Yii::$app->redis->setex(Redis::key(\frontendApi\modules\v1\models\User::CACHE_IS_QUICKLY_LOGIN . $token), Yii::$app->params['frontAccessTokenExpiresIn'], 1);
+        }
+
+        $this->_token = array_merge($this->_token ? $this->_token : [], [
+            $typeToken . 'Token' => $token,
+            $typeToken . 'TokenExpiresIn' => $expiresIn,
+            $typeToken . 'TokenUpdateAt' => $userTokenModel->$updateField,
+        ]);
+
+        return true;
+    }
+
+    /**
+     * 获取管理员ID
+     * @return int|null|string
+     */
+    public function getId() {
+        return $this->_userId;
+    }
+
+    /**
+     * 获取token
+     * @return null
+     */
+    public function getToken() {
+        return $this->_token;
+    }
+
+    /**
+     * 获取管理员信息
+     * @return null
+     */
+    public function getUserInfo() {
+        return $this->_userInfo;
+    }
+
+    /**
+     * 获取身份信息
+     * @param bool $autoRenew
+     * @return null|IdentityInterface
+     */
+    public function getIdentity($autoRenew = true) {
+        if ($this->_apiIdentity) {
+            return $this->_apiIdentity;
+        } else {
+            if ($this->_userId) {
+                /* @var $class IdentityInterface */
+                $class = $this->identityClass;
+                return $class::findOne(['ID' => $this->_userId]);
+            } else {
+                return null;
+            }
+        }
+    }
+
+    /**
+     * 获取权限
+     * @return mixed
+     */
+    public function getUserPermission() {
+        return [];
+    }
+
+    /**
+     * 校验权限
+     * @param $controller
+     * @param string $action
+     * @return bool
+     */
+    public function validateUserAction($controller, $action = '') {
+        $isRecharge = \common\models\BaUser::getEnCodeInfo($this->_userId)['IS_RECHARGE'];
+        if($controller=='finance' &&  $action=='recharge' &&  $isRecharge==0){
+            return false;
+        }
+        return true;
+//        $userInfo = $this->_userInfo;
+//        if($userInfo['roleId'] === Yii::$app->params['superAdminRoleId']){
+//            return true;
+//        }
+//        // 查看控制器是否在白名单中,如果在白名单中则直接返回true
+//        $noCheckActions = Yii::$app->params['noCheckPermissionActions'];
+//        if(in_array($controller.'/'.$action, $noCheckActions)){
+//            return true;
+//        }
+//        return true;
+    }
+
+    /**
+     * 查看是否有该控制器的权限
+     * @param $controller
+     * @return bool
+     */
+    public function validateUserController($controller) {
+        $isAtlas = \common\models\BaUser::getEnCodeInfo($this->_userId)['IS_ATLAS'];
+        if($controller=='atlas' &&  $isAtlas==0){
+            return false;
+        }
+        return true;
+//        if($userInfo['roleId'] === Yii::$app->params['superAdminRoleId']){
+//            return true;
+//        }
+//        $result = true;
+//        // 查看控制器是否在白名单中,如果在白名单中则直接返回true
+//        $noCheckActions = Yii::$app->params['noCheckPermissionActions'];
+//        foreach($noCheckActions as $action){
+//            if(preg_match('/^'.$controller.'\//', $action)){
+//                $result = true;
+//                break;
+//            }
+//        }
+//
+//        return $result;
+    }
+
+    /**
+     * 校验后台登录前台时所带的参数是否正确
+     * @return bool
+     */
+    public function validateBackendAuth() {
+        $data = [];
+        $getData = \Yii::$app->getRequest()->get();
+        $postData = \Yii::$app->getRequest()->post();
+        $route = '/' . Yii::$app->controller->module->id . '/' . Yii::$app->controller->id . '/' . Yii::$app->controller->action->id;
+        if (isset($getData[$route])) unset($getData[$route]);
+        if (!empty($getData)) $data = array_merge($data, $getData);
+        if (!empty($postData)) $data = array_merge($data, $postData);
+        return (isset($data['signature']) && isset($data['timestamp']) && BackendToFrontendApi::checkSignature($data['signature'], $data));
+    }
+
+
+}

+ 21 - 0
frontendApi/modules/v1/controllers/AtlasController.php

@@ -8,8 +8,11 @@
 
 namespace frontendApi\modules\v1\controllers;
 
+use backendApi\modules\v1\models\lists\shop\BaUserList;
 use common\helpers\Cache;
 use common\helpers\user\Info;
+use common\models\BaUser;
+use common\models\BaUserInfo;
 use common\models\DeclarationLevel;
 use common\models\EmployLevel;
 use common\models\Period;
@@ -214,4 +217,22 @@ class AtlasController extends BaseController {
 
         return static::notice($data);
     }
+
+    /**
+     * 会员推荐的BA会员
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBrandAmbassadorList()
+    {
+        $data = BaUserInfo::find()->alias('I')
+            ->select('I.USER_ID, I.USER_NAME, U.REAL_NAME, U.PERIOD_AT, U.WHETHER_UPGRADE, U.BA_UPGRADE_AT')
+            ->where('I.REC_UID = :REC_UID', ['REC_UID' => \Yii::$app->user->id])
+            ->join('INNER JOIN', BaUser::tableName() . ' AS U', 'I.USER_ID = U.ID')
+            ->orderBy('I.CREATED_AT DESC')
+            ->asArray()
+            ->all();
+
+        return static::notice($data);
+    }
 }

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio