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

Merge branch 'feature/1962-memberBrandAmbassador' into dev

kevin_zhangl пре 3 година
родитељ
комит
55f3f21c53
82 измењених фајлова са 12216 додато и 3229 уклоњено
  1. 4 1
      backendApi/config/menu.php
  2. 10 0
      backendApi/config/urlManagerRules.php
  3. 105 31
      backendApi/modules/v1/controllers/ShopController.php
  4. 234 91
      backendApi/modules/v1/controllers/UserController.php
  5. 23 0
      backendApi/modules/v1/models/exportForms/BaShopExportForm.php
  6. 24 0
      backendApi/modules/v1/models/exportForms/BaUserExportForm.php
  7. 362 0
      backendApi/modules/v1/models/lists/shop/BaOrderList.php
  8. 191 0
      backendApi/modules/v1/models/lists/shop/BaUserList.php
  9. 171 0
      backendApi/modules/v1/models/lists/user/BaUserList.php
  10. 24 0
      backendEle/src/router/index.js
  11. 1 1
      backendEle/src/utils/config_trial.js
  12. 13 1
      backendEle/src/utils/index.js
  13. 207 0
      backendEle/src/views/shop/ba-dec-order-list.vue
  14. 144 0
      backendEle/src/views/shop/ba-order-list.vue
  15. 345 0
      backendEle/src/views/user/ba-user-list.vue
  16. 84 0
      common/helpers/user/Info.php
  17. 388 9
      common/libs/export/BaseExport.php
  18. 10 0
      common/libs/export/module/BaShopExport.php
  19. 10 0
      common/libs/export/module/BaUserExport.php
  20. 1 1
      common/models/ApproachDecOrder.php
  21. 97 0
      common/models/BaApproachDecOrder.php
  22. 131 0
      common/models/BaApproachOrder.php
  23. 77 0
      common/models/BaApproachOrderGoods.php
  24. 92 0
      common/models/BaDecOrder.php
  25. 157 0
      common/models/BaOrder.php
  26. 77 0
      common/models/BaOrderGoods.php
  27. 79 0
      common/models/BaReceiveAddress.php
  28. 487 0
      common/models/BaUser.php
  29. 251 0
      common/models/BaUserInfo.php
  30. 17 16
      common/models/forms/ApproachDeclarationForm.php
  31. 1 0
      common/models/forms/ApproachDeclarationLoopForm.php
  32. 561 0
      common/models/forms/BaApproachDeclarationForm.php
  33. 216 0
      common/models/forms/BaApproachDeclarationLoopForm.php
  34. 500 0
      common/models/forms/BaApproachOrderForm.php
  35. 546 0
      common/models/forms/BaDeclarationForm.php
  36. 191 0
      common/models/forms/BaDeclarationLoopForm.php
  37. 201 0
      common/models/forms/BaReceiveAddressForm.php
  38. 224 0
      common/models/forms/BaUserBasicForm.php
  39. 234 0
      common/models/forms/BaUserForm.php
  40. 20 15
      common/models/forms/DeclarationForm.php
  41. 1 0
      common/models/forms/DeclarationLoopForm.php
  42. 7 7
      common/models/forms/ReceiveAddressForm.php
  43. 1 1
      composer.json
  44. 49 0
      console/controllers/ShopController.php
  45. 35 0
      console/controllers/UserController.php
  46. 8 0
      frontendApi/config/main.php
  47. 6 3
      frontendApi/config/menu.php
  48. 63 0
      frontendApi/config/menuBA.php
  49. 23 0
      frontendApi/config/urlManagerRules.php
  50. 399 0
      frontendApi/modules/v1/components/BrandAuth.php
  51. 577 0
      frontendApi/modules/v1/controllers/BaController.php
  52. 58 19
      frontendApi/modules/v1/controllers/BaseController.php
  53. 101 4
      frontendApi/modules/v1/controllers/ConfigController.php
  54. 63 0
      frontendApi/modules/v1/controllers/DashboardController.php
  55. 15 4
      frontendApi/modules/v1/controllers/OauthController.php
  56. 489 20
      frontendApi/modules/v1/controllers/ShopController.php
  57. 58 0
      frontendApi/modules/v1/controllers/SiteController.php
  58. 184 10
      frontendApi/modules/v1/controllers/UserController.php
  59. 47 12
      frontendApi/modules/v1/models/LoginForm.php
  60. 229 0
      frontendApi/modules/v1/models/brand/User.php
  61. 4 1
      frontendEle/package.json
  62. 386 231
      frontendEle/src/router/index.js
  63. 5 2
      frontendEle/src/utils/baseInfo.js
  64. 1 1
      frontendEle/src/utils/config_trial.js
  65. 4 1
      frontendEle/src/utils/network.js
  66. 10 0
      frontendEle/src/utils/userInfo.js
  67. 149 0
      frontendEle/src/views/config/ba-receive-address-edit.vue
  68. 171 0
      frontendEle/src/views/config/ba-receive-address-list.vue
  69. 230 0
      frontendEle/src/views/dashboard/ba-index.vue
  70. 4 2
      frontendEle/src/views/layout/layout.vue
  71. 6 1
      frontendEle/src/views/login/index.vue
  72. 143 0
      frontendEle/src/views/shop/ba-dec-order-list.vue
  73. 134 0
      frontendEle/src/views/shop/ba-order-list.vue
  74. 203 0
      frontendEle/src/views/shop/ba-product-list.vue
  75. 438 0
      frontendEle/src/views/shop/ba-shopping-cart.vue
  76. 705 0
      frontendEle/src/views/user/ba-dec.vue
  77. 100 0
      frontendEle/src/views/user/ba-info.vue
  78. 106 0
      frontendEle/src/views/user/ba-password.vue
  79. 39 3
      frontendEle/src/views/user/dec.vue
  80. 0 2715
      sql/StoredProcedure-NG.sql
  81. 429 0
      sql/upgrade/1962.sql
  82. 26 26
      sql/upgrade/1988.sql

+ 4 - 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,],

+ 10 - 0
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',
         ],
     ],
     [

+ 105 - 31
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()
     {
@@ -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.'); // 导出开始,请到文件管理-导出文件查看
+    }
 }

+ 234 - 91
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()
     {
@@ -157,7 +162,7 @@ class UserController extends BaseController
      * 导出会员列表
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIndexExport()
     {
@@ -214,7 +219,7 @@ class UserController extends BaseController
      * 空单会员列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionEmptyList()
     {
@@ -276,7 +281,7 @@ class UserController extends BaseController
      * 点位绑定
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBind()
     {
@@ -301,7 +306,7 @@ class UserController extends BaseController
      * 点位绑定导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBindExport()
     {
@@ -326,7 +331,7 @@ class UserController extends BaseController
     /**
      * 添加点位绑定
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBindAdd()
     {
@@ -341,7 +346,7 @@ class UserController extends BaseController
      * 编辑点位绑定
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBindEdit()
     {
@@ -365,7 +370,7 @@ class UserController extends BaseController
      * 删除点位绑定
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBindDelete()
     {
@@ -382,7 +387,7 @@ class UserController extends BaseController
      * 生成点位合作的用户名
      * @return mixed
      * @throws \yii\base\InvalidConfigException
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGenerateUserName()
     {
@@ -397,7 +402,7 @@ class UserController extends BaseController
      * 点位合作
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamwork()
     {
@@ -425,7 +430,7 @@ class UserController extends BaseController
      * 点位合作导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamworkExport()
     {
@@ -453,7 +458,7 @@ class UserController extends BaseController
     /**
      * 添加点位合作
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamworkAdd()
     {
@@ -473,7 +478,7 @@ class UserController extends BaseController
      * 编辑点位合作
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamworkEdit()
     {
@@ -504,7 +509,7 @@ class UserController extends BaseController
      * 删除方法
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionTeamworkDelete()
     {
@@ -520,7 +525,7 @@ class UserController extends BaseController
      * 会员体系
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystem()
     {
@@ -547,7 +552,7 @@ class UserController extends BaseController
      * 体系管理导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystemExport()
     {
@@ -577,7 +582,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 +603,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 +622,7 @@ class UserController extends BaseController
     /**
      * 恢复体系
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystemRenew()
     {
@@ -632,7 +637,7 @@ class UserController extends BaseController
      * 删除方法
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionSystemDelete()
     {
@@ -649,7 +654,7 @@ class UserController extends BaseController
      * 团队领导人列表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGroup()
     {
@@ -668,7 +673,7 @@ class UserController extends BaseController
      * 团队领导人列表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGroupExport()
     {
@@ -688,7 +693,7 @@ class UserController extends BaseController
      * 会员移网记录
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMove()
     {
@@ -723,7 +728,7 @@ class UserController extends BaseController
      * 移网管理导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveExport()
     {
@@ -757,7 +762,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 +777,7 @@ class UserController extends BaseController
     /**
      * 获取全部移网类型
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveNetType()
     {
@@ -783,7 +788,7 @@ class UserController extends BaseController
      * 获取移网数据
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveGet()
     {
@@ -801,7 +806,7 @@ class UserController extends BaseController
      * 修改移网数据
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveEdit()
     {
@@ -819,7 +824,7 @@ class UserController extends BaseController
      * 审核通过移网数据(实际的移网动作在这里,异步操作)
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMovePass()
     {
@@ -839,7 +844,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 +861,7 @@ class UserController extends BaseController
      * 删除移网数据
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMoveDelete()
     {
@@ -872,7 +877,7 @@ class UserController extends BaseController
     /**
      * 会员的基础用户信息
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFullInfo()
     {
@@ -897,7 +902,7 @@ class UserController extends BaseController
     /**
      * 会员的基本信息编号名称
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBaseInfo()
     {
@@ -909,7 +914,7 @@ class UserController extends BaseController
     /**
      * 点位合作主点位分成比例
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionMainDivide()
     {
@@ -924,7 +929,7 @@ class UserController extends BaseController
     /**
      * 获取子公司
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGetSubCom()
     {
@@ -936,7 +941,7 @@ class UserController extends BaseController
     /**
      * 判断是否在同一推荐网络
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChkRelation()
     {
@@ -956,7 +961,7 @@ class UserController extends BaseController
     /**
      * 获取当前期数
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGetPeriodNum()
     {
@@ -976,7 +981,7 @@ class UserController extends BaseController
     /**
      * 关停列表
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
 //    public function actionClose()
 //    {
@@ -1009,7 +1014,7 @@ class UserController extends BaseController
     /**
      * 申请关停或停发
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
 //    public function actionCloseAdd()
 //    {
@@ -1040,7 +1045,7 @@ class UserController extends BaseController
      * 审核关停或停发
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
 //    public function actionCloseAudit()
 //    {
@@ -1066,7 +1071,7 @@ class UserController extends BaseController
     /**
      * 添加会员
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionUserAdd()
     {
@@ -1090,7 +1095,7 @@ class UserController extends BaseController
     /**
      * 分页导入excel文件到待导入数据的表中
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportUsersToExcelTable()
     {
@@ -1132,7 +1137,7 @@ class UserController extends BaseController
     /**
      * 个人资料获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionProfileGet() {
         $id = Yii::$app->request->get('id');
@@ -1181,7 +1186,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 +1201,7 @@ class UserController extends BaseController
     /**
      * 分页把待导入表中的数据导入到真正的数据中
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportUsersAdd()
     {
@@ -1226,7 +1231,7 @@ class UserController extends BaseController
     /**
      * 判断是否满足删除条件
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChkDelUser()
     {
@@ -1276,7 +1281,7 @@ class UserController extends BaseController
      * 删除空单会员
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionUserDel()
     {
@@ -1294,7 +1299,7 @@ class UserController extends BaseController
     /**
      * 复销列表
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionReConsumeList()
     {
@@ -1329,7 +1334,7 @@ class UserController extends BaseController
      *      'CREATED_AT' => '>=,2018-11-10,date'
      * ]
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionFilterUser()
     {
@@ -1405,7 +1410,7 @@ class UserController extends BaseController
      * 会员级别变动记录
      * @return mixed
      * @throws \yii\base\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionDecLevelList()
     {
@@ -1424,7 +1429,7 @@ class UserController extends BaseController
     /**
      * 调整会员级别报单级别
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChangeUserDecLevel()
     {
@@ -1441,7 +1446,7 @@ class UserController extends BaseController
     /**
      * 调整会员级别报单级别
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChangeUserDecRole()
     {
@@ -1458,7 +1463,7 @@ class UserController extends BaseController
     /**
      * 修改会员前台显示聘级
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChangeShowEmpLevel()
     {
@@ -1476,7 +1481,7 @@ class UserController extends BaseController
      * 注册信息管理
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfo()
     {
@@ -1502,7 +1507,7 @@ class UserController extends BaseController
     /**
      * 注册信息管理中提交修改注册信息
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoEdit()
     {
@@ -1520,7 +1525,7 @@ class UserController extends BaseController
      * 会员注册信息审核
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAudit()
     {
@@ -1552,7 +1557,7 @@ class UserController extends BaseController
     /**
      * 会员注册信息添加
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditAdd()
     {
@@ -1567,7 +1572,7 @@ class UserController extends BaseController
     /**
      * 会员注册信息添加获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditAddOpt()
     {
@@ -1579,7 +1584,7 @@ class UserController extends BaseController
      * 会员注册信息获取
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditGet()
     {
@@ -1601,7 +1606,7 @@ class UserController extends BaseController
      * 会员注册信息修改
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditEdit()
     {
@@ -1619,7 +1624,7 @@ class UserController extends BaseController
      * 会员注册信息审核
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditAudit()
     {
@@ -1636,7 +1641,7 @@ class UserController extends BaseController
     /**
      * 分页导入excel文件到待导入数据的表中
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportRegInfoToExcelTable()
     {
@@ -1669,7 +1674,7 @@ class UserController extends BaseController
      * 分页把待导入表中的数据导入到真正的数据中
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionImportRegInfo()
     {
@@ -1695,7 +1700,7 @@ class UserController extends BaseController
      * 会员注册信息删除
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRegInfoAuditDelete()
     {
@@ -1709,7 +1714,7 @@ class UserController extends BaseController
     /**
      * 禁止登录
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseLogin()
     {
@@ -1727,7 +1732,7 @@ class UserController extends BaseController
     /**
      * 禁止登陆类型获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseLoginGet()
     {
@@ -1737,7 +1742,7 @@ class UserController extends BaseController
     /**
      * 关闭地区登录
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseAreaLogin()
     {
@@ -1758,7 +1763,7 @@ class UserController extends BaseController
     /**
      * 批量登录管理
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBatchCloseLogin()
     {
@@ -1782,7 +1787,7 @@ class UserController extends BaseController
     /**
      * 关闭报单信息获取
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseDecGet()
     {
@@ -1792,7 +1797,7 @@ class UserController extends BaseController
     /**
      * 关闭报单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseDec()
     {
@@ -1809,7 +1814,7 @@ class UserController extends BaseController
     /**
      * 批量关闭报单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionBatchCloseDec()
     {
@@ -1832,7 +1837,7 @@ class UserController extends BaseController
     /**
      * 按地区关闭报单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCloseAreaDec()
     {
@@ -1853,7 +1858,7 @@ class UserController extends BaseController
      * 会员状态管理
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
 //    public function actionStatusAuditList()
 //    {
@@ -1885,7 +1890,7 @@ class UserController extends BaseController
      * 会员状态管理导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditExport()
     {
@@ -1917,7 +1922,7 @@ class UserController extends BaseController
     /**
      * 申请修改会员状态
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditAdd()
     {
@@ -1933,7 +1938,7 @@ class UserController extends BaseController
     /**
      * 获取全部移网类型
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditGetStatuses()
     {
@@ -1945,7 +1950,7 @@ class UserController extends BaseController
      * 获取会员状态数据
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditGet()
     {
@@ -1973,7 +1978,7 @@ class UserController extends BaseController
      * @return mixed
      * @throws Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAudit()
     {
@@ -1991,7 +1996,7 @@ class UserController extends BaseController
      * 删除审核修改会员状态
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionStatusAuditDelete()
     {
@@ -2009,7 +2014,7 @@ class UserController extends BaseController
     /**
      * 设置是否运作
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsOperating()
     {
@@ -2030,7 +2035,7 @@ class UserController extends BaseController
     /**
      * 团队领导人
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsGroup()
     {
@@ -2051,7 +2056,7 @@ class UserController extends BaseController
     /**
      * 报单中心
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsDec()
     {
@@ -2063,7 +2068,7 @@ class UserController extends BaseController
     /**
      * 工作室
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsStudio()
     {
@@ -2075,7 +2080,7 @@ class UserController extends BaseController
     /**
      * 网络图谱
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsAtlas()
     {
@@ -2087,7 +2092,7 @@ class UserController extends BaseController
     /**
      * 会员充值管理显隐设置
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIsRecharge()
     {
@@ -2099,7 +2104,7 @@ class UserController extends BaseController
     /**
      * 获取企业银行信息
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionCompanyBankGet()
     {
@@ -2120,7 +2125,7 @@ class UserController extends BaseController
     /**
      * 调整会员转账/提现比例
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionChangeTransferProp()
     {
@@ -2149,7 +2154,7 @@ class UserController extends BaseController
      * @return mixed
      * @throws Exception
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionClearWallet()
     {
@@ -2172,7 +2177,7 @@ class UserController extends BaseController
      * 会员历史年度最高聘级表
      * @return mixed
      * @throws Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionYearHighestEmpLv()
     {
@@ -2193,7 +2198,7 @@ class UserController extends BaseController
      * 会员历史年度最高聘级表导出
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionYearHighestEmpLvExport()
     {
@@ -2215,7 +2220,7 @@ class UserController extends BaseController
      * 会员现金充值
      * @return mixed
      * @throws \yii\db\Exception
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionRechargeToUser()
     {
@@ -2226,4 +2231,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);
+    }
+
+
+}

+ 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;
+    }
+}

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

@@ -0,0 +1,191 @@
+<?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, 
+                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'
+                    ],
+                ],
+            ];
+        }
+        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;
+    }
+}

+ 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;
+    }
+}

+ 24 - 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'),

+ 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
     }
-}
+}

+ 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>

+ 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--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<!-- 快速登录 -->
+                      </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>

+ 84 - 0
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;
     }
 
@@ -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],

+ 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,
+            ],
+        ];
+    }
+}

+ 17 - 16
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 . '的安置网上级中');

+ 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');// 报单数据格式错误
             }

+ 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 = 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;
+        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;
+    }
+}

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

@@ -0,0 +1,500 @@
+<?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\BaApproachOrder;
+use common\models\BaApproachOrderGoods;
+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('支付金额与订单金额不符'));
+        }
+
+        $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);
+
+            // 删除中间表
+            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;
+    }
+}

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

@@ -0,0 +1,546 @@
+<?php
+namespace common\models\forms;
+
+use common\components\Model;
+use common\helpers\Cache;
+use common\helpers\Date;
+use common\helpers\Form;
+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;
+    }
+}

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

@@ -62,6 +62,7 @@ class DeclarationForm extends Model
     public $county;
     public $cityName;
     public $lgaName;
+    public $decType;
 
     // 传过来的全部数据
     public $allData;
@@ -189,21 +190,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 +324,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');// 报单数据格式错误
             }

+ 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
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,

+ 6 - 3
frontendApi/config/menu.php

@@ -26,19 +26,22 @@ return [
         'action'=>'',
         'routePath'=>'shop',
         'show'=>1,
+        'brandAmbassador' => 1,
+        'isTop' => 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'=>'Welcome Brand Ambassador', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'ba-dec', 'routePath'=>'user/ba-dec', 'show'=>1,'allow'=>'declarer',],
+            ['name'=>'Welcome BA 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',

+ 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], // 收货地址管理
+        ]
+    ],
+];

+ 23 - 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',
         ],
     ],
     [
@@ -174,6 +190,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));
+    }
+
+
+}

+ 577 - 0
frontendApi/modules/v1/controllers/BaController.php

@@ -0,0 +1,577 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: leo
+ * Date: 2018/2/24
+ * Time: 下午12:48
+ */
+
+namespace frontendApi\modules\v1\controllers;
+
+use common\helpers\Cache;
+use common\helpers\Form;
+use common\helpers\Tool;
+use common\helpers\user\Info;
+use common\models\Config;
+use common\models\DeclarationLevel;
+use common\models\DeclarationPackage;
+use common\models\DecOrder;
+use common\models\forms\ApproachDeclarationLoopForm;
+use common\models\forms\ApproachDeclarationUpgradeForm;
+use common\models\forms\DeclarationForm;
+use common\models\forms\DeclarationLoopForm;
+use common\models\forms\UploadForm;
+use common\models\forms\UserBindForm;
+use common\models\forms\UserForm;
+use common\models\OpenBank;
+use common\models\ReceiveAddress;
+use common\models\Region;
+use common\models\ShopGoods;
+use common\models\UpgradeType;
+use common\models\User;
+use common\models\UserBind;
+use common\models\UserInfo;
+use common\models\UserNetwork;
+use common\models\forms\DeclarationUpgradeForm;
+use yii\db\Exception;
+use yii\web\UploadedFile;
+
+class BaController extends BaseController {
+    public $modelClass = BaUserInfo::class;
+
+    /**
+     * 会员资料
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionIndex() {
+        $allNation = \Yii::$app->params['nation'];
+        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
+        $data['allNation'] = $allNation;
+        $data['allOpenBank'] = $allOpenBank;
+        $data['userInfo'] = User::getEnCodeInfo(\Yii::$app->user->id);
+        $data['userInfo']['NATION'] = $data['userInfo']['NATION_ID'];
+        return static::notice($data);
+    }
+
+    /**
+     * 编辑会员资料
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionEdit() {
+        if(\Yii::$app->request->isPost){
+            $form = new UserForm();
+            $post = \Yii::$app->request->post();
+            $form->scenario = 'modifyProfile';
+            if($form->load($post, '') && $result = $form->modifyProfile()){
+                return static::notice('Personal data modified successfully');//个人资料修改成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+            }
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+
+    /**
+     * 修改登录密码
+     */
+    public function actionPassword(){
+        if(\Yii::$app->request->isPost){
+            $form = new UserForm();
+            $form->scenario = 'modifyPassword';
+            $post = \Yii::$app->request->post();
+            if($form->load($post, '') && $result = $form->modifyPassword()){
+                return static::notice('Password modified successfully');//密码修改成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+            }
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+
+    /**
+     * 修改支付密码
+     */
+    public function actionPayPassword(){
+        if(\Yii::$app->request->isPost){
+            $form = new UserForm();
+            $form->scenario = 'modifyPasswordPay';
+            $post = \Yii::$app->request->post();
+            $form->userId = \Yii::$app->user->id;
+            if($form->load($post, '') && $result = $form->modifyPasswordPay()){
+                return static::notice('支付密码修改成功');
+            } else {
+                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+            }
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+
+    /**
+     * 直推会员列表
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionRecUser() {
+        $allData = UserInfo::lists('AND REC_UID=:REC_UID', [':REC_UID' => \Yii::$app->user->id], ['useSlaves' => true, 'select'=>'USER_ID,CREATED_AT']);
+        foreach ($allData['list'] as $key => $data) {
+            $userBaseInfo = User::getEnCodeInfo($data['USER_ID']);
+            $userBaseInfo['NATION'] = \Yii::$app->params['nation'][$userBaseInfo['NATION']]['name'] ?? '';
+            $allData['list'][$key]['BASE_INFO'] = $userBaseInfo;
+        }
+        return static::notice($allData);
+    }
+
+    /**
+     * 上传身份证
+     * @return mixed
+     * @throws \yii\base\Exception
+     * @throws \yii\web\HttpException
+     */
+    public function actionIdCard() {
+        if (\Yii::$app->request->isPost) {
+            $formModel = new UploadForm();
+            $formModel->scenario = 'idCardFront';
+            $formModel->file = UploadedFile::getInstanceByName('file');
+            //$formModel->token = \Yii::$app->request->post('uploadToken');
+            $formModel->token = \Yii::$app->request->request('uploadToken');
+            if ($formModel->file && $formModel->upload()) {
+                return static::notice('Successful');
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
+            }
+        }
+        // 查看该用户是否已经上传过身份证
+        $oneData = User::find()->select('ID_IMAGE')->where('ID=:ID', [':ID' => \Yii::$app->user->id])->asArray()->one();
+        if ($oneData['ID_IMAGE']) {
+            return static::notice($oneData);
+        } else {
+            $token = Cache::setUploadToken();
+            return static::notice($token);
+        }
+    }
+
+    /**
+     * 点位绑定
+     * @return mixed
+     * @throws \yii\base\Exception
+     * @throws \yii\web\HttpException
+     */
+    public function actionBind() {
+        $userBind = UserBind::findOneAsArray('USER_ID=:USER_ID AND IS_DEL=0', [':USER_ID' => \Yii::$app->user->id]);
+        $allData['list']=UserBind::findAllAsArray('MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userBind['MAIN_UID']], 'ID,USER_ID,MAIN_UID,CREATED_AT,UPDATED_AT');
+        foreach ($allData['list'] as $key => $value) {
+            $baseInfo = Info::baseInfoZh($value['USER_ID']);
+            if ($baseInfo['STATUS'] != 1) {
+                unset($allData['list'][$key]);
+                continue;
+            }
+            $allData['list'][$key]['USER_NAME'] = $baseInfo['USER_NAME'];
+            $allData['list'][$key]['REAL_NAME'] = $baseInfo['REAL_NAME'];
+            $allData['list'][$key]['BANK_PROVINCE_NAME'] = $baseInfo['BANK_PROVINCE_NAME'];
+            $allData['list'][$key]['BANK_CITY_NAME'] = $baseInfo['BANK_CITY_NAME'];
+            $allData['list'][$key]['BANK_COUNTY_NAME'] = $baseInfo['BANK_COUNTY_NAME'];
+            $allData['list'][$key]['OPEN_BANK_NAME'] = $baseInfo['OPEN_BANK_NAME'];
+            $allData['list'][$key]['BANK_NO'] = $baseInfo['BANK_NO'];
+            $allData['list'][$key]['MAIN_USER_NAME'] =Info::getUserNameByUserId($value['MAIN_UID']);
+        }
+        $allData['list'] = array_values($allData['list']);
+        return static::notice($allData);
+    }
+
+    /**
+     * 编辑点位绑定
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBindEdit(){
+        $id = \Yii::$app->request->get('id');
+        if(\Yii::$app->request->isPost) {
+            return parent::edit(UserBindForm::class, '修改主点位成功', 'frontEdit', ['frontEdit'], null, function($form, $result){
+                //log
+            });
+        }
+        // 获得当前会员的用户名等信息
+        $userBind = UserBind::findOneAsArray('ID=:ID AND IS_DEL=0', [':ID' => $id]);
+        $userBinds = UserBind::findAllAsArray('MAIN_UID=:MAIN_UID AND IS_DEL=0',[':MAIN_UID'=>$userBind['MAIN_UID']], 'ID,USER_ID,MAIN_UID,CREATED_AT,UPDATED_AT');
+        foreach($userBinds as $key=>$value){
+            $status = Info::getStatusByUserId($value['USER_ID']);
+            if ($status != 1) {
+                unset($userBinds[$key]);
+                continue;
+            }
+            $userBinds[$key]['USER_NAME'] = Info::getUserNameByUserId($value['USER_ID']);
+
+        }
+        $userBinds = array_values($userBinds);
+        return static::notice(['userBinds' => $userBinds,'mainUid'=>$userBind['MAIN_UID']]);
+    }
+
+    // 会员升级,通过会员的编号,获取会员信息
+    public function actionUpgradeInfo() {
+        $isSwitchUpgrade = Config::find()
+        ->where("CONFIG_NAME='isOpenUpgrade'")
+        ->asArray()
+        ->one();
+        $isOpen = !empty($isSwitchUpgrade) && isset($isSwitchUpgrade['VALUE']) ? $isSwitchUpgrade['VALUE'] : 0;
+        if ($isOpen < 1) {
+            return static::notice('The function is not available',400); // 功能暂未开放
+        }
+        $userNumber = \Yii::$app->request->request('userName');
+        $baseInfo = Info::baseInfoZhByUserName($userNumber);
+        if ($baseInfo['STATUS'] != 1) {
+            return static::notice('Inactive user. Please contact customer service.',400);// 非激活用户,请联系客服
+        }
+        // 1. 如果是最高级别,则只显示用户基本信息
+        // 2. 如果不是最高级别,如果用户累计报单数据是0, 或者用户累计报单业绩不符合级别信息,则提示 请联系客服核对业绩
+        $userId = $baseInfo['ID'];
+        $userDecId = $baseInfo['DEC_LV'];// 用户当前的级别
+        // 获取系统中的DEC 报单级别配置
+        $decConfig = Cache::getDecLevelConfig();
+        $userDecInfo = $decConfig[$userDecId]; // 会员的级别具体信息
+        $maxPerfInfo = DeclarationLevel::getMaxDecPref(); 
+        $maxDecId = $maxPerfInfo['ID']; // 级别配置中最高级别ID
+        $observe = Config::getConfigByType('observe'); // 获取观察期配置信息
+        $observeLimit = $observe['observePeriodLimit']['value']; // 月份限制
+        $isObserve = User::checkIsObserve($baseInfo['CREATED_AT'], $observeLimit); // 判断用户是否再观察期中
+        // 如果用户已经是最高级别,则只展示用户信息
+        $isMax = false;
+        if ($maxDecId == $userDecId) {
+            $isMax = true;
+        }
+        // 如果用户已经是最高级别,则只展示用户信息
+        $userInfo = [
+            'DEC_NAME' => $baseInfo['DEC_LV_NAME'], // 用户级别中文
+            'DEC_ID' => $userDecId, // 用户级别id
+            'REAL_NAME' => $baseInfo['REAL_NAME'], // 真实姓名
+            'ADD_AT' => date('Y-m-d', $baseInfo['CREATED_AT']), // 加入时间
+            'IS_OBSERVE' => $isObserve, // 是否是观察期  true为是观察期
+            'IS_MAX' => $isMax, // 是否已是最大级别 最大级别不需要判断报单总PV是多少 只展示基本信息
+        ];
+        
+        // 如果是最高级别了,则无需升级
+        if ($isMax) {
+            return static::notice(['baseInfo' => $userInfo]);
+        }
+
+        $levelPerf = $userDecInfo['PERF'];// 用户当前级别对应的业绩值
+        if (!$isMax) {
+            $userDecPvSum = User::sumDevPvByUserId($userId); // 用户所有报单PV总和
+            // // 如果总和小于级别业绩 去掉这校验直接补比如3000-980的差值
+            // if ($userDecPvSum < $levelPerf) {
+            //     return static::notice('请联系客服人员核对业绩',400);
+            // }
+            // 下一级业绩
+            $nextLevelPerf = DeclarationLevel::getNextDecPref($levelPerf)['PERF'];
+            // 如果总和超过了下一级业绩
+            if ($userDecPvSum >= $nextLevelPerf) {
+                return static::notice('Please contact customer service to check performance.',400);// 请联系客服人员核对业绩
+            }
+            $type = $isObserve ? 1 : 2;
+            $userInfo['UPGRADE_FUNC'] = $isObserve ? 'filling up of a deficit' : 'full payment';// 升级方式
+            $upgradeType = UpgradeType::getOneByType($type);
+            // 如果用户不是最大级别,则需要获取是否观察期,算出PV是否有问题,应该补多少,
+            $userInfo['UPGRADE_TYPE'] = $upgradeType;
+            $userInfo['NOW_PERF'] = $userDecPvSum;
+            $userInfo['NEXT_PERF'] =  $nextLevelPerf;
+            // 用户可选择的级别列表
+            $userInfo['LEVEL_LIST'] = DeclarationLevel::getNextAll($levelPerf);// 用户可选择的级别列表
+            // 循环列表,补充升级所需要的补差
+            foreach ($userInfo['LEVEL_LIST'] as &$v) {
+                $v['REPAIR_PV'] = $isObserve ? $v['PERF'] - $userInfo['NOW_PERF'] : $v['PERF'];
+            }   
+        }
+        
+        return static::notice(['baseInfo' => $userInfo]);
+    }
+    
+    // 会员升级管理
+    public function actionUpgrade() {
+        $isSwitchUpgrade = Config::find()
+        ->where("CONFIG_NAME='isOpenUpgrade'")
+        ->asArray()
+        ->one();
+        $isOpen = !empty($isSwitchUpgrade) && isset($isSwitchUpgrade['VALUE']) ? $isSwitchUpgrade['VALUE'] : 0;
+        if ($isOpen < 1) {
+            return static::notice('功能暂未开放',400);
+        }
+        // 开始升级
+        if (\Yii::$app->request->isPost) {
+            $post = \Yii::$app->request->post();
+            // 根据支付方式区分逻辑
+            $payMethod = \Yii::$app->request->post('payType', '');
+            if ($payMethod === 'pay_stack') {
+                $formModel = new ApproachDeclarationUpgradeForm();
+            } else {
+                unset($post['payType']);
+                $formModel = new DeclarationUpgradeForm();
+            }
+
+            $post['type'] = DeclarationForm::TYPE_ZC;
+            if ($formModel->load($post, '') && $result = $formModel->add($post)) {
+                return static::notice($result);// Upgrade declaration succeeded升级报单成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
+            }
+        }
+
+        //所有报单套餐
+        $allDecPackage = DeclarationPackage::getAllData();
+        $decLevels = Cache::getDecLevelConfig();
+        foreach ($allDecPackage as $k=>$v){
+            $levelName = $decLevels[$v['LEVEL_ID']]['LEVEL_NAME'] ?? '';
+            $allDecPackage[$k]['LEVEL_NAME'] = $levelName;
+        }
+        //所有自选商品
+        $isDecReg = Cache::getSystemConfig()['isDecReg']['VALUE'];
+        $isDec = User::getEnCodeInfo(\Yii::$app->user->id)['IS_DEC'];
+        $isStudio = User::getEnCodeInfo(\Yii::$app->user->id)['IS_STUDIO'];
+        $decUserName = User::getEnCodeInfo(\Yii::$app->user->id)['USER_NAME'];
+        $query_condition= " AND (1<>1";
+        if(!$isDecReg || ($isDecReg && $isDec==1)){
+            $query_condition = " AND (FIND_IN_SET(1,GIFT_TYPE)>0";
+        }
+        if($isStudio==1){
+            $query_condition.= " OR FIND_IN_SET(3,GIFT_TYPE)>0";
+        }
+        $query_condition.= ")";
+
+        $allGoods = ShopGoods::find()->where("STATUS=1 AND CATEGORY_TYPE=1 " . $query_condition)->orderBy('SORT ASC')->asArray()->all();
+        foreach ($allGoods as &$goods) {
+            $goods['TAX'] = Tool::calculateTax($goods['SELL_PRICE'], $goods['TAX_RATE']);
+        }
+
+        return static::notice([
+            'allDecPackage' => $allDecPackage,
+            'allGoods' => $allGoods,
+            'decUserName'=>$decUserName,
+            'payList' => ShopGoods::payTypes(),
+            'sellType' => ShopGoods::CATEGORY_TYPE,
+            'categoryType' => ShopGoods::CATEGORY_TYPE[0]['id'],
+        ]);
+    }
+
+    /**
+     * 报单管理
+     */
+    public function actionDec() {
+        // 生成随机码 , 初始化redis
+        $userName = Info::generateWebUserName('NG',9);
+        $redis = \Yii::$app->redis;
+        $post = \Yii::$app->request->post();
+
+        if (\Yii::$app->request->isPost) {
+            // 根据支付方式区分逻辑
+            $payMethod = \Yii::$app->request->post('payType', '');
+
+            if ($payMethod === 'pay_stack') {
+                $formModel = new ApproachDeclarationLoopForm();
+            } else {
+                unset($post['payType']);
+                $formModel = new DeclarationLoopForm();
+            }
+
+            $formModel->scenario = 'userDec';
+
+            $post['province'] = $post['province'] ? :1;
+            $post['city'] = $post['city'] ? :1;
+            $post['county'] = $post['county'] ? :1;
+            $post['conUserName'] = trim($post['conUserName']);
+            $post['recUserName'] = trim($post['recUserName']);
+            $post['cityName'] = trim($post['cityName']);
+            $post['lgaName'] = trim($post['lgaName']);
+
+            // 针对于会员编号的判断
+            $insertUserName = strtoupper($post['insertUserName']);
+            $getRedisUserName = $redis->get('key_' . $insertUserName);
+            if (!$getRedisUserName){
+                return static::notice('Membership number expired',400);//会员编号过期
+            }
+            if ($insertUserName != $getRedisUserName){
+                return static::notice('Member number does not conform to',400);//会员编号不符合
+            }
+
+            $post['insertUserName'] = $insertUserName;
+            $post['type'] = DeclarationForm::TYPE_ZC;
+            $allData['data'][] = $post;
+            if ($formModel->load($allData, '') && $result = $formModel->add()) {
+                return static::notice($result);//报单成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
+            }
+        }
+
+        //所有报单套餐
+        $allDecPackage = DeclarationPackage::getAllData();
+        $decLevels = Cache::getDecLevelConfig();
+        foreach ($allDecPackage as $k=>$v){
+            $levelName = $decLevels[$v['LEVEL_ID']]['LEVEL_NAME'] ?? '';
+            $allDecPackage[$k]['LEVEL_NAME'] = $levelName;
+        }
+        //所有自选商品
+        $isDecReg = Cache::getSystemConfig()['isDecReg']['VALUE'];
+        $isDec = User::getEnCodeInfo(\Yii::$app->user->id)['IS_DEC'];
+        $isStudio = User::getEnCodeInfo(\Yii::$app->user->id)['IS_STUDIO'];
+        $query_condition= " AND (1<>1";
+        if(!$isDecReg || ($isDecReg && $isDec==1)){
+            $query_condition = " AND (FIND_IN_SET(1,GIFT_TYPE)>0";
+        }
+        if($isStudio==1){
+            $query_condition.= " OR FIND_IN_SET(3,GIFT_TYPE)>0";
+        }
+        $query_condition.= ")";
+        // 只查询普通商品
+        $allGoods = ShopGoods::find()->where("STATUS=1 AND CATEGORY_TYPE=1".$query_condition)->orderBy('SORT ASC')->asArray()->all();
+
+        //$allGoods = ShopGoods::findAllAsArray('STATUS=1');
+        // 所有开户行
+        $allOpenBank = OpenBank::find()->where('STATUS=1')->orderBy('LIST_ORDER ASC')->asArray()->all();
+        if (!$userName) {
+            return static::notice('Failed to generate member number', 400);//会员编号生成失败
+        }
+        //随机码保存在redis中方便进行比对
+        $redis->setex('key_'.$userName , 3600 , $userName);
+
+        return static::notice([
+            'allDecPackage' => $allDecPackage,
+            'allGoods' => $allGoods,
+            'allOpenBank' => $allOpenBank,
+            'userName' => $userName,
+            'payList' => ShopGoods::payTypes(),
+            'sellType' => ShopGoods::CATEGORY_TYPE,
+            'categoryType' => ShopGoods::CATEGORY_TYPE[0]['id'],
+            ]);
+    }
+
+    /**
+     * 报单级别套餐
+     */
+    public function actionDecPackage() {
+        $decLv = \Yii::$app->request->get('id');
+        //所有报单级别套餐
+        $allDecPackage = DeclarationPackage::getPackageFromLevelId($decLv);
+        return static::notice(['allDecPackage' => $allDecPackage]);
+
+    }
+
+    /*
+     * 从会员名和左右,获取底部安置人
+     *
+     */
+    public function actionGetAutoPlace() {
+        $userName = \Yii::$app->request->get('userName');
+        $side = \Yii::$app->request->get('side');
+        $userId = Info::getUserIdByUserName($userName);
+//        print_r($userId);
+        $bottomPlace = UserNetwork::getBottomPlace($userId,'', $side);
+        $bottomUser = UserNetwork::find()->select('USER_ID')->where('LOCATION_TAG=:LOCATION_TAG', ['LOCATION_TAG' => $bottomPlace])->asArray()->one();
+        $bottomUser = User::findOneAsArray('ID=:ID', [':ID' => $bottomUser['USER_ID']], 'USER_NAME');
+//        print_r($bottomUser);
+        return static::notice($bottomUser);
+    }
+
+    /**
+     * 会员信息查询
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionFullInfo()
+    {
+        $userName = \Yii::$app->request->get('userName');
+        $userId = Info::getUserIdByUserName($userName);
+        $userInfo['REAL_NAME'] = '';
+        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'REAL_NAME');
+        if($user){
+            $userInfo['REAL_NAME'] = $user['REAL_NAME'];
+            $allChildUser = UserNetwork::getFirstFloorChildren($userId);
+            $isLocation = [1 => 'Left-', 2 => 'Right-'];
+            if($allChildUser) {
+                foreach ($allChildUser as $child) {
+                    if ($child['RELATIVE_LOCATION']<'3'){
+                        $isLocation[$child['RELATIVE_LOCATION']].= 'Full';
+                    }
+                }
+            }
+            $userInfo['isLocation'] = '('.implode(',',$isLocation).')';
+            return static::notice($userInfo);
+        }else{
+            return static::notice('Member number does not exist', 400);//会员编号不存在
+        }
+    }
+
+    /**
+     * 复消会员信息查询
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionUserBaseInfo()
+    {
+        $userName = \Yii::$app->request->get('userName');
+        $userId = Info::getUserIdByUserName($userName);
+        if($userId){
+            $allAddress = ReceiveAddress::findAllAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId]);
+            if($allAddress) {
+                foreach ($allAddress as $key => $row) {
+                    $allAddress[$key]['PROVINCE_NAME'] = Region::getCnName($row['PROVINCE']);
+                    $allAddress[$key]['CITY_NAME'] = Region::getCnName($row['CITY']);
+                    $allAddress[$key]['COUNTY_NAME'] = Region::getCnName($row['COUNTY']);
+                }
+            }
+
+            $userInfo = Info::baseInfoWithNet($userId);
+//            $decLevelConfig = Cache::getDecLevelConfig();
+//            $empLevelConfig = Cache::getEmpLevelConfig();
+
+            $arr = [
+                'REAL_NAME'=>$userInfo['REAL_NAME'],
+//                'DEC_LEVEL_NAME' => $decLevelConfig[$userInfo['DEC_LV']]['LEVEL_NAME'],
+//                'EMP_LEVEL_NAME'=>$empLevelConfig[$userInfo['EMP_LV']]['LEVEL_NAME'],
+//                'REC_UID'=>$userInfo['REC_USER_NAME'].'('.$userInfo['REC_REAL_NAME'].')',
+//                'CON_UID'=>$userInfo['CON_USER_NAME'].'('.$userInfo['CON_REAL_NAME'].')',
+                'allAddress'=>$allAddress
+            ];
+            return static::notice($arr);
+        }else{
+            return static::notice('Repeat sales Member No. does not exist', 400);//复消会员编号不存在
+        }
+    }
+
+    /**
+     * 会员资料
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaInfo()
+    {
+        $allNation = \Yii::$app->params['nation'];
+        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
+        $data['allNation'] = $allNation;
+        $data['allOpenBank'] = $allOpenBank;
+        $data['userInfo'] = User::getEnCodeInfo(\Yii::$app->user->id);  // TODO
+        $data['userInfo']['NATION'] = $data['userInfo']['NATION_ID'];
+        return static::notice($data);
+    }
+
+    /**
+     * 编辑会员资料
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaEdit()
+    {
+        if(\Yii::$app->request->isPost)
+        {
+            $form = new UserForm();
+            $post = \Yii::$app->request->post();
+            $form->scenario = 'modifyProfile';
+            if ($form->load($post, '') && $result = $form->modifyProfile()){
+                return static::notice('Personal data modified successfully');//个人资料修改成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+            }
+        }
+
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+}

+ 58 - 19
frontendApi/modules/v1/controllers/BaseController.php

@@ -11,6 +11,8 @@ namespace frontendApi\modules\v1\controllers;
 use common\components\ActiveRecord;
 use common\helpers\Date;
 use common\helpers\Form;
+use common\helpers\LoggerTool;
+use \frontendApi\modules\v1\models\brand\User AS Brand;
 use frontendApi\modules\v1\models\User;
 use Yii;
 use yii\db\Exception;
@@ -38,6 +40,17 @@ class BaseController extends \yii\rest\ActiveController {
         }
     }
 
+    /**
+     * @throws ForbiddenHttpException
+     */
+    protected function forbiddenQuicklyBaUser() {
+        $isQuickly = Brand::isQuicklyLogin();
+        $requestMethod = Yii::$app->request->getMethod();
+        if ($isQuickly == 1 && strtoupper($requestMethod) != 'GET') {
+            throw new ForbiddenHttpException('快速登录的会员无法进行任何操作!');
+        }
+    }
+
     /**
      * @param $action
      * @return bool
@@ -45,27 +58,53 @@ class BaseController extends \yii\rest\ActiveController {
      * @throws \yii\web\BadRequestHttpException
      */
     public function beforeAction($action) {
-        $this->forbiddenQuicklyUser();
+        if (!\Yii::$app->getUser()->isGuest) {
+            $this->forbiddenQuicklyUser();
 
-        // 增加的判断用户登录后未操作后的超时 和 快速登录的逻辑
-        $isQuickly = User::isQuicklyLogin();
-        if ($isQuickly != 1 && Yii::$app->getUser()->getUserInfo()){
-            $userId = Yii::$app->getUser()->getUserInfo()['id'];
-            $redisKey = 'user:timeOut';
+            // 增加的判断用户登录后未操作后的超时 和 快速登录的逻辑
+            $isQuickly = User::isQuicklyLogin();
+            if ($isQuickly != 1 && Yii::$app->getUser()->getUserInfo()) {
+                $userId = Yii::$app->getUser()->getUserInfo()['id'];
+                $redisKey = 'user:timeOut';
 
-            $lastTime = '';
-            if (!Yii::$app->tokenRedis->hget($redisKey, $userId)) {
-                $lastTime = time();
-            }else{
-                $lastTime = Yii::$app->tokenRedis->hget($redisKey, $userId);
+                $lastTime = '';
+                if (!Yii::$app->tokenRedis->hget($redisKey, $userId)) {
+                    $lastTime = time();
+                } else {
+                    $lastTime = Yii::$app->tokenRedis->hget($redisKey, $userId);
+                }
+
+                $currentTime = time();
+                $timeOut = Yii::$app->params['operationTimeOut'];
+                if ($currentTime - $lastTime > $timeOut) {
+                    return self::notice('Connection not operated for too long', 402);
+                } else {
+                    Yii::$app->tokenRedis->hset($redisKey, $userId, time());
+                }
             }
+        } else {
+            $this->forbiddenQuicklyBaUser();
 
-            $currentTime = time();
-            $timeOut = Yii::$app->params['operationTimeOut'];
-            if ($currentTime - $lastTime > $timeOut) {
-                return self::notice('Connection not operated for too long', 402);
-            } else {
-                Yii::$app->tokenRedis->hset($redisKey, $userId, time());
+            // 增加的判断用户登录后未操作后的超时 和 快速登录的逻辑
+            $isQuickly = Brand::isQuicklyLogin();
+            if ($isQuickly != 1 && \Yii::$app->getUser()->getId()) {
+                $userId = Yii::$app->getUser()->getId();
+                $redisKey = 'user:timeOut';
+
+                $lastTime = '';
+                if (!Yii::$app->tokenRedis->hget($redisKey, $userId)) {
+                    $lastTime = time();
+                } else {
+                    $lastTime = Yii::$app->tokenRedis->hget($redisKey, $userId);
+                }
+
+                $currentTime = time();
+                $timeOut = Yii::$app->params['operationTimeOut'];
+                if ($currentTime - $lastTime > $timeOut) {
+                    return self::notice('Connection not operated for too long', 402);
+                } else {
+                    Yii::$app->tokenRedis->hset($redisKey, $userId, time());
+                }
             }
         }
 
@@ -184,7 +223,7 @@ class BaseController extends \yii\rest\ActiveController {
             if ($isDelData) {
                 // 真实删除数据
                 if (!$modelClass::deleteAll($condition, $params)) {
-                    throw new Exception('删除失败');
+                    throw new Exception('failed to delete');//删除失败
                 }
             } else {
                 // 设置IS_DEL字段为1
@@ -192,7 +231,7 @@ class BaseController extends \yii\rest\ActiveController {
             }
             if ($afterFun) $afterFun($selected);
             $transaction->commit();
-            return self::notice('删除成功');
+            return self::notice('delete successfully');//删除成功
         } catch (Exception $e) {
             $transaction->rollBack();
             return self::notice($e->getMessage(), 500);

+ 101 - 4
frontendApi/modules/v1/controllers/ConfigController.php

@@ -10,6 +10,8 @@ namespace frontendApi\modules\v1\controllers;
 use common\helpers\Cache;
 use common\helpers\Form;
 use common\helpers\snowflake\SnowFake;
+use common\models\BaReceiveAddress;
+use common\models\forms\BaReceiveAddressForm;
 use common\models\forms\ReceiveAddressForm;
 use common\models\forms\UserConfigForm;
 use common\models\ReceiveAddress;
@@ -122,7 +124,7 @@ class ConfigController extends BaseController
         if(\Yii::$app->request->isPost) {
             return parent::edit(ReceiveAddressForm::class, 'Added Successfully', 'userAdd', ['edit']);
         }
-        return static::notice('非法访问', 400);
+        return static::notice('Illegal request', 400); // 非法请求
     }
 
     /**
@@ -134,7 +136,7 @@ class ConfigController extends BaseController
         if(\Yii::$app->request->isPost) {
             return parent::edit(ReceiveAddressForm::class, 'Modified Successfully', 'userEdit', ['edit']);
         }
-        return static::notice('非法访问', 400);
+        return static::notice('Illegal request', 400); // 非法请求
     }
 
     /**
@@ -146,7 +148,7 @@ class ConfigController extends BaseController
         if(\Yii::$app->request->isPost) {
             return parent::edit(ReceiveAddressForm::class, '添加收货地址成功', 'userIsDefault', ['edit']);
         }
-        return static::notice('非法访问', 400);
+        return static::notice('Illegal request', 400); // 非法请求
     }
 
     /**
@@ -168,7 +170,102 @@ class ConfigController extends BaseController
                 }
             } , true);
         }
-        return static::notice('非法访问', 400);
+        return static::notice('Illegal request', 400); // 非法请求
     }
 
+    /**
+     * 收货地址列表
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaReceiveAddressList() {
+        $condition = ' AND USER_ID=:USER_ID';
+        $params[':USER_ID'] = \Yii::$app->getUser()->getId();
+        $data = BaReceiveAddress::lists($condition, $params, [
+            'SELECT' => 'ID,CONSIGNEE,MOBILE,PROVINCE,LGA_NAME,CITY_NAME,ADDRESS,IS_DEFAULT',
+            'orderBy' => 'IS_DEFAULT DESC,CREATED_AT DESC',
+            'useSlaves' => true,
+        ]);
+        if($data['list']){
+            foreach($data['list'] as $key=>$row){
+                $data['list'][$key]['PROVINCE_NAME'] = Region::getCnName($row['PROVINCE']);
+            }
+        }
+        return static::notice($data);
+    }
+
+    /**
+     * 获取一条收货地址
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaReceiveAddressOne() {
+        $data = BaReceiveAddress::findOneAsArray(
+            'USER_ID=:USER_ID AND ID=:ID',
+            [':USER_ID'=>\Yii::$app->getUser()->getId(), ':ID' => \Yii::$app->request->get('id')]
+        );
+        return static::notice($data);
+    }
+
+    /**
+     * 添加收货地址
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaReceiveAddressAdd() {
+        Region::updateToCache();
+        if (\Yii::$app->request->isPost) {
+            return parent::edit(BaReceiveAddressForm::class, 'Added Successfully', 'userAdd', ['edit']);
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+
+    /**
+     * 编辑收货地址
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaReceiveAddressEdit() {
+        if(\Yii::$app->request->isPost) {
+            return parent::edit(BaReceiveAddressForm::class, 'Modified Successfully', 'userEdit', ['edit']);
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+
+    /**
+     * 设置取消默认收货地址
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaReceiveAddressDefault() {
+        if(\Yii::$app->request->isPost) {
+            return parent::edit(BaReceiveAddressForm::class, '添加收货地址成功', 'userIsDefault', ['edit']);
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+
+    /**
+     * 删除
+     * @return mixed
+     * @throws \yii\db\Exception
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaReceiveAddressDelete() {
+        if(\Yii::$app->request->isPost) {
+            return parent::delete(BaReceiveAddress::class, null, function() {
+                // 如果没有默认地址的话,就在设置一个默认地址
+                if (!BaReceiveAddress::find()->where('USER_ID=:USER_ID AND IS_DEFAULT=1', [':USER_ID' => \Yii::$app->getUser()->getId()])->exists()) {
+                    $addressNumber = BaReceiveAddress::find()->where('USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->getUser()->getId()])->count();
+                    if ($addressNumber >= 1) {
+                        $model = BaReceiveAddress::find()->where('USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->getUser()->getId()])->one();
+                        $model->IS_DEFAULT = 1;
+                        if (!$model->save()) {
+                            throw new Exception('更新默认地址失败');
+                        }
+                    }
+                }
+            } , true);
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
 }

+ 63 - 0
frontendApi/modules/v1/controllers/DashboardController.php

@@ -171,4 +171,67 @@ class DashboardController extends BaseController
         $chartData = ChartData::instance();
         return static::notice($chartData->userBonusData(\Yii::$app->user->id));
     }
+
+    /**
+     * 控制台首页
+     * @return mixed
+     * @throws \yii\base\Exception
+     * @throws \yii\db\Exception
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaIndex(){
+        $nowTime = Date::nowTime();
+        $news = ArticleCategory::find()->select('ID,CATE_NAME')->orderBy('SORT ASC')->asArray()->all();
+        $where = ' CID=:CID AND STATUS=1';
+        foreach ($news as &$value){
+            $params = [
+                ':CID'=>$value['ID'],
+            ];
+            $value['LISTS'] = Article::find()->select('ID,TITLE,CID,CREATED_AT')->where($where,$params)->orderBy('CREATED_AT DESC')->limit(6)->asArray()->all();
+        }
+
+        //期数显示
+        $period = Period::instance();
+        $periodNum = $period->getNowPeriodNum();
+        //
+        $curYM = Period::find()->select("CALC_YEAR,CALC_MONTH")->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM'=>$periodNum])->asArray()->one();
+
+        $plist = Period::find()->select("PERIOD_NUM")->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH', [':CALC_YEAR'=>$curYM['CALC_YEAR'],':CALC_MONTH'=>$curYM['CALC_MONTH']])->orderBy('PERIOD_NUM ASC')->asArray()->all();
+
+        $wkrd = '';
+        foreach ($plist as $k=>$v) {
+            if($v['PERIOD_NUM'] == $periodNum){
+                $wkrd = $k + 1;
+                break;
+            }
+        }
+        if ($wkrd == 1) {
+            $wkrd .= 'st';
+        } else {
+            $wkrd .= 'nd';
+        }
+
+        $monthArray = [
+            1 => 'Jan',
+            2 => 'Feb',
+            3 => 'Mar',
+            4 => 'Apr',
+            5 => 'May',
+            6 => 'Jun',
+            7 => 'Jul',
+            8 => 'Aug',
+            9 => 'Sep',
+            10 => 'Oct',
+            11 => 'Nov',
+            12 => 'Dec',
+        ];
+
+
+        return static::notice([
+            'nowTime' => $nowTime,
+            'slides'=> Ad::findUseSlaves()->select('ID,IMAGE,LID,TITLE,CONTENT,TYPE')->where('LID=:LID AND STATUS=1', [':LID'=>'7EFF6260A16C3CC7E053693418AC03E4'])->orderBy('SORT ASC')->asArray()->all(),
+            'news'=>$news,
+            'periodNum'=>$periodNum . ' ,' . $wkrd . ' PC of '. $monthArray[$curYM['CALC_MONTH']],
+        ]);
+    }
 }

+ 15 - 4
frontendApi/modules/v1/controllers/OauthController.php

@@ -9,6 +9,7 @@ namespace frontendApi\modules\v1\controllers;
 
 use common\helpers\Cache;
 use common\helpers\Form;
+use common\models\BaUser;
 use common\models\forms\UserForm;
 use common\models\UserInfo;
 use common\models\UserToken;
@@ -66,8 +67,18 @@ class OauthController extends BaseController
      * @throws HttpException
      */
     public function actionInfo(){
-        User::updateBaseInfoToRedis(\Yii::$app->user->id);
-        return static::notice(User::getEnCodeInfo(\Yii::$app->user->id));
+        $isGuest = Yii::$app->getUser()->isGuest;
+        if (!$isGuest) {
+            User::updateBaseInfoToRedis(\Yii::$app->user->id);
+            $result = User::getEnCodeInfo(\Yii::$app->user->id);
+        } else {
+            BaUser::updateBaseInfoToRedis(\Yii::$app->user->id);
+            $result = BaUser::getEnCodeInfo(\Yii::$app->user->id);
+        }
+
+        $result['identity'] = !$isGuest ? 'user' : 'brand';
+
+        return static::notice($result);
     }
 
     /**
@@ -106,7 +117,7 @@ class OauthController extends BaseController
             $model->scenario = 'login';
         }
         if ($model->load(Yii::$app->request->post(), '') && $model->login()) {
-            $token = Yii::$app->getUser()->getToken();
+            $token = !Yii::$app->getUser()->isGuest ? Yii::$app->getUser()->getToken() : Yii::$app->brand->getToken();
             return static::notice($token);
         } else {
             $firstError = $model->getFirstError('LoginForm');
@@ -197,7 +208,7 @@ class OauthController extends BaseController
                 return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
             }
         }
-        return static::notice('非法访问', 400);
+        return static::notice('Illegal request', 400); // 非法请求
     }
 
 }

+ 489 - 20
frontendApi/modules/v1/controllers/ShopController.php

@@ -8,7 +8,6 @@
 
 namespace frontendApi\modules\v1\controllers;
 
-use Codeception\PHPUnit\ResultPrinter\HTML;
 use common\helpers\Cache;
 use common\helpers\Date;
 use common\helpers\Form;
@@ -16,19 +15,23 @@ use common\helpers\LoggerTool;
 use common\helpers\Tool;
 use common\helpers\user\Info;
 use common\models\ApproachDecOrder;
+use common\models\BaApproachDecOrder;
 use common\models\ApproachOrder;
 use common\models\ApproachOrderGoods;
-use common\models\DealType;
+use common\models\BaApproachOrder;
+use common\models\BaApproachOrderGoods;
+use common\models\BaOrder;
+use common\models\BaOrderGoods;
+use common\models\BaReceiveAddress;
+use common\models\BaUser;
 use common\models\DecOrder;
+use common\models\BaDecOrder;
 use common\models\forms\ApproachOrderForm;
+use common\models\forms\BaApproachOrderForm;
 use common\models\forms\DeclarationForm;
 use common\models\forms\OrderForm;
 use common\models\Order;
-use common\models\OrderDec;
 use common\models\OrderGoods;
-use common\models\OrderGoodsDec;
-use common\models\OrderStandard;
-use common\models\OrderStandardGoods;
 use common\models\ReceiveAddress;
 use common\models\Region;
 use common\models\ShopGoods;
@@ -38,6 +41,7 @@ use common\models\UserWallet;
 use Yii;
 use yii\data\Pagination;
 use yii\db\Query;
+use yii\web\HttpException;
 
 
 class ShopController extends BaseController {
@@ -46,7 +50,7 @@ class ShopController extends BaseController {
     /**
      * 商品列表
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionIndex() {
         // 商品分类
@@ -78,7 +82,7 @@ class ShopController extends BaseController {
     /**
      * 获取商品详情
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGoodsDetail(){
         $id = \Yii::$app->request->get('id');
@@ -91,7 +95,7 @@ class ShopController extends BaseController {
 
     /**
      * 购物车订单展示
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionShowCart(){
         $userId = \Yii::$app->user->id;
@@ -159,7 +163,7 @@ class ShopController extends BaseController {
 
     /**
      * 订单支付成功
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionPaySuccess(){
         $orderSn = \Yii::$app->request->get('orderSn');
@@ -190,7 +194,7 @@ class ShopController extends BaseController {
 
     /**
      * PayStack支付成功的webhook.
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      * @throws \Exception
      */
     public function actionVerifyApproachOrder() {
@@ -206,10 +210,11 @@ class ShopController extends BaseController {
                 // 订单状态
                 $orderStatus = ($status == 'success') ? \Yii::$app->params['orderStatus']['paid']['value'] : \Yii::$app->params['orderStatus']['failPaid']['value'];
 
-                $customFields = $data['metadata']['custom_fields'][0] ?? [];
-                $oderSn = $customFields['value'] ?? '';
+                $customFields = $data['metadata']['custom_fields'] ?? [];
+                $oderSn = $customFields[0]['value'] ?? '';
+                $isBrandAmbassador = $customFields[1]['value'] ?? false;
 
-                $formModel = new ApproachOrderForm();
+                $formModel = !$isBrandAmbassador ? new ApproachOrderForm() : new BaApproachOrderForm();
                 $formModel->scenario = 'verifyPayStack';
                 $load = [
                     'sn' => $oderSn,
@@ -267,7 +272,7 @@ class ShopController extends BaseController {
     /**
      * 我的报单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionDecOrderList() {
         $condition = ' DO.USER_ID=:USER_ID AND DO.IS_DEL=0';
@@ -328,7 +333,7 @@ class ShopController extends BaseController {
     /**
      * 我的订单
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionOrderList() {
         $uname = Info::getUserNameByUserId(\Yii::$app->user->id);
@@ -428,7 +433,7 @@ class ShopController extends BaseController {
 
     /**
      * 帮会员复消购物车
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionReconsumeCart(){
         $userId = \Yii::$app->user->id;
@@ -467,7 +472,7 @@ class ShopController extends BaseController {
     /**
      * 商品列表tabs分类
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionGoodsActive()
     {
@@ -499,7 +504,7 @@ class ShopController extends BaseController {
     /**
      * 导出订单.
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      * @throws \Mpdf\MpdfException
      */
     public function actionOrderExport()
@@ -745,7 +750,7 @@ ORDER;
     /**
      * 导出订单.
      * @return mixed
-     * @throws \yii\web\HttpException
+     * @throws HttpException
      */
     public function actionDecOrderExport()
     {
@@ -995,4 +1000,468 @@ ORDER;
         $file_name = 'orderBackingOut.xlsx';
         return static::notice(['fileUrl' => $file_name]);
     }
+
+    /**
+     * BA商品列表
+     * @return mixed
+     * @throws HttpException
+     */
+    public function actionBaProductList() {
+        // 商品分类
+        $categoryType = \Yii::$app->request->get('categoryType', 1);
+
+        $condition = ' AND STATUS=1 AND (FIND_IN_SET(2,GIFT_TYPE)>0';
+        $isStudio = BaUser::getEnCodeInfo(\Yii::$app->user->id)['IS_STUDIO'];
+        if($isStudio==1){
+            $condition.= " OR FIND_IN_SET(4,GIFT_TYPE)>0";
+        }
+        $condition .= ") AND CATEGORY_TYPE = :CATEGORY_TYPE";
+        $params[':CATEGORY_TYPE'] = intval($categoryType);
+
+        $data = ShopGoods::lists($condition, $params, [
+            'orderBy' => 'SORT ASC,CREATED_AT DESC',
+            'from' => ShopGoods::tableName(),
+        ]);
+        foreach ($data['list'] as $key => $value) {
+            if ($value['TYPE'] == 1 || $value['TYPE'] == 2) {
+                $data['list'][$key]['DISCOUNT'] = ShopGoods::GOODS_TYPE[$value['TYPE']]['discount'];
+            } else {
+                $data['list'][$key]['DISCOUNT'] = $value['SELL_DISCOUNT']*100;
+            }
+        }
+        return static::notice($data);
+    }
+
+    /**
+     * BA购物车订单展示
+     * @throws HttpException
+     */
+    public function actionBaShoppingCart()
+    {
+        // 收货地址
+        $allAddress = BaReceiveAddress::findAllAsArray('USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->user->id]);
+        if($allAddress) {
+            foreach ($allAddress as $key => $row) {
+                $allAddress[$key]['PROVINCE_NAME'] = Region::getCnName($row['PROVINCE']);
+                $allAddress[$key]['CITY_NAME'] = Region::getCnName($row['CITY']);
+                $allAddress[$key]['COUNTY_NAME'] = Region::getCnName($row['COUNTY']);
+            }
+        }
+
+        // 运费.奈拉
+        $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
+        // 普通商品免运费阈值.奈拉
+        $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
+
+        return static::notice([
+            'freight'       => $freight,
+            'freeShipping'  => $freeShipping,
+            'allAddress'    => $allAddress,
+        ]);
+    }
+
+    /**
+     * 确认BA订单
+     * @throws HttpException|\yii\base\Exception
+     */
+    public function actionBaSureApproachOrder()
+    {
+        if (\Yii::$app->request->isPost) {
+            $formModel = new BaApproachOrderForm();
+            $formModel->scenario = 'userOrder';
+            $formModel->remark = '复销备注';
+            $post = \Yii::$app->request->post();
+            $post['type'] = DeclarationForm::TYPE_FX;
+            if ($formModel->load($post, '') && $order = $formModel->add()) {
+                return static::notice($order);
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
+            }
+        }
+    }
+
+    /**
+     * 删除BA准订单
+     * @throws HttpException
+     */
+    public function actionBaDeleteApproachOrder()
+    {
+        $orderSn = \Yii::$app->request->post('orderSn');
+        // 删除订单中间表
+        BaApproachOrder::deleteAll('SN = :SN', [':SN' => $orderSn]);
+        // 删除订单商品中间表
+        BaApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $orderSn]);
+
+        return static::notice('');
+    }
+
+    /**
+     * BA订单
+     * @return mixed
+     * @throws HttpException
+     */
+    public function actionBaOrderList()
+    {
+        $uname = Info::getBaUserNameByUserId(\Yii::$app->user->id);
+        $condition = " (USER_ID=:USER_ID OR CREATE_USER='$uname') AND O.IS_DELETE = 0";
+        $params[':USER_ID'] = \Yii::$app->user->id;
+        $orderQuery = BaOrder::find()
+            ->alias('O')
+            ->where($condition, $params)
+            ->select('O.*,U.REAL_NAME,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');
+
+        // 订单中间表只查询待支付和支付失败的订单
+        $params[':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value'];   // 待支付
+        $params[':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value'];   // 支付失败
+        $orderStandardQuery = BaApproachOrder::find()
+            ->alias('O')
+            ->where($condition . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $params)
+            ->select('O.*,U.REAL_NAME,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();
+
+        $data = [
+            'list' => $lists,
+            'currentPage'=>$pagination->page,
+            'totalPages'=>$pagination->pageCount,
+            'startNum' => $pagination->page * $pagination->pageSize + 1,
+            'totalCount' => $pagination->totalCount,
+            'pageSize' => $pagination->pageSize,
+        ];
+
+        foreach ($data['list'] as $key => $value) {
+            $data['list'][$key]['ORDER_TYPE'] = 'Reselling';
+            $data['list'][$key]['PAY_AT'] = $value['PAY_AT'] ? Date::convert($value['PAY_AT'],'Y-m-d H:i:s') : '';
+            $data['list'][$key]['CREATED_AT'] = $value['CREATED_AT'] ? Date::convert($value['CREATED_AT'],'Y-m-d H:i:s') : '';
+            $data['list'][$key]['PAY_TYPE'] = array_column(ShopGoods::SALE_TYPE, NULL, 'label')[$value['PAY_TYPE']]['name'] ?? '';
+            $data['list'][$key]['STATUS'] = \Yii::$app->params['orderStatus'][$value['STATUS']]['label'] ?? '';
+            $data['list'][$key]['FULL_ADDRESS'] = $value['ADDRESS'];
+            $data['list'][$key]['TAX_AMOUNT'] = Tool::formatPrice(($value['REAL_PRICE'] - $value['REAL_PRICE'] / (1 + $value['TAX_RATE'] / 100)) * $value['BUY_NUMS']);
+            $data['list'][$key]['TOTAL_AMOUNT'] = Tool::formatPrice($value['REAL_PRICE'] * $value['BUY_NUMS']);
+            if ($value['LGA_NAME']) {
+                $data['list'][$key]['FULL_ADDRESS'] .= ', ' . $value['LGA_NAME'];
+            }
+        }
+
+        return static::notice($data);
+    }
+
+    /**
+     * 我的BA报单
+     * @return mixed
+     * @throws HttpException
+     */
+    public function actionBaDecOrderList() {
+        $condition = ' DO.USER_ID=:USER_ID AND DO.IS_DEL=0';
+        $params[':USER_ID'] = \Yii::$app->user->id;
+
+        $orderQuery = BaDecOrder::find()
+            ->alias('DO')
+            ->where($condition, $params)
+            ->select('DO.*,O.STATUS,U.USER_NAME USER_NAME,U.REAL_NAME REAL_NAME,RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,CU.USER_NAME CON_USER_NAME,CU.REAL_NAME CON_REAL_NAME,OG.SKU_CODE,OG.GOODS_TITLE,OG.BUY_NUMS,OG.REAL_PRICE,OG.REAL_PV,OG.TAX_RATE')
+            ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'DO.TO_USER_ID=U.ID')
+            ->join('LEFT JOIN', User::tableName() . ' AS RU', 'DO.REC_USER_ID=RU.ID')
+            ->join('LEFT JOIN', User::tableName() . ' AS CU', 'DO.CON_USER_ID=CU.ID')
+            ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=DO.ORDER_SN')
+            ->join('LEFT JOIN', BaOrder::tableName() . ' AS O', 'O.SN=DO.ORDER_SN')
+            ->orderBy('DO.CREATED_AT DESC');
+
+        // 订单中间表只查询待支付和支付失败的订单
+        $params[':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value'];   // 待支付
+        $params[':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value'];   // 支付失败
+        $orderStandardQuery = BaApproachDecOrder::find()
+            ->alias('DO')
+            ->where($condition . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $params)
+            ->select('DO.*,O.STATUS,U.USER_NAME USER_NAME,U.REAL_NAME REAL_NAME,RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,CU.USER_NAME CON_USER_NAME,CU.REAL_NAME CON_REAL_NAME,OG.SKU_CODE,OG.GOODS_TITLE,OG.BUY_NUMS,OG.REAL_PRICE,OG.REAL_PV,OG.TAX_RATE')
+            ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'DO.TO_USER_ID=U.ID')
+            ->join('LEFT JOIN', User::tableName() . ' AS RU', 'DO.REC_USER_ID=RU.ID')
+            ->join('LEFT JOIN', User::tableName() . ' AS CU', 'DO.CON_USER_ID=CU.ID')
+            ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=DO.ORDER_SN')
+            ->join('LEFT JOIN', BaApproachOrder::tableName() . ' AS O', 'O.SN=DO.ORDER_SN')
+            ->orderBy('DO.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();
+
+        $data = [
+            'list' => $lists,
+            'currentPage'=>$pagination->page,
+            'totalPages'=>$pagination->pageCount,
+            'startNum' => $pagination->page * $pagination->pageSize + 1,
+            'totalCount' => $pagination->totalCount,
+            'pageSize' => $pagination->pageSize,
+        ];
+
+        foreach ($data['list'] as &$value) {
+            $value['TAX_AMOUNT'] = Tool::calculateTax($value['REAL_PRICE'], floatval($value['TAX_RATE']), intval($value['BUY_NUMS']));
+            $value['STATUS'] = \Yii::$app->params['orderStatus'][$value['STATUS']]['label'] ?? '';
+            $value['CREATED_AT'] = $value['CREATED_AT'] ? Date::convert($value['CREATED_AT'],'Y-m-d H:i:s') : '';
+            $value['REAL_PV'] = Tool::formatPrice($value['REAL_PV'] * $value['BUY_NUMS']);
+            $value['TOTAL_AMOUNT'] = Tool::formatPrice($value['REAL_PRICE'] * $value['BUY_NUMS']);
+        }
+
+        return static::notice($data);
+    }
+
+    /**
+     * 导出订单.
+     * @return mixed
+     * @throws HttpException
+     */
+    public function actionBaDecOrderExport()
+    {
+        $orderSn = \Yii::$app->request->get('orderSn');
+
+        $condition = ' AND DO.USER_ID=:USER_ID AND IS_DEL=0 AND DO.ORDER_SN=:ORDER_SN';
+        $params = [
+            ':USER_ID'  => \Yii::$app->user->id,
+            ':ORDER_SN' => $orderSn,
+        ];
+        $data = BaDecOrder::lists($condition, $params, [
+            'select' => 'DO.*,U.USER_NAME USER_NAME,U.REAL_NAME REAL_NAME,RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,CU.USER_NAME CON_USER_NAME,CU.REAL_NAME CON_REAL_NAME,OG.*,OD.PROVINCE,OD.CITY,OD.COUNTY,OD.ADDRESS,OD.MOBILE,OD.PAY_AT,OD.ORDER_AMOUNT',
+            'orderBy' => 'DO.CREATED_AT DESC',
+            'from' => BaDecOrder::tableName() . ' AS DO',
+            'join' => [
+                ['LEFT JOIN', BaUser::tableName() . ' AS U', 'DO.TO_USER_ID=U.ID'],
+                ['LEFT JOIN', User::tableName() . ' AS RU', 'DO.REC_USER_ID=RU.ID'],
+                ['LEFT JOIN', User::tableName() . ' AS CU', 'DO.CON_USER_ID=CU.ID'],
+                ['LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=DO.ORDER_SN'],
+                ['LEFT JOIN', BaOrder::tableName() . ' AS OD', 'OD.SN=DO.ORDER_SN'],
+            ],
+        ]);
+
+        if (!$data['list']) {
+            $data = BaApproachDecOrder::lists($condition, $params, [
+                'select' => 'DO.*,U.USER_NAME USER_NAME,U.REAL_NAME REAL_NAME,RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,CU.USER_NAME CON_USER_NAME,CU.REAL_NAME CON_REAL_NAME,OG.*,OD.PROVINCE,OD.CITY,OD.COUNTY,OD.ADDRESS,OD.MOBILE,OD.PAY_AT,OD.ORDER_AMOUNT',
+                'orderBy' => 'DO.CREATED_AT DESC',
+                'from' => BaApproachDecOrder::tableName() . ' AS DO',
+                'join' => [
+                    ['LEFT JOIN', BaUser::tableName() . ' AS U', 'DO.TO_USER_ID=U.ID'],
+                    ['LEFT JOIN', User::tableName() . ' AS RU', 'DO.REC_USER_ID=RU.ID'],
+                    ['LEFT JOIN', User::tableName() . ' AS CU', 'DO.CON_USER_ID=CU.ID'],
+                    ['LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=DO.ORDER_SN'],
+                    ['LEFT JOIN', BaApproachOrder::tableName() . ' AS OD', 'OD.SN=DO.ORDER_SN'],
+                ],
+            ]);
+        }
+
+        $userId = '';
+        $userName = '';
+        $address = '';
+        $mobile = '';
+        $orderAt = '';
+        $orderDetails = '';
+        $orderAmount = 0;  // 合计总额
+        $orderNums = 0; // 合计总数
+        $totalTaxAmount = 0; // 合计税额
+        $totalAmount = 0;
+        foreach ($data['list'] 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');
+
+            // 总价
+            $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
+            $orderAmount += $totalAmount;
+            $orderNums += $value['BUY_NUMS'];
+            // 税额
+            $taxAmount = floatval(Tool::formatPrice(($value['REAL_PRICE'] - ($value['REAL_PRICE'] / (1 + $value['TAX_RATE'] / 100))) * $value['BUY_NUMS']));
+            $totalTaxAmount += $taxAmount;
+            $taxAmount = sprintf('%.2f', $taxAmount);
+            $totalAmount = sprintf('%.2f', $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 = sprintf('%.2f', $orderAmount);
+        $totalTaxAmount = sprintf('%.2f', $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 20px; 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="8%" 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="12%" 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>{$totalTaxAmount}</td>
+                                    <td>{$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);
+
+        ob_clean();
+
+        $file_name = $orderSn . '.pdf';
+        $path = 'pdfs/' . $file_name;
+        $pdf->Output(Yii::$app->basePath . '/web/' . $path, 'F');
+        @exec('chmod -R 777 /' . Yii::$app->basePath . '/web' . $path);
+
+        return static::notice(['fileUrl' => $path, 'targetName' => $file_name]);
+    }
 }

+ 58 - 0
frontendApi/modules/v1/controllers/SiteController.php

@@ -12,6 +12,7 @@ use common\helpers\snowflake\PageSnowFake;
 use common\models\Ad;
 use common\models\AdLocation;
 use common\models\ArticleCategory;
+use common\models\BaUser;
 use common\models\DecOrder;
 use common\models\DecRole;
 use Yii;
@@ -119,12 +120,14 @@ class SiteController extends BaseController
         $daysDiff = Yii::$app->params['daysDiff'];
         // 钱包
         $shopWalletType = Yii::$app->params['shopWalletType'];
+
         return [
             'decLevels' => $decLevels,
             'empLevels' => $empLevels,
             'menu' => $menu,
             'daysDiff' => $daysDiff,
             'shopWalletType' => $shopWalletType,
+            'whetherBA' => false,
         ];
     }
 
@@ -262,4 +265,59 @@ class SiteController extends BaseController
         $siteTitle = $systemConfig['siteTitle']['VALUE'];
         return static::notice(['siteClose' => false, 'siteTitle' => $siteTitle]);
     }
+
+    /**
+     * 请求基础信息
+     * @return array
+     */
+    public function actionBaBaseInfo(){
+        // 菜单
+        $menu = require Yii::getAlias('@frontendApi/config/menuBA.php');
+        // 获取全部文章分类
+        $allArticleCategory = ArticleCategory::getAllCategory();
+        foreach($allArticleCategory as $category){
+            $menu['article']['child'][] = ['name'=>$category['CATE_NAME'], 'class'=>'', 'icon'=>'', 'controller'=>'article', 'action'=>'list', 'routePath'=>'article/list/'.$category['ID'], 'show'=>1,];
+        }
+        $menu = $this->_childBaMenu($menu);
+        // 时间差
+        $daysDiff = Yii::$app->params['daysDiff'];
+        // 钱包
+        $shopWalletType = Yii::$app->params['shopWalletType'];
+
+        return [
+            'decLevels' => '',
+            'empLevels' => '',
+            'menu' => $menu,
+            'daysDiff' => $daysDiff,
+            'shopWalletType' => $shopWalletType,
+            'whetherBA' => true,
+        ];
+    }
+
+    private function _childBaMenu($parentArray) {
+        $menuResult = [];
+        foreach ($parentArray as $key => $parentMenu) {
+            if ($key !== 'article'){
+                // 菜单是否显示
+                if (isset($parentMenu['show']) && !$parentMenu['show']) {
+                    continue;
+                }
+                // 查看是否有该控制器的权限
+                if(isset($parentMenu['controller']) && $parentMenu['controller']){
+                    if(!Yii::$app->user->validateUserController($parentMenu['controller'])) continue;
+                }
+                // 查看是否有权限
+                if(isset($parentMenu['action']) && $parentMenu['action']){
+                    if(!Yii::$app->user->validateUserAction($parentMenu['controller'], $parentMenu['action'])) continue;
+                }
+                // 子菜单同样设置
+                if(isset($parentMenu['child']) && !empty($parentMenu['child'])){
+                    $parentMenu['child'] = $this->_childBaMenu($parentMenu['child']);
+                }
+            }
+
+            $menuResult[] = $parentMenu;
+        }
+        return $menuResult;
+    }
 }

+ 184 - 10
frontendApi/modules/v1/controllers/UserController.php

@@ -12,14 +12,19 @@ use common\helpers\Cache;
 use common\helpers\Form;
 use common\helpers\Tool;
 use common\helpers\user\Info;
+use common\models\BaUser;
 use common\models\Config;
 use common\models\DeclarationLevel;
 use common\models\DeclarationPackage;
 use common\models\DecOrder;
 use common\models\forms\ApproachDeclarationLoopForm;
+use common\models\forms\BaApproachDeclarationLoopForm;
 use common\models\forms\ApproachDeclarationUpgradeForm;
+use common\models\forms\BaUserForm;
 use common\models\forms\DeclarationForm;
+use common\models\forms\BaDeclarationForm;
 use common\models\forms\DeclarationLoopForm;
+use common\models\forms\BaDeclarationLoopForm;
 use common\models\forms\UploadForm;
 use common\models\forms\UserBindForm;
 use common\models\forms\UserForm;
@@ -31,6 +36,7 @@ use common\models\UpgradeType;
 use common\models\User;
 use common\models\UserBind;
 use common\models\UserInfo;
+use common\models\BaUserInfo;
 use common\models\UserNetwork;
 use common\models\forms\DeclarationUpgradeForm;
 use yii\db\Exception;
@@ -70,7 +76,7 @@ class UserController extends BaseController {
                 return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
             }
         }
-        return static::notice('非法访问', 400);
+        return static::notice('Illegal request', 400); // 非法请求
     }
 
     /**
@@ -87,7 +93,7 @@ class UserController extends BaseController {
                 return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
             }
         }
-        return static::notice('非法访问', 400);
+        return static::notice('Illegal request', 400); // 非法请求
     }
 
     /**
@@ -105,7 +111,7 @@ class UserController extends BaseController {
                 return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
             }
         }
-        return static::notice('非法访问', 400);
+        return static::notice('Illegal request', 400); // 非法请求
     }
 
     /**
@@ -383,17 +389,22 @@ class UserController extends BaseController {
             $post['lgaName'] = trim($post['lgaName']);
 
             // 针对于会员编号的判断
-            $insertUserName = strtoupper($post['insertUserName']);
-            $getRedisUserName = $redis->get('key_' . $insertUserName);
-            if (!$getRedisUserName){
-                return static::notice('Membership number expired',400);//会员编号过期
-            }
-            if ($insertUserName != $getRedisUserName){
-                return static::notice('Member number does not conform to',400);//会员编号不符合
+            if($post['decType']=='normal'){ // 普通报单,判断Redis中的用户名是否一致
+                $insertUserName = strtoupper($post['insertUserName']);
+                $getRedisUserName = $redis->get('key_' . $insertUserName);
+                if (!$getRedisUserName){
+                    return static::notice('Membership number expired',400);//会员编号过期
+                }
+                if ($insertUserName != $getRedisUserName){
+                    return static::notice('Member number does not conform to',400);//会员编号不符合
+                }
+            }else{ // BA升级,需要判断BA用户是否存在
+                $insertUserName = $post['insertUserName'];
             }
 
             $post['insertUserName'] = $insertUserName;
             $post['type'] = DeclarationForm::TYPE_ZC;
+
             $allData['data'][] = $post;
             if ($formModel->load($allData, '') && $result = $formModel->add()) {
                 return static::notice($result);//报单成功
@@ -536,4 +547,167 @@ class UserController extends BaseController {
             return static::notice('Repeat sales Member No. does not exist', 400);//复消会员编号不存在
         }
     }
+
+    /**
+     * 会员资料
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaInfo()
+    {
+        $allNation = \Yii::$app->params['nation'];
+        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
+        $data['allNation'] = $allNation;
+        $data['allOpenBank'] = $allOpenBank;
+        $data['userInfo'] = BaUser::getEnCodeInfo(\Yii::$app->user->id);
+        $data['userInfo']['NATION'] = $data['userInfo']['NATION_ID'];
+        return static::notice($data);
+    }
+
+    /**
+     * 编辑会员资料
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaEdit()
+    {
+        if(\Yii::$app->request->isPost)
+        {
+            $form = new BaUserForm();
+            $post = \Yii::$app->request->post();
+            $form->scenario = 'modifyProfile';
+            if ($form->load($post, '') && $result = $form->modifyProfile()){
+                return static::notice('Personal data modified successfully');//个人资料修改成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+            }
+        }
+
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+
+    /**
+     * 修改登录密码
+     */
+    public function actionBaPassword(){
+        if(\Yii::$app->request->isPost) {
+            $form = new BaUserForm();
+            $form->scenario = 'modifyPassword';
+            $post = \Yii::$app->request->post();
+            if($form->load($post, '') && $result = $form->modifyPassword()){
+                return static::notice('Password modified successfully');//密码修改成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+            }
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+
+    /**
+     * 修改支付密码
+     */
+    public function actionBaPayPassword(){
+        if(\Yii::$app->request->isPost){
+            $form = new BaUserForm();
+            $form->scenario = 'modifyPasswordPay';
+            $post = \Yii::$app->request->post();
+            $form->userId = \Yii::$app->user->id;
+            if($form->load($post, '') && $result = $form->modifyPasswordPay()){
+                return static::notice('Payment password modified successfully');  // 支付密码修改成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
+            }
+        }
+        return static::notice('Illegal request', 400); // 非法请求
+    }
+    
+    /**
+     * BA报单管理
+     */
+    public function actionBaDec() {
+        // 生成随机码 , 初始化redis
+        $userName = Info::generateWebUserName('NG',9);
+        $redis = \Yii::$app->redis;
+        $post = \Yii::$app->request->post();
+
+        if (\Yii::$app->request->isPost) {
+            // 根据支付方式区分逻辑
+            $payMethod = \Yii::$app->request->post('payType', '');
+
+            if ($payMethod === 'pay_stack') {
+                $formModel = new BaApproachDeclarationLoopForm();
+            } else {
+                unset($post['payType']);
+                $formModel = new BaDeclarationLoopForm();
+            }
+
+            $formModel->scenario = 'userDec';
+
+            $post['province'] = $post['province'] ? :1;
+            $post['city'] = $post['city'] ? :1;
+            $post['county'] = $post['county'] ? :1;
+//            $post['conUserName'] = trim($post['conUserName']);
+            $post['recUserName'] = trim($post['recUserName']);
+            $post['cityName'] = trim($post['cityName']);
+            $post['lgaName'] = trim($post['lgaName']);
+
+            // 针对于会员编号的判断
+            $insertUserName = strtoupper($post['insertUserName']);
+            $getRedisUserName = $redis->get('key_' . $insertUserName);
+            if (!$getRedisUserName){
+                return static::notice('Membership number expired',400); // 会员编号过期
+            }
+            if ($insertUserName != $getRedisUserName){
+                return static::notice('Member number does not conform to',400); // 会员编号不符合
+            }
+
+            $post['insertUserName'] = $insertUserName;
+            $post['type'] = BaDeclarationForm::TYPE_ZC;
+            $allData['data'][] = $post;
+            if ($formModel->load($allData, '') && $result = $formModel->add()) {
+                return static::notice($result); // 报单成功
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
+            }
+        }
+
+        // 只查询普通商品
+        $allGoods = ShopGoods::find()->where("ID='399659569762144384'")->orderBy('SORT ASC')->asArray()->all();
+        if (!$userName) {
+            return static::notice('Failed to generate member number', 400); // 会员编号生成失败
+        }
+        //随机码保存在redis中方便进行比对
+        $redis->setex('key_'.$userName , 3600 , $userName);
+
+        return static::notice([
+            'allGoods' => $allGoods,
+            'userName' => $userName,
+            'payList' => ShopGoods::payTypes(),
+            'sellType' => ShopGoods::CATEGORY_TYPE,
+            'categoryType' => ShopGoods::CATEGORY_TYPE[0]['id'],
+        ]);
+    }
+
+    /**
+     * BA会员信息
+     * @return mixed
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaUserInfo()
+    {
+        $userName = \Yii::$app->request->get('userName');
+        $userId = Info::getBaUserIdByUserName($userName);
+        $userInfo['REAL_NAME'] = '';
+        $user = BaUser::findOneAsArray('ID=:ID', [':ID' => $userId], 'REAL_NAME');
+        $uInfo = BaUserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'REC_UID');
+        if($user){
+            $rec_user = UserInfo::findOneAsArray('USER_ID=:USER_ID',[':USER_ID' => $uInfo['REC_UID']], 'USER_ID, USER_NAME');
+            $userInfo['REAL_NAME'] = $user['REAL_NAME'];
+            $userInfo['REC_USER_ID'] = $rec_user['USER_ID'];
+            $userInfo['REC_USER_NAME'] = $rec_user['USER_NAME'];
+            return static::notice($userInfo);
+        }else{
+            return static::notice('Member number does not exist', 400);//会员编号不存在
+        }
+    }
 }

+ 47 - 12
frontendApi/modules/v1/models/LoginForm.php

@@ -4,11 +4,15 @@ namespace frontendApi\modules\v1\models;
 use common\components\Model;
 use common\helpers\Date;
 use common\libs\LoginIpChecker;
+use common\models\BaUser;
+use common\models\BaUserInfo;
 use common\models\UserInfo;
+use ReflectionProperty;
 use Yii;
 use yii\base\Exception;
 use yii\captcha\Captcha;
 use common\libs\logging\login\UserLogin as UserLoginLogger;
+use \frontendApi\modules\v1\models\brand\User as Brand;
 
 /**
  * Login form
@@ -22,6 +26,7 @@ class LoginForm extends Model
 
     private $_user;
     private $_userInfo;
+    private $_whetherBA;
 
     const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
 
@@ -76,9 +81,16 @@ class LoginForm extends Model
      * @throws \Exception
      */
     private function _updateFailTimes($transaction,$returnResult){
-        UserInfo::updateAllCounters([
-            'FAIL_NUMS' => 1,
-        ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        if (!$this->_whetherBA) {
+            UserInfo::updateAllCounters([
+                'FAIL_NUMS' => 1,
+            ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        } else {
+            BaUserInfo::updateAllCounters([
+                'FAIL_NUMS' => 1,
+            ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        }
+
         $transaction->commit();
 
         $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
@@ -96,9 +108,15 @@ class LoginForm extends Model
         $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
         Yii::$app->tokenRedis->del($cacheKey);
 
-        UserInfo::updateAllCounters([
-            'LOGIN_NUMS' => 1,
-        ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        if (!$this->_whetherBA) {
+            UserInfo::updateAllCounters([
+                'LOGIN_NUMS' => 1,
+            ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        } else {
+            BaUserInfo::updateAllCounters([
+                'LOGIN_NUMS' => 1,
+            ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        }
     }
 
     /**
@@ -158,9 +176,17 @@ class LoginForm extends Model
                 $update = [
                     'BONUS_APP_CLIENT_ID' => $clientId,
                 ];
-                if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
-                    $this->_updateFailTimes($transaction, 'Member APP device information update failed'); // 会员APP设备信息更新失败
-                    throw new Exception('Member APP device information update failed'); // 会员APP设备信息更新失败
+
+                if (!$this->_whetherBA) {
+                    if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
+                        $this->_updateFailTimes($transaction, 'Member APP device information update failed'); // 会员APP设备信息更新失败
+                        throw new Exception('Member APP device information update failed'); // 会员APP设备信息更新失败
+                    }
+                } else {
+                    if (!BaUser::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
+                        $this->_updateFailTimes($transaction, 'Member APP device information update failed'); // 会员APP设备信息更新失败
+                        throw new Exception('Member APP device information update failed'); // 会员APP设备信息更新失败
+                    }
                 }
             }
 
@@ -173,11 +199,14 @@ class LoginForm extends Model
             // 把用户的登录时间存在操作时间里
             Yii::$app->tokenRedis->hset('user:timeOut', $this->_userInfo['USER_ID'], time());
 
-            return Yii::$app->user->loginWithUAndP($this->_user);
+            if (!$this->_whetherBA) {
+                return Yii::$app->user->loginWithUAndP($this->_user);
+            } else {
+                return Yii::$app->brand->loginWithUAndP($this->_user);
+            }
         }catch(\Exception $e){
             $transaction->rollBack();
-            $this->setError($e->getMessage());
-            //AdminLoginLogger::fail($this->_user, $e->getMessage());
+            $this->setError($e->getFile() . '  ' . $e->getLine() . '  ' . $e->getMessage());
             return false;
         }
     }
@@ -191,6 +220,12 @@ class LoginForm extends Model
         if ($this->_user === null) {
             $this->_user = User::findByUsername($this->userName);
             $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
+            if (!$this->_user || !$this->_userInfo) {
+                $this->_user = Brand::findByUsername($this->userName);
+                $this->_userInfo = BaUserInfo::findOne(['USER_NAME' => $this->userName]);
+                // 是否BA会员
+                $this->_whetherBA = $this->_user && $this->_userInfo;
+            }
         }
         return $this->_user;
     }

+ 229 - 0
frontendApi/modules/v1/models/brand/User.php

@@ -0,0 +1,229 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: leo
+ * Date: 2018/2/24
+ * Time: 下午1:02
+ */
+
+namespace frontendApi\modules\v1\models\brand;
+
+use common\components\Redis;
+use common\helpers\Date;
+use common\models\BaUser;
+use common\models\UserToken;
+use Yii;
+use yii\web\IdentityInterface;
+
+class User extends BaUser implements IdentityInterface {
+    const CACHE_IS_QUICKLY_LOGIN = 'quickly:user:';
+
+    /**
+     * @param mixed $token
+     * @param null $type
+     * @return null|IdentityInterface|static
+     */
+    public static function findIdentityByAccessToken($token, $type = null) {
+        // 从redis中把 token 找到
+        return Yii::$app->tokenRedis->hget($token, 'ID');
+//        if($userId){
+//            return static::findOne(['ID' => $userId]);
+//        }
+//        return null;
+    }
+
+    public function fields() {
+        $fields = parent::fields();
+
+        // 删除一些包含敏感信息的字段
+        unset($fields['PASSWORD_HASH'], $fields['PAY_PASSWORD']);
+
+        return $fields;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function behaviors() {
+        return [
+            'yii\behaviors\TimestampBehavior',
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public static function findIdentity($id) {
+        return static::findOne(['ID' => $id]);
+    }
+
+    /**
+     * Finds user by username
+     *
+     * @param string $username
+     * @return static|null
+     */
+    public static function findByUsername($username) {
+        return static::findOne(['USER_NAME' => $username]);
+    }
+
+    /**
+     * 通过用户名获取信息并带着token表内容
+     * @param $username
+     * @return array
+     */
+    public static function findByUsernameWithToken($username) {
+        return static::find()->select(static::tableName() . '.*,T.ACCESS_TOKEN,T.REFRESH_TOKEN,T.CREATED_AT,T.UPDATED_AT')->join('LEFT JOIN', UserToken::tableName() . ' AS T', static::tableName() . '.ID=T.USER_ID')->where(static::tableName() . '.USER_NAME=:USER_NAME', ['USER_NAME' => $username])->asArray()->one();
+    }
+
+    /**
+     * 静态方法校验两个密码
+     * @param $password
+     * @param $validatePassword
+     * @return bool
+     */
+    public static function validatePasswordStatic($password, $validatePassword) {
+        return Yii::$app->security->validatePassword($password, $validatePassword);
+    }
+
+    /**
+     * 生成PCAccessToken
+     * @param $appType (pc|app)
+     * @return string
+     * @throws \yii\base\Exception
+     */
+    public static function generateAccessToken($appType) {
+        $appTypeUper = strtoupper($appType);
+        // 从redis的AccessTokenIncr中自增一个值
+        $incrValue = Yii::$app->tokenRedis->incr($appTypeUper . 'AccessTokenIncr');
+        // upa(user_pc_access)
+        return md5('u' . $appType[0] . 'a_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
+    }
+
+    /**
+     * 生成PCRefreshToken
+     * @param $appType (pc|app)
+     * @return string
+     * @throws \yii\base\Exception
+     */
+    public static function generateRefreshToken($appType) {
+        $appTypeUper = strtoupper($appType);
+        // 从redis的AccessTokenIncr中自增一个值
+        $incrValue = Yii::$app->tokenRedis->incr($appTypeUper . 'RefreshTokenIncr');
+        // upr(user_pc_access)
+        return md5('u' . $appType[0] . 'r_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
+    }
+
+    /**
+     * 通过重设密码 token 找到用户
+     * @param $token
+     * @return null|static
+     */
+    public static function findByPasswordResetToken($token) {
+        if (!static::isPasswordResetTokenValid($token)) {
+            return null;
+        }
+
+        return static::findOne([
+            'PASSWORD_RESET_TOKEN' => $token,
+        ]);
+    }
+
+    /**
+     * Finds out if password reset token is valid
+     *
+     * @param string $token password reset token
+     * @return bool
+     */
+    public static function isPasswordResetTokenValid($token) {
+        if (empty($token)) {
+            return false;
+        }
+
+        $timestamp = (int)substr($token, strrpos($token, '_') + 1);
+        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
+        return $timestamp + $expire >= time();
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function getId() {
+        return $this->getPrimaryKey();
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function getAuthKey() {
+        return $this->AUTH_KEY;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function validateAuthKey($authKey) {
+        return $this->getAuthKey() === $authKey;
+    }
+
+    /**
+     * Validates password
+     *
+     * @param string $password password to validate
+     * @return bool if password provided is valid for current user
+     */
+    public function validatePassword($password) {
+        //return password_verify($password, $this->PASSWORD_HASH);
+        return Yii::$app->security->validatePassword($password, $this->PASSWORD_HASH);
+    }
+
+    /**
+     * Generates password hash from password and sets it to the model
+     * @param $password
+     * @throws \yii\base\Exception
+     */
+    public function setPassword($password) {
+        $this->PASSWORD_HASH = Yii::$app->security->generatePasswordHash($password);
+    }
+
+    /**
+     * Generates "remember me" authentication key
+     * @throws \yii\base\Exception
+     */
+    public function generateAuthKey() {
+        $this->AUTH_KEY = Yii::$app->security->generateRandomString();
+    }
+
+    /**
+     * Generates new password reset token
+     * @throws \yii\base\Exception
+     */
+    public function generatePasswordResetToken() {
+        $this->PASSWORD_RESET_TOKEN = Yii::$app->security->generateRandomString() . '_' . Date::nowTime();
+    }
+
+    /**
+     * Removes password reset token
+     */
+    public function removePasswordResetToken() {
+        $this->PASSWORD_RESET_TOKEN = null;
+    }
+
+
+    /**
+     * 简单的缓存信息,此信息是在登录时缓存的
+     * @return mixed
+     */
+    public static function isQuicklyLogin() {
+        $authHeader = Yii::$app->request->getHeaders()->get('Authorization');
+        if ($authHeader !== null && preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
+            $token = ($matches && isset($matches[1])) ? $matches[1] : null;
+            if ($token) {
+                $key = Redis::key(self::CACHE_IS_QUICKLY_LOGIN . $token);
+                $value = (int)Yii::$app->redis->get($key);
+                return $value;
+            }
+        }
+        return 0;
+    }
+}

+ 4 - 1
frontendEle/package.json

@@ -16,18 +16,21 @@
   },
   "dependencies": {
     "ajv": "^6.2.0",
+    "animate": "^1.0.0",
     "axios": "^0.19.0",
     "babel-polyfill": "^6.26.0",
     "countup.js": "^1.9.3",
     "echarts": "^4.1.0",
     "element-ui": "^2.13.0",
+    "font-awesome": "^4.7.0",
     "nix-tinymce": "^1.0.7",
     "v-charts": "^1.16.20",
     "vue": "^2.6.14",
     "vue-countup-v2": "^1.0.3",
     "vue-paystack": "^2.0.4",
     "vue-router": "^3.0.2",
-    "vuex": "^3.0.1"
+    "vuex": "^3.0.1",
+    "waves": "^0.1.1"
   },
   "devDependencies": {
     "autoprefixer": "^7.1.2",

+ 386 - 231
frontendEle/src/router/index.js

@@ -4,9 +4,9 @@ import layout from '../views/layout/layout'
 
 const _import = require('./_import_' + process.env.NODE_ENV)
 
-if(Router.version >= '3.1.0'){
+if (Router.version >= '3.1.0') {
   const originalPush = Router.prototype.push
-  Router.prototype.push = function push(location) {
+  Router.prototype.push = function push (location) {
     return originalPush.call(this, location).catch(err => err)
   }
 }
@@ -30,116 +30,176 @@ export const constantRouterMap = [
       component: _import('dashboard/index'),
       name: 'dashboard_index',
       meta: {
-        title: 'Dashboard',//控制台
+        title: 'Dashboard', // 控制台
         breadcrumb: [
-          {title: 'Dashboard', path: '/dashboard/index'},//首页
-        ],
+          {title: 'Dashboard', path: '/dashboard/index'} // 首页
+        ]
+      }
+    },
+      {
+        path: '/dashboard/ba-index',
+        component: _import('dashboard/ba-index'),
+        name: 'dashboard_ba_index',
+        meta: {
+          title: 'Dashboard', // 控制台
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/ba-index'} // 首页
+          ]
+        }
       },
-    }]
+      ]
   },
   {
-        path: '/shop',
-        component: layout,
-        redirect: '/shop/dec-order-list',
-        children: [
-            {
-                path: '/shop/dec-order-list',
-                component: _import('shop/dec-order-list'),
-                name: 'shop_dec-order-list',
-                meta: {
-                    title: 'Welcome Pack Listing',//报单列表
-                    breadcrumb: [
-                        {title: 'Dashboard', path: '/dashboard/index'},//首页
-                        {title: 'Shopping Mall', path: '/shop/dec-order-list'},//商城管理
-                    ],
-                },
-            },
-            {
-                path: '/shop/order-list',
-                component: _import('shop/order-list'),
-                name: 'shop_order-list',
-                meta: {
-                    title: 'Order List',//订单列表
-                    breadcrumb: [
-                        {title: 'Dashboard', path: '/dashboard/index'},//首页
-                        {title: 'Shopping Mall', path: '/shop/dec-order-list'},//商城管理
-                    ],
-                },
-            },
-            {
-                path: '/shop/index',
-                component: _import('shop/index'),
-                name: 'shop_index',
-                meta: {
-                    title: 'Products list',//商品列表
-                    breadcrumb: [
-                        {title: 'Dashboard', path: '/dashboard/index'},//首页
-                        {title: 'Shopping Mall', path: '/shop/dec-order-list'},//商城管理
-                    ],
-                },
-            },
-            {
-              path: '/shop/order-backing-out',
-              component: _import('shop/order-backing-out'),
-              name: 'shop_order-list',
-              meta: {
-                  title: '订单退货',//订单退货
-                  breadcrumb: [
-                      {title: 'Dashboard', path: '/dashboard/index'},//首页
-                      {title: 'Shopping Mall', path: '/shop/dec-order-list'},//商城管理
-                  ],
-              }
-            },
-            {
-                path: '/shop/order',
-                component: _import('shop/order'),
-                name: 'shop_order',
-                meta: {
-                    title: 'Products settlement',
-                    breadcrumb: [
-                        {title: 'Dashboard', path: '/dashboard/index'},//首页
-                        {title: 'Shopping Mall', path: '/shop/dec-order-list'}//商城管理
-                    ],
-                },
-            },
-            {
-                path: '/shop/goods-detail/:id',
-                component: _import('shop/goods-detail'),
-                name: 'shop_goods-detail',
-                meta: {
-                    title: '商品详情',
-                    breadcrumb: [
-                        {title: 'Dashboard', path: '/dashboard/index'},
-                        {title: 'Shopping Mall', path: '/shop/dec-order-list'},
-                    ],
-                },
-            },
-            // {
-            //     path: '/shop/reconsume',
-            //     component: _import('shop/reconsume'),
-            //     name: 'shop_reconsume',
-            //     meta: {
-            //         title: '复消商品',
-            //         breadcrumb: [
-            //             {title: '首页', path: '/dashboard/index'},
-            //             {title: '商城管理', path: '/shop/dec-order-list'},
-            //         ],
-            //     },
-            // },
-            // {
-            //     path: '/shop/reconsume-order',
-            //     component: _import('shop/reconsume-order'),
-            //     name: 'reconsume-order',
-            //     meta: {
-            //         title: '复消商品结算',
-            //         breadcrumb: [
-            //             {title: '首页', path: '/dashboard/index'},
-            //             {title: '商城管理', path: '/shop/dec-order-list'}
-            //         ],
-            //     },
-            // },
-        ],
-    },
+    path: '/shop',
+    component: layout,
+    redirect: '/shop/dec-order-list',
+    children: [
+      {
+        path: '/shop/dec-order-list',
+        component: _import('shop/dec-order-list'),
+        name: 'shop_dec-order-list',
+        meta: {
+          title: 'Welcome Pack Listing', // 报单列表
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/dec-order-list'} // 商城管理
+          ]
+        }
+      },
+      {
+        path: '/shop/order-list',
+        component: _import('shop/order-list'),
+        name: 'shop_order-list',
+        meta: {
+          title: 'Order List', // 订单列表
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/dec-order-list'} // 商城管理
+          ]
+        }
+      },
+      {
+        path: '/shop/index',
+        component: _import('shop/index'),
+        name: 'shop_index',
+        meta: {
+          title: 'Products list', // 商品列表
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/dec-order-list'} // 商城管理
+          ]
+        }
+      },
+      {
+        path: '/shop/order-backing-out',
+        component: _import('shop/order-backing-out'),
+        name: 'shop_order-list',
+        meta: {
+          title: '订单退货', // 订单退货
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/dec-order-list'} // 商城管理
+          ]
+        }
+      },
+      {
+        path: '/shop/order',
+        component: _import('shop/order'),
+        name: 'shop_order',
+        meta: {
+          title: 'Products settlement',
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/dec-order-list'}// 商城管理
+          ]
+        }
+      },
+      {
+        path: '/shop/goods-detail/:id',
+        component: _import('shop/goods-detail'),
+        name: 'shop_goods-detail',
+        meta: {
+          title: '商品详情',
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'},
+            {title: 'Shopping Mall', path: '/shop/dec-order-list'}
+          ]
+        }
+      },
+      {
+        path: '/shop/ba-product-list',
+        component: _import('shop/ba-product-list'),
+        name: 'ba_product_list',
+        meta: {
+          title: 'Products list', // BA商品列表
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/ba-order-list'} // 商城管理
+          ]
+        }
+      },
+      {
+        path: '/shop/ba-shopping-cart',
+        component: _import('shop/ba-shopping-cart'),
+        name: 'ba-shopping-cart',
+        meta: {
+          title: 'Products settlement', // 购物车
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/ba-shopping-cart'}// 商城管理
+          ]
+        }
+      },
+      {
+        path: '/shop/ba-order-list',
+        component: _import('shop/ba-order-list'),
+        name: 'ba_order_list',
+        meta: {
+          title: 'Order List', // BA订单列表
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/ba-order-list'}// 商城管理
+          ]
+        }
+      },
+      {
+        path: '/shop/ba-dec-order-list',
+        component: _import('shop/ba-dec-order-list'),
+        name: 'shop_ba-dec-order-list',
+        meta: {
+          title: 'Welcome Listing', // BA报单列表
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Shopping Mall', path: '/shop/dec-order-list'} // 商城管理
+          ]
+        }
+      }
+      // {
+      //     path: '/shop/reconsume',
+      //     component: _import('shop/reconsume'),
+      //     name: 'shop_reconsume',
+      //     meta: {
+      //         title: '复消商品',
+      //         breadcrumb: [
+      //             {title: '首页', path: '/dashboard/index'},
+      //             {title: '商城管理', path: '/shop/dec-order-list'},
+      //         ],
+      //     },
+      // },
+      // {
+      //     path: '/shop/reconsume-order',
+      //     component: _import('shop/reconsume-order'),
+      //     name: 'reconsume-order',
+      //     meta: {
+      //         title: '复消商品结算',
+      //         breadcrumb: [
+      //             {title: '首页', path: '/dashboard/index'},
+      //             {title: '商城管理', path: '/shop/dec-order-list'}
+      //         ],
+      //     },
+      // },
+    ]
+  },
   {
     path: '/user',
     component: layout,
@@ -150,24 +210,24 @@ export const constantRouterMap = [
         component: _import('user/index'),
         name: 'user_index',
         meta: {
-          title: 'Personal info',//个人资料
+          title: 'Personal info', // 个人资料
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Member management', path: '/user/index'},//会员管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Member management', path: '/user/index'} // 会员管理
+          ]
+        }
       },
       {
-          path: '/user/password',
-          component: _import('user/password'),
-          name: 'user_password',
-          meta: {
-              title: 'Reset Password',//重置密码
-              breadcrumb: [
-                  {title: 'Dashboard', path: '/dashboard/index'},//首页
-                  {title: 'Member management', path: '/user/index'},//会员管理
-              ],
-          },
+        path: '/user/password',
+        component: _import('user/password'),
+        name: 'user_password',
+        meta: {
+          title: 'Reset Password', // 重置密码
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Member management', path: '/user/index'} // 会员管理
+          ]
+        }
       },
       {
         path: '/user/id-card',
@@ -177,9 +237,9 @@ export const constantRouterMap = [
           title: '上传身份证',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Member management', path: '/user/index'},
-          ],
-        },
+            {title: 'Member management', path: '/user/index'}
+          ]
+        }
       },
       {
         path: '/user/rec-user',
@@ -189,9 +249,9 @@ export const constantRouterMap = [
           title: '开拓会员列表',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Member management', path: '/user/index'},
-          ],
-        },
+            {title: 'Member management', path: '/user/index'}
+          ]
+        }
       },
       {
         path: '/user/bind',
@@ -201,9 +261,9 @@ export const constantRouterMap = [
           title: '点位绑定列表',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Member management', path: '/user/index'},
-          ],
-        },
+            {title: 'Member management', path: '/user/index'}
+          ]
+        }
       },
       {
         path: '/user/bind-edit/:id',
@@ -215,35 +275,90 @@ export const constantRouterMap = [
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
             {title: 'Member management', path: '/user/index'},
-            {title: '点位绑定列表', path: '/user/bind'},
-          ],
-        },
+            {title: '点位绑定列表', path: '/user/bind'}
+          ]
+        }
       },
       {
         path: '/user/dec',
         component: _import('user/dec'),
         name: 'user_dec',
         meta: {
-          title: 'Welcome Pack management',//报单管理
+          title: 'Welcome Pack management', // 报单管理
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Member management', path: '/user/index'},//会员管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Member management', path: '/user/index'} // 会员管理
+          ]
+        }
       },
       {
         path: '/user/upgrade',
         component: _import('user/upgrade'),
         name: 'user_upgrade',
         meta: {
-          title: 'Upgrade management',//升级管理
+          title: 'Upgrade management', // 升级管理
           highLight: '/user/bind',
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Member management', path: '/user/index'},//会员管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Member management', path: '/user/index'} // 会员管理
+          ]
+        }
+      },
+      {
+        path: '/user/ba-dec',
+        component: _import('user/ba-dec'),
+        name: 'user_ba-dec',
+        meta: {
+          title: 'Welcome BA', // 个人资料
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Member management', path: '/user/index'} // 会员管理
+          ]
+        }
+      },
+      {
+        path: '/user/ba-info',
+        component: _import('user/ba-info'),
+        name: 'ba-info',
+        meta: {
+          title: 'Personal info', // 个人资料
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Member management', path: '/user/index'} // 会员管理
+          ]
+        }
       },
+      {
+        path: '/user/ba-password',
+        component: _import('user/ba-password'),
+        name: 'ba-password',
+        meta: {
+          title: 'Reset Password', // 重置密码
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Member management', path: '/user/index'} // 会员管理
+          ]
+        }
+      }
+    ]
+  },
+  {
+    path: '/atlas',
+    component: layout,
+    redirect: '/atlas/network',
+    children: [
+      {
+        path: '/atlas/network',
+        component: _import('atlas/network'),
+        name: 'atlas_network',
+        meta: {
+          title: 'Placement network',
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'},
+            {title: 'Network Chart', path: '/atlas/network'}
+          ]
+        }
+      }
     ]
   },
   {
@@ -287,12 +402,12 @@ export const constantRouterMap = [
         component: _import('bonus/index'),
         name: 'bonus_index',
         meta: {
-          title: 'My account',//我的账户
+          title: 'My account', // 我的账户
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Bonus management', path: '/bonus/index'},//奖金管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Bonus management', path: '/bonus/index'} // 奖金管理
+          ]
+        }
       },
       {
         path: '/bonus/new',
@@ -302,33 +417,33 @@ export const constantRouterMap = [
           title: '最新奖金',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Bonus management', path: '/bonus/index'},
-          ],
-        },
+            {title: 'Bonus management', path: '/bonus/index'}
+          ]
+        }
       },
       {
         path: '/bonus/other',
         component: _import('bonus/other'),
         name: 'bonus_other',
         meta: {
-          title: 'Previous bonus',//往期奖金
+          title: 'Previous bonus', // 往期奖金
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//Dashboard
-            {title: 'Bonus management', path: '/bonus/index'},//奖金管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // Dashboard
+            {title: 'Bonus management', path: '/bonus/index'} // 奖金管理
+          ]
+        }
       },
       {
         path: '/bonus/historical-cumulative-bonus',
         component: _import('bonus/historical-cumulative-bonus'),
         name: 'historical-cumulative-bonus',
         meta: {
-          title: 'Historical cumulative bonus',//往期历史奖金累积
+          title: 'Historical cumulative bonus', // 往期历史奖金累积
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//Dashboard
-            {title: 'Bonus management', path: '/bonus/index'},//奖金管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // Dashboard
+            {title: 'Bonus management', path: '/bonus/index'} // 奖金管理
+          ]
+        }
       },
       {
         path: '/bonus/real-time-perf',
@@ -338,9 +453,9 @@ export const constantRouterMap = [
           title: '实时业绩',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Bonus management', path: '/bonus/index'},
-          ],
-        },
+            {title: 'Bonus management', path: '/bonus/index'}
+          ]
+        }
       },
       {
         path: '/bonus/fc-point',
@@ -350,10 +465,10 @@ export const constantRouterMap = [
           title: '房产积分',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Bonus management', path: '/bonus/index'},
-          ],
-        },
-      },
+            {title: 'Bonus management', path: '/bonus/index'}
+          ]
+        }
+      }
 
     ]
   },
@@ -370,9 +485,9 @@ export const constantRouterMap = [
           title: 'Article List',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Article Management', path: '/article/list'},
-          ],
-        },
+            {title: 'Article Management', path: '/article/list'}
+          ]
+        }
       },
       {
         path: '/article/detail/:id',
@@ -382,10 +497,10 @@ export const constantRouterMap = [
           title: 'Article Detail',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Article Management', path: '/article/list'},
-          ],
-        },
-      },
+            {title: 'Article Management', path: '/article/list'}
+          ]
+        }
+      }
     ]
   },
   {
@@ -401,9 +516,9 @@ export const constantRouterMap = [
           title: '站内信列表',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: '站内信', path: '/message/list'},
-          ],
-        },
+            {title: '站内信', path: '/message/list'}
+          ]
+        }
       },
       {
         path: '/message/detail/:id',
@@ -413,10 +528,10 @@ export const constantRouterMap = [
           title: '站内信详情',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: '站内信', path: '/message/list'},
-          ],
-        },
-      },
+            {title: '站内信', path: '/message/list'}
+          ]
+        }
+      }
     ]
   },
   {
@@ -432,35 +547,35 @@ export const constantRouterMap = [
           title: '会员复销池余额流水',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Financial management', path: '/finance/withdraw'},
-          ],
-        },
+            {title: 'Financial management', path: '/finance/withdraw'}
+          ]
+        }
       },
       {
         path: '/finance/withdraw',
         component: _import('finance/withdraw'),
         name: 'finance_withdraw',
         meta: {
-          title: 'Withdrawal details',//提现明细
+          title: 'Withdrawal details', // 提现明细
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Financial management', path: '/finance/index'},//财务管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Financial management', path: '/finance/index'} // 财务管理
+          ]
+        }
       },
       {
         path: '/finance/withdraw-add',
         component: _import('finance/withdraw-add'),
         name: 'finance_withdraw-add',
         meta: {
-          title: 'Withdraw',//我要提现
+          title: 'Withdraw', // 我要提现
           highLight: '/finance/withdraw',
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Financial management', path: '/finance/index'},//财务管理
-            {title: 'Withdrawal details', path: '/finance/withdraw'},//提现明细
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Financial management', path: '/finance/index'}, // 财务管理
+            {title: 'Withdrawal details', path: '/finance/withdraw'} // 提现明细
+          ]
+        }
       },
       {
         path: '/finance/dec-list',
@@ -470,9 +585,9 @@ export const constantRouterMap = [
           title: '报单订货单列表',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Financial management', path: '/finance/index'},
-          ],
-        },
+            {title: 'Financial management', path: '/finance/index'}
+          ]
+        }
       },
       {
         path: '/finance/transfer-list',
@@ -482,9 +597,9 @@ export const constantRouterMap = [
           title: 'Transfer',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Financial management', path: '/finance/index'},
-          ],
-        },
+            {title: 'Financial management', path: '/finance/index'}
+          ]
+        }
       },
       {
         path: '/finance/transfer-add',
@@ -495,9 +610,9 @@ export const constantRouterMap = [
           highLight: '/finance/transfer-list',
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'},
-            {title: 'Financial management', path: '/finance/index'},
-          ],
-        },
+            {title: 'Financial management', path: '/finance/index'}
+          ]
+        }
       },
       {
         path: '/finance/recharge',
@@ -507,9 +622,9 @@ export const constantRouterMap = [
           title: 'Recharge details', // 充值明细
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'}, // 首页
-            {title: 'financial management', path: '/finance/index'}, // 财务管理
-          ],
-        },
+            {title: 'financial management', path: '/finance/index'} // 财务管理
+          ]
+        }
       },
       {
         path: '/finance/recharge-add',
@@ -521,10 +636,10 @@ export const constantRouterMap = [
           breadcrumb: [
             {title: 'Dashboard', path: '/dashboard/index'}, // 首页
             {title: 'financial management', path: '/finance/index'}, // 财务管理
-            {title: 'Recharge details', path: '/finance/recharge'},
-          ],
-        },
-      },
+            {title: 'Recharge details', path: '/finance/recharge'}
+          ]
+        }
+      }
     ]
   },
   {
@@ -537,26 +652,26 @@ export const constantRouterMap = [
         component: _import('config/receive-address-list'),
         name: 'config_receive-address-list',
         meta: {
-          title: 'Shipping Address',//收货地址管理
+          title: 'Shipping Address', // 收货地址管理
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Setting', path: '/config/base'},//设置
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Setting', path: '/config/base'} // 设置
+          ]
+        }
       },
       {
         path: '/config/receive-address-add',
         component: _import('config/receive-address-edit'),
         name: 'config_receive-address-add',
         meta: {
-          title: 'Add shipping address',//添加收货地址
+          title: 'Add shipping address', // 添加收货地址
           highLight: '/config/receive-address-list',
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Setting', path: '/config/base'},//设置
-            {title: 'Shipping Address', path: '/config/receive-address-list'},//收货地址管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Setting', path: '/config/base'}, // 设置
+            {title: 'Shipping Address', path: '/config/receive-address-list'} // 收货地址管理
+          ]
+        }
       },
       {
         path: '/config/receive-address-edit/:id',
@@ -566,15 +681,55 @@ export const constantRouterMap = [
           title: 'Edit address',
           highLight: '/config/receive-address-list',
           breadcrumb: [
-            {title: 'Dashboard', path: '/dashboard/index'},//首页
-            {title: 'Setting', path: '/config/base'},//设置
-            {title: 'Shipping Address', path: '/config/receive-address-list'},//收货地址管理
-          ],
-        },
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Setting', path: '/config/base'}, // 设置
+            {title: 'Shipping Address', path: '/config/receive-address-list'} // 收货地址管理
+          ]
+        }
       },
 
+      {
+        path: '/config/ba-receive-address-list',
+        component: _import('config/ba-receive-address-list'),
+        name: 'ba-receive-address-list',
+        meta: {
+          title: 'Shipping Address', // 收货地址管理
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Setting', path: '/config/base'} // 设置
+          ]
+        }
+      },
+      {
+        path: '/config/ba-receive-address-add',
+        component: _import('config/ba-receive-address-edit'),
+        name: 'ba-receive-address-add',
+        meta: {
+          title: 'Add Shipping Address', // 添加收货地址
+          highLight: '/config/ba-receive-address-list',
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Setting', path: '/config/base'}, // 设置
+            {title: 'Shipping Address', path: '/config/ba-receive-address-list'} // 收货地址管理
+          ]
+        }
+      },
+      {
+        path: '/config/ba-receive-address-edit/:id',
+        component: _import('config/ba-receive-address-edit'),
+        name: 'ba-receive-address-edit',
+        meta: {
+          title: 'Edit Address',
+          highLight: '/config/ba-receive-address-list',
+          breadcrumb: [
+            {title: 'Dashboard', path: '/dashboard/index'}, // 首页
+            {title: 'Setting', path: '/config/base'}, // 设置
+            {title: 'Shipping Address', path: '/config/ba-receive-address-list'} // 收货地址管理
+          ]
+        }
+      }
     ]
-  },
+  }
 ]
 
 export default new Router({

+ 5 - 2
frontendEle/src/utils/baseInfo.js

@@ -54,7 +54,10 @@ const baseInfo = {
   },
   siteTitle(){
     return this.get('siteTitle')
-  }
+  },
+  whetherBA() {
+    return this.get('whetherBA');
+  },
 }
 
-export default baseInfo
+export default baseInfo

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

@@ -1,7 +1,7 @@
 const APP_NAME = '奖金结算系统'
 const SERVER_API_DOMAIN = '16.163.228.151'
 const SERVER_API_HTTP_TYPE = 'http://'
-const SERVER_API_PORT = ':8033' // ':8102'
+const SERVER_API_PORT = ':8033'  // ':8102'
 const SERVER_API_VERSION = 'v1'
 const REQUEST_URL = `${SERVER_API_HTTP_TYPE}${SERVER_API_DOMAIN}${SERVER_API_PORT}/${SERVER_API_VERSION}/`
 const WEBSOCKET_HOST = 'ws://127.0.0.1:9512'

+ 4 - 1
frontendEle/src/utils/network.js

@@ -101,6 +101,7 @@ const network = {
           userInfo.userId(response.ID)
           userInfo.userName(response.USER_NAME)
           userInfo.userEmail(response.EMAIL)
+          userInfo.userIdentity(response.identity)
           userInfo.baseData({AVATAR: response.AVATAR,VERIFIED: response.VERIFIED,DEC_LV: response.DEC_LV,EMP_LV: response.EMP_LV,PROVINCE: response.PROVINCE,CITY: response.CITY,COUNTY: response.COUNTY})
           // 成功
           resolve(response)
@@ -115,8 +116,10 @@ const network = {
   },
   getBaseInfo () {
     let promise = new Promise((resolve, reject) => {
+      // 区分BA会员或者正式会员
+      let router = userInfo.userIdentity() === 'user' ? `site/base-info` : `site/ba-base-info`;
       updateToken(function (accessToken) {
-        axiosObj.get(`site/base-info`, {
+        axiosObj.get(router, {
           headers: {
             'Authorization': ACCESS_TOKEN_PREFIX + accessToken,
           }

+ 10 - 0
frontendEle/src/utils/userInfo.js

@@ -68,6 +68,16 @@ const userInfo = {
     }
     localStorage.setItem('userEmail', arg[0])
   },
+  userIdentity (...arg) {
+    if (arg.length === 0) {
+      return localStorage.getItem('identity')
+    }
+    if (arg[0] === '') {
+      localStorage.removeItem('identity')
+      return
+    }
+    localStorage.setItem('identity', arg[0])
+  },
   accessToken (...arg) {
     if (arg.length === 0) {
       return localStorage.getItem('accessToken')

+ 149 - 0
frontendEle/src/views/config/ba-receive-address-edit.vue

@@ -0,0 +1,149 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <el-form ref="form" :model="form" label-width="180px" style="width: 500px;">
+        <el-form-item>
+          <template slot="label">
+            <span class="text-danger">*</span>
+            Consignee<!-- 收货人 -->
+          </template>
+          <el-input v-model="form.consignee"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            <span class="text-danger">*</span>
+            Phone Number<!-- 手机号 -->
+          </template>
+          <el-input v-model="form.mobile"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            <span class="text-danger">*</span>
+            City
+          </template>
+          <el-input v-model="form.cityName"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            <span class="text-danger">*</span>
+            Local Government Area
+          </template>
+          <el-input v-model="form.lgaName"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            <span class="text-danger">*</span>
+            State<!-- 地区 -->
+          </template>
+          <el-select v-model="form.areaSelected">
+            <el-option v-for="(item,index) in regionData" :key="index" :label="item.label" :value="item.value"></el-option>
+          </el-select>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            <span class="text-danger">*</span>
+            Detailed Address<!-- 详细地址 -->
+          </template>
+          <el-input v-model="form.address"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Default<!-- 是否默认 -->
+          </template>
+          <el-switch v-model="form.isDefault" ></el-switch>
+        </el-form-item>
+        <el-form-item>
+          <el-button type="primary" @click="onSubmit" :loading="submitButtonStat">Confirm<!-- 确认 --></el-button>
+        </el-form-item>
+      </el-form>
+    </div>
+  </div>
+</template>
+
+<script>
+import store from '@/utils/vuexStore'
+import network from '@/utils/network'
+import tool from '@/utils/tool'
+import userInfo from '@/utils/userInfo'
+
+export default {
+  name: 'ba-receive-address-edit',
+  mounted () {
+    if (this.$route.name === 'ba-receive-address-add') {
+      this.loading = false
+    } else {
+      this.getData()
+    }
+  },
+  data () {
+    return {
+      regionData: store.state.regionInfo.regionData,
+      form: {
+        consignee: '',
+        mobile: '',
+        areaSelected: '',
+        lgaName: '',
+        cityName: '',
+        address: '',
+        isDefault: false,
+      },
+      loading: true,
+      submitButtonStat: false,
+    }
+  },
+  methods: {
+    onSubmit () {
+      this.submitButtonStat = true
+      let path = 'config/ba-receive-address-add'
+      let postData = {
+        consignee: this.form.consignee,
+        mobile: this.form.mobile,
+        province: this.form.areaSelected ? this.form.areaSelected : '',
+        lgaName: this.form.lgaName,
+        cityName: this.form.cityName,
+        address: this.form.address,
+        isDefault: this.form.isDefault,
+      }
+      if (this.$route.name === 'ba-receive-address-edit'){
+        path = 'config/ba-receive-address-edit'
+        postData = {
+          id: this.$route.params.id,
+          consignee: this.form.consignee,
+          mobile: this.form.mobile,
+          province: this.form.areaSelected ? this.form.areaSelected : '',
+          lgaName: this.form.lgaName,
+          cityName: this.form.cityName,
+          address: this.form.address,
+          isDefault: this.form.isDefault,
+        }
+      }
+      return network.postData(path, postData).then(response => {
+        this.$message({
+          message: response,
+          type: 'success'
+        })
+        this.submitButtonStat = false
+        this.$router.go(-1)
+      }).catch(() => {
+        this.submitButtonStat = false
+      })
+    },
+    getData () {
+      network.getData(`config/ba-receive-address-one/${this.$route.params.id}`).then(response => {
+        this.form.consignee = response.CONSIGNEE
+        this.form.mobile = response.MOBILE
+        this.form.areaSelected = response.PROVINCE
+        this.form.lgaName = response.LGA_NAME
+        this.form.cityName = response.CITY_NAME
+        this.form.address = response.ADDRESS
+        this.form.isDefault = response.IS_DEFAULT === '1'
+        this.loading = false
+      })
+    },
+  }
+}
+</script>
+
+<style scoped>
+
+</style>

+ 171 - 0
frontendEle/src/views/config/ba-receive-address-list.vue

@@ -0,0 +1,171 @@
+<template>
+    <div v-loading="loading">
+        <div class="white-box">
+            <el-table class="table-box" ref="multipleTable" :data="tableData" stripe style="width: 100%;">
+            <el-table-column label="Consignee" prop="CONSIGNEE" width="150"></el-table-column><!-- 收货人 -->
+            <el-table-column label="Phone Number" prop="MOBILE" width="150"></el-table-column><!-- 手机号码 -->
+            <el-table-column label="Address" prop="ADDRESS" ></el-table-column><!-- 详细地址 -->
+            <el-table-column label="City" prop="CITY_NAME" width="150"></el-table-column>
+            <el-table-column label="Local Government Area" prop="LGA_NAME" width="180"></el-table-column>
+            <el-table-column label="State" prop="PROVINCE_NAME" width="150"></el-table-column>
+            <el-table-column label="Default" width="100">
+                <template slot-scope="scope">
+                    {{scope.row.IS_DEFAULT === '1' ? 'YES' : 'NO'}}<!-- 是:否 -->
+                </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 command="edit" @click.native="handleUpdate(scope.row)">Edit</el-dropdown-item><!-- 编辑 -->
+                            <el-dropdown-item command="edit" @click.native="handleDelete(scope.row)">Delete</el-dropdown-item><!-- 删除 -->
+                        </el-dropdown-menu>
+                    </el-dropdown>
+                </template>
+            </el-table-column>
+            </el-table>
+            <div class="white-box-footer">
+                <el-button type="primary" size="small" @click="handleAdd">Add Shipping Address</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 Pagination from '@/components/Pagination'
+
+    export default {
+        name: 'ba-receive-address-list',
+        components: {
+            Pagination
+        },
+        mounted() {
+            this.loading = false;
+            this.getData();
+        },
+        data() {
+            return {
+                tableData: [],
+                loading: true,
+                multipleSelection: [],
+                currentPage: 1,
+                totalPages: 1,
+                totalCount: 1,
+                pageSize: 20,
+                tool: tool,
+                filterData: null,
+                filterStatus: 'ALL',
+                periodNum: null,
+                periodNums: null,
+                allType:{
+                    ORDER: '订货店补',
+                    TRANS: '转账店补',
+                    PROD: '产品补贴',
+                    TOOL: '工具流补贴'
+                },
+            }
+        },
+        methods: {
+            handleCurrentChange(page) {
+                this.getData(page, this.pageSize)
+            },
+            handleSizeChange(pageSize) {
+                this.getData(this.currentPage, pageSize)
+            },
+            getData(page, pageSize) {
+                let vueObj = this
+                network.getPageData(this, 'config/ba-receive-address-list', page, pageSize, {}, function (response) {
+                    vueObj.tableData = response.list
+                })
+            },
+            handleAdd() {
+                this.$router.push({path: `/config/ba-receive-address-add`})
+            },
+            handleUpdate (row) {
+                this.$router.push({path: `/config/ba-receive-address-edit/${row.ID}`})
+            },
+            handleDelete (row) {
+                this.$confirm(`Are you sure you want to delete the selected data?`, 'Hint', {//`确定要删除所选数据吗?`, '提示'
+                    confirmButtonText: 'Confirm',//确定
+                    cancelButtonText: 'Cancel',//取消
+                    type: 'warning'
+                }).then(() => {
+                    let selectedIds = [row.ID]
+                        return network.postData(`config/ba-receive-address-delete`, {selected: selectedIds})
+                }).then(response => {
+                    this.$message({
+                        message: response,
+                        type: 'success'
+                    })
+
+                    this.getData(this.currentPage, this.pageSize)
+                }).catch(response => {
+                    this.$message({
+                        message: response,
+                        type: 'error'
+                    })
+                })
+            },
+        }
+    }
+</script>
+
+<style scoped>
+  .leo-filter {
+    padding: 0 0 15px 0;
+  }
+
+  .leo-filter .filter-hidden {
+    display: none;
+  }
+
+  .filter-item {
+    margin-right: 10px;
+  }
+
+  @media (min-width: 768px) {
+    .leo-filter {
+    }
+
+    .leo-filter .filter-item {
+      display: inline-block;
+      max-width: 200px;
+    }
+
+    .leo-filter .filter-item.filter-date-month-picker {
+      display: inline-block;
+      max-width: 220px;
+    }
+
+    .leo-filter .filter-item.filter-date-range-picker {
+      display: inline-block;
+      max-width: 380px;
+    }
+
+    .leo-filter .filter-item.filter-filter-btn {
+      height: 38px;
+      width: 80px;
+    }
+
+    .leo-filter .filter-hidden {
+      display: none;
+    }
+  }
+
+  .table-box .el-form-item__label {
+    width: 100px;
+    color: #99a9bf;
+  }
+
+  .table-box .el-form-item {
+    width: 30%;
+    margin-right: 0;
+    margin-bottom: 0;
+  }
+</style>

+ 230 - 0
frontendEle/src/views/dashboard/ba-index.vue

@@ -0,0 +1,230 @@
+<template>
+  <div v-loading="loading">
+    <div>
+      <div class="welcome" :style="getEmpBg()">
+        <h1>Welcome,{{userName}} <!--欢迎您-->
+
+        <b v-if="verified==='0'" class="text-danger">You do not have real name authentication, please log in the member system to complete the member information and upload ID card.</b><!--您未实名认证,请登录商城系统完善会员资料并上传身份证-->
+        </h1>
+        <el-row :gutter="0" class="wel-info">
+          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
+            <el-row :gutter="10">
+              <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="12">Current System Time:{{nowDateTime}}</el-col> <!--当前系统时间-->
+            </el-row>
+          </el-col>
+        </el-row>
+      </div>
+      <div style="display: none;">
+        <el-button type="success" @click="go('/user/ba-index')">Personal Information</el-button><!--个人资料-->
+      </div>
+    </div>
+    <el-carousel trigger="click" :height="bannerHeight+'px'">
+      <el-carousel-item v-for="(item,key) in slides" :key="key">
+        <template v-if="item.TYPE==='1'">
+          <router-link :to="`/shop/ba-index`" target="_self" class="islide">
+            <img ref="bannerHeight" :src="imageArticle(item.IMAGE)" alt="" @load="imgLoad">
+          </router-link>
+        </template>
+        <template v-else>
+          <router-link :to="`/article/detail/${item.CONTENT}`" target="_blank" class="islide">
+            <img ref="bannerHeight" :src="imageArticle(item.IMAGE)" alt="" @load="imgLoad">
+          </router-link>
+        </template>
+      </el-carousel-item>
+    </el-carousel>
+
+    <el-row :gutter="10" class="news-c">
+      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" v-for="(item,key) in news" :key="key">
+        <el-card class="box-card">
+          <div slot="header" class="clearfix">
+            <span>{{item.CATE_NAME}}</span>
+            <el-button type="text" class="box-card-more">
+              <router-link :to="`/article/list/${item.ID}`">more+</router-link>
+            </el-button>
+          </div>
+          <div v-for="(o,k) in item.LISTS" :key="k" class="text item" v-if="item.LISTS.length>0">
+            <router-link :to="`/article/detail/${o.ID}`" :title="o.TITLE">{{sub_str(o.TITLE)}}</router-link>
+            <span>{{tool.formatDate(o.CREATED_AT,false)}}</span>
+          </div>
+          <div v-if="item.LISTS.length==0">No content</div><!--暂无内容-->
+        </el-card>
+      </el-col>
+    </el-row>
+  </div>
+</template>
+
+<script>
+import network from '@/utils/network'
+import tool from '@/utils/tool'
+import baseInfo from '@/utils/baseInfo'
+import userInfo from '@/utils/userInfo'
+import countUp from 'vue-countup-v2'
+
+export default {
+  name: 'dashboard_ba_index',
+  components: {
+    countUp
+  },
+  mounted () {
+    network.getData(`dashboard/ba-index`).then(response => {
+      this.slides = response.slides
+      this.news = response.news
+      this.periodNum = response.periodNum
+      this.loading = false
+      this.imgLoad()
+    })
+    this.calcTime()
+    window.addEventListener('resize', () => {
+      this.imgLoad()
+    }, false)
+  },
+  data () {
+    return {
+      loading: false,
+      tool: tool,
+      nowTime: tool.getTimestamp(),
+      userName: userInfo.userName(),
+      verified: userInfo.baseData().VERIFIED,
+      slides: [],
+      news: [],
+      periodNum: '',
+      bannerHeight: ''
+    }
+  },
+  computed: {
+    nowDateTime: function () {
+      return tool.formatDate(this.nowTime)
+    }
+  },
+  methods: {
+    getEmpIco () {
+      return require('@/assets/emp-ico-1.png')
+    },
+    getEmpBg () {
+      return 'backgroundImage:url(' + require('@/assets/emp-bg-1.png') + ')'
+    },
+    sub_str (str, len = 15) {
+      if (str) return str.slice(0, len)
+    },
+    calcTime () {
+      let obj = this
+      setInterval(function () {
+        obj.nowTime += 1
+      }, 1000)
+    },
+    go: function (url) {
+      this.$router.push(url)
+    },
+    imgLoad () {
+      let _this = this
+      if (_this.$refs.bannerHeight) {
+        _this.$nextTick(function () {
+          _this.bannerHeight = _this.$refs.bannerHeight[0].height
+        })
+      }
+    },
+    imageArticle (imageUrl) {
+      return tool.getArImage(imageUrl, '/files/')
+    }
+  }
+}
+</script>
+
+<style scoped>
+  h1 {
+    margin-top: 0
+  }
+
+  .welcome {
+    padding-bottom: 10px;
+    background-repeat: no-repeat;
+    background-position: right top;
+  }
+
+  .wel-info {
+    line-height: 36px;
+  }
+
+  .wel-info img {
+    vertical-align: middle;
+  }
+
+  .news-c .el-col .box-card {
+    margin-top: 10px;
+  }
+
+  .news-c .el-col:nth-child(3n+1) .box-card {
+    border-bottom: 4px solid #f34d14;
+  }
+
+  .news-c .el-col:nth-child(3n+2) .box-card {
+    border-bottom: 4px solid #27a2d3;
+  }
+
+  .news-c .el-col:nth-child(3n+3) .box-card {
+    border-bottom: 4px solid #1bbc61;
+  }
+
+  .box-card-more {
+    float: right;
+    padding: 3px 10px;
+    border: 1px solid #ddd;
+    border-radius: 10px;
+  }
+
+  .box-card-more a {
+    color: #666;
+  }
+
+  .box-card-more:hover {
+    border-color: #409EFF;
+  }
+
+  .box-card .item {
+    position: relative;
+    line-height: 30px;
+    padding-left: 10px;
+  }
+
+  .box-card .item:before {
+    content: '';
+    display: block;
+    width: 4px;
+    height: 4px;
+    background: #f60;
+    position: absolute;
+    left: 0px;
+    top: 14px;
+  }
+
+  .box-card .item:after {
+    content: '';
+    display: table;
+    clear: both;
+  }
+
+  .box-card .item a {
+    color: #333;
+    float: left;
+  }
+
+  .box-card .item a:hover {
+    color: #f60;
+  }
+
+  .box-card .item span {
+    float: right;
+    color: #999;
+    font-size: 12px;
+  }
+
+  .islide {
+    display: block;
+    text-align: center;
+  }
+
+  .islide img {
+    max-width: 100%;
+    max-height: 330px;
+  }
+</style>

+ 4 - 2
frontendEle/src/views/layout/layout.vue

@@ -175,6 +175,7 @@ export default {
       unreadMessage: null,
       tool: tool,
       siteTitle: '',
+      whetherBA: baseInfo.whetherBA(),
     }
   },
   computed: {
@@ -198,7 +199,7 @@ export default {
       } else {
         return false
       }
-    }
+    },
   },
   methods: {
     onMenu () {
@@ -235,7 +236,8 @@ export default {
       this.profileShow = !this.profileShow
     },
     onGo(url) {
-      this.$router.push(url)
+      let _url = !this.whetherBA ? url : '/user/ba-info';
+      this.$router.push(_url)
     },
     onLogout () {
       userInfo.clear()

+ 6 - 1
frontendEle/src/views/login/index.vue

@@ -64,6 +64,7 @@ export default {
       pageId: '',
       captchaUrl: '',
       isLoginVerify: false,
+      baseInfo: baseInfo,
     }
   },
   beforeCreate () {
@@ -129,7 +130,11 @@ export default {
         if (response > 0) {
           store.state.baseInfo.messageUnreadNum = response
         }
-        this.$router.push('dashboard/index')
+        if (!this.baseInfo.whetherBA()) {
+          this.$router.push('dashboard/index')
+        } else {
+          this.$router.push('dashboard/ba-index')
+        }
       }).catch(error => {
         console.log(error);
         this.refreshLoginVerifyStatus();

+ 143 - 0
frontendEle/src/views/shop/ba-dec-order-list.vue

@@ -0,0 +1,143 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <el-table class="withdraw-table" :data="tableData" :max-height="maxHeight" style="width: 100%;" :span-method="objectSpanMethod">
+        <el-table-column width="120" label="Product code" prop="SKU_CODE"></el-table-column><!--商品编号-->
+        <el-table-column width="120" label="Product Name" prop="GOODS_TITLE"></el-table-column><!--商品名称-->
+        <el-table-column width="120" label="Product Price" prop="REAL_PRICE"></el-table-column><!--报单金额-->
+        <el-table-column width="120" label="Product BV" prop="REAL_PV"></el-table-column><!--报单BV-->
+        <el-table-column width="120" label="Qty" prop="BUY_NUMS"></el-table-column><!--数量-->
+        <el-table-column width="120" label="Tax rate" prop="TAX_RATE"></el-table-column><!--税率-->
+        <el-table-column width="120" label="Tax" prop="TAX_AMOUNT"></el-table-column><!--税额-->
+        <el-table-column width="120" label="Total Price" prop="TOTAL_AMOUNT"></el-table-column><!--总计金额-->
+        <el-table-column width="120" label="Code" prop="DEC_SN"></el-table-column><!--报单编号-->
+        <el-table-column width="120" label="Order code" prop="ORDER_SN"></el-table-column><!--订单编号-->
+        <el-table-column width="120" label="Member code" prop="USER_NAME"></el-table-column><!--会员编号-->
+        <el-table-column width="120" label="Member name" prop="REAL_NAME"></el-table-column><!--会员姓名-->
+        <el-table-column width="150" label="Shipping Address" prop="ADDRESS"></el-table-column><!--收货地址-->
+        <el-table-column width="120" label="Status" prop="STATUS"></el-table-column><!--状态-->
+        <el-table-column width="150" label="Created time" prop="CREATED_AT"></el-table-column >
+        <el-table-column width="120" label="Action"><!--操作-->
+          <template slot-scope="scope">
+            <el-button type="primary" size="small" @click.native="handleOrderExportPDF(scope.row.ORDER_SN)">Export PDF</el-button><!--导出PDF-->
+          </template>
+        </el-table-column>
+      </el-table>
+      <div class="white-box-footer">
+          <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 Pagination from '@/components/Pagination'
+import {SERVER_API_HTTP_TYPE, SERVER_API_DOMAIN,SERVER_API_PORT} from '@/utils/config'
+export default {
+  name: 'dec-order-list',
+  components: {Pagination},
+  mounted () {
+    this.getData()
+  },
+  data () {
+    return {
+      loading: false,
+      form: {},
+      tableData: null,
+      list: null,
+      currentPage: 1,
+      totalPages: 1,
+      totalCount: 1,
+      pageSize: 20,
+      tool: tool,
+      // 订单号判断
+      spanArr: [], // 用于存放需要合并的行的个数
+      pos: 0, // 记录spanArr数组的下标
+      maxHeight: tool.getTableHeight()
+    }
+  },
+  methods: {
+    objectSpanMethod (obj) {
+      if (obj.columnIndex >= 7) {
+      // ⼆维数组存储的数据取出
+        let _row = this.spanArr[obj.rowIndex]
+        let _col = _row > 0 ? 1 : 0
+        return {
+          rowspan: _row,
+          colspan: _col
+        }
+      } else {
+        return false
+      }
+    },
+    getSpanArr (orderList) { // 传⼊你的列表数据
+      this.pos = 0
+      orderList.forEach((item, index) => {
+        // 判断是否是第⼀项
+        if (index === 0) {
+          this.spanArr.push(1)
+          this.pos = 0
+        } else {
+          // 不是第⼀项时,就根据标识去存储
+          if ( // orderSn,createdAt...是你的第⼀个数据、第⼆个数据...
+            orderList[index].DEC_SN === orderList[index - 1].DEC_SN &&
+            orderList[index].ORDER_SN === orderList[index - 1].ORDER_SN &&
+            orderList[index].USER_NAME === orderList[index - 1].USER_NAME &&
+            orderList[index].REAL_NAME === orderList[index - 1].REAL_NAME &&
+            orderList[index].CON_USER_NAME === orderList[index - 1].CON_USER_NAME &&
+            orderList[index].P_CALC_MONTH === orderList[index - 1].P_CALC_MONTH
+          ) {
+            // 查找到符合条件的数据时每次要把之前存储的数据+1
+            this.spanArr[this.pos] += 1
+            this.spanArr.push(0)
+          } else {
+            // 没有符合的数据时,要记住当前的index
+            this.spanArr.push(1)
+            this.pos = index
+          }
+        }
+      })
+    },
+    handleCurrentChange (page) {
+      this.getData(page, this.pageSize)
+    },
+    handleSizeChange (pageSize) {
+      this.getData(this.currentPage, pageSize)
+    },
+    getData (page, pageSize) {
+      this.spanArr = []
+      this.pos = 0
+      let _this = this
+      network.getPageData(_this, 'shop/ba-dec-order-list', page, pageSize, {type: this.type}, function (response) {
+        _this.loading = false
+        _this.list = response.list
+        let settingObj = _this.list
+
+        _this.tableData = Object.keys(settingObj).map(key => {
+          return settingObj[key] // 把每个对象返回出去生成一个新的数组中相当于0:{id:1}
+        })
+        _this.getSpanArr(_this.tableData)
+      })
+    },
+    // 导出PDF订单
+    handleOrderExportPDF (orderSn) {
+      network.getData(`shop/ba-dec-order-export/${orderSn}`).then(response => {
+        let { fileUrl, targetName } = response
+        let downloadElement = document.createElement('a')
+        downloadElement.target = '_blank'
+        downloadElement.href = SERVER_API_HTTP_TYPE + SERVER_API_DOMAIN + SERVER_API_PORT + '/' + fileUrl
+        // 下载后文件名
+        downloadElement.download = targetName
+        // 点击下载
+        downloadElement.click()
+      })
+    }
+  }
+}
+</script>
+
+<style scoped>
+
+</style>

+ 134 - 0
frontendEle/src/views/shop/ba-order-list.vue

@@ -0,0 +1,134 @@
+<template>
+    <div v-loading="loading">
+        <div class="white-box">
+            <el-table class="withdraw-table" :data="tableData" :max-height="maxHeight" style="width: 100%;" :span-method="objectSpanMethod">
+                <el-table-column width="120" label="Product Code" prop="SKU_CODE"></el-table-column><!--商品编号-->
+                <el-table-column width="120" label="Product Name" prop="GOODS_TITLE"></el-table-column><!--商品名称-->
+                <el-table-column width="120" label="Product Price" prop="REAL_PRICE"></el-table-column><!--商品价格-->
+                <el-table-column width="120" label="Qty" prop="BUY_NUMS"></el-table-column><!--数量-->
+                <el-table-column width="120" label="Tax Rate" prop="TAX_RATE"></el-table-column><!--税率-->
+                <el-table-column width="120" label="Tax" prop="TAX_AMOUNT"></el-table-column><!--税额-->
+                <el-table-column width="120" label="Total Price" prop="TOTAL_AMOUNT"></el-table-column><!--税额-->
+                <el-table-column width="120" label="Order Code" prop="SN"></el-table-column><!--订单编号-->
+                <el-table-column width="120" label="Member Code" prop="USER_NAME"></el-table-column><!--会员编号-->
+                <el-table-column width="120" label="Member Name" prop="REAL_NAME"></el-table-column><!--会员姓名-->
+                <el-table-column width="130" label="Recipient name" prop="CONSIGNEE"></el-table-column><!--收货人-->
+                <el-table-column width="120" label="Phone Number" prop="MOBILE"></el-table-column><!--收货电话-->
+                <el-table-column width="150" label="Shipping Address" prop="FULL_ADDRESS"></el-table-column><!--收货地址-->
+                <el-table-column width="120" label="Created Name" prop="CREATE_USER"></el-table-column><!--创建人-->
+                <el-table-column width="120" label="Created time" prop="CREATED_AT"></el-table-column><!--下单时间-->
+                <el-table-column width="150" label="Payment" prop="PAY_TYPE"></el-table-column><!--支付方式-->
+                <el-table-column width="120" label="Pay time" prop="PAY_AT"></el-table-column><!--支付时间-->
+                <el-table-column width="120" label="Pay Status" prop="STATUS"></el-table-column><!--支付状态-->
+            </el-table>
+            <div class="white-box-footer">
+                <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 Pagination from '@/components/Pagination'
+
+export default {
+    name: "ba-order-list",
+    components: {
+        Pagination
+    },
+    mounted() {
+        this.getData();
+    },
+    data() {
+        return {
+            loading: false,
+            form:{},
+            tableData:null,
+            list: null,
+            currentPage: 1,
+            totalPages: 1,
+            totalCount: 1,
+            pageSize: 20,
+            tool: tool,
+            spanArr: [], // 用于存放需要合并的行的个数
+            pos: 0, // 记录spanArr数组的下标
+            maxHeight: tool.getTableHeight(),
+        }
+    },
+    methods: {
+        handleCurrentChange (page) {
+            this.getData(page, this.pageSize)
+        },
+        handleSizeChange (pageSize) {
+            this.getData(this.currentPage, pageSize)
+        },
+        // 列表页合并
+        objectSpanMethod(obj) {
+            if (obj.columnIndex >= 7) {
+                // ⼆维数组存储的数据取出
+                let _row = this.spanArr[obj.rowIndex];
+                let _col = _row > 0 ? 1 : 0;
+                return {
+                    rowspan: _row,
+                    colspan: _col,
+                };
+            } else {
+                return false;
+            }
+        },
+        // 列表页合并
+        getSpanArr(orderList) {
+            this.pos = 0;
+            orderList.forEach((item, index) => {
+                //判断是否是第⼀项
+                if (index === 0) {
+                    this.spanArr.push(1);
+                    this.pos = 0;
+                } else {
+                    //不是第⼀项时,就根据标识去存储
+                    if (
+                        orderList[index].ORDER_SN === orderList[index - 1].ORDER_SN &&
+                        orderList[index].USER_NAME === orderList[index - 1].USER_NAME &&
+                        orderList[index].REAL_NAME === orderList[index - 1].REAL_NAME &&
+                        orderList[index].CONSIGNEE === orderList[index - 1].CONSIGNEE &&
+                        orderList[index].MOBILE === orderList[index - 1].MOBILE &&
+                        orderList[index].PAY_AT === orderList[index - 1].PAY_AT &&
+                        orderList[index].STATUS === orderList[index - 1].STATUS &&
+                        orderList[index].PAY_TYPE === orderList[index - 1].PAY_TYPE &&
+                        orderList[index].CREATED_AT === orderList[index - 1].CREATED_AT
+                    ) {
+                        // 查找到符合条件的数据时每次要把之前存储的数据+1
+                        this.spanArr[this.pos] += 1;
+                        this.spanArr.push(0);
+                    } else {
+                        // 没有符合的数据时,要记住当前的index
+                        this.spanArr.push(1);
+                        this.pos = index;
+                    }
+                }
+            });
+        },
+        // 查询列表数据
+        getData(page, pageSize) {
+            this.spanArr = [];
+            this.pos = 0;
+            let _this = this
+            network.getPageData(_this, 'shop/ba-order-list', page, pageSize, {type: this.type}, function (response) {
+                _this.loading = false;
+                _this.list = response.list;
+                let settingObj = _this.list;
+                _this.tableData = Object.keys(settingObj).map(item => {
+                    //把每个对象返回出去生成一个新的数组中相当于0:{id:1}
+                    return settingObj[item];
+                });
+                _this.getSpanArr(_this.tableData);
+            });
+        },
+    }
+}
+</script>
+<style scoped>
+
+</style>

+ 203 - 0
frontendEle/src/views/shop/ba-product-list.vue

@@ -0,0 +1,203 @@
+<template>
+    <div v-loading="loading">
+        <div class="white-box">
+            <el-table v-if="numList.length > 0" :max-height="maxHeight" class="withdraw-table" :data="tableData" stripe style="width: 100%;" ref="multipleTable" @selection-change="handleSelectionChange">
+              <el-table-column type="selection" width="55"></el-table-column>
+              <el-table-column label="Product Name" prop="GOODS_NAME"></el-table-column><!--商品名称-->
+              <el-table-column label="Product Picture"><!--图片-->
+                  <template slot-scope="scope">
+                      <el-image style="width: 100px; height: 100px" :src="tool.getArImage(scope.row.COVER, '/files/')" :preview-src-list="[tool.getArImage(scope.row.COVER, '/files/')]"></el-image>
+                  </template>
+              </el-table-column>
+
+              <el-table-column label="Product Price" prop="SELL_PRICE"><!--商品价格-->
+                  <template slot-scope="scope">
+                      <span>{{ Math.round(scope.row.SELL_PRICE * 100) / 100 }}</span>
+                  </template>
+              </el-table-column>
+
+              <el-table-column label="Tax rate" prop="TAX_RATE"><!--税率-->
+                  <template slot-scope="scope">
+                      <span>{{ Math.round(scope.row.TAX_RATE * 100) / 100 }}</span>
+                  </template>
+              </el-table-column>
+
+              <el-table-column label="Tax"><!--税额-->
+                  <template slot-scope="scope">
+                      <span>{{ Math.round((scope.row.SELL_PRICE - scope.row.SELL_PRICE / (1 + scope.row.TAX_RATE / 100)) * 100) / 100 }}</span>
+                  </template>
+              </el-table-column>
+
+              <el-table-column label="Inventory" prop="STORE_NUMS"></el-table-column><!--库存-->
+
+              <el-table-column label="Qty"  width="155"><!--数量-->
+                  <template slot-scope="scope">
+                      <el-input-number size="mini" v-model="numList[scope.$index]" :min="0" :max="Number(scope.row.STORE_NUMS)" @change="(val)=>{handleInputNumber(val, scope.row)}"></el-input-number>
+                  </template>
+              </el-table-column>
+            </el-table>
+
+            <div class="white-box-footer">
+                <el-button type="primary" size="small" @click="goToAccounts()">Check Out</el-button><!--去结算-->
+                <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
+            </div>
+            <div class='flex data' style="line-height: 35px; font-size: 14px;margin-top: 20px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 0 15px;">
+              <div style="margin-right: 2rem;">Price:₦ {{ sell_price_sum }}</div><!--商品价格-->
+              <div>Tax:₦ {{ tax_sum }}</div><!--商品税额-->
+            </div>
+        </div>
+    </div>
+</template>
+
+<script>
+import network from '@/utils/network'
+import tool from '@/utils/tool'
+import Pagination from '@/components/Pagination'
+
+export default {
+    name: "ba-product-list",
+    components: {
+        Pagination
+    },
+    async created() {
+        await this.getData()
+    },
+    data() {
+        return {
+            loading: false,
+            num:1,
+            form:{},
+            tableData:[],
+            list: [],
+            tool: tool,
+            currentPage: 1,
+            totalPages: 1,
+            totalCount: 1,
+            pageSize: 20,
+            multipleSelection: [],
+            is_go_order: true,
+            numList: [],
+            selectLock: false,
+            maxHeight: tool.getTableHeight() - 35,
+            sell_price_sum: 0.00,
+            tax_sum: 0.00,
+        }
+    },
+    watch: {
+        '$route': function () {
+            this.getData()
+        },
+    },
+    methods: {
+        async getData (page, pageSize) {
+            let obj = this
+            await network.getPageData(this, `shop/ba-product-list`, page, pageSize, {}, function (response) {
+                obj.loading = false;
+                obj.currentPage = response.currentPage;
+                obj.list = response.list;
+                let settingObj=obj.list;
+                for (let i in settingObj) {
+                    obj.numList[i] = 1;
+                    settingObj[i].chose_num = 0;
+                }
+
+                obj.selectLock = true;
+                obj.tableData = Object.values(settingObj);
+                let pageList = obj.multipleSelection[obj.currentPage];
+                obj.$nextTick(function () {
+                    for(let i in obj.tableData){
+                        for( let j in  pageList) {
+                            if( pageList[j].ID === obj.tableData[i].ID ) {
+                                obj.numList[i] = pageList[j].chose_num;
+                                obj.tableData[i].chose_num = pageList[j].chose_num;
+                                break;
+                            }
+                        }
+                    }
+                    obj.selectLock = false;
+                })
+            })
+        },
+        goToAccounts() {
+            if (this.multipleSelection.length <= 0) {
+                this.$message.error('Please choose the products.')
+                return false
+            }
+
+            this.is_go_order = true;
+            setTimeout(() => {
+                if(this.is_go_order) {
+                    // 填充商品信息到购物车
+                    sessionStorage.setItem('order_goods', JSON.stringify(this.multipleSelection))
+                    this.$router.push({path: `/shop/ba-shopping-cart`});
+                }
+            })
+        },
+        handleSelectionChange(val) {
+            if( this.selectLock ) return;
+            let idx = -1,num;
+            for(let i in this.tableData){
+                for(let v in val){
+                    if(val[v].ID==this.tableData[i].ID){
+                        idx = i;
+                        num = this.numList[idx];
+                        val[v]["chose_num"] = num;
+                        break;
+                    }
+                }
+            }
+            this.multipleSelection[this.currentPage] = val;
+
+            // 计算统计
+            this.handleSureChange()
+        },
+        handleSureChange() {
+            if (this.multipleSelection.length > 0) {
+                let accumulatorSellPrice = 0, accumulatorPricePv = 0, accumulatorTax = 0;
+                this.multipleSelection.forEach(item => {
+                    item.forEach(accumulator => { accumulatorSellPrice += accumulator.SELL_PRICE * accumulator.chose_num * accumulator.DISCOUNT / 100; });
+                    item.forEach(accumulator => { accumulatorPricePv += Number(accumulator.PRICE_PV) * Number(accumulator.chose_num) * (Number(accumulator.DISCOUNT) / 100); });
+                    item.forEach(accumulator => { accumulatorTax += tool.calculateTax(Number(accumulator.SELL_PRICE), Number(accumulator.TAX_RATE), Number(accumulator.chose_num)); });
+                })
+
+                this.sell_price_sum = parseFloat(accumulatorSellPrice).toFixed(2);
+                this.price_pv_sum = parseFloat(accumulatorPricePv).toFixed(2);
+                this.tax_sum = parseFloat(accumulatorTax).toFixed(2);
+            } else {
+                this.sell_price_sum = 0.00;
+                this.price_pv_sum = 0.00;
+                this.tax_sum = 0.00;
+            }
+        },
+        handleInputNumber(val, row){
+            let pageList = this.multipleSelection[this.currentPage];
+            let selectStatus = false;
+            for(let i in pageList){
+                if( pageList[i].ID == row.ID ) {
+                    pageList[i].chose_num = val;
+                    selectStatus = true;
+                    break;
+                }
+            }
+
+            if( selectStatus ) {
+                this.multipleSelection[this.currentPage] = pageList;
+                // 计算统计
+                this.handleSureChange()
+            }
+        },
+        handleCurrentChange (page) {
+            this.getData(page, this.pageSize)
+        },
+        handleSizeChange (pageSize) {
+            this.getData(this.currentPage, pageSize)
+        },
+    }
+}
+</script>
+
+<style scoped>
+.flex{
+    display: flex;
+}
+</style>

+ 438 - 0
frontendEle/src/views/shop/ba-shopping-cart.vue

@@ -0,0 +1,438 @@
+<template>
+    <div v-loading="loading">
+        <div class="white-box">
+            <el-table :data="goods" style="width: 100%" show-summary :summary-method="getSummaries">
+                <el-table-column label="Product Name" prop="GOODS_NAME"></el-table-column><!--商品名称-->
+
+                <el-table-column label="Product Picture" ><!--图片-->
+                    <template slot-scope="scope">
+                        <el-image style="width: 100px; height: 100px" :src="tool.getArImage(scope.row.COVER, '/files/')" :preview-src-list="[tool.getArImage(scope.row.COVER, '/files/')]"></el-image>
+                    </template>
+                </el-table-column>
+
+                <el-table-column label="Product Price" prop="member_price"><!--商品价格-->
+                    <template slot-scope="scope">
+                        <span>{{ Math.round(scope.row.member_price * 100) / 100 }}</span>
+                    </template>
+                </el-table-column>
+
+                <el-table-column label="Tax Rate" prop="TAX_RATE"><!--税率-->
+                    <template slot-scope="scope">
+                        <span>{{ Math.round(scope.row.TAX_RATE * 100) / 100 }}</span>
+                    </template>
+                </el-table-column>
+
+                <el-table-column label="Tax" prop="tax_amount_plus"><!--税额-->
+                    <template slot-scope="scope">
+                        <span>{{ Math.round(scope.row.tax_amount_plus * 100) / 100 }}</span>
+                    </template>
+                </el-table-column>
+
+                <el-table-column label="Quantity" prop="chose_num"></el-table-column><!--数量-->
+
+                <el-table-column label="Total Amount" prop="member_price_plus"><!--合计金额-->
+                    <template slot-scope="scope">
+                        <span>{{ Math.round(scope.row.member_price_plus * 100) / 100 }}</span>
+                    </template>
+                </el-table-column>
+        </el-table>
+
+            <div class="address_box">
+                Please select the shipping address:	<!--  请选择收货地址 -->
+                <el-radio-group v-model="addressId" @change='choseAddress'>
+                    <div v-for="(item , index) in all_address" :key='index' class="address">
+                        <el-radio :label="item.ID" >
+                            Full Address:{{item.ADDRESS}}, {{item.CITY_NAME}}, {{item.LGA_NAME}}, {{item.PROVINCE_NAME}}<!-- 详细地址 -->
+                            Recipient Name:{{item.CONSIGNEE}}<!-- 收件人姓名 -->
+                            Phone Number:{{item.MOBILE}}<!-- 手机号码 -->
+                        </el-radio>
+                    </div>
+                    <div class="address">
+                        <el-radio label="100000000000000000">Self Pick-up</el-radio><!--自提-->
+                    </div>
+                </el-radio-group>
+            </div>
+
+            <div class="box address_box">
+                Total Orders:<!-- 订单合计 -->
+                <div class="sum">
+                    <div class="sum_box">
+                        <div>Freight</div><!-- 运费 -->
+                        <div>{{ pointFreight }} {{ unit }}</div>
+                    </div>
+                    <div class="sum_box">
+                        <div>Amount Paid</div><!-- 实付金额 -->
+                        <div>
+                            <span>{{ prefixSign }} {{ pointsSum }} {{ unit }}</span>
+                        </div>
+                    </div>
+                </div>
+          </div>
+
+            <div class="">
+                <el-button type="danger"  size="small" @click="cancelOrder()">Go Back</el-button>
+                <el-button type="primary" size="small" @click="goToAccounts()" :loading="submitButtonStat">Pay</el-button><!--去结算-->
+            </div>
+        </div>
+
+        <!-- payStack模态框 -->
+        <el-dialog title="Pay" v-if="visible" :visible.sync="visible" width="30%" v-loading="payStackLoading" :before-close="handleClose">
+            <section>
+                <div class="formcontainer">
+                    <el-divider></el-divider>
+                    <div class="container">
+                        <el-form :model="form">
+                            <el-form-item label="Email" label-width="100px" required>
+                                <el-input v-model="form.email" autocomplete="off"></el-input>
+                            </el-form-item>
+                            <el-form-item label="Amount" label-width="100px" required>
+                                <el-input v-model="form.amount" autocomplete="off" readonly></el-input>
+                            </el-form-item>
+                        </el-form>
+                    </div>
+                </div>
+            </section>
+            <paystack
+                :firstname="form.firstname"
+                :lastname="form.lastname"
+                :amount="form.amount * 100"
+                :email="form.email"
+                :metadata="form.metadata"
+                :currency="form.currency"
+                :paystackkey="form.publicKey"
+                :reference="reference"
+                :channels="channels"
+                :callback="processPayment"
+                :close="processClose"
+            >
+            <el-button type="primary" size="small">Pay</el-button>
+            </paystack>
+            <el-button type="danger" size="small" class="cancelButton" @click="handleClose">Cancel</el-button>
+    </el-dialog>
+
+        <!-- 倒计时页面 -->
+        <el-dialog title="Tips" :visible.sync="payDialog" :show-close="false" width="350px" :close="handleOrderList">
+            <el-result icon="success" title="the order is successful">
+                <template slot="extra">
+                    <span style="color: #008efa; font-size: 30px;">{{ countdown }}</span>
+                </template>
+            </el-result>
+        </el-dialog>
+    </div>
+</template>
+
+<script>
+import network from '@/utils/network';
+import tool from '@/utils/tool';
+import userInfo from '@/utils/userInfo';
+import store from '@/utils/vuexStore';
+import { PAY_STACK_PUBLIC_KEY, PAY_STACK_CURRENCY } from '@/utils/config';
+import paystack from 'vue-paystack';
+
+export default{
+    name: 'ba-shopping-cart',
+    data: function () {
+        return {
+            tool: tool,
+            loading: true,
+            goods: [],
+            payList: [],
+            pointsSum: '',
+            cashSum: '',
+            freight: '',
+            pointFreight: '',
+            freeShipping: '',
+            goodsId: '',
+            goodsNum: '',
+            payPassword: '',
+            submitButtonStat: false,
+            prefixSign: '₦',
+            unit: 'NGN',
+            sn: '',
+            orderType: '',
+            payDialog: false,
+            countdown: 5,
+            visible: false,
+            payType: 'pay_stack',
+            payStackLoading: false,
+            channels: ["card", "bank", "ussd", "qr"], // eft(南非)  mobile_money(加纳)
+            form: {
+                publicKey: PAY_STACK_PUBLIC_KEY,
+                currency: PAY_STACK_CURRENCY,
+                firstname: userInfo.userName(),
+                lastname: '',
+                email: userInfo.userEmail(),
+                amount: 0, // kobo
+                orderSn: '',
+                metadata: {
+                    cart_id: this.sn,
+                    custom_fields: [
+                        {
+                            display_name: 'orderSn',
+                            variable_name: 'orderSn',
+                            value: this.sn
+                        },
+                        {
+                            display_name: 'isBrandAmbassador',
+                            variable_name: 'isBrandAmbassador',
+                            value: true,
+                        },
+                    ]
+            },
+          },
+            regionData: store.state.regionInfo.regionData,
+            addressId: '100000000000000000',
+            all_address: [],
+        }
+    },
+    components: {
+        paystack
+    },
+    created() {
+        // 加载sessionStorage中推送的商品
+        let option = sessionStorage.getItem('order_goods');
+        // 加载购物车
+        this.getShowCart();
+        if (option) {
+            let pageGoodsList = JSON.parse(option);
+            let pageList;
+            for (let i in pageGoodsList) {
+                pageList = pageGoodsList[i];
+                if (!pageList) continue;
+
+                pageList.map((pageData, index) => {
+                    if (Number(pageData.chose_num) > 0) {
+                        let discount = pageData.DISCOUNT / 100;
+                        pageData.member_price = Math.round(pageData.SELL_PRICE * discount * 100) / 100;
+                        pageData.member_price_plus = Math.round(pageData.SELL_PRICE * Number(pageData.chose_num) * discount * 100) / 100;
+                        pageData.tax_amount_plus = Math.round((pageData.member_price - pageData.member_price / (1 + pageData.TAX_RATE / 100)) * pageData.chose_num * 100) / 100;
+                        this.goods.push(pageData)
+                    }
+                })
+            }
+            // 计算价格
+          this.getSumMoney();
+        }
+    },
+    computed: {
+        // PayStack混淆串
+        reference() {
+            let text = '';
+            let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+            for (let i = 0; i < 10; i++) {
+                text += possible.charAt(Math.floor(Math.random() * possible.length));
+            }
+            return text;
+        }
+    },
+    methods: {
+        // 取消订单
+        cancelOrder() {
+            history.go(-1)
+        },
+        // 设置运费
+        setFreight() {
+            // 如果地址为自提,则运费为0
+            this.pointFreight = (this.addressId === '100000000000000000') ? Number(0) : Number(this.freight);
+        },
+        // 表格合并
+        getSummaries(param) {
+            const { columns, data } = param;
+            const sums = [];
+            columns.forEach((column, index) => {
+                if (index === 0) {
+                    sums[index] = 'Total'; // 合计
+                    return;
+                }
+                const values = data.map(item => Number(item[column.property]));
+                if ((!values.every(value => isNaN(value))) && [4, 5, 6].includes(index)) {
+                    sums[index] = values.reduce((prev, curr) => {
+                        const value = Number(curr);
+                        if (!isNaN(value)) {
+                            return Math.round((prev + curr) * 100) / 100;
+                        } else {
+                            return Math.round(prev * 100) / 100;
+                        }
+                    }, 0);
+                }
+            });
+
+            return sums;
+        },
+        // 支付
+        goToAccounts() {
+            this.submitButtonStat = true
+            this.$prompt('Please enter your payment password', 'Hint', { // '请输入支付密码', '提示'
+                confirmButtonText: 'Confirm', // 确定
+                cancelButtonText: 'Cancel', // 取消
+                inputType: 'password',
+                inputPattern: /\S+/,
+                inputErrorMessage: 'Please enter your payment password' // 请输入支付密码
+            }).then(({value}) => {
+                this.payPassword = value
+                let params = {
+                    goodsId: this.goodsId,
+                    goodsNum: this.goodsNum,
+                    payPassword: this.payPassword,
+                    email: this.form.email,
+                    addressId: this.addressId,
+                    address: this.address,
+                };
+
+                // PayStack支付
+                return network.postData('shop/ba-sure-approach-order', params).then(response => {
+                    this.submitButtonStat = false;
+                    this.form.orderSn = response.SN;
+                    this.form.amount = this.cashSum;
+                    this.form.metadata.custom_fields[0].value = response.SN;
+                    this.visible = true;
+                }).catch(_ => {
+                    this.submitButtonStat = false;
+                });
+            }).catch(_ => {
+                this.submitButtonStat = false;
+            });
+        },
+        // 计算价格
+        getSumMoney () {
+            let cash_plus_sum = [];
+            let goodsId = [];
+            let goodsNum = [];
+            let choseNum = 0;
+            this.goods.map(item => {
+                choseNum = Number(item.chose_num);
+                if (choseNum > 0) {
+                    cash_plus_sum.push(item.SELL_PRICE * choseNum * (item.DISCOUNT / 100));
+                    goodsId.push(item.ID);
+                    goodsNum.push(choseNum);
+                }
+            })
+            this.goodsNum = goodsNum;
+            this.goodsId = goodsId;
+            // 增加运费
+            let payAmount = tool.sum(cash_plus_sum);
+            // 设置运费
+            this.setFreight();
+            // 商品总价大于预定值,免运费
+            this.pointFreight = (this.pointFreight > 0) ? ((payAmount >= this.freeShipping) ? 0 : this.freight) : 0
+            // 计算总价
+            this.pointsSum = this.cashSum = this.form.amount = tool.formatPrice(tool.sum(cash_plus_sum) + this.pointFreight) ;
+        },
+        // 展示购物车信息
+        getShowCart () {
+            network.getData('shop/ba-shopping-cart', {}).then(response => {
+                this.loading = false;
+                // 免运费阈值
+                this.freeShipping = response.freeShipping;
+                // 运费
+                this.freight = response.freight;
+                // 收货地址
+                this.all_address = response.allAddress;
+                this.all_address.map((item, index) => {
+                    if (item.IS_DEFAULT === 1) {
+                        this.addressId = item.ID
+                    }
+                })
+            }).catch(_ => {
+                this.loading = false;
+            })
+        },
+        // 选择收货地址
+        choseAddress (addressId) {
+            this.addressId = addressId;
+            // 设置运费
+            this.setFreight()
+            // 计算价格
+            this.getSumMoney()
+        },
+        // 关闭支付回调
+        handleClose() {
+            let _this = this
+            _this.$confirm('Confirm to close?').then(_ => {
+                return network.postData('shop/ba-delete-approach-order', { orderSn: this.form.orderSn }).then(_ => {
+                    // 关闭支付模态框
+                    _this.visible = false
+                    // 关闭购物车页面,返回到订单列表页
+                    sessionStorage.setItem('order_goods', null)
+                    this.$router.push({path: `/shop/ba-product-list`})
+                })
+            }).catch(_ => {
+                // 关闭支付模态框
+                _this.visible = false
+                // 关闭购物车页面,返回到订单列表页
+                sessionStorage.setItem('order_goods', null)
+                this.$router.push({path: `/shop/ba-product-list`})
+            })
+        },
+        // 支付成功回调
+        processPayment() {
+            // 关闭支付页面
+            this.visible = false
+            this.payStackLoading = false
+            // 显示支付成功模态框
+            this.payDialog = true;
+            // 启动支付成功倒计时
+            this.handleCountdown()
+        },
+        // 关闭支付回调
+        processClose () {
+            // 关闭支付模态框
+            this.visible = false
+            // 关闭购物车页面,返回到订单列表页
+            sessionStorage.removeItem('order_goods')
+            this.$router.push({path: `/shop/ba-product-list`})
+        },
+        // 倒计时结束跳转
+        handleOrderList () {
+            this.$router.push({path: `/shop/ba-order-list`})
+        },
+        // 启动倒计时
+        handleCountdown () {
+            // 创建定时器
+            setInterval(() => {
+                // 每隔1秒把time的值减一,赋值给span标签
+                this.countdown--
+                if (this.countdown === 0) {
+                    // 倒计时结束,跳转到订单列表
+                    this.$router.push({path: `/shop/ba-order-list`});
+                }
+            }, 1000)
+        },
+    },
+}
+</script>
+
+<style scoped>
+.address{
+    /* height: 3rem; */
+    line-height: 3.5rem;
+
+}
+.address_box{
+     border-bottom: 1px solid #e3e3e3;
+}
+.sum{
+    display: inline-block;
+}
+.box{
+    margin: 1rem 0;
+    display: flex;
+    justify-content: flex-start;
+    align-items: center;
+    padding-bottom: 1rem;
+}
+.sum_box{
+    display: flex;
+    margin-left: 1rem;
+}
+.sum_box > div{
+    line-height: 2rem;
+}
+.sum_box > div:nth-child(1){
+    margin-right: 1rem;
+}
+.payButton {
+    border: none;
+    padding: 0;
+}
+</style>

+ 705 - 0
frontendEle/src/views/user/ba-dec.vue

@@ -0,0 +1,705 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <el-form ref="form"  label-width="180px" class="form-page">
+        <div class="hr-tip"><span>Account Information<!--账号信息--></span></div>
+
+        <el-form-item label="New member code"><!--会员编号-->
+          <el-input v-model="form.insertUserName" readonly="readonly"></el-input>
+        </el-form-item>
+<!--        <el-form-item>-->
+<!--          <template slot="label">-->
+<!--            Entry level&lt;!&ndash;实时报单级别&ndash;&gt;-->
+<!--          </template>-->
+<!--          <el-select v-model="form.decLv" placeholder="Select entry level" @change="selectOne($event)">-->
+<!--            <el-option v-for="(item,index) in allDecLevel" :key="index" :label="item.LEVEL_NAME"-->
+<!--             :value="item.ID"></el-option>-->
+<!--          </el-select>&lt;!&ndash;请选择报单级别&ndash;&gt;-->
+<!--        </el-form-item>-->
+        <el-form-item label="Stockist Code"><!--报单中心编号-->
+          <el-input v-model="form.decUserName" readonly></el-input>
+        </el-form-item>
+
+        <el-form-item>
+          <template slot="label">
+            Select Welcome Pack<!--报单方式二选一-->
+          </template>
+          <el-tabs type="border-card" v-model="decWay" style="position: relative;width: 1200px;">
+            <el-tab-pane label="Product" name="2"><!-- 商品报单 -->
+              <el-table class="table-box" v-if="numList.length > 0" :data="tableDatas" stripe style="width: 100%;" highlight-current-row  @selection-change="handleSelectionChange">
+                <el-table-column
+                  type="selection"
+                  width="55">
+                </el-table-column>
+
+                <el-table-column label="Product Name" prop="GOODS_NAME" width="300"><!-- 商品名称 -->
+
+                </el-table-column>
+                <el-table-column label="Product code" prop="GOODS_NO" width="120"><!-- 商品编号 -->
+
+                </el-table-column>
+                <el-table-column label="Product price" prop="SELL_PRICE" width="120"><!-- 卖价 -->
+
+                </el-table-column>
+
+                <el-table-column label="Product BV" prop="PRICE_PV" width="100"><!-- BV价格 -->
+
+                </el-table-column>
+                <el-table-column label="Tax rate" prop="TAX_RATE" width="100">
+                  <template slot-scope="scope">
+                    {{ Math.round(scope.row.TAX_RATE * 100) / 100 }}
+                  </template>
+                </el-table-column>
+                <el-table-column label="Tax" width="100">
+                  <template slot-scope="scope">
+                    {{ Math.round((scope.row.SELL_PRICE - scope.row.SELL_PRICE / (1 + scope.row.TAX_RATE / 100)) * 100) / 100 }}
+                  </template>
+                </el-table-column>
+                <el-table-column label="Quantity" width="150"><!-- 数量 -->
+                  <template slot-scope="scope">
+                    <el-input-number size="mini" v-model="numList[scope.$index]"  :min="0" :max="Number(scope.row.STORE_NUMS)" @change="value=>{handleChange(value,scope.row.ID)}"></el-input-number>
+                  </template>
+                  <!-- <template slot-scope="scope">
+                    <el-input-number v-if="form.goodsId.some(item=>item==scope.row.ID)" v-model='scope.row.goodsNum' @change="value=>{handleChange(value,scope.row.ID)}" controls-position="right" style="width: 70px;" size="mini"></el-input-number>
+                  </template> -->
+                </el-table-column>
+              </el-table>
+              <div class="white-box-footer flex">
+                <el-button @click="getSum()">Total Calculation</el-button><!--计算合计-->
+                <div class='flex data' style="flex:1;justify-content: flex-end;">
+                  <div style="margin-right:2rem">Price:₦{{sell_price_sum}}</div><!--商品价格-->
+                  <div style="margin-right:2rem">BV:{{price_pv_sum}}</div><!--商品BV-->
+                  <div>Tax:₦{{tax_sum}}</div><!--商品BV-->
+                </div>
+              </div>
+
+            </el-tab-pane>
+          </el-tabs>
+        </el-form-item>
+
+        <div class="hr-tip"><span>Network Information</span></div><!--网络信息-->
+        <el-form-item label="Sponsor code"><!--推荐人编号-->
+          <el-input v-model="form.recUserName" @change="handleChkRecUser">
+            <template slot="append">【{{recRealName}}】</template>
+          </el-input>
+        </el-form-item>
+
+<!--        <el-form-item label="Placement code">&lt;!&ndash;接点人编号&ndash;&gt;-->
+<!--          <el-input v-model="form.conUserName" @change="handleChkConUser">-->
+<!--            <template slot="append">【{{conRealName}}】</template>-->
+<!--          </el-input>-->
+<!--        </el-form-item>-->
+
+<!--        <el-form-item label="Placement tree">&lt;!&ndash;安置区位&ndash;&gt;-->
+<!--          <el-radio-group v-model="form.location">-->
+<!--            <el-radio :label="1" >Left</el-radio>&lt;!&ndash;左区&ndash;&gt;-->
+<!--            <el-radio :label="2" >Right</el-radio>&lt;!&ndash;右区&ndash;&gt;-->
+<!--          </el-radio-group>-->
+<!--        </el-form-item>-->
+
+<!--        <el-form-item label="">&lt;!&ndash;自动安置区位&ndash;&gt;-->
+<!--          <el-button type="primary" @click="setAutoPlace('left')">Placement Auto Location: L</el-button>-->
+<!--          <el-button type="primary" @click="setAutoPlace('right')">Placement Auto Location: R</el-button>-->
+<!--        </el-form-item>-->
+
+        <div class="hr-tip"><span>Personal Information<!--个人信息--></span></div>
+        <el-form-item>
+          <template slot="label">
+            Member Name<!-- 会员姓名 -->
+          </template>
+          <el-input v-model="form.realName"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Phone Number<!-- 会员手机 -->
+          </template>
+          <el-input v-model="form.mobile"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Email
+          </template>
+          <el-input v-model="form.email"></el-input>
+        </el-form-item>
+
+        <el-form-item>
+          <template slot="label">
+            Login Password<!-- 登录密码 -->
+          </template>
+          <el-input v-model="form.password" maxlength="32" placeholder="Enter password"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Payment Password<!-- 支付密码 -->
+          </template>
+          <el-input v-model="form.payPassword" maxlength="32" placeholder="Enter Payment password"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Recipient Name<!-- 收货人 -->
+          </template>
+          <el-input v-model="form.consignee"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Phone Number<!-- 收货人手机 -->
+          </template>
+          <el-input v-model="form.acceptMobile"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Shipping<!-- 收货方式 -->
+          </template>
+          <el-radio-group v-model="form.way" @change="wayChange">
+            <el-radio label="express">Delivery</el-radio>
+            <el-radio label="pickup">Self Pick-up<!--自提--></el-radio>
+          </el-radio-group>
+        </el-form-item>
+        <el-form-item prop="areaSelected">
+          <template slot="label">
+            State<!-- 地区 -->
+          </template>
+          <el-cascader
+            :disabled="areaDisabled"
+            size="large"
+            :options="regionData"
+            v-model="form.areaSelected">
+          </el-cascader>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Full address<!-- 详细地址 -->
+          </template>
+          <el-input :disabled="addressDisabled" v-model="form.address"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            City<!-- 详细地址 -->
+          </template>
+          <el-input :disabled="addressDisabled" v-model="form.cityName"></el-input>
+        </el-form-item>
+        <el-form-item>
+          <template slot="label">
+            Local Government Area<!-- 详细地址 -->
+          </template>
+          <el-input :disabled="addressDisabled" v-model="form.lgaName"></el-input>
+        </el-form-item>
+
+<!--        <div class="hr-tip"><span>Bank Info&lt;!&ndash; 银行信息 &ndash;&gt;</span></div>-->
+
+<!--        <el-form-item label="Bank Name">&lt;!&ndash; 开户行 &ndash;&gt;-->
+<!--          <el-select v-model="form.openBank" placeholder="Select Bank">&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="Account Name">&lt;!&ndash; 开户支行 &ndash;&gt;-->
+<!--          <el-input v-model="form.bankAddress"></el-input>-->
+<!--        </el-form-item>-->
+<!--        <el-form-item label="Account Number">&lt;!&ndash; 银行账号 &ndash;&gt;-->
+<!--          <el-input v-model="form.bankNo" maxlength="19"></el-input>-->
+<!--        </el-form-item>-->
+
+        <div class="hr-tip"><span>Pay Info<!-- 支付信息 --></span></div>
+        <el-form-item label="Payment method" required><!-- 支付方式 -->
+          <el-radio-group v-model="form.payType" @change="payMethodChange">
+            <el-radio v-for="(item, index) in payList" :key='index' :label="item.label">{{ item.name }}</el-radio>
+          </el-radio-group>
+        </el-form-item>
+
+        <el-form-item>
+          <el-button type="primary" @click="onSubmit" :loading="submitButtonStat">Save<!-- 保存 --></el-button>
+        </el-form-item>
+      </el-form>
+      </div>
+
+      <el-dialog title="Pay" v-if="visible" :visible.sync="visible" width="30%" v-loading="payStackLoading" :before-close="handleClose">
+        <section>
+          <div class="formcontainer">
+            <el-divider></el-divider>
+            <div class="container">
+              <el-form :model="PayStackForm">
+                <el-form-item label="Email" label-width="100px" required>
+                  <el-input v-model="PayStackForm.email" autocomplete="off"></el-input>
+                </el-form-item>
+                <el-form-item label="Amount" label-width="100px" required>
+                  <el-input v-model="PayStackForm.amount" autocomplete="off" readonly></el-input>
+                </el-form-item>
+              </el-form>
+            </div>
+          </div>
+        </section>
+
+        <paystack
+          :firstname="PayStackForm.firstname"
+          :lastname="PayStackForm.lastname"
+          :amount="PayStackForm.amount * 100"
+          :email="PayStackForm.email"
+          :metadata="PayStackForm.metadata"
+          :currency="PayStackForm.currency"
+          :paystackkey="PayStackForm.publicKey"
+          :reference="reference"
+          :channels="channels"
+          :callback="processPayment"
+          :close="processClose"
+        >
+          <el-button type="primary" size="small">Pay</el-button>
+
+        </paystack>
+        <el-button type="danger" size="small" class="cancelButton" @click="handleClose">Cancel</el-button>
+      </el-dialog>
+
+      <el-dialog title="Tips" :visible.sync="payDialog" :show-close="false" width="350px" :close="handleOrderList">
+        <el-result icon="success" title="the order is successful">
+          <template slot="extra">
+            <span style="color: #008efa; font-size: 30px;">{{ countdown }}</span>
+          </template>
+        </el-result>
+      </el-dialog>
+  </div>
+</template>
+
+<script>
+import Vue from 'vue'
+import network from '@/utils/network'
+import baseInfo from '@/utils/baseInfo'
+import store from '@/utils/vuexStore'
+import tool from '@/utils/tool'
+import userInfo from '@/utils/userInfo'
+import { PAY_STACK_PUBLIC_KEY, PAY_STACK_CURRENCY } from '@/utils/config'
+import paystack from 'vue-paystack'
+
+export default {
+  name: 'user_dec',
+  async created () {
+    await this.getData()
+  },
+  computed: {
+    // _tableData () {
+    //   if (this.tableData == null) {
+    //     return []
+    //   }
+    //   if (this.form.decLv === '') {
+    //     return this.tableData
+    //   }
+    //   return this.tableData.filter(item => {
+    //     return item.LEVEL_ID === this.form.decLv
+    //   })
+    // },
+    reference () {
+      let text = ''
+      let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
+      for (let i = 0; i < 10; i++) {
+        text += possible.charAt(Math.floor(Math.random() * possible.length))
+      }
+      return text
+    }
+  },
+
+  data () {
+    return {
+      currentRow: null,
+      decWay: '2',
+      regionData: store.state.regionInfo.regionData,
+      form: {
+        realName: '',
+        decLv: '',
+        insertUserName: '',
+        decUserName: userInfo.userName(),
+        recUserName: '',
+        conUserName: '',
+        insertUserIdCard: '',
+        consignee: '',
+        acceptMobile: '',
+        areaSelected: [],
+        address: '',
+        openBank: '',
+        bankAddress: '',
+        bankProvince: '',
+        bankCity: '',
+        bankCounty: '',
+        bankNo: '',
+        bankAreaSelected: [],
+        password: '111111',
+        payPassword: '111111',
+        mobile: '',
+        email: '',
+        packageId: '',
+        goodsId: [],
+        goodsNum: [],
+        province: '',
+        cityName: '',
+        lgaName: '',
+        way: 'express',
+        payType: '',
+        autoPlace: '',
+        location: ''
+      },
+      conRealName: '-',
+      recRealName: '-',
+      num: 1,
+      // tableData: null,
+      tableDatas: null,
+      allOpenBank: null,
+      // allDecPackage: {},
+      allDecLevel: baseInfo.decLevels(),
+      loading: false,
+      submitButtonStat: false,
+      submitButton: false,
+      allGoods: [],
+      multipleSelection: [],
+      goodsNums: [],
+      numList: [],
+      sell_price_sum: 0.00,
+      price_pv_sum: 0.00,
+      tax_sum: 0.00,
+      areaDisabled: false,
+      addressDisabled: false,
+      category_type: '',
+      payList: [],
+      sn: '',
+      payDialog: false,
+      countdown: 5,
+      visible: false,
+      payStackLoading: false,
+      channels: ['card', 'bank', 'ussd', 'qr'], // eft(南非)  mobile_money(加纳)
+      PayStackForm: {
+        publicKey: PAY_STACK_PUBLIC_KEY,
+        currency: PAY_STACK_CURRENCY,
+        firstname: userInfo.userName(),
+        lastname: '',
+        email: userInfo.userEmail(),
+        amount: 0, // kobo
+        orderSn: '',
+        metadata: {
+          cart_id: this.sn,
+          custom_fields: [
+            {
+              display_name: 'orderSn',
+              variable_name: 'orderSn',
+              value: this.sn
+            },
+            {
+              display_name: 'isBrandAmbassador',
+              variable_name: 'isBrandAmbassador',
+              value: true,
+            },
+          ]
+        }
+      }
+    }
+  },
+  components: {
+    paystack
+  },
+  methods: {
+    wayChange () {
+      if (this.form.way === 'pickup') {
+        this.areaDisabled = true
+        this.addressDisabled = true
+      } else {
+        this.areaDisabled = false
+        this.addressDisabled = false
+      }
+    },
+    getSum () {
+      let sell_price_sum = 0, price_pv_sum = 0, tax_sum = 0
+      this.multipleSelection.map((item, index) => {
+        sell_price_sum += Number(item.SELL_PRICE) * item.goodsNum
+        price_pv_sum += Number(item.PRICE_PV) * item.goodsNum
+        tax_sum += Number(item.SELL_PRICE - item.SELL_PRICE / (1 + item.TAX_RATE / 100)) * item.goodsNum
+      })
+      this.sell_price_sum = tool.formatPrice(sell_price_sum)
+      this.price_pv_sum = tool.formatPrice(price_pv_sum)
+      this.tax_sum = tool.formatPrice(tax_sum)
+    },
+    async getData () {
+      await network.getData(`user/ba-dec`).then(response => {
+        this.loading = false
+        this.form.insertUserName = response.userName
+        // this.allOpenBank = response.allOpenBank
+        // this.allDecPackage = response.allDecPackage
+        this.allGoods = response.allGoods
+        this.categoryType = 1
+
+        // let settingObj = this.allDecPackage
+        // let settingArr = Object.keys(settingObj).map(key => {
+        //   return settingObj[key] // 把每个对象返回出去生成一个新的数组中相当于0:{id:1}
+        // })
+        // this.tableData = settingArr
+        let settingObj1 = this.allGoods
+        for (let i in settingObj1) {
+          this.numList[i] = 1
+          settingObj1[i].goodsNum = 1
+        }
+        this.tableDatas = settingObj1
+
+        // 支付方式
+        this.payList = response.sellType[0]['sell_type']
+        // 支付方式的第一项默认选中
+        this.form.payType = Object.values(this.payList)[1]['label']
+      })
+    },
+    handleCurrentChange (val) {
+      if (!val) { return }
+      this.currentRow = val
+      this.form.packageId = this.currentRow.ID
+    },
+    handleSelectionChange (val) {
+      let idx = -1, num
+      for (let i in this.tableDatas) {
+        for (let v in val) {
+          if (val[v].ID === this.tableDatas[i].ID) {
+            idx = i
+            num = this.numList[idx]
+            val[v]['goodsNum'] = num
+            break
+          }
+        }
+      }
+      this.multipleSelection = val
+    },
+    handleChange (value, ID) {
+      for (let i in this.multipleSelection) {
+        if (this.multipleSelection[i]['ID'] === ID) {
+          this.multipleSelection[i]['goodsNum'] = value
+        }
+      }
+    },
+    getGoods () {
+      this.form.goodsId = []
+      this.form.goodsNum = []
+      this.multipleSelection.map((item, index) => {
+        this.form.goodsId.push(item.ID)
+        this.form.goodsNum.push(item.goodsNum)
+      })
+    },
+    onSubmit () {
+      let _this = this
+      _this.getGoods()
+      _this.submitButtonStat = true
+      let path = 'user/ba-dec'
+      let postData = {
+        consignee: _this.form.consignee,
+        acceptMobile: _this.form.acceptMobile,
+        province: _this.form.areaSelected[0] ? _this.form.areaSelected[0] : '',
+        city: _this.form.areaSelected[1] ? _this.form.areaSelected[1] : '',
+        county: _this.form.areaSelected[2] ? _this.form.areaSelected[2] : '',
+        address: _this.form.address,
+        insertUserName: _this.form.insertUserName,
+        decLv: _this.form.decLv,
+        realName: _this.form.realName,
+        decUserName: _this.form.decUserName,
+        conUserName: _this.form.conUserName,
+        recUserName: _this.form.recUserName,
+        insertUserIdCard: _this.form.insertUserIdCard,
+        openBank: _this.form.openBank,
+        bankAddress: _this.form.bankAddress,
+        mobile: _this.form.mobile,
+        email: _this.form.email,
+        cityName: _this.form.cityName,
+        lgaName: _this.form.lgaName,
+
+        bankProvince: _this.form.bankAreaSelected[0] ? _this.form.bankAreaSelected[0] : '',
+        bankCity: _this.form.bankAreaSelected[1] ? _this.form.bankAreaSelected[1] : '',
+        bankCounty: _this.form.bankAreaSelected[2] ? _this.form.bankAreaSelected[2] : '',
+
+        bankNo: _this.form.bankNo,
+        password: _this.form.password,
+        payPassword: _this.form.payPassword,
+        packageId: _this.form.packageId,
+        goodsId: _this.form.goodsId,
+        goodsNum: _this.form.goodsNum,
+        location: _this.form.location,
+        decWay: _this.decWay,
+        payType: _this.form.payType
+      }
+
+      return network.postData(path, postData).then((response) => {
+        // 非PayStack支付
+        if (_this.form.payType !== 'pay_stack') {
+          console.log(response)
+          _this.$message({
+            message: response,
+            type: 'success'
+          })
+          _this.submitButtonStat = false
+          _this.$router.push({path: `/shop/ba-dec-order-list`})
+        } else {
+          // PayStack支付
+          _this.submitButtonStat = false
+          _this.PayStackForm.orderSn = response.SN
+          _this.PayStackForm.amount = response.ORDER_AMOUNT
+          _this.PayStackForm.metadata.custom_fields[0].value = response.SN
+          _this.visible = true
+        }
+      }).catch(response => {
+        _this.submitButtonStat = false
+        _this.$message({
+          message: response,
+          type: 'error'
+        })
+      })
+    },
+
+    selectOne (event, item) {
+      network.getData(`user/ba-dec`).then(response => {
+      })
+    },
+
+    handleChkConUser () {
+      if (this.form.conUserName) {
+        this.loading = true
+        network.getData('user/full-info', {userName: this.form.conUserName}).then(response => {
+          this.conRealName = response.REAL_NAME + response.isLocation
+          this.loading = false
+        }).catch(response => {
+          this.conRealName = '-'
+          this.loading = false
+        })
+      }
+    },
+
+    handleChkRecUser () {
+      this.form.conUserName = ''
+      this.conRealName = '-'
+      this.form.autoPlace = ''
+      if (this.form.recUserName) {
+        this.loading = true
+        network.getData('user/full-info', {userName: this.form.recUserName}).then(response => {
+          // console.log(response)
+          this.recRealName = response.REAL_NAME
+          this.loading = false
+        }).catch(response => {
+          this.recRealName = '-'
+          this.loading = false
+        })
+      }
+    },
+    // 切换支付方式
+    payMethodChange (type) {
+      this.form.payType = type
+    },
+    // 关闭支付回调
+    handleClose () {
+      let _this = this
+      _this.$confirm('Confirm to close?').then(() => {
+        return network.postData('shop/delete-approach-order', {orderSn: this.PayStackForm.orderSn}).then(() => {
+          // 关闭支付模态框
+          _this.visible = false
+        })
+      }).catch(() => {
+        // 关闭支付模态框
+        _this.visible = false
+      })
+    },
+    // 支付成功回调
+    processPayment (response) {
+      // 关闭支付页面
+      this.visible = false
+      this.payStackLoading = false
+
+      // 显示支付成功模态框
+      this.payDialog = true
+      this.handleCountdown()
+    },
+    // 关闭支付回调
+    processClose () {
+      // 关闭支付模态框
+      this.visible = false
+    },
+    // 支付tips结束,跳转到报单列表
+    handleOrderList () {
+      this.$router.push({path: `/shop/ba-dec-order-list`})
+    },
+    // 启动倒计时
+    handleCountdown () {
+      // 创建定时器
+      setInterval(() => {
+        // 每隔1秒把time的值减一,赋值给span标签
+        this.countdown--
+        if (this.countdown === 0) {
+          // 倒计时结束,跳转到报单列表
+          this.$router.push({path: `/shop/ba-dec-order-list`})
+        }
+      }, 1000)
+    }
+  }
+}
+</script>
+
+<style>
+  .hr-tip {
+    font-size: 12px;
+    position: relative;
+    text-align: center;
+    height: 30px;
+    line-height: 30px;
+    color: #999;
+    margin-bottom: 20px;
+  }
+
+  .hr-tip:before {
+    content: '';
+    display: block;
+    position: absolute;
+    left: 0;
+    right: 0;
+    top: 14px;
+    border-bottom: 1px dashed #ddd;
+    height: 1px;
+  }
+
+  .hr-tip span {
+    display: inline-block;
+    background: #fff;
+    position: relative;
+    padding: 0 10px;
+  }
+  .el-input-number--mini .el-input-number__decrease, .el-input-number--mini .el-input-number__increase{
+    width: 22px!important
+  }
+  .el-input-number.is-controls-right .el-input__inner{
+    padding-left: 10px;
+    padding-right: 30px;
+  }
+  .el-tabs--border-card{
+    position: relative;
+    width: 600px;
+  }
+  .flex{
+    display: flex;
+  }
+  .address{
+    /* height: 3rem; */
+    line-height: 3.5rem;
+  }
+  .address_box{
+    border-bottom: 1px solid #e3e3e3;
+  }
+  .sum{
+    display: inline-block;
+  }
+  .box{
+    margin: 1rem 0;
+    display: flex;
+    justify-content: flex-start;
+    align-items: center;
+    padding-bottom: 1rem;
+  }
+  .sum_box{
+    display: flex;
+    margin-left: 1rem;
+  }
+  .sum_box > div{
+    line-height: 2rem;
+  }
+  .sum_box > div:nth-child(1){
+    margin-right: 1rem;
+  }
+  .payButton {
+    border: none;
+    padding: 0;
+  }
+</style>

+ 100 - 0
frontendEle/src/views/user/ba-info.vue

@@ -0,0 +1,100 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <el-tabs v-model="tabActive" style="overflow: auto">
+        <el-tab-pane label="Essential Information" name="baseInfo" style="overflow: auto"><!-- 基本信息 -->
+          <el-form ref="form" :model="infoData" label-width="250px" class="form-page">
+            <el-form-item label="Member code"><!-- 会员编号 -->
+              <el-input v-model="infoData.USER_NAME" :disabled="true"></el-input>
+            </el-form-item>
+
+            <el-form-item label="Member name"><!-- 会员姓名 -->
+              <el-input v-model="infoData.REAL_NAME" :disabled="true"></el-input>
+            </el-form-item>
+
+            <el-form-item label="Phone Number"><!-- 手机号 -->
+              <el-input v-model="infoData.MOBILE" :disabled="true"></el-input>
+            </el-form-item>
+
+            <el-form-item label="Email"><!-- Email -->
+              <el-input v-model="infoData.EMAIL"></el-input>
+            </el-form-item>
+
+            <el-form-item>
+              <el-button type="primary" @click="handleSubmit" :loading="submitButtonStat">Confirm<!-- 保存 --></el-button>
+            </el-form-item>
+
+          </el-form>
+        </el-tab-pane>
+      </el-tabs>
+    </div>
+  </div>
+</template>
+
+<script>
+import network from './../../utils/network'
+
+export default {
+  name: 'ba-info',
+  mounted () {
+    this.getData()
+  },
+  data () {
+    return {
+      infoData: {
+        USER_NAME: '',
+        NATION: '',
+        REAL_NAME: '',
+        MOBILE: '',
+        OPEN_BANK: '',
+        BANK_ADDRESS: '',
+        BANK_NO: '',
+        EMAIL: '',
+      },
+      allOpenBank: null,
+      allNation: null,
+      tabActive: 'baseInfo',
+      loading: true,
+      submitButtonStat: false,
+    }
+  },
+  methods: {
+    getData () {
+      network.getData('user/ba-info').then(response => {
+        this.infoData = response.userInfo
+        this.allOpenBank = response.allOpenBank
+        this.allNation = response.allNation
+        this.loading = false
+      })
+    },
+    handleSubmit(){
+        this.submitButtonStat = true
+        let path = 'user/ba-edit'
+        let postData = {
+            nation: this.infoData.NATION,
+            realName: this.infoData.REAL_NAME,
+            mobile: this.infoData.MOBILE,
+            openBank: this.infoData.OPEN_BANK,
+            bankAddress: this.infoData.BANK_ADDRESS,
+            bankNo: this.infoData.BANK_NO,
+            email: this.infoData.EMAIL,
+        }
+        return network.postData(path, postData).then(response => {
+            this.$message({
+                message: response,
+                type: 'success'
+            })
+            this.submitButtonStat = false
+            this.getData();
+        }).catch(() => {
+            this.submitButtonStat = false
+        })
+    },
+  }
+}
+
+</script>
+
+<style scoped>
+
+</style>

+ 106 - 0
frontendEle/src/views/user/ba-password.vue

@@ -0,0 +1,106 @@
+<template>
+  <div v-loading="loading">
+    <div class="white-box">
+      <el-tabs v-model="tabActive" style="overflow: auto">
+        <el-tab-pane label="Login password" name="password" style="overflow: auto"><!--登录密码-->
+          <el-form ref="form" :model="passwordInfo" label-width="250px" class="form-page">
+            <el-form-item label="Original Login password"><!--原登录密码-->
+              <el-input v-model="passwordInfo.oldPassword" show-password></el-input>
+            </el-form-item>
+            <el-form-item label="New Login password"><!--新登录密码-->
+              <el-input v-model="passwordInfo.password" show-password></el-input>
+            </el-form-item>
+            <el-form-item label="Confirm new password"><!--确认新密码-->
+              <el-input v-model="passwordInfo.verifyPassword" show-password></el-input>
+            </el-form-item>
+            <el-form-item>
+              <el-button type="primary" @click="handlePasswordSubmit" :loading="passwordButtonStat">Confirm</el-button><!--确认-->
+            </el-form-item>
+          </el-form>
+        </el-tab-pane>
+
+        <el-tab-pane label="Payment password" name="payPassword" style="overflow: auto"><!--支付密码-->
+          <el-form ref="form" :model="payPasswordInfo" label-width="250px" class="form-page">
+            <el-form-item label="Original payment password"><!--原支付密码-->
+              <el-input v-model="payPasswordInfo.oldPassword" show-password></el-input>
+            </el-form-item>
+            <el-form-item label="New payment password"><!--新支付密码-->
+              <el-input v-model="payPasswordInfo.payPassword" show-password></el-input>
+            </el-form-item>
+            <el-form-item label="Confirm new password"><!--确认新密码-->
+              <el-input v-model="payPasswordInfo.verifyPassword" show-password></el-input>
+            </el-form-item>
+            <el-form-item>
+              <el-button type="primary" @click="handlePayPasswordSubmit" :loading="payPasswordButtonStat">Confirm</el-button><!--确认-->
+            </el-form-item>
+          </el-form>
+        </el-tab-pane>
+      </el-tabs>
+    </div>
+  </div>
+</template>
+
+<script>
+import network from './../../utils/network'
+
+export default {
+  name: 'ba-password',
+  mounted () {
+  },
+  data () {
+    return {
+      passwordInfo:{
+          oldPassword:'',
+          password:'',
+          verifyPassword:'',
+      },
+      payPasswordInfo:{
+          oldPassword:'',
+          payPassword:'',
+          verifyPassword:'',
+      },
+      tabActive: 'password',
+      loading: false,
+      passwordButtonStat:false,
+      payPasswordButtonStat:false,
+    }
+  },
+  methods: {
+    handlePasswordSubmit(){
+        this.passwordButtonStat = true
+        let path = 'user/ba-password'
+        return network.postData(path, this.passwordInfo).then(response => {
+
+            this.$message({
+                message: response,
+                type: 'success'
+            })
+            this.passwordButtonStat = false
+        }).catch(() => {
+            this.passwordButtonStat = false
+        })
+    },
+
+    handlePayPasswordSubmit(){
+        this.payPasswordButtonStat = true
+        let path = 'user/ba-pay-password'
+        return network.postData(path, this.payPasswordInfo).then(response => {
+
+            this.$message({
+                message: response,
+                type: 'success'
+            })
+            this.payPasswordButtonStat = false
+        }).catch(() => {
+            this.payPasswordButtonStat = false
+        })
+    },
+
+  }
+}
+
+</script>
+
+<style scoped>
+
+</style>

+ 39 - 3
frontendEle/src/views/user/dec.vue

@@ -2,10 +2,16 @@
   <div v-loading="loading">
     <div class="white-box">
       <el-form ref="form"  label-width="180px" class="form-page">
+        <el-form-item label="Welcome Pack Way"><!--报单方式-->
+          <el-radio-group v-model="form.decType" @change="decTypeChange()">
+            <el-radio label="normal" >Normal</el-radio>
+            <el-radio label="ba" >BA Upgrade</el-radio>
+          </el-radio-group>
+        </el-form-item>
         <div class="hr-tip"><span>Account Information<!--账号信息--></span></div>
 
         <el-form-item label="New member code"><!--会员编号-->
-          <el-input v-model="form.insertUserName" :readonly="userReadOnly"></el-input>
+          <el-input v-model="form.insertUserName" @blur="checkBaUser()" :readonly="userReadOnly"></el-input>
         </el-form-item>
         <el-form-item>
           <template slot="label">
@@ -125,7 +131,7 @@
 
         <div class="hr-tip"><span>Network Information</span></div><!--网络信息-->
         <el-form-item label="Sponsor code"><!--推荐人编号-->
-          <el-input v-model="form.recUserName" @change="handleChkRecUser">
+          <el-input v-model="form.recUserName" @change="handleChkRecUser" :readonly="recReadOnly">
             <template slot="append">【{{recRealName}}】</template>
           </el-input>
         </el-form-item>
@@ -356,8 +362,10 @@ export default {
       currentRow: null,
       decWay: '2',
       regionData: store.state.regionInfo.regionData,
+      recReadOnly: false,
       userReadOnly: true,
       form: {
+        decType: 'normal',
         realName: '',
         decLv: '',
         insertUserName: '',
@@ -566,6 +574,7 @@ export default {
         city: _this.form.areaSelected[1] ? _this.form.areaSelected[1] : '',
         county: _this.form.areaSelected[2] ? _this.form.areaSelected[2] : '',
         address: _this.form.address,
+        decType: _this.form.decType,
         insertUserName: _this.form.insertUserName,
         decLv: _this.form.decLv,
         realName: _this.form.realName,
@@ -702,7 +711,34 @@ export default {
           this.$router.push({path: `/shop/dec-order-list`})
         }
       }, 1000)
-    }
+    },
+    decTypeChange () {
+      if (this.form.decType=='ba'){
+        this.form.insertUserName = ''
+        this.userReadOnly = false
+      } else {
+        this.form.recUserName = ''
+        this.recRealName = '-'
+        this.recReadOnly = false
+        this.userReadOnly = true
+        this.getData()
+      }
+    },
+    checkBaUser () {
+      if (this.form.decType === 'ba' && this.form.insertUserName !== '') {
+        this.loading = true
+        network.getData('user/ba-user-info', {userName: this.form.insertUserName}).then(response => {
+          // console.log(response.REAL_NAME)
+          this.form.recUserName = response.REC_USER_NAME
+          this.form.realName = response.REAL_NAME
+          this.handleChkRecUser()
+          this.recReadOnly = true
+          this.loading = false
+        }).catch(response => {
+          this.loading = false
+        })
+      }
+    },
   }
 }
 </script>

+ 0 - 2715
sql/StoredProcedure-NG.sql

@@ -1,2715 +0,0 @@
--- MariaDB dump 10.19  Distrib 10.7.4-MariaDB, for Linux (x86_64)
---
--- Host: ngds-db-live.cdehazle30lc.ap-east-1.rds.amazonaws.com    Database: coco_milk_0524
--- ------------------------------------------------------
--- Server version	10.6.7-MariaDB-log
-
-/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
-/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
-/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
-/*!40101 SET NAMES utf8mb4 */;
-/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
-/*!40103 SET TIME_ZONE='+00:00' */;
-/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
-/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-
---
--- Dumping routines for database 'coco_milk_0524'
---
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALC10` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALC10`(IN `PCPID` INT)
-BEGIN
-    DECLARE
-        MLAYER,
-        MMAXLAYER INT;
-    DECLARE
-        MRATE,
-        MLIMITPV DECIMAL ( 10, 2 );-- 查询第一个级别的限制以及等奖比例
-    SELECT
-        T.ACHIEVE_PV,
-        T.BS_PERCENT / 100 INTO MLIMITPV,
-        MRATE
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = 'E121497617216708615';
-    SELECT
-        MAX( LAYER ) INTO MLAYER
-    FROM
-        AR_BS_BONUS_103_CALC
-    WHERE
-            PV > 0;
-
-    SET MMAXLAYER := MLAYER;
-    WHILE
-            MLAYER >= 0 DO
-            IF
-                ( MLAYER < MMAXLAYER ) THEN-- 向上累计
-                UPDATE AR_BS_BONUS_103_CALC T1
-                    INNER JOIN (
-                        SELECT
-                            INTRODUCER_ID,
-                            SUM( GPV10 ) GPV10
-                        FROM
-                            AR_BS_BONUS_103_CALC
-                        WHERE
-                                LAYER = MLAYER + 1
-                          AND USER_TYPE10 = 0
-                          AND GPV10 > 0
-                        GROUP BY
-                            INTRODUCER_ID
-                    ) T2 ON T1.USER_ID = T2.INTRODUCER_ID
-                        AND T1.LAYER = MLAYER
-                SET T1.GPV10 = T2.GPV10;-- 没有升级的会员需要将自己的小组业绩清零
-                UPDATE AR_BS_BONUS_103_CALC T
-                SET T.GPV10 = 0
-                WHERE
-                        T.GPV10 < T.ACHIEVE_PERF_PV AND T.LAYER = MLAYER + 1 AND USER_TYPE10 = 0 AND T.GPV10 > 0;
-
-            END IF;
-            UPDATE AR_BS_BONUS_103_CALC T1
-            SET T1.GPV10 = T1.GPV10 + T1.PV
-            WHERE
-                    T1.LAYER = MLAYER
-              AND T1.PV > 0;-- 是否达标 如果达标
-            UPDATE AR_BS_BONUS_103_CALC T
-            SET T.USER_TYPE10 = 10
-            WHERE
-                    T.GPV10 >= T.ACHIEVE_PERF_PV
-              AND T.LAYER = MLAYER
-              AND T.USER_TYPE10 = 0;
-            IF
-                ( MLAYER > 0 ) THEN-- 升级为蓝星A
-                CALL CALCUPGARDE ( MLAYER );
-
-            END IF;
-
-            SET MLAYER := MLAYER - 1;
-
-        END WHILE;
-    UPDATE AR_BS_BONUS_103_CALC T
-    SET T.BONUS10 = T.GPV10 * MRATE
-    WHERE
-            T.USER_TYPE10 = 10
-      AND T.GPV10 > 0;
-    UPDATE AR_BS_BONUS_103_CALC
-    SET USER_TYPE = 0;
-
-    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-    SELECT USER_ID, NULL, 10, GPV10 * MRATE, GPV10, MRATE ,PCPID FROM AR_BS_BONUS_103_CALC WHERE USER_TYPE10 = 10
-                                                                                             AND GPV10 > 0;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALC20` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALC20`(IN `PCPID` INT)
-BEGIN
-    DECLARE
-        MLAYER,
-        MMAXLAYER,
-        MCOUNT INT;
-    DECLARE
-        MRATE,
-        MLIMITPV DECIMAL ( 10, 2 );
-    START TRANSACTION;-- 第一个级别的限制
-    SELECT
-        T.ACHIEVE_PV INTO MLIMITPV
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = 'E121497617216708615';-- 第二个级别得奖的比例
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '67BE5FE7857C216AE055736AECE8644D';
-    SELECT
-        MAX( LAYER ) INTO MLAYER
-    FROM
-        AR_BS_BONUS_103_CALC
-    WHERE
-            PV > 0;
-
-    SET MMAXLAYER := MLAYER;
-    WHILE
-            MLAYER >= 0 DO
-            IF
-                ( MLAYER < MMAXLAYER ) THEN-- 向上累计
-                UPDATE AR_BS_BONUS_103_CALC T1
-                    INNER JOIN (
-                        SELECT
-                            INTRODUCER_ID,
-                            SUM( GPV ) GPV
-                        FROM
-                            AR_BS_BONUS_103_CALC
-                        WHERE
-                                LAYER = MLAYER + 1
-                          AND USER_TYPE = 0
-                          AND GPV > 0
-                        GROUP BY
-                            INTRODUCER_ID
-                    ) T2 ON T1.USER_ID = T2.INTRODUCER_ID
-                        AND T1.LAYER = MLAYER
-                SET T1.GPV = T2.GPV;-- 没有升级的会员需要将自己的小组业绩清零
-                UPDATE AR_BS_BONUS_103_CALC T
-                SET T.GPV = 0
-                WHERE
-                        T.GPV < T.ACHIEVE_PERF_PV AND T.LAYER = MLAYER + 1 AND GPV > 0;
-
-            END IF;
-            UPDATE AR_BS_BONUS_103_CALC T1
-            SET T1.GPV = T1.GPV + T1.PV
-            WHERE
-                    T1.LAYER = MLAYER;-- 是否达标 如果达标
-            UPDATE AR_BS_BONUS_103_CALC T
-            SET T.USER_TYPE = 10
-            WHERE
-                    T.GPV >= T.ACHIEVE_PERF_PV
-              AND T.LAYER = MLAYER;
-
-            SET MLAYER := MLAYER - 1;
-
-        END WHILE;
-    UPDATE AR_BS_BONUS_103_CALC
-    SET GPV = 0
-    WHERE
-            USER_TYPE = 0
-      AND GPV > 0;
-    SELECT
-        MAX( LAYER ) INTO MLAYER
-    FROM
-        AR_BS_BONUS_103_CALC
-    WHERE
-            USER_TYPE > 0;
-
-    SET MMAXLAYER := MLAYER;-- 添加至新网体页面
-    INSERT INTO AR_BS_BONUS_103_CALC_NET ( USER_ID, INTRODUCER_ID, CALC_PERIOD_ID, USER_TYPE, GPV, DIRECTLY_UNDER, LAYER, TEAM_GPV ) SELECT
-                                                                                                                                         USER_ID,
-                                                                                                                                         INTRODUCER_ID,
-                                                                                                                                         CALC_PERIOD_ID,
-                                                                                                                                         USER_TYPE,
-                                                                                                                                         GPV,
-                                                                                                                                         0,
-                                                                                                                                         LAYER,
-                                                                                                                                         0
-    FROM
-        AR_BS_BONUS_103_CALC
-    WHERE
-            LAYER <= MLAYER; -- 处理新的网体
-    DELETE FROM AR_BS_BONUS_103_CALC_NET WHERE LAYER = MLAYER AND USER_TYPE = 0; SET MLAYER := MLAYER - 1; WHILE MLAYER >= 0 DO-- 计算直属宽度
-    UPDATE AR_BS_BONUS_103_CALC_NET T1
-        INNER JOIN ( SELECT INTRODUCER_ID, COUNT( * ) SONS FROM AR_BS_BONUS_103_CALC_NET WHERE LAYER = MLAYER + 1 GROUP BY INTRODUCER_ID ) T2 ON T1.USER_ID = T2.INTRODUCER_ID
-            AND T1.LAYER = MLAYER
-    SET T1.DIRECTLY_UNDER = T2.SONS;-- 本人达标并且下属满足一个及以上的达标数升级为第二个级别
-    UPDATE AR_BS_BONUS_103_CALC_NET T1
-    SET T1.USER_TYPE = 20
-    WHERE
-            T1.LAYER = MLAYER
-      AND USER_TYPE = 10
-      AND DIRECTLY_UNDER >= 1;-- 计算本层达标人员
-    SELECT
-        COUNT( * ) INTO MCOUNT
-    FROM
-        AR_BS_BONUS_103_CALC_NET C
-    WHERE
-            C.DIRECTLY_UNDER >= 2
-      AND C.USER_TYPE = 0
-      AND LAYER = MLAYER;
-    IF
-        ( MCOUNT > 0 ) THEN
-        CALL CALC20_0 ( MLAYER, PCPID );
-
-    END IF;-- 删除未达标人员
-    CALL CALCDELNET ( MLAYER );
-
-    SET MLAYER := MLAYER - 1;
-
-        END WHILE;-- 计算GPV_4_CALC,会员级别
-    UPDATE AR_BS_BONUS_103_CALC C1
-        INNER JOIN AR_BS_BONUS_103_CALC_NET C2 ON C1.USER_ID = C2.USER_ID
-    SET C1.GPV_4_CALC = C2.GPV,
-        C1.USER_TYPE = C2.USER_TYPE;-- 计算见习奖金
-    UPDATE AR_BS_BONUS_103_CALC C1
-        INNER JOIN ( SELECT INTRODUCER_ID, SUM( GPV ) ALL_GPV FROM AR_BS_BONUS_103_CALC_NET GROUP BY INTRODUCER_ID ) C2 ON C1.USER_ID = C2.INTRODUCER_ID
-            AND C1.USER_TYPE = 20
-    SET C1.BONUS20 = C2.ALL_GPV * MRATE;
-    COMMIT;
-    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE, PERIOD_NUM ) SELECT
-                                                                                                                           C1.USER_ID,
-                                                                                                                           NULL,
-                                                                                                                           20,
-                                                                                                                           C2.ALL_GPV * MRATE,
-                                                                                                                           C2.ALL_GPV,
-                                                                                                                           MRATE,
-                                                                                                                           PCPID
-    FROM
-        AR_BS_BONUS_103_CALC C1
-            INNER JOIN ( SELECT INTRODUCER_ID, SUM( GPV ) ALL_GPV FROM AR_BS_BONUS_103_CALC_NET GROUP BY INTRODUCER_ID ) C2 ON C1.USER_ID = C2.INTRODUCER_ID
-            AND C1.USER_TYPE = 20
-            AND ALL_GPV > 0;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALC20_0` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALC20_0`(IN PLAYER INT,IN `PCPID` INT)
-BEGIN
-	DECLARE
-		FLAG INT DEFAULT 0;
-	DECLARE
-		MUSERID,
-		MMAXUSERID VARCHAR ( 50 );
-	DECLARE
-		MGPV DECIMAL ( 10, 2 );
-	DECLARE
-		MC CURSOR FOR SELECT
-		C.USER_ID 
-	FROM
-		AR_BS_BONUS_103_CALC_NET C 
-	WHERE
-		C.DIRECTLY_UNDER >= 2 
-		AND C.USER_TYPE = 0 
-		AND LAYER = PLAYER;
-	DECLARE
-		CONTINUE HANDLER FOR NOT FOUND 
-		SET FLAG = 1;-- 打开游标
-	OPEN MC;-- 获取结果
-	L2 :
-	LOOP
-			FETCH MC INTO MUSERID;
-		IF
-			FLAG = 1 THEN-- 当无法FETCH会触发HANDLER CONTINUE
-				LEAVE L2;
-			
-		END IF;-- 这里是为了显示获取结果
-		SELECT
-			MIN( GPV ) INTO MGPV 
-		FROM
-			AR_BS_BONUS_103_CALC_NET C 
-		WHERE
-			C.INTRODUCER_ID = MUSERID 
-			AND C.USER_TYPE >= 10;
-		SELECT
-			MAX( USER_ID ) INTO MMAXUSERID 
-		FROM
-			AR_BS_BONUS_103_CALC_NET C 
-		WHERE
-			C.INTRODUCER_ID = MUSERID 
-			AND C.GPV = MGPV;
-		UPDATE AR_BS_BONUS_103_CALC_NET C 
-		SET C.USER_TYPE = 20,
-		C.GPV = MGPV 
-		WHERE
-			USER_ID = MUSERID;
-		UPDATE AR_BS_BONUS_103_CALC_NET C 
-		SET C.GPV = 0 
-		WHERE
-			USER_ID = MMAXUSERID;-- 关闭游标
-		
-		INSERT INTO AR_CALC_BONUS_BS_DETAIL_GPV(USER_ID,INTRODUCER_ID,GPV,PERIOD_NUM)
-		VALUES(MMAXUSERID,MUSERID,MGPV,PCPID);
-	END LOOP;
-	CLOSE MC;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCBLUE` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCBLUE`(IN `PCPID` INT)
-LABEL: BEGIN
-DECLARE MCALCYEAR INT;
-DECLARE MISMONTH,MCALCMONTH,MISSENT TINYINT;
-
-START TRANSACTION;
--- 日志;
-DELETE FROM AR_BS_BONUS_103_CALC_EVENT ;-- WHERE CALC_PERIOD_ID >= PCPID;
-CALL CALCRECORD(-1,'开始',PCPID,NOW());
-COMMIT;
--- SELECT USER_ID INTO MISMONTH FROM ZR_USER;
-SELECT AP.IS_MONTH,AP.CALC_MONTH,AP.CALC_YEAR,AP.IS_SENT
-INTO MISMONTH,MCALCMONTH,MCALCYEAR,MISSENT
-FROM AR_PERIOD AP WHERE AP.PERIOD_NUM = PCPID;
-
-	-- 查看是否月结
--- IF(MISMONTH  =  0 OR MISSENT = 1)THEN
--- LEAVE LABEL;
--- END IF;
-
-
--- 清除数据
-CALL CALCRECORD(1,'清除数据',PCPID,NOW());
-COMMIT;
-CALL CALCCLEAN(PCPID);
-COMMIT;
-
--- 初始化
-CALL CALCRECORD(2,'初始化',PCPID,NOW());
-COMMIT;
-CALL CALCINIT(PCPID,MCALCMONTH,MCALCYEAR);
-COMMIT;
-
-
--- 初始业绩
--- 3.蓝星奖
-CALL CALCRECORD(3,'蓝星奖',PCPID,NOW());
-COMMIT;
-CALL CALC10(PCPID);
-COMMIT;
-
--- 4.新网体
-CALL CALCRECORD(4,'新网体',PCPID,NOW());
-COMMIT;
-CALL CALC20(PCPID);
-COMMIT;
-
--- 5.升级主任
-CALL CALCRECORD(5,'升级主任',PCPID,NOW());
-COMMIT;
-CALL CALCUP30;
-COMMIT;
-
--- 6.计算主任自己第一层的总业绩
-CALL CALCRECORD(6,'计算主任自己第一层的总业绩',PCPID,NOW());
-COMMIT;
-CALL CALCTOTALGPV;
-COMMIT;
-
--- 7.计算平级奖
-CALL CALCRECORD(7,'计算平级奖',PCPID,NOW());
-COMMIT;
-CALL CALCLEVEL(PCPID);
-COMMIT;
-
--- 8.积分
-CALL CALCRECORD(8,'积分',PCPID,NOW());
-COMMIT;
-CALL CALCPOINT;
-COMMIT;
-
--- 9.汇总
-CALL CALCRECORD(9,'汇总',PCPID,NOW());
-COMMIT;
-CALL CALCSUMMARY;
-COMMIT;
-
--- 10.记录总表
-CALL CALCRECORD(10,'记录总表',PCPID,NOW());
-COMMIT;
-CALL CALCKEEP(MCALCYEAR,MCALCMONTH);
-COMMIT;
-
--- 11.计算拨出比
-CALL CALCRECORD(11,'计算拨出比',PCPID,NOW());
-COMMIT;
-CALL CALCSTAT(PCPID);
-COMMIT;
-
-CALL CALCRECORD(12,'结束',PCPID,NOW());
-COMMIT;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCCHECKING` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCCHECKING`(IN `PCPID` INT)
-LABEL : BEGIN-- 遍历数据结束标志
-	DECLARE
-		MCOLUMNNAME,
-		MVALUES,
-		MVALUES0,
-		MVALUES1,
-		MVALUES2 VARCHAR ( 100 );-- 定义预处理SQL语句
-	DECLARE
-		SQL_FOR_SELECT VARCHAR ( 2000 );
-	DECLARE
-		MCOUNT INT DEFAULT 0;
-	DECLARE
-		DONE INT DEFAULT FALSE;
-	DECLARE
-		MISMONTH,
-		MISSEND TINYINT;-- 游标
-	DECLARE
-		CUR_ACCOUNT CURSOR FOR SELECT
-		COLUMN_NAME 
-	FROM
-		INFORMATION_SCHEMA.COLUMNS 
-	WHERE
-		TABLE_NAME = 'AR_CALC_BONUS_BS_DETAIL' 
-		AND TABLE_SCHEMA = 'aikang_db_28' 
-		AND COLUMN_NAME NOT IN ( 'CALC_YEAR', 'CALC_MONTH', 'P_CALC_MONTH', 'CREATED_AT', 'ID', 'LAYER' ) 
-		AND DATA_TYPE IN ( 'DECIMAL', 'DOUBLE', 'INT' );-- 将结束标志绑定到游标
-	DECLARE
-		CONTINUE HANDLER FOR NOT FOUND 
-		SET DONE = TRUE;
-	START TRANSACTION;
-	SELECT
-		AP.IS_MONTH,
-		AP.IS_SENT INTO MISMONTH,
-		MISSEND 
-	FROM
-		AR_PERIOD AP 
-	WHERE
-		AP.PERIOD_NUM = PCPID;-- 查看是否月结
-	IF
-		( MISMONTH = 0 OR MISSEND = 1 ) THEN
-			LEAVE LABEL;
-		
-	END IF;-- 打开游标
-	DELETE 
-	FROM
-		AR_CALC_BONUS_BS_CHECKING 
-	WHERE
-		PERIOD_NUM >= PCPID;
-	OPEN CUR_ACCOUNT;-- 遍历
-	READ_LOOP :
-	LOOP-- 取值 取多个字段
-		FETCH NEXT 
-		FROM
-			CUR_ACCOUNT INTO MCOLUMNNAME;
-		IF
-			DONE THEN
-				LEAVE READ_LOOP;
-			
-		END IF;
-		
-		SET SQL_FOR_SELECT = CONCAT(
-			"SELECT COUNT(*) INTO @MVALUES0 FROM (SELECT IFNULL(A1.USER_ID,'-1') MAIN_ID,IFNULL(A2.USER_ID,'-1') TEST_ID,IFNULL(A1.",
-			MCOLUMNNAME,
-			",0) NAME1,IFNULL(A2.",
-			MCOLUMNNAME,
-			",0) NAME2 FROM AR_CALC_BONUS_BS_DETAIL A1 LEFT JOIN AR_CALC_BONUS_BS_DETAIL_CALC A2 ON A1.USER_ID = A2.USER_ID WHERE A1.PERIOD_NUM = ",
-			PCPID,
-			" AND A2.PERIOD_NUM = ",
-			PCPID,
-			" UNION SELECT IFNULL(A2.USER_ID,'-1') MAIN_ID,IFNULL(A1.USER_ID,'-1') TEST_ID,IFNULL(A2.",
-			MCOLUMNNAME,
-			",0) NAME1,IFNULL(A1.",
-			MCOLUMNNAME,
-			",0) NAME2 FROM AR_CALC_BONUS_BS_DETAIL_CALC A1 LEFT JOIN AR_CALC_BONUS_BS_DETAIL A2 ON A1.USER_ID = A2.USER_ID WHERE A1.PERIOD_NUM = ",
-			PCPID,
-			" AND A2.PERIOD_NUM = ",
-			PCPID,
-			") B WHERE B.MAIN_ID != B.TEST_ID OR ABS(B.NAME1-B.NAME2)>0.5" 
-		);-- 拼接查询SQL语句
-		
-		SET @SQL = SQL_FOR_SELECT;
-		PREPARE STMT 
-		FROM
-			@SQL;-- 预处理动态SQL语句
-		EXECUTE STMT;-- 执行SQL语句
-		DEALLOCATE PREPARE STMT;
-		
-		SET MVALUES0 := @MVALUES0;
-		
-		SET SQL_FOR_SELECT = CONCAT( "SELECT IFNULL(SUM(", MCOLUMNNAME, "),0) INTO @MVALUES1 FROM  AR_CALC_BONUS_BS_DETAIL  WHERE PERIOD_NUM = '", PCPID, "'" );-- 拼接查询SQL语句
-		
-		SET @SQL = SQL_FOR_SELECT;
-		PREPARE STMT 
-		FROM
-			@SQL;-- 预处理动态SQL语句
-		EXECUTE STMT;-- 执行SQL语句
-		DEALLOCATE PREPARE STMT;
-		
-		SET MVALUES1 := @MVALUES1;
-		
-		SET SQL_FOR_SELECT = CONCAT( "SELECT IFNULL(SUM(", MCOLUMNNAME, "),0) INTO @MVALUES2 FROM  AR_CALC_BONUS_BS_DETAIL_CALC  WHERE USER_ID != '0' AND PERIOD_NUM = '", PCPID, "'" );-- 拼接查询SQL语句
-		
-		SET @SQL = SQL_FOR_SELECT;
-		PREPARE STMT 
-		FROM
-			@SQL;-- 预处理动态SQL语句
-		EXECUTE STMT;-- 执行SQL语句
-		DEALLOCATE PREPARE STMT;
-		
-		SET MVALUES2 := @MVALUES2;
-		INSERT INTO AR_CALC_BONUS_BS_CHECKING ( PERIOD_NUM, COLUMN_NAME, DIFF_COUNT, MAIN_SUM, CALC_SUM, DIFF_SUM )
-		VALUES
-			(
-				PCPID,
-				MCOLUMNNAME,
-				MVALUES0,
-				MVALUES1,
-				MVALUES2,
-				ABS(
-					CONVERT (
-						MVALUES1,
-						DECIMAL ( 12, 2 ))- CONVERT (
-						MVALUES2,
-					DECIMAL ( 12, 2 ))));
-		COMMIT;
-		
-	END LOOP;
-	CLOSE CUR_ACCOUNT;
-	SELECT
-		COUNT(*) INTO MCOUNT 
-	FROM
-		AR_CALC_BONUS_BS_CHECKING 
-	WHERE
-		( DIFF_COUNT > 0 OR DIFF_SUM >= 1 ) 
-		AND COLUMN_NAME IN (
-			'USER_TYPE10',
-			'USER_TYPE',
-			'BONUS10',
-			'BONUS20',
-			'BONUS30',
-			'BONUS40',
-			'BONUS50',
-			'BONUS60',
-			'BONUS70',
-			'BONUS80',
-			'BONUS90',
-			'BONUS100',
-			'BONUS110',
-			'ORI_BONUS',
-			'AMOUNT',
-			'PRODUCT_POINT' 
-		);
-	IF
-		( MCOUNT = 0 ) THEN
-			UPDATE AR_CALC_BONUS_BS_STAT T 
-			SET T.CHECK_STATUS = 1 
-		WHERE
-			T.PERIOD_NUM = PCPID;
-		
-	END IF;
-	COMMIT;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCCLEAN` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCCLEAN`(IN `PCPID` INT)
-BEGIN-- 删除当期奖金
-	DELETE 
-	FROM
-		AR_BS_BONUS_103_CALC;
-	DELETE 
-	FROM
-		AR_BS_BONUS_103_TEST 
-	WHERE
-		CALC_PERIOD_ID >= PCPID;-- 使用的奖金表
-	DELETE 
-	FROM
-		AR_CALC_BONUS_BS 
-	WHERE
-		PERIOD_NUM >= PCPID;
-	DELETE 
-	FROM
-		AR_CALC_BONUS_BS_DETAIL 
-	WHERE
-		PERIOD_NUM >= PCPID;-- 删除当期网体
-	DELETE 
-	FROM
-		AR_BS_BONUS_103_CALC_NET;
-	DELETE 
-	FROM
-		AR_BS_BONUS_103_TEST_NET 
-	WHERE
-		CALC_PERIOD_ID >= PCPID;-- 删除拨出表
-	DELETE 
-	FROM
-		AR_CALC_BONUS_BS_STAT 
-	WHERE
-		PERIOD_NUM >= PCPID;-- 删除明细表
-	DELETE 
-	FROM
-		AR_CALC_BONUS_BS_DETAIL_BONUS 
-	WHERE
-		PERIOD_NUM >= PCPID;-- 删除日志
-	DELETE 
-	FROM
-		AR_CALC_BONUS_BS_DETAIL_GPV 
-	WHERE
-		PERIOD_NUM >= PCPID;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCDELNET` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCDELNET`(IN `PLAYER` INT)
-BEGIN
-	DECLARE
-		FLAG INT DEFAULT 0;
-	DECLARE
-		MUSERID,
-		MMAXUSERID,
-		MINTRODUCERID VARCHAR ( 50 );
-	/*DECLARE
-		MGPV DECIMAL ( 10, 2 );
-	DECLARE
-		DN CURSOR FOR SELECT
-		USER_ID 
-	FROM
-		AR_BS_BONUS_103_CALC_NET 
-	WHERE
-		LAYER = PLAYER 
-		AND USER_TYPE = 0;
-	DECLARE
-		CONTINUE HANDLER FOR NOT FOUND 
-		SET FLAG = 1;*/
-	START TRANSACTION;-- 打开游标
-	/*OPEN DN;-- 获取结果
-	L2 :
-	LOOP
-			FETCH DN INTO MUSERID;
-		IF
-			FLAG = 1 THEN-- 当无法FETCH会触发HANDLER CONTINUE
-				LEAVE L2;
-			
-		END IF;-- 查询需要删除会员的推荐人ID
-		SELECT
-			T.INTRODUCER_ID INTO MINTRODUCERID 
-		FROM
-			AR_BS_BONUS_103_CALC_NET T 
-		WHERE
-			T.USER_ID = MUSERID;-- 更改需要删除会员第一代的推荐人ID以及层数
-		UPDATE AR_BS_BONUS_103_CALC_NET T 
-		SET T.INTRODUCER_ID = MINTRODUCERID,
-		T.LAYER = T.LAYER - 1 
-		WHERE
-			T.INTRODUCER_ID = MUSERID;-- 关闭游标
-		
-	END LOOP;
-	CLOSE DN;*/
-	UPDATE AR_BS_BONUS_103_CALC_NET
-	SET DELETED = 1
-	WHERE
-		LAYER = PLAYER 
-		AND USER_TYPE = 0;
-	UPDATE AR_BS_BONUS_103_CALC_NET T1
-	INNER JOIN AR_BS_BONUS_103_CALC_NET T2
-	ON T1.INTRODUCER_ID = T2.USER_ID AND T1.LAYER = PLAYER+1 AND T2.LAYER =  PLAYER AND T2.USER_TYPE = 0
-	SET T1.INTRODUCER_ID = T2.INTRODUCER_ID,T1.LAYER = PLAYER;
-	DELETE
-	FROM
-		AR_BS_BONUS_103_CALC_NET 
-	WHERE
-		LAYER = PLAYER 
-		AND USER_TYPE = 0
-		AND DELETED = 1;
-	COMMIT;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCINIT` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCINIT`(IN `PCPID` INT, IN `PCALCMONTH` TINYINT, IN `PCALCYEAR` INT)
-BEGIN
-
-    DECLARE
-        AC_USER_NO INT;     -- 邀请会员达标数
-    DECLARE
-        MLIMITPV,   -- 邀请会员不及格达标PV
-        AC_PERF_PV DECIMAL ( 10, 2 );   -- 邀请会员及格达标PV
-
-    -- 查询第一个级别的邀请会员数、达标PV值以及等奖比例
-    SELECT
-        T.ACHIEVE_PV,
-        T.ACHIEVE_PERF_PV,
-        T.ACHIEVE_MEMBER_NUM
-    INTO MLIMITPV, AC_PERF_PV, AC_USER_NO
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-        T.ID = 'E121497617216708615';
-
-    INSERT INTO AR_BS_BONUS_103_CALC (
-        LAST_DEC_LV,
-        LAST_EMP_LV,
-        LAST_STATUS,
-        USER_ID,
-        INTRODUCER_ID,
-        LAYER,
-        PV,
-        GPV10,
-        GPV,
-        GPV_4_CALC,
-        USER_TYPE10,
-        USER_TYPE,
-        BONUS10,
-        BONUS20,
-        BONUS30,
-        BONUS40,
-        BONUS50,
-        BONUS60,
-        BONUS70,
-        BONUS80,
-        BONUS90,
-        BONUS100,
-        BONUS110,
-        BONUS,
-        PRODUCT_POINT,
-        CALC_PERIOD_ID,
-        ACHIEVE_MEMBER_NUM,
-        ACHIEVE_PERF_PV
-    ) SELECT
-          AU.LAST_DEC_LV,
-          AU.EMP_LV,
-          AU.STATUS,
-          AU.ID,
-          IFNULL( AURN.PARENT_UID, 0 ),
-          AURN.TOP_DEEP,
-          IFNULL( AO.PV, 0 ),
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          0,
-          PCPID,
-          IFNULL(DO.ACHIEVE_MEMBER_NUM, 0),
-          IF(DO.ACHIEVE_MEMBER_NUM >= AC_USER_NO, AC_PERF_PV, MLIMITPV)
-    FROM
-        AR_USER AU
-    INNER JOIN AR_USER_RELATION_NEW AURN ON AU.ID = AURN.USER_ID
-    LEFT JOIN (
-        SELECT
-            USER_ID,
-            SUM( PV ) PV
-        FROM
-            AR_PERF_ORDER
-        WHERE
-                PERIOD_NUM IN ( SELECT PERIOD_NUM FROM AR_PERIOD WHERE CALC_YEAR = PCALCYEAR AND CALC_MONTH = PCALCMONTH )
-        GROUP BY
-            USER_ID
-    ) AO ON AO.USER_ID = AU.ID
-    LEFT JOIN (
-        SELECT
-            R.PARENT_UID,
-            COUNT(R.USER_ID) AS ACHIEVE_MEMBER_NUM
-        FROM
-            AR_PERF_ORDER O
-            INNER JOIN AR_USER_RELATION_NEW R ON O.USER_ID = R.USER_ID
-        WHERE
-            O.DEC_TYPE = 'ZC' AND O.PERIOD_NUM IN ( SELECT PERIOD_NUM FROM AR_PERIOD WHERE CALC_YEAR = PCALCYEAR AND CALC_MONTH = PCALCMONTH )
-        GROUP BY R.PARENT_UID
-    ) DO ON DO.PARENT_UID = AU.ID
-    WHERE
-            AU.DELETED = 0;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCKEEP` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCKEEP`(IN PCALCYEAR int, IN PCALCMONTH int)
-BEGIN
-    INSERT INTO AR_BS_BONUS_103_TEST SELECT
-        *
-    FROM
-        AR_BS_BONUS_103_CALC;
-    INSERT INTO AR_BS_BONUS_103_TEST_NET SELECT
-        *
-    FROM
-        AR_BS_BONUS_103_CALC_NET;
-    INSERT INTO AR_CALC_BONUS_BS (
-        USER_ID,
-        INTRODUCER_ID,
-        LAST_DEC_LV,
-        LAST_EMP_LV,
-        LAST_STATUS,
-        LEVEL_ID,
-        ORI_BONUS,
-        MANAGE_TAX,
-        AMOUNT,
-        PRODUCT_POINT,
-        PERIOD_NUM,
-        CALC_YEAR,
-        CALC_MONTH,
-        P_CALC_MONTH,
-        CREATED_AT,
-        ORI_BONUS_MNT,
-        MANAGE_TAX_MNT,
-        AMOUNT_MNT,
-        ORI_BONUS_ABBR,
-        MANAGE_TAX_ABBR,
-        AMOUNT_ABBR,
-        ACHIEVE_MEMBER_NUM,
-        ACHIEVE_PERF_PV
-    ) SELECT
-          A.USER_ID,
-          A.INTRODUCER_ID,
-          A.LAST_DEC_LV,
-          A.LAST_EMP_LV,
-          A.LAST_STATUS,
-          B.ID,
-          IFNULL( A.BONUS, 0 ),
-          0,
-          IFNULL( A.BONUS, 0 ),
-          IFNULL( A.PRODUCT_POINT, 0 ),
-          CALC_PERIOD_ID,
-          PCALCYEAR,
-          PCALCYEAR*100+PCALCMONTH,
-          NOW(),
-          UNIX_TIMESTAMP(
-                  NOW()),
-          IFNULL( A.BONUS_MNT, 0 ),
-          0,
-          IFNULL( A.BONUS_MNT, 0 ),
-          IFNULL( A.BONUS_ABBR, 0 ),
-          0,
-          IFNULL( A.BONUS_ABBR, 0 ),
-          A.ACHIEVE_MEMBER_NUM,
-          A.ACHIEVE_PERF_PV
-    FROM
-        AR_BS_BONUS_103_CALC A
-            LEFT JOIN AR_EMPLOY_LEVEL B ON A.USER_TYPE = B.SORT * 10
-    WHERE
-            A.BONUS > 0
-       OR A.PRODUCT_POINT > 0;
-    INSERT INTO AR_CALC_BONUS_BS_DETAIL (
-        USER_ID,
-        INTRODUCER_ID,
-        LAST_DEC_LV,
-        LAST_EMP_LV,
-        LAST_STATUS,
-        LEVEL_ID,
-        ORI_BONUS,
-        MANAGE_TAX,
-        AMOUNT,
-        PRODUCT_POINT,
-        PERIOD_NUM,
-        LAYER,
-        PV,
-        GPV10,
-        GPV,
-        GPV_4_CALC,
-        USER_TYPE10,
-        USER_TYPE,
-        BONUS10,
-        BONUS20,
-        BONUS30,
-        BONUS40,
-        BONUS50,
-        BONUS60,
-        BONUS70,
-        BONUS80,
-        BONUS90,
-        BONUS100,
-        BONUS110,
-        CALC_YEAR,
-        CALC_MONTH,
-        P_CALC_MONTH,
-        CREATED_AT,
-        ORI_BONUS_MNT,
-        MANAGE_TAX_MNT,
-        AMOUNT_MNT,
-        ORI_BONUS_ABBR,
-        MANAGE_TAX_ABBR,
-        AMOUNT_ABBR
-    ) SELECT
-          USER_ID,
-          INTRODUCER_ID,
-          LAST_DEC_LV,
-          LAST_EMP_LV,
-          LAST_STATUS,
-          B.ID,
-          IFNULL( BONUS, 0 ),
-          0,
-          IFNULL( BONUS, 0 ),
-          IFNULL( PRODUCT_POINT, 0 ),
-          CALC_PERIOD_ID,
-          LAYER,
-          PV,
-          GPV10,
-          GPV,
-          GPV_4_CALC,
-          USER_TYPE10,
-          USER_TYPE,
-          BONUS10,
-          BONUS20,
-          BONUS30,
-          BONUS40,
-          BONUS50,
-          BONUS60,
-          BONUS70,
-          BONUS80,
-          BONUS90,
-          BONUS100,
-          BONUS110,
-          PCALCYEAR,
-          PCALCYEAR*100+PCALCMONTH,
-          NOW(),
-          UNIX_TIMESTAMP(
-                  NOW()),
-          IFNULL( A.BONUS_MNT, 0 ),
-          0,
-          IFNULL( A.BONUS_MNT, 0 ),
-          IFNULL( A.BONUS_ABBR, 0 ),
-          0,
-          IFNULL( A.BONUS_ABBR, 0 )
-    FROM
-        AR_BS_BONUS_103_CALC A
-            LEFT JOIN ( SELECT ID, SORT FROM AR_EMPLOY_LEVEL ) B ON A.USER_TYPE = B.SORT * 10;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCLEVEL` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCLEVEL`(IN `PCPID` INT)
-BEGIN
-	DECLARE
-		FLAG,
-		MLAYER,
-		MUSERTYPE INT DEFAULT 0;
-	DECLARE
-		MGPV DECIMAL ( 10, 2 );
-	
-		DECLARE
-		MC CURSOR FOR SELECT
-		LAYER
-	FROM
-		AR_BS_BONUS_103_CALC_NET T 
-	WHERE
-		T.USER_TYPE = 30 GROUP BY LAYER ORDER BY LAYER DESC;
-	DECLARE
-		CONTINUE HANDLER FOR NOT FOUND 
-		SET FLAG = 1;
-	START TRANSACTION;-- 打开游标
-
-	OPEN MC;-- 获取结果
-	L2 :
-	LOOP
-			FETCH MC INTO MLAYER;
-		IF
-			FLAG = 1 THEN-- 当无法FETCH会触发HANDLER CONTINUE
-				LEAVE L2;
-			
-		END IF;
-		
--- 计算当前层数的奖金以及向上所贡献的奖金
-			CALL CALCLEVEL_ ( MLAYER ,PCPID);
-	END LOOP;
-	CLOSE MC;
-	/*WHILE
-			( MLAYER >= 0 ) DO-- 计算当前层数的奖金以及向上所贡献的奖金
-			CALL CALCLEVEL_ ( MLAYER );
-		
-		SET MLAYER := MLAYER - 1;
-		
-	END WHILE;*/-- 级别更新
-	
-
-	UPDATE AR_BS_BONUS_103_CALC C1
-	INNER JOIN AR_BS_BONUS_103_CALC_NET C2 ON C1.USER_ID = C2.USER_ID 
-	AND C1.USER_TYPE <> C2.USER_TYPE 
-	SET C1.USER_TYPE = C2.USER_TYPE;
-
-
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCLEVEL_` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCLEVEL_`(IN PLAYER int, IN PCPID int)
-BEGIN
-	DECLARE
-		FLAG,
-		MLAYER,
-		MUSERTYPE INT DEFAULT 0;
-	DECLARE
-		MUSERID,
-		MBONUSID,
-		MNEWBONUSID VARCHAR ( 50 );
-	DECLARE
-		MRATE,
-		MRATE30,
-		MRATE40,
-		MRATE50,
-		MRATE60,
-		MRATE70,
-		MRATE80,
-		MRATE90,
-		MRATE100,
-		MRATE110,
-		MBONUS,
-		MGPV DECIMAL ( 10, 2 );
-	DECLARE
-		MC CURSOR FOR SELECT
-		C.USER_ID,
-		C.TEAM_GPV 
-	FROM
-		AR_BS_BONUS_103_CALC_NET C 
-	WHERE
-		C.USER_TYPE >= 30 
-		AND LAYER = PLAYER;
-	DECLARE
-		CONTINUE HANDLER FOR NOT FOUND 
-		SET FLAG = 1;
-
-	START TRANSACTION;
-
-	-- 取各级别蓝星奖比例【开始】
-	SELECT
-		T.BS_PERCENT / 100 INTO MRATE30 
-	FROM
-		AR_EMPLOY_LEVEL T 
-	WHERE
-		T.ID = 'E121497617216708616';
-
-	SELECT
-		T.BS_PERCENT / 100 INTO MRATE40 
-	FROM
-		AR_EMPLOY_LEVEL T 
-	WHERE
-		T.ID = '67BE6A4D03C52288E055736AECE8644D';
-
-	SELECT
-		T.BS_PERCENT / 100 INTO MRATE50 
-	FROM
-		AR_EMPLOY_LEVEL T 
-	WHERE
-		T.ID = '67BE6EA2070D22EBE055736AECE8644D';
-
-	SELECT
-		T.BS_PERCENT / 100 INTO MRATE60
-	FROM
-		AR_EMPLOY_LEVEL T
-	WHERE
-		T.ID = '67BE742A336F2370E055736AECE8644D';
-
-	SELECT
-		T.BS_PERCENT / 100 INTO MRATE70
-	FROM
-		AR_EMPLOY_LEVEL T
-	WHERE
-		T.ID = '67BE805032C22492E055736AECE8644D';
-
-# 	SELECT
-# 		T.BS_PERCENT / 100 INTO MRATE80
-# 	FROM
-# 		AR_EMPLOY_LEVEL T
-# 	WHERE
-# 		T.ID = '67BE82019BE524CAE055736AECE8644D';
-#
-# 	SELECT
-# 		T.BS_PERCENT / 100 INTO MRATE90
-# 	FROM
-# 		AR_EMPLOY_LEVEL T
-# 	WHERE
-# 		T.ID = '99BE5FE7857C216AE055736AECE8644D';
-#
-# 	SELECT
-# 		T.BS_PERCENT / 100 INTO MRATE100
-# 	FROM
-# 		AR_EMPLOY_LEVEL T
-# 	WHERE
-# 		T.ID = '99BE5FE9008C216AE055736AECE8644D';
-#
-# 	SELECT
-# 		T.BS_PERCENT / 100 INTO MRATE110
-# 	FROM
-# 		AR_EMPLOY_LEVEL T
-# 	WHERE
-# 		T.ID = '99BE5FE7857C216AE000223AECE8644D';
-    -- 取各级别蓝星奖比例【结束】
-
-    -- 打开游标
-	OPEN MC;-- 获取结果
-	L2 :
-	LOOP
-			FETCH MC INTO MUSERID,
-			MGPV;
-		IF
-			FLAG = 1 THEN-- 当无法FETCH会触发HANDLER CONTINUE
-				LEAVE L2;
-			
-		END IF;-- 这里是为了显示获取结果
-		
-		SET MLAYER := 1;
-		
-		SET MBONUSID := MUSERID;
-		OUTER_LABEL :
-		WHILE ( MLAYER <= 5 ) DO
-			IF ( MLAYER > 1 ) THEN
-					CALL CALCREFEREE ( MBONUSID, MNEWBONUSID );
-				IF ( ISNULL( MNEWBONUSID ) OR MNEWBONUSID = 0 ) THEN
-						LEAVE OUTER_LABEL;
-					ELSE 
-						SET MBONUSID := MNEWBONUSID;
-					
-				END IF;
-				
-			END IF;
-			IF
-				( MLAYER = 1 ) THEN
-					
-					SET MRATE := MRATE30;
-				
-				ELSEIF ( MLAYER = 2 ) THEN
-				
-				SET MRATE := MRATE40;
-				
-				ELSEIF ( MLAYER = 3 ) THEN
-				
-				SET MRATE := MRATE50;
-				
-				ELSEIF ( MLAYER = 4 ) THEN
-				
-				SET MRATE := MRATE60;
-				
-				ELSEIF ( MLAYER = 5 ) THEN
-				
-				SET MRATE := MRATE70;
-				
-				ELSEIF ( MLAYER = 6 ) THEN
-				
-				SET MRATE := MRATE80;
-				
-				ELSEIF ( MLAYER = 7 ) THEN
-				
-				SET MRATE := MRATE90;
-				
-				ELSEIF ( MLAYER = 8 ) THEN
-				
-				SET MRATE := MRATE100;
-				
-				ELSEIF ( MLAYER = 9 ) THEN
-				
-				SET MRATE := MRATE110;
-				
-			END IF;
-			
-			SET MBONUS := MGPV * MRATE;
-			IF
-				( MLAYER = 1 ) THEN
-					UPDATE AR_BS_BONUS_103_CALC T 
-					SET T.BONUS30 = T.BONUS30 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, NULL, 30, MBONUS, MGPV, MRATE ,PCPID);
-				
-				ELSEIF ( MLAYER = 2 ) THEN
-				UPDATE AR_BS_BONUS_103_CALC T 
-				SET T.BONUS40 = T.BONUS40 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, MUSERID, 40, MBONUS, MGPV, MRATE ,PCPID);
-				
-				ELSEIF ( MLAYER = 3 ) THEN
-				UPDATE AR_BS_BONUS_103_CALC T 
-				SET T.BONUS50 = T.BONUS50 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, MUSERID, 50, MBONUS, MGPV, MRATE,PCPID );
-				
-				ELSEIF ( MLAYER = 4 ) THEN
-				UPDATE AR_BS_BONUS_103_CALC T 
-				SET T.BONUS60 = T.BONUS60 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, MUSERID, 60, MBONUS, MGPV, MRATE,PCPID );
-				
-				ELSEIF ( MLAYER = 5 ) THEN
-				UPDATE AR_BS_BONUS_103_CALC T 
-				SET T.BONUS70 = T.BONUS70 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, MUSERID, 70, MBONUS, MGPV, MRATE,PCPID );
-				
-				ELSEIF ( MLAYER = 6 ) THEN
-				UPDATE AR_BS_BONUS_103_CALC T 
-				SET T.BONUS80 = T.BONUS80 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, MUSERID, 80, MBONUS, MGPV, MRATE,PCPID );
-				
-				ELSEIF ( MLAYER = 7 ) THEN
-				UPDATE AR_BS_BONUS_103_CALC T 
-				SET T.BONUS90 = T.BONUS90 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, MUSERID, 90, MBONUS, MGPV, MRATE,PCPID );
-				
-				ELSEIF ( MLAYER = 8 ) THEN
-				UPDATE AR_BS_BONUS_103_CALC T 
-				SET T.BONUS100 = T.BONUS100 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, MUSERID, 100, MBONUS, MGPV, MRATE,PCPID );
-				
-				ELSEIF ( MLAYER = 9 ) THEN
-				UPDATE AR_BS_BONUS_103_CALC T 
-				SET T.BONUS110 = T.BONUS110 + MBONUS 
-				WHERE
-					T.USER_ID = MBONUSID;
-				INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-				VALUES
-					( MBONUSID, MUSERID, 110, MBONUS, MGPV, MRATE,PCPID );
-				
-			END IF;-- 计算会员的级别
-			UPDATE AR_BS_BONUS_103_CALC_NET T 
-			SET T.USER_TYPE = ( MLAYER + 2 )* 10 
-			WHERE
-				T.USER_ID = MBONUSID 
-				AND USER_TYPE <=(
-					MLAYER + 1 
-				)* 10;
-			
-			SET MLAYER := MLAYER + 1;
-			
-		END WHILE;-- 关闭游标
-		
-	END LOOP;
-	CLOSE MC;
-	COMMIT;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCLEVEL_kevin_01` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCLEVEL_kevin_01`(IN PLAYER int, IN PCPID int)
-BEGIN
-    DECLARE
-        FLAG,
-        MLAYER,
-        MUSERTYPE INT DEFAULT 0;
-    DECLARE
-        MUSERID,
-        MBONUSID,
-        MNEWBONUSID VARCHAR ( 50 );
-    DECLARE
-        MRATE,
-        MRATE30,
-        MRATE40,
-        MRATE50,
-        MRATE60,
-        MRATE70,
-        MRATE80,
-        MRATE90,
-        MRATE100,
-        MRATE110,
-        MBONUS,
-        MGPV DECIMAL ( 10, 2 );
-    DECLARE
-        MC CURSOR FOR SELECT
-                          C.USER_ID,
-                          C.TEAM_GPV
-                      FROM
-                          AR_BS_BONUS_103_CALC_NET C
-                      WHERE
-                              C.USER_TYPE >= 30
-                        AND LAYER = PLAYER;
-    DECLARE
-        CONTINUE HANDLER FOR NOT FOUND
-        SET FLAG = 1;
-    START TRANSACTION;
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE30
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = 'E121497617216708616';
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE40
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '67BE6A4D03C52288E055736AECE8644D';
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE50
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '67BE6EA2070D22EBE055736AECE8644D';
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE60
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '67BE742A336F2370E055736AECE8644D';
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE70
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '67BE805032C22492E055736AECE8644D';
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE80
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '67BE82019BE524CAE055736AECE8644D';
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE90
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '99BE5FE7857C216AE055736AECE8644D';
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE100
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '99BE5FE9008C216AE055736AECE8644D';
-    SELECT
-            T.BS_PERCENT / 100 INTO MRATE110
-    FROM
-        AR_EMPLOY_LEVEL T
-    WHERE
-            T.ID = '99BE5FE7857C216AE000223AECE8644D';-- 打开游标
-    OPEN MC;-- 获取结果
-    L2 :
-    LOOP
-        FETCH MC INTO MUSERID,
-            MGPV;
-        IF
-                FLAG = 1 THEN-- 当无法FETCH会触发HANDLER CONTINUE
-            LEAVE L2;
-
-        END IF;-- 这里是为了显示获取结果
-
-        SET MLAYER := 1;
-
-        SET MBONUSID := MUSERID;
-        OUTER_LABEL :
-        WHILE
-            ( MLAYER <= 9 ) DO
-                IF
-                    ( MLAYER > 1 ) THEN
-                    CALL CALCREFEREE ( MBONUSID, MNEWBONUSID );
-                    IF
-                        ( ISNULL( MNEWBONUSID ) OR MNEWBONUSID = 0 ) THEN
-                        LEAVE OUTER_LABEL;
-                    ELSE
-                        SET MBONUSID := MNEWBONUSID;
-
-                    END IF;
-
-                END IF;
-                IF
-                    ( MLAYER = 1 ) THEN
-
-                    SET MRATE := MRATE30;
-
-                ELSEIF ( MLAYER = 2 ) THEN
-
-                    SET MRATE := MRATE40;
-
-                ELSEIF ( MLAYER = 3 ) THEN
-
-                    SET MRATE := MRATE50;
-
-                ELSEIF ( MLAYER = 4 ) THEN
-
-                    SET MRATE := MRATE60;
-
-                ELSEIF ( MLAYER = 5 ) THEN
-
-                    SET MRATE := MRATE70;
-
-                ELSEIF ( MLAYER = 6 ) THEN
-
-                    SET MRATE := MRATE80;
-
-                ELSEIF ( MLAYER = 7 ) THEN
-
-                    SET MRATE := MRATE90;
-
-                ELSEIF ( MLAYER = 8 ) THEN
-
-                    SET MRATE := MRATE100;
-
-                ELSEIF ( MLAYER = 9 ) THEN
-
-                    SET MRATE := MRATE110;
-
-                END IF;
-
-                SET MBONUS := MGPV * MRATE;
-                IF
-                    ( MLAYER = 1 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS30 = T.BONUS30 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, NULL, 30, MBONUS, MGPV, MRATE ,PCPID);
-
-                ELSEIF ( MLAYER = 2 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS40 = T.BONUS40 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, MUSERID, 40, MBONUS, MGPV, MRATE ,PCPID);
-
-                ELSEIF ( MLAYER = 3 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS50 = T.BONUS50 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, MUSERID, 50, MBONUS, MGPV, MRATE,PCPID );
-
-                ELSEIF ( MLAYER = 4 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS60 = T.BONUS60 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, MUSERID, 60, MBONUS, MGPV, MRATE,PCPID );
-
-                ELSEIF ( MLAYER = 5 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS70 = T.BONUS70 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, MUSERID, 70, MBONUS, MGPV, MRATE,PCPID );
-
-                ELSEIF ( MLAYER = 6 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS80 = T.BONUS80 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, MUSERID, 80, MBONUS, MGPV, MRATE,PCPID );
-
-                ELSEIF ( MLAYER = 7 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS90 = T.BONUS90 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, MUSERID, 90, MBONUS, MGPV, MRATE,PCPID );
-
-                ELSEIF ( MLAYER = 8 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS100 = T.BONUS100 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, MUSERID, 100, MBONUS, MGPV, MRATE,PCPID );
-
-                ELSEIF ( MLAYER = 9 ) THEN
-                    UPDATE AR_BS_BONUS_103_CALC T
-                    SET T.BONUS110 = T.BONUS110 + MBONUS
-                    WHERE
-                            T.USER_ID = MBONUSID;
-                    INSERT INTO AR_CALC_BONUS_BS_DETAIL_BONUS ( USER_ID, INTRODUCER_ID, LAST_EMP_LV, ORI_BONUS, PV, RATE,PERIOD_NUM )
-                    VALUES
-                        ( MBONUSID, MUSERID, 110, MBONUS, MGPV, MRATE,PCPID );
-
-                END IF;-- 计算会员的级别
-                UPDATE AR_BS_BONUS_103_CALC_NET T
-                SET T.USER_TYPE = ( MLAYER + 2 )* 10
-                WHERE
-                        T.USER_ID = MBONUSID
-                  AND USER_TYPE <=(
-                                          MLAYER + 1
-                                      )* 10;
-
-                SET MLAYER := MLAYER + 1;
-
-            END WHILE;-- 关闭游标
-
-    END LOOP;
-    CLOSE MC;
-    COMMIT;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCMAIN` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCMAIN`(IN `PCPID` int,OUT `PRESULT` varchar(100))
-BEGIN
-	#Routine body goes here...
-DECLARE EXIT HANDLER FOR SQLEXCEPTION  
-SET PRESULT = 'FAIL';
- CALL CalcBlue(PCPID);
-SET PRESULT = 'SUCCESS';
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCPOINT` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCPOINT`()
-BEGIN
-	DECLARE
-		MPOINTRATE DECIMAL ( 10, 2 );
-	SELECT 
-	VALUE
-		/ 100 INTO MPOINTRATE 
-	FROM
-		AR_CONFIG 
-	WHERE
-		CONFIG_NAME = 'bsNoPvPointsPercent';
-	UPDATE AR_BS_BONUS_103_CALC 
-	SET PRODUCT_POINT = PV * MPOINTRATE 
-	WHERE
-		USER_TYPE10 = 0 
-		AND USER_TYPE = 0 
-		AND PV > 0;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCRECORD` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCRECORD`(IN `PID` INT, IN `PEVENT` VARCHAR ( 255 ), IN `PCPID` INT, IN `PNOW` DATETIME)
-BEGIN
-	INSERT INTO AR_BS_BONUS_103_CALC_EVENT ( ID, EVENT, CREATION_TIME, CALC_PERIOD_ID )
-	VALUES
-		( PID, PEVENT, NOW(), PCPID );
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCREFEREE` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCREFEREE`(IN `PBONUSID` VARCHAR ( 50 ),
-	OUT `PNEWBONUSID` VARCHAR ( 50 ))
-BEGIN
-	DECLARE
-		MUSERID,
-		MBONUSID VARCHAR ( 50 );
-	DECLARE
-		MUSERTYPE INT;
-	
-	/*SET MUSERID := PBONUSID;
-	OUTER_LABEL :
-	WHILE
-			(
-			ISNULL( MBONUSID )) DO
-		SELECT
-			INTRODUCER_ID INTO MUSERID 
-		FROM
-			AR_BS_BONUS_103_CALC_NET T 
-		WHERE
-			T.USER_ID = MUSERID;
-		IF
-			( MUSERID = 0 ) THEN
-				
-				SET PNEWBONUSID := NULL;
-			LEAVE OUTER_LABEL;
-			
-		END IF;
-		SELECT
-			USER_TYPE INTO MUSERTYPE 
-		FROM
-			AR_BS_BONUS_103_CALC_NET T 
-		WHERE
-			T.USER_ID = MUSERID;
-		IF
-			( MUSERTYPE >= 30 ) THEN
-				
-				SET PNEWBONUSID := MUSERID;
-			LEAVE OUTER_LABEL;
-			
-		END IF;
-		
-	END WHILE;*/
-  SELECT INTRODUCER_ID30 INTO PNEWBONUSID FROM AR_BS_BONUS_103_CALC_NET WHERE USER_ID = PBONUSID;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCSTAT` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCSTAT`(IN PCPID int)
-BEGIN
-	INSERT INTO AR_CALC_BONUS_BS_STAT (
-		PERIOD_NUM,
-		TOTAL_PV,
-		BONUS10,
-		PERCENT10,
-		BONUS20,
-		PERCENT20,
-		BONUS30,
-		PERCENT30,
-		BONUS40,
-		PERCENT40,
-		BONUS50,
-		PERCENT50,
-		BONUS60,
-		PERCENT60,
-		BONUS70,
-		PERCENT70,
-		BONUS80,
-		PERCENT80,
-		BONUS90,
-		PERCENT90,
-		BONUS100,
-		PERCENT100,
-		BONUS110,
-		PERCENT110,
-		BONUS,
-		PERCENT,
-		CHECK_STATUS,
-        BONUS_MNT,
-        BONUS_MNT_PERCENT,
-        BONUS_ABBR,
-        BONUS_ABBR_PERCENT
-	) SELECT
-	PCPID,
-	SUM( PV ),
-	SUM( BONUS10 ),
-	0,
-	SUM( BONUS20 ),
-	0,
-	SUM( BONUS30 ),
-	0,
-	SUM( BONUS40 ),
-	0,
-	SUM( BONUS50 ),
-	0,
-	SUM( BONUS60 ),
-	0,
-	SUM( BONUS70 ),
-	0,
-	SUM( BONUS80 ),
-	0,
-	SUM( BONUS90 ),
-	0,
-	SUM( BONUS100 ),
-	0,
-	SUM( BONUS110 ),
-	0,
-	SUM( BONUS ),
-	0,
-	0,
-    SUM(BONUS_MNT),
-    0,
-	SUM(BONUS_ABBR),
-    0
-	FROM
-		AR_BS_BONUS_103_CALC;
-
-	UPDATE AR_CALC_BONUS_BS_STAT 
-        SET PERCENT10 = BONUS10 / TOTAL_PV,
-        PERCENT20 = BONUS20 / TOTAL_PV,
-        PERCENT30 = BONUS30 / TOTAL_PV,
-        PERCENT40 = BONUS40 / TOTAL_PV,
-        PERCENT50 = BONUS50 / TOTAL_PV,
-        PERCENT60 = BONUS60 / TOTAL_PV,
-        PERCENT70 = BONUS70 / TOTAL_PV,
-        PERCENT80 = BONUS80 / TOTAL_PV,
-        PERCENT90 = BONUS90 / TOTAL_PV,
-        PERCENT100 = BONUS100 / TOTAL_PV,
-        PERCENT110 = BONUS110 / TOTAL_PV,
-        PERCENT = BONUS / TOTAL_PV,
-        BONUS_MNT_PERCENT = BONUS_MNT / TOTAL_PV,
-        BONUS_ABBR_PERCENT = BONUS_ABBR / TOTAL_PV
-	WHERE
-		PERIOD_NUM = PCPID AND TOTAL_PV > 0;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCSUMMARY` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCSUMMARY`()
-BEGIN
-	UPDATE AR_BS_BONUS_103_CALC T 
-	    SET T.BONUS = BONUS10 + BONUS20 + BONUS30 + BONUS40 + BONUS50 + BONUS60 + BONUS70 + BONUS80 + BONUS90 + BONUS100 + BONUS110,
-	        T.BONUS_MNT = BONUS30 + BONUS40 + BONUS50 + BONUS60 + BONUS70 + BONUS80 + BONUS90 + BONUS100 + BONUS110,
-	        T.BONUS_ABBR = BONUS10 + BONUS20
-	WHERE
-		T.BONUS10 > 0 
-		OR T.BONUS20 > 0 
-		OR T.BONUS30 > 0 
-		OR T.BONUS40 > 0 
-		OR T.BONUS50 > 0 
-		OR T.BONUS60 > 0 
-		OR T.BONUS70 > 0 
-		OR T.BONUS80 > 0 
-		OR T.BONUS90 > 0 
-		OR T.BONUS100 > 0 
-		OR T.BONUS110 > 0;
-	UPDATE AR_BS_BONUS_103_CALC T 
-	SET GPV = 0 
-	WHERE
-		T.INTRODUCER_ID = '0' 
-		AND USER_TYPE = 0;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCTOTALGPV` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCTOTALGPV`()
-BEGIN
-	DECLARE
-		MLAYER,
-		MMINLAYER,
-		MUSERTYPE INT DEFAULT 0;
-	DECLARE
-		MUSERID,
-		MMAXUSERID VARCHAR ( 50 );
-	DECLARE
-		MGPV DECIMAL ( 10, 2 );
-	SELECT
-		MAX( LAYER ) INTO MLAYER 
-	FROM
-		AR_BS_BONUS_103_CALC_NET 
-	WHERE
-		GPV > 0;
-	SELECT
-		MIN( LAYER ) INTO MMINLAYER 
-	FROM
-		AR_BS_BONUS_103_CALC_NET 
-	WHERE
-		USER_TYPE = 30;
-	UPDATE AR_BS_BONUS_103_CALC_NET T1
-	INNER JOIN AR_BS_BONUS_103_CALC_NET T2 ON IFNULL( T1.INTRODUCER_ID, '0' ) = T2.USER_ID 
-	AND T1.USER_TYPE = 30 
-	AND T2.USER_TYPE = 30 
-	SET T1.INTRODUCER_ID30 = T2.USER_ID;
-	WHILE
-			MLAYER > MMINLAYER DO
-			CALL CALCTOTALGPV_ ( MLAYER, MMINLAYER );
-		
-		SET MLAYER = MLAYER - 1;
-		
-	END WHILE;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCTOTALGPV_` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCTOTALGPV_`(IN `PLAYER` INT, -- 第几层
-	IN `PMINLAYER` INT)
-BEGIN
-	DECLARE
-		FLAG,
-		MLAYER,
-		MINTLAYER,
-		MUSERTYPE,
-		MINTTYPE INT DEFAULT 0;
-	DECLARE
-		MGPV DECIMAL ( 10, 2 );
-	DECLARE
-		MUSERID,
-		MUSERINTID,
-		MINTUSERID,
-		MINTRODUCERID VARCHAR ( 50 );
-	DECLARE
-		MC CURSOR FOR SELECT
-		C.USER_ID,
-		C.INTRODUCER_ID,
-		C.USER_TYPE,
-		C.GPV 
-	FROM
-		(
-		SELECT
-			USER_ID,
-			IFNULL( INTRODUCER_ID, '0' ) INTRODUCER_ID,
-			USER_TYPE,
-			GPV 
-		FROM
-			AR_BS_BONUS_103_CALC_NET 
-		WHERE
-			LAYER = PLAYER 
-			AND GPV > 0 
-			OR ( GPV = 0 AND USER_TYPE = 30 ) 
-		ORDER BY
-			USER_ID DESC 
-		) C;
-	DECLARE
-		CONTINUE HANDLER FOR NOT FOUND 
-		SET FLAG = 1;
-	START TRANSACTION;-- 打开游标
-	OPEN MC;-- 获取结果
-	L2 :
-	LOOP
-			FETCH MC INTO MUSERID,
-			MUSERINTID,
-			MUSERTYPE,
-			MGPV;
-		IF
-			FLAG = 1 THEN-- 当无法FETCH会触发HANDLER CONTINUE
-				LEAVE L2;
-			
-		END IF;
-		SET MLAYER = PLAYER;
-		
-		SET MINTUSERID = MUSERINTID;
-		IF
-			( MINTUSERID != '0' ) THEN
-				OUTLABEL :
-			WHILE
-					MLAYER > PMINLAYER DO
-				SELECT
-					INTRODUCER_ID,
-					USER_TYPE,
-					LAYER INTO MINTRODUCERID,
-					MINTTYPE,
-					MLAYER 
-				FROM
-					AR_BS_BONUS_103_CALC_NET 
-				WHERE
-					USER_ID = MINTUSERID;
-				IF
-					( MINTUSERID != MUSERINTID AND MINTTYPE = 30 ) THEN
-						UPDATE AR_BS_BONUS_103_CALC_NET 
-						SET TEAM_GPV = TEAM_GPV + MGPV 
-					WHERE
-						USER_ID = MINTUSERID;
-					IF
-						( MUSERTYPE = 30 ) THEN
-							UPDATE AR_BS_BONUS_103_CALC_NET 
-							SET INTRODUCER_ID30 = MINTUSERID 
-						WHERE
-							USER_ID = MUSERID 
-							AND INTRODUCER_ID30 IS NULL;
-						
-					END IF;
-					LEAVE OUTLABEL;
-					
-				END IF;
-				
-				SET MINTUSERID = MINTRODUCERID;
-				
-			END WHILE;
-			
-		END IF;-- 关闭游标
-		
-	END LOOP;
-	CLOSE MC;
-	COMMIT;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCUP30` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCUP30`()
-BEGIN
-	START TRANSACTION;
-	UPDATE AR_BS_BONUS_103_CALC_NET T1 
-	SET T1.USER_TYPE = 30 
-	WHERE
-		USER_TYPE >= 10 
-		AND DIRECTLY_UNDER >= 3;
-	COMMIT;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CALCUPGARDE` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CALCUPGARDE`(IN `PLAYER` INT)
-BEGIN
-	DECLARE
-		MLAYER,
-		MCOUNT,
-		MCOUNT1,
-		MCOUNT2 INT;
-	
-	SET MLAYER := PLAYER;
-	SELECT
-		COUNT(*) INTO MCOUNT 
-	FROM
-		AR_BS_BONUS_103_CALC T 
-	WHERE
-		T.LAYER = MLAYER 
-		AND USER_TYPE10 = 10 
-		AND USER_TYPE = 0;
-	IF
-		( MCOUNT > 0 ) THEN
-			BREAKLABLE :
-		WHILE
-				MLAYER > 0 DO
-			SELECT
-				COUNT(*) INTO MCOUNT1 
-			FROM
-				AR_BS_BONUS_103_CALC T1 
-			WHERE
-				T1.USER_TYPE10 = 10 
-				AND T1.LAYER = MLAYER - 1;
-			UPDATE AR_BS_BONUS_103_CALC T1
-			INNER JOIN ( SELECT INTRODUCER_ID FROM AR_BS_BONUS_103_CALC WHERE LAYER = MLAYER AND USER_TYPE10 = 10 GROUP BY INTRODUCER_ID ) T2 ON T1.USER_ID = T2.INTRODUCER_ID 
-			AND T1.USER_TYPE10 = 0 
-			AND T1.LAYER = MLAYER - 1 
-			SET T1.USER_TYPE10 = 10,
-			T1.USER_TYPE = 10;
-			SELECT
-				COUNT(*) INTO MCOUNT2 
-			FROM
-				AR_BS_BONUS_103_CALC T1 
-			WHERE
-				T1.USER_TYPE10 = 10 
-				AND T1.LAYER = MLAYER - 1;
-			IF
-				( MCOUNT1 = MCOUNT2 ) THEN
-					LEAVE BREAKLABLE;
-				
-			END IF;
-			
-			SET MLAYER := MLAYER - 1;
-			
-		END WHILE;
-		
-	END IF;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CLEANACTIVE` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CLEANACTIVE`(IN `UNUMBER` VARCHAR(32))
-BEGIN
-DECLARE t_error INTEGER DEFAULT 0;    
-DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1;
-
-START TRANSACTION;
-  -- 备份用户的余额 奖金 兑换积分 复消积分
-	INSERT INTO `AR_ACTIVED_ACCOUNT_BACK` ( `USER_ID`, `USER_NAME`, `USER_CASH`, `EXCHANGE_POINTS`, `EXCHANGE_POINTS_TOTAL`, `RECONSUME_POINTS`, `RECONSUME_POINTS_TOTAL`, `USER_BONUS`, `RECONSUME_POINTS_EXPIRED` ) SELECT
-`AR_USER_BONUS`.`USER_ID`,
-`AR_USER`.`USER_NAME`,
-`AR_USER_WALLET`.`CASH`,
-`AR_USER_BONUS`.`EXCHANGE_POINTS`,
-`AR_USER_BONUS`.`EXCHANGE_POINTS_TOTAL`,
-`AR_USER_BONUS`.`RECONSUME_POINTS`,
-`AR_USER_BONUS`.`RECONSUME_POINTS_TOTAL`,
-`AR_USER_BONUS`.`BONUS`,
-`AR_USER_BONUS`.`RECONSUME_POINTS_EXPIRED` 
-FROM
-	`AR_USER_BONUS`
-	INNER JOIN `AR_USER` ON `AR_USER`.`ID` = `AR_USER_BONUS`.`USER_ID`
-	LEFT JOIN `AR_USER_WALLET` ON `AR_USER_WALLET`.`USER_ID` = `AR_USER_BONUS`.`USER_ID` 
-WHERE
-	`AR_USER`.`USER_NAME` = `UNUMBER`;
-
-	-- 删除用户奖金
-	DELETE  `UB`  FROM  `AR_USER_BONUS` `UB` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`UB`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	
-	-- 清除用户的cash余额
-	UPDATE `AR_USER_WALLET` INNER JOIN `AR_USER` ON `AR_USER`.`ID`=`AR_USER_WALLET`.`USER_ID`      SET  `AR_USER_WALLET`.`CASH`=0 WHERE `AR_USER`.`USER_NAME` = `UNUMBER`; 
-	
-	
-	-- 删除用户累计业绩
-	DELETE  `UP`  FROM  `AR_USER_PERF` `UP` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`UP`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	
-	-- 删除用户总奖金发送记录
-	DELETE  `CB`  FROM  `AR_CALC_BONUS` `CB` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CB`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	
-	-- 删除用户各个奖金发送记录
-	DELETE  `CBBD`  FROM  `AR_CALC_BONUS_BD` `CBBD` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBBD`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBBS`  FROM  `AR_CALC_BONUS_BS` `CBBS` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBBS`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBBT`  FROM  `AR_CALC_BONUS_BT` `CBBT` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBBT`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBCF`  FROM  `AR_CALC_BONUS_CF` `CBCF` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBCF`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBFL`  FROM  `AR_CALC_BONUS_FL` `CBFL` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBFL`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBFW`  FROM  `AR_CALC_BONUS_FW` `CBFW` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBFW`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBFX`  FROM  `AR_CALC_BONUS_FX` `CBFX` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBFX`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBGL`  FROM  `AR_CALC_BONUS_GL` `CBGL` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBGL`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBGX`  FROM  `AR_CALC_BONUS_GX` `CBGX` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBGX`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBLS`  FROM  `AR_CALC_BONUS_LS` `CBLS` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBLS`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBLX`  FROM  `AR_CALC_BONUS_LX` `CBLX` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBLX`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBQY`  FROM  `AR_CALC_BONUS_QY` `CBQY` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBQY`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBST`  FROM  `AR_CALC_BONUS_STANDARD` `CBST` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBST`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBTG`  FROM  `AR_CALC_BONUS_TG` `CBTG` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBTG`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBVIP`  FROM  `AR_CALC_BONUS_VIP` `CBVIP` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBVIP`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBXF`  FROM  `AR_CALC_BONUS_XF` `CBXF` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBXF`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBYC`  FROM  `AR_CALC_BONUS_YC` `CBYC` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBYC`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CBYJ`  FROM  `AR_CALC_BONUS_YJ` `CBYJ` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CBYJ`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `CMBU`  FROM  `AR_CALC_MONTH_BONUS_USER` `CMBU` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`CMBU`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `FB`  FROM  `AR_FLOW_BONUS` `FB` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`FB`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `FC`  FROM  `AR_FLOW_CF` `FC` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`FC`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `FDZ`  FROM  `AR_FLOW_DEDUCT_ZR` `FDZ` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`FDZ`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `FEP`  FROM  `AR_FLOW_EXCHANGE_POINTS` `FEP` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`FEP`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `FLX`  FROM  `AR_FLOW_LX` `FLX` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`FLX`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `FRP`  FROM  `AR_FLOW_RECONSUME_POINTS` `FRP` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`FRP`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `FW`  FROM  `AR_FLOW_WALLET` `FW` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`FW`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `HB`  FROM  `AR_HISTORY_BONUS` `HB` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`HB`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `UPEP`  FROM  `AR_USER_PERIOD_EXCHANGE_POINTS` `UPEP` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`UPEP`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `UPP`  FROM  `AR_USER_PERIOD_POINTS` `UPP` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`UPP`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `AW`  FROM  `AR_WITHDRAW` `AW` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`AW`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `AT`  FROM  `AR_TRANSFER` `AT` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`AT`.`OUT_UID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `ABA`  FROM  `AR_BALANCE_AUDIT` `ABA` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`ABA`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `R`  FROM  `AR_RECHARGE` `R` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`R`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	DELETE  `ASM`  FROM  `AR_SCORE_MONTH` `ASM` INNER JOIN `AR_USER` `U` ON `U`.`ID`=`ASM`.`USER_ID` 
-	WHERE `U`.`USER_NAME` = `UNUMBER`;
-	
-	IF t_error = 1 THEN    
-      ROLLBACK;    
-  ELSE
-	    COMMIT;
-	END IF;
-	select t_error;  -- 返回标识位的结果集
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `CONFOUNDING_DATA` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `CONFOUNDING_DATA`()
-BEGIN
-	#Routine body goes here...
-	UPDATE AR_BALANCE_AUDIT SET CREATE_REMARK = '';
-	
-	UPDATE AR_CALC_BONUS SET LAST_REAL_NAME = CONCAT(LAST_USER_NAME,'REAL_NAME'),LAST_REC_REAL_NAME = CONCAT(LAST_REC_USER_NAME,'REAL_NAME'),LAST_CON_REAL_NAME = CONCAT(LAST_CON_USER_NAME,'REAL_NAME');
-
-	UPDATE AR_FLOW_BONUS SET REMARK ='';
-	
-	UPDATE AR_FLOW_WALLET SET REMARK ='';
-	
-	UPDATE AR_ORDER SET CONSIGNEE = CONCAT(USER_NAME,'CONSIGNEE_NAME'),MOBILE = '18888888888',ADDRESS = 'Virtual Address';
-	
-	UPDATE AR_ORDER_DEC SET MOBILE = '18888888888',CONSIGNEE = CONCAT(USER_NAME,'CONSIGNEE_NAME'),ADDRESS = 'Virtual Address';
-	
-	UPDATE AR_ORDER_SHOP SET MOBILE = '18888888888',CONSIGNEE = CONCAT(USER_NAME,'CONSIGNEE_NAME'),ADDRESS = 'Virtual Address';
-
-	UPDATE AR_RECEIVE_ADDRESS SET CONSIGNEE = CONCAT(USER_NAME,'CONSIGNEE_NAME'),MOBILE = '18888888888',ADDRESS = 'Virtual Address';
-
-	UPDATE AR_RECHARGE SET REAL_NAME = USER_ID;
-
-	UPDATE AR_TRANSFER SET LAST_OUT_REAL_NAME = CONCAT(LAST_OUT_USER_NAME,'REAL_NAME'),LAST_IN_REAL_NAME = CONCAT(LAST_IN_USER_NAME,'REAL_NAME'),REMARK = '';
-
-	UPDATE AR_USER SET REAL_NAME = CONCAT(USER_NAME,'REAL_NAME'),MOBILE = '18888888888',ADDRESS = 'Virtual Address';
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `QTRCALC` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `QTRCALC`(IN `PCPID` INT)
-LABEL: BEGIN
--- DECLARE QTRSTARTPID, QTRSTARTMONTH, THISYEAR, THISMONTH, MISMONTH INT;
-
-DECLARE TBONUS,BONUSPERU DECIMAL; -- 奖金总额,每份奖金
-DECLARE QTRSTARTMONTH, THISYEAR, THISMONTH, MISMONTH INT; -- 这个月
-
--- DECLARE OCROWN1NUM,OCROWN2NUM,OCROWN3NUM,OCROWN4NUM,OCROWN5NUM,OCROWN6NUM,OCROWN7NUM INT; -- 各星级的人数,原始不加权
--- DECLARE  CROWN1U, CROWN2U, CROWN3U, CROWN4U, CROWN5U, CROWN6U, CROWN7U INT; -- 各星级的人数(加权)
-
-DECLARE TOTALU INT; -- 加权的总份数
-
-DECLARE MAXID, USERTBID INT;
-DECLARE Q, R INT;
-
-START TRANSACTION;
--- 日志;
-DELETE FROM AR_QTR_CALC_RECORD ;
-CALL QTRCALCRECORD(-1,'开始',PCPID,NOW());
-COMMIT;
-
-CALL QTRCLEAN(PCPID);
-CALL QTRCALCRECORD(1,'清除数据',PCPID,NOW());
-COMMIT;
-
-SELECT
- CALC_YEAR, CALC_MONTH, IS_MONTH INTO THISYEAR, THISMONTH, MISMONTH FROM AR_PERIOD WHERE PERIOD_NUM = PCPID;
-
-CALL QTRCALCRECORD(2,'初始化',PCPID,NOW());
-COMMIT;
-
--- 查看是否季度结
-
-IF(THISMONTH!=3 AND THISMONTH!=6 AND THISMONTH!=9 AND THISMONTH!=12) OR MISMONTH!=1 THEN
-  CALL QTRCALCRECORD(12,'非季结,结束',PCPID,NOW());
-	COMMIT;
-  LEAVE LABEL;
-END IF;
-
-CALL QTRCALCRECORD(3,'计算总奖金',PCPID,NOW());
-COMMIT;
-
--- 按照条件,查询当前季度所有月的总PV,计算总奖金
-SET QTRSTARTMONTH = THISMONTH - 2;
-
-SELECT 
-   SUM(PV_PCS) * 0.02 
-INTO TBONUS
-  FROM AR_PERF_MONTH 
-WHERE CALC_MONTH >= CONCAT(THISYEAR, lpad(QTRSTARTMONTH,2,0)) AND CALC_MONTH <= CONCAT(THISYEAR, lpad(THISMONTH,2,0));
-
-CALL QTRCALCRECORD(4,'计算总人数及加权',PCPID,NOW());
-COMMIT;
-
-
--- 查找,所有星级用户
-INSERT INTO AR_QTR_CALC_WEIGHT
-	SELECT 
-		NULL AS ID,
-		QY.USER_ID,
-		MAX(CL.SORT) AS MAX_SORT,
-		(MAX(CL.SORT) - 1)/2 + 1 AS WEIGHT,
-		PERIOD_NUM,
-		CALC_MONTH,
-		CALC_YEAR
-	FROM
-		AR_CALC_BONUS_QY AS QY
-	 INNER JOIN 
-		AR_CROWN_LEVEL AS CL
-	 ON QY.LAST_CROWN_LV = CL.ID
-	 INNER JOIN 
-		AR_USER AS U
-	 ON QY.USER_ID = U.ID
-	 
-	WHERE
-		QY.LAST_CROWN_LV != (SELECT ID FROM AR_CROWN_LEVEL WHERE SORT = 0)
-		AND U.DEC_LV = '67ABCE0ECE705575E055736AECE8644D'
-		AND QY.CALC_MONTH >= CONCAT(THISYEAR, lpad(QTRSTARTMONTH,2,0)) 
-		AND QY.CALC_MONTH <= CONCAT(THISYEAR, lpad(THISMONTH,2,0))
-
-	GROUP BY USER_ID, CALC_MONTH;
-
-COMMIT;
-
-INSERT INTO AR_QTR_CALC_SCORE
-	SELECT
-		NULL AS ID,
-		USER_ID, 
-		COUNT(*) AS CNT,
-		SUM(WEIGHT) AS SCORE,
-		CALC_MONTH,
-		CALC_YEAR
-	FROM 
-		AR_QTR_CALC_WEIGHT
-	GROUP BY USER_ID;
-
-COMMIT;
-	
-SELECT SUM(SCORE) INTO TOTALU FROM AR_QTR_CALC_SCORE;
-
-SET BONUSPERU = TBONUS / TOTALU;
-
-
-CALL QTRCALCRECORD(5,'计算每一份奖金',PCPID,NOW());
-COMMIT;
-
-INSERT INTO AR_QTR_CALC_USER
-	SELECT 
-		NULL AS ID,
-		SC.USER_ID,
-		BONUSPERU * SC.SCORE AS AMOUNT,
-		CALC_YEAR,
-		CALC_MONTH,
-		PCPID AS PERIOD_NUM
-	FROM
-		AR_QTR_CALC_SCORE AS SC;
-
-CALL QTRCALCRECORD(6,'写入user表',PCPID,NOW());
-
-COMMIT;
-
-INSERT INTO AR_CALC_BONUS_QUARTER
-	SELECT
-		NULL AS ID,
-		AU.USER_ID,
-		AU.AMOUNT AS ORI_BONUS,
-		0 AS MANAGE_TAX,
-		AU.AMOUNT,
-		0 AS RECONSUME_POINTS,
-		U.DEC_LV,
-		AU.CALC_MONTH, 
-		AU.PERIOD_NUM,
-		NOW() AS CREATE_AT
-	FROM
-		AR_QTR_CALC_USER AS AU
-	 LEFT JOIN
-	  AR_USER AS U
-	 ON AU.USER_ID = U.ID;
-
-CALL QTRCALCRECORD(20,'写入季度奖金表',PCPID,NOW());
-COMMIT;	
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `QTRCALCRECORD` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `QTRCALCRECORD`(IN `PID` INT, IN `PEVENT` VARCHAR ( 255 ), IN `PCPID` INT, IN `PNOW` DATETIME)
-BEGIN
-	INSERT INTO AR_QTR_CALC_RECORD ( ID, EVENT, CREATION_TIME, CALC_PERIOD_ID )
-	VALUES
-		( PID, PEVENT, NOW(), PCPID );
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `QTRCLEAN` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `QTRCLEAN`(IN `PCPID` INT)
-BEGIN-- 删除当期奖金
-	DELETE 
-	FROM
-		AR_CALC_BONUS_QUARTER
-	WHERE
-		PERIOD_NUM >= PCPID;
-  TRUNCATE
-		AR_QTR_CALC_USER;
-	TRUNCATE
-		AR_QTR_CALC_WEIGHT;
-	TRUNCATE
-		AR_QTR_CALC_SCORE;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
-/*!50003 SET sql_mode              = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `UPPERCASE` */;
-/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client  = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`black_tea_0309`@`%` PROCEDURE `UPPERCASE`(IN DBNAME VARCHAR(200))
-BEGIN 
-  
-DECLARE DONE INT DEFAULT 0;  
-  
-DECLARE OLDNAME VARCHAR(200);  
-  
-DECLARE CUR CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DBNAME;  
-  
-DECLARE CONTINUE HANDLER FOR NOT FOUND SET DONE = 1;  
-  
-OPEN CUR;  
-  
-REPEAT  
-  
-FETCH CUR INTO OLDNAME;  
-  
-SET @NEWNAME = UPPER(OLDNAME);  
-SET @ISNOTSAME = @NEWNAME <> BINARY OLDNAME;   
-IF NOT DONE && @ISNOTSAME THEN   
-SET @SQL = CONCAT('RENAME TABLE `',OLDNAME,'` TO `', LOWER(@NEWNAME), '_TMP` ');   
-PREPARE TMPSTMT FROM @SQL;   
-EXECUTE TMPSTMT;  
-
-SET @SQL = CONCAT('RENAME TABLE `',LOWER(@NEWNAME),'_TMP` TO `',@NEWNAME, '`');   
-PREPARE TMPSTMT FROM @SQL;   
-EXECUTE TMPSTMT; 
-  
-DEALLOCATE PREPARE TMPSTMT;  
-  
-END IF;   
-UNTIL DONE END REPEAT;   
-CLOSE CUR;   
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode              = @saved_sql_mode */ ;
-/*!50003 SET character_set_client  = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection  = @saved_col_connection */ ;
-/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
-
-/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
-/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
-/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
-/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
-/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-
--- Dump completed on 2022-09-30  6:50:45

+ 429 - 0
sql/upgrade/1962.sql

@@ -0,0 +1,429 @@
+CREATE TABLE `AR_BA_APPROACH_ORDER_GOODS` (
+  `ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `ORDER_SN` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `GOODS_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `GOODS_TITLE` varchar(255) COLLATE utf8mb4_bin NOT NULL,
+  `PRICE` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `REAL_PRICE` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `REAL_PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `STANDARD_PRICE` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '标准价格',
+  `REAL_STANDARD_PRICE` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '支付标准价格',
+  `EXCHANGE_RATE` float(10,4) NOT NULL DEFAULT 0.0000 COMMENT '汇率',
+  `TAX_RATE` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '税率',
+  `SKU_CODE` varchar(16) COLLATE utf8mb4_bin NOT NULL,
+  `BUY_NUMS` int(10) NOT NULL DEFAULT 0,
+  `P_CALC_MONTH` date NOT NULL,
+  `POINT` smallint(5) unsigned NOT NULL DEFAULT 0,
+  `CATEGORY_TYPE` tinyint(1) unsigned NOT NULL DEFAULT 1 COMMENT '商品分类:1普通商品',
+  `PAY_TYPE` varchar(30) COLLATE utf8mb4_bin NOT NULL DEFAULT 'cash' COMMENT '支付方式:7-pay_stack',
+  `EMAIL` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '邮箱',
+  PRIMARY KEY (`ID`) USING BTREE,
+  KEY `GOODS_ID` (`GOODS_ID`) USING BTREE,
+  KEY `ORDER_SN` (`ORDER_SN`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='BA会员订单中包含的商品';
+
+
+CREATE TABLE `AR_BA_APPROACH_ORDER` (
+  `ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `SN` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+  `DEC_SN` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `USER_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `USER_NAME` varchar(16) COLLATE utf8mb4_bin NOT NULL,
+  `ORDER_TYPE` varchar(12) COLLATE utf8mb4_bin NOT NULL,
+  `ORDER_AMOUNT` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `PAY_AMOUNT` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `PAY_PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `ORDER_AMOUNT_STANDARD` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '订单价格-标准价格',
+  `PAY_AMOUNT_STANDARD` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '标准价格',
+  `EXCHANGE_RATE` float(10,4) NOT NULL DEFAULT 0.0000 COMMENT '汇率',
+  `PAY_AT` int(10) NOT NULL DEFAULT 0,
+  `FREIGHT` float(10,2) NOT NULL DEFAULT 0.00,
+  `PAY_FREIGHT` float(10,2) NOT NULL DEFAULT 0.00,
+  `DELIVERY_STATUS` tinyint(2) NOT NULL DEFAULT 0,
+  `DELIVERY_PERIOD` int(10) NOT NULL DEFAULT 0,
+  `DELIVERY_AT` int(10) NOT NULL DEFAULT 0,
+  `EXPRESS_COMPANY` varchar(128) COLLATE utf8mb4_bin DEFAULT '',
+  `ORDER_TRACK_NO` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `EXPRESS_TYPE` tinyint(1) NOT NULL DEFAULT 0,
+  `FRONT_REMARK` varchar(1000) COLLATE utf8mb4_bin DEFAULT '',
+  `REMARK` text COLLATE utf8mb4_bin DEFAULT NULL,
+  `NOTE` text COLLATE utf8mb4_bin DEFAULT NULL COMMENT '备注内容',
+  `PERIOD_NUM` int(10) NOT NULL DEFAULT 0,
+  `STATUS` int(3) NOT NULL DEFAULT 0,
+  `CONSIGNEE` varchar(120) COLLATE utf8mb4_bin DEFAULT '',
+  `MOBILE` varchar(11) COLLATE utf8mb4_bin DEFAULT '',
+  `TEL` varchar(16) COLLATE utf8mb4_bin DEFAULT '',
+  `PROVINCE` int(6) NOT NULL DEFAULT 0,
+  `CITY` int(6) DEFAULT 0,
+  `COUNTY` int(9) DEFAULT 0,
+  `LGA_NAME` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL,
+  `CITY_NAME` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL,
+  `ADDRESS` varchar(255) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+  `P_CALC_MONTH` date NOT NULL,
+  `CREATED_AT` int(10) NOT NULL DEFAULT 0,
+  `CREATE_USER` varchar(16) COLLATE utf8mb4_bin NOT NULL,
+  `UPDATED_AT` int(10) NOT NULL DEFAULT 0,
+  `UPDATER` varchar(16) COLLATE utf8mb4_bin DEFAULT '',
+  `IS_DELETE` int(10) NOT NULL DEFAULT 0,
+  `DELETED_AT` int(10) NOT NULL DEFAULT 0,
+  `PAY_TYPE` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT 'cash',
+  `WAREHOUSE` varchar(16) COLLATE utf8mb4_bin NOT NULL DEFAULT '01',
+  `EMAIL` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '邮箱',
+  `REMAIN_PV` decimal(16,2) NOT NULL DEFAULT 0.00 COMMENT '当期未计入的剩余PV',
+  `IS_AUTO` int(11) NOT NULL DEFAULT 0 COMMENT '假订单标志',
+  PRIMARY KEY (`ID`) USING BTREE,
+  KEY `SN` (`SN`) USING BTREE,
+  KEY `USER_ID` (`USER_ID`) USING BTREE,
+  KEY `USER_NAME` (`USER_NAME`) USING BTREE,
+  KEY `PERIOD_NUM` (`PERIOD_NUM`) USING BTREE,
+  KEY `IS_DELETE` (`IS_DELETE`) USING BTREE,
+  KEY `ORDER_TYPE` (`ORDER_TYPE`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='BA会员商品中间订单';
+
+CREATE TABLE `AR_BA_ORDER` (
+  `ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `SN` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+  `DEC_SN` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `USER_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `USER_NAME` varchar(16) COLLATE utf8mb4_bin NOT NULL,
+  `ORDER_TYPE` varchar(12) COLLATE utf8mb4_bin NOT NULL,
+  `ORDER_AMOUNT` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `PAY_AMOUNT` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `PAY_PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `ORDER_AMOUNT_STANDARD` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '订单价格-标准价格',
+  `PAY_AMOUNT_STANDARD` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '支付金额-标准价格',
+  `EXCHANGE_RATE` float(10,4) NOT NULL DEFAULT 0.0000 COMMENT '汇率',
+  `PAY_AT` int(10) NOT NULL DEFAULT 0,
+  `FREIGHT` float(10,2) NOT NULL DEFAULT 0.00,
+  `PAY_FREIGHT` float(10,2) NOT NULL DEFAULT 0.00,
+  `DELIVERY_STATUS` tinyint(2) NOT NULL DEFAULT 0,
+  `DELIVERY_PERIOD` int(10) NOT NULL DEFAULT 0,
+  `DELIVERY_AT` int(10) NOT NULL DEFAULT 0,
+  `EXPRESS_COMPANY` varchar(128) COLLATE utf8mb4_bin DEFAULT '',
+  `ORDER_TRACK_NO` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `EXPRESS_TYPE` tinyint(1) NOT NULL DEFAULT 0,
+  `FRONT_REMARK` varchar(1000) COLLATE utf8mb4_bin DEFAULT '',
+  `REMARK` text COLLATE utf8mb4_bin DEFAULT NULL,
+  `NOTE` text COLLATE utf8mb4_bin DEFAULT NULL COMMENT '备注内容',
+  `PERIOD_NUM` int(10) NOT NULL DEFAULT 0,
+  `STATUS` int(3) NOT NULL DEFAULT 0,
+  `CONSIGNEE` varchar(120) COLLATE utf8mb4_bin DEFAULT '',
+  `MOBILE` varchar(11) COLLATE utf8mb4_bin DEFAULT '',
+  `TEL` varchar(16) COLLATE utf8mb4_bin DEFAULT '',
+  `PROVINCE` int(6) NOT NULL DEFAULT 0,
+  `CITY` int(6) DEFAULT NULL,
+  `COUNTY` int(6) DEFAULT NULL,
+  `CITY_NAME` varchar(50) COLLATE utf8mb4_bin DEFAULT '' COMMENT '城市名(NG)',
+  `LGA_NAME` varchar(50) COLLATE utf8mb4_bin DEFAULT '' COMMENT 'Local Gov Area(NG)',
+  `ADDRESS` varchar(255) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+  `P_CALC_MONTH` date NOT NULL,
+  `CREATED_AT` int(10) NOT NULL DEFAULT 0,
+  `CREATE_USER` varchar(16) COLLATE utf8mb4_bin NOT NULL,
+  `UPDATED_AT` int(10) NOT NULL DEFAULT 0,
+  `UPDATER` varchar(16) COLLATE utf8mb4_bin DEFAULT '',
+  `IS_DELETE` int(10) NOT NULL DEFAULT 0,
+  `DELETED_AT` int(10) NOT NULL DEFAULT 0,
+  `PAY_TYPE` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT 'cash',
+  `WAREHOUSE` varchar(16) COLLATE utf8mb4_bin NOT NULL DEFAULT '01',
+  `EMAIL` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '邮箱',
+  `REMAIN_PV` decimal(16,2) NOT NULL DEFAULT 0.00 COMMENT '当期未计入的剩余PV',
+  `IS_AUTO` int(11) NOT NULL DEFAULT 0 COMMENT '假订单标志',
+  PRIMARY KEY (`ID`) USING BTREE,
+  KEY `SN` (`SN`) USING BTREE,
+  KEY `USER_ID` (`USER_ID`) USING BTREE,
+  KEY `USER_NAME` (`USER_NAME`) USING BTREE,
+  KEY `PERIOD_NUM` (`PERIOD_NUM`) USING BTREE,
+  KEY `IS_DELETE` (`IS_DELETE`) USING BTREE,
+  KEY `ORDER_TYPE` (`ORDER_TYPE`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='BA会员商品订单';
+
+
+CREATE TABLE `AR_BA_ORDER_GOODS` (
+  `ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `ORDER_SN` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `GOODS_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `GOODS_TITLE` varchar(255) COLLATE utf8mb4_bin NOT NULL,
+  `PRICE` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `REAL_PRICE` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `REAL_PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `STANDARD_PRICE` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '标准价格',
+  `EXCHANGE_RATE` float(10,4) NOT NULL DEFAULT 0.0000 COMMENT '汇率',
+  `TAX_RATE` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '税率',
+  `REAL_STANDARD_PRICE` float(16,2) NOT NULL DEFAULT 0.00 COMMENT '支付标准价格',
+  `SKU_CODE` varchar(16) COLLATE utf8mb4_bin NOT NULL,
+  `BUY_NUMS` int(10) NOT NULL DEFAULT 0,
+  `P_CALC_MONTH` date NOT NULL,
+  `POINT` smallint(5) unsigned NOT NULL DEFAULT 0,
+  `EMAIL` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '邮箱',
+  `CATEGORY_TYPE` tinyint(1) NOT NULL DEFAULT 1,
+  `PAY_TYPE` varchar(30) COLLATE utf8mb4_bin DEFAULT 'cash',
+  `REMAIN_PV` decimal(16,2) NOT NULL DEFAULT 0.00 COMMENT '当期未计入的剩余PV',
+  PRIMARY KEY (`ID`) USING BTREE,
+  KEY `GOODS_ID` (`GOODS_ID`) USING BTREE,
+  KEY `ORDER_SN` (`ORDER_SN`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='BA会员订单中包含的商品';
+
+CREATE TABLE `AR_BA_APPROACH_DEC_ORDER` (
+  `ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `DEC_SN` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+  `ORDER_SN` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+  `USER_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `TO_USER_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `TYPE` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `IS_ADMIN` tinyint(1) NOT NULL DEFAULT 0,
+  `DEC_AMOUNT` decimal(16,3) NOT NULL DEFAULT 0.000,
+  `DEC_PV` decimal(16,3) NOT NULL DEFAULT 0.000,
+  `PAID_WALLET` varchar(48) COLLATE utf8mb4_bin NOT NULL,
+  `IS_BATCH` tinyint(1) NOT NULL DEFAULT 0,
+  `REMARK` text COLLATE utf8mb4_bin DEFAULT NULL,
+  `REC_USER_ID` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `CON_USER_ID` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `PERIOD_NUM` int(10) NOT NULL,
+  `P_CALC_MONTH` date NOT NULL,
+  `CALC_MONTH` int(8) NOT NULL DEFAULT 0,
+  `CREATED_AT` int(10) NOT NULL,
+  `UPDATER` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `UPDATED_AT` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '0',
+  `IS_DEL` tinyint(1) NOT NULL DEFAULT 0,
+  `DELETED_AT` int(10) NOT NULL DEFAULT 0,
+  `DEC_ID` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `DETAIL_TYPE` tinyint(1) NOT NULL DEFAULT 1 COMMENT '默认为1注册 2为升级',
+  `UPGRADE_TYPE` tinyint(1) NOT NULL DEFAULT 0 COMMENT '1 补差额升级 2全额升级',
+  `ORI_LV` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '升级前的级别',
+  `UPGRADE_LV` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '升级后的级别',
+  PRIMARY KEY (`ID`) USING BTREE,
+  UNIQUE KEY `DEC_SN` (`DEC_SN`) USING BTREE,
+  KEY `USER_ID` (`USER_ID`) USING BTREE,
+  KEY `TYPE` (`TYPE`) USING BTREE,
+  KEY `PERIOD_NUM` (`PERIOD_NUM`) USING BTREE,
+  KEY `IS_DEL` (`IS_DEL`) USING BTREE,
+  KEY `ORDER_SN` (`ORDER_SN`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='报单中间表';
+
+CREATE TABLE `AR_BA_RECEIVE_ADDRESS` (
+  `ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `USER_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL,
+  `USER_NAME` varchar(16) COLLATE utf8mb4_bin NOT NULL,
+  `CONSIGNEE` varchar(120) COLLATE utf8mb4_bin NOT NULL,
+  `MOBILE` varchar(11) COLLATE utf8mb4_bin NOT NULL,
+  `PROVINCE` int(6) NOT NULL,
+  `CITY` int(6) DEFAULT NULL,
+  `COUNTY` int(6) DEFAULT NULL,
+  `CITY_NAME` varchar(50) COLLATE utf8mb4_bin DEFAULT '' COMMENT '城市名(NG)',
+  `LGA_NAME` varchar(50) COLLATE utf8mb4_bin DEFAULT '' COMMENT 'Local Gov Area(NG)',
+  `ADDRESS` varchar(255) COLLATE utf8mb4_bin NOT NULL,
+  `IS_DEFAULT` tinyint(1) NOT NULL DEFAULT 0,
+  `CREATED_AT` int(10) NOT NULL DEFAULT 0,
+  `UPDATER` varchar(10) COLLATE utf8mb4_bin DEFAULT '',
+  `UPDATED_AT` int(10) NOT NULL DEFAULT 0,
+  PRIMARY KEY (`ID`) USING BTREE,
+  KEY `USER_ID` (`USER_ID`) USING BTREE,
+  KEY `USER_NAME` (`USER_NAME`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='BA会员收货地址';
+
+INSERT INTO `AR_BA_RECEIVE_ADDRESS` (`ID`, `USER_ID`, `USER_NAME`, `CONSIGNEE`, `MOBILE`, `PROVINCE`, `CITY`, `COUNTY`, `CITY_NAME`, `LGA_NAME`, `ADDRESS`, `IS_DEFAULT`, `CREATED_AT`, `UPDATER`, `UPDATED_AT`) VALUES ('100000000000000000', '300000000000000000', 'D', 'DCONSIGNEE_NAME', '18888888888', 1, 1, 1, '', '', '狮驼岭', 0, 1589064762, '', 0);
+
+CREATE TABLE `AR_BA_USER` (
+  `ID` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '会员ID',
+  `USER_NAME` varchar(16) COLLATE utf8mb4_bin NOT NULL COMMENT '会员编号',
+  `PASSWORD_HASH` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '会员登录密码',
+  `PAY_PASSWORD` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '支付密码',
+  `NATION` tinyint(4) NOT NULL DEFAULT 0,
+  `REAL_NAME` varchar(128) COLLATE utf8mb4_bin NOT NULL COMMENT '会员姓名',
+  `ID_CARD` varchar(18) COLLATE utf8mb4_bin DEFAULT NULL,
+  `ID_TYPE` tinyint(1) NOT NULL DEFAULT 0,
+  `MOBILE` varchar(11) COLLATE utf8mb4_bin DEFAULT '' COMMENT '手机号码',
+  `ADDRESS` varchar(2000) COLLATE utf8mb4_bin DEFAULT '' COMMENT '详细地址',
+  `ID_IMAGE` varchar(255) COLLATE utf8mb4_bin DEFAULT '',
+  `OPEN_BANK` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '开户行',
+  `BANK_ADDRESS` varchar(255) COLLATE utf8mb4_bin DEFAULT '' COMMENT '开户行地址',
+  `BANK_NO` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '银行卡号',
+  `BANK_PROVINCE` int(11) DEFAULT 0 COMMENT '开户行所在省',
+  `BANK_CITY` int(11) DEFAULT 0 COMMENT '开户行所在市',
+  `BANK_COUNTY` int(11) DEFAULT 0 COMMENT '开户行所在区',
+  `SPOUSE_NAME` varchar(16) COLLATE utf8mb4_bin DEFAULT '',
+  `SPOUSE_IDCARD` varchar(18) COLLATE utf8mb4_bin DEFAULT '',
+  `CREATED_AT` int(11) NOT NULL DEFAULT 0,
+  `UPDATED_AT` int(11) NOT NULL DEFAULT 0,
+  `STATUS` tinyint(1) NOT NULL DEFAULT 1,
+  `DEC_CLOSED` tinyint(1) NOT NULL DEFAULT 0,
+  `DEC_CLOSED_AT` int(11) NOT NULL DEFAULT 0,
+  `DEC_LV` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '会员级别',
+  `EMP_LV` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '荣衔级别',
+  `CROWN_LV` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
+  `PROVINCE` int(11) NOT NULL DEFAULT 0 COMMENT '省',
+  `CITY` int(11) NOT NULL DEFAULT 0 COMMENT '市',
+  `COUNTY` int(11) NOT NULL DEFAULT 0 COMMENT '区',
+  `CITY_NAME` varchar(50) COLLATE utf8mb4_bin DEFAULT '' COMMENT '城市名(NG)',
+  `LGA_NAME` varchar(50) COLLATE utf8mb4_bin DEFAULT '' COMMENT 'Local Gov Area(NG)',
+  `TEL` varchar(16) COLLATE utf8mb4_bin DEFAULT '',
+  `LOGIN_TIMES` int(11) NOT NULL DEFAULT 0,
+  `LOGIN_IP` varchar(15) COLLATE utf8mb4_bin DEFAULT '',
+  `LOGIN_AT` int(11) NOT NULL DEFAULT 0,
+  `PULL_MESSAGE_AT` int(11) NOT NULL DEFAULT 0,
+  `SUB_COM_ID` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `AVATAR` varchar(255) COLLATE utf8mb4_bin NOT NULL,
+  `DELETED` tinyint(1) NOT NULL DEFAULT 0,
+  `DELETED_AT` int(11) NOT NULL DEFAULT 0,
+  `ALLOW_TRANSFER` tinyint(1) NOT NULL DEFAULT 1,
+  `TRANSFER_PROP` float(10,2) NOT NULL DEFAULT 0.00,
+  `PARTITION_DATE` timestamp NOT NULL DEFAULT current_timestamp() COMMENT '加入日期',
+  `IS_DEC` tinyint(1) NOT NULL DEFAULT 0,
+  `DEC_ID` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '1',
+  `BIRTHDAY` date DEFAULT '1990-09-09',
+  `DEC_ROLE_ID` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `PERIOD_AT` int(11) NOT NULL DEFAULT 0 COMMENT '加入期数',
+  `DEC_PROVINCE` int(11) NOT NULL DEFAULT 0,
+  `DEC_CITY` int(11) NOT NULL DEFAULT 0,
+  `DEC_COUNTY` int(11) NOT NULL DEFAULT 0,
+  `IS_UNION` tinyint(1) NOT NULL DEFAULT 0,
+  `STATUS_AT` int(11) NOT NULL DEFAULT 0,
+  `VERIFIED` tinyint(1) NOT NULL DEFAULT 0,
+  `VERIFIED_AT` int(11) NOT NULL DEFAULT 0,
+  `ALLOW_LOGIN` tinyint(1) NOT NULL DEFAULT 1,
+  `NOT_OPERATING` tinyint(1) NOT NULL DEFAULT 0,
+  `REG_FROM` tinyint(1) NOT NULL DEFAULT 1,
+  `ID_CARD_PREFIX` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `ALLOW_BONUS_LOGIN` tinyint(1) NOT NULL DEFAULT 1,
+  `SEX` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '性别',
+  `DEC_ACCOUNT_OLD` varchar(64) COLLATE utf8mb4_bin DEFAULT '',
+  `BANK_UPDATED_AT` int(11) NOT NULL DEFAULT 0,
+  `IS_DIRECT_SELLER` tinyint(1) NOT NULL DEFAULT 0,
+  `DEC_LV_UPDATED_AT` int(11) NOT NULL DEFAULT 0,
+  `DEC_LV_UPDATED_PERIOD` int(11) NOT NULL DEFAULT 0,
+  `DEC_ADDRESS` varchar(2000) COLLATE utf8mb4_bin DEFAULT '',
+  `DEC_PHONE` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `GUARANTOR` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `GUARANTOR_NAME` varchar(64) COLLATE utf8mb4_bin DEFAULT '',
+  `PART_FUNC_CLOSED` tinyint(1) NOT NULL DEFAULT 0,
+  `LAST_DEC_LV_UPDATED_PERIOD` int(11) NOT NULL DEFAULT 0,
+  `USER_CREATOR` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `USER_UPDATER` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `LAST_DEC_LV_UPDATED_AT` int(11) NOT NULL DEFAULT 0,
+  `DEC_CREATED_AT` int(11) NOT NULL DEFAULT 0,
+  `PART_FUNC_CLOSED_REMARK` text COLLATE utf8mb4_bin DEFAULT NULL,
+  `DEC_CREATED_PERIOD` int(11) NOT NULL DEFAULT 0,
+  `PASSWORD_CHANGED` tinyint(1) NOT NULL DEFAULT 0,
+  `SUB_COM_LEADER` tinyint(1) NOT NULL DEFAULT 0,
+  `LOGIN_FAIL_TIMES` int(11) NOT NULL DEFAULT 0,
+  `ZG_UPGRADE_PV` decimal(16,2) NOT NULL DEFAULT 0.00,
+  `APP_CLIENT_ID` varchar(128) COLLATE utf8mb4_bin DEFAULT '',
+  `READ_AGREEMENT` tinyint(1) NOT NULL DEFAULT 1,
+  `LAST_DEC_LV` varchar(32) COLLATE utf8mb4_bin DEFAULT '',
+  `BONUS_APP_CLIENT_ID` varchar(128) COLLATE utf8mb4_bin DEFAULT '',
+  `IS_FIRST_OPEN` tinyint(1) DEFAULT 1,
+  `IS_ATLAS` tinyint(3) unsigned NOT NULL DEFAULT 0,
+  `LEADER_ALIAS` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '所属领导人',
+  `MEMBER_TYPE_TITLE` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '所属荣衔会员',
+  `MANAGE_OF_STUDIO` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '所属工作室店长',
+  `IS_MODIFY_PASSWORD` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT '0:关闭,1:开启',
+  `IS_STUDIO` tinyint(3) unsigned NOT NULL DEFAULT 0 COMMENT '工作室',
+  `IS_RECHARGE` tinyint(3) unsigned NOT NULL DEFAULT 0 COMMENT '是否显示充值',
+  `EMAIL` varchar(32) COLLATE utf8mb4_bin DEFAULT '' COMMENT '邮箱',
+  `LAST_CROWN_LV` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '最新Crown级别',
+  `LAST_CROWN_LV_UPDATED_AT` int(11) NOT NULL DEFAULT 0 COMMENT '最新Crown级别更新时间',
+  `LAST_CROWN_LV_UPDATED_PERIOD` int(11) NOT NULL DEFAULT 0 COMMENT '最新Crown级别更新期数',
+  PRIMARY KEY (`ID`) USING BTREE,
+  UNIQUE KEY `USER_NAME` (`USER_NAME`) USING BTREE,
+  UNIQUE KEY `ID` (`ID`) USING BTREE,
+  KEY `DEC_ID` (`DEC_ID`) USING BTREE,
+  KEY `STATUS` (`STATUS`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='用户';
+
+CREATE TABLE `AR_BA_USER_INFO`  (
+  `ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+  `USER_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+  `USER_NAME` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+  `ZC_PV` decimal(16, 3) NOT NULL DEFAULT 0,
+  `CON_UID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+  `REC_UID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+  `CON_NUM` int(10) NOT NULL DEFAULT 0,
+  `REC_NUM` int(10) NOT NULL DEFAULT 0,
+  `NETWORK_DEEP` int(10) NOT NULL DEFAULT 0,
+  `RELATION_DEEP` int(10) NOT NULL DEFAULT 0,
+  `SYSTEM_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
+  `IS_GROUP_LEADER` tinyint(1) NOT NULL DEFAULT 0,
+  `IS_SYSTEM_LEADER` tinyint(1) NOT NULL DEFAULT 0,
+  `IS_TEAM` tinyint(1) NOT NULL DEFAULT 0,
+  `IS_BIND` tinyint(1) NOT NULL DEFAULT 0,
+  `IS_TEAM_MAIN` tinyint(1) NOT NULL DEFAULT 0,
+  `IS_BIND_MAIN` tinyint(1) NOT NULL DEFAULT 0,
+  `IS_AUTO_WITHDRAW` tinyint(1) NOT NULL DEFAULT 0,
+  `CLOSE_LOGIN` tinyint(1) NOT NULL DEFAULT 0,
+  `REG_TYPE` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '56D9181C0F5D428FA2DBD4CAB263BF2F',
+  `SHOULD_REG_TYPE` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT '56D9181C0F5D428FA2DBD4CAB263BF2F',
+  `REG_NAME` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
+  `CREDIT_CODE` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
+  `PREMISES` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
+  `LEGAL_PERSON` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
+  `REG_EXPIRES` int(10) NULL DEFAULT NULL,
+  `STORE_TYPE` tinyint(1) NOT NULL DEFAULT 0,
+  `INVOICE_BALANCE` decimal(16, 2) NOT NULL DEFAULT 0,
+  `HIGHEST_EMP_LV` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
+  `CREATED_AT` int(10) NOT NULL,
+  `UPDATED_AT` int(10) NOT NULL DEFAULT 0,
+  `CLOSE_LOGIN_AT` int(10) NOT NULL DEFAULT 0,
+  `PULLED_AT` int(10) NOT NULL DEFAULT 0,
+  `DELETED` tinyint(1) NOT NULL DEFAULT 0,
+  `DELETED_AT` int(10) NOT NULL DEFAULT 0,
+  `GROUP_LEADER_AT` int(10) NOT NULL DEFAULT 0,
+  `ALLOW_TRANSFER` tinyint(1) NOT NULL DEFAULT 1,
+  `ALLOW_RECONSUME_SMS` tinyint(1) NOT NULL DEFAULT 0,
+  `ALLOW_RECONSUME_SMS_TO` int(10) NOT NULL DEFAULT 0,
+  `HIGHEST_EMP_LV_PERIOD` int(10) NOT NULL DEFAULT 1,
+  `TRANSFER_PROP` float(10, 2) NOT NULL DEFAULT 100,
+  `LOGIN_NUMS` int(10) NOT NULL DEFAULT 0,
+  `FAIL_NUMS` int(10) NOT NULL DEFAULT 0,
+  `LAST_LOGIN_IP` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '0.0.0.0',
+  `LAST_LOGIN_AT` int(10) NOT NULL DEFAULT 0,
+  `SHOW_EMP_LV` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT '',
+  `ZC_AMOUNT` decimal(16, 3) NOT NULL DEFAULT 0,
+  PRIMARY KEY (`ID`) USING BTREE,
+  UNIQUE INDEX `USER_ID`(`USER_ID`) USING BTREE,
+  INDEX `USER_NAME_DELETED`(`USER_NAME`, `DELETED`) USING BTREE,
+  INDEX `NETWORK_DEEP`(`NETWORK_DEEP`) USING BTREE,
+  INDEX `RELATION_DEEP`(`RELATION_DEEP`) USING BTREE,
+  INDEX `REC_UID`(`REC_UID`) USING BTREE,
+  INDEX `CON_UID`(`CON_UID`) USING BTREE
+) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin COMMENT = '会员资料表' ROW_FORMAT = Dynamic;
+
+CREATE TABLE `AR_BA_DEC_ORDER`  (
+    `ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+    `DEC_SN` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+    `ORDER_SN` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '',
+    `USER_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+    `TO_USER_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+    `TYPE` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+    `IS_ADMIN` tinyint(1) NOT NULL DEFAULT 0,
+    `DEC_AMOUNT` decimal(16, 3) NOT NULL DEFAULT 0,
+    `DEC_PV` decimal(16, 3) NOT NULL DEFAULT 0,
+    `PAID_WALLET` varchar(48) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
+    `IS_BATCH` tinyint(1) NOT NULL DEFAULT 0,
+    `REMARK` text CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
+    `REC_USER_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT '',
+    `CON_USER_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT '',
+    `PERIOD_NUM` int(10) NOT NULL,
+    `P_CALC_MONTH` date NOT NULL,
+    `CALC_MONTH` int(8) NOT NULL DEFAULT 0,
+    `CREATED_AT` int(10) NOT NULL,
+    `UPDATER` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT '',
+    `UPDATED_AT` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '0',
+    `IS_DEL` tinyint(1) NOT NULL DEFAULT 0,
+    `DELETED_AT` int(10) NOT NULL DEFAULT 0,
+    `DEC_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT '',
+    `DETAIL_TYPE` tinyint(1) NOT NULL DEFAULT 1 COMMENT '默认为1注册 2为升级',
+    `UPGRADE_TYPE` tinyint(1) NOT NULL DEFAULT 0 COMMENT '1 补差额升级 2全额升级',
+    `ORI_LV` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '升级前的级别',
+    `UPGRADE_LV` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '升级后的级别',
+    PRIMARY KEY (`ID`) USING BTREE,
+    UNIQUE INDEX `DEC_SN`(`DEC_SN`) USING BTREE,
+    INDEX `USER_ID`(`USER_ID`) USING BTREE,
+    INDEX `TYPE`(`TYPE`) USING BTREE,
+    INDEX `PERIOD_NUM`(`PERIOD_NUM`) USING BTREE,
+    INDEX `IS_DEL`(`IS_DEL`) USING BTREE,
+    INDEX `ORDER_SN`(`ORDER_SN`) USING BTREE
+) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin COMMENT = '报单' ROW_FORMAT = Dynamic;

+ 26 - 26
sql/upgrade/1988.sql

@@ -35,7 +35,7 @@ BEGIN
     FROM
         AR_EMPLOY_LEVEL T
     WHERE
-            T.ID = 'E121497617216708615';
+        T.ID = 'E121497617216708615';
 
     INSERT INTO AR_BS_BONUS_103_CALC (
         LAST_DEC_LV,
@@ -93,33 +93,33 @@ BEGIN
           0,
           0,
           PCPID,
-          IFNULL(DO.ACHIEVE_MEMBER_NUM, 0),
-          IF(DO.ACHIEVE_MEMBER_NUM >= AC_USER_NO, AC_PERF_PV, MLIMITPV)
+          IFNULL(DO.ACHIEVE_MEMBER_NUM, 0) AS ACHIEVE_NUM,
+          IF(DO.ACHIEVE_MEMBER_NUM >= AC_USER_NO, AC_PERF_PV, MLIMITPV) AS ACHIEVE_PV
     FROM
         AR_USER AU
-            INNER JOIN AR_USER_RELATION_NEW AURN ON AU.ID = AURN.USER_ID
-            LEFT JOIN (
-            SELECT
-                USER_ID,
-                SUM( PV ) PV
-            FROM
-                AR_PERF_ORDER
-            WHERE
-                    PERIOD_NUM IN ( SELECT PERIOD_NUM FROM AR_PERIOD WHERE CALC_YEAR = PCALCYEAR AND CALC_MONTH = PCALCMONTH )
-            GROUP BY
-                USER_ID
-        ) AO ON AO.USER_ID = AU.ID
-            LEFT JOIN (
-            SELECT
-                R.PARENT_UID,
-                COUNT(R.USER_ID) AS ACHIEVE_MEMBER_NUM
-            FROM
-                AR_PERF_ORDER O
-                    INNER JOIN AR_USER_RELATION_NEW R ON O.USER_ID = R.USER_ID
-            WHERE
-                    O.DEC_TYPE = 'ZC' AND O.PERIOD_NUM IN ( SELECT PERIOD_NUM FROM AR_PERIOD WHERE CALC_YEAR = PCALCYEAR AND CALC_MONTH = PCALCMONTH )
-            GROUP BY R.PARENT_UID
-        ) DO ON DO.PARENT_UID = AU.ID
+    INNER JOIN AR_USER_RELATION_NEW AURN ON AU.ID = AURN.USER_ID
+    LEFT JOIN (
+        SELECT
+            USER_ID,
+            SUM( PV ) PV
+        FROM
+            AR_PERF_ORDER
+        WHERE
+                PERIOD_NUM IN ( SELECT PERIOD_NUM FROM AR_PERIOD WHERE CALC_YEAR = PCALCYEAR AND CALC_MONTH = PCALCMONTH )
+        GROUP BY
+            USER_ID
+    ) AO ON AO.USER_ID = AU.ID
+    LEFT JOIN (
+        SELECT
+            R.PARENT_UID,
+            COUNT(R.USER_ID) AS ACHIEVE_MEMBER_NUM
+        FROM
+            AR_PERF_ORDER O
+            INNER JOIN AR_USER_RELATION_NEW R ON O.USER_ID = R.USER_ID
+        WHERE
+            O.CALC_MONTH = CONCAT(PCALCYEAR, PCALCMONTH) AND O.DEC_TYPE = 'ZC'
+        GROUP BY R.PARENT_UID
+    ) DO ON DO.PARENT_UID = AU.ID
     WHERE
             AU.DELETED = 0;