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

Merge branch 'master' of http://16.162.42.175:8014/guanli/ngds into feature/EK-2806

# Conflicts:
#	backendApi/modules/v1/controllers/AdminController.php
#	backendApi/modules/v1/models/AdminCountry.php
#	frontendApi/modules/v1/controllers/UserController.php
kevin пре 3 месеци
родитељ
комит
4d5cf323bf
77 измењених фајлова са 2768 додато и 543 уклоњено
  1. 7 6
      backendApi/config/menu.php
  2. 5 8
      backendApi/config/params.php
  3. 25 19
      backendApi/config/urlManagerRules.php
  4. 66 46
      backendApi/modules/v1/controllers/AdminController.php
  5. 161 11
      backendApi/modules/v1/controllers/BonusController.php
  6. 124 0
      backendApi/modules/v1/controllers/ConfigController.php
  7. 26 2
      backendApi/modules/v1/controllers/CurrencyController.php
  8. 114 4
      backendApi/modules/v1/controllers/FinanceController.php
  9. 106 11
      backendApi/modules/v1/controllers/ShopController.php
  10. 26 4
      backendApi/modules/v1/controllers/SiteController.php
  11. 102 13
      backendApi/modules/v1/controllers/UserController.php
  12. 36 31
      backendApi/modules/v1/models/Admin.php
  13. 14 3
      backendApi/modules/v1/models/AdminCountry.php
  14. 24 2
      backendApi/modules/v1/models/AdminForm.php
  15. 9 0
      backendApi/modules/v1/models/AdminRole.php
  16. 8 3
      backendApi/modules/v1/models/lists/bonus/BalanceList.php
  17. 8 4
      backendApi/modules/v1/models/lists/bonus/FlowBonusList.php
  18. 7 2
      backendApi/modules/v1/models/lists/bonus/PerfMonthList.php
  19. 10 5
      backendApi/modules/v1/models/lists/bonus/PerfOrderList.php
  20. 8 1
      backendApi/modules/v1/models/lists/bonus/PeriodBonusList.php
  21. 7 2
      backendApi/modules/v1/models/lists/bonus/UserPerfList.php
  22. 7 2
      backendApi/modules/v1/models/lists/finance/BalanceAuditList.php
  23. 1 1
      backendApi/modules/v1/models/lists/finance/RechargeList.php
  24. 12 2
      backendApi/modules/v1/models/lists/finance/TransferList.php
  25. 17 62
      backendApi/modules/v1/models/lists/shop/GoodsList.php
  26. 11 10
      backendApi/modules/v1/models/lists/shop/OrderList.php
  27. 6 1
      backendApi/modules/v1/models/lists/shop/OrderPeriodAdjustList.php
  28. 7 2
      backendApi/modules/v1/models/lists/user/ChangeHighestEmpLevelList.php
  29. 7 3
      backendApi/modules/v1/models/lists/user/DecLevelList.php
  30. 7 2
      backendApi/modules/v1/models/lists/user/MoveList.php
  31. BIN
      backendEle/static/src/img/ngds-logo.jpg
  32. 2 10
      common/config/main.php
  33. 10 10
      common/helpers/Email.php
  34. 11 0
      common/helpers/PayStack.php
  35. 4 3
      common/helpers/user/Info.php
  36. 25 9
      common/libs/export/BaseExport.php
  37. 15 1
      common/messages/en-US/app.php
  38. 2 0
      common/messages/en-US/ctx.php
  39. 15 2
      common/messages/zh-CN/app.php
  40. 2 0
      common/messages/zh-CN/ctx.php
  41. 49 0
      common/models/AmpPeriod.php
  42. 2 0
      common/models/ApproachDecOrder.php
  43. 3 2
      common/models/ApproachOrder.php
  44. 7 2
      common/models/ApproachReconsumeOrder.php
  45. 20 0
      common/models/Countries.php
  46. 0 1
      common/models/Currency.php
  47. 4 2
      common/models/Order.php
  48. 1 1
      common/models/OrderDec.php
  49. 1 1
      common/models/OrderShop.php
  50. 4 0
      common/models/Period.php
  51. 1 1
      common/models/ReceiveAddress.php
  52. 6 3
      common/models/Region.php
  53. 4 2
      common/models/ShopGoods.php
  54. 4 11
      common/models/User.php
  55. 1 1
      common/models/UserRelation.php
  56. 759 0
      common/models/forms/ApproachAutoMaintenanceOrderForm.php
  57. 22 41
      common/models/forms/ApproachDeclarationForm.php
  58. 1 3
      common/models/forms/ApproachDeclarationLoopForm.php
  59. 7 4
      common/models/forms/ApproachDeclarationUpgradeForm.php
  60. 75 18
      common/models/forms/ApproachOrderForm.php
  61. 150 65
      common/models/forms/ApproachReconsumeOrderForm.php
  62. 5 22
      common/models/forms/DeclarationForm.php
  63. 1 0
      common/models/forms/DeclarationUpgradeForm.php
  64. 326 19
      common/models/forms/OrderForm.php
  65. 6 6
      common/models/forms/ShopGoodsForm.php
  66. 32 4
      common/models/forms/WithdrawForm.php
  67. BIN
      common/runtime/uploads/ngds-logo.jpg
  68. 8 1
      console/controllers/BonusController.php
  69. 6 0
      console/controllers/ToolController.php
  70. 1 0
      frontendApi/config/menu.php
  71. 1 1
      frontendApi/config/params.php
  72. 3 0
      frontendApi/config/urlManagerRules.php
  73. 161 19
      frontendApi/modules/v1/controllers/ShopController.php
  74. 3 4
      frontendApi/modules/v1/controllers/SiteController.php
  75. 40 12
      frontendApi/modules/v1/controllers/UserController.php
  76. BIN
      frontendEle/static/src/img/ngds-logo.jpg
  77. BIN
      ngds-logo.jpg

+ 7 - 6
backendApi/config/menu.php

@@ -29,6 +29,7 @@ return [
             ['name'=>'编辑商品', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'goods-edit', 'routePath'=>'shop/goods-edit', 'show'=>0,],
             ['name'=>'商品上下架', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'goods-status', 'routePath'=>'shop/goods-status', 'show'=>0],
             ['name'=>'删除商品', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'goods-delete', 'routePath'=>'shop/goods-delete', 'show'=>0,],
+            ['name'=>'商品国家', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'goods-add', 'routePath'=>'site/countries', 'show'=>0],
             ['name'=>'商品列表导出', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'goods-list-export', 'routePath'=>'shop/goods-list-export', 'show'=>0,],
             ['name'=>'Order list', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-list', 'routePath'=>'shop/order-list', 'show'=>1, 'wiki' => 'orderList'],//订单列表
             ['name'=>'订单列表导出', 'class'=>'', 'icon'=>'', 'controller'=>'shop', 'action'=>'order-list-export', 'routePath'=>'shop/order-list-export', 'show'=>0,],
@@ -66,8 +67,8 @@ return [
             ['name'=>'Member level adjustment list', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'dec-level-list', 'routePath'=>'user/dec-level-list', 'show'=>1, 'wiki' => 'memberLevelAdjustmentList'],//会员级别调整列表
             ['name'=>'修改会员级别', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'change-user-dec-level', 'routePath'=>'user/change-user-dec-level', 'show'=>0,],
             ['name'=>'Modify Stockist level', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'change-user-dec-role', 'routePath'=>'user/change-user-dec-role', 'show'=>1, 'wiki' => 'modifyStockistLevel'],//修改报单中心级别
-            ['name'=>'会员最高聘级调整', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'change-user-dec-level', 'routePath'=>'user/change-highest-emp-level-list', 'show'=>1, 'wiki' => 'memberHighestEmpLevelAdjustment'],
-            ['name'=>'修改会员最高聘级', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'change-user-dec-level', 'routePath'=>'user/change-highest-emp-level', 'show'=>0,],
+            ['name'=>'会员最高聘级调整', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'change-highest-emp-level-list', 'routePath'=>'user/change-highest-emp-level-list', 'show'=>1, 'wiki' => 'memberHighestEmpLevelAdjustment'],
+            ['name'=>'修改会员最高聘级', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'change-highest-emp-level', 'routePath'=>'user/change-highest-emp-level', 'show'=>0,],
         ]
     ],
     'atlas'=>[
@@ -274,10 +275,10 @@ return [
             ['name'=>'编辑会员级别', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'dec-level-edit', 'routePath'=>'config/dec-level-edit', 'show'=>0,],
             ['name'=>'报单中心级别配置', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'dec-role', 'routePath'=>'config/dec-role', 'show'=>1, 'wiki' => 'decRoleConfig'],
             ['name'=>'编辑报单中心级别', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'dec-role-edit', 'routePath'=>'config/dec-role-edit', 'show'=>0,],
-            ['name'=>'汇率列表', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'currencies-conversions', 'routePath'=>'currency/currencies-conversions', 'show'=>1,  'wiki' => 'exchangeRateConfig'],
-            ['name'=>'汇率配置', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'set-currencies-conversions', 'routePath'=>'currency/set-currencies-conversions', 'show'=>0],
-            ['name'=>'运费模板列表', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'transportation', 'routePath'=>'transportation/transportation', 'show'=>1,  'wiki' => 'transportationConfig'],
-            ['name'=>'运费模板设置', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'set-transportation', 'routePath'=>'transportation/set-transportation', 'show'=>0],
+            ['name'=>'汇率列表', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'currencies', 'routePath'=>'config/currencies', 'config'=>'config/currencies', 'show'=>1,  'wiki' => 'currenciesConfig'],
+            ['name'=>'汇率配置', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'set-currencies-conversions', 'config'=>'config/set-currencies-conversions', 'show'=>0],
+            ['name'=>'运费模板', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'transportation', 'routePath'=>'config/transportation', 'show'=>1,  'wiki' => 'transportationConfig'],
+            ['name'=>'运费设置', 'class'=>'', 'icon'=>'', 'controller'=>'config', 'action'=>'set-transportation', 'routePath'=>'config/set-transportation', 'show'=>0],
         ],
     ],
 ];

+ 5 - 8
backendApi/config/params.php

@@ -13,7 +13,6 @@ return [
         'v1/site/send-notice',
         'v1/site/send-notify',
         'v1/site/languages',
-        'v1/site/countries',
         'v1/ad/sort',
         'v1/article/detail',
         'v1/admin/change-language',
@@ -24,8 +23,8 @@ return [
         'v1/bonus/calc-period',
         'v1/calc/record-list',
         'v1/calc/auto-calc',
-        'v1/shop/order-detail',
         'v1/shop/order-period-adjust-batch',
+//        'v1/site/countries'
     ],
     'noCheckPermissionActions' => [
         'oauth/login',
@@ -39,7 +38,6 @@ return [
         'site/page-data',
         'site/captcha',
         'site/languages',
-        'site/countries',
         'user/full-info',
         'user/filter-user',
         'user/generate-user-name',
@@ -85,10 +83,10 @@ return [
         'demo/ipayments',
         'article/detail',
         'admin/change-language',
-        'currency/currencies-conversions',
-        'currency/set-currencies-conversions',
-        'transportation/transportation',
-        'transportation/set-transportation',
+//        'currency/currencies-conversions',
+//        'currency/set-currencies-conversions',
+//        'transportation/transportation',
+//        'transportation/set-transportation',
         'bonus/auto-calc',
         'bonus/calc-period',
         'bonus/close-period',
@@ -96,7 +94,6 @@ return [
         'bonus/calc-period',
         'calc/record-list',
         'calc/auto-calc',
-        'shop/order-detail',
         'shop/order-period-adjust-batch',
     ],
 ];

+ 25 - 19
backendApi/config/urlManagerRules.php

@@ -322,6 +322,10 @@ return [
             'POST,GET sms' => 'sms',
             'POST,GET transfer' => 'transfer',
             'POST,GET score' => 'score',
+            'GET currencies' => 'currencies',
+            'POST set-currencies-conversions' => 'set-currencies-conversions',
+            'GET transportation' => 'transportation',
+            'POST set-transportation' => 'set-transportation',
         ],
     ],
     [
@@ -593,23 +597,25 @@ return [
             'GET sync-calc-record/<periodNum>' => 'sync-calc-record',
         ],
     ],
-    [
-        'class' => 'yii\rest\UrlRule',
-        'pluralize' => false,
-        'controller' => 'v1/currency',
-        'extraPatterns' => [
-            'GET currencies' => 'currencies',
-            'GET currencies-conversions' => 'currencies-conversions',
-            'POST set-currencies-conversions' => 'set-currencies-conversions',
-        ],
-    ],
-    [
-        'class' => 'yii\rest\UrlRule',
-        'pluralize' => false,
-        'controller' => 'v1/transportation',
-        'extraPatterns' => [
-            'GET transportation' => 'transportation',
-            'POST set-transportation' => 'set-transportation',
-        ],
-    ],
+//    [
+//        'class' => 'yii\rest\UrlRule',
+//        'pluralize' => false,
+//        'controller' => 'v1/currency',
+//        'extraPatterns' => [
+//            'GET currencies' => 'currencies',
+//            'GET currencies-conversions' => 'currencies-conversions',
+//            'POST set-currencies-conversions' => 'set-currencies-conversions',
+//            'GET transportation' => 'transportation',
+//            'POST set-transportation' => 'set-transportation',
+//        ],
+//    ],
+//    [
+//        'class' => 'yii\rest\UrlRule',
+//        'pluralize' => false,
+//        'controller' => 'v1/transportation',
+//        'extraPatterns' => [
+//            'GET transportation' => 'transportation',
+//            'POST set-transportation' => 'set-transportation',
+//        ],
+//    ],
 ];

+ 66 - 46
backendApi/modules/v1/controllers/AdminController.php

@@ -25,6 +25,7 @@ use yii\helpers\Json;
 class AdminController extends BaseController
 {
     public $modelClass = User::class;
+
     public function behaviors() {
         $behaviors = parent::behaviors();
         //$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
@@ -40,22 +41,27 @@ class AdminController extends BaseController
         $filter = $this->filterCondition([
             'ADMIN_NAME' => 'A.ADMIN_NAME',
             'REAL_NAME' => 'A.REAL_NAME',
-            'REMARK' => 'A.REMARK',
             'ROLE_NAME' => 'AR.ROLE_NAME',
             'IS_ENABLE' => 'A.IS_ENABLE',
-            'LOGIN_NUMS' => 'A.LOGIN_NUMS',
-            'LAST_LOGIN_IP' => 'A.LAST_LOGIN_IP',
-            'LAST_LOGIN_AT' => 'A.LAST_LOGIN_AT',
-            'BIND_IP' => 'A.BIND_IP',
-            'CREATED_AT' => 'A.CREATED_AT',
-            'UPDATED_AT' => 'A.UPDATED_AT',
-            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
-            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
         ]);
 
         $condition = $filter['condition'];
-        $condition .= ' AND A.IS_DEL=0';
         $params = $filter['params'];
+        $condition .= ' AND A.IS_DEL=0';
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $adminIds = AdminCountry::find()->select('ADMIN_ID')->where(['in', 'COUNTRY_ID', $adminCountry])->column();
+            $quotedAdminId = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminIds);
+
+            $condition .= ' AND A.ID IN (' . implode(',', $quotedAdminId) . ')';
+        }
+
         $data = Admin::lists($condition, $params, [
             'select' => 'A.*,AR.ROLE_NAME,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME UPDATE_ADMIN_NAME',
             'from' => Admin::tableName().' AS A',
@@ -67,24 +73,17 @@ class AdminController extends BaseController
             'orderBy' => 'A.CREATED_AT ASC',
         ]);
 
-        // 遍历查询管理员关联国家,只返回国家CODE AS COUNTRY_CODE
-//        foreach ($data['list'] as &$value) {
-//            // 跳过超管
-//            if ($value['ROLE_ID'] == \Yii::$app->params['superAdminRoleId']) {
-//                $value['COUNTRY_CODE'] = '';
-//                continue;
-//            }
-//
-//            $countryCode = AdminCountry::find()
-//                ->from(AdminCountry::tableName() . ' AS AC')
-//                ->join('INNER JOIN', Countries::tableName() . ' AS COU', 'AC.COUNTRY_ID=COU.ID')
-//                ->select('COU.CODE AS COUNTRY_CODE')
-//                ->where(['AC.ADMIN_ID' => $value['ID']])
-//                ->asArray()
-//                ->column();
-//
-//            $value['COUNTRY_CODE'] = implode(',', $countryCode);
-//        }
+        foreach ($data['list'] as &$admin) {
+            $isSuperAdmin = AdminRole::isSuperAdmin($admin['ROLE_ID']);
+            $admin['isSuper'] = $isSuperAdmin;
+            if ($isSuperAdmin) {
+                $admin['countryId'] = [];
+                $admin['country'] = [];
+            } else {
+                $admin['countryId'] = AdminCountry::getCountry($admin['ID']);
+                $admin['country'] = Countries::find()->select('NAME')->where(['in', 'ID', $admin['countryId']])->column();
+            }
+        }
 
         return static::notice($data);
     }
@@ -102,25 +101,21 @@ class AdminController extends BaseController
                 // Log::adminHandle('添加管理员:'.$result->ADMIN_NAME);
             });
         }
-        // 获取全部管理员角色
-        $adminRoles = Cache::getAdminRole();
 
-        $admin = Admin::findOne(Yii::$app->user->id);
-        $roleId = $admin->ROLE_ID;
-        if ($roleId == \Yii::$app->params['superAdminRoleId']) {
-            $countries = Countries::find()->asArray()->all();
-        } else {
-            // 关联国家
-            $countries = Countries::find()
-                ->select('COU.ID, COU.CODE, COU.NAME')
-                ->from(['COU' => Countries::tableName()])
-                ->join('INNER JOIN', AdminCountry::tableName() . ' AS ADL', 'countries.COUNTRY_ID = ADL.ID')
-                ->where(['ADL.ADMIN_ID' => $admin->ID])
-                ->asArray()
-                ->all();
+        $countries = Cache::getCountries();
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
         }
 
-        return static::notice(['adminRoles'=>$adminRoles, 'countries'=>$countries]);
+        return static::notice([
+            'adminRoles' => Cache::getAdminRole(),
+            'countries'  => $countries
+        ]);
     }
 
     /**
@@ -137,10 +132,35 @@ class AdminController extends BaseController
                 // Log::adminHandle('编辑管理员:'.$result->ADMIN_NAME);
             });
         }
-        $oneData = Admin::findOneAsArray(['ID'=>$id]);
+
+        $oneData = Admin::findOneAsArray(['ID' => $id]);
+        $adminCountry = AdminCountry::getCountry($id);
         // 获取全部管理员角色
         $adminRoles = Cache::getAdminRole();
-        return static::notice(['oneData'=>['adminName'=>$oneData['ADMIN_NAME'],'realName'=>$oneData['REAL_NAME'],'remark'=>$oneData['REMARK'],'isEnable'=>$oneData['IS_ENABLE']?true:false,'isModifyPassword'=>$oneData['IS_MODIFY_PASSWORD']?true:false,'bindIp'=>$oneData['BIND_IP'],'roleId'=>$oneData['ROLE_ID']], 'adminRoles'=>$adminRoles]);
+
+        $countries = Cache::getCountries();
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
+        }
+
+        return static::notice([
+            'adminRoles' => $adminRoles,
+            'countries'  => $countries,
+            'oneData' => [
+                'adminName' => $oneData['ADMIN_NAME'],
+                'realName' => $oneData['REAL_NAME'],
+                'remark' => $oneData['REMARK'],
+                'isEnable' => (bool)$oneData['IS_ENABLE'],
+                'isModifyPassword' => (bool)$oneData['IS_MODIFY_PASSWORD'],
+                'bindIp' => $oneData['BIND_IP'],
+                'roleId' => $oneData['ROLE_ID'],
+                'countryId' => AdminCountry::getCountry($oneData['ID']),
+            ]]);
     }
 
     /**

+ 161 - 11
backendApi/modules/v1/controllers/BonusController.php

@@ -8,6 +8,8 @@
 
 namespace backendApi\modules\v1\controllers;
 
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
 use backendApi\modules\v1\models\exportForms\BonusExportForm;
 use backendApi\modules\v1\models\lists\bonus\BalanceList;
 use backendApi\modules\v1\models\lists\bonus\FlowBalanceList;
@@ -197,6 +199,18 @@ class BonusController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new FlowBonusList();
         $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
         return static::notice($data);
@@ -227,8 +241,23 @@ class BonusController extends BaseController {
             'REMARK' => 'REMARK',
             'TRANSFER_SN' => 'TRANSFER_SN',
         ]);
+
+        $condition = $filter['condition'];
+        $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new BonusExportForm();
-        $result = $form->run($filter, 'Bonus_Flow'); // 奖金流水
+        $result = $form->run(['condition'=>$condition, 'params'=>$params], 'Bonus_Flow'); // 奖金流水
         if (!$result) {
             return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
         }
@@ -311,6 +340,9 @@ class BonusController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+
+
         $listObj = new FlowBalanceList();
         $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
         return static::notice($data);
@@ -836,8 +868,23 @@ class BonusController extends BaseController {
         }
         $period = Period::instance();
         $yearMonth = $period->getYearMonth($periodNum);
+
+        $condition = $filter['condition'];
+        $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND CU.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new BonusExportForm();
-        $result = $form->run(array_merge($filter, ['others'=>['yearMonth'=>$yearMonth]]), 'Member Bonus'); // 往期奖金
+        $result = $form->run(array_merge(['condition'=>$condition, 'params'=>$params, 'others'=>['yearMonth'=>$yearMonth]]), 'Member Bonus'); // 往期奖金
         if (!$result) {
             return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
         }
@@ -894,6 +941,17 @@ class BonusController extends BaseController {
             $params[':PERIOD_NUM'] = $periodNum;
         }
 
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND CU.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new PeriodBonusList();
         return $listObj->getList(['condition'=>$condition, 'params'=>$params, 'others'=>['yearMonth'=>$yearMonth]]);
     }
@@ -2066,11 +2124,22 @@ class BonusController extends BaseController {
         $filter = $this->filterCondition([
             'USER_NAME' => 'UI.USER_NAME',
             'REAL_NAME' => 'UI.REAL_NAME',
-            'userIds' => 'UB.USER_ID',
             'IS_DEC' => 'UI.IS_DEC',
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND UI.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new BalanceList();
         $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
         return static::notice($data);
@@ -2086,17 +2155,25 @@ class BonusController extends BaseController {
         $filter = $this->filterCondition([
             'USER_NAME' => 'UI.USER_NAME',
             'REAL_NAME' => 'UI.REAL_NAME',
-            'userIds' => 'UB.USER_ID',
-            'BONUS' => 'BONUS',
             'IS_DEC' => 'UI.IS_DEC',
-            'PERIOD_AT' => 'UI.PERIOD_AT',
-            'MOBILE' => 'UI.MOBILE',
-            'TEL' => 'UI.TEL',
-//            'CF' => 'CF',
-//            'LX' => 'LX',
         ]);
+
+        $condition = $filter['condition'];
+        $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND UI.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new BonusExportForm();
-        $result = $form->run($filter, '会员奖金余额');
+        $result = $form->run(['condition'=>$condition, 'params'=>$params], '会员奖金余额');
         if (!$result) {
             return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
         }
@@ -2317,6 +2394,18 @@ class BonusController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new PerfOrderList();
         $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
 
@@ -2359,6 +2448,18 @@ class BonusController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new BonusExportForm();
         $result = $form->run(['condition'=>$condition, 'params'=>$params], '业绩单');
         if (!$result) {
@@ -2427,6 +2528,18 @@ class BonusController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new PerfMonthList();
         $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
 
@@ -2449,6 +2562,18 @@ class BonusController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new BonusExportForm();
         $result = $form->run(['condition'=>$condition, 'params'=>$params], '月业绩');
         if (!$result) {
@@ -2651,6 +2776,18 @@ class BonusController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new UserPerfList();
         $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
 
@@ -2669,6 +2806,18 @@ class BonusController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new BonusExportForm();
         $result = $form->run(['condition'=>$condition, 'params'=>$params], '用户业绩');
         if (!$result) {
@@ -2682,6 +2831,7 @@ class BonusController extends BaseController {
      *
      */
     public function actionAutoWithdraw() {
+        Cache::setWithdrawLock(0); // todo
         $withdrawLock = Cache::getWithdrawLock();
         if ($withdrawLock!=0){
             return static::notice(Form::formatErrorsForApi('已有进程在生成'), 400);

+ 124 - 0
backendApi/modules/v1/controllers/ConfigController.php

@@ -9,14 +9,22 @@
 namespace backendApi\modules\v1\controllers;
 
 use backendApi\modules\v1\models\Admin;
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
 use common\helpers\Cache;
 use common\helpers\Date;
 use common\helpers\Form;
+use common\helpers\LoggerTool;
+use common\models\Countries;
+use common\models\Currency;
+use common\models\CurrencyConversions;
 use common\models\DecRole;
 use common\models\forms\ConfigForm;
 use common\models\forms\ConfigPeriodForm;
+use common\models\forms\CurrenciesConversionsForm;
 use common\models\forms\DecLevelForm;
 use common\models\forms\DecRoleForm;
+use common\models\forms\FreeTemplateForm;
 use common\models\forms\RegTypeForm;
 use common\models\forms\DeclarationLevelForm;
 use common\models\forms\EmployLevelForm;
@@ -24,6 +32,7 @@ use common\models\forms\OcrApiForm;
 use common\models\forms\SmsApiForm;
 use common\models\forms\SmsTemplateForm;
 use common\models\forms\WithdrawLevelForm;
+use common\models\FreeTemplate;
 use common\models\OcrApi;
 use common\models\RegType;
 use common\models\DeclarationLevel;
@@ -35,10 +44,18 @@ use Yii;
 use common\models\Config;
 use yii\base\Exception;
 use yii\helpers\Json;
+use yii\web\HttpException;
 
 class ConfigController extends BaseController {
     public $modelClass = Config::class;
 
+    public $currencyModelClass = Currency::class;
+
+    public $currencyConversionsModelClass = CurrencyConversions::class;
+
+    public $freeTemplateModelClass = FreeTemplate::class;
+    public $countiesModelClass = Countries::class;
+
     public function behaviors() {
         return parent::behaviors();
     }
@@ -798,4 +815,111 @@ class ConfigController extends BaseController {
         file_put_contents($path, $content, LOCK_EX);
         return static::notice(Yii::t('ctx', 'successfully'));
     }
+
+    public function actionCurrencies()
+    {
+        // 国家
+        $countries = Cache::getCountries();
+        // 货币
+        $currencies = $this->currencyModelClass::getFromCache();
+        // 汇率
+        $currencyConversion = $this->currencyConversionsModelClass::getFromCache();
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
+        }
+
+        $countriesCurrencyIds = array_column($countries, 'LOCAL_CURRENCY_ID');
+        $currencyConversion = array_filter($currencyConversion, fn($item) => in_array($item['TO_CURRENCY_ID'], $countriesCurrencyIds));
+        $currencyConversion = array_values($currencyConversion);
+        $currencyConversion = array_column($currencyConversion, null, 'TO_CURRENCY_ID');
+
+        $currencies = array_filter($currencies, fn($item) => in_array($item['ID'], $countriesCurrencyIds));
+        $currencies = array_values($currencies);
+
+        foreach ($currencies as &$currency) {
+            $currency['PRODUCT_RATE'] = $currencyConversion[$currency['ID']]['PRODUCT_RATE'] ?? 0;
+            $currency['BONUSES_RATE'] = $currencyConversion[$currency['ID']]['BONUSES_RATE'] ?? 0;
+        }
+
+        return static::notice(['data' => $currencies]);
+    }
+
+    /**
+     * @throws \yii\db\Exception
+     * @throws HttpException
+     */
+    public function actionSetCurrenciesConversions()
+    {
+        if (\Yii::$app->request->isPost) {
+            $formModel = new CurrenciesConversionsForm();
+            $formModel->scenario = 'setCurrenciesConversions';
+            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->setCurrenciesConversions()) {
+                // 更新缓存
+                $this->currencyConversionsModelClass::updateToCache();
+
+                return static::notice(\Yii::t('ctx', 'successfully'));
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
+
+            }
+        }
+
+        return static::notice(\Yii::t('ctx', 'illegalRequest'));
+    }
+
+    public function actionTransportation()
+    {
+        // 国家列表
+        $countries = $this->countiesModelClass::getFromCache();
+        // 运费列表
+        $transportation = $this->freeTemplateModelClass::getFromCache();
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
+            $countriesId = array_column($countries, 'ID');
+
+            $transportation = array_filter($transportation, fn($item) => in_array($item['country_id'], $countriesId));
+            $transportation = array_values($transportation);
+        }
+
+        $transportation = array_column($transportation, NULL, 'country_id');
+
+        foreach ($countries as &$country) {
+            $country['freight'] = $transportation[$country['ID']]['freight'] ?? 0;
+            $country['free_shipping'] = $transportation[$country['ID']]['free_shipping'] ?? 0;
+            $country['currency'] = $this->currencyModelClass::getById($country['LOCAL_CURRENCY_ID']);
+        }
+
+        return static::notice(['data' => $countries]);
+    }
+
+    public function actionSetTransportation()
+    {
+        if (\Yii::$app->request->isPost) {
+            $formModel = new FreeTemplateForm();
+            $formModel->scenario = 'setTransportation';
+            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->setTransportation()) {
+                // 更新缓存
+                $this->modelClass::updateToCache();
+
+                return static::notice(\Yii::t('ctx', 'successfully'));
+            } else {
+                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
+
+            }
+        }
+
+        return static::notice(\Yii::t('ctx', 'illegalRequest'));
+    }
 }

+ 26 - 2
backendApi/modules/v1/controllers/CurrencyController.php

@@ -2,10 +2,14 @@
 
 namespace backendApi\modules\v1\controllers;
 
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
+use common\helpers\Cache;
 use common\helpers\Form;
 use common\models\Currency;
 use common\models\CurrencyConversions;
 use common\models\forms\CurrenciesConversionsForm;
+use Yii;
 use yii\db\Exception;
 use yii\web\HttpException;
 
@@ -23,10 +27,30 @@ class CurrencyController extends BaseController
 
     public function actionCurrenciesConversions()
     {
-        // 货币列表
+        // 国家
+        $countries = Cache::getCountries();
+        // 货币
         $currencies = $this->modelClass::getFromCache();
-        // 货币汇率配置
+        // 汇率配置
         $currencyConversion = $this->currencyConversionsModelClass::getFromCache();
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
+            $countriesId = array_column($countries, 'ID');
+
+            $currencies = array_filter($currencies, fn($currency) => in_array($currency['ID'], $countriesId));
+            $currencies = array_values($currencies);
+            $currenciesId = array_column($currencies, 'ID');
+
+            $currencyConversion = array_filter($currencyConversion, fn($conversion) => in_array($conversion['TO_CURRENCY_ID'], $currenciesId));
+            $currencyConversion = array_values($currencyConversion);
+        }
+
         $currencyConversion = array_column($currencyConversion, NULL, 'TO_CURRENCY_ID');
 
         foreach ($currencies as &$currency) {

+ 114 - 4
backendApi/modules/v1/controllers/FinanceController.php

@@ -9,6 +9,8 @@
 namespace backendApi\modules\v1\controllers;
 
 use backendApi\modules\v1\models\Admin;
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
 use backendApi\modules\v1\models\exportForms\FinanceExportForm;
 use backendApi\modules\v1\models\lists\finance\BalanceAuditList;
 use backendApi\modules\v1\models\lists\finance\HistoryBonusList;
@@ -93,6 +95,18 @@ class FinanceController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new BalanceAuditList();
         $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
         return static::notice($data);
@@ -123,8 +137,23 @@ class FinanceController extends BaseController {
             'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
             'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
         ]);
+
+        $condition = $filter['condition'];
+        $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new FinanceExportForm();
-        $result = $form->run($filter, Yii::t('ctx', 'memberEcoinAdjustmentListFileName')); // 会员余额调整列表
+        $result = $form->run(['condition' => $condition, 'params' => $params], Yii::t('ctx', 'memberEcoinAdjustmentListFileName')); // 会员余额调整列表
         if (!$result) {
             return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
         }
@@ -273,6 +302,18 @@ class FinanceController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new TransferList();
         $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
         return static::notice($data);
@@ -305,8 +346,23 @@ class FinanceController extends BaseController {
             'PERIOD_NUM' => 'PERIOD_NUM',
             'REMARK' => 'REMARK',
         ]);
+
+        $condition = $filter['condition'];
+        $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new FinanceExportForm();
-        $result = $form->run($filter, Yii::t('ctx', 'financeControllerTransferListExport')); // 转账列表
+        $result = $form->run(['condition' => $condition, 'params' => $params], Yii::t('ctx', 'financeControllerTransferListExport')); // 转账列表
         if (!$result) {
             return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
         }
@@ -330,6 +386,18 @@ class FinanceController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new WithdrawList();
         $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
 
@@ -453,8 +521,23 @@ class FinanceController extends BaseController {
                  $filter['condition'] .= " AND W.WITHDRAW_PERIOD_NUM = $periodNum";
             }
         }
+
+        $condition = $filter['condition'];
+        $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new FinanceExportForm();
-        $result = $form->run($filter, Yii::t('ctx', 'exportWithdrawApplyExcelName')); // 提现申请
+        $result = $form->run(['condition' => $condition, 'params' => $params], Yii::t('ctx', 'exportWithdrawApplyExcelName')); // 提现申请
         if (!$result) {
             return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
         }
@@ -1084,6 +1167,18 @@ class FinanceController extends BaseController {
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new RechargeList();
         $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
         return static::notice($data);
@@ -1104,8 +1199,23 @@ class FinanceController extends BaseController {
             'BANK_NO' => 'R.BANK_NO',
             'CREATED_AT' => 'R.CREATED_AT',
         ]);
+
+        $condition = $filter['condition'];
+        $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $form = new FinanceExportForm();
-        $result = $form->run($filter, 'Recharge'); // 充值申请
+        $result = $form->run(['condition' => $condition, 'params' => $params], 'Recharge'); // 充值申请
         if (!$result) {
             return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
         }

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

@@ -8,6 +8,8 @@
 
 namespace backendApi\modules\v1\controllers;
 
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
 use backendApi\modules\v1\models\exportForms\BaShopExportForm;
 use backendApi\modules\v1\models\exportForms\ShopExportForm;
 use backendApi\modules\v1\models\lists\shop\DecOrderList;
@@ -24,6 +26,9 @@ use backendApi\modules\v1\models\lists\shop\FlowRemainPvList;
 use common\helpers\Cache;
 use common\helpers\Date;
 use common\helpers\Form;
+use common\helpers\LoggerTool;
+use common\models\Countries;
+use common\models\Currency;
 use common\models\CurrencyConversions;
 use common\models\DeclarationPackage;
 use common\models\DecOrder;
@@ -74,6 +79,7 @@ class ShopController extends BaseController {
             'SELL_TYPE'=> 'SELL_TYPE',
             'PRICE_PV'=> 'PRICE_PV',
             'CATEGORY_TYPE' => 'CATEGORY_TYPE',
+            'AUTO_MAINTENANCE' => 'AUTO_MAINTENANCE',
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
@@ -111,6 +117,7 @@ class ShopController extends BaseController {
             'SELL_TYPE'=> 'SELL_TYPE',
             'PRICE_PV'=> 'PRICE_PV',
             'CATEGORY_TYPE' => 'CATEGORY_TYPE',
+            'AUTO_MAINTENANCE' => 'AUTO_MAINTENANCE',
         ]);
         $form = new ShopExportForm();
         $result = $form->run($filter, \Yii::t('ctx', 'shopExportListName')); // 商品列表
@@ -136,11 +143,36 @@ class ShopController extends BaseController {
                 return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
             }
         }
+
+        $countries = Cache::getCountries();
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
+        }
+
+        // 货币
+        $currencies = Cache::getCurrencies();
+        $currencies = array_column($currencies, NULL, 'ID');
+        // 货币汇率
+        $currenciesConversions = CurrencyConversions::getFromCache();
+        $currenciesConversions = array_column($currenciesConversions, NULL, 'TO_CURRENCY_ID');
+
+        foreach ($countries as $key => $country) {
+            $countries[$key]['LOCAL_CURRENCY_NAME'] = $currencies[$country['LOCAL_CURRENCY_ID']]['NAME'] ?? '';
+            $countries[$key]['CURRENCY_PRODUCT_RATE'] = $currenciesConversions[$country['LOCAL_CURRENCY_ID']]['PRODUCT_RATE'] ?? 0;
+        }
+
         return static::notice([
             'sellType' => ShopGoods::getSaleType(),
             'goodsType' => ShopGoods::getGoodType(),
             'giftType' => ShopGoods::getGiftType(),
             'categoryType' => ShopGoods::getCategoryType(),
+            'countries' => $countries,
         ]);
     }
 
@@ -179,15 +211,24 @@ class ShopController extends BaseController {
         $currenciesConversions = CurrencyConversions::getFromCache();
         $currenciesConversions = array_column($currenciesConversions, NULL, 'TO_CURRENCY_ID');
 
-        foreach ($countries as &$country) {
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
+        }
+
+        foreach ($countries as $key => $country) {
             // 货币
-            $country['LOCAL_CURRENCY_NAME'] = $currencies[$country['LOCAL_CURRENCY_ID']]['NAME'] ?? '';
-            $country['CURRENCY_PRODUCT_RATE'] = $currenciesConversions[$country['LOCAL_CURRENCY_ID']]['PRODUCT_RATE'] ?? 0;
+            $countries[$key]['LOCAL_CURRENCY_NAME'] = $currencies[$country['LOCAL_CURRENCY_ID']]['NAME'] ?? '';
+            $countries[$key]['CURRENCY_PRODUCT_RATE'] = $currenciesConversions[$country['LOCAL_CURRENCY_ID']]['PRODUCT_RATE'] ?? 0;
             // 商品属性
-            $country['SHOP_GOODS_NATURE'] = ShopGoodsNature::findAllAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID', [':GOODS_ID' => $id, ':COUNTRY_ID' => $country['ID']]);
+            $countries[$key]['SHOP_GOODS_NATURE'] = ShopGoodsNature::findAllAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID', [':GOODS_ID' => $id, ':COUNTRY_ID' => $country['ID']]);
         }
 
-        $data['SHOP_GOODS_NATURE'] = $countries;
+        $data['SHOP_GOODS_NATURE'] = array_values($countries);
 
         return static::notice(
             [
@@ -426,9 +467,23 @@ class ShopController extends BaseController {
             'ORDER_TYPE'=> 'O.ORDER_TYPE',
             'STATUS' => 'O.STATUS',
             'COUNTRY' => 'O.COUNTRY_ID',
-            'IS_AUTO' => 'O.IS_AUTO'
+            'AUTO_MAINTENANCE' => 'O.AUTO_MAINTENANCE'
         ]);
+
         $condition = ' 1=1 ' . $filter['condition'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition = ' 1=1 ' . $filter['condition'] . " AND O.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $params = $filter['params'];
         $condition .= $condition ? ' AND O.IS_DELETE=0' : ' O.IS_DELETE=0';
         $listObj = new OrderList();
@@ -452,9 +507,23 @@ class ShopController extends BaseController {
             'CREATED_AT'=> 'O.CREATED_AT',
             'ORDER_TYPE'=> 'O.ORDER_TYPE',
             'STATUS' => 'O.STATUS',
-            'IS_AUTO' => 'O.IS_AUTO'
+            'AUTO_MAINTENANCE' => 'O.AUTO_MAINTENANCE'
         ]);
-        $filter['condition'] = !$filter['condition'] ? '1=1 AND O.IS_DELETE=0' : ('O.IS_DELETE=0 ' . $filter['condition']);
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $filter['condition'] = ('O.IS_DELETE=0 ' . $filter['condition']) . " AND O.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        } else {
+            $filter['condition'] = ('O.IS_DELETE=0 ' . $filter['condition']);
+        }
+
         $form = new ShopExportForm();
         $result = $form->run($filter, \Yii::t('ctx', 'shopOrderListExport')); // 订单列表
         if (!$result) {
@@ -910,6 +979,17 @@ class ShopController extends BaseController {
                 'MODERN_PERIOD'=> 'P.MODERN_PERIOD',
                 'CREATED_AT'=> 'P.CREATED_AT',
             ]);
+
+            $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+            if (!$isSuper) {
+                $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+                $adminCountry = AdminCountry::getCountry($adminId);
+                $quotedAdminCountry = array_map(function($item) {
+                    return "'" . addslashes($item) . "'";
+                }, $adminCountry);
+                $filter['condition'] .= ' AND O.COUNTRY_ID IN (' . implode(',', $quotedAdminCountry) . ')';
+            }
+
             $listObj = new OrderPeriodAdjustList();
             $data = $listObj->getList(['condition' => $filter['condition'], 'params' => $filter['params']]);
             return static::notice($data);
@@ -925,12 +1005,26 @@ class ShopController extends BaseController {
     {
         $orderSn = \Yii::$app->request->get('orderSn');
 
-        $order = Order::findOneAsArray('SN=:SN', [':SN' => $orderSn]);
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function ($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $order = Order::findOneAsArray('SN=:SN AND COUNTRY_ID IN (' . implode(',', $quotedAdminCountry) . ')', [':SN' => $orderSn]);
+        } else {
+            $order = Order::findOneAsArray('SN=:SN', [':SN' => $orderSn]);
+        }
         if (!$order) {
             return static::notice(Yii::t('ctx', 'orderNotExist'), 400);
         }
+
         $order['ORDER_TYPE'] = $order['ORDER_TYPE'] === 'ZC' ? Yii::t('ctx', 'shopOrderListOrderTypeZc') : Yii::t('ctx', 'shopOrderListOrderTypeFx');
-        // 如果当前订单所在期数已挂网,则不可调整
+        $order['COUNTRY'] = Countries::getById($order['COUNTRY_ID'])['NAME'] ?? '';
+
+        // 已挂网,不可调整
         $period = Period::getInfoByPeriodNum($order['PERIOD_NUM']);
         if (!$period) {
             return static::notice(Yii::t('ctx', 'invalidPcNo'), 400);
@@ -938,7 +1032,8 @@ class ShopController extends BaseController {
         if ($period['IS_SENT'] > 0) {
             return static::notice(Yii::t('ctx', 'orderHasBeenConnected'), 400);
         }
-        // 根据订单期数查询可调整期数
+
+        // 可调整期数
         $availablePeriod = [];
         if ($order['PERIOD_NUM']) {
             $availablePeriod = Period::getPeriodList(+$order['PERIOD_NUM'] - 1);

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

@@ -7,6 +7,9 @@
  */
 namespace backendApi\modules\v1\controllers;
 
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
+use common\helpers\LoggerTool;
 use common\helpers\snowflake\PageSnowFake;
 use common\helpers\Tool;
 use common\models\CurrencyConversions;
@@ -103,6 +106,8 @@ class SiteController extends BaseController
         $periodNum = $period->getNowPeriodNum();
         // 汇率
         $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
+        $isSuperAdmin = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+
         return [
             'decLevels' => $decLevels,
             'empLevels' => $empLevels,
@@ -122,6 +127,7 @@ class SiteController extends BaseController
             'allNation' => $allNation,
             'nowPeriodNum' => $periodNum,
             'exchangeRate' => $exchangeRate,
+            'isSuperAdmin' => $isSuperAdmin,
         ];
     }
 
@@ -179,6 +185,17 @@ class SiteController extends BaseController
     {
         // 国家
         $countries = Cache::getCountries();
+
+//        $filter = \Yii::$app->request->get('filter', 0);
+        $isSuperAdmin = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuperAdmin) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
+        }
+
         // 货币
         $currencies = Cache::getCurrencies();
         $currencies = array_column($currencies, NULL, 'ID');
@@ -186,10 +203,15 @@ class SiteController extends BaseController
         $currenciesConversions = CurrencyConversions::getFromCache();
         $currenciesConversions = array_column($currenciesConversions, NULL, 'TO_CURRENCY_ID');
 
-        foreach ($countries as &$country) {
-            $country['LOCAL_CURRENCY_NAME'] = $currencies[$country['LOCAL_CURRENCY_ID']]['NAME'] ?? '';
-            $country['CURRENCY_PRODUCT_RATE'] = $currenciesConversions[$country['LOCAL_CURRENCY_ID']]['PRODUCT_RATE'] ?? 0;
-        }
+        $countries = array_map(function ($country) use ($currencies, $currenciesConversions) {
+            return array_merge(
+                $country,
+                [
+                    'LOCAL_CURRENCY_NAME' => $currencies[$country['LOCAL_CURRENCY_ID']]['NAME'] ?? '',
+                    'CURRENCY_PRODUCT_RATE' => $currenciesConversions[$country['LOCAL_CURRENCY_ID']]['PRODUCT_RATE'] ?? 0
+                ]
+            );
+        }, $countries);
 
         return static::notice(['data' => $countries]);
     }

+ 102 - 13
backendApi/modules/v1/controllers/UserController.php

@@ -10,6 +10,8 @@ namespace backendApi\modules\v1\controllers;
 
 use backendApi\modules\v1\components\UserAuth;
 use backendApi\modules\v1\models\Admin;
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
 use backendApi\modules\v1\models\exportForms\BaUserExportForm;
 use backendApi\modules\v1\models\exportForms\UserExportForm;
 use backendApi\modules\v1\models\lists\shop\BaUserList;
@@ -27,6 +29,7 @@ use common\helpers\Date;
 use common\helpers\Form;
 use common\helpers\http\BackendToFrontendApi;
 use common\helpers\Log;
+use common\helpers\LoggerTool;
 use common\helpers\NetPoint;
 use common\helpers\Tool;
 use common\helpers\user\Balance;
@@ -143,9 +146,26 @@ class UserController extends BaseController
             ],
             'ADDRESS' => 'U.ADDRESS',
         ]);
-        $condition = $filter['condition'];
-        $params = $filter['params'];
-        $condition .= ' AND UI.DELETED=0 ';
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition = $filter['condition'] ?? '';
+            $filter['condition'] = $condition . " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+
+            $condition = $filter['condition'];
+            $params = $filter['params'];
+            $condition .= " AND U.DELETED=0 AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        } else {
+            $condition = $filter['condition'] . ' AND U.DELETED=0' ?? ' AND U.DELETED=0';
+            $params = $filter['params'];
+        }
+
         $listObj = new IndexList();
         $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
         return static::notice($data);
@@ -200,6 +220,22 @@ class UserController extends BaseController
             'VERIFIED_AT' => 'U.VERIFIED_AT',
             'ALLOW_TRANSFER' => 'UI.ALLOW_TRANSFER',
         ]);
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition = $filter['condition'] ?? '';
+            $filter['condition'] = $condition . " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        } else {
+            $condition = $filter['condition'] ?? '';
+            $filter['condition'] = $condition;
+        }
+
         $form = new UserExportForm();
         $result = $form->run($filter, 'Member_List');
         if (!$result) {
@@ -691,27 +727,30 @@ class UserController extends BaseController
     public function actionMove()
     {
         $filter = $this->filterCondition([
-//            'userIds' => 'UM.USER_ID',
             'filterStatus' => 'UM.AUDIT_STATUS',
             'MOVE_USER_NAME' => 'CU.USER_NAME',
             'MOVE_REAL_NAME' => 'CU.REAL_NAME',
-//            'moveType' => 'UM.TYPE',
-//            'FROM_USER_NAME' => 'FUI.USER_NAME',
-//            'TO_USER_NAME' => 'TUI.USER_NAME',
             'MOVE_PERCENT_SHOW' => 'UM.MOVE_PERCENT',
-//            'STARTED_AT' => 'UM.STARTED_AT',
-//            'ENDED_AT' => 'UM.ENDED_AT',
             'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
             'PERIOD_NUM' => 'UM.PERIOD_NUM',
-//            'CREATED_AT' => 'UM.CREATED_AT',
             'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
             'MOVE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
-//            'AUDIT_PERIOD_NUM' => 'UM.AUDIT_PERIOD_NUM',
             'AUDITED_AT' => 'UM.AUDITED_AT',
-//            'CREATE_REMARK' => 'UM.CREATE_REMARK',
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND CU.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new MoveList();
         $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
         return static::notice($data);
@@ -876,6 +915,17 @@ class UserController extends BaseController
     {
         $userName = Yii::$app->request->get('userName');
         $userInfo = Info::getBaseUserByUserName($userName);
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            if (!in_array($userInfo['COUNTRY_ID'], $adminCountry)) {
+                return static::notice('Member number does not exist', 400);
+            }
+        }
+
         if($userInfo){
             $decLevelConfig = Cache::getDecLevelConfig();
             $userInfo['LEVEL_NAME'] = isset($decLevelConfig[$userInfo['DEC_LV']])?$decLevelConfig[$userInfo['DEC_LV']]['LEVEL_NAME'] : '';
@@ -883,6 +933,9 @@ class UserController extends BaseController
             $userInfo['CASH'] = Cash::getAvailableBalance($userInfo['ID']);
             $userInfo['RECONSUME_POINTS'] = Balance::getBalanceReconsumePoints($userInfo['ID']);
             $userInfo['EXCHANGE_POINTS'] = Balance::getBalanceExchangePoints($userInfo['ID']);
+            $userInfo['country'] = Countries::getNameById($userInfo['COUNTRY_ID']);
+            $userInfo['countryCode'] = Countries::getCodeById($userInfo['COUNTRY_ID']);
+
             return static::notice($userInfo);
         }else{
             return static::notice('Member number does not exist', 400);//会员编号不存在
@@ -1152,13 +1205,25 @@ class UserController extends BaseController
         $data['allNation'] = \Yii::$app->params['nation'];
         $data['region'] = Region::getByCountryId($userInfo['COUNTRY_ID']);
         $data['language'] = Language::getFromCache();
-        $data['country'] = Countries::getFromCache();
         $data['allOpenBank'] = OpenBank::find()
             ->where('STATUS=:STATUS AND COUNTRY_ID=:COUNTRY_ID', [':STATUS' => 1, ':COUNTRY_ID' => $userInfo['COUNTRY_ID']])
             ->orderBy('BANK_NAME ASC')
             ->asArray()
             ->all();
 
+        $countries = Countries::getFromCache();
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+
+            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
+            $countries = array_values($countries);
+        }
+
+        $data['country'] = array_values($countries);
+
         $data['userInfo'] = [
             'userId' => $userInfo['ID'],
             'nation' => \Yii::$app->params['nation'][$userInfo['NATION']]['name']??'',
@@ -1433,6 +1498,18 @@ class UserController extends BaseController
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND CU.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new DecLevelList();
         $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
 
@@ -2397,6 +2474,18 @@ class UserController extends BaseController
         ]);
         $condition = $filter['condition'];
         $params = $filter['params'];
+
+        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
+        if (!$isSuper) {
+            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
+            $adminCountry = AdminCountry::getCountry($adminId);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition .= " AND CU.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         $listObj = new ChangeHighestEmpLevelList();
         $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
 

+ 36 - 31
backendApi/modules/v1/models/Admin.php

@@ -132,6 +132,11 @@ class Admin extends ActiveRecord
         return $data ? $data['ADMIN_NAME'] : null;
     }
 
+    public static function getRoleIdById($id){
+        $data = self::findOneAsArray('ID=:ID', [':ID' => $id], 'ROLE_ID');
+        return $data ? $data['ROLE_ID'] : null;
+    }
+
     /**
      * 操作日志记录条件
      * @return array
@@ -140,11 +145,11 @@ class Admin extends ActiveRecord
         return [
             'ADMIN_NAME' => '用户名',
             'REAL_NAME' => '会员姓名',
-            'REMARK' => '备注',
+//            'REMARK' => '备注',
             'ROLE_ID' => [
                 'label' => '角色名称',
                 'type' => function($data){
-                    $value = isset($data['value']) ? $data['value'] : '';
+                    $value = $data['value'] ?? '';
                     $result = AdminRole::findOneAsArray('ID=:ID', [':ID'=>$value], 'ROLE_NAME');
                     return !empty($result) ? $result['ROLE_NAME'] : '';
                 },
@@ -153,35 +158,35 @@ class Admin extends ActiveRecord
                 'label' => '是否启用',
                 'type' => ValueTypeConfig::YES_NO_TYPE,
             ],
-            'BIND_IP' => '绑定IP',
-            'CREATE_ADMIN' => [
-                'label' => '创建人',
-                'type' => function($data){
-                    $value = isset($data['value']) ? $data['value'] : '';
-                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
-                    return !empty($result) ? $result['ADMIN_NAME'] : '';
-                },
-            ],
-            'UPDATE_ADMIN' => [
-                'label' => '更新人',
-                'type' => function($data){
-                    $value = isset($data['value']) ? $data['value'] : '';
-                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
-                    return !empty($result) ? $result['ADMIN_NAME'] : '';
-                },
-            ],
-            'CREATED_AT' => [
-                'label' => '创建时间',
-                'type' => ValueTypeConfig::DATE_TIME_TYPE,
-            ],
-            'UPDATED_AT' => [
-                'label' => '更新时间',
-                'type' => ValueTypeConfig::DATE_TIME_TYPE,
-            ],
-            'IS_MODIFY_PASSWORD' => [
-                'label' => '是否修改密码',
-                'type' => ValueTypeConfig::YES_NO_TYPE,
-            ],
+//            'BIND_IP' => '绑定IP',
+//            'CREATE_ADMIN' => [
+//                'label' => '创建人',
+//                'type' => function($data){
+//                    $value = isset($data['value']) ? $data['value'] : '';
+//                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
+//                    return !empty($result) ? $result['ADMIN_NAME'] : '';
+//                },
+//            ],
+//            'UPDATE_ADMIN' => [
+//                'label' => '更新人',
+//                'type' => function($data){
+//                    $value = isset($data['value']) ? $data['value'] : '';
+//                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
+//                    return !empty($result) ? $result['ADMIN_NAME'] : '';
+//                },
+//            ],
+//            'CREATED_AT' => [
+//                'label' => '创建时间',
+//                'type' => ValueTypeConfig::DATE_TIME_TYPE,
+//            ],
+//            'UPDATED_AT' => [
+//                'label' => '更新时间',
+//                'type' => ValueTypeConfig::DATE_TIME_TYPE,
+//            ],
+//            'IS_MODIFY_PASSWORD' => [
+//                'label' => '是否修改密码',
+//                'type' => ValueTypeConfig::YES_NO_TYPE,
+//            ],
         ];
     }
 }

+ 14 - 3
backendApi/modules/v1/models/AdminCountry.php

@@ -2,6 +2,8 @@
 
 namespace backendApi\modules\v1\models;
 
+use common\components\ActiveRecord;
+
 /**
  * This is the model class for table "{{%ADMIN_COUNTRY}}".
  *
@@ -11,7 +13,7 @@ namespace backendApi\modules\v1\models;
  * @property int $CREATED_AT 创建时间
  * @property int $UPDATED_AT 更新时间
  */
-class AdminCountry extends \common\components\ActiveRecord
+class AdminCountry extends ActiveRecord
 {
     /**
      * @inheritdoc
@@ -22,7 +24,7 @@ class AdminCountry extends \common\components\ActiveRecord
     }
 
     /**
-     * @inheritdoc
+     * {@inheritdoc}
      */
     public function rules()
     {
@@ -34,7 +36,7 @@ class AdminCountry extends \common\components\ActiveRecord
     }
 
     /**
-     * @inheritdoc
+     * {@inheritdoc}
      */
     public function attributeLabels()
     {
@@ -46,4 +48,13 @@ class AdminCountry extends \common\components\ActiveRecord
             'UPDATED_AT' => '更新时间',
         ];
     }
+
+    /**
+     * @param $adminId
+     * @return array
+     */
+    public static function getCountry($adminId): array
+    {
+        return self::find()->select('COUNTRY_ID')->where(['ADMIN_ID' => $adminId])->column();
+    }
 }

+ 24 - 2
backendApi/modules/v1/models/AdminForm.php

@@ -23,6 +23,7 @@ class AdminForm extends Model
     public $surePassword;
     public $roleId;
     public $lang;
+    public $countryId;
 
     public function init() {
         parent::init();
@@ -54,8 +55,8 @@ class AdminForm extends Model
     {
         $parentScenarios =  parent::scenarios();
         $customScenarios = [
-            'add' => ['adminName', 'realName', 'password', 'surePassword', 'roleId', 'remark', 'isEnable', 'isModifyPassword', 'bindIp'],
-            'edit' => ['id', 'password', 'surePassword', 'roleId', 'realName', 'remark', 'isEnable', 'isModifyPassword', 'bindIp'],
+            'add' => ['adminName', 'realName', 'password', 'surePassword', 'roleId', 'remark', 'isEnable', 'isModifyPassword', 'bindIp', 'countryId'],
+            'edit' => ['id', 'password', 'surePassword', 'roleId', 'realName', 'remark', 'isEnable', 'isModifyPassword', 'bindIp', 'countryId'],
             'changePassword' => ['password', 'surePassword'],
             'noLoginModifyPassword' => ['adminName', 'oldPassword', 'password', 'surePassword'],
             'changeLanguage' => ['adminName', 'lang'],
@@ -77,6 +78,7 @@ class AdminForm extends Model
             'password' => '密码',
             'surePassword' => '确认密码',
             'roleId' => '角色',
+            'countryId' => '国家',
         ];
     }
 
@@ -173,6 +175,15 @@ class AdminForm extends Model
                 'userName' => $model->ADMIN_NAME,
                 'remark' => $this->remark,
             ]);
+
+            if (!AdminRole::isSuperAdmin($this->roleId)) {
+                foreach ($this->countryId as $country) {
+                    $adminCountry = new AdminCountry();
+                    $adminCountry->ADMIN_ID = $model->ID;
+                    $adminCountry->COUNTRY_ID = $country;
+                    $adminCountry->save();
+                }
+            }
         } elseif($this->scenario == 'edit') {
             $this->adminOperateLogger->afterUpdate($model);
             $this->adminOperateLogger->clean()->save([
@@ -180,6 +191,17 @@ class AdminForm extends Model
                 'userName' => $model->ADMIN_NAME,
                 'remark' => $this->remark,
             ]);
+
+            (new AdminCountry())->deleteAll(['ADMIN_ID' => $model->ID]);
+            if (!AdminRole::isSuperAdmin($this->roleId)) {
+                // 国家
+                foreach ($this->countryId as $country) {
+                    $adminCountry = new AdminCountry();
+                    $adminCountry->ADMIN_ID = $model->ID;
+                    $adminCountry->COUNTRY_ID = $country;
+                    $adminCountry->save();
+                }
+            }
         } elseif($this->scenario == 'noLoginModifyPassword') {
             $this->adminOperateLogger->clean()->save([
                 'optType' => '不登录重置密码',

+ 9 - 0
backendApi/modules/v1/models/AdminRole.php

@@ -187,4 +187,13 @@ class AdminRole extends \common\components\ActiveRecord
         }
         return $allColumns;
     }
+
+    /**
+     * 判断是否为超级管理员角色
+     * @param string $roleId 角色ID
+     * @return bool
+     */
+    public static function isSuperAdmin($roleId){
+        return $roleId === Yii::$app->params['superAdminRoleId'];
+    }
 }

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

@@ -6,6 +6,7 @@ use common\helpers\user\Info;
 use common\libs\dataList\column\Price;
 use common\libs\dataList\column\YesNo;
 use common\libs\dataList\DataListInterface;
+use common\models\Countries;
 use common\models\User;
 use common\models\UserBind;
 use common\models\UserBonus;
@@ -34,13 +35,14 @@ class BalanceList extends \common\libs\dataList\DataList implements DataListInte
     {
         $this->condition .= ' AND UI.STATUS=1 AND I.LAST_LOGIN_AT>=1620748800';
         $this->listData = UserBonus::lists($this->condition, $this->params, [
-            'select' => 'UB.*,UI.*,UW.CASH, UP.AMOUNTS AS PRP',
+            'select' => 'UB.*,UI.*,UW.CASH, UP.AMOUNTS AS PRP, C.NAME AS COUNTRY',
             'from' => UserBonus::tableName() . ' AS UB',
             'join' => [
-                ['LEFT JOIN', User::tableName() . ' AS UI', 'UI.ID=UB.USER_ID'],
+                ['INNER JOIN', User::tableName() . ' AS UI', 'UI.ID=UB.USER_ID'],
                 ['LEFT JOIN', UserWallet::tableName() . ' AS UW', 'UW.USER_ID=UB.USER_ID'],
                 ['LEFT JOIN', UserInfo::tableName() . ' AS I', 'I.USER_ID=UB.USER_ID'],
-                ['LEFT JOIN', "(SELECT USER_ID,SUM(AMOUNTS) AS AMOUNTS FROM AR_USER_PERFORMANCE WHERE STATUS_ID<30 GROUP BY USER_ID) UP", 'UW.USER_ID=UP.USER_ID']
+                ['LEFT JOIN', "(SELECT USER_ID,SUM(AMOUNTS) AS AMOUNTS FROM AR_USER_PERFORMANCE WHERE STATUS_ID<30 GROUP BY USER_ID) UP", 'UW.USER_ID=UP.USER_ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'UI.COUNTRY_ID=C.ID'],
             ],
             'orderBy' => 'UB.CREATED_AT ASC, UB.ID ASC',
             'page' => $this->page,
@@ -74,6 +76,9 @@ class BalanceList extends \common\libs\dataList\DataList implements DataListInte
                         'tag'=>['type'=>'success', 'size' => 'small', 'class'=>'no-border']
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'IS_DEC' => [
                     'header' => \Yii::t('ctx', 'whetherStockist'), // 是否报单中心
                     'value' => function($row) {

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

@@ -8,9 +8,11 @@ use common\helpers\user\Info;
 use common\libs\dataList\column\Price;
 use common\libs\dataList\column\YesNo;
 use common\libs\dataList\DataListInterface;
+use common\models\Countries;
 use common\models\DealType;
 use common\models\FlowBonus;
 use common\libs\dataList\column\DateTime;
+use common\models\User;
 use Yii;
 
 class FlowBonusList extends \common\libs\dataList\DataList implements DataListInterface {
@@ -28,18 +30,17 @@ class FlowBonusList extends \common\libs\dataList\DataList implements DataListIn
      */
     public function dataHandle() {
         $this->listData = FlowBonus::lists($this->condition, $this->params, [
-            'select' => 'FB.*,U.USER_NAME,U.REAL_NAME,U.IS_DEC',
+            'select' => 'FB.*,U.USER_NAME,U.REAL_NAME,U.IS_DEC, C.NAME AS COUNTRY',
             'orderBy' => 'FB.CREATED_AT DESC,FB.SORT DESC,FB.AUTO_SORT DESC,FB.ID DESC',
             'from' => FlowBonus::tableName() . ' AS FB',
             'join' => [
-                ['LEFT JOIN', \common\models\User::tableName() . ' AS U', 'FB.USER_ID=U.ID'],
+                ['INNER JOIN', User::tableName() . ' AS U', 'FB.USER_ID=U.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'U.COUNTRY_ID=C.ID'],
             ],
             'page' => $this->page,
             'pageSize' => $this->pageSize,
         ]);
         foreach ($this->listData['list'] as $key => $value) {
-            //$userInfo = Info::baseInfoZh($value['USER_ID']);
-            //$this->listData['list'][$key] = array_merge($userInfo, $value);
             $this->listData['list'][$key]['DEAL_TYPE_NAME'] = DealType::getAllTypesForShow()[$value['DEAL_TYPE_ID']]['TYPE_NAME'] ?? '';
             $this->listData['list'][$key]['LAST_DEC_LV_NAME'] = Cache::getDecLevelConfig()[$value['LAST_DEC_LV']]['LEVEL_NAME'] ?? '';
             $this->listData['list'][$key]['LAST_EMP_LV_NAME'] = Cache::getEmpLevelConfig()[$value['LAST_EMP_LV']]['LEVEL_NAME'] ?? '';
@@ -101,6 +102,9 @@ class FlowBonusList extends \common\libs\dataList\DataList implements DataListIn
                         'tag' => ['type' => 'success', 'size' => 'small', 'class' => 'no-border']
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'LAST_DEC_LV_NAME' => [
                     'header' => Yii::t('ctx', 'memberLevel'), // 会员级别
                     'headerOther' => [

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

@@ -4,6 +4,7 @@ namespace backendApi\modules\v1\models\lists\bonus;
 use common\helpers\Cache;
 use common\helpers\user\Info;
 use common\models\CalcBonusBSDefault;
+use common\models\Countries;
 use common\models\PerfMonth;
 use common\models\User as modelUser;
 use common\libs\dataList\column\Price;
@@ -29,12 +30,13 @@ class PerfMonthList extends \common\libs\dataList\DataList implements DataListIn
     public function dataHandle()
     {
         $data = PerfMonth::lists($this->condition, $this->params, [
-            'select'=>'PM.*, U.USER_NAME, U.REAL_NAME,RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME',
+            'select'=>'PM.*, U.USER_NAME, U.REAL_NAME,RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME, C.NAME AS COUNTRY',
             'from' => PerfMonth::tableName().' AS PM',
             'join' => [
-                ['LEFT JOIN', modelUser::tableName() . ' AS U', 'PM.USER_ID=U.ID'],
+                ['INNER JOIN', modelUser::tableName() . ' AS U', 'PM.USER_ID=U.ID'],
                 ['LEFT JOIN', UserInfo::tableName() . ' AS UI', 'PM.USER_ID=UI.USER_ID'],
                 ['LEFT JOIN', modelUser::tableName() . ' AS RU', 'UI.REC_UID=RU.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'U.COUNTRY_ID=C.ID'],
             ],
             'orderBy' => 'PM.CREATED_AT DESC, PM.ID DESC',
             'page' => $this->page,
@@ -74,6 +76,9 @@ class PerfMonthList extends \common\libs\dataList\DataList implements DataListIn
                         'width' => '150',
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'REC_USER_NAME' => [
                     'header' => Yii::t('ctx', 'recommenderNo'), // 推荐人编号
                     'headerOther' => [

+ 10 - 5
backendApi/modules/v1/models/lists/bonus/PerfOrderList.php

@@ -3,6 +3,7 @@ namespace backendApi\modules\v1\models\lists\bonus;
 
 use backendApi\modules\v1\models\Admin;
 use backendApi\modules\v1\models\User;
+use common\models\Countries;
 use common\models\User as modelUser;
 use common\helpers\Cache;
 use common\helpers\user\Info;
@@ -36,10 +37,11 @@ class PerfOrderList extends \common\libs\dataList\DataList implements DataListIn
     public function dataHandle()
     {
         $data = PerfOrder::lists($this->condition, $this->params, [
-            'select'=>'PO.*, U.USER_NAME, U.REAL_NAME',
+            'select'=>'PO.*, U.USER_NAME, U.REAL_NAME, C.NAME AS COUNTRY',
             'from' => PerfOrder::tableName().' AS PO',
             'join' => [
-                ['LEFT JOIN', modelUser::tableName() . ' AS U', 'PO.USER_ID=U.ID'],
+                ['INNER JOIN', modelUser::tableName() . ' AS U', 'PO.USER_ID=U.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'U.COUNTRY_ID=C.ID'],
             ],
             'orderBy' => 'PO.CREATED_AT DESC, PO.ID DESC',
             'page' => $this->page,
@@ -63,7 +65,7 @@ class PerfOrderList extends \common\libs\dataList\DataList implements DataListIn
                 'PERIOD_NUM' => [
                     'header' => Yii::t('ctx', 'payCycle'), // 结算期数
                     'headerOther' => [
-                        'width' => '140',
+                        'width' => '120',
                     ],
                 ],
                 'SN' => [
@@ -72,13 +74,13 @@ class PerfOrderList extends \common\libs\dataList\DataList implements DataListIn
                         return "\t".$row['SN'];
                     },
                     'headerOther' => [
-                        'width' => '250',
+                        'width' => '220',
                     ],
                 ],
                 'DEC_TYPE' => [
                     'header' =>  Yii::t('ctx', 'saleType'), // 业绩单类型
                     'headerOther' => [
-                        'width' => '130',
+                        'width' => '160',
                     ],
                     'value' => function($row){
                         $decTypes = [
@@ -109,6 +111,9 @@ class PerfOrderList extends \common\libs\dataList\DataList implements DataListIn
                         'width' => '150',
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'LAST_REC_USER_NAME' => [
                     'header' => Yii::t('ctx', 'sponsorNoAtSettlement'), // 结算时开拓者编号
                     'headerOther' => [

+ 8 - 1
backendApi/modules/v1/models/lists/bonus/PeriodBonusList.php

@@ -6,10 +6,12 @@ use common\helpers\Tool;
 use common\helpers\user\Info;
 use common\libs\dataList\DataListInterface;
 use common\models\CalcBonus;
+use common\models\Countries;
 use common\models\DeclarationLevel;
 use common\models\EliteLevel;
 use common\models\EmployLevel;
 use common\models\Period;
+use common\models\User;
 use common\models\UserInfo;
 use Yii;
 
@@ -31,11 +33,13 @@ class PeriodBonusList extends \common\libs\dataList\DataList implements DataList
     {
         $yearMonth = $this->others['yearMonth'];
         $this->listData = CalcBonus::lists($this->condition, $this->params, [
-            'select'=>'CB.*,UI.CON_UID,UI.REC_UID,PO.CALC_YEAR,PO.CALC_MONTH',
+            'select'=>'CB.*,UI.CON_UID,UI.REC_UID,PO.CALC_YEAR,PO.CALC_MONTH, C.NAME AS COUNTRY',
             'from' => CalcBonus::tableName().' AS CB',
             'join' => [
                 ['INNER JOIN', UserInfo::tableName() . ' AS UI', 'CB.USER_ID=UI.USER_ID'],
                 ['INNER JOIN', Period::tableName() . ' AS PO', 'PO.PERIOD_NUM=CB.PERIOD_NUM'],
+                ['INNER JOIN', User::tableName() . ' AS CU', 'UI.USER_ID=CU.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'CU.COUNTRY_ID=C.ID'],
             ],
             'yearMonth' => $yearMonth,
             'orderBy' => 'CB.CREATED_AT DESC, CB.ID DESC',
@@ -97,6 +101,9 @@ class PeriodBonusList extends \common\libs\dataList\DataList implements DataList
                         'tag'=>['type'=>'success', 'size' => 'small', 'class'=>'no-border']
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'LAST_DEC_LV_NAME' => [
                     'header' => \Yii::t('ctx', 'PCMemberLevel'), // 结算时会员级别
                     'headerOther' => [

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

@@ -3,6 +3,7 @@ namespace backendApi\modules\v1\models\lists\bonus;
 
 use common\helpers\Cache;
 use common\helpers\user\Info;
+use common\models\Countries;
 use common\models\PerfMonth;
 use common\models\User as modelUser;
 use common\libs\dataList\column\Price;
@@ -29,10 +30,11 @@ class UserPerfList extends \common\libs\dataList\DataList implements DataListInt
     public function dataHandle()
     {
         $data = UserPerf::lists($this->condition, $this->params, [
-            'select'=>'UP.*, U.USER_NAME, U.REAL_NAME',
+            'select'=>'UP.*, U.USER_NAME, U.REAL_NAME, C.NAME AS COUNTRY',
             'from' => UserPerf::tableName().' AS UP',
             'join' => [
-                ['LEFT JOIN', modelUser::tableName() . ' AS U', 'UP.USER_ID=U.ID'],
+                ['INNER JOIN', modelUser::tableName() . ' AS U', 'UP.USER_ID=U.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'U.COUNTRY_ID=C.ID'],
             ],
             'orderBy' => 'UP.ID DESC',
             'page' => $this->page,
@@ -60,6 +62,9 @@ class UserPerfList extends \common\libs\dataList\DataList implements DataListInt
                         'width' => '200',
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'PV_PCS' => [
                     'header' => Yii::t('ctx', 'personalPerformance'), // 个人业绩
                     'headerOther' => [

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

@@ -9,6 +9,7 @@ use common\libs\dataList\column\DateTime;
 use common\libs\dataList\column\YesNo;
 use common\libs\dataList\DataListInterface;
 use common\models\BalanceAudit;
+use common\models\Countries;
 use common\models\DealType;
 use common\models\User;
 use Yii;
@@ -28,13 +29,14 @@ class BalanceAuditList extends \common\libs\dataList\DataList implements DataLis
      */
     public function dataHandle() {
         $this->listData = BalanceAudit::lists($this->condition, $this->params, [
-            'select' => 'BA.*,U.USER_NAME,U.REAL_NAME,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME AUDIT_ADMIN_NAME',
+            'select' => 'BA.*,U.USER_NAME,U.REAL_NAME,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME AUDIT_ADMIN_NAME, C.NAME AS COUNTRY',
             'orderBy' => 'BA.CREATED_AT DESC, BA.ID DESC',
             'from' => BalanceAudit::tableName() . ' AS BA',
             'join' => [
-                ['LEFT JOIN', User::tableName() . ' AS U', 'BA.USER_ID=U.ID'],
+                ['INNER JOIN', User::tableName() . ' AS U', 'BA.USER_ID=U.ID'],
                 ['LEFT JOIN', Admin::tableName() . ' AS ADMC', 'BA.UPDATE_ADMIN_ID=ADMC.ID'],
                 ['LEFT JOIN', Admin::tableName() . ' AS ADMU', 'BA.AUDIT_ADMIN_ID=ADMU.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'U.COUNTRY_ID=C.ID'],
             ],
             'page' => $this->page,
             'pageSize' => $this->pageSize,
@@ -71,6 +73,9 @@ class BalanceAuditList extends \common\libs\dataList\DataList implements DataLis
                         'width' => '120',
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'LAST_DEC_LV_NAME' => [
                     'header' => Yii::t('ctx', 'modelListFinanceBalanceAuditListMemberLevel'), // 会员级别
                     'headerOther' => [

+ 1 - 1
backendApi/modules/v1/models/lists/finance/RechargeList.php

@@ -32,7 +32,7 @@ class RechargeList extends \common\libs\dataList\DataList implements DataListInt
             'from' => Recharge::tableName() . ' AS R',
             'join' => [
                 ['LEFT JOIN', UserInfo::tableName() . ' AS UI', 'UI.USER_ID=R.USER_ID'],
-                ['LEFT JOIN', USER::tableName() . ' AS U', 'U.ID=R.USER_ID'],
+                ['INNER JOIN', USER::tableName() . ' AS U', 'U.ID=R.USER_ID'],
                 ['LEFT JOIN', OpenBank::tableName() . ' AS OB', 'OB.BANK_CODE=R.OPEN_BANK'],
                 ['LEFT JOIN', Admin::tableName() . ' AS ADMA', 'ADMA.ID=R.AUDIT_ADMIN'],
                 ['LEFT JOIN', Countries::tableName() . ' AS CN', 'U.COUNTRY_ID=CN.ID'],

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

@@ -12,6 +12,7 @@ use common\libs\dataList\column\DateTime;
 use common\libs\dataList\column\YesNo;
 use common\libs\dataList\DataListInterface;
 use common\models\BalanceAudit;
+use common\models\Countries;
 use common\models\DealType;
 use common\models\forms\ReconsumeForm;
 use common\models\PerfAudit;
@@ -19,6 +20,7 @@ use common\models\ReconsumeAudit;
 use common\models\ReconsumePool;
 use common\models\DecRole;
 use common\models\Transfer;
+use common\models\User;
 use common\models\UserInfo;
 use common\models\UserSystem;
 use common\models\YearHighestEmpLv;
@@ -39,8 +41,13 @@ class TransferList extends \common\libs\dataList\DataList implements DataListInt
      */
     public function dataHandle() {
         $this->listData = Transfer::lists($this->condition, $this->params, [
-            'orderBy' => 'CREATED_AT DESC, ID DESC',
-            'from' => Transfer::tableName(),
+            'select' => 'BA.*, C.NAME AS COUNTRY',
+            'orderBy' => 'BA.CREATED_AT DESC, BA.ID DESC',
+            'from' => Transfer::tableName() . ' AS BA',
+            'join' => [
+                ['INNER JOIN', User::tableName() . ' AS U', 'BA.OUT_UID=U.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'U.COUNTRY_ID=C.ID'],
+            ],
             'page' => $this->page,
             'pageSize' => $this->pageSize,
         ]);
@@ -79,6 +86,9 @@ class TransferList extends \common\libs\dataList\DataList implements DataListInt
                         'width' => '120',
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'LAST_OUT_DEC_LV_NAME' => [
                     'header' => Yii::t('ctx', 'modelListFinanceTranserListLastOutDecLvName'), // 转出主体会员级别
                     'headerOther' => [

+ 17 - 62
backendApi/modules/v1/models/lists/shop/GoodsList.php

@@ -46,22 +46,6 @@ class GoodsList extends \common\libs\dataList\DataList implements DataListInterf
                     'header' => \Yii::t('ctx', 'shopListProductsCode'), // 商品编号
                     'headerOther' => ['width' => '200'],
                 ],
-                'SELL_DISCOUNT' => [
-                    'header' => \Yii::t('ctx', 'shopListDiscountRate'), // 商品折扣
-                    'value' => function($row) {
-                        $discount = 0;
-                        if ($row['TYPE'] == 1) {
-                            $discount = '0.5';
-                        } else if($row['TYPE'] == 2) {
-                            $discount = '0.6';
-                        } else {
-                            $discount = $row['SELL_DISCOUNT'];
-                        }
-
-                        return $discount;
-                    },
-                    'headerOther' => ['width' => '150'],
-                ],
                 'GIFT_TYPE' => [
                     'header' => \Yii::t('ctx', 'shopListProductsType'), // 商品类型
                     'value' => function($row){
@@ -76,27 +60,6 @@ class GoodsList extends \common\libs\dataList\DataList implements DataListInterf
                     },
                     'headerOther' => ['width' => '150'],
                 ],
-//                'CATEGORY_TYPE' => [
-//                    'header' => \Yii::t('ctx', 'shopListProductCategory'), // 商品分类
-//                    'value' => function($row) {
-//                        $categoryType =  array_column($this->getCategoryType(), NULL, 'id'); //array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
-//                        return $categoryType[$row['CATEGORY_TYPE']]['name'] ?? '';
-//                    },
-//                    'headerOther' => ['width' => '150'],
-//                ],
-//                'SELL_TYPE' => [
-//                    'header' => \Yii::t('ctx', 'shopListPaymentMode'), // 购买方式
-//                    'value' => function($row){
-//                        $sellType =  $this->getSaleType(); //ShopGoods::SALE_TYPE;
-//                        $sel = explode(',',$row['SELL_TYPE']);
-//                        $value = '';
-//                        foreach ($sel as $v){
-//                            $value.= $sellType[$v]['name'].',';
-//                        }
-//                        return $value;
-//                    },
-//                    'headerOther' => ['width' => '150'],
-//                ],
                 'SELL_PRICE_STANDARD' => [
                     'header' => \Yii::t('ctx', 'shopListPriceStandard'), // 标准价格($)
                     'headerOther' => [
@@ -105,11 +68,6 @@ class GoodsList extends \common\libs\dataList\DataList implements DataListInterf
                     'value' => function ($row) {
                         return Tool::formatPrice($row['SELL_PRICE_STANDARD']);
                     },
-                    'valueOther' => function ($row) {
-                        return [
-                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
-                        ];
-                    },
                 ],
                 'PRICE_PV' => [
                     'header' => \Yii::t('ctx', 'shopListProductsBv'), // 产品BV
@@ -119,11 +77,6 @@ class GoodsList extends \common\libs\dataList\DataList implements DataListInterf
                     'value' => function ($row) {
                         return Tool::formatPrice($row['PRICE_PV']);
                     },
-                    'valueOther' => function ($row) {
-                        return [
-                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
-                        ];
-                    },
                 ],
                 'STORE_NUMS' => [
                     'header' => \Yii::t('ctx', 'shopListInventory'), // 库存
@@ -132,23 +85,29 @@ class GoodsList extends \common\libs\dataList\DataList implements DataListInterf
                     ],
                 ],
                 'STATUS' => [
-                    'header' => \Yii::t('ctx', 'shopListStatus'), // 状态
+                    'header' => \Yii::t('ctx', 'shopListStatus'), // 产品BV
+                    'headerOther' => [
+                        'width' => '120',
+                    ],
+                    'value' => function ($row) {
+                        return $row['STATUS'] == 1 ? \Yii::t('ctx', 'shopListOnSale') : \Yii::t('ctx', 'shopListSoldOut');
+                    },
+                    'valueOther' => function ($row) {
+                        $tag = ($row['STATUS'] == 1) ? 'success' : 'danger';
+                        return [
+                            'tag' => ['type' => $tag, 'size' => 'small', 'class' => 'no-border']
+                        ];
+                    },
+                ],
+                'AUTO_MAINTENANCE' => [
+                    'header' => \Yii::t('ctx', 'shopListAutoMaintenance'),
                     'value' => function($row) {
-                        return $row['STATUS'] == 1 ? \Yii::t('ctx', 'shopListOnSale') : \Yii::t('ctx', 'shopListSoldOut'); //已上架:已下架
+                        return $row['AUTO_MAINTENANCE'] == 1 ? \Yii::t('ctx', 'yes') : \Yii::t('ctx', 'no');
                     },
                     'headerOther' => [
                         'width' => '110',
                     ],
                 ],
-                'UPDATED_AT' => [
-                    'header' => \Yii::t('ctx', 'shopListUpdatedAt'), // 更新时间
-                    'value' => function ($row) {
-                        return (new DateTime([
-                            'value' => $row['UPDATED_AT'],
-                        ]))->result();
-                    },
-                    'headerOther' => ['width' => '190'],
-                ],
             ];
         }
         return $this->columns;
@@ -169,8 +128,6 @@ class GoodsList extends \common\libs\dataList\DataList implements DataListInterf
                     'selectData' => [
                         ['id' => 1, 'name' => \Yii::t('ctx', 'shopList1stPurchase')], 
                         ['id' => 2, 'name' => \Yii::t('ctx', 'shopListRepeatPurchase')], 
-//                        ['id' => 3, 'name' => \Yii::t('ctx', 'shopListEntryArea')],
-//                        ['id' => 4, 'name' => \Yii::t('ctx', 'shopListResellingArea')]
                     ]
                 ],
                 'STATUS'=> [
@@ -186,8 +143,6 @@ class GoodsList extends \common\libs\dataList\DataList implements DataListInterf
                 'CATEGORY_TYPE' => [
                     'name' => \Yii::t('ctx', 'shopListProductCategory'), 
                     'other'=> 'select', 
-                    // 翻译无法使用const,改成其他方式
-                    // 'selectData'=> ShopGoods::CATEGORY_TYPE
                     'selectData'=> $this->getCategoryType()
                 ], // 商品分类
             ];

+ 11 - 10
backendApi/modules/v1/models/lists/shop/OrderList.php

@@ -37,7 +37,7 @@ class OrderList extends \common\libs\dataList\DataList implements DataListInterf
         $orderQuery = Order::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,OG.STANDARD_PRICE,CS.NAME AS COUNTRY,CY.CODE AS CURRENCY, DO.DEC_ID AS ORDER_DEC_ID')
+            ->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,OG.STANDARD_PRICE,CS.NAME AS COUNTRY,CY.CODE AS CURRENCY, O.DEC_USER_ID AS ORDER_DEC_ID')
             ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
             ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
             ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
@@ -52,7 +52,7 @@ class OrderList extends \common\libs\dataList\DataList implements DataListInterf
         $orderStandardQuery = ApproachOrder::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,OG.STANDARD_PRICE,CS.NAME AS COUNTRY,CY.CODE AS CURRENCY, DO.DEC_ID AS ORDER_DEC_ID')
+            ->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,OG.STANDARD_PRICE,CS.NAME AS COUNTRY,CY.CODE AS CURRENCY, O.DEC_USER_ID AS ORDER_DEC_ID')
             ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
             ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
             ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
@@ -87,7 +87,8 @@ class OrderList extends \common\libs\dataList\DataList implements DataListInterf
                     $this->listData['list'][$key]['DEC_USER_NAME'] = Info::getUserNameByUserId($value['DEC_ID']);
                 }
             } else {
-                $this->listData['list'][$key]['DEC_USER_NAME'] = Info::getUserNameByUserId($value['ORDER_DEC_ID']);
+//                $this->listData['list'][$key]['DEC_USER_NAME'] = Info::getUserNameByUserId($value['ORDER_DEC_ID']);
+                $this->listData['list'][$key]['DEC_USER_NAME'] = $value['ORDER_DEC_ID'];
             }
 
             $CREATE_USER_ID = Info::getUserIdByUserName($value['CREATE_USER']);
@@ -377,10 +378,10 @@ class OrderList extends \common\libs\dataList\DataList implements DataListInterf
                        return $this->getDeliveryStatus()[$row['DELIVERY_STATUS']]['label'] ?? '';
                     },
                 ],
-                'IS_AUTO' => [
-                    'header' => \Yii::t('ctx', 'shopOrderListIsAuto'), // 是否自动
+                'AUTO_MAINTENANCE' => [
+                    'header' => \Yii::t('ctx', 'shopListAutoMaintenance'),
                     'value' => function ($row) {
-                        return $row['IS_AUTO'] == 1 ? \Yii::t('ctx', 'shopOrderListIsAutoYes') : \Yii::t('ctx', 'shopOrderListIsAutoNo');
+                        return $row['AUTO_MAINTENANCE'] == 1 ? \Yii::t('ctx', 'yes') : \Yii::t('ctx', 'no');
                     },
                 ],
             ];
@@ -423,12 +424,12 @@ class OrderList extends \common\libs\dataList\DataList implements DataListInterf
                         ['id' => $this->getOrderStatus()['failPaid']['value'], 'name' => $this->getOrderStatus()['failPaid']['label']]
                     ]
                 ],
-                'IS_AUTO' => [
-                    'name'=>\Yii::t('ctx', 'shopOrderListIsAuto'),
+                'AUTO_MAINTENANCE' => [
+                    'name'=>\Yii::t('ctx', 'shopListAutoMaintenance'),
                     'other'=> 'select',
                     'selectData'=> [
-                        ['id'=>1, 'name'=>\Yii::t('ctx', 'shopOrderListIsAutoYes')],
-                        ['id'=>0, 'name'=>\Yii::t('ctx', 'shopOrderListIsAutoNo')],
+                        ['id'=>1, 'name'=>\Yii::t('ctx', 'yes')],
+                        ['id'=>0, 'name'=>\Yii::t('ctx', 'no')],
                     ]
                 ]
             ];

+ 6 - 1
backendApi/modules/v1/models/lists/shop/OrderPeriodAdjustList.php

@@ -2,6 +2,7 @@
 namespace backendApi\modules\v1\models\lists\shop;
 
 use common\libs\dataList\DataListInterface;
+use common\models\Countries;
 use common\models\Order;
 use common\models\OrderPeriodAdjust;
 use common\libs\dataList\column\DateTime;
@@ -23,11 +24,12 @@ class OrderPeriodAdjustList extends \common\libs\dataList\DataList implements Da
     public function dataHandle()
     {
         $this->listData = OrderPeriodAdjust::lists($this->condition, $this->params, [
-            'select' => 'P.*,O.ORDER_TYPE',
+            'select' => 'P.*,O.ORDER_TYPE,O.COUNTRY_ID,C.NAME AS COUNTRY_NAME',
             'orderBy' => 'P.CREATED_AT DESC, P.ID DESC',
             'from' => OrderPeriodAdjust::tableName() . ' AS P',
             'join' => [
                 ['LEFT JOIN', Order::tableName() . ' AS O', 'P.ORDER_SN=O.SN'],
+                ['LEFT JOIN', Countries::tableName() . ' AS C', 'O.COUNTRY_ID=C.ID'],
             ],
             'page' => $this->page,
             'pageSize' => $this->pageSize,
@@ -51,6 +53,9 @@ class OrderPeriodAdjustList extends \common\libs\dataList\DataList implements Da
                         return $row['ORDER_TYPE'] == 'ZC' ? Yii::t('ctx', 'shopOrderListOrderTypeZc') : Yii::t('ctx', 'shopOrderListOrderTypeFx');
                     },
                 ],
+                'COUNTRY_NAME' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'ORIGIN_PERIOD' => [
                     'header' => Yii::t('ctx', 'beforeAdjustmentPcNo'),
                 ],

+ 7 - 2
backendApi/modules/v1/models/lists/user/ChangeHighestEmpLevelList.php

@@ -4,6 +4,7 @@ namespace backendApi\modules\v1\models\lists\user;
 use backendApi\modules\v1\models\Admin;
 use common\helpers\Cache;
 use common\libs\dataList\DataListInterface;
+use common\models\Countries;
 use common\models\HighestEmpLevelLog;
 use common\models\User;
 use common\libs\dataList\column\DateTime;
@@ -25,12 +26,13 @@ class ChangeHighestEmpLevelList extends \common\libs\dataList\DataList implement
     public function dataHandle()
     {
         $this->listData = HighestEmpLevelLog::lists($this->condition, $this->params, [
-            'select' => 'LL.*, CU.USER_NAME, ADM.ADMIN_NAME',
+            'select' => 'LL.*, CU.USER_NAME, ADM.ADMIN_NAME, C.NAME AS COUNTRY',
             'orderBy' => 'LL.CREATED_AT DESC, LL.ID DESC',
             'from' => HighestEmpLevelLog::tableName() . ' AS LL',
             'join' => [
                 ['LEFT JOIN', Admin::tableName() . ' AS ADM', 'LL.ADMIN_ID=ADM.ID'],
-                ['LEFT JOIN', User::tableName() . ' AS CU', 'LL.USER_ID=CU.ID'],
+                ['INNER JOIN', User::tableName() . ' AS CU', 'LL.USER_ID=CU.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'CU.COUNTRY_ID=C.ID'],
             ],
             'page' => $this->page,
             'pageSize' => $this->pageSize,
@@ -50,6 +52,9 @@ class ChangeHighestEmpLevelList extends \common\libs\dataList\DataList implement
                 'USER_NAME' => [
                     'header' => Yii::t('ctx', 'memberCode'),
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'FROM_HIGHEST_EMP_LV_NAME' => [
                     'header' => Yii::t('ctx', 'levelBeforeModification'),
                     'value' => function($row) use($empLevelConfig) {

+ 7 - 3
backendApi/modules/v1/models/lists/user/DecLevelList.php

@@ -4,6 +4,7 @@ namespace backendApi\modules\v1\models\lists\user;
 use backendApi\modules\v1\models\Admin;
 use common\helpers\Cache;
 use common\libs\dataList\DataListInterface;
+use common\models\Countries;
 use common\models\DecLevelLog;
 use common\models\User;
 use common\models\UserInfo;
@@ -27,13 +28,13 @@ class DecLevelList extends \common\libs\dataList\DataList implements DataListInt
     public function dataHandle()
     {
         $this->listData = DecLevelLog::lists($this->condition, $this->params, [
-            'select' => 'LL.*,
-                CU.USER_NAME,ADM.ADMIN_NAME',
+            'select' => 'LL.*, CU.USER_NAME, ADM.ADMIN_NAME, C.NAME AS COUNTRY',
             'orderBy' => 'LL.CREATED_AT DESC, LL.ID DESC',
             'from' => DecLevelLog::tableName() . ' AS LL',
             'join' => [
                 ['LEFT JOIN', Admin::tableName() . ' AS ADM', 'LL.ADMIN_ID=ADM.ID'],
-                ['LEFT JOIN', User::tableName() . ' AS CU', 'LL.USER_ID=CU.ID'],
+                ['INNER JOIN', User::tableName() . ' AS CU', 'LL.USER_ID=CU.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'CU.COUNTRY_ID=C.ID'],
             ],
             'page' => $this->page,
             'pageSize' => $this->pageSize,
@@ -54,6 +55,9 @@ class DecLevelList extends \common\libs\dataList\DataList implements DataListInt
                     'header' => Yii::t('ctx', 'memberCode'),
                     'headerOther' => ['minWidth' => '120'],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'FROM_DEC_LV_NAME' => [
                     'header' => Yii::t('ctx', 'levelBeforeModification'),
                     'headerOther' => ['minWidth' => '110'],

+ 7 - 2
backendApi/modules/v1/models/lists/user/MoveList.php

@@ -6,6 +6,7 @@ use common\helpers\Cache;
 use common\helpers\http\BackendToFrontendApi;
 use common\helpers\user\Info;
 use common\libs\dataList\DataListInterface;
+use common\models\Countries;
 use common\models\DecRole;
 use common\models\OpenBank;
 use common\models\Region;
@@ -36,15 +37,16 @@ class MoveList extends \common\libs\dataList\DataList implements DataListInterfa
         $this->listData = User::lists($this->condition, $this->params, [
             'select' => 'UM.*,
                 CU.USER_NAME MOVE_USER_NAME,CU.REAL_NAME MOVE_REAL_NAME,FUI.USER_NAME FROM_USER_NAME,TUI.USER_NAME TO_USER_NAME,ADMC.ADMIN_NAME MOVE_ADMIN_NAME,ADMU.ADMIN_NAME AUDIT_ADMIN_NAME
-                ',
+                , C.NAME AS COUNTRY',
             'orderBy' => 'UM.CREATED_AT DESC, UM.ID DESC',
             'from' => UserMove::tableName() . ' AS UM',
             'join' => [
-                ['LEFT JOIN', User::tableName() . ' AS CU', 'UM.USER_ID=CU.ID'],
+                ['INNER JOIN', User::tableName() . ' AS CU', 'UM.USER_ID=CU.ID'],
                 ['LEFT JOIN', UserInfo::tableName() . ' AS FUI', 'UM.FROM_UID=FUI.USER_ID'],
                 ['LEFT JOIN', UserInfo::tableName() . ' AS TUI', 'UM.TO_UID=TUI.USER_ID'],
                 ['LEFT JOIN', Admin::tableName() . ' AS ADMC', 'UM.MOVE_ADMIN_ID=ADMC.ID'],
                 ['LEFT JOIN', Admin::tableName() . ' AS ADMU', 'UM.AUDIT_ADMIN_ID=ADMU.ID'],
+                ['INNER JOIN', Countries::tableName() . ' AS C', 'CU.COUNTRY_ID=C.ID'],
             ],
             'page' => $this->page,
             'pageSize' => $this->pageSize,
@@ -71,6 +73,9 @@ class MoveList extends \common\libs\dataList\DataList implements DataListInterfa
                         'tag'=>['type'=>'success', 'size' => 'small', 'class'=>'no-border']
                     ],
                 ],
+                'COUNTRY' => [
+                    'header' => Yii::t('ctx', 'country'),
+                ],
                 'FROM_USER_NAME' => [
                     'header' => Yii::t('ctx', 'uperCodeBeforeMoving'),
                     'headerOther' => ['width' => '120'],

BIN
backendEle/static/src/img/ngds-logo.jpg


+ 2 - 10
common/config/main.php

@@ -55,10 +55,8 @@ return [
         'mailer' => [
             'class' => 'yii\swiftmailer\Mailer',
             'viewPath' => '@common/mail',
-            // send all mails to a file by default. You have to set
-            // 'useFileTransport' to false and configure a transport
-            // for the mailer to send real emails.
-            'useFileTransport' => true, // true(缓存到文件中) false(发送邮件)
+            'useFileTransport' => false,
+            'enableSwiftMailerLogging' => true,
             'transport' => [
                 'class' => 'Swift_SmtpTransport',
                 'host' => 'mail.authsmtp.com',
@@ -66,12 +64,6 @@ return [
                 'username' => 'ac71555',
                 'password' => 'I1j-MKi-fJ8-nHb',
                 'encryption' => 'TLS',
-
-//                'host' => 'smtp.163.com',
-//                'port' => 465,
-//                'username' => '18511880790@163.com',
-//                'password' => 'YOUSSWQHISDSWPVB',
-//                'encryption' => 'SSL',
             ],
         ],
         'swooleAsyncTimer' => [

+ 10 - 10
common/helpers/Email.php

@@ -10,26 +10,26 @@ class Email
      * @param string $email
      * @param string $userName
      * @param string $password
+     * @return false|void
      */
     public static function sendRegistrationEmail(string $email, string $userName, string $password)
     {
-        $subject = 'Elken Welcome You.';
-        // $str = "<p>恭喜!  恭喜您成功注册到Elken Global系统和家庭。  我们致力于打造你来打造他人  使用下面提供的链接登录您的后台办公室   用户名=".$userName." 密码=".$password."  我们建议您将密码更改为您容易记住的密码。  如需进一步查询,请随时联系+23480 3413 0554  我们致力于确保您成功。  再次恭喜!</p>";
-        $str = "
-            <p>CONGRATULATIONS!</p>
-            <p>Congratulations on your successful registration into Elken Global system and family.  We are committed to building you to build others  Login to your back office using the link provided below  <a href='https://ngds.elken.com/#/login'>Member Management System</a>   Username = ".$userName." Password = ".$password."</p>  
-<p>We recommend that you change your password to what you will easily remember.  For further inquiries do not hesitate to contact +23480 3413 0554  We are committed to ensuring that you succeed.  </p>
-            <p>Once again congratulations!</p>
-        ";
-        $message = \Yii::t('app', $str);
+        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
+            return false;
+        }
+
+        $subject = \Yii::t('app', 'decRegistrationEmailSubject', []);
+        $message = \Yii::t('app', 'decRegistrationEmailContent', ['userName' => $userName, 'passWord' => $password]);
 
         $mailer = Yii::$app->mailer;
         $mailer->useFileTransport = false;
-        $mailer->compose()
+        $response = $mailer->compose()
             ->setFrom('eshop-noreply@elken.com')
             ->setTo($email)
             ->setSubject($subject)
             ->setHtmlBody($message)
             ->send();
+
+        LoggerTool::debug('sendRegistrationEmail' . sprintf('sendRegistrationEmail: %s', json_encode([$email, $userName, $password, $response])));
     }
 }

+ 11 - 0
common/helpers/PayStack.php

@@ -20,6 +20,17 @@ class PayStack
     {
         $secretKey = self::getSecretKey();
 
+        LoggerTool::info('env: ' . YII_ENV);
+
+        if (YII_ENV != YII_ENV_PROD) {
+            return [
+                'status' => true,
+                'data' => [
+                    'amount' => $amount
+                ]
+            ];
+        }
+
         try {
             $url = "https://api.paystack.co/transaction/initialize";
             $fields = [

+ 4 - 3
common/helpers/user/Info.php

@@ -344,10 +344,11 @@ class Info {
                 $netParentBaseInfo = self::baseInfo($baseInfo['CON_UID']);
                 $networkParent = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId]);
                 //$baseInfo['CON_UID'] = $baseInfo['CON_UID'];
-                $baseInfo['CON_USER_NAME'] = $netParentBaseInfo['USER_NAME'];
-                $baseInfo['CON_REAL_NAME'] = $netParentBaseInfo['REAL_NAME'];
-                $baseInfo['LOCATION'] = $networkParent['RELATIVE_LOCATION'];
+                $baseInfo['CON_USER_NAME'] = $netParentBaseInfo['USER_NAME'] ?? '';
+                $baseInfo['CON_REAL_NAME'] = $netParentBaseInfo['REAL_NAME'] ?? '';
+                $baseInfo['LOCATION'] = $networkParent['RELATIVE_LOCATION'] ?? 1;
             }
+
             if (isset($baseInfo['REC_UID']) && $baseInfo['REC_UID']) {
                 // 推荐网上级
                 //$relationParentUserInfo = UserRelation::getFirstParentUserInfo($userId);

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

@@ -308,7 +308,7 @@ class BaseExport extends Component {
         $orderQuery = Order::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,OG.STANDARD_PRICE')
+            ->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,OG.STANDARD_PRICE')
             ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
             ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
             ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
@@ -320,7 +320,7 @@ class BaseExport extends Component {
         $orderStandardQuery = ApproachOrder::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,OG.STANDARD_PRICE')
+            ->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,OG.STANDARD_PRICE')
             ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
             ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
             ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
@@ -335,11 +335,10 @@ class BaseExport extends Component {
             foreach($lists as $columnData) {
                 $CREATE_USER_ID = Info::getUserIdByUserName($columnData['CREATE_USER']);
                 $createUserName = Info::getUserRealNameByUserId($CREATE_USER_ID);
-                $decUserName = Info::getUserNameByUserId($columnData['DEC_ID']);
 
                 $columnAccept = [
                     'USER_NAME' => $columnData['USER_NAME'],
-                    'DEC_USER_NAME' => $decUserName,
+                    'DEC_USER_NAME' => $columnData['DEC_USER_ID'],
                     'CREATE_USER' => $columnData['CREATE_USER'],
                     'CREATE_USER_NAME' => $createUserName,
                     'SN' => $columnData['SN'],
@@ -583,7 +582,7 @@ class BaseExport extends Component {
             throw new Exception('无法获取需要的参数');
         }
         $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
-        $realFile = $path . __DS__ . $this->getFileName('.pdf');
+        $realFile = $this->mkdir($path) . __DS__ . $this->getFileName('.pdf');
 
         $this->completed = false;
         $this->getExportId();
@@ -831,10 +830,17 @@ ORDER;
             $pdf->AddPage();
             // 设置字体
             $pdf->SetFont('stsongstdlight', '', 10, '', true);
-            $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+            //        $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
+//        if (!file_exists($image_file)) {
+//            $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
+//        }
+            $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
+            $image = file_get_contents($image_file);
             $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
             $pdf->writeHTML($context);
-            $pdf->Output($realFile, 'F');
+
+            $result = $pdf->Output($realFile, 'F');
+            LoggerTool::debug(['result' => $result]);
 
             $this->_updateFirst($realFile, 1);
         }
@@ -1105,7 +1111,12 @@ ORDER;
             // 设置字体
             $pdf->SetFont('stsongstdlight', '', 10, '', true);
             $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
-            $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+            //        $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
+//        if (!file_exists($image_file)) {
+//            $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
+//        }
+            $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
+            $image = file_get_contents($image_file);
             $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
             $pdf->writeHTML($context);
             $pdf->Output($realFile, 'F');
@@ -1501,7 +1512,12 @@ ORDER;
             $pdf->AddPage();
             // 设置字体
             $pdf->SetFont('stsongstdlight', '', 10, '', true);
-            $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+            //        $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
+//        if (!file_exists($image_file)) {
+//            $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
+//        }
+            $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
+            $image = file_get_contents($image_file);
             $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
             $pdf->writeHTML($context);
             $pdf->Output($realFile, 'F');

+ 15 - 1
common/messages/en-US/app.php

@@ -33,6 +33,8 @@ return [
     'instalmentGoodsNoError' => 'Products No. error',
     'instalmentOrderInProcess' => '分期商品订单未完成',
     'productsDoesSoldOut' => 'Products has sold out!',
+    'productsDoesNotAmp' => 'Products does not Auto Maintenance!',
+    'ampOrderSubStandard' => 'Minimum {ampBv} amp BV required. Please meet that criteria to proceed with the purchase.',
     'cashDoesNotAdequate' => 'Insufficient balance, unable to make the payment.',
     'userPerformanceDoesNotAdequate' => 'Performance bonus, unable to make the payment.',
     'exchangePointDoesNotAdequate' => '兑换积分不足,无法购买商品',
@@ -57,6 +59,7 @@ return [
     'cityName' => 'City Name',
     'detailAddress' => 'Address',
     'shippingAddress' => 'shipping Address',
+    'amp' => 'Auto Maintenance',
 
     'orderDoesNotExist' => 'the order does not exist',
     'orderHasBeenCancelCanNotDeliver ' => '订单已取消不能发货',
@@ -173,6 +176,7 @@ return [
     'isModifyPassword' => 'IS_MODIFY_PASSWORD',
     'isStudio' => 'IS_STUDIO',
     'email' => 'EMAIL',
+    'invalidEmail' => 'Invalid Email',
 
     'fillingUpOfADeficit' => 'filling up of a deficit',
     'fullPayment' => 'full payment',
@@ -224,7 +228,17 @@ return [
     'dataFormatError' => 'Data format error',
     'decUserNameDoesNotExist' => '请输入报单中心编号',
     'decUserNameIsWrong' => '报单中心编号输入错误',
-
+    'decRegistrationEmailSubject' => 'Elken Welcome You.',
+    'decRegistrationEmailContent' => "
+        <p>Welcome to Elken Global!</p>
+        <p>Congratulations on successfully joining the Elken family! We are committed to empowering you to grow and succeed.</p>  
+        <p>Access your back office here: <a href='https://meads.elken.com'>https://ngds.elken.com</a></p>
+        <p>Username: [{userName}]</p>
+        <p>Password: {passWord} (Please change it for security reasons.)</p>
+        <p>To kickstart your success journey, explore essential resources, videos, and guides here: <a href='https://bit.ly/ElkenWelcomeKit'>https://bit.ly/ElkenWelcomeKit</a></p>
+        <p>For any inquiries, reach out to us at +23480 3413 0554. We are here to support you every step of the way.</p>
+        <p>Welcome aboard, and best wishes for your success!</p>
+    ",
 
 
     # 奖金

+ 2 - 0
common/messages/en-US/ctx.php

@@ -212,6 +212,7 @@ return [
     'shopListTax' => 'Tax(₦)',
     'shopListInventory' => 'Inventory',
     'shopListStatus' => 'Status',
+    'shopListAutoMaintenance' => 'AMP',
     'shopListOnSale' => 'On sale',
     'shopListSoldOut' => 'Sold out',
     'shopListUpdatedAt' => 'Update Time',
@@ -797,6 +798,7 @@ return [
     'dbConfigWithdrawFee' => '提现手续费',
     'dbConfigWithdrawFreezeDays' => '提现预付款天数',
     'dbConfigReportAlarmOpen' => '是否开启预警信息推送',
+    'dbConfigAmpBVCondition' => 'AMP订单最低限制',
 
     # 【参数】
     # 钱包类型

+ 15 - 2
common/messages/zh-CN/app.php

@@ -33,6 +33,8 @@ return [
     'instalmentGoodsNoError' => '分期商品的期数错误',
     'instalmentOrderInProcess' => '分期商品订单未完成',
     'productsDoesSoldOut' => '商品已下架',
+    'productsDoesNotAmp' => '非AMP商品!',
+    'ampOrderSubStandard' => 'AMP订单最少需要 {ampBv} BV. 请满足该标准以继续购买.',
     'cashDoesNotAdequate' => '余额不足,无法购买商品',
     'userPerformanceDoesNotAdequate' => '绩效奖金不足,无法购买商品',
     'exchangePointDoesNotAdequate' => '兑换积分不足,无法购买商品',
@@ -173,8 +175,8 @@ return [
     'isModifyPassword' => '是否修改密码',
     'isStudio' => '是否是工作室',
     'email' => '电子邮箱',
-
-
+    'amp' => 'Auto Maintenance',
+    'invalidEmail' => '电子邮箱无效',
 
     'fillingUpOfADeficit' => '补差额',
     'fullPayment' => '全额',
@@ -230,6 +232,17 @@ return [
     'currencyDoesNotExist' => '未设置汇率',
     'countryDoesNotSelect' => '未选择国家',
     'transferMemberDoesNotSame' => '转账会员非本国会员',
+    'decRegistrationEmailSubject' => '欢迎来到Elken Global!',
+    'decRegistrationEmailContent' => "
+        <p>欢迎来到Elken Global!</p>
+        <p>祝贺您成功加入Elken大家庭!我们致力于赋予您成长和成功的能力。</p>  
+        <p>访问您的后台: <a href='https://meads.elken.com'>https://ngds.elken.com</a></p>
+        <p>用户名: [{userName}]</p>
+        <p>密码: {passWord} (出于安全原因,请更改密码。)</p>
+        <p>要启动您的成功之旅,请在此处浏览必要的资源、视频和指南: <a href='https://bit.ly/ElkenWelcomeKit'>https://bit.ly/ElkenWelcomeKit</a></p>
+        <p>如有任何疑问,请致电+23480 3413 0554联系我们。我们在这里帮助您完成每一步。</p>
+        <p>欢迎加入,祝你成功!</p>
+    ",
 
     # 奖金
     'memberBonus' => '收益积分',

+ 2 - 0
common/messages/zh-CN/ctx.php

@@ -202,6 +202,7 @@ return [
     'shopListTax' => '税额(₦)',
     'shopListInventory' => '库存',
     'shopListStatus' => '状态',
+    'shopListAutoMaintenance' => 'AMP',
     'shopListOnSale' => '已上架',
     'shopListSoldOut' => '已下架',
     'shopListUpdatedAt' => '更新时间',
@@ -801,6 +802,7 @@ return [
     'dbConfigWithdrawFee' => '提现手续费',
     'dbConfigWithdrawFreezeDays' => '提现预付款天数',
     'dbConfigReportAlarmOpen' => '是否开启预警信息推送',
+    'dbConfigAmpBVCondition' => 'AMP订单最低限制',
 
     # 【参数】
     # 钱包类型

+ 49 - 0
common/models/AmpPeriod.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace common\models;
+
+/**
+ * This is the model class for table "{{%AMP_PERIOD}}".
+ *
+ * @property string ID
+ * @property string USER_ID 用户ID
+ * @property string ORDER_SN 订单号
+ * @property int    PERIOD_NUM 周期
+ * @property double BV BV
+ */
+class AmpPeriod extends \common\components\ActiveRecord
+{
+    /**
+     * @inheritdoc
+     */
+    public static function tableName()
+    {
+        return '{{%AMP_PERIOD}}';
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['USER_ID', 'ORDER_SN', 'PERIOD_NUM', 'BV'], 'required'],
+            [['PERIOD_NUM', 'BV'], 'number'],
+            [['ID'], 'unique'],
+        ];
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ID' => 'ID',
+            'USER_ID' => '用户ID',
+            'ORDER_SN' => '订单号',
+            'PERIOD_NUM' => '周期',
+            'BV' => 'BV',
+        ];
+    }
+}

+ 2 - 0
common/models/ApproachDecOrder.php

@@ -34,6 +34,7 @@ use Yii;
  * @property int $UPGRADE_TYPE 升级类型
  * @property string $ORI_LV 升级前级别
  * @property string $UPGRADE_LV 升级后级别
+ * @property int AUTO_MAINTENANCE AMP订单
  */
 class ApproachDecOrder extends \common\components\ActiveRecord
 {
@@ -92,6 +93,7 @@ class ApproachDecOrder extends \common\components\ActiveRecord
             'UPDATED_AT' => '更新时间',
             'IS_DEL' => '是否删除',
             'DELETED_AT' => '删除时间',
+            'AUTO_MAINTENANCE' => 'AMP订单',
         ];
     }
 }

+ 3 - 2
common/models/ApproachOrder.php

@@ -75,7 +75,7 @@ class ApproachOrder extends \common\components\ActiveRecord
         return [
             [['USER_ID',  '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'],
+            [['PAY_AT', 'DELIVERY_STATUS', 'DELIVERY_PERIOD', 'DELIVERY_AT', 'EXPRESS_TYPE', 'PERIOD_NUM', 'STATUS', 'PROVINCE', 'CITY', 'COUNTY', 'CREATED_AT', 'UPDATED_AT', 'IS_DELETE', 'DELETED_AT', 'AUTO_MAINTENANCE'], 'integer'],
             [['ID','SN', 'DEC_SN', 'USER_ID', 'ORDER_TRACK_NO','PAY_TYPE','DEC_USER_ID'], 'string', 'max' => 32],
             [['USER_NAME', 'TEL', 'CREATE_USER', 'UPDATER', 'WAREHOUSE'], 'string', 'max' => 16],
             [['ORDER_TYPE'], 'string', 'max' => 12],
@@ -83,7 +83,7 @@ class ApproachOrder extends \common\components\ActiveRecord
             [['FRONT_REMARK'], 'string', 'max' => 1000],
             [['REMARK', 'NOTE'], 'string', 'max' => 4000],
             [['CONSIGNEE'], 'string', 'max' => 120],
-            [['MOBILE'], 'string', 'max' => 11],
+            [['MOBILE'], 'string', 'max' => 15],
             [['ADDRESS'], 'string', 'max' => 255],
             [['SN'], 'unique'],
         ];
@@ -140,6 +140,7 @@ class ApproachOrder extends \common\components\ActiveRecord
             'EMAIL' => 'Email',
             'COUNTRY_ID' => '国家ID',
             'CURRENCY_ID' => '币种ID',
+            'AUTO_MAINTENANCE' => 'AMP'
         ];
     }
 

+ 7 - 2
common/models/ApproachReconsumeOrder.php

@@ -53,6 +53,10 @@ use Yii;
  * @property string $PAY_AMOUNT_STANDARD 支付价格
  * @property string $ORDER_AMOUNT_STANDARD 订单总价格($)
  * @property string $EXCHANGE_RATE 汇率
+ * @property string $COUNTRY_ID 国家ID
+ * @property int $CURRENCY_ID 币种ID
+ * @property int $AUTO_MAINTENANCE AMP订单
+ * @property string $DEC_USER_ID  会员编号
  */
 class ApproachReconsumeOrder extends \common\components\ActiveRecord
 {
@@ -80,7 +84,7 @@ class ApproachReconsumeOrder extends \common\components\ActiveRecord
             [['FRONT_REMARK'], 'string', 'max' => 1000],
             [['REMARK', 'NOTE'], 'string', 'max' => 4000],
             [['CONSIGNEE'], 'string', 'max' => 120],
-            [['MOBILE'], 'string', 'max' => 11],
+            [['MOBILE'], 'string', 'max' => 15],
             [['ADDRESS'], 'string', 'max' => 255],
             [['SN'], 'unique'],
         ];
@@ -133,7 +137,8 @@ class ApproachReconsumeOrder extends \common\components\ActiveRecord
             'IS_DELETE' => '是否删除',
             'DELETED_AT' => '删除时间',
             'WAREHOUSE' => '发货仓',
-            'EMAIL' => 'Email'
+            'EMAIL' => 'Email',
+            'AUTO_MAINTENANCE' => 'AMP',
         ];
     }
 

+ 20 - 0
common/models/Countries.php

@@ -103,6 +103,26 @@ class Countries extends \common\components\ActiveRecord
         return self::findOneAsArray('ID=:ID', [':ID' => $id]);
     }
 
+    /**
+     * 通过ID获取
+     * @param string $id
+     * @return string
+     */
+    public static function getNameById(string $id): string
+    {
+        return self::findOneAsArray('ID=:ID', [':ID' => $id])['NAME'];
+    }
+
+    /**
+     * 通过ID获取
+     * @param string $id
+     * @return string
+     */
+    public static function getCodeById(string $id): string
+    {
+        return self::findOneAsArray('ID=:ID', [':ID' => $id])['CODE'];
+    }
+
     /**
      * 通过ID查询币种.
      * @param string $id

+ 0 - 1
common/models/Currency.php

@@ -59,7 +59,6 @@ class Currency extends \common\components\ActiveRecord
     public static function getFromCache()
     {
         $data = Yii::$app->cache->get(Cache::CURRENCIES_KEY);
-        Yii::$app->cache->delete(Cache::CURRENCIES_KEY);
         if (!$data) {
             // 获取信息
             $data = self::getAllData();

+ 4 - 2
common/models/Order.php

@@ -56,6 +56,7 @@ use Yii;
  * @property string $NOTE 备注说明
  * @property string COUNTRY_ID 国家ID
  * @property int CURRENCY_ID 币种ID
+ * @property int AUTO_MAINTENANCE AMP订单
  */
 class Order extends \common\components\ActiveRecord
 {
@@ -75,7 +76,7 @@ class Order extends \common\components\ActiveRecord
         return [
             [['USER_ID', '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'],
+            [['PAY_AT', 'DELIVERY_STATUS', 'DELIVERY_PERIOD', 'DELIVERY_AT', 'EXPRESS_TYPE', 'PERIOD_NUM', 'STATUS', 'PROVINCE', /*'CITY', 'COUNTY', */'CREATED_AT', 'UPDATED_AT', 'IS_DELETE', 'DELETED_AT', 'AUTO_MAINTENANCE'], 'integer'],
             [['ID','SN', 'DEC_SN', 'USER_ID', 'ORDER_TRACK_NO','PAY_TYPE','DEC_USER_ID'], 'string', 'max' => 32],
             [['USER_NAME', 'TEL', 'CREATE_USER', 'UPDATER', 'WAREHOUSE'], 'string', 'max' => 16],
             [['ORDER_TYPE'], 'string', 'max' => 12],
@@ -83,7 +84,7 @@ class Order extends \common\components\ActiveRecord
             [['FRONT_REMARK'], 'string', 'max' => 1000],
             [['REMARK', 'NOTE'], 'string', 'max' => 4000],
             [['CONSIGNEE'], 'string', 'max' => 120],
-            [['MOBILE'], 'string', 'max' => 11],
+            [['MOBILE'], 'string', 'max' => 15],
             [['ADDRESS'], 'string', 'max' => 255],
             [['SN'], 'unique'],
         ];
@@ -138,6 +139,7 @@ class Order extends \common\components\ActiveRecord
             'EMAIL' => 'Email',
             'COUNTRY_ID' => '国家ID',
             'CURRENCY_ID' => '币种ID',
+            'AUTO_MAINTENANCE' => 'AMP订单',
         ];
     }
     /*

+ 1 - 1
common/models/OrderDec.php

@@ -74,7 +74,7 @@ class OrderDec extends \common\components\ActiveRecord
             [['FRONT_REMARK'], 'string', 'max' => 1000],
             [['REMARK'], 'string', 'max' => 4000],
             [['CONSIGNEE'], 'string', 'max' => 120],
-            [['MOBILE'], 'string', 'max' => 11],
+            [['MOBILE'], 'string', 'max' => 15],
             [['ADDRESS'], 'string', 'max' => 255],
             [['SN'], 'unique'],
         ];

+ 1 - 1
common/models/OrderShop.php

@@ -74,7 +74,7 @@ class OrderShop extends \common\components\ActiveRecord
             [['FRONT_REMARK'], 'string', 'max' => 1000],
             [['REMARK'], 'string', 'max' => 4000],
             [['CONSIGNEE'], 'string', 'max' => 120],
-            [['MOBILE'], 'string', 'max' => 11],
+            [['MOBILE'], 'string', 'max' => 15],
             [['ADDRESS'], 'string', 'max' => 255],
             [['SN'], 'unique'],
         ];

+ 4 - 0
common/models/Period.php

@@ -4,6 +4,7 @@ namespace common\models;
 
 use common\helpers\bonus\Calc\CalcConsole;
 use common\helpers\Date;
+use common\helpers\LoggerTool;
 use common\helpers\Tool;
 use Yii;
 use yii\db\Exception;
@@ -520,6 +521,9 @@ class Period extends \common\components\ActiveRecord
     public function isCanCalc($periodNum = null) {
         // 没有挂网可以结算
         $period = $this->setPeriodNum($periodNum);
+
+        LoggerTool::notice([$period, $period['IS_SENT'], self::SEND_FINISH, ($period['IS_SENT'] == self::SEND_FINISH), $period['START_TIME'] > time()]);
+
         if ($period['IS_SENT'] == self::SEND_FINISH) {
             return false;
         }

+ 1 - 1
common/models/ReceiveAddress.php

@@ -45,7 +45,7 @@ class ReceiveAddress extends \common\components\ActiveRecord
             [['ID', 'USER_ID'], 'string', 'max' => 32],
             [['USER_NAME'], 'string', 'max' => 16],
             [['CONSIGNEE'], 'string', 'max' => 120],
-            [['MOBILE'], 'string', 'max' => 11],
+            [['MOBILE'], 'string', 'max' => 15],
             [['ADDRESS'], 'string', 'max' => 255],
             [['LGA_NAME'], 'string', 'max' => 50],
             [['CITY_NAME'], 'string', 'max' => 50],

+ 6 - 3
common/models/Region.php

@@ -92,7 +92,7 @@ class Region extends \common\components\ActiveRecord
      */
     public static function getFromCache(){
         $data = Yii::$app->cache->get(Cache::REGION_CONFIG_KEY);
-        Yii::$app->cache->delete(Cache::REGION_CONFIG_KEY);
+        $data = null;
         if(!$data){
             // 获取信息
             $data = self::getAllData();
@@ -133,10 +133,13 @@ class Region extends \common\components\ActiveRecord
     public static function getWarehouseByCode($regionCode){
         //'540000','710000','810000','820000'
         $ZoningArr = [
-            '01'=>['10100','10200','10300','10400','10500','10600','10700','10800','10900',
+            '01' => ['10100','10200','10300','10400','10500','10600','10700','10800','10900',
                 '11000','11100','11200','11300','11400','11500','11600','11700','11800',
                 '11900','12000','12100','12200','12300','12400','12500','12600','12700',
-                '12800','12900','13000','13100','13200','13300','13400','13500','13600','19900']
+                '12800','12900','13000','13100','13200','13300','13400','13500','13600','19900',
+
+                '10000', '10001', '10002', '10003', '10004', '10005', '10006',
+                ]
         ];
         $zoning = '';
         foreach ($ZoningArr as $key=>$val){

+ 4 - 2
common/models/ShopGoods.php

@@ -27,6 +27,7 @@ namespace common\models;
  * @property int $DELETED_AT 删除时间
  * @property int $STATUS 状态
  * @property string $SORT 排序
+ * @property int $AUTO_MAINTENANCE AMP
  */
 class ShopGoods extends \common\components\ActiveRecord
 {
@@ -115,8 +116,8 @@ class ShopGoods extends \common\components\ActiveRecord
     public function rules()
     {
         return [
-            [['SELL_DISCOUNT','GOODS_NAME', 'CATE_ID','GIFT_TYPE', 'GOODS_NO', 'PRICE_PV','STORE_NUMS', 'SELL_TYPE', 'CATEGORY_TYPE', 'SELL_PRICE_STANDARD'], 'required'],
-            [['STORE_NUMS'], 'integer'],
+            [['SELL_DISCOUNT','GOODS_NAME', 'CATE_ID','GIFT_TYPE', 'GOODS_NO', 'PRICE_PV','STORE_NUMS', 'SELL_TYPE', 'CATEGORY_TYPE', 'SELL_PRICE_STANDARD', 'AUTO_MAINTENANCE'], 'required'],
+            [['STORE_NUMS', 'AUTO_MAINTENANCE'], 'integer'],
             [['PRICE_PV','POINT', 'CATEGORY_TYPE' ,'SELL_PRICE_STANDARD'], 'number'],
             [['ID','CATE_ID', 'GOODS_NO','GIFT_TYPE'], 'string', 'max' => 32],
             [['UNIT'], 'string', 'max' => 16],
@@ -154,6 +155,7 @@ class ShopGoods extends \common\components\ActiveRecord
             'UPDATED_AT' => '更新时间',
             'DELETED_AT' => '更新时间',
             'SORT' => '排序',
+            'AUTO_MAINTENANCE' => 'AMP'
         ];
     }
 

+ 4 - 11
common/models/User.php

@@ -121,7 +121,7 @@ class User extends \common\components\ActiveRecord
             [['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],
+//            [['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],
@@ -241,16 +241,9 @@ class User extends \common\components\ActiveRecord
      * @param $userId
      * @return array|null|\yii\db\ActiveRecord
      */
-    public static function getBaseInfoFromRedis($userId){
-        //$userInfo = Yii::$app->redis->hget(Cache::USER_INFO_KEY, $userId);
-        $userInfo = '';
-        if(!$userInfo){
-            $userInfo = static::find()->select('ID,USER_NAME,NATION,COUNTRY_ID,LANGUAGE_ID,REAL_NAME,ID_CARD,ID_TYPE,MOBILE,ADDRESS,STATUS,DEC_LV,LAST_DEC_LV,EMP_LV,ELITE_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;
+    public static function getBaseInfoFromRedis($userId)
+    {
+        return static::find()->select('ID,USER_NAME,NATION,COUNTRY_ID,LANGUAGE_ID,REAL_NAME,ID_CARD,ID_TYPE,MOBILE,ADDRESS,STATUS,DEC_LV,LAST_DEC_LV,EMP_LV,ELITE_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();
     }
 
     /**

+ 1 - 1
common/models/UserRelation.php

@@ -280,7 +280,7 @@ class UserRelation extends \common\components\ActiveRecord
         $table = self::getTableNameFromPeriod($periodNum);
         $db = $table['db'];
         $tableName = $table['tableName'];
-        return $db->createCommand("SELECT USER_ID,PARENT_UID,TOP_DEEP FROM {$tableName} WHERE PARENT_UID=:PARENT_UID ORDER BY {$orderBy}")->bindValues([':PARENT_UID'=>$userId])->queryAll();
+        return $db->createCommand("SELECT USER_ID,PARENT_UID,TOP_DEEP FROM {$tableName} AS AT INNER JOIN AR_USER U ON AT.USER_ID = U.ID AND U.DELETED=0 WHERE PARENT_UID=:PARENT_UID ORDER BY {$orderBy}")->bindValues([':PARENT_UID'=>$userId])->queryAll();
     }
 
 

+ 759 - 0
common/models/forms/ApproachAutoMaintenanceOrderForm.php

@@ -0,0 +1,759 @@
+<?php
+namespace common\models\forms;
+
+use common\helpers\Cache;
+use common\helpers\Date;
+use common\components\Model;
+use common\helpers\Form;
+use common\helpers\Log;
+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\AmpPeriod;
+use common\models\ApproachDecOrder;
+use common\models\ApproachOrder;
+use common\models\ApproachReconsumeOrder;
+use common\models\ApproachOrderGoods;
+use common\models\BaUser;
+use common\models\Countries;
+use common\models\CurrencyConversions;
+use common\models\DealType;
+use common\models\DecLevelLog;
+use common\models\DecOrder;
+use common\models\FreeTemplate;
+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\ShopGoodsNature;
+use common\models\User;
+use common\models\UserNetwork;
+use common\models\Instalment;
+use Yii;
+use yii\base\Exception;
+class ApproachAutoMaintenanceOrderForm 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 $decUserName;
+    public $consignee;
+    public $acceptMobile;
+    public $province;
+    public $city;
+    public $county;
+    public $lgaName;
+    public $cityName;
+    public $autoMaintenance;
+    public $exchangeRate;
+    public $detailaddress;
+
+    private $_address;
+    private $_decAmount;
+    private $_decPv;
+    private $_realPv;
+    private $_freight;
+    private $_payAmount;
+    private $_orderGoods;
+    private $_standardAmount;
+    private $_decAmountStandard;
+
+    /**
+     * @var ApproachOrder
+     */
+    private $_model;
+
+    public function init() {
+        parent::init();
+        $this->adminOperateLogger = new AdminOperate([
+            'fetchClass' => ApproachOrder::class,
+        ]);
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function rules()
+    {
+        return [
+            [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email', 'decUserName'], 'trim'],
+            [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'detailaddress' ,'decUserName'], 'required'],
+            [['status'], 'isStatus'],
+            [['addressId'], 'isAddress'],
+            [['payType'], 'isPayType'],
+            [['payPassword'], 'validatePassword'],
+        ];
+    }
+
+    public function attributeLabels()
+    {
+        return [
+            'sn' => Yii::t('app', 'orderSn'),
+            'expressCompany' => Yii::t('app', 'expressCompany'),
+            'orderTrackNo' => Yii::t('app', 'orderTrackNo'),
+            'status' => Yii::t('app', 'state'),
+            'remark' => Yii::t('app', 'remark'),
+            'type' => Yii::t('app', 'orderType'),
+            'addressId' => Yii::t('app', 'shippingAddress'),
+            'payType' => Yii::t('app', 'payType'),
+            'goodsId' => Yii::t('app', 'productID'),
+            'goodsNum' => Yii::t('app', 'quantity'),
+            'userName' => Yii::t('app', 'repeatSalesMemberNo'),
+            'consignee' => Yii::t('app', 'consignee'),
+            'acceptMobile' => Yii::t('app', 'acceptMobile'),
+            'province' => Yii::t('app', 'province'),
+            'city' => Yii::t('app', 'city'),
+            'county' => Yii::t('app', 'county'),
+            'lgaName' =>Yii::t('app', 'lgaName'),
+            'cityName' => Yii::t('app', 'cityName'),
+            'detailaddress' => Yii::t('app', 'detailAddress'),
+            'email' => Yii::t('app', 'email'),
+            'decUserName' => Yii::t('app', 'decUserName'),
+        ];
+    }
+
+    /**
+     * 指定校验场景
+     * @return array
+     */
+    public function scenarios()
+    {
+        $parentScenarios =  parent::scenarios();
+        $customScenarios = [
+            // 管理员修改订单状态
+            'adminStatus' => ['sn', 'status'],
+            // 校验订单支付
+            'verifyPayStack' => ['sn', 'note', 'status'],
+            // 会员下单
+            'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
+            // 为会员复消
+            'autoMaintenanceOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress', 'decUserName'],
+        ];
+        return array_merge($parentScenarios, $customScenarios);
+    }
+
+    /**
+     * 校验之前
+     * @return bool
+     */
+    public function beforeValidate()
+    {
+        $parentValidate = parent::beforeValidate();
+        if ($this->sn) {
+            $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
+            if (!$this->_model){
+                $this->addError('sn', Yii::t('app', 'orderDoesNotExist'));
+                return false;
+            }
+        }
+
+        if ($this->scenario == 'verifyPayStack'){
+            if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
+                $this->addError('sn', Yii::t('app', 'payTypeError'));
+                return false;
+            }
+        }
+
+        return $parentValidate;
+    }
+
+    /**
+     * 判断收货地址是否存在
+     * @param $attribute
+     */
+    public function isAddress($attribute){
+        if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
+            $this->addError($attribute, Yii::t('app', 'shippingDoesNotExist'));
+        } else {
+            $this->_address = $receiveAddress;
+        }
+    }
+
+    /**
+     * 校验支付密码
+     * @param $attribute
+     * @param $params
+     */
+    public function validatePassword($attribute, $params) {
+        if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
+            $this->addError($attribute, Yii::t('app', 'paymentPasswordError'));
+        }
+    }
+
+    /**
+     * 判断支付方式
+     * @param $attribute
+     * @throws Exception
+     */
+    public function isPayType($attribute)
+    {
+        if ($this->payType != 'pay_stack'){
+            $this->addError($attribute, Yii::t('app', 'payTypeError'));
+            return;
+        }
+
+        // 一个订单只能包含一类商品
+        $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
+        if (!$goods) {
+            throw new Exception(Yii::t('app', 'orderCanNotContainMultipleProductCategories'));
+        }
+        $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
+        if (count($goodsCategoryType) > 1) {
+            $this->addError($attribute, Yii::t('app', 'orderCanNotHasMoreClassification'));
+            return;
+        }
+
+        // 购买方式
+        $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
+        if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
+            $this->addError($attribute, Yii::t('app', 'payTypeError'));
+            return;
+        }
+
+        // 所选支付方式必须是商品分类支持的类型
+        $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
+        // 商品类型
+        $currCategoryType = $goodsCategoryType[0];
+        if (!array_key_exists($currCategoryType, $categoryType)) {
+            $this->addError($attribute, Yii::t('app', 'shopGoodClassificationError'));
+            return;
+        }
+
+        $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
+        if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
+            $this->addError($attribute, Yii::t('app', 'payTypeError'));
+        }
+    }
+
+    /**
+     * 校验类型
+     * @param $attribute
+     */
+    public function isStatus($attribute){
+        if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
+            $this->addError($attribute, Yii::t('app', 'orderStatusTypeError'));
+            return ;
+        }
+        if ($this->scenario == 'adminStatus'){
+            if ($this->status == $this->_model['STATUS']) {
+                $this->addError($attribute, Yii::t('app', 'orderStatusDoesNotChange'));
+                return ;
+            }
+            if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
+                $this->addError($attribute, Yii::t('app', 'orderHasBeenLogisticsStatusDoesNotChangedUnpaid'));
+                return ;
+            }
+            elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
+                $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
+                return ;
+            }
+            elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
+                $this->addError($attribute, Yii::t('app', 'orderCanNotBeenChangedLogistics'));
+                return ;
+            }
+            elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
+                $this->addError($attribute, Yii::t('app', 'orderHasBeenInvalidCanNotProcess'));
+                return ;
+            }
+            elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
+                if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
+                    $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotCancel'));
+                    return ;
+                }
+                if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
+                    $this->addError($attribute, Yii::t('app', 'orderHasBeenDeletedCanNotCancel'));
+                    return ;
+                }
+            }
+            elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
+                if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
+                    $this->addError($attribute, Yii::t('app', 'orderHasBeenFinishedCanNotDelete'));
+                    return ;
+                }
+            }
+        }
+
+    }
+
+    /**
+     * 校验PayStack支付,更新订单状态.同步到正式订单.
+     * @throws Exception
+     */
+    public function verifyPayStack(): ?ApproachOrder
+    {
+        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(Yii::t('app', 'payAmountNotEqualOrderAmount')));
+        }
+
+        // 订单类型:userOrder(会员订单)、userUpgrade(会员升级)、userDec(会员报单)
+        $orderType = $this->note['metadata']['custom_fields'][1]['value'] ?? false;
+
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            // 更新准订单状态为已支付
+            $this->_model->STATUS = $this->status;
+            $this->_model->NOTE = json_encode($this->note);
+            $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
+            $this->_model->EMAIL = $this->note['email'];
+            if (!$this->_model->save()) {
+                throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
+            }
+            // 更新订单商品的支付Email
+            ApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+
+            // 同步准订单到正式订单
+            Order::insertOne($this->_model->toArray());
+            // 同步准订单商品到正式订单商品
+            $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+            foreach ($approachOrderGoods as &$approachOrderGood) {
+                $approachOrderGood['EMAIL'] = $this->email;
+            }
+            OrderGoods::batchInsert($approachOrderGoods);
+
+            // AMP订单
+            $order = Order::findOne($this->_model->ID);
+            if ($order['AUTO_MAINTENANCE'] == 1) {
+                $this->orderAutoMaintenance($order);
+            }
+
+            // 会员报单、BA升级
+            if (in_array($orderType, ['userDec', 'baUpgrade', 'userUpgrade'])) {
+                // 同步报单
+                $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+                if ($approachDecOrder) {
+                    unset($approachDecOrder['STATUS']);
+
+                    // 同步报单
+                    DecOrder::insertOne($approachDecOrder);
+
+                    // 修改会员锁定状态
+                    if (in_array($orderType, ['userDec', 'baUpgrade'])) {
+                        if (!User::updateAll(['STATUS' => 1], 'ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']])) {
+                            throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'changeUserStatusError')));
+                        }
+                    }
+                    // 修改BA会员升级状态
+                    if ($orderType === 'baUpgrade') {
+                        // 查询BA会员名
+                        $userInfo = User::findOneAsArray('ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']]);
+                        if (!BaUser::updateAll(['WHETHER_UPGRADE' => 1, 'BA_UPGRADE_AT' => time()], 'USER_NAME=:USER_NAME', [':USER_NAME' => $userInfo['USER_NAME']])) {
+                            throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'brandAmbassadorUpgradeError')));
+                        }
+                    }
+
+                    // 正式会员-升级单
+                    if ($orderType === 'userUpgrade') {
+                        // 会员升级 报单类型:2会员升级单
+                        if ($approachDecOrder['DETAIL_TYPE'] == 2) {
+                            // 为被升级人进行升级操作
+                            $decLevelLog = new DecLevelLog();
+                            $decLog = [
+                                'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
+                                'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
+                                'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
+                                'actionId' => $approachDecOrder['USER_ID'],
+                                'remark' => $approachDecOrder['REMARK'],
+                                'lvPv' => $this->_model->PV,
+                            ];
+                            $modifyDecLv = $decLevelLog->frontendChange($decLog);
+                            if (empty($modifyDecLv)) {
+                                $transaction->rollBack();
+                                throw new Exception(Yii::t('app', 'failedToUpgrade'));
+                            }
+                        }
+                    }
+
+                    // 删除中间表
+                    ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+                }
+            }
+
+            // 删除中间表
+            ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
+            ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
+
+            $transaction->commit();
+        } catch (Exception $e) {
+            $transaction->rollBack();
+            $this->addError('edit', $e->getFile() . '  ' . $e->getMessage());
+            return null;
+        }
+
+        return $this->_model;
+    }
+
+    /**
+     * AMP
+     * @throws Exception
+     * @throws \yii\db\Exception
+     */
+    public function autoMaintenanceSureOrder()
+    {
+        if(!$this->validate()){
+            return null;
+        }
+
+        $ids = $this->goodsId;
+        $totalAmount = 0;
+        $totalPv = 0;
+        $totalRealPv = 0;
+        $totalAmountStandard = 0;
+        $this->autoMaintenance = 1;
+
+        $goodsType = ShopGoods::getGoodType();
+        $hasInstalment = 0;
+        $userId = Info::getUserIdByUserName($this->userName);
+        $user = User::getEnCodeInfo($userId);
+
+        $decUserID = Info::getUserIdByUserName($this->decUserName);
+        $stockist_user = User::getEnCodeInfo($decUserID);
+        if(!$stockist_user || $stockist_user['IS_DEC'] != 1){
+            throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
+        }
+
+        // 报单中心汇率
+        $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $decCountry = Countries::getById($decCountryId);
+        $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
+        // 会员汇率
+        $country = Countries::getById($user['COUNTRY_ID']);
+        $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
+        // 判断是否是报单中心
+        $loginUser = User::getEnCodeInfo(\Yii::$app->user->id);
+        if ($loginUser['IS_DEC'] == 1){
+            if($decUserID != \Yii::$app->user->id){
+                throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
+            }
+        }
+
+        foreach ($this->goodsNum as $k => $v) {
+            if ($v) {
+                $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1 AND AUTO_MAINTENANCE=1',[':ID'=> $ids[$k]]);
+                if (!$goods) {
+                    throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                }
+
+                $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
+                    [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
+                if (!$goodsNature) {
+                    throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                }
+
+                $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
+
+                if($goods['STORE_NUMS']>0){
+                    if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
+                        $discount = $goodsType[$goods['TYPE']]['discount'];
+                        $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
+                        $realPv = $goods['PRICE_PV'] * $discount/100;
+                        $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
+                    } else {
+                        $discount = $goods['SELL_DISCOUNT'];
+                        $realPrice = $goodsNature['SELL_PRICE'] * $discount;
+                        $realPv = $goods['PRICE_PV'] * $discount;
+                        $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
+                    }
+
+                    $currentPv = $goods['PRICE_PV'];
+                    $totalPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
+                    $totalRealPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
+
+                    $totalAmount += $realPrice * intval($v);
+                    $totalAmountStandard += $realPriceStandard * intval($v);
+
+                    $this->_orderGoods[] = [
+                        'GOODS_ID' => $goods['ID'],
+                        'PRICE' => $goodsNature['SELL_PRICE'],
+                        'PV' => $currentPv,
+                        'REAL_PRICE' => $realPrice,
+                        'REAL_PV' => $realPv,
+                        'REMAIN_PV' => 0,
+                        'POINT' => $goods['POINT'],
+                        'BUY_NUMS' => intval($v),
+                        'SKU_CODE' => $goods['GOODS_NO'],
+                        'GOODS_TITLE' => $goods['GOODS_NAME'],
+                        'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
+                        'PAY_TYPE' => $this->payType,
+                        'EMAIL' => $this->email,
+                        'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
+                        'REAL_STANDARD_PRICE' => $realPriceStandard,
+                        'EXCHANGE_RATE' => $currencyRate,
+                        'TAX_RATE' => $goodsNature['TAX_RATE'],
+                    ];
+                }
+
+                if ($goods['INSTALMENT']>0) {
+                    if ($v > 1) {
+                        throw new Exception(Yii::t('app', 'allowOnlyOne'));
+                    }
+
+                    $userStage = Instalment::getStage($userId);
+                    $userInstalmentInfo = Instalment::getInfo($userId);
+
+                    $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
+                    if (intval($goods['INSTALMENT']) > $instalment) {
+                        throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
+                    }
+
+                    if ($userStage == $instalment) {
+                        if ($goods['INSTALMENT'] != 1) {
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+                    } else {
+                        if ($userInstalmentInfo) {
+                            if ($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE'] != 'FX') {
+                                throw new Exception(Yii::t('app', 'canNotBuy'));
+                            }
+                        }
+
+                        if ($userStage + 1 != $goods['INSTALMENT']) {
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+
+                        if ($userStage + 1 > $instalment){
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+                    }
+                    $hasInstalment = $goods['INSTALMENT'];
+                }
+            }
+        }
+
+        $sysConfig = Cache::getSystemConfig();
+        $ampDivideLine = (int)$sysConfig['ampBVCondition']['VALUE'];
+        if ($totalPv < $ampDivideLine) {
+            throw new Exception(Yii::t('app', 'ampOrderSubStandard', ['ampBv' => $ampDivideLine]));
+        }
+
+        // 运费模板
+        $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
+        // 运费
+        $freight = $freeTemplate['freight'] ?? 0;
+        // 普通商品免运费阈值
+        $freeShipping = $freeTemplate['free_shipping'] ?? 0;
+
+        $this->_decAmount = $totalAmount;
+        $this->_decPv = $totalPv;
+        $this->_realPv = $totalRealPv;
+        $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
+
+        $this->_payAmount = $this->_decAmount + $this->_freight;
+
+        $this->_decAmountStandard = $totalAmountStandard;
+        $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
+
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+
+        try {
+            //写入订单
+            if (!$orderResult = $this->addOrder()) {
+                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
+            }
+
+            if ($hasInstalment){
+                $instalmentModel = Instalment::findOne(['USER_ID' => $userId]);
+                if(!$instalmentModel) {
+                    $instalmentModel = new Instalment();
+                }
+                $instalmentModel->USER_ID = $userId;
+                $instalmentModel->STAGE = $hasInstalment;
+                $instalmentModel->UPDATE_TIME = time();
+                $instalmentModel->save();
+            }
+
+            $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);
+        //帮复消会员Id(登陆会员)
+        $loginUserId = \Yii::$app->user->id;
+        $loginUserName = Info::getUserNameByUserId($loginUserId);
+        //订单会员Id
+        $userId = Info::getUserIdByUserName($this->userName);
+        $countryId = Info::getUserCountryByUserId($userId);
+        $email = Info::getEmailByUserId($this->userName);
+        $country = Countries::getById($countryId);
+
+        $warehouse = '01';
+        $_hasPV = $this->_decPv;
+
+        $ordNo = $this->_generateSn();
+        $orderModel = new ApproachReconsumeOrder();
+        $orderModel->SN = 'OS' . $ordNo;
+        $orderModel->DEC_SN = 'DS' . $ordNo;
+        $orderModel->ORDER_TYPE = $this->type;
+        $orderModel->USER_ID = $userId;
+        $orderModel->USER_NAME = $this->userName;
+        $orderModel->ORDER_AMOUNT = $this->_decAmount;
+        $orderModel->PV = $_hasPV;
+        $orderModel->PAY_AMOUNT = $this->_payAmount;
+        $orderModel->PAY_PV = $_hasPV;
+        $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->consignee;
+        $orderModel->MOBILE = $this->acceptMobile;
+        $orderModel->PROVINCE = $this->province[0];
+        $orderModel->LGA_NAME = $this->lgaName;
+        $orderModel->CITY_NAME = $this->cityName;
+        $orderModel->ADDRESS = $this->detailaddress;
+        $orderModel->FRONT_REMARK = $this->remark;
+        $orderModel->WAREHOUSE = $warehouse;
+        $orderModel->STATUS = Yii::$app->params['orderStatus']['notPaid']['value'];
+        $orderModel->CREATED_AT = Date::nowTime();
+        $orderModel->CREATE_USER = $loginUserName;
+        $orderModel->EMAIL = $email ?? '';
+        $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
+        $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
+        $orderModel->EXCHANGE_RATE = $this->exchangeRate;
+        $orderModel->COUNTRY_ID = $countryId;
+        $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
+        $orderModel->DEC_USER_ID = $this->decUserName;
+        $orderModel->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
+        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);
+        }
+        ApproachOrderGoods::batchInsert($this->_orderGoods);
+
+        return $orderModel;
+    }
+
+    /**
+     * 生成流水号
+     * @return string
+     */
+    private function _generateSn() {
+        return Date::today('Ymd') . $this->_random(10, 1);
+    }
+
+    /**
+     * 生成随机数
+     * @param $length
+     * @param int $numeric
+     * @return string
+     */
+    private function _random($length, $numeric = 0) {
+        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
+        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
+        $hash = '';
+        $max = strlen($seed) - 1;
+        for ($i = 0; $i < $length; $i++) {
+            $hash .= $seed[mt_rand(0, $max)];
+        }
+        return $hash;
+    }
+
+    private function orderAutoMaintenance($order)
+    {
+        $nowPeriodNum = Period::instance()->getNowPeriodNum();
+
+        try {
+            $sysConfig = Cache::getSystemConfig();
+            $divideLine = (int)$sysConfig['monthPcsPvFxCondition']['VALUE'];
+
+            $orderTotalBv = $order->PV;
+
+            if ($orderTotalBv <= $divideLine) {
+                return;
+            }
+
+            $lastAmpPeriod = AmpPeriod::find()
+                ->where(['USER_ID' => $order->USER_ID])
+                ->orderBy(['PERIOD_NUM' => SORT_DESC])
+                ->one();
+
+            $startPeriodNum = $lastAmpPeriod ? $lastAmpPeriod->PERIOD_NUM + 1 : $nowPeriodNum;
+
+            if (!$lastAmpPeriod) {
+                $memberOrderBv = Order::find()
+                    ->select('SUM(PV) AS total_pv')
+                    ->where([
+                        'USER_ID' => $order->USER_ID,
+                        'IS_DELETE' => 0,
+                        'PERIOD_NUM' => $nowPeriodNum
+                    ])
+                    ->scalar();
+
+                if ($memberOrderBv >= $divideLine) {
+                    $startPeriodNum = $nowPeriodNum + 1;
+                }
+            }
+
+            $periodCount = floor($orderTotalBv / $divideLine);
+            $remainderBv = $orderTotalBv % $divideLine;
+
+            $ampPeriods = [];
+            for ($i = 1; $i <= $periodCount; $i++) {
+                $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
+                $ampPeriods[] = [
+                    'USER_ID' => $order->USER_ID,
+                    'ORDER_SN' => $order->SN,
+                    'PERIOD_NUM' => $startPeriodNum + $i - 1,
+                    'BV' => $currentBv,
+                ];
+            }
+
+            if (!empty($ampPeriods)) {
+                AmpPeriod::batchInsert($ampPeriods);
+            }
+        } catch (\Exception $e) {
+            // 记录日志或进行错误处理
+            \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
+        }
+    }
+}

+ 22 - 41
common/models/forms/ApproachDeclarationForm.php

@@ -5,8 +5,6 @@ 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;
@@ -15,16 +13,10 @@ use common\models\ApproachOrderGoods;
 use common\models\Countries;
 use common\models\CurrencyConversions;
 use common\models\DeclarationPackage;
-use common\models\DecOrder;
 use common\models\EmployLevel;
 use common\models\Language;
-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\ShopGoodsNature;
@@ -140,8 +132,8 @@ class ApproachDeclarationForm extends Model
             [['insertUserName'], 'isCanAddUser'],
             [['decUserName', 'decType'], 'issetDec'],
             [['conUserName'], 'isConUserName'],
-//            [['recUserName'], 'isRecUserName'],
-//            [['location'], 'isLocation'],
+            [['recUserName'], 'isRecUserName'],
+            [['location'], 'isLocation'],
 //            [['insertUserIdCard'], 'isSameSystem'],
         ];
     }
@@ -211,19 +203,6 @@ class ApproachDeclarationForm extends Model
                 $this->addError($attribute, Yii::t('app', 'stockistDoesNotExist'));
                 return false;
             } else {
-//                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'];
             }
         }
@@ -270,10 +249,10 @@ class ApproachDeclarationForm extends Model
             if($conUser['CON_NUM'] >= 3){
                 if($this->insertUserName){
                    // $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'下级点位已满');
-                    $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'lower level is full');
+//                    $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'lower level is full');
                 } else {
                     //$this->addError($attribute, '指导老师'.$this->conUserName.'下级点位已满');
-                    $this->addError($attribute, 'Instructor'.$this->conUserName.'lower level is full');
+//                    $this->addError($attribute, 'Instructor'.$this->conUserName.'lower level is full');
                 }
                 return;
             }
@@ -340,14 +319,11 @@ class ApproachDeclarationForm extends Model
             $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;
 
             // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
-            if($this->decType !== 'ba' && $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->loopFindParentToNetwork($this->insertUserName);
+//            if (!$this->recUserIsInNetworkParent()) {
+//                $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Sponsor' . $this->recUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
+//                return ;
+//            }
 
             // 把自己加入到临时上级会员数组中
             $this->_tempParentUser[$this->insertUserName] = [
@@ -523,13 +499,13 @@ class ApproachDeclarationForm extends Model
             // 判断接点会员的下级会员是否大于三个,如果大于三个则不允许
             if($conUser['CON_NUM'] >= 3){
 //                $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'下级点位已满');
-                $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->conUserName.'lower level is full');
+//                $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->conUserName.'lower level is full');
                 return;
             }
             // 判断指导老师相应的区位是否已满
             if($conUser['LOCATION'.$this->location]){
 //                $this->addError($attribute, '为'.$this->insertUserName.'报单,指导老师'.$this->conUserName.'该市场已存在会员');
-                $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->conUserName.'Members already exist in this market');
+//                $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->conUserName.'Members already exist in this market');
                 return;
             }
 //            if($conUser['CON_NUM'] == 0 && $this->location != 1){
@@ -643,7 +619,8 @@ class ApproachDeclarationForm extends Model
                 }
 
                 // 报单中心汇率
-                $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+                $userInfo = User::findOne(\Yii::$app->user->id);
+                $decCountryId = $userInfo->COUNTRY_ID;
                 $decCountry = Countries::getById($decCountryId);
                 $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
                 // 升级会员汇率
@@ -749,7 +726,7 @@ class ApproachDeclarationForm extends Model
                 return $decResult;
             } catch (\Exception $e) {
 //                throw new Exception(Form::formatErrorsForApi($e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage()));
-                throw new Exception(Form::formatErrorsForApi($e->getMessage()));
+                throw new Exception(Form::formatErrorsForApi($e->getMessage() . ', ' . $e->getFile() . '(' . $e->getLine() . ')'));
             }
         }
         return true;
@@ -806,6 +783,7 @@ class ApproachDeclarationForm extends Model
         if (!$user->save()) {
             throw new Exception(Form::formatErrorsForApi($user->getErrors()));
         }
+
         $this->_insertUserId = $user->ID;
         $userForm = new UserForm();
         $this->_userForm = $userForm;
@@ -876,10 +854,12 @@ class ApproachDeclarationForm extends Model
         }
 
         // 升级会员
-        $userCountry = User::getEnCodeInfo($this->_insertUserId);
+        $userCountryId = User::getEnCodeInfo($this->_insertUserId)['COUNTRY_ID'];
+        $userCountry = Countries::getById($userCountryId);
         $userCurrencyRate = CurrencyConversions::getToUSDRate($userCountry['LOCAL_CURRENCY_ID']);
         // 报单中心汇率
-        $decCountry = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $decCountry = Countries::getById($decCountryId);
         $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
 
         $orderModel = new ApproachOrder();
@@ -913,8 +893,9 @@ class ApproachDeclarationForm extends Model
         $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
         $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
         $orderModel->EXCHANGE_RATE = $userCurrencyRate;
-        $orderModel->COUNTRY_ID = $userCountry['COUNTRY_ID'];
+        $orderModel->COUNTRY_ID = $userCountryId;
         $orderModel->CURRENCY_ID = $userCountry['LOCAL_CURRENCY_ID'] ?? 0;
+        $orderModel->DEC_USER_ID = Info::getUserNameByUserId($this->_decId);
         if ($this->province==1) {
             $orderModel->EXPRESS_TYPE = 1;
         }
@@ -936,7 +917,7 @@ class ApproachDeclarationForm extends Model
             $addressModel->USER_NAME = $this->insertUserName;
             $addressModel->CONSIGNEE = $this->consignee;
             $addressModel->MOBILE = $this->acceptMobile;
-            $addressModel->COUNTRY_ID = $userCountry['COUNTRY_ID'];
+            $addressModel->COUNTRY_ID = $userCountryId;
             $addressModel->PROVINCE = $this->province;
             $addressModel->CITY_NAME = $this->cityName;
             $addressModel->LGA_NAME = $this->lgaName;

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

@@ -59,7 +59,6 @@ class ApproachDeclarationLoopForm extends Model
      * @param $attribute
      */
     public function formatData($attribute){
-        //$this->data = Json::decode($this->data);
         if(!is_array($this->data)){
             $this->addError($attribute, 'Data format error');// 数据格式错误
         }
@@ -220,8 +219,7 @@ class ApproachDeclarationLoopForm extends Model
             return $result;
         } catch (\Exception $e){
             $transaction->rollBack();
-//            $this->addError('add', $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
-            $this->addError('add', $e->getMessage());
+            $this->addError('add', $e->getMessage() . '; ' . $e->getLine() . '; ' . $e->getFile());
             return null;
         }
     }

+ 7 - 4
common/models/forms/ApproachDeclarationUpgradeForm.php

@@ -329,10 +329,12 @@ class ApproachDeclarationUpgradeForm extends Model
             }
 
             // 升级会员
-            $userCountry = User::getEnCodeInfo($this->_insertUserId);
+            $userCountryId = User::getEnCodeInfo($this->_insertUserId)['COUNTRY_ID'];
+            $userCountry = Countries::getById($userCountryId);
             $userCurrencyRate = CurrencyConversions::getToUSDRate($userCountry['LOCAL_CURRENCY_ID']);
             // 报单中心汇率
-            $decCountry = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+            $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+            $decCountry = Countries::getById($decCountryId);
             $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
 
             $orderModel = new ApproachOrder();
@@ -365,7 +367,8 @@ class ApproachDeclarationUpgradeForm extends Model
             $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
             $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
             $orderModel->EXCHANGE_RATE = $userCurrencyRate;
-            $orderModel->COUNTRY_ID = $userCountry['COUNTRY_ID'];
+            $orderModel->DEC_USER_ID = Info::getUserNameByUserId(\Yii::$app->user->id);
+            $orderModel->COUNTRY_ID = $userCountryId;
             $orderModel->CURRENCY_ID = $userCountry['LOCAL_CURRENCY_ID'] ?? 0;
             if(!$orderModel->save()){
                 $transaction->rollBack();
@@ -409,7 +412,7 @@ class ApproachDeclarationUpgradeForm extends Model
             $addressModel->USER_NAME = $this->insertUserName;
             $addressModel->CONSIGNEE = $this->consignee;
             $addressModel->MOBILE = $this->acceptMobile;
-            $addressModel->COUNTRY_ID = $userCountry['COUNTRY_ID'];
+            $addressModel->COUNTRY_ID = $userCountryId;
             $addressModel->PROVINCE = $this->province;
             $addressModel->LGA_NAME = $this->lgaName;
             $addressModel->CITY_NAME = $this->cityName;

+ 75 - 18
common/models/forms/ApproachOrderForm.php

@@ -12,6 +12,7 @@ use common\helpers\user\Balance;
 use common\helpers\user\Cash;
 use common\helpers\user\Info;
 use common\libs\logging\operate\AdminOperate;
+use common\models\AmpPeriod;
 use common\models\ApproachDecOrder;
 use common\models\ApproachOrder;
 use common\models\ApproachOrderGoods;
@@ -127,6 +128,7 @@ class ApproachOrderForm extends Model
             'cityName' => Yii::t('app', 'cityName'),
             'detailaddress' => Yii::t('app', 'detailAddress'),
             'email' => Yii::t('app', 'email'),
+            'autoMaintenance' => Yii::t('app', 'amp'),
         ];
     }
 
@@ -303,14 +305,14 @@ class ApproachOrderForm extends Model
 
         // 调用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(Yii::t('app', 'payAmountNotEqualOrderAmount')));
-        }
+//        $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(Yii::t('app', 'payAmountNotEqualOrderAmount')));
+//        }
 
         // 订单类型:userOrder(会员订单)、userUpgrade(会员升级)、userDec(会员报单)
         $orderType = $this->note['metadata']['custom_fields'][1]['value'] ?? false;
@@ -338,6 +340,12 @@ class ApproachOrderForm extends Model
             }
             OrderGoods::batchInsert($approachOrderGoods);
 
+            // AMP订单
+            $order = Order::findOne($this->_model->ID);
+            if ($order['AUTO_MAINTENANCE'] == 1) {
+                $this->orderAutoMaintenance($order);
+            }
+
             // 会员报单、BA升级
             if (in_array($orderType, ['userDec', 'baUpgrade', 'userUpgrade'])) {
                 // 同步报单
@@ -354,14 +362,6 @@ class ApproachOrderForm extends Model
                             throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'changeUserStatusError')));
                         }
                     }
-                    // 修改BA会员升级状态
-//                    if ($orderType === 'baUpgrade') {
-//                        // 查询BA会员名
-//                        $userInfo = User::findOneAsArray('ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']]);
-//                        if (!BaUser::updateAll(['WHETHER_UPGRADE' => 1, 'BA_UPGRADE_AT' => time()], 'USER_NAME=:USER_NAME', [':USER_NAME' => $userInfo['USER_NAME']])) {
-//                            throw new Exception(Form::formatErrorsForApi(Yii::t('app', 'brandAmbassadorUpgradeError')));
-//                        }
-//                    }
 
                     // 正式会员-升级单
                     if ($orderType === 'userUpgrade') {
@@ -634,8 +634,6 @@ class ApproachOrderForm extends Model
         }
         ApproachOrderGoods::batchInsert($this->_orderGoods);
 
-        // TODO: 记录流水
-
         return $orderModel;
     }
 
@@ -663,4 +661,63 @@ class ApproachOrderForm extends Model
         }
         return $hash;
     }
+
+    private function orderAutoMaintenance($order)
+    {
+        $nowPeriodNum = Period::instance()->getNowPeriodNum();
+
+        try {
+            $sysConfig = Cache::getSystemConfig();
+            $divideLine = (int)$sysConfig['monthPcsPvFxCondition']['VALUE'];
+
+            $orderTotalBv = $order->PV;
+
+            if ($orderTotalBv <= $divideLine) {
+                return;
+            }
+
+            $lastAmpPeriod = AmpPeriod::find()
+                ->where(['USER_ID' => $order->USER_ID])
+                ->orderBy(['PERIOD_NUM' => SORT_DESC])
+                ->one();
+
+            $startPeriodNum = $lastAmpPeriod ? $lastAmpPeriod->PERIOD_NUM + 1 : $nowPeriodNum;
+
+            if (!$lastAmpPeriod) {
+                $memberOrderBv = Order::find()
+                    ->select('SUM(PV) AS total_pv')
+                    ->where([
+                        'USER_ID' => $order->USER_ID,
+                        'IS_DELETE' => 0,
+                        'PERIOD_NUM' => $nowPeriodNum
+                    ])
+                    ->scalar();
+
+                if ($memberOrderBv >= $divideLine) {
+                    $startPeriodNum = $nowPeriodNum + 1;
+                }
+            }
+
+            $periodCount = floor($orderTotalBv / $divideLine);
+            $remainderBv = $orderTotalBv % $divideLine;
+
+            $ampPeriods = [];
+            for ($i = 1; $i <= $periodCount; $i++) {
+                $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
+                $ampPeriods[] = [
+                    'USER_ID' => $order->USER_ID,
+                    'ORDER_SN' => $order->SN,
+                    'PERIOD_NUM' => $startPeriodNum + $i - 1,
+                    'BV' => $currentBv,
+                ];
+            }
+
+            if (!empty($ampPeriods)) {
+                AmpPeriod::batchInsert($ampPeriods);
+            }
+        } catch (\Exception $e) {
+            // 记录日志或进行错误处理
+            \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
+        }
+    }
 }

+ 150 - 65
common/models/forms/ApproachReconsumeOrderForm.php

@@ -7,6 +7,7 @@ use common\components\Model;
 use common\helpers\Form;
 use common\helpers\LoggerTool;
 use common\helpers\PayStack;
+use common\helpers\Tool;
 use common\helpers\user\Balance;
 use common\helpers\user\Cash;
 use common\helpers\user\Info;
@@ -16,18 +17,23 @@ use common\models\ApproachOrder;
 use common\models\ApproachReconsumeOrder;
 use common\models\ApproachOrderGoods;
 use common\models\BaUser;
+use common\models\Countries;
+use common\models\CurrencyConversions;
 use common\models\DealType;
 use common\models\DecLevelLog;
 use common\models\DecOrder;
+use common\models\FreeTemplate;
 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\ShopGoodsNature;
 use common\models\User;
 use common\models\UserNetwork;
 use common\models\Instalment;
+use common\models\UserPerformance;
 use Yii;
 use yii\base\Exception;
 
@@ -37,12 +43,8 @@ use yii\base\Exception;
 class ApproachReconsumeOrderForm extends Model
 {
     public $sn;
-    public $expressCompany;
-    public $orderTrackNo;
     public $status;
     public $remark;
-    public $note;
-
     public $type;
     public $addressId;
     public $payType;
@@ -50,21 +52,25 @@ class ApproachReconsumeOrderForm extends Model
     public $goodsNum;
     public $payPassword;
     public $email;
+    public $period;
 
     public $userName;
+    public $decUserName;
     public $consignee;
     public $acceptMobile;
     public $province;
     public $city;
-    public $county;
     public $lgaName;
     public $cityName;
+    public $county;
+    public $exchangeRate;
     public $detailaddress;
 
     private $_address;
     private $_decAmount;
     private $_decPv;
     private $_freight;
+    private $_realPv;
     private $_payAmount;
     private $_orderGoods;
     private $_standardAmount;
@@ -88,8 +94,8 @@ class ApproachReconsumeOrderForm extends Model
     public function rules()
     {
         return [
-            [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
-            [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'/*,'email'*/], 'required'],
+            [['sn', 'expressCompany', 'orderTrackNo', 'status','type','remark','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
+            [['sn', 'expressCompany', 'orderTrackNo', 'status','type','remark','addressId','payType','goodsId','goodsNum', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'/*,'email'*/,'decUserName'], 'required'],
             [['status'], 'isStatus'],
             [['addressId'], 'isAddress'],
             [['payType'], 'isPayType'],
@@ -137,8 +143,8 @@ class ApproachReconsumeOrderForm extends Model
             'verifyPayStack' => ['sn', 'note', 'status'],
             // 会员下单
             'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
-            // 为会员复消
-            'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress'],
+            // 帮会员复消下单
+            'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress','decUserName'],
         ];
         return array_merge($parentScenarios, $customScenarios);
     }
@@ -206,7 +212,6 @@ class ApproachReconsumeOrderForm extends Model
         $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
         if (!$goods) {
             throw new Exception(Yii::t('app', 'orderCanNotContainMultipleProductCategories'));
-            return;
         }
         $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
         if (count($goodsCategoryType) > 1) {
@@ -412,42 +417,80 @@ class ApproachReconsumeOrderForm extends Model
         $ids = $this->goodsId;
         $totalAmount = 0;
         $totalPv = 0;
+        $totalRealPv = 0;
         $totalAmountStandard = 0;
-        $goodsType = ShopGoods::GOODS_TYPE;
+
+        $goodsType = ShopGoods::getGoodType();
         $hasInstalment = 0;
-        $loginUserId = \Yii::$app->user->id;
-        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
+        $userId = Info::getUserIdByUserName($this->userName);
+        $user = User::getEnCodeInfo($userId);
+
+        $decUserID = Info::getUserIdByUserName($this->decUserName);
+        $stockist_user = User::getEnCodeInfo($decUserID);
+        if(!$stockist_user || $stockist_user['IS_DEC'] != 1){
+            throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
+        }
+
+        // 报单中心汇率
+        $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $decCountry = Countries::getById($decCountryId);
+        $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
+        // 会员汇率
+        $country = Countries::getById($user['COUNTRY_ID']);
+        $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
+        //判断是否是报单中心
+        $loginUser = User::getEnCodeInfo(\Yii::$app->user->id);
+        if($loginUser['IS_DEC'] == 1){
+            if($decUserID != \Yii::$app->user->id){
+                throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
+            }
+        }
+
         foreach ($this->goodsNum as $k => $v) {
             if ($v) {
                 $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
                 if (!$goods) {
                     throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
                 }
+                $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
+                    [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
+                if (!$goodsNature) {
+                    throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                }
+
+                // 汇率
+                $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
+
                 if($goods['STORE_NUMS']>0){
                     if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
                         $discount = $goodsType[$goods['TYPE']]['discount'];
-                        $realPrice = $goods['SELL_PRICE'] * $discount/100;
+                        $realPrice = $goodsNature['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;
+                        $realPrice = $goodsNature['SELL_PRICE'] * $discount;
                         $realPv = $goods['PRICE_PV'] * $discount;
                         $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
                     }
+
+                    $currentPv = $goods['PRICE_PV'];
+                    $totalPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
+                    $totalRealPv += $this->payType == 'prp' ? 0 : $realPv * intval($v);
+                    $remainPv = 0;
+
                     $totalAmount += $realPrice * intval($v);
-                    $totalPv += $realPv * intval($v);
                     $totalAmountStandard += $realPriceStandard * intval($v);
 
                     $this->_orderGoods[] = [
                         'GOODS_ID' => $goods['ID'],
-                        'PRICE' => $goods['SELL_PRICE'],
-                        'PV' => $goods['PRICE_PV'],
+                        'PRICE' => $goodsNature['SELL_PRICE'],
+                        'PV' => $this->payType == 'prp' ? 0 : $currentPv, // $goods['PRICE_PV'],
                         'REAL_PRICE' => $realPrice,
-                        'REAL_PV' => $realPv,
+                        'REAL_PV' => $this->payType == 'prp' ? 0 : $realPv,
+                        'REMAIN_PV' => $this->payType == 'prp' ? 0 : $remainPv,
                         'POINT' => $goods['POINT'],
                         'BUY_NUMS' => intval($v),
-                        'TAX_RATE' => $goods['TAX_RATE'],
                         'SKU_CODE' => $goods['GOODS_NO'],
                         'GOODS_TITLE' => $goods['GOODS_NAME'],
                         'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
@@ -455,7 +498,8 @@ class ApproachReconsumeOrderForm extends Model
                         'EMAIL' => $this->email,
                         'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
                         'REAL_STANDARD_PRICE' => $realPriceStandard,
-                        'EXCHANGE_RATE' => $exchangeRate,
+                        'EXCHANGE_RATE' => $currencyRate,
+                        'TAX_RATE' => $goodsNature['TAX_RATE'],
                     ];
                 }
                 if($goods['INSTALMENT']>0){ // 如果有分期付款商品,检查用户的分期付款状态
@@ -463,20 +507,24 @@ class ApproachReconsumeOrderForm extends Model
                         throw new Exception(Yii::t('app', 'allowOnlyOne'));
                     }
 
-                    $userStage = Instalment::getStage($loginUserId);
+                    $userStage = Instalment::getStage($userId);
+                    $userInstalmentInfo = Instalment::getInfo($userId);
                     // 分期的总期数
                     $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
                     // 分期商品的期数不能大于总分期数限制
                     if (intval($goods['INSTALMENT']) > $instalment) {
                         throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
                     }
-                    if ($userStage==0){
-
-                    } else if ($userStage == $instalment) {
+                    if ($userStage == $instalment){
                         if ($goods['INSTALMENT'] != 1) {
                             throw new Exception(Yii::t('app', 'canNotBuy'));
                         }
                     }else{
+                        if($userInstalmentInfo){
+                            if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
+                                throw new Exception(Yii::t('app', 'canNotBuy'));
+                            }
+                        }
                         if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
                             throw new Exception(Yii::t('app', 'canNotBuy'));
                         }
@@ -489,38 +537,82 @@ class ApproachReconsumeOrderForm extends Model
             }
         }
 
-        // 运费.奈拉
-        $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
-        // 普通商品免运费阈值.奈拉
-        $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
+        // 运费模板
+        $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
+        // 运费
+        $freight = $freeTemplate['freight'] ?? 0;
+        // 普通商品免运费阈值
+        $freeShipping = $freeTemplate['free_shipping'] ?? 0;
 
         $this->_decAmount = $totalAmount;
-        $this->_decPv = $totalPv;
+        $this->_decPv = $this->payType == 'prp' ? 0 : $totalPv;
         $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
-
         $this->_payAmount = $this->_decAmount + $this->_freight;
         $this->_decAmountStandard = $totalAmountStandard;
         $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
 
         $db = \Yii::$app->db;
         $transaction = $db->beginTransaction();
-
         try {
+            $loginUserId = \Yii::$app->user->id;
+
             //写入订单
             if (!$orderResult = $this->addOrder()) {
                 throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
             }
+
+            //是否开启伞下会员限制
+            // $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
+            // if($isResaleUmbrella){
+            //     $userId = Info::getUserIdByUserName($this->userName);
+            //     $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
+            //     if(!$userNetwork){
+            //         throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
+            //     }
+            // }
+
+            foreach ($this->goodsNum as $k => $v){
+                if ($v){
+                    $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
+                    if (!$goods) {
+                        throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                    }
+                    if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
+                        $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
+                        $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
+                        $data->STORE_NUMS = $goods_store_nums;
+                        $data->update();
+                        //下单后库存小于等于0 商品下架
+                        if($goods_store_nums <= 0){
+                            $data->STATUS = 0;
+                            $data->UPDATED_AT = Date::nowTime();
+                            $data->update();
+
+                        }
+                    } else {
+                        throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
+                    }
+                }
+            }
+
+            // 写入订单
+            if (!$orderResult = $this->addOrder()) {
+                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
+            }
+
             if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
-                $instalmentModel = Instalment::findOne(['USER_ID'=>$loginUserId]);
+                $instalmentModel = Instalment::findOne(['USER_ID'=>$userId]);
                 if(!$instalmentModel) {
                     $instalmentModel = new Instalment();
                 }
-                $instalmentModel->USER_ID = $loginUserId;
+                $instalmentModel->USER_ID = $userId;
                 $instalmentModel->STAGE = $hasInstalment;
+                $instalmentModel->ORDER_TYPE = 'FX';
                 $instalmentModel->UPDATE_TIME = time();
                 $instalmentModel->save();
             }
 
+
             $transaction->commit();
 
             return $orderResult;
@@ -541,29 +633,30 @@ class ApproachReconsumeOrderForm extends Model
         $nowPeriodNum = $periodObj->getNowPeriodNum();
         $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
 
-        $userId = \Yii::$app->user->id;
+        //帮复消会员Id(登陆会员)
+        $loginUserId = \Yii::$app->user->id;
+        $loginUserName = Info::getUserNameByUserId($loginUserId);
+        //订单会员Id
+        $userId = Info::getUserIdByUserName($this->userName);
+        $countryId = Info::getUserCountryByUserId($userId);
+        $email = Info::getEmailByUserId($this->userName);
+        $country = Countries::getById($countryId);
 
-        $userName = Info::getUserNameByUserId($userId);
-        $userRealName = Info::getUserRealNameByUserId($userId);
-        $userMobile = Info::getUserMobileByUserId($userId);
-        $userEmail = Info::getUserEmailByUserId($userId);
-        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
-        // 加入订单信息
         $warehouse = '01';
-        $_hasPV = $this->_decPv;
 
         $ordNo = $this->_generateSn();
         $orderModel = new ApproachReconsumeOrder();
-        $orderModel->SN = 'OS' . $ordNo;
-        $orderModel->DEC_SN = 'DS' . $ordNo;
+        $orderModel->SN = 'OS'.$ordNo;
+        $orderModel->DEC_SN = 'DS'.$ordNo;
         $orderModel->ORDER_TYPE = $this->type;
+        $orderModel->ORDER_CATEGORY = 'STUDIO';
         $orderModel->USER_ID = $userId;
-        $orderModel->USER_NAME = $userName;
+        $orderModel->USER_NAME = $this->userName;
         $orderModel->ORDER_AMOUNT = $this->_decAmount;
-        $orderModel->PV = $_hasPV;
+        $orderModel->PV = $this->payType == 'prp' ? 0 : $this->_decPv;
         $orderModel->PAY_AMOUNT = $this->_payAmount;
-        $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
-        $orderModel->PAY_AT = 0;
+        $orderModel->PAY_PV = $this->payType == 'prp' ? 0 : $this->_decPv;
+        $orderModel->PAY_AT = Date::nowTime();
         $orderModel->PAY_TYPE = $this->payType;
         $orderModel->PERIOD_NUM = $nowPeriodNum;
         $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
@@ -575,29 +668,23 @@ class ApproachReconsumeOrderForm extends Model
         $orderModel->LGA_NAME = $this->lgaName;
         $orderModel->CITY_NAME = $this->cityName;
         $orderModel->ADDRESS = $this->detailaddress;
-
         $orderModel->FRONT_REMARK = $this->remark;
         $orderModel->WAREHOUSE = $warehouse;
-        $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
+        $orderModel->STATUS = 1;
         $orderModel->CREATED_AT = Date::nowTime();
-        $orderModel->CREATE_USER = $userName;
-        $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.net';
+        $orderModel->CREATE_USER = $loginUserName;
+        $orderModel->EMAIL = $email ?? '';
         $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
         $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
-        $orderModel->EXCHANGE_RATE = $exchangeRate;
-//        if($this->_address['PROVINCE']==1){
-//            $orderModel->EXPRESS_TYPE = 1;
-//            $orderModel->CONSIGNEE = $userRealName;
-//            $orderModel->MOBILE = $userMobile;
-//            $orderModel->PROVINCE = 1;
-//            $orderModel->CITY = 1;
-//            $orderModel->COUNTY = 1;
-//            $orderModel->ADDRESS = '';
-//        }
-
+        $orderModel->EXCHANGE_RATE = $this->exchangeRate;
+        $orderModel->COUNTRY_ID = $countryId;
+        $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
+        $orderModel->DEC_USER_ID = $this->decUserName;
+        $orderModel->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
         if(!$orderModel->save()){
             throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
         }
+
         // 加入商品到订单商品表
         foreach($this->_orderGoods as $key=>$value) {
             $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
@@ -605,8 +692,6 @@ class ApproachReconsumeOrderForm extends Model
         }
         ApproachOrderGoods::batchInsert($this->_orderGoods);
 
-        // TODO: 记录流水
-
         return $orderModel;
     }
 

+ 5 - 22
common/models/forms/DeclarationForm.php

@@ -208,27 +208,10 @@ class DeclarationForm extends Model
         if(!$this->decUserName){
             $this->_decId = '';
         } else {
-
-
             if (!$decUser = User::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
                 $this->addError($attribute, Yii::t('app', 'stockistDoesNotExist'));
                 return false;
             } else {
-                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;
-//                    }
-                }
                 $this->_decId = $decUser['ID'];
             }
         }
@@ -346,14 +329,12 @@ class DeclarationForm extends Model
 
             // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
             if($this->insertUserName) {
-                if ($this->decType !== 'ba') {
                     $this->loopFindParentToNetwork($this->insertUserName);
-                    if (!$this->recUserIsInNetworkParent()) {
+//                    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 ;
-                    }
-                }
+//                    }
             }
 
             // 把自己加入到临时上级会员数组中
@@ -664,7 +645,8 @@ class DeclarationForm extends Model
             }
 
             // 报单中心汇率
-            $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+            $userInfo = User::findOne(\Yii::$app->user->id);
+            $decCountryId = $userInfo->COUNTRY_ID;
             $decCountry = Countries::getById($decCountryId);
             $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
             // 升级会员汇率
@@ -962,6 +944,7 @@ class DeclarationForm extends Model
         $orderModel->COUNTRY_ID = $userCountryId;
         $orderModel->DEC_USER_ID = $this->decUserName;
         $orderModel->CURRENCY_ID = $userCountry['LOCAL_CURRENCY_ID'] ?? 0;
+        $orderModel->DEC_USER_ID = Info::getUserNameByUserId($this->_decId);
         if($this->province==1){
             $orderModel->EXPRESS_TYPE = 1;
         }

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

@@ -372,6 +372,7 @@ class DeclarationUpgradeForm extends Model
             $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
             $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
             $orderModel->EXCHANGE_RATE = $userCurrencyRate;
+            $orderModel->DEC_USER_ID = Info::getUserNameByUserId(\Yii::$app->user->id);
             $orderModel->COUNTRY_ID = $userCountryId;
             $orderModel->CURRENCY_ID = $userCountry['LOCAL_CURRENCY_ID'] ?? 0;
             if(!$orderModel->save()){

+ 326 - 19
common/models/forms/OrderForm.php

@@ -12,6 +12,7 @@ use common\helpers\user\Balance;
 use common\helpers\user\Cash;
 use common\helpers\user\Info;
 use common\libs\logging\operate\AdminOperate;
+use common\models\AmpPeriod;
 use common\models\Countries;
 use common\models\CurrencyConversions;
 use common\models\DealType;
@@ -62,6 +63,7 @@ class OrderForm extends Model
     public $lgaName;
     public $cityName;
     public $county;
+    public $autoMaintenance;
     public $detailaddress;
 
     private $_address;
@@ -152,6 +154,8 @@ class OrderForm extends Model
             'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','cityName','lgaName','detailaddress','decUserName'],
             // 管理员退款
             'adminRefund' => ['sn'],
+            // AMP
+            'autoMaintenanceOrder' => ['type', 'userName', 'payType', 'goodsId', 'goodsNum', 'remark', 'payPassword', 'consignee', 'acceptMobile', 'province', 'cityName', 'lgaName', 'detailaddress', 'decUserName'],
         ];
         return array_merge($parentScenarios, $customScenarios);
     }
@@ -974,14 +978,14 @@ class OrderForm extends Model
             $loginUserId = \Yii::$app->user->id;
 
             //是否开启伞下会员限制
-            $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
-            if($isResaleUmbrella){
-                $userId = Info::getUserIdByUserName($this->userName);
-                $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
-                if(!$userNetwork){
-                    throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
-                }
-            }
+            // $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
+            // if($isResaleUmbrella){
+            //     $userId = Info::getUserIdByUserName($this->userName);
+            //     $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
+            //     if(!$userNetwork){
+            //         throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
+            //     }
+            // }
 
             if ($this->payType == 'prp') {
                 //看余额是否充足
@@ -1050,7 +1054,8 @@ class OrderForm extends Model
     /**
      * 帮会员复消的订单
      */
-    public function addUserOrder(){
+    public function addUserOrder()
+    {
         $periodObj = Period::instance();
         $nowPeriodNum = $periodObj->getNowPeriodNum();
         $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
@@ -1063,15 +1068,8 @@ class OrderForm extends Model
         $email = Info::getEmailByUserId($this->userName);
         $country = Countries::getById($countryId);
 
-        // 加入订单信息
-//        if($this->province!=1){
-//            $warehouse = Region::getWarehouseByCode($this->province);//仓库
-//            if(!$warehouse){
-//                throw new Exception(Yii::t('app', 'deliveryTemporarilyNotSupported'));
-//            }
-//        }else{
-            $warehouse = '01';
-//        }
+        $warehouse = '01';
+
         $ordNo = $this->_generateSn();
         $orderModel = new Order();
         $orderModel->SN = 'OS'.$ordNo;
@@ -1107,7 +1105,8 @@ class OrderForm extends Model
         $orderModel->EXCHANGE_RATE = $this->exchangeRate;
         $orderModel->COUNTRY_ID = $countryId;
         $orderModel->CURRENCY_ID = $country['LOCAL_CURRENCY_ID'] ?? 0;
-        $orderModel->DEC_USER_ID = $this->decUserName;;
+        $orderModel->DEC_USER_ID = $this->decUserName;
+        $orderModel->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
         if(!$orderModel->save()){
             throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
         }
@@ -1126,6 +1125,11 @@ class OrderForm extends Model
         } else{
             Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => Yii::t('app', 'membersExchangePointPayment')]);
         }
+
+        if (($this->payType != 'prp') && ($this->autoMaintenance == 1)) {
+            $this->orderAutoMaintenance($orderModel);
+        }
+
         return $orderModel;
     }
 
@@ -1180,4 +1184,307 @@ class OrderForm extends Model
         }
         return $orderModel;
     }
+
+    /**
+     * AMP
+     * @return bool|null
+     * @throws Exception|\Throwable
+     */
+    public function autoMaintenanceSureOrder()
+    {
+        if (!$this->validate()) {
+            return null;
+        }
+
+        $ids = $this->goodsId;
+        $totalAmount = 0;
+        $totalPv = 0;
+        $totalRealPv = 0;
+        $totalAmountStandard = 0;
+        $this->autoMaintenance = 1;
+
+        $goodsType = ShopGoods::getGoodType();
+        $hasInstalment = 0;
+        $userId = Info::getUserIdByUserName($this->userName);
+        $user = User::getEnCodeInfo($userId);
+
+        $decUserID = Info::getUserIdByUserName($this->decUserName);
+        $stockist_user = User::getEnCodeInfo($decUserID);
+        if(!$stockist_user || $stockist_user['IS_DEC'] != 1){
+            throw new Exception(Yii::t('app', 'stockistDoesNotExist'));
+        }
+
+        // 报单中心汇率
+        $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $decCountry = Countries::getById($decCountryId);
+        $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
+        // 会员汇率
+        $country = Countries::getById($user['COUNTRY_ID']);
+        $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
+        // 判断是否是报单中心
+        $loginUser = User::getEnCodeInfo(\Yii::$app->user->id);
+        if ($loginUser['IS_DEC'] == 1){
+            if($decUserID != \Yii::$app->user->id){
+                throw new Exception(Yii::t('app', 'decUserNameIsWrong'));
+            }
+        }
+
+        if ($this->payType == 'prp') {
+            throw new Exception(Yii::t('app', 'payTypeError'));
+        }
+
+        foreach ($this->goodsNum as $k => $v) {
+            if ($v) {
+                $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1 AND AUTO_MAINTENANCE=1',[':ID'=> $ids[$k]]);
+                if (!$goods) {
+                    throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                }
+
+                $goodsNature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID',
+                    [':GOODS_ID' => $ids[$k], ':COUNTRY_ID' => $user['COUNTRY_ID']]);
+                if (!$goodsNature) {
+                    throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                }
+
+                $this->exchangeRate = CurrencyConversions::getToUSDRate($goodsNature['LOCAL_CURRENCY_ID']);
+
+                if($goods['STORE_NUMS']>0){
+                    if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
+                        $discount = $goodsType[$goods['TYPE']]['discount'];
+                        $realPrice = $goodsNature['SELL_PRICE'] * $discount/100;
+                        $realPv = $goods['PRICE_PV'] * $discount/100;
+                        $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
+                    } else {
+                        $discount = $goods['SELL_DISCOUNT'];
+                        $realPrice = $goodsNature['SELL_PRICE'] * $discount;
+                        $realPv = $goods['PRICE_PV'] * $discount;
+                        $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
+                    }
+
+                    $currentPv = $goods['PRICE_PV'];
+                    $totalPv += $realPv * intval($v);
+                    $totalRealPv += $realPv * intval($v);
+                    $remainPv = 0;
+                    $this->_remainPv += 0;
+
+                    $totalAmount += $realPrice * intval($v);
+                    $totalAmountStandard += $realPriceStandard * intval($v);
+
+                    $this->_orderGoods[] = [
+                        'GOODS_ID' => $goods['ID'],
+                        'PRICE' => $goodsNature['SELL_PRICE'],
+                        'PV' => $currentPv,
+                        'REAL_PRICE' => $realPrice,
+                        'REAL_PV' => $realPv,
+                        'REMAIN_PV' => $remainPv,
+                        'POINT' => $goods['POINT'],
+                        'BUY_NUMS' => intval($v),
+                        'SKU_CODE' => $goods['GOODS_NO'],
+                        'GOODS_TITLE' => $goods['GOODS_NAME'],
+                        'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
+                        'PAY_TYPE' => $this->payType,
+                        'EMAIL' => $this->email,
+                        'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
+                        'REAL_STANDARD_PRICE' => $realPriceStandard,
+                        'EXCHANGE_RATE' => $currencyRate,
+                        'TAX_RATE' => $goodsNature['TAX_RATE'],
+                    ];
+                }
+                if($goods['INSTALMENT']>0){
+                    if ($v > 1) {
+                        throw new Exception(Yii::t('app', 'allowOnlyOne'));
+                    }
+
+                    $userStage = Instalment::getStage($userId);
+                    $userInstalmentInfo = Instalment::getInfo($userId);
+                    // 分期的总期数
+                    $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
+                    // 分期商品的期数不能大于总分期数限制
+                    if (intval($goods['INSTALMENT']) > $instalment) {
+                        throw new Exception(Yii::t('app', 'instalmentGoodsNoError'));
+                    }
+                    if ($userStage == $instalment){
+                        if ($goods['INSTALMENT'] != 1) {
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+                    }else{
+                        if($userInstalmentInfo){
+                            if($userInstalmentInfo['STAGE']>0 && $userInstalmentInfo['ORDER_TYPE']!='FX'){
+                                throw new Exception(Yii::t('app', 'canNotBuy'));
+                            }
+                        }
+                        if($userStage + 1 != $goods['INSTALMENT']){ // 若用户分期阶段+1不等于商品的分期阶段,则报异常
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+                        if ($userStage + 1 > $instalment){ // 若用户分期阶段+1大于总分期阶段,则报异常
+                            throw new Exception(Yii::t('app', 'canNotBuy'));
+                        }
+                    }
+                    $hasInstalment = $goods['INSTALMENT'];
+                }
+            }
+        }
+
+        $sysConfig = Cache::getSystemConfig();
+        $ampDivideLine = (int)$sysConfig['ampBVCondition']['VALUE'];
+        if ($totalPv < $ampDivideLine) {
+            throw new Exception(Yii::t('app', 'ampOrderSubStandard', ['ampBv' => $ampDivideLine]));
+        }
+
+        // 运费模板
+        $freeTemplate = FreeTemplate::getByCountryId($user['COUNTRY_ID']);
+        // 运费
+        $freight = $freeTemplate['freight'] ?? 0;
+        // 普通商品免运费阈值
+        $freeShipping = $freeTemplate['free_shipping'] ?? 0;
+
+        $this->_decAmount = $totalAmount;
+        $this->_decPv = $totalPv;
+        $this->_realPv = $totalRealPv;
+        $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
+
+        $this->_payAmount = $this->_decAmount + $this->_freight;
+
+        $this->_decAmountStandard = $totalAmountStandard;
+        $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
+
+
+        $db = \Yii::$app->db;
+        $transaction = $db->beginTransaction();
+        try {
+            $loginUserId = \Yii::$app->user->id;
+
+            //是否开启伞下会员限制
+            // $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
+            // if($isResaleUmbrella){
+            //     $userId = Info::getUserIdByUserName($this->userName);
+            //     $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
+            //     if(!$userNetwork){
+            //         throw new Exception($this->userName . Yii::t('app', 'doesNotYourSubMemberCanNotReconsume'));
+            //     }
+            // }
+
+            $decCash = Cash::getAvailableBalance($loginUserId);
+
+            // 转换后的余额
+            $localCash = Tool::convertAmount($decCash, $decUserCurrencyRate, $currencyRate);
+            if ($localCash < $this->_decAmount){
+                throw new Exception(Yii::t('app', 'applicantPrpShort'), 400);
+            }
+
+            foreach ($this->goodsNum as $k => $v){
+                if ($v){
+                    $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
+                    if (!$goods) {
+                        throw new Exception(Yii::t('app', 'productsDoesSoldOut'));
+                    }
+                    if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]){
+                        $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
+                        $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
+                        $data->STORE_NUMS = $goods_store_nums;
+                        $data->update();
+                        //下单后库存小于等于0 商品下架
+                        if($goods_store_nums <= 0){
+                            $data->STATUS = 0;
+                            $data->UPDATED_AT = Date::nowTime();
+                            $data->update();
+
+                        }
+                    }else{
+                        throw new Exception($goods['GOODS_NAME'] . Yii::t('app', 'insufficientInventory'));
+                    }
+                }
+            }
+
+            //写入订单
+            if (!$orderResult = $this->addUserOrder()) {
+                throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
+            }
+
+            if ($hasInstalment){ // 如果有分期付款的商品,写入信息至分期付款表
+                $instalmentModel = Instalment::findOne(['USER_ID'=>$userId]);
+                if(!$instalmentModel) {
+                    $instalmentModel = new Instalment();
+                }
+                $instalmentModel->USER_ID = $userId;
+                $instalmentModel->STAGE = $hasInstalment;
+                $instalmentModel->ORDER_TYPE = 'FX';
+                $instalmentModel->UPDATE_TIME = time();
+                $instalmentModel->save();
+            }
+
+            $transaction->commit();
+        }catch (\Exception $e){
+            $transaction->rollBack();
+            $this->addError('add', $e->getMessage());
+            return null;
+        }
+        return true;
+    }
+
+    private function orderAutoMaintenance($order)
+    {
+        $nowPeriodNum = Period::instance()->getNowPeriodNum();
+
+        try {
+            $sysConfig = Cache::getSystemConfig();
+            $divideLine = (float)$sysConfig['monthPcsPvFxCondition']['VALUE'];
+
+            $orderTotalBv = $order->PV;
+
+            if ($orderTotalBv <= $divideLine) {
+                return;
+            }
+
+            $lastAmpPeriod = AmpPeriod::find()
+                ->where(['USER_ID' => $order->USER_ID])
+                ->orderBy(['PERIOD_NUM' => SORT_DESC])
+                ->one();
+
+            $startPeriodNum = $lastAmpPeriod ? $lastAmpPeriod->PERIOD_NUM + 1 : $nowPeriodNum;
+
+            if (!$lastAmpPeriod) {
+                $memberOrderBv = Order::find()
+                    ->select('SUM(PV) AS total_pv')
+                    ->where([
+                        'USER_ID' => $order->USER_ID,
+                        'IS_DELETE' => 0,
+                        'PERIOD_NUM' => $nowPeriodNum
+                    ])
+                    ->andWhere(['!=', 'SN', $order->SN])
+                    ->scalar();
+
+                if ($memberOrderBv >= $divideLine) {
+                    $startPeriodNum = $nowPeriodNum + 1;
+                }
+
+                LoggerTool::notice([
+                    $lastAmpPeriod, $startPeriodNum, $divideLine, $memberOrderBv, $nowPeriodNum
+                ]);
+            }
+
+            $periodCount = floor($orderTotalBv / $divideLine);
+            $remainderBv = $orderTotalBv % $divideLine;
+
+            $ampPeriods = [];
+            for ($i = 1; $i <= $periodCount; $i++) {
+                $currentBv = $i < $periodCount ? $divideLine : ($divideLine + $remainderBv);
+                $ampPeriods[] = [
+                    'USER_ID' => $order->USER_ID,
+                    'ORDER_SN' => $order->SN,
+                    'PERIOD_NUM' => $startPeriodNum,
+                    'BV' => $currentBv,
+                ];
+
+                $startPeriodNum++;
+            }
+
+            if (!empty($ampPeriods)) {
+                AmpPeriod::batchInsert($ampPeriods);
+            }
+        } catch (\Exception $e) {
+            // 记录日志或进行错误处理
+            \Yii::error('Order auto maintenance failed: ' . $e->getMessage());
+        }
+    }
 }

+ 6 - 6
common/models/forms/ShopGoodsForm.php

@@ -37,6 +37,7 @@ class ShopGoodsForm extends Model
     public $status;
     public $categoryType;
     public $nature;
+    public $autoMaintenance = 0;
 
     private $_model;
 
@@ -85,6 +86,7 @@ class ShopGoodsForm extends Model
             'storeNums' => 'Inventory', // 库存
             'content' => 'Content',
             'listOrder' => 'Order',// 排序
+            'autoMaintenance' => 'Auto Maintenance',
         ];
     }
 
@@ -96,8 +98,8 @@ class ShopGoodsForm extends Model
     {
         $parentScenarios =  parent::scenarios();
         $customScenarios = [
-            'add' => ['goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','pricePv','storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'taxRate', 'taxAmount','pvSplit', 'nature'],
-            'edit' => ['id','goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','pricePv', 'storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'nature','pvSplit'],
+            'add' => ['goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','pricePv','storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'taxRate', 'taxAmount','pvSplit', 'nature', 'autoMaintenance'],
+            'edit' => ['id','goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','pricePv', 'storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'nature','pvSplit', 'autoMaintenance'],
             'changeStatus' => ['selectedIds', 'status'],
         ];
         return array_merge($parentScenarios, $customScenarios);
@@ -211,6 +213,7 @@ class ShopGoodsForm extends Model
             $shopGoods->CATE_ID = '1';
             $shopGoods->CREATED_AT = Date::nowTime();
             $shopGoods->CATEGORY_TYPE = $this->categoryType;
+            $shopGoods->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
             if (!$shopGoods->save()) {
                 throw new Exception(Form::formatErrorsForApi($shopGoods->getErrors()));
             }
@@ -271,19 +274,16 @@ class ShopGoodsForm extends Model
             $model->SORT = $this->sort;
             $model->UPDATED_AT = Date::nowTime();
             $model->CATEGORY_TYPE = $this->categoryType;
+            $model->AUTO_MAINTENANCE = $this->autoMaintenance ?? 0;
             if (!$model->save()) {
                 throw new Exception(Form::formatErrorsForApi($model->getErrors()));
             }
 
-            // 移除属性表中商品属性
             ShopGoodsNature::deleteAll(['GOODS_ID' => $model->ID]);
 
             // 商品属性
             foreach ($this->nature as $item) {
-                // 国家
                 $country = Countries::getById($item['ID']);
-                // 转换美元汇率
-                $productRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
 
                 $shopGoodsNature = new ShopGoodsNature();
                 $shopGoodsNature->GOODS_ID = $model->ID;

+ 32 - 4
common/models/forms/WithdrawForm.php

@@ -2,10 +2,14 @@
 
 namespace common\models\forms;
 
+use backendApi\modules\v1\models\Admin;
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
 use common\components\Model;
 use common\helpers\Cache;
 use common\helpers\Date;
 use common\helpers\Form;
+use common\helpers\LoggerTool;
 use common\helpers\Tool;
 use common\helpers\user\Balance;
 use common\helpers\user\Info;
@@ -735,11 +739,36 @@ class WithdrawForm extends Model {
      *
      * @throws \yii\db\Exception
      */
-    public function batchWithdraw($limit, $start){
+    public function batchWithdraw($limit, $start, $params){
         $config = Cache::getSystemConfig();
         $minAmount = $config['manualWithdrawMinAmount']['VALUE'];
+
+        $condition = '';
+        $adminRoleId = Admin::getRoleIdById($params['handleUserId']);
+        $isSuper = AdminRole::isSuperAdmin($adminRoleId);
+        if (!$isSuper) {
+            $adminCountry = AdminCountry::getCountry($params['handleUserId']);
+            $quotedAdminCountry = array_map(function($item) {
+                return "'" . addslashes($item) . "'";
+            }, $adminCountry);
+
+            $condition = " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
+        }
+
         // 查找有奖金的用户
-        $allData = UserBonus::find()->select('USER_ID, USER_NAME, ID_CARD, BONUS')->from(UserBonus::tableName().' AS UB')->join('LEFT JOIN', User::tableName().' AS U','UB.USER_ID = U.ID')->where("BONUS>$minAmount")->offset(0)->limit($limit)->orderBy('U.ID')->asArray()->all();
+        $allData = UserBonus::find()
+            ->select('USER_ID, USER_NAME, ID_CARD, BONUS')
+            ->from(UserBonus::tableName().' AS UB')
+            ->join('INNER JOIN', User::tableName() . ' AS U','UB.USER_ID = U.ID ' . $condition)
+            ->where("BONUS>$minAmount")
+            ->offset(0)
+            ->limit($limit)
+            ->orderBy('U.ID')
+            ->asArray()
+            ->all();
+
+        LoggerTool::debug($allData);
+
         if($allData){
             foreach ($allData as $data){
                 $db = \Yii::$app->db;
@@ -776,7 +805,6 @@ class WithdrawForm extends Model {
                     if (!$withdrawModel->save()) {
                         throw new Exception(Form::formatErrorsForApi($withdrawModel->getErrors()));
                     }
-//                    print_r($data['BONUS'].',,'.$i.PHP_EOL);
                     $transaction->commit();
                     unset($withdrawModel);
                 } catch (Exception $e) {
@@ -788,7 +816,7 @@ class WithdrawForm extends Model {
             unset($allData);
             $start = $start + $limit;
 
-            return self::batchWithdraw($limit, $start);
+            return self::batchWithdraw($limit, $start, $params);
         }
         return true;
     }

BIN
common/runtime/uploads/ngds-logo.jpg


+ 8 - 1
console/controllers/BonusController.php

@@ -7,6 +7,9 @@
  */
 namespace console\controllers;
 
+use backendApi\modules\v1\models\Admin;
+use backendApi\modules\v1\models\AdminCountry;
+use backendApi\modules\v1\models\AdminRole;
 use backendApi\modules\v1\models\lists\bonus\BalanceList;
 use backendApi\modules\v1\models\lists\bonus\CfLxAuditList;
 use backendApi\modules\v1\models\lists\bonus\FlowBalanceList;
@@ -51,6 +54,7 @@ use common\helpers\Excel;
 use common\helpers\Form;
 use common\helpers\http\RemoteUploadApi;
 use common\helpers\Log;
+use common\helpers\LoggerTool;
 use common\libs\export\module\BonusExport;
 use common\models\forms\PeriodForm;
 use common\models\forms\UserPerformanceForm;
@@ -58,6 +62,7 @@ use common\models\forms\WithdrawForm;
 use common\models\LogAsync;
 use common\models\Withdraw;
 use common\models\UserBonus;
+use Yii;
 use yii\db\Exception;
 
 class BonusController extends BaseController
@@ -529,9 +534,11 @@ class BonusController extends BaseController
      *
      */
     public function actionAutoWithdraw($taskKey){
+        $params = Cache::getAsyncParams($taskKey);
+
         Cache::setWithdrawLock(1);
         $formModel = new WithdrawForm();
-        $formModel->batchWithdraw(1000,0);
+        $formModel->batchWithdraw(5,0, $params);
         Cache::setWithdrawLock(0);
     }
 

+ 6 - 0
console/controllers/ToolController.php

@@ -11,6 +11,7 @@ namespace console\controllers;
 use common\helpers\bonus\CalcCache;
 use common\helpers\Cache;
 use common\helpers\Date;
+use common\helpers\Email;
 use common\helpers\LoggerTool;
 use common\helpers\Tool;
 use common\helpers\user\Balance;
@@ -202,6 +203,11 @@ class ToolController extends BaseController
         }
     }
 
+    public function actionSendEmail()
+    {
+        Email::sendRegistrationEmail('18511880790@163.com', 'zhangl', 'test123');
+    }
+
     public function actionUpdatePercent() {
         $percent = 100;
         $periodNum = 134;

+ 1 - 0
frontendApi/config/menu.php

@@ -41,6 +41,7 @@ return [
         'child'=>[
             ['name'=>'Member Welcome Pack', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'dec', 'routePath'=>'user/dec', 'show'=>1,  'wiki' => 'welcomePack',], // 会员报单
             ['name'=>'Member Repeat Purchase', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'reconsume', 'routePath'=>'shop/reconsume', 'show'=>1, 'wiki' => 'memberRepeatPurchase',],//会员复消
+            ['name'=>'Member Auto Maintenance', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'reconsume', 'routePath'=>'shop/auto-maintenance', 'show'=>1, 'wiki' => 'memberAutoMaintenance',],//AMP
             ['name'=>'Member Upgrade', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'dec', 'routePath'=>'user/upgrade', 'show'=>1, /**'allow'=>'declarer',**/ 'wiki' => 'memberUpgrade',],//会员升级
             ['name'=>'Member Order', 'class'=>'', 'icon'=>'', 'controller'=>'user', 'action'=>'member-order', 'routePath'=>'shop/member-order', 'show'=>1, 'wiki' => 'memberOrder',],//会员订单
         ]

+ 1 - 1
frontendApi/config/params.php

@@ -20,7 +20,7 @@ return [
         'v1/finance/prove-add',
         'v1/site/get-instance',
         'v1/site/languages',
-        'v1/site/countries',
+//        'v1/site/countries',
         'v1/bonus/period',
         ],
     'noCheckPermissionActions' => [],

+ 3 - 0
frontendApi/config/urlManagerRules.php

@@ -96,6 +96,9 @@ return [
             'GET ba-dec-order-list' => 'ba-dec-order-list',
             'GET ba-dec-order-export/<orderSn>' => 'ba-dec-order-export',
             'POST sure-approach-reconsume-order' => 'sure-approach-reconsume-order',
+            'GET auto-maintenance' => 'auto-maintenance',
+            'POST auto-maintenance-sure-order' => 'auto-maintenance-sure-order',
+            'POST auto-maintenance-approach-sure-order' => 'auto-maintenance-approach-sure-order',
         ],
     ],
     [

+ 161 - 19
frontendApi/modules/v1/controllers/ShopController.php

@@ -29,6 +29,7 @@ use common\models\Currency;
 use common\models\CurrencyConversions;
 use common\models\DecOrder;
 use common\models\BaDecOrder;
+use common\models\forms\ApproachAutoMaintenanceOrderForm;
 use common\models\forms\ApproachOrderForm;
 use common\models\forms\ApproachReconsumeOrderForm;
 use common\models\forms\BaApproachOrderForm;
@@ -47,6 +48,7 @@ use common\models\UserBonus;
 use common\models\UserPerformance;
 use common\models\UserWallet;
 use Yii;
+use yii\base\Exception;
 use yii\data\Pagination;
 use yii\db\Query;
 use yii\web\HttpException;
@@ -143,17 +145,31 @@ class ShopController extends BaseController {
                 $allAddress[$key]['COUNTY_NAME'] = Region::getCnName($row['COUNTY']);
             }
         }
+
+        // 账户币种
+        $country = Countries::getById($user['COUNTRY_ID']);
+        $coin = Currency::getById($country['LOCAL_CURRENCY_ID']);
+
+        $decCountryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $decCountry = Countries::getById($decCountryId);
+        $decUserCurrencyRate = CurrencyConversions::getToUSDRate($decCountry['LOCAL_CURRENCY_ID']);
+        $currencyRate = CurrencyConversions::getToUSDRate($country['LOCAL_CURRENCY_ID']);
+
         $userBalance = [
             'cash' => 0,
             'prp' => 0,
+            'localCash' => 0,
+            'localRrp' => 0,
         ];
 
         if ($userCashResult = UserWallet::findOneAsArray(['USER_ID' => $user['ID']])) {
             $userBalance['cash'] = $userCashResult['CASH'];
+            $userBalance['localCash'] = Tool::convertAmount($userCashResult['CASH'], $decUserCurrencyRate, $currencyRate);
         }
 
         if ($userPerformance = UserPerformance::getAmounts($user['ID'])) {
             $userBalance['prp'] = $userPerformance;
+            $userBalance['localCash'] = Tool::convertAmount($userPerformance, $decUserCurrencyRate, $currencyRate);
         }
 
         // 运费模板
@@ -169,6 +185,10 @@ class ShopController extends BaseController {
         $country = Countries::getById($user['COUNTRY_ID']);
         $coin = Currency::getById($country['LOCAL_CURRENCY_ID']);
 
+        // AMP
+        $sysConfig = Cache::getSystemConfig();
+        $ampDivideLine = (int)$sysConfig['ampBVCondition']['VALUE'];
+
         return static::notice(
             [
                 'payList'=>$payList,
@@ -179,6 +199,7 @@ class ShopController extends BaseController {
                 'freeShipping' => $freeShipping,
                 'isDec' => $isDec,
                 'coin' => $coin['CODE'] ?? '',
+                'ampDivideLine' => floatval($ampDivideLine),
             ]);
     }
 
@@ -192,24 +213,27 @@ class ShopController extends BaseController {
             $formModel->remark = 'FX';//复销备注
             $post = \Yii::$app->request->post();
             $post['type'] = DeclarationForm::TYPE_FX;
-            $userInfo = User::getEnCodeInfo(\Yii::$app->user->id);
-            $userName = $post['userName'] ?? '';
-            if($userInfo['IS_DEC'] == 1 && $userName != $userInfo['USER_NAME']){
+            $loginUserInfo = User::getEnCodeInfo(\Yii::$app->user->id);
+            $stockist = $post['userName'] ?? '';
+            if (!$stockist) {
+                return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+            }
+            if($loginUserInfo['IS_DEC'] == 1 && $stockist != $loginUserInfo['USER_NAME']){
                 return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
             }
-            if($userName && $userInfo['IS_DEC'] == 0){
+            if($loginUserInfo['IS_DEC'] == 0){
                 //查询报单编号是否存在
-                $userId = Info::getUserIdByUserName($userName);
-                if(!$userId){
+                $stockistId = Info::getUserIdByUserName($stockist);
+                if(!$stockistId){
                     return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
                 }
-                $isDec = User::getEnCodeInfo($userId)['IS_DEC'];
+                $isDec = User::getEnCodeInfo($stockistId)['IS_DEC'];
                 if(!$isDec){
                     return static::notice(Yii::t('app', 'decUserNameIsWrong'), 400);
                 }
             }
 
-            $formModel->decUserName = $userName;
+            $formModel->decUserName = $stockist;
             if ($formModel->load($post, '') && $order = $formModel->add()) {
                 return static::notice($order);
             } else {
@@ -241,16 +265,16 @@ class ShopController extends BaseController {
             $formModel->remark = '复销备注';
             $post = \Yii::$app->request->post();
             $post['type'] = DeclarationForm::TYPE_FX;
-            $userInfo = User::getEnCodeInfo(\Yii::$app->user->id);
-            if($userInfo['IS_DEC'] == 1 && !empty($post['userName']) && $post['userName'] != $userInfo['USER_NAME']){
+            $loginUserInfo = User::getEnCodeInfo(\Yii::$app->user->id);
+            $stockist = $post['userName'] ?? '';
+            if (!$stockist) {
                 return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
             }
-
-            if(empty($post['userName'])){
-                return static::notice(Yii::t('app', 'decUserNameIsWrong'), 400);
+            if($loginUserInfo['IS_DEC'] == 1 && !empty($post['userName']) && $post['userName'] != $loginUserInfo['USER_NAME']){
+                return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
             }
             //查询报单编号是否存在
-            if($post['userName'] && $userInfo['IS_DEC'] == 0){
+            if($loginUserInfo['IS_DEC'] == 0){
                 $userId = Info::getUserIdByUserName($post['userName']);
                 if(!$userId){
                     return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
@@ -260,6 +284,7 @@ class ShopController extends BaseController {
                     return static::notice(Yii::t('app', 'decUserNameIsWrong'), 400);
                 }
             }
+
             $formModel->decUserName = $post['userName'];
             if ($formModel->load($post, '') && $order = $formModel->add()) {
                 return static::notice($order);
@@ -276,9 +301,15 @@ class ShopController extends BaseController {
         if (\Yii::$app->request->isPost) {
             $formModel = new ApproachReconsumeOrderForm();
             $formModel->scenario = 'reconsumeOrder';
-            $formModel->remark = '为用户复消';
+            $formModel->remark = Yii::t('app', 'reconsume');
             $post = \Yii::$app->request->post();
             $post['type'] = DeclarationForm::TYPE_FX;
+
+            $stockist = $post['userName'] ?? '';
+            if (!$stockist) {
+                return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+            }
+
             if ($formModel->load($post, '') && $order = $formModel->add()) {
                 return static::notice($order);
             } else {
@@ -721,6 +752,12 @@ class ShopController extends BaseController {
             $formModel->remark = Yii::t('app', 'reconsume');
             $post = \Yii::$app->request->post();
             $post['type'] = DeclarationForm::TYPE_FX;
+
+            $stockist = $post['decUserName'] ?? '';
+            if (!$stockist) {
+                return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+            }
+
             if ($formModel->load($post, '') && $formModel->reconsumeAdd()) {
                 return static::notice(Yii::t('app', 'reconsumeSuccessfully'));
             } else {
@@ -1009,7 +1046,12 @@ ORDER;
         $pdf->AddPage();
         // 设置字体
         $pdf->SetFont('stsongstdlight', '', 10, '', true);
-        $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+        //        $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
+//        if (!file_exists($image_file)) {
+//            $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
+//        }
+        $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
+        $image = file_get_contents($image_file);
         $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
         $pdf->writeHTML($context);
 
@@ -1018,7 +1060,6 @@ ORDER;
         $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]);
@@ -1273,7 +1314,12 @@ ORDER;
         $pdf->AddPage();
         // 设置字体
         $pdf->SetFont('stsongstdlight', '', 10, '', true);
-        $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+        //        $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
+//        if (!file_exists($image_file)) {
+//            $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
+//        }
+        $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
+        $image = file_get_contents($image_file);
         $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
         $pdf->writeHTML($context);
 
@@ -1843,7 +1889,13 @@ ORDER;
         $pdf->AddPage();
         // 设置字体
         $pdf->SetFont('stsongstdlight', '', 10, '', true);
-        $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
+//        $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
+//        if (!file_exists($image_file)) {
+//            $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
+//        }
+        $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
+        $image = file_get_contents($image_file);
+
         $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
         $pdf->writeHTML($context);
 
@@ -1856,4 +1908,94 @@ ORDER;
 
         return static::notice(['fileUrl' => $path, 'targetName' => $file_name]);
     }
+
+    /**
+     * AMP
+     */
+    public function actionAutoMaintenance()
+    {
+        // 会员信息
+        $user = User::findOneAsArray('ID=:ID', [':ID' => \Yii::$app->request->get('userId')]);
+        if (!$user) {
+            return static::notice(Yii::t('app', 'memberDoesNotExist'), 400);
+        }
+
+        $condition = ' AND STATUS=1 AND (FIND_IN_SET(2,GIFT_TYPE)>0 OR FIND_IN_SET(4,GIFT_TYPE)>0) AND N.COUNTRY_ID=:COUNTRY_ID AND AUTO_MAINTENANCE=1';
+        $data = ShopGoods::lists($condition, [':COUNTRY_ID' => $user['COUNTRY_ID']], [
+            'select' => 'S.*,N.MARKET_PRICE,N.SELL_PRICE,N.TAX_RATE,N.LOCAL_CURRENCY_ID,N.COUNTRY_ID',
+            'from' => ShopGoods::tableName() . ' AS S',
+            'join' => [
+                ['INNER JOIN', ShopGoodsNature::tableName() . ' AS N', 'N.GOODS_ID = S.ID'],
+            ],
+            'orderBy' => 'SORT ASC,CREATED_AT DESC',
+            'limit' => 100,
+        ]);
+
+        $currencies = Currency::getAllData();
+        $currencies = array_column($currencies, NULL, 'ID');
+
+        foreach ($data['list'] as $key => $value) {
+            $data['list'][$key]['DISCOUNT'] = in_array($value['TYPE'], [1, 2]) ? ShopGoods::getGoodType()[$value['TYPE']]['discount'] : $value['SELL_DISCOUNT'] * 100;
+            $data['list'][$key]['COIN'] = $currencies[$value['LOCAL_CURRENCY_ID']]['CODE'] ?? '';
+        }
+
+        return static::notice($data);
+    }
+
+    /**
+     * AMP
+     */
+    public function actionAutoMaintenanceSureOrder()
+    {
+        if (\Yii::$app->request->isPost) {
+            $formModel = new OrderForm();
+            $formModel->scenario = 'autoMaintenanceOrder';
+            $formModel->remark = Yii::t('app', 'autoMaintenance');
+            $post = \Yii::$app->request->post();
+            $post['type'] = DeclarationForm::TYPE_FX;
+
+            $stockist = $post['decUserName'] ?? '';
+            if (!$stockist) {
+                return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+            }
+
+            try {
+                if ($formModel->load($post, '') && $formModel->autoMaintenanceSureOrder()) {
+                    return static::notice(Yii::t('app', 'successfully'));
+                } else {
+                    return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
+                }
+            } catch (HttpException|Exception|\Throwable $e) {
+                return static::notice(Form::formatErrorsForApi($e->getMessage()), 400);
+            }
+        }
+    }
+
+    /**
+     * AMP
+     */
+    public function actionAutoMaintenanceApproachSureOrder(){
+        if (\Yii::$app->request->isPost) {
+            $formModel = new ApproachAutoMaintenanceOrderForm();
+            $formModel->scenario = 'autoMaintenanceOrder';
+            $formModel->remark = 'Auto Maintenance Order';
+            $post = \Yii::$app->request->post();
+            $post['type'] = DeclarationForm::TYPE_FX;
+
+            $stockist = $post['decUserName'] ?? '';
+            if (!$stockist) {
+                return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+            }
+
+            try {
+                if ($formModel->load($post, '') && $order = $formModel->autoMaintenanceSureOrder()) {
+                    return static::notice($order);
+                } else {
+                    return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
+                }
+            } catch (\yii\db\Exception|HttpException|Exception $e) {
+                return static::notice(Form::formatErrorsForApi($e->getMessage()), 400);
+            }
+        }
+    }
 }

+ 3 - 4
frontendApi/modules/v1/controllers/SiteController.php

@@ -415,15 +415,14 @@ class SiteController extends BaseController
 
     public function actionCountries()
     {
-        // 国家列表
-        $data = Cache::getCountries();
+        $countryId = User::getEnCodeInfo(\Yii::$app->user->id)['COUNTRY_ID'];
+        $countries = array_filter(Cache::getCountries(), fn($country) => $country['ID'] === $countryId);
 
-        return static::notice(['data' => $data]);
+        return static::notice(['data' => array_values($countries)]);
     }
 
     public function actionLanguages()
     {
-        // 语言列表
         $data = Cache::getLanguages();
 
         return static::notice(['data' => $data]);

+ 40 - 12
frontendApi/modules/v1/controllers/UserController.php

@@ -245,6 +245,12 @@ class UserController extends BaseController {
         if ($baseInfo['STATUS'] != 1) {
             return static::notice(Yii::t('app', 'inactiveUser'), 400);
         }
+
+        $loginUserInfo = User::getEnCodeInfo(\Yii::$app->user->id);
+        if ($baseInfo['COUNTRY_ID'] !== $loginUserInfo['COUNTRY_ID']) {
+            return static::notice(Yii::t('app', 'memberNumberDoesNotExist'), 400);
+        }
+
         // 1. 如果是最高级别,则只显示用户基本信息
         // 2. 如果不是最高级别,如果用户累计报单数据是0, 或者用户累计报单业绩不符合级别信息,则提示 请联系客服核对业绩
         $userId = $baseInfo['ID'];
@@ -368,6 +374,11 @@ class UserController extends BaseController {
                 $formModel = new DeclarationUpgradeForm();
             }
 
+            $stockist = $post['decUserName'] ?? '';
+            if (!$stockist) {
+                return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+            }
+
             $post['type'] = DeclarationForm::TYPE_ZC;
             if ($formModel->load($post, '') && $result = $formModel->add($post)) {
                 return static::notice($result);// Upgrade declaration succeeded升级报单成功
@@ -508,11 +519,21 @@ class UserController extends BaseController {
         $redis = \Yii::$app->redis;
         $post = \Yii::$app->request->post();
         if (\Yii::$app->request->isPost) {
-            $userInfo = User::getEnCodeInfo(\Yii::$app->user->id);
-            if($userInfo['IS_DEC'] == 1 && !empty($post['decUserName']) && $post['decUserName'] != $userInfo['USER_NAME']){
+            $email = $post['email'] ?? '';
+            if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
+                return static::notice(Yii::t('app', 'invalidEmail'), 400);
+            }
+
+            $stockist = $post['decUserName'] ?? '';
+            if (!$stockist) {
+                return static::notice(Yii::t('app', 'stockistDoesNotExist'), 400);
+            }
+
+            $loginUserInfo = User::getEnCodeInfo(\Yii::$app->user->id);
+            if($loginUserInfo['IS_DEC'] == 1 && !empty($post['decUserName']) && $post['decUserName'] != $loginUserInfo['USER_NAME']){
                 return static::notice(Yii::t('app', 'decUserNameIsWrong'), 400);
             }
-            if($userInfo['IS_DEC'] == 0 && $post['decUserName']){
+            if($loginUserInfo['IS_DEC'] == 0 && $post['decUserName']){
                 //查询报单编号是否存在
                 $userId = Info::getUserIdByUserName($post['decUserName']);
                 if(!$userId){
@@ -625,16 +646,17 @@ SQL;
             $post['type'] = DeclarationForm::TYPE_ZC;
 
             $allData['data'][] = $post;
-            if ($formModel->load($allData, '') && $result = $formModel->add()) {
-                //发送邮件
-                try {
-                    Email::sendRegistrationEmail($post['email'], $post['insertUserName'], $post['password']);
-                } catch (\Exception $e) {
-                    //Yii::error($e->getMessage());
-                    Yii::info('邮箱:'.$post['email'].'----错误信息:'.$e->getMessage());
+
+            try {
+                if ($formModel->load($allData, '') && $result = $formModel->add()) {
+                    //发送邮件
+//                    Email::sendRegistrationEmail($post['email'], $post['insertUserName'], $post['password']);
+                    return static::notice($result);//报单成功
+                } else {
+                    return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
                 }
-                return static::notice($result);//报单成功
-            } else {
+            } catch (\Exception $e) {
+                LoggerTool::error($e->getMessage() . '; ' . $e->getLine() . '; ' . $e->getFile());
                 return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
             }
         }
@@ -775,6 +797,12 @@ SQL;
         $userId = Info::getUserIdByUserName($userName);
         $userInfo['REAL_NAME'] = '';
         $user = User::findOneAsArray('ID=:ID', [':ID' => $userId]);
+
+        $loginUserInfo = User::getEnCodeInfo(\Yii::$app->user->id);
+        if ($user['COUNTRY_ID'] !== $loginUserInfo['COUNTRY_ID']) {
+            return static::notice(Yii::t('app', 'memberNumberDoesNotExist'), 400);
+        }
+
         if($user){
             $userInfo['REAL_NAME'] = $user['REAL_NAME'];
             $allChildUser = UserNetwork::getFirstFloorChildren($userId);

BIN
frontendEle/static/src/img/ngds-logo.jpg